
    X-Ph                    j   d Z ddlmZ ddlZddlZddlmZ ddlmZm	Z	 ddl
mZmZmZmZmZmZmZmZ ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZmZ ddlmZm Z  ddl!m"Z" ddl#m$Z$m%Z%m&Z&m'Z' ddl(m)Z)m*Z* ddl+m,Z,m-Z- ddl.m/Z/m0Z0m1Z1m2Z2 ddl3m4Z4 ddl5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z< ddl=m>Z> ddl?m@Z@ ddlAmBZBmCZCmDZD ddlEmFZFmGZG ddlHmIZI ddlJmKZK ddlLmMZM ddlNmOZO ddlPmQZQmRZR ddlSmTZT ddlUmVZV ddlWmXZX dd lYmZZZ dd!l[m\Z\ dd"l]m^Z^ dd#l_m`Z` dd$lambZb ecede         eee         f         Zfedef         Zgedeceeeef                  Zh G d% d&          Zi G d' d(e          Zj	 	 dqdrd7Zkdsd@ZldtdAZmdudDZndvdHZodwdKZpdxdPZqdydSZrdzdUZsd{dZZtd|d]Zud}d_Zv G d` da          Zw e	db          Zxd~dfZyddjZzddmZ{ddpZ|dS )zHGenerate C code for a Python C extension module from Python source code.    )annotationsN)Iterable)OptionalTypeVar)BuildResultBuildSourceStatebuildcompute_hashcreate_metastoreget_cache_namessorted_components)CompileError)FileSystemCache)MypyFile)Options)PluginReportConfigContext)hash_digest
json_dumps)c_string_initializer)EmitterEmitterContextHeaderDeclarationc_array_initializer)generate_classgenerate_class_type_decl)generate_native_functionnative_function_header) generate_legacy_wrapper_functiongenerate_wrapper_functionlegacy_wrapper_function_headerwrapper_function_header)Literals)MODULE_PREFIXPREFIXRUNTIME_C_FILESTOP_LEVEL_NAMETYPE_VAR_PREFIXshared_lib_nameshort_id_from_name)Errors)FuncIR)ModuleIR	ModuleIRsdeserialize_modules)	DeserMapsLoadLiteral)RType)build_ir)Mapper)load_type_map)NameGeneratorexported_name)CompilerOptions)do_copy_propagation)insert_exception_handling)do_flag_elimination)lower_ir)insert_ref_count_opcodes)insert_spills)insert_uninit_checksc                      e Zd ZdZd
dZd	S )MarkedDeclarationz(Add a mark, useful for topological sort.declarationr   markboolreturnNonec                "    || _         d| _        d S )NF)rC   rD   )selfrC   rD   s      X/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/mypyc/codegen/emitmodule.py__init__zMarkedDeclaration.__init__a   s    &			    N)rC   r   rD   rE   rF   rG   )__name__
__module____qualname____doc__rK    rL   rJ   rB   rB   ^   s.        22     rL   rB   c                  4     e Zd ZdZd fd
ZddZddZ xZS )MypycPlugina  Plugin for making mypyc interoperate properly with mypy incremental mode.

    Basically the point of this plugin is to force mypy to recheck things
    based on the demands of mypyc in a couple situations:
      * Any modules in the same group must be compiled together, so we
        tell mypy that modules depend on all their groupmates.
      * If the IR metadata is missing or stale or any of the generated
        C source files associated missing or stale, then we need to
        recompile the module so we mark it as stale.
    optionsr   compiler_optionsr9   groupsGroupsrF   rG   c                    t                                          |           i | _        |D ]/\  }}t          d |D                       }|D ]}||f| j        |<   0|| _        t          |          | _        d S )Nc              3  $   K   | ]}|j         V  d S Nmodule.0sources     rJ   	<genexpr>z'MypycPlugin.__init__.<locals>.<genexpr>x   s$      AAvV]AAAAAArL   )superrK   	group_mapsortedrU   r   	metastore)	rI   rT   rU   rV   sourcesnamemodulesid	__class__s	           rJ   rK   zMypycPlugin.__init__r   s     	!!!BD# 	5 	5MGTAAAAAAAG 5 5&*G_r""5 !1)'22rL   ctxr   #tuple[str | None, list[str]] | Nonec                &   |j         |j        |j        }}}|| j        vrd S |s| j        |         S t	          ||| j                  \  }}}t          ||| j                  }	 | j                            |          }| j                            |          }	n# t          $ r Y d S w xY wt          j        |	          }
t          |          |
d         k    rd S |
d                                         D ]\  }}	 t          t          j                            | j        j        |          d          5 }|                                }d d d            n# 1 swxY w Y   n# t          $ r Y  d S w xY wt          |          }||k    r d S | j        |         S )N	meta_hash
src_hashesrb)rh   pathis_checkrb   r   rT   get_ir_cache_namerd   readFileNotFoundErrorjsonloadsr   itemsopenosjoinrU   
target_dir)rI   rj   rh   rp   rq   	meta_path_ir_path	meta_jsonir_jsonir_datahashfcontents	real_hashs                  rJ   report_config_datazMypycPlugin.report_config_data   s    !VSXs|(DT^##4  	&>"%% *"dDLAA	1a#Bdl;;	++I66In))'22GG  	 	 	 44		 *W%% y!!W[%9994 ",/5577 	 	JD$"',,t'<'GNNPTUU (YZ vvxxH( ( ( ( ( ( ( ( ( ( ( ( ( ( ($   ttt#H--Iy  tt ! ~b!!sH   !4B 
B$#B$68E.EEE	EE	E
E*)E*filer   list[tuple[int, str, int]]c                f    d | j                             |j        d g f          d         D             S )Nc                    g | ]}d |dfS )
   rQ   )r^   rh   s     rJ   
<listcomp>z3MypycPlugin.get_additional_deps.<locals>.<listcomp>   s    XXXRXXXrL      )rb   getfullname)rI   r   s     rJ   get_additional_depszMypycPlugin.get_additional_deps   s5    XXt~'9'9$-$PR'T'TUV'WXXXXrL   )rT   r   rU   r9   rV   rW   rF   rG   )rj   r   rF   rk   )r   r   rF   r   )rM   rN   rO   rP   rK   r   r   __classcell__)ri   s   @rJ   rS   rS   f   sx        	 	3 3 3 3 3 3/" /" /" /"bY Y Y Y Y Y Y YrL   rS   re   list[BuildSource]rT   r   rU   r9   rV   rW   fscacheFileSystemCache | Nonealt_lib_path
str | NonerF   r   c                    |j         s
J d            t          | |||t          |||          g          }|j        rt	          |j                  |S )Nz!strict_optional must be turned on)re   rT   r   r   extra_plugins)strict_optionalr
   rS   errorsr   )re   rT   rU   rV   r   r   results          rJ   parse_and_typecheckr      sp     "GG$GGGG!"7,<fEEF  F } *6=)))MrL   scclist[MypyFile]r   mapperr5   r   r,   r/   c                   |j         r?t          d                    d                    d | D                                            t	          | |j        |j        |||          }|j        dk    r|S i }|                                D ]}|j	        D ]}|j
        r
|||j
        <   |                                D ]}|j        D ]y}	t          |	           t          |	           t          |	           |	|v rt          |	||	                    t!          |	|           t#          |	|           t%          |	|           z|S )a  Compile an SCC into ModuleIRs.

    Any modules that this SCC depends on must have either compiled or
    loaded from a cache into mapper.

    Arguments:
        scc: The list of MypyFiles to compile
        result: The BuildResult from the mypy front-end
        mapper: The Mapper object mapping mypy ASTs to class and func IRs
        compiler_options: The compilation options
        errors: Where to report any errors encountered

    Returns the IR of the modules.
    zCompiling {}z, c              3  $   K   | ]}|j         V  d S rZ   )rf   )r^   xs     rJ   r`   z$compile_scc_to_ir.<locals>.<genexpr>   s$      -B-Baf-B-B-B-B-B-BrL   r   )verboseprintformatrz   r4   graphtypes
num_errorsvaluesclassesenv_user_function	functionsr@   r;   r>   r?   r=   r:   r<   )
r   r   r   rU   r   rg   env_user_functionsr\   clsfns
             rJ   compile_scc_to_irr      s   ,  En##DII-B-Bc-B-B-B$B$BCCDDD sFL&,@PRXYYG1.."" @ @> 	@ 	@C$ @<?"3#89	@ .."" 6 6" 	6 	6B $$$%b)))$R((('''b"4R"8999 R)***$4555$45555	6" NrL   c                J    t          i i           }i }t           j                  D ]y} fd|D             }fd|D             }|s!t           fd|D                       }	|	rt	          | |           Qt          | ||          }
|                    |
           z|S )zCompile a collection of modules into ModuleIRs.

    The modules to compile are specified as part of mapper's group_map.

    Returns the IR of the modules.
    c                *    g | ]}j         |         S rQ   )r   r^   rh   r   s     rJ   r   z)compile_modules_to_ir.<locals>.<listcomp>  s     5552fl2&555rL   c                H    g | ]}|j         j        v |j        |j        S rQ   )rh   rb   tree)r^   str   s     rJ   r   z)compile_modules_to_ir.<locals>.<listcomp>  s1    WWWR&:J1J1Jrw1J1J1J1JrL   c              3  4   K   | ]}|j         j        vV  d S rZ   )managerrechecked_modulesr   s     rJ   r`   z(compile_modules_to_ir.<locals>.<genexpr>  s-      MM2Bfn>>MMMMMMrL   )r1   r   r   allload_scc_from_cacher   update)r   r   rU   r   	deser_ctxrg   r   
scc_statestreesfreshscc_irs   ``         rJ   compile_modules_to_irr     s     "b!!IG !.. # #5555555
WWWW:WWW 	MMMMMMMMM 	#vvyAAAA&uff>NPVWWFNN6""""NrL   rg   'dict[str | None, list[tuple[str, str]]]c           	         fd| D             }t          d | D                       }i }| D ]K\  }}	fd|D             }
|
sg ||	<   t          |
||	|j        ||          }|                                ||	<   L|S )zCompile a collection of ModuleIRs to C source text.

    Returns a dictionary mapping group names to a list of (file name,
    file text) pairs.
    c                Z    i | ]'\  }}|D ]}|j         j        |j                  j         (S rQ   )r\   r   xpath)r^   re   r}   r_   r   s       rJ   
<dictcomp>z#compile_ir_to_c.<locals>.<dictcomp>-  sT       GQ   	v|FM28   rL   c                ,    g | ]\  }}d  |D             S )c                    g | ]	}|j         
S rQ   r[   r]   s     rJ   r   z.compile_ir_to_c.<locals>.<listcomp>.<listcomp>3  s    @@@fFM@@@rL   rQ   )r^   re   r}   s      rJ   r   z#compile_ir_to_c.<locals>.<listcomp>3  s+    ZZZZWa@@@@@ZZZrL   c                H    i | ]}|j         v |j         |j                  S rQ   r[   )r^   r_   rg   s     rJ   r   z#compile_ir_to_c.<locals>.<dictcomp>9  s;     
 
 
}'' M76=1'''rL   )r7   GroupGeneratorrb   generate_c_for_modules)rV   rg   r   r   rU   source_pathsnamesctextgroup_sources
group_namegroup_modules	generators    ``         rJ   compile_ir_to_cr   !  s          L ZZSYZZZ[[E 68E%+ ? ?!z
 
 
 
'
 
 

  	 "E*"<V5EuN^
 
	 &<<>>jLrL   rh   strrp   c                X    t          | ||          \  }}}|                    dd          S )Nz
.meta.jsonz.ir.json)r   replace)rh   rp   rT   r|   r}   s        rJ   rr   rr   I  s/    %b$88OIq!\:666rL   stater	   c                B    t          | j        | j        | j                  S rZ   )rr   rh   r   rT   )r   s    rJ   get_state_ir_cache_namer   N  s    UXu{EMBBBrL   rb   dict[str, str | None]r   rG   c                j   i }|                                 D ]\  }}d |D             ||<   |                                  D ]\  }}|j        |         }	t          ||	j        |j        j                  \  }
}}	 |j        j                            |
          }n# t          $ r Y cw xY wt          |	          }|
                                t          |          |||                  d}|j        j                            |t          |                     |j        j                                         dS )a  Write out the cache information for modules.

    Each module has the following cache information written (which is
    in addition to the cache information written by mypy itself):
      * A serialized version of its mypyc IR, minus the bodies of
        functions. This allows code that depends on it to use
        these serialized data structures when compiling against it
        instead of needing to recompile it. (Compiling against a
        module requires access to both its mypy and mypyc data
        structures.)
      * The hash of the mypy metadata cache file for the module.
        This is used to ensure that the mypyc cache and the mypy
        cache are in sync and refer to the same version of the code.
        This is particularly important if mypyc crashes/errors/is
        stopped after mypy has written its cache but before mypyc has.
      * The hashes of all of the source file outputs for the group
        the module is in. This is so that the module will be
        recompiled if the source outputs are missing.
    c                4    i | ]\  }}|t          |          S rQ   )r   )r^   r   datas      rJ   r   zwrite_cache.<locals>.<dictcomp>n  s&    IIIZT4l400IIIrL   )irrm   rn   N)rw   r   r   r   r   rT   rd   rs   OSErrorr   	serializer   writer   commit)rg   r   rb   r   hashesrf   filesrh   r\   r   r|   r}   	meta_datanewpathr   s                  rJ   write_cacher   R  sM   4 F{{}} J JeII5IIIt mmoo E E
F\")"bh8NOO	1a	055i@@II 	 	 	H	 *"--""$$$Y// 2/
 
 	 &&w
70C0CDDDD
N##%%%%%s   7B
B$#B$rj   r1   c                f    fd| D             }t          ||          }t          || |           |S )zfLoad IR for an SCC of modules from the cache.

    Arguments and return are as compile_scc_to_ir.
    c                    i | ]\}|j         t          j        j        j                            t          j        |j                                                d          ]S )r   )r   ru   rv   r   rd   rs   r   r   )r^   kr   s     rJ   r   z'load_scc_from_cache.<locals>.<dictcomp>  sk         	

DJN$))*A&,qzBZ*[*[\\
 

  rL   )r0   r6   )r   r   r   rj   
cache_datarg   s    `    rJ   r   r     sU        	  J "*c22G&#s###NrL   ,tuple[ModuleIRs, list[FileContents], Mapper]c                ^   d |D             }t          |          }| j        j                            ddd| j        j                   t          | |||          }|j        dk    ri g t          i           fS t          ||| ||          t          || |           |fd|D             |fS )a@  Compile Python module(s) to the source of Python C extension modules.

    This generates the source code for the "shared library" module
    for each group. The shim modules are generated in mypyc.build.
    Each shared library module provides, for each module in its group,
    a PyCapsule containing an initialization function.
    Additionally, it provides a capsule containing an export table of
    pointers to all of the group's functions and static variables.

    Arguments:
        result: The BuildResult from the mypy front-end
        compiler_options: The compilation options
        errors: Where to report any errors encountered
        groups: The groups that we are compiling. See documentation of Groups type above.

    Returns the IR of the modules and a list containing the generated files for each group.
    c                .    i | ]\  }}|D ]
}|j         |S rQ   r[   )r^   grouplib_namer_   s       rJ   r   z(compile_modules_to_c.<locals>.<dictcomp>  s.    [[[_UHUZ[[6[[[[rL   z<mypyc>N)r\   scoperT   r   c                &    g | ]\  }}|         S rQ   rQ   )r^   r}   rf   r   s      rJ   r   z(compile_modules_to_c.<locals>.<listcomp>  s!    777WQU4[777rL   )	r5   r   r   set_filerT   r   r   r   r   )r   rU   r   rV   rb   r   rg   r   s          @rJ   compile_modules_to_cr     s    * \[[[[IIF N""$dFN4J #    $FF4DfMMG12vbzz!!FGVV=MNNEE2227777777??rL   r   r-   emitterr   c                8   t          t          | j        |           dd          |j        j        |                    | j                  <   | j        t          k    rt          | |j	                  rTt          t          | |j                   d          |j        j        t          |                     |j                  z   <   d S t          t          | |j                   d          |j        j        t          |                     |j                  z   <   d S d S N;Tneeds_export)r   r   declcontextdeclarationsnative_function_namerf   r(   is_fastcall_supportedcapi_versionr#   r   r&   cnamer"   )r   r   s     rJ   generate_function_declarationr    s   J[!"'733666TK K KGO !=!=bg!F!FG 
w.   W%9:: 	M^*2w}==@@@N NGO("((7=2I2I)IJJJ N_1"gmDDGGGN NGO("((7=2I2I)IJJJ ! rL   r   rf   c                p    d| v r|                      |d| d          S |                      |d|           S )zHGiven a C decl and its name, modify it to be a declaration to a pointer.(z(*)*)r   )r   rf   s     rJ   
pointerizer	    sE     d{{||D,t,,,/// ||D*d**---rL   r   c                v    t           j                            |                     d          dd                   S )z>Given a group name, return the relative directory path for it..Nr   )ry   seprz   split)r   s    rJ   	group_dirr    s-    6;;z'',,SbS1222rL   c                      e Zd Zd;dZed<d            Zed<d            Zd=dZd>dZd?dZ	d@dZ
d@dZdAd ZdBd!ZdCd#Zd$d%dDd)ZdEd*ZdFd+ZdEd,ZdGd/ZdHd2ZdId5ZdJd7ZdKd:Zd$S )Lr   rg   dict[str, ModuleIR]r   dict[str, str]r   r   rb   r   r   r7   rU   r9   rF   rG   c                    || _         || _        t          |||          | _        || _        g | _        || _        |du| _        || _        |j	        | _	        dS )a  Generator for C source for a compilation group.

        The code for a compilation group contains an internal and an
        external .h file, and then one .c if not in multi_file mode or
        one .c file per module if in multi_file mode.)

        Arguments:
            modules: (name, ir) pairs for each module in the group
            source_paths: Map from module names to source file paths
            group_name: The name of the group (or None if this is single-module compilation)
            group_map: A map of modules to their group names
            names: The name generator for the compilation
            multi_file: Whether to put each module in its own source file regardless
                        of group structure.
        N)
rg   r   r   r   r   simple_initsr   use_shared_librU   
multi_file)rI   rg   r   r   rb   r   rU   s          rJ   rK   zGroupGenerator.__init__  sa    0 (%eZCC
 46$(4 0*5rL   r   c                B    | j         rdt          | j                   z   ndS )Nr}    )r   r8   rI   s    rJ   group_suffixzGroupGenerator.group_suffix  s#    7;Ns]4?3333BNrL   c                t    | j         r0dt          | j                             d          d                   z   ndS )Nr}   r  r   r  )r   r8   r  r  s    rJ   short_group_suffixz!GroupGenerator.short_group_suffix	  s7    FJo]s]4?#8#8#=#=b#ABBBB[]]rL   list[tuple[str, str]]c                   g }| j         o| j        }| j                                        D ]&}|j        D ]}t          || j        j                   't          | j                  }| j	        j
        r#t          D ]}|                    d| d           |                    d| j         d           |                    d| j         d           |}|                                  | j                                        D ]\  }}|rPt          | j                  }|                    d| j         d           |                    d| j         d           |                     ||           |                     ||           |                     |j        |           |j        D ]}	|	j        rt-          |	||           |                     |||           |j        D ]}|                                 t1          ||| j        |         |           |j        t6          k    rd|                                 t9          ||j                  rt=          ||| j        |         |           t?          ||| j        |         |           |rMd|j         !                    |           d}|"                    |d#                    |j$                  f           t          | j                  }
|
                    d	| j%         d
           |
                    d| j%         d
           |
                    d           |
                    d           t          | j                  }|                    d| j%         d
           |                    d| j%         d
           |                    d           |                    d           |                    d| j         d           |                                 |                    d           |                                 | j                                        D ]s\  }}| &                    ||j'        |           |j        D ]}	tQ          |	||
|           | )                    ||j*        |           |j        D ]}tW          ||           ttY          | j        j-                  D ]}t]          |          }t]          |/                    d          d                   }|0                    d1                    td          j3        #                    ti          |          d| d                    d| d| d           | 5                                }|}| 6                    |           |                                 |D ]s}|j7        r|
n|}|j7        sP |j0        d|j8        d          g|j8        dd          R   |j9        r |j0        |j9          T |j0        |j8          d |j0        |j8          t| j:        r+| ;                    |
|           | <                    |           |
                    d           |                    d           | j:        rti          | j:                  nd}|td          j3        #                    |d| j         d          d#                    |j$                  ftd          j3        #                    |d| j         d          d#                    |j$                  ftd          j3        #                    |d| j         d          d#                    |
j$                  fgz   S )Nz
#include ""z#include "__nativez.h"z#include "__native_internal	__native_z.cr  z#ifndef MYPYC_NATIVE_Hz#define MYPYC_NATIVEz#include <Python.h>z#include <CPy.h>z#ifndef MYPYC_NATIVE_INTERNALz#define MYPYC_NATIVE_INTERNALzint CPyGlobalsInit(void);r  r   z#include <{}>z.hzstruct export_table_z	 exports_r   zextern r   r   z#endif__native__native_internal)=r  r  rg   r   r   collect_literalsr   literalsr   rU   include_runtime_filesr'   	emit_liner  generate_literal_tablesrw   declare_moduledeclare_internal_globalsdeclare_importsimportsr   is_ext_classr   generate_module_defr   r   rf   r(   r  r  r!   r    r   private_nameappendrz   	fragmentsr  declare_finalsfinal_namesr   declare_type_varstype_var_namesr  rc   
group_depsr8   r  
emit_linesr   ry   rp   r  toposort_declarationsgenerate_globals_initis_typer   defnr   generate_export_tablegenerate_shared_lib_init)rI   file_contentsr  r\   r   base_emitterrf   r   module_nameclext_declarationsr   libelib	short_libsorted_declsrC   decls
output_dirs                      rJ   r   z%GroupGenerator.generate_c_for_modules  s%   (<T_
 l))++ 	< 	<F& < < T\%:;;;;< t|,,  6 	=' = =&&';D';';';<<<<PD4KPPPQQQYT=TYYYZZZ$$&&&#'<#5#5#7#7  	I  	IK ^!$,//!!"St7N"S"S"STTT!!"\@W"\"\"\]]]W555))+w???  999n = =? ="2{G<<< $$Wk6BBB&  !!###(Wd6G6TVabbb7n,,%%''',R1EFF 1):;)G    9):;)G    IN7=#=#=k#J#JNNN$$dBGGG4E,F,F%GHHH #4<00""#O$:K#O#O#OPPP""#O$:K#O#O#OPPP""#8999""#5666t|,,Tt?PTTTUUUTt?PTTTUUU45551222PD4KPPPQQQ   :;;;   #'<#5#5#7#7 	@ 	@KV-?NNNn V V(W6FUUUU"";0E|TTT& @ @-b,????@ $,122 	 	C %%D%ciinnR&899I##&&rw||IcNND]PYD]D]D]'^'^__=t==d===   
 1133""7+++' 	4 	4K(3(;M$$E& 	4  !@;+;A+>!@!@X;CSTUTVTVCWXXXX # :&G&(8999&G&(8999  +"2333? 	3&&'7AAA))'222""8,,,x(((37?JYt///
Z)OD4K)O)O)OPP)**
 Z)XT=T)X)X)XYY.//
 Z)OD4K)O)O)OPP(233 
 
 	
rL   c                   | j         j        }|                     d|                                z  d           t	          |                                          }|                     dd|           t	          |                                          }|                     dd|           t	          |                                          }|                     dd|           t          |	                                          }|                     dd	|           t          |
                                          }|                     dd
|           t          |                                          }|                     dd|           t          |                                          }|                     dd|           dS )a  Generate tables containing descriptions of Python literals to construct.

        We will store the constructed literals in a single array that contains
        literals of all types. This way we can refer to an arbitrary literal by
        its index.
        zPyObject *[%d]
CPyStaticszconst char * const []
CPyLit_StrinitializerCPyLit_Bytes
CPyLit_Intzconst double []CPyLit_FloatCPyLit_Complexzconst int []CPyLit_TupleCPyLit_FrozenSetN)r   r$  declare_globalnum_literalsc_string_array_initializerencoded_str_valuesencoded_bytes_valuesencoded_int_valuesr   encoded_float_valuesencoded_complex_valuesencoded_tuple_valuesencoded_frozenset_values)	rI   r$  init_str
init_bytesinit_intinit_floatsinit_complex
init_tupleinit_frozensets	            rJ   r'  z&GroupGenerator.generate_literal_tables  s    <(,x/D/D/F/FFUUU-h.I.I.K.KLL3\xXXX/0M0M0O0OPP
3^Q[\\\-h.I.I.K.KLL3\xXXX)(*G*G*I*IJJ-~;WWW*8+J+J+L+LMM-/?\ZZZ()F)F)H)HII
NN
SSS,X-N-N-P-PQQN,>N[[[[[rL   decl_emitterr   code_emitterc                   |j         j        }|                    dd| j         d           |                                D ]G\  }}|j        r;|                    t          d                    |j	                  |                     H|                    d           |                    dd| j         d           |                                D ]%\  }}|j        r|                    d| d	           &|                    d           d
S )a  Generate the declaration and definition of the group's export struct.

        To avoid needing to deal with deeply platform specific issues
        involving dynamic library linking (and some possibly
        insurmountable issues involving cyclic dependencies), compiled
        code accesses functions and data in other compilation groups
        via an explicit "export struct".

        Each group declares a struct type that contains a pointer to
        every function and static variable it exports. It then
        populates this struct and stores a pointer to it in a capsule
        stored as an attribute named 'exports' on the group's shared
        library's python module.

        On load, a group's init function will import all of its
        dependencies' exports tables using the capsule mechanism and
        copy the contents into a local copy of the table (to eliminate
        the need for a pointer indirection when accessing it).

        Then, all calls to functions in another group and accesses to statics
        from another group are done indirectly via the export table.

        For example, a group containing a module b, where b contains a class B
        and a function bar, would declare an export table like:
            struct export_table_b {
                PyTypeObject **CPyType_B;
                PyObject *(*CPyDef_B)(CPyTagged cpy_r_x);
                CPyTagged (*CPyDef_B___foo)(PyObject *cpy_r_self, CPyTagged cpy_r_y);
                tuple_T2OI (*CPyDef_bar)(PyObject *cpy_r_x);
                char (*CPyDef___top_level__)(void);
            };
        that would be initialized with:
            static struct export_table_b exports = {
                &CPyType_B,
                &CPyDef_B,
                &CPyDef_B___foo,
                &CPyDef_bar,
                &CPyDef___top_level__,
            };
        To call `b.foo`, then, a function in another group would do
        `exports_b.CPyDef_bar(...)`.
        r  zstruct export_tablez {
};zstatic struct export_tablez exports = {&,N)
r   r   r6  r  rw   r   r&  r	  rz   r   )rI   rd  re  rF  rf   r   s         rJ   r;  z$GroupGenerator.generate_export_table  s!   X $1$P$:K$P$P$PQQQ++-- 	O 	OJD$  O&&z$))DI2F2F'M'MNNNt$$$$aAR$a$a$abbb++-- 	4 	4JD$  4&&{4{{{333t$$$$$rL   r   c                   | j         J |                                 |                    d                    t	          | j                                       d          d                   dd                    t	          | j                             ddd	d
ddddddddd           |                    d                    t	          | j                             ddddddddd
  
         | j        D ]_}t          |          }|                    d| dd                    |t	          | j                   |          dddd| dddddd           `t          | j	        j
                  D ]}t          |          }|                    d                    t	          |                    d                    ||t	          |                    d| d ddd!                    |"          d           |                    dd#d$d%d           dS )&a  Generate the init function for a shared library.

        A shared library contains all of the actual code for a
        compilation group.

        The init function is responsible for creating Capsules that
        wrap pointers to the initialization function of all the real
        init functions for modules in this shared library as well as
        the export table containing all of the exported functions and
        values from all the modules.

        These capsules are stored in attributes of the shared library.
        NzPyMODINIT_FUNC PyInit_{}(void)r  r   {zQstatic PyModuleDef def = {{ PyModuleDef_HEAD_INIT, "{}", NULL, -1, NULL, NULL }};zint res;zPyObject *capsule;zPyObject *tmp;zstatic PyObject *module;zif (module) {zPy_INCREF(module);zreturn module;}zmodule = PyModule_Create(&def);zif (!module) {z
goto fail;r  z6capsule = PyCapsule_New(&exports, "{}.exports", NULL);zif (!capsule) {z9res = PyObject_SetAttrString(module, "exports", capsule);zPy_DECREF(capsule);zif (res < 0) {zextern PyObject *CPyInit_z(void);z@capsule = PyCapsule_New((void *)CPyInit_{}, "{}.init_{}", NULL);z+res = PyObject_SetAttrString(module, "init_z", capsule);zGtmp = PyImport_ImportModule("{}"); if (!tmp) goto fail; Py_DECREF(tmp);zHstruct export_table_{} *pexports_{} = PyCapsule_Import("{}.exports", 0);zif (!pexports_) {zDmemcpy(&exports_{group}, pexports_{group}, sizeof(exports_{group}));)r   fail:zPy_XDECREF(module);return NULL;)r   r&  r6  r   r*   r  rg   r8   rc   r   r5  )rI   r   modrf   r   egroups         rJ   r<  z'GroupGenerator.generate_shared_lib_init  s    ***,330066s;;B?  cjj#DO44   & --	
 	
 	
2 	DKK00  G!	
 	
 	
 < 	 	C %%D9D999RYY/$/::D  "PdPPP%      DL344 	 	E"5))FY``#E**  [aaFOE$:$:  .---V]]  ^        	+W6K^]`aaaaarL   c                   |                     dddddd           |                    d           | j        D ] \  }}|                    | d| d           !d	}|                     d
| ddd           |                     ddd           d S )Nr  zint CPyGlobalsInit(void)rl  zstatic int is_initialized = 0;zif (is_initialized) return 0;zCPy_Init(); = r   zbCPyLit_Str, CPyLit_Bytes, CPyLit_Int, CPyLit_Float, CPyLit_Complex, CPyLit_Tuple, CPyLit_FrozenSetz&if (CPyStatics_Initialize(CPyStatics, z) < 0) {z
return -1;rm  zis_initialized = 1;z	return 0;)r6  r&  r  )rI   r   symbolfixupr   s        rJ   r8  z$GroupGenerator.generate_globals_initO  s    &,+	
 	
 	
 	-(((!. 	6 	6MFE44E4445555uFVFFFVY	
 	
 	
 	0+sCCCCCrL   r?  r\   r.   c           
        |j                             |          }|                    d| d           |j        D ]}|j        |j        t          k    rt          |j        |j        j	        |j
                  }t          ||j                  rd}nd}|                    d                    ||                    |j                   t          |                     |                    d           |                    d	           |                                 |                    d
| ddd| dddd| dd	           |                                 | j        sd| d}ndt%          |           d}|                    |d           |                    d           |                     ||          }	|                    d|	 dd|	 dd|	 dd           |                    |	 d| d d!|	 d"d#           |                    d$|	 d%           |                    d&|          }
|                    |
 d'|	 dd!|
 d"d#           g }|j        D ]v}|                    |          }|                    |           |j        rC|                    d(                    |)                     |                    d*| d+d#           w|                    d,d#           |                     ||           |                    d-           |                    d|	 d           |                    d.d/|	 dd0           |j        D ]c\  }}|                    ||          }|                    ||d12           |                    |          }|                    | d3| d           d|D ]}|                    d/| d           |                    d4           |                    d           dS )5zFEmit the PyModuleDef struct for a module and the module init function.zstatic PyMethodDef zmodule_methods[] = {NMETH_FASTCALLMETH_VARARGSzY{{"{name}", (PyCFunction){prefix}{cname}, {flag} | METH_KEYWORDS, NULL /* docstring */}},)rf   r  prefixflagz{NULL, NULL, 0, NULL}rh  zstatic struct PyModuleDef z
module = {zPyModuleDef_HEAD_INIT,r  z",zNULL, /* docstring */z9-1,       /* size of per-interpreter state of the module,zD             or -1 if the module keeps state in global variables. */module_methodszPyMODINIT_FUNC PyInit_z(void)zPyObject *CPyInit_rl  zPyObject* modname = NULL;zif (rn  z
Py_INCREF(z);zreturn r   rm  z = PyModule_Create(&zmodule);zif (unlikely(z
 == NULL))    goto fail;z-modname = PyObject_GetAttrString((PyObject *)z, "__name__");globalsz = PyModule_GetDict(zT{t} = (PyTypeObject *)CPyType_FromTemplate((PyObject *){t}_template, NULL, modname);)tzif (unlikely(!z))zif (CPyGlobalsInit() < 0)zPy_DECREF(modname);ro  z	Py_CLEAR(zPy_CLEAR(modname);T)is_xdecrt  rp  )r   r.  r&  r   
class_namerf   r(   r+   r   	shortnameliner  r  r   r  r&   r6  r  r8   module_internal_static_namestatic_namer   type_struct_namer/  is_generatedgenerate_top_level_callr2  emit_dec_refc_undefined_value)rI   r   r?  r\   module_prefixr   rf   r{  rC   module_staticmodule_globalstype_structsr@  type_structtypr  undefr  s                     rJ   r-  z"GroupGenerator.generate_module_defd  s	     22;??TTTTUUU" 	 	B}(BG~,E,E%bgrw/@"'JJD$R)=>> &&%.&d"((7=*A*A&W[&\\	    	1222$ 	CCCC$#GR,,,		
 		
 		
 	 " 	RF;FFFKKQ}[/I/IQQQK;,,,5666 88gNN&=&&&****&m&&&		
 	
 	
 	II-III5M555	
 	
 	

 	YMYYY	
 	
 	
 !,,YDDDD=DDD6N666	
 	
 	
 #%. 	W 	WB!22266K,,, W""@@F@U@U   ""#CK#C#C#CEUVVV68HIII$$VW55501114M4445557$A$A$A$ACWXXX+ 	; 	;ID#!--dK@@K  c4 @@@--c22E99999::::  	1 	1A/!///0000.)))#rL   c                    t          |j                  D ]H}|j        t          k    r6|                    d|                    |j                   ddd            dS IdS )z8Generate call to function representing module top level.zchar result = z();zif (result == 2)r}  N)reversedr   rf   r(   r6  r   r   )rI   r\   r   r   s       rJ   r  z&GroupGenerator.generate_top_level_call  s     6+,, 	 	Bw.((""OW%A%A"'%J%JOOO&$  
  )	 	rL   list[HeaderDeclaration]c                    g i | j         j                                        D ]\  }}t          |d          |<   dfdD ]} |           S )a~  Topologically sort the declaration dict by dependencies.

        Declarations can require other declarations to come prior in C (such as declaring structs).
        In order to guarantee that the C output will compile the declarations will thus need to
        be properly ordered. This simple DFS guarantees that we have a proper ordering.

        This runs in O(V + E).
        Frf   r   rF   rG   c                    |          }|j         rd S |j        j        D ]} |                               |j                   d|_         d S )NT)rD   rC   dependenciesr/  )rf   r   child_toposort_visitmarked_declarationsr   s      rJ   r  z=GroupGenerator.toposort_declarations.<locals>._toposort_visit  sd    &t,Dy )6 ' '&&&&MM$*+++DIIIrL   )rf   r   rF   rG   )r   r   rw   rB   )rI   r   vrf   r  r  r   s       @@@rJ   r7  z$GroupGenerator.toposort_declarations  s     <>L-3355 	A 	ADAq%6q%%@%@""		 		 		 		 		 		 		 		 ( 	" 	"DOD!!!!rL   NrK  type_spacedrf   rL  c                   d|vr| | }n"|                     dd          \  }}| | d| }|sd }n	| d| dg}|| j        j        vr#t          | d|          | j        j        |<   d S d S )N[r   rt  r   )r:  )r  r   r   r   )rI   r  rf   rL  baseabr:  s           rJ   rS  zGroupGenerator.declare_global  s     k!!!)4))DD$$S!,,DAq#####D 	0DD...../Dt|000.?4


QU.V.V.VDL%d+++ 10rL   c                ^    |                     d|          }|                     d|           d S )Nr~  
PyObject *r  rS  )rI   r?  r   r  s       rJ   r)  z'GroupGenerator.declare_internal_globals
  s3    )))[AAL+66666rL   c                B    |                     |dz   d t                    S )N	_internalrz  )r  r%   )rI   r?  r   s      rJ   r  z*GroupGenerator.module_internal_static_name  s"    "";#<d="YYYrL   c                   || j         v r.|                     ||          }|                     d|d           |                    |d t                    }|                     d|           | j                            |df           d S )NzCPyModule *NULLrK  r  Py_None)rg   r  rS  r  r%   r  r/  )rI   r?  r   internal_static_namer  s        rJ   r(  zGroupGenerator.declare_module  s    
 $,&&#'#C#CKQX#Y#Y /CQWXXX))+tM)RRM;777  +y!9:::::rL   impsIterable[str]c                <    |D ]}|                      ||           d S rZ   )r(  )rI   r  r   imps       rJ   r*  zGroupGenerator.declare_imports  s4     	. 	.CW----	. 	.rL   r2  Iterable[tuple[str, RType]]c           
         |D ]i\  }}|                     ||          }t          |                    |           | d|                     ||||          gd          |j        j        |<   jd S r   )r  r   ctype_spacedfinal_definitionr   r   )rI   r\   r2  r   rf   r  r  s          rJ   r1  zGroupGenerator.declare_finals!  s     % 	 	ID#!--dF;;K8I'',,<k<<<&&vtS'BBC!9 9 9GO(55	 	rL   r  r3   c                    |                     ||          }|                    |          }|                    |           | d| dS )Nrt  r   )r  c_initializer_undefined_valuer  )rI   r\   rf   r  r   r  	undefineds          rJ   r  zGroupGenerator.final_definition,  sT    ))$7799#>>	&&s++I[IIYIIIIrL   
identifierc                ^    |                     |d           }|                     d|           d S )Nr  r  )rI   r  r   ru  s       rJ   declare_static_pyobjectz&GroupGenerator.declare_static_pyobject2  s3    $$Z66L&11111rL   r4  	list[str]c                    |D ]G}|                     ||t                    }t          d| dd| dgd          |j        j        |<   Hd S )Nr  r  r   z = NULL;Fr   )r  r)   r   r   r   )rI   r\   r4  r   rf   r  s         rJ   r3  z GroupGenerator.declare_type_vars6  sx    " 	 	D!--dF?-SSK8I+[+++3k3334"9 9 9GO(55	 	rL   )rg   r  r   r  r   r   rb   r   r   r7   rU   r9   rF   rG   )rF   r   )rF   r  )rF   rG   )rd  r   re  r   rF   rG   )r   r   rF   rG   )r   r   r?  r   r\   r.   rF   rG   )r\   r.   r   r   rF   rG   )rF   r  )r  r   rf   r   rL  r   rF   rG   )r?  r   r   r   rF   rG   )r?  r   r   r   rF   r   )r  r  r   r   rF   rG   )r\   r   r2  r  r   r   rF   rG   )
r\   r   rf   r   r  r3   r   r   rF   r   )r  r   r   r   rF   rG   )r\   r   r4  r  r   r   rF   rG   )rM   rN   rO   rK   propertyr  r  r   r'  r;  r<  r8  r-  r  r7  rS  r)  r  r(  r*  r1  r  r  r3  rQ   rL   rJ   r   r     s       "6 "6 "6 "6H O O O XO ^ ^ ^ X^E
 E
 E
 E
N\ \ \ \@:% :% :% :%x]b ]b ]b ]b~D D D D*j j j jX
 
 
 
   > IMW W W W W W 7 7 7 7Z Z Z Z
; 
; 
; 
;. . . .	 	 	 	J J J J2 2 2 2     rL   r   Tdepsdict[T, set[T]]list[T]c                `     g t                      d fd D ]} |           S )zUTopologically sort a dict from item to dependencies.

    This runs in O(V + E).
    itemr  rF   rG   c                    | v rd S |          D ]} |                                |                                |            d S rZ   )r/  add)r  r  r  r   visitvisiteds     rJ   r  ztoposort.<locals>.visitK  s]    7??F$Z 	 	EE%LLLLdDrL   )r  r  rF   rG   )set)r  r  r   r  r  s   ` @@@rJ   toposortr  C  sh    
 FeeG           dMrL   r  tuple[int, int]rE   c                D    | j         | j        dk    rdS | j        dk    S dS )N__call__TrK   )r  rf   )r   r  s     rJ   r  r  [  s.    	} 7j  4w*$$4rL   r$  r$   c                    | j         D ];}|j        D ]1}t          |t                    r|                    |j                   2<dS )zStore all Python literal object refs in fn.

    Collecting literals must happen only after we have the final IR.
    This way we won't include literals that have been optimized away.
    N)blocksops
isinstancer2   record_literalvalue)r   r$  blockops       rJ   r#  r#  e  s^      2 2) 	2 	2B"k** 2''111	22 2rL   
componentslist[bytes]c                    g }|                     d           | D ]*}|                     dt          |          z   dz              +|                     d           d                    |          S )Nz{
z    z,
rm  r  )r/  r   rz   )r  r   ss      rJ   rU  rU  q  st    F
MM% @ @f3A666>????
MM#776??rL   )NN)re   r   rT   r   rU   r9   rV   rW   r   r   r   r   rF   r   )r   r   r   r   r   r5   rU   r9   r   r,   rF   r/   )
r   r   r   r5   rU   r9   r   r,   rF   r/   )rV   rW   rg   r/   r   r   r   r5   rU   r9   rF   r   )rh   r   rp   r   rT   r   rF   r   )r   r	   rF   r   )
rg   r/   r   r   rb   r   r   r   rF   rG   )
r   r   r   r   r   r5   rj   r1   rF   r/   )
r   r   rU   r9   r   r,   rV   rW   rF   r   )r   r-   r   r   rF   rG   )r   r   rf   r   rF   r   )r   r   rF   r   )r  r  rF   r  )r   r-   r  r  rF   rE   )r   r-   r$  r$   rF   rG   )r  r  rF   r   )}rP   
__future__r   ru   ry   collections.abcr   typingr   r   
mypy.buildr   r   r	   r
   r   r   r   r   mypy.errorsr   mypy.fscacher   
mypy.nodesr   mypy.optionsr   mypy.pluginr   r   	mypy.utilr   r   mypyc.codegen.cstringr   mypyc.codegen.emitr   r   r   r   mypyc.codegen.emitclassr   r   mypyc.codegen.emitfuncr   r   mypyc.codegen.emitwrapperr    r!   r"   r#   mypyc.codegen.literalsr$   mypyc.commonr%   r&   r'   r(   r)   r*   r+   mypyc.errorsr,   mypyc.ir.func_irr-   mypyc.ir.module_irr.   r/   r0   mypyc.ir.opsr1   r2   mypyc.ir.rtypesr3   mypyc.irbuild.mainr4   mypyc.irbuild.mapperr5   mypyc.irbuild.preparer6   mypyc.namegenr7   r8   mypyc.optionsr9    mypyc.transform.copy_propagationr:   mypyc.transform.exceptionsr;    mypyc.transform.flag_eliminationr<   mypyc.transform.lowerr=   mypyc.transform.refcountr>   mypyc.transform.spillr?   mypyc.transform.uninitr@   tuplelistr   GrouprW   FileContentsrB   rS   r   r   r   r   rr   r   r   r   r   r  r	  r  r   r  r  r  r#  rU  rQ   rL   rJ   <module>r     s   N N
 # " " " " "  				 $ $ $ $ $ $ $ $ $ $ $ $ $ $	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 % $ $ $ $ $ ( ( ( ( ( (                   3 3 3 3 3 3 3 3 - - - - - - - - 6 6 6 6 6 6 ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ L L L L L L L L S S S S S S S S            , + + + + +                         # # # # # # G G G G G G G G G G / / / / / / / / ! ! ! ! ! ! ' ' ' ' ' ' ' ' ' ' ' ' / / / / / / 6 6 6 6 6 6 6 6 ) ) ) ) ) ) @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ * * * * * * = = = = = = / / / / / / 7 7 7 7 7 7, 	d;#./	e E#s(O$       LY LY LY LY LY& LY LY LYh '+#    *6 6 6 6r   <% % % %P7 7 7 7
C C C C2& 2& 2& 2&j   $%@ %@ %@ %@P   . . . .3 3 3 3
]	 ]	 ]	 ]	 ]	 ]	 ]	 ]	@ GCLL   0   	2 	2 	2 	2     rL   