
    i!                        d Z ddlmZ ddlZddlZddlZddlZddlZddlZddl	m
Z
 ddlZddlmZmZmZ ddlmZ ddlmZ ddZddZdddZ	 dddZdS )a  Build and cache librt for use in tests.

This module provides a way to build librt extension modules once and cache
them across test runs, and across different test cases in a single run. The
cache is invalidated when source files or details of the build environment change.

Note: Tests must run in a subprocess to use the cached librt, since importing
this module also triggers the import of the regular installed librt.

Usage:
    from mypyc.test.librt_cache import get_librt_path, run_with_librt

    # Get path to built librt (builds if needed)
    path = get_librt_path()

    # Run a test file in subprocess with built librt
    result = run_with_librt("test_librt.py")
    )annotationsN)Any)LIBRT_MODULES
get_cflagsinclude_dir)RUNTIME_C_FILES)PREFIXexperimentalbool	opt_levelstrreturnc                   ddl m} t          j                    }|                    | rdnd           |                    d|                                            |                    t          j                                                   t          t          d          }|                    |rdnd           t          t          j        d	                    }|                    |rd
nd           |                                }|                    |j                                                   dD ]N}t          j                            |d          }|                    | d|                                            Ot"          D ]}	t          j                            t)                      |	          }
|                    |	                                dz              t+          |
d          5 }|                    |                                           ddd           n# 1 swxY w Y   t.          D ]\  }}}}||z   D ]}t          j                            t)                      |          }
|                    |                                dz              t+          |
d          5 }|                    |                                           ddd           n# 1 swxY w Y   |                                dd         S )zFCompute hash for librt build, including sources and build environment.r   )	ccompilers   exps   noexpzopt=gettotalrefcounts   debugs   releasePy_GIL_DISABLEDs   freethreadeds   gil)CCCXXCFLAGSCPPFLAGSLDFLAGS =   |rbN   )	distutilsr   hashlibsha256updateencodesysversionhasattrr   	sysconfigget_config_varnew_compilercompiler_typeosenvirongetr   pathjoinr   openreadr   	hexdigest)r
   r   r   his_debugis_free_threadedcompilervarvalnamer,   fmodfilesextraincludesfnames                    U/root/projects/qq-shell/venv/lib64/python3.11/site-packages/mypyc/test/librt_cache.py_librt_build_hashr?   %   s+    $#####AHH|1VV222HHI&&(()))HHS[!!"""s.//HHH1XXz222I45FGGHHHH 0<__f===**,,HHHX#**,,---= * *jnnS"%%	C#&&(())))  w||KMM400	%&&&$ 	HHQVVXX	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 (5 # ##UE8U] 	# 	#E7<<u55DHHU\\^^d*+++dD!! #Q"""# # # # # # # # # # # # # # #	#
 ;;=="s$   6(H**H.	1H.	1(K%%K),K)	build_dirc                    t                      }t          ||          }t          d t          D                       }t          t                    }t          |          }d| d|d| d| d| dS )	zGenerate setup.py content for building librt directly.

    We inline LIBRT_MODULES/RUNTIME_C_FILES/include_dir/cflags values to avoid
    importing mypyc.build, which recursively imports lots of things.
    )r   experimental_featuresc                B    g | ]}|j         |j        |j        |j        fS  )modulec_filesother_filesinclude_dirs).0ms     r>   
<listcomp>z&_generate_setup_py.<locals>.<listcomp>Z   s)    UUU!!(AIq}an	=UUU    zimport os
from setuptools import setup, Extension
import build_setup  # noqa: F401  # Monkey-patches compiler for per-file SIMD flags

build_dir = z
lib_rt_dir = z

RUNTIME_C_FILES = z
LIBRT_MODULES = z

CFLAGS = a  

def write_file(path, contents):
    os.makedirs(os.path.dirname(path), exist_ok=True)
    with open(path, "wb") as f:
        f.write(contents)

# Copy runtime C files
for name in RUNTIME_C_FILES:
    src = os.path.join(lib_rt_dir, name)
    dst = os.path.join(build_dir, name)
    with open(src, "rb") as f:
        write_file(dst, f.read())

# Build extensions for each librt module
extensions = []
for mod, file_names, extra_files, includes in LIBRT_MODULES:
    # Copy source files
    for fname in file_names + extra_files:
        src = os.path.join(lib_rt_dir, fname)
        dst = os.path.join(build_dir, fname)
        with open(src, "rb") as f:
            write_file(dst, f.read())

    extensions.append(Extension(
        mod,
        sources=[os.path.join(build_dir, f) for f in file_names + RUNTIME_C_FILES],
        include_dirs=[lib_rt_dir] + [os.path.join(lib_rt_dir, d) for d in includes],
        extra_compile_args=CFLAGS,
    ))

setup(name='librt_cached', ext_modules=extensions)
)r   r   reprr   r   )r@   r
   r   
lib_rt_dircflagslibrt_modules_reprruntime_files_reprcflags_reprs           r>   _generate_setup_pyrS   M   s     J )<PPPF UU}UUU  o..v,,K*
 * * * * &* * $* * * * * *rL   T0c           
        t           j                            t          dd          }t	          | |          }t           j                            |d|           }t           j                            |d| d          }t           j                            |d          }t          j        |d           t          j        |d	          5  t           j                            |          r|cd
d
d
           S t           j                            |          rt          j
        |           t          j        |           t           j                            |d          }t          j        |           t          t           j                            |d          d          5 }	 d
d
d
           n# 1 swxY w Y   t           j                            t           j                            t           j                            t           j                            t                                        d          }	t           j                            |d          }
t          j        |	|
           t           j                            |d          }t          |d          5 }|                    t#          || |                     d
d
d
           n# 1 swxY w Y   t%          j        t(          j        |ddg|dd          }|j        dk    rt/          d|j         d|j                   t          |d          5 }|                    d           d
d
d
           n# 1 swxY w Y   d
d
d
           n# 1 swxY w Y   |S )a9  Get path to librt built from the repository, building and caching if necessary.

    Uses build/librt-cache/ under the repo root (gitignored). The cache is
    keyed by a hash of sources and build environment, so it auto-invalidates
    when relevant factors change.

    Safe to call from multiple parallel pytest workers - uses file locking.

    Args:
        experimental: Whether to enable experimental features.
        opt_level: Optimization level ("0".."3") used when building librt.

    Returns:
        Path to directory containing built librt modules.
    buildzlibrt-cachezlibrt-z.lockz	.completeT)exist_oki,  )timeoutNlibrtz__init__.pywzbuild_setup.pyzsetup.py	build_extz	--inplace)cwdcapture_outputtextr   zlibrt build failed:

ok)r)   r,   r-   r	   r?   makedirsfilelockFileLockexistsshutilrmtreer.   dirnameabspath__file__copywriterS   
subprocessrunr"   
executable
returncodeRuntimeErrorstdoutstderr)r
   r   
cache_root
build_hashr@   	lock_filemarker	librt_pkgr8   build_setup_srcbuild_setup_dstsetup_pyresults                r>   get_librt_pathr|      s   " fg}==J"<;;JZ)>*)>)>??IZ)C*)C)C)CDDIW\\)[11FK
T****		9c	2	2	2 ) )7>>&!! 	) ) ) ) ) ) ) )
 7>>)$$ 	%M)$$$
I GLLG44	
I"',,y-88#>> 	!	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ',,GOOBGOOBGOOH,E,EFFGGIY
 
 ',,y2BCCO_555 7<<	:66(C   	LAGG&y,	JJKKK	L 	L 	L 	L 	L 	L 	L 	L 	L 	L 	L 	L 	L 	L 	L
 ^X{K@	
 
 
 !!Wv}WWWWXXX &# 	!GGDMMM	 	 	 	 	 	 	 	 	 	 	 	 	 	 	Q) ) ) ) ) ) ) ) ) ) ) ) ) ) )V s   
!M08B)M0!F/#M0/F3	3M06F3	7C$M0%K M0K	M0K	A#M07MM0M	M0 M	!M00M47M4	file_pathcheck subprocess.CompletedProcess[str]c                   t          ||          }t          j                                        }|                    dd          }||rt          j        |z   ndz   |d<   t          j        t          j	        | gdd||          S )a)  Run a Python file in a subprocess with built librt available.

    This runs the file in a fresh Python process where the built librt
    is at the front of sys.path, avoiding conflicts with any system librt.

    Args:
        file_path: Path to Python file to execute.
        experimental: Whether to use experimental features.
        check: If True, raise CalledProcessError on non-zero exit.
        opt_level: Optimization level ("0".."3") used when building librt.

    Returns:
        CompletedProcess with stdout, stderr, and returncode.
    )r   
PYTHONPATHr   T)r]   r^   r~   env)
r|   r)   r*   rj   r+   pathseprl   rm   r"   rn   )r}   r
   r~   r   
librt_pathr   existings          r>   run_with_librtr      s    "  	BBBJ
*//

Cww|R((H"x&Obj8&;&;RPC>	#Dt5VY   rL   )r
   r   r   r   r   r   )r@   r   r
   r   r   r   r   r   )TrT   )TTrT   )
r}   r   r
   r   r~   r   r   r   r   r   )__doc__
__future__r   r   r)   re   rl   r"   r%   typingr   rb   mypyc.buildr   r   r   mypyc.commonr   mypyc.test.configr	   r?   rS   r|   r   rD   rL   r>   <module>r      s/   & # " " " " "  				      



            > > > > > > > > > > ( ( ( ( ( ( $ $ $ $ $ $% % % %P< < < <~D D D D DP UX      rL   