o
    tBh                    @  sV  U d Z ddlmZ ddlmZmZmZmZ ddlm	Z	 ddl
mZ ddlmZmZmZm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 dd
lmZ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+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z?m@Z@mAZAmBZBmCZCmDZDmEZEmFZF ddlGmHZHmIZImJZJmKZKmLZLmMZMmNZNmOZOmPZPmQZQmRZRmSZSmTZTmUZUmVZVmWZWmXZXmYZYmZZZm[Z[m\Z\m]Z]m^Z^m_Z_m`Z`maZambZbmcZcmdZdmeZemfZfmgZgmhZhmiZimjZjmkZkmlZl ddlmmnZn ddlompZp ddlqmrZr ddlsmtZt ddlumvZvmwZwmxZxmyZy ddlzm{Z{m|Z| ddl}m~Z~mZmZmZmZmZmZmZ ddlmZ ddlmZmZmZ ddlmZmZmZ ddlmZmZmZmZmZ ddlmZ ddlmZmZmZ ddlmZmZmZ ddlmZ ddlmZ ddlmZ eeeF eFf ZdZd ed! d  > Zd"ed#< G d$d% d%Zd/d,d-Zd.S )0a  A "low-level" IR builder class.

LowLevelIRBuilder provides core abstractions we use for constructing
IR as well as a number of higher-level ones (accessing attributes,
calling functions and methods, and coercing between types, for
example). The core principle of the low-level IR builder is that all
of its facilities operate solely on the IR level and not the AST
level---it has *no knowledge* of mypy types or expressions.
    )annotations)CallableOptionalSequenceTuple)Final)map_actuals_to_formals)ARG_POSARG_STAR	ARG_STAR2ArgKind)
op_methods)AnyType	TypeOfAny)FAST_ISINSTANCE_MAX_SUBCLASSESMAX_LITERAL_SHORT_INTMIN_LITERAL_SHORT_INTPLATFORM_SIZEuse_method_vectorcalluse_vectorcall)ClassIRall_concrete_classes)FuncDeclFuncSignature)#	ERR_FALSE	ERR_NEVERNAMESPACE_MODULENAMESPACE_STATICNAMESPACE_TYPEAssignAssignMulti
BasicBlockBoxBranchCallCallCCastComparisonOpGetAttrGetElementPtrGotoIntegerIntOp	KeepAliveLoadAddressLoadErrorValueLoadLiteralLoadMem
LoadStatic
MethodCallOpRaiseStandardErrorRegisterSetMemTruncateTupleGetUnboxUnreachableValue)%PyListObjectPyObjectPySetObjectPyVarObjectRArray	RInstanceRTupleRTypeRUnionbit_rprimitivebool_rprimitivebytes_rprimitivec_int_rprimitivec_pyssize_t_rprimitivec_size_t_rprimitivedict_rprimitivefloat_rprimitiveint_rprimitiveis_bit_rprimitiveis_bool_rprimitiveis_bytes_rprimitiveis_dict_rprimitiveis_list_rprimitiveis_none_rprimitiveis_set_rprimitiveis_short_int_rprimitiveis_str_rprimitive	is_taggedis_tuple_rprimitivelist_rprimitivenone_rprimitiveobject_pointer_rprimitiveobject_rprimitiveoptional_value_typepointer_rprimitiveshort_int_rprimitivestr_rprimitive)Mapperconcrete_arg_kind)CompilerOptions)bytes_compare)dict_build_opdict_new_opdict_ssize_t_size_opdict_update_in_display_op)err_occurred_opkeep_propagating_op)generic_len_opgeneric_ssize_t_len_op
py_call_oppy_call_with_kwargs_oppy_getattr_oppy_method_call_oppy_vectorcall_method_oppy_vectorcall_op)int_comparison_op_mapping)list_build_oplist_extend_opnew_list_op)bool_opfast_isinstance_opnone_object_op)ERR_NEG_INTCFunctionDescription
binary_opsmethod_call_ops	unary_ops)
new_set_op)str_check_if_truestr_ssize_t_size_opunicode_compare)list_tuple_opnew_tuple_opnew_tuple_with_length_op)is_runtime_subtype)is_same_type)
is_subtype
         r   PY_VECTORCALL_ARGUMENTS_OFFSETc                   @  s  e Zd Zdd	d
Zd ddZdddZdddZdddZdddZdddZ	dd d!Z
dd"d#Zdd%d&Zd'd(dd/d0Z	'd	d'd(d
d2d3Zdd4d5Zd'd6dd;d<Zdd?d@ZddAdBZddEdFZddGdHZddJdKZddNdOZddUdVZ	W	Wddd_d`Z	W	WdddbdcZddddeZddgdhZddidjZddpdqZddtduZ	W	W	'dddzd{Zdd~dZ dddZ!dddZ"dddZ#dddZ$d ddZ%d!ddZ&d"ddZ'd#ddZ(d$ddZ)dWe*ddWfd%ddZ+d&ddZ,d'ddZ-d(ddZ.d)ddZ/d	d*ddZ0d+ddZ1d,ddZ2d+ddZ3d+ddZ4d-d+ddZ5d.ddZ6d)ddZ7d/ddĄZ8d0ddǄZ9d1dd˄Z:d2dd΄Z;d3ddфZ<d3ddӄZ=d4ddلZ>d5ddۄZ?	Wd6d7dd߄Z@	W	'd8d9ddZAd:ddZBd;ddZCd	d<ddZDd=ddZEd2ddZFd>ddZG	'd	d?ddZHd@ddZIdAddZJdBddZKdWS (C  LowLevelIRBuildercurrent_modulestrmapperrb   optionsre   returnNonec                 C  s0   || _ || _|| _g | _g | _d g| _g | _d S N)r   r   r   argsblockserror_handlerskeep_alives)selfr   r   r    r   o/var/www/html/riverr-enterprise-integrations-main/venv/lib/python3.10/site-packages/mypyc/irbuild/ll_builder.py__init__   s   
zLowLevelIRBuilder.__init__opr4   r<   c                 C  s*   | j d jr
J d| j d j| |S )z
Add an op.zCan't add to finished block)r   
terminatedopsappend)r   r   r   r   r   add   s   zLowLevelIRBuilder.addtargetr!   c                 C  s"   | j d js| t| dS dS )zAdd goto to a basic block.r   N)r   r   r   r*   )r   r   r   r   r   goto   s   zLowLevelIRBuilder.gotoblockc                 C  s2   | j r| j d jsJ | jd |_| j | dS )z>Add a basic block and make it the active one (target of adds).r   N)r   r   r   error_handlerr   r   r   r   r   r   activate_block   s   z LowLevelIRBuilder.activate_blockc                 C  s   |  | | | dS )z.Add goto a block and make it the active block.N)r   r   r   r   r   r   goto_and_activate   s   
z#LowLevelIRBuilder.goto_and_activatehandlerBasicBlock | Nonec                 C  s   | j | d S r   )r   r   )r   r   r   r   r   push_error_handler      z$LowLevelIRBuilder.push_error_handlerc                 C  s
   | j  S r   )r   popr   r   r   r   pop_error_handler   s   
z#LowLevelIRBuilder.pop_error_handlerr6   c                 C  s
   | j d S )zWReturn reference to the 'self' argument.

        This only works in a method.
        r   )r   r   r   r   r   r      s   
zLowLevelIRBuilder.selfc                 C  s,   | j r| t| j d d   g | _ d S d S r   )r   r   r-   r   r   r   r   flush_keep_alives   s   
z#LowLevelIRBuilder.flush_keep_alivessrcc                 C  sF   |j jr!t|trt|j r| t|jd? tdS | t	|S |S )Nr   rtype)
type
is_unboxed
isinstancer+   rX   r   r0   valuer]   r"   )r   r   r   r   r   box   s
   zLowLevelIRBuilder.boxF
can_borrowtarget_typerD   lineintr   boolc                C  s>   |j r| t|||S |r| j| | t||||dS )Nborrow)r   r   r:   r   r   r&   )r   r   r   r   r   r   r   r   unbox_or_cast   s
   zLowLevelIRBuilder.unbox_or_castforcec                C  s   |j jr|js| |S |j jr%|jr%t|j |s%| |}| |||S |j js,|js2t|j |s;| j||||dS |rKt|}| t|| |S |S )a  Generate a coercion/cast from one type to other (only if needed).

        For example, int -> object boxes the source int; int -> int emits nothing;
        object -> int unboxes the object. All conversions preserve object value.

        If force is true, always generate an op (even if it is just an assignment) so
        that the result will have exactly target_type as the type.

        Returns the register with the converted value (may be same as src).
        r   )	r   r   r   r   r   r   r6   r   r   )r   r   r   r   r   r   tmpr   r   r   coerce   s    

zLowLevelIRBuilder.coercec           
      C  s   |j j|jkr|jrt|j |s|jst|j |r|S t|}t t t }}}| t|||tj | 	| | 
|||}| t||| | | | 	| | t|}	| t||	| | | |S )z2Generate a coercion from a potentially null value.)r   r   r   r   r6   r!   r   r#   IS_ERRORr   r   r   r   r/   r   )
r   r   r   r   r   validinvalidoutcoercederrorr   r   r   coerce_nullable  s,   





z!LowLevelIRBuilder.coerce_nullabler   objattrresult_typer   c                C  sx   t |jtr%|jjjr%|jj|r%|r| j| | t	||||dS t |jt
r5| ||j|||S | |||S )z.Get a native or Python attribute of an object.r   )r   r   rB   class_iris_ext_classhas_attrr   r   r   r(   rE   union_get_attrpy_get_attr)r   r   r   r   r   r   r   r   r   get_attr+  s   
zLowLevelIRBuilder.get_attrr   rE   c                   s&   d fdd} |||S )z0Get an attribute of an object with a union type.r   r<   r   c                   s    |  S r   )r   r   r   r   r   r   r   r   get_item_attrA  r   z7LowLevelIRBuilder.union_get_attr.<locals>.get_item_attrNr   r<   r   r<   )decompose_union_helper)r   r   r   r   r   r   r   r   r   r   r   <  s   z LowLevelIRBuilder.union_get_attrc                 C  s   |  |}| t||g|S )zuGet a Python attribute (slow).

        Prefer get_attr() which generates optimized code for native classes.
        )load_strcall_crq   )r   r   r   r   keyr   r   r   r   F  s   
zLowLevelIRBuilder.py_get_attr	class_irslist[ClassIR]c                   sb   |s  S |d |dd D ] d fdd}dtfd	d
|qS )zHFast path for isinstance() that checks against a list of native classes.r   r   Nr   r<   c                     s     S r   )isinstance_nativer   )r   r   r   r   r   r   otherW     z2LowLevelIRBuilder.isinstance_helper.<locals>.otherorc                         S r   r   r   retr   r   <lambda>Z      z5LowLevelIRBuilder.isinstance_helper.<locals>.<lambda>r   r<   )falser   shortcircuit_helperrG   )r   r   r   r   r   r   )r   r   r   r   r   r   isinstance_helperP  s   z#LowLevelIRBuilder.isinstance_helperc                 C  s8   |  t|td|}|  tt|}|  t|g |S )Nob_type)r   r)   r>   r1   r]   r-   )r   r   r   ob_type_addressr   r   r   r   get_type_of_obj]  s   z!LowLevelIRBuilder.get_type_of_objtype_objc                 C  s"   |  ||}| t||tj|S r   )r   r   r'   EQ)r   r   r   r   typr   r   r   
type_is_opc  s   zLowLevelIRBuilder.type_is_opr   r   c                   s   t |}|du st|td krt|gS |s" S |d }||dd D ] d fdd}dt	fd	d
|q6S )zFast isinstance() check for a native class.

        If there are three or fewer concrete (non-trait) classes among the class
        and all its children, use even faster type comparison checks `type(obj)
        is typ`.
        Nr   r   r   r<   c                     s     S r   )r   get_native_typer   )cr   r   r   r   r   r   x     z2LowLevelIRBuilder.isinstance_native.<locals>.otherr   c                     r   r   r   r   r   r   r   r   {  r   z5LowLevelIRBuilder.isinstance_native.<locals>.<lambda>r   )
r   lenr   r   rz   r   r   r   r   rG   )r   r   r   r   concreter   r   r   )r   r   r   r   r   r   r   g  s   z#LowLevelIRBuilder.isinstance_nativer   +Sequence[tuple[Value, ArgKind, str | None]]has_star	has_star2!tuple[Value | None, Value | None]c                C  s`  d}d}g }g }g }	d}
|D ]`\}}}|t kr,|du r"| ||}| t||g| q|tkrF|du r;| ||	|}| jt||g|d q| }| oO|}|	 p[| o[|o[|}|rw|rj|du rj| ||}|rw|du rw| ||	|}|r|du r|
| q|r|du r|dusJ | |}|
| |	
| q|
}t }|r|r|
stt}| t||  | |rt n|}t }| t|||tj | | |r|r|
rt t }}| t|
||tj n
t  }}| | |r| | |sJ | j|d|gd|d | | |rC|r|
rC| | |dus(J | |}|s2J | j|d||gd|d | | |rh|rh|rh||usSJ | | | t||  | | | | | |}
q|sv|r{|s{J |s|	r|sJ |r|du r| ||}n| t|g|}|r|du r| ||	|}||fS )a  Construct *args and **kwargs from a collection of arguments

        This is pretty complicated, and almost all of the complication here stems from
        one of two things (but mostly the second):
          * The handling of ARG_STAR/ARG_STAR2. We want to create as much of the args/kwargs
            values in one go as we can, so we collect values until our hand is forced, and
            then we emit creation of the list/tuple, and expand it from there if needed.

          * Support potentially nullable argument values. This has very narrow applicability,
            as this will never be done by our compiled Python code, but is critically used
            by gen_glue_method when generating glue methods to mediate between the function
            signature of a parent class and its subclasses.

            For named-only arguments, this is quite simple: if it is
            null, don't put it in the dict.

            For positional-or-named arguments, things are much more complicated.
              * First, anything that was passed as a positional arg
                must be forwarded along as a positional arg. It *must
                not* be converted to a named arg. This is because mypy
                does not enforce that positional-or-named arguments
                have the same name in subclasses, and it is not
                uncommon for code to have different names in
                subclasses (a bunch of mypy's visitors do this, for
                example!). This is arguably a bug in both mypy and code doing
                this, and they ought to be using positional-only arguments, but
                positional-only arguments are new and ugly.

              * On the flip side, we're willing to accept the
                infelicity of sometimes turning an argument that was
                passed by keyword into a positional argument. It's wrong,
                but it's very marginal, and avoiding it would require passing
                a bitmask of which arguments were named with every function call,
                or something similar.
                (See some discussion of this in testComplicatedArgs)

            Thus, our strategy for positional-or-named arguments is to
            always pass them as positional, except in the one
            situation where we can not, and where we can be absolutely
            sure they were passed by name: when an *earlier*
            positional argument was missing its value.

            This means that if we have a method `f(self, x: int=..., y: object=...)`:
              * x and y present:      args=(x, y), kwargs={}
              * x present, y missing: args=(x,),   kwargs={}
              * x missing, y present: args=(),     kwargs={'y': y}

            To implement this, when we have multiple optional
            positional arguments, we maintain a flag in a register
            that tracks whether an argument has been missing, and for
            each such optional argument (except the first), we check
            the flag to determine whether to append the argument to
            the *args list or add it to the **kwargs dict. What a
            mess!

            This is what really makes everything here such a tangle;
            otherwise the *args and **kwargs code could be separated.

        The arguments has_star and has_star2 indicate whether the target function
        takes an ARG_STAR and ARG_STAR2 argument, respectively.
        (These will always be true when making a pycall, and be based
        on the actual target signature for a native call.)
        Nr   r   r   r   __setitem__)r
   rx   r   rw   r   _create_dictrj   is_optionalis_positionalis_namedr   r   r!   r6   rG   r   r   r   r#   r   r   BOOLr   translate_special_method_calltrue	new_tupler   )r   r   r   r   r   star_resultstar2_resultstar_values
star2_keysstar2_valuesseen_empty_regr   kindnamenullable	maybe_posmaybe_namedr   new_seen_empty_regr   skipkeep	pos_blocknamed_blockr   r   r   _construct_varargs  s   H

















z$LowLevelIRBuilder._construct_varargsNfunction
arg_valueslist[Value]	arg_kindslist[ArgKind] | None	arg_namesSequence[str | None] | Nonec           	      C  s   t | jjr| |||||}|dur|S |du s"tdd |D r,| t|g| |S |dus2J | jtt	||||ddd\}}|rG|sIJ | t
|||g|S )zCall a Python function (non-native and slow).

        Use py_call_op or py_call_with_kwargs_op for Python function call.
        Nc                 s      | ]}|t kV  qd S r   r	   .0r  r   r   r   	<genexpr>R      z,LowLevelIRBuilder.py_call.<locals>.<genexpr>Tr   r   )r   r   capi_version_py_vector_callallr   ro   r  listziprp   )	r   r  r  r   r  r   resultpos_args_tuplekw_args_dictr   r   r   py_call?  s   
zLowLevelIRBuilder.py_callValue | Nonec                   s   |du st dd |D r[|r3tttt|} fdd|D }t|| tt|}nt	dt}t
||}	|}
t||t	|	t|
g }|rYt| |S dS )zCall function using the vectorcall API if possible.

        Return the return value if successful. Return None if a non-vectorcall
        API should be used instead.
        Nc                 s  $    | ]}|   o|  V  qd S r   is_starr  r$  r   r   r   r&  m      
z4LowLevelIRBuilder._py_vector_call.<locals>.<genexpr>c                      g | ]	} |t qS r   r   r]   r%  argr   r   r   r   
<listcomp>s      z5LowLevelIRBuilder._py_vector_call.<locals>.<listcomp>r   )r+  r6   rA   r]   r   r   r    r.   r\   r+   num_positional_args_vectorcall_keywordsr   rt   rK   r-   )r   r  r  r   r  r   arraycoerced_argsarg_ptrnum_poskeywordsr   r   r;  r   r*  _  s(   


z!LowLevelIRBuilder._py_vector_callc                 C  s4   |rdd |D }|r|  tt|tS tdtS )zReturn a reference to a tuple literal with keyword argument names.

        Return null pointer if there are no keyword arguments.
        c                 S  s   g | ]}|d ur|qS r   r   )r%  r  r   r   r   r<    s    z:LowLevelIRBuilder._vectorcall_keywords.<locals>.<listcomp>r   )r   r0   tupler]   r+   )r   r   kw_listr   r   r   r?    s
   
z&LowLevelIRBuilder._vectorcall_keywordsmethod_namec           
      C  s   t | jjr| ||||||}|dur|S |du s#tdd |D r3| |}| t||g| |S | |||}	| j	|	||||dS )z+Call a Python method (non-native and slow).Nc                 s  r"  r   r#  r$  r   r   r   r&    r'  z3LowLevelIRBuilder.py_method_call.<locals>.<genexpr>r  r   )
r   r   r)  _py_vector_method_callr+  r   r   rr   r   r1  )
r   r   rG  r  r   r  r   r.  method_name_regmethodr   r   r   py_method_call  s   

z LowLevelIRBuilder.py_method_callc                   s   |du st dd |D rf|}tttt|d }|t }	|	g fdd|D  }
t||
 t	t
|}t||}|}t||t|d tB t|g }t|
 |S dS )zCall method using the vectorcall API if possible.

        Return the return value if successful. Return None if a non-vectorcall
        API should be used instead.
        Nc                 s  r3  r   r4  r$  r   r   r   r&    r6  z;LowLevelIRBuilder._py_vector_method_call.<locals>.<genexpr>r   c                   r7  r   r8  r9  r;  r   r   r<    s    z<LowLevelIRBuilder._py_vector_method_call.<locals>.<listcomp>)r+  r   r6   rA   r]   r   r   r   r    r.   r\   r>  r?  r   rs   r+   r   rK   r-   )r   r   rG  r  r   r  r   rJ  r@  self_argrA  rB  rC  rD  r   r   r;  r   rI    s2   


z(LowLevelIRBuilder._py_vector_method_calldeclr   Sequence[Value]list[ArgKind]Sequence[str | None]c                 C  s&   |  ||||j|}| t|||S )zCall a native function.)native_args_to_positionalsigr   r$   )r   rN  r   r  r   r   r   r   r   call  s   
zLowLevelIRBuilder.callrS  r   c                   sl  dd |j D }dd |j D }dd  D }t|||dd }	d }
}g }t|	|j D ]%\}}|j rD| fdd|D  |
pJ|jtk}
|pQ|jtk}q-| j|||
|d	\}}g }t|	|j D ]M\}}|jtkrv|ssJ |}n8|jtkr|sJ |}n,|s| 	t
|jd
d}n|d  } |d   r| ||j|}n| ||j|}|| qf|S )a  Prepare arguments for a native call.

        Given args/kinds/names and a target signature for a native call, map
        keyword arguments to their appropriate place in the argument list,
        fill in error values for unspecified default arguments,
        package arguments that will go into *args/**kwargs into a tuple/dict,
        and coerce arguments to the appropriate type.
        c                 S     g | ]}|j qS r   )r  r9  r   r   r   r<        z?LowLevelIRBuilder.native_args_to_positional.<locals>.<listcomp>c                 S  rU  r   )r  r9  r   r   r   r<    rV  c                 S  s   g | ]}t |qS r   rc   )r%  arg_kindr   r   r   r<        c                 S  s
   t tjS r   )r   r   special_form)nr   r   r   r     s   
 z=LowLevelIRBuilder.native_args_to_positional.<locals>.<lambda>Fc                   s"   g | ]}|  | | fqS r   r   r%  ir  r   r   r   r   r<    s   " r(  T)is_borrowedr   )r   r   r-  r  r5  extendr
   r   r  r   r/   r   r  r   r   r   )r   r   r  r   rS  r   sig_arg_kindssig_arg_namesconcrete_kindsformal_to_actualr   r   star_arg_entrieslstr:  star_arg	star2_argoutput_args
output_argbase_argr   r]  r   rR    sH   	



z+LowLevelIRBuilder.native_args_to_positionalbaser  RType | Nonelist[str | None] | Nonec	              
   C  s  |durt dd |D r| ||||j||S t|jtr|jjjr|jjjs|jj	|rr|jj
|}	|du rQ|du sBJ ddd |D }dd |D }n|dusYJ d|	js^J | ||||	j|}| t||||S |jj|r| t|||}
| j|
||||d	S nt|jtr| ||j||||||S |r|tgt| kr| j||||||d
}|r|S | ||||||S )z/Generate either a native or Python method call.Nc                 s  s    | ]}|  V  qd S r   )r5  r$  r   r   r   r&  5  r'  z4LowLevelIRBuilder.gen_method_call.<locals>.<genexpr>z&arg_kinds not present but arg_names isc                 S  s   g | ]}t qS r   r#  r%  _r   r   r   r<  B      z5LowLevelIRBuilder.gen_method_call.<locals>.<listcomp>c                 S  s   g | ]}d qS r   r   rn  r   r   r   r<  C  rp  z&arg_kinds present but arg_names is notrH  r   )anyrL  r   r   r   rB   r   r   builtin_base
has_methodmethod_decl	bound_sigrR  r   r3   r   r(   r1  rE   union_method_callr	   r   r  )r   rk  r  r  r   r   r  r   r   rN  r  r   r   r   r   gen_method_call(  sJ   


z!LowLevelIRBuilder.gen_method_callobj_typereturn_rtypec	           
        s4   pt d fdd}	|||	S )z8Generate a method call with a union type for the object.r   r<   r   c              	     s    |  S r   )rw  r   r  r   r  r   r  ry  r   r   r   call_union_items  s   z<LowLevelIRBuilder.union_method_call.<locals>.call_union_itemNr   )r]   r   )
r   rk  rx  r  r  ry  r   r  r   r{  r   rz  r   rv  c  s   z#LowLevelIRBuilder.union_method_callc                 C  
   t dtS )z0Load unboxed None value (type: none_rprimitive).r   )r+   r[   r   r   r   r   none|     
zLowLevelIRBuilder.nonec                 C  r|  )z0Load unboxed True value (type: bool_rprimitive).r   r+   rG   r   r   r   r   r    r~  zLowLevelIRBuilder.truec                 C  r|  )z1Load unboxed False value (type: bool_rprimitive).r   r  r   r   r   r   r     r~  zLowLevelIRBuilder.falsec                 C  s   |  ttjtjddS )z1Load Python None value (type: object_rprimitive).r   r   )r   r.   r{   r   r   r   r   r   r   none_object  s   zLowLevelIRBuilder.none_objectr   c                 C  s(   |t ks|tk r| t|tS t|S )z-Load a tagged (Python) integer literal value.)r   r   r   r0   rN   r+   r   r   r   r   r   load_int  s   zLowLevelIRBuilder.load_intfloatc                 C     |  t|tS )zLoad a float literal value.)r   r0   rM   r  r   r   r   
load_float     zLowLevelIRBuilder.load_floatc                 C  r  )zLoad a str literal value.

        This is useful for more than just str literals; for example, method calls
        also require a PyObject * form for the name of the method.
        )r   r0   ra   r  r   r   r   r     s   zLowLevelIRBuilder.load_strbytesc                 C  r  )zLoad a bytes literal value.)r   r0   rH   r  r   r   r   
load_bytes  r  zLowLevelIRBuilder.load_bytescomplexc                 C  r  )zLoad a complex literal value.)r   r0   r]   r  r   r   r   load_complex  r  zLowLevelIRBuilder.load_complexr   r   
identifiermodule_name
str | None	namespace	error_msgc           
   	   C  s   |d u r
d| d}t  t  }}| t|||||d}	| t|	||tjdd | | | ttj|| | t  | | |	S )Nzname "z" is not definedr   T)rare)	r!   r   r2   r#   r   r   r5   
NAME_ERRORr;   )
r   r   r  r  r  r   r  ok_blockerror_blockr   r   r   r   load_static_checked  s   	

z%LowLevelIRBuilder.load_static_checkedc                 C  s   |  tt|tdS )N)r  )r   r2   r]   r   )r   r  r   r   r   load_module  r   zLowLevelIRBuilder.load_moduleclsc                 C  s   |j  d|j }| |S )zLoad native type object..)r  r  load_native_type_object)r   r  fullnamer   r   r   r     s   
z!LowLevelIRBuilder.get_native_typer  c                 C  s$   | dd\}}| tt||tS )Nr  r   )rsplitr   r2   r]   r   )r   r  moduler  r   r   r   r    s   z)LowLevelIRBuilder.load_native_type_objectlregrregc           
      C  sl  |j }|j }t|trt|tr|dv r| ||||S |dv r.| ||||}|d ur.|S |dv r:| ||||S t|rNt|rN|dv rN| ||||S t|rbt|rb|dv rb| 	||||S t
|rvt
|rv|tv rv| ||||S t|rt|r|dv r| |||d |S t|tr|dv r| ||||S t|g }| |||g|}	|	sJ d| |	S )N==!=)isis not)&z&=|z|=^z^=r   )innot inz Unsupported binary operation: %s)r   r   rC   compare_tuplestranslate_eq_cmptranslate_is_oprW   compare_stringsrQ   compare_bytesrX   ru   compare_taggedrP   bool_bitwise_oprB   translate_instance_containsr~   getmatching_call_c)
r   r  r  r   r   ltyper   r   call_c_ops_candidatesr   r   r   r   	binary_op  s8   zLowLevelIRBuilder.binary_opvalnegatedc           	      C  sP   t dt|}| t||tj|}t dt|}|rtjntj}| ||||}|S )zuCheck if a tagged integer is a short integer.

        Return the result of the check (value of type 'bit').
        r   r   )	r+   rJ   int_opr,   ANDr'   NEQr   comparison_op)	r   r  r   r  int_tagbitwise_andzeror   checkr   r   r   check_tagged_short_int  s   z(LowLevelIRBuilder.check_tagged_short_intlhsrhsc                 C  sF  t |jrt |jr| ||t| d |S t| \}}}}tt}	t t t }
}}| ||}|dv r:|}n| ||}| t	||t
j|}| t||
|tj | |
 | ||||}| t|	|| | | | | |r|||g}n||g}| |||}|r| |d|}n|}| t|	|| | | |	S )zACompare two tagged integers using given operator (value context).r   r  not)rV   r   r  ru   r6   rG   r!   r  r  rF   r,   r  r   r#   r  r   r   r   r   unary_opr   )r   r  r  r   r   op_typec_func_descnegate_resultswap_opr.  short_int_block	int_blockr   	check_lhsr  	check_rhseqr   rT  call_resultr   r   r   r    s4   




z LowLevelIRBuilder.compare_taggedr  r   c                 C  s  |dv }t |jrt |js|r7t |jst |jr7| ||t| d |}|   | t|||tj dS t| \}	}
}}t t }}| j	||dd}|sUt |jre|   | t|||tj n*t }| t|||tj | 
| | j	||dd}|   | t|||tj | 
| |r||g}n||g}| |
||}|r| t|||tj n|   | t|||tj | 
| | |||	|}| t|||tj dS )a  Compare two tagged integers using given operator (conditional context).

        Assume lhs and and rhs are tagged integers.

        Args:
            lhs: Left operand
            rhs: Right operand
            op: Operation, one of '==', '!=', '<', '<=', '>', '<='
            true: Branch target if comparison is true
            false: Branch target if comparison is false
        r  r   NT)r  )rV   r   r  ru   r   r   r#   r  r!   r  r   r   )r   r  r  r   r  r   r   is_eqr  r  r  r  r  r  r  r  	rhs_blockr  r   rT  r  r   r   r   compare_tagged_condition  sH   



z*LowLevelIRBuilder.compare_tagged_conditionc                 C  s  |  t||g|}tdt|}| t||tj|}t t t }}	}
t|||
tj	}d|_
| | | | |  tg |}tdt|}| t||tj|}t||	|
tj	}d|_
| | | |	 |  tg | | |
 | |
 |dkrtjntj}| t|tdt||S )zCompare two stringsr   Fr   r  )r   r   r+   rI   r   r'   r   r!   r#   r  r  r   rk   r_   r  rl   r   )r   r  r  r   r   compare_resulterror_constantcompare_error_checkexception_check	propagatefinal_comparebranchcheck_error_resultnullr  r   r   r   r  T  s0   





z!LowLevelIRBuilder.compare_stringsc                 C  s@   |  t||g|}|dkrtjntj}| t|tdt||S )Nr  r   )r   rf   r'   r   r  r   r+   rI   )r   r  r  r   r   r  r  r   r   r   r  o  s   zLowLevelIRBuilder.compare_bytesc                   s  t  jtrt jtsJ |dkrdnd}tt}t jjdkr=tjjdkr=t||r4	 n
  |S t jj}t t t }}	}
dd t|D } fddt|D }fddt|D }|ry||	}}n|	|}}tt jjD ]Q}|dkr||  || }|| }|||}t|jst|g}|t jjd	 k rt||||d	  tj}nt|||tj}||_| q| t|
  |
 |	 t|	  |
 |S )
zCompare two tuples item by itemr  TFr   c                 S  s   g | ]}t  qS r   )r!   rn  r   r   r   r<    rV  z4LowLevelIRBuilder.compare_tuples.<locals>.<listcomp>c                   s   g | ]} t |qS r   r   r9   r[  )r  r   r   r   r   r<        c                   s   g | ]} t| qS r   r  r[  )r   r  r   r   r   r<    r  r   )r   r   rC   r6   rG   r   typesr   r   r  r   r!   ranger   r  rP   r   ry   r#   r  r  r   r   )r   r  r  r   r   equalr.  lengthfalse_assigntrue_assignr   check_blocks	lhs_items	rhs_items
early_stopfinalr\  lhs_itemrhs_itemcomparer  r   )r  r   r  r   r   r  t  sD    "





z LowLevelIRBuilder.compare_tuplesinstitemc                 C  sR   |  |d|gd |}t|js| t|g|}|dkr'| |tdtdd|}|S )N__contains__r  r   r   r  )rw  rP   r   r   ry   r  r+   rG   )r   r  r  r   r   resr   r   r   r    s   
z-LowLevelIRBuilder.translate_instance_containsc                 C  sN   |dkrt j}n|dkrt j}n|dkrt j}nJ || t t||||S )Nr  r  r  )r,   r  ORXORr   rG   )r   r  r  r   r   coder   r   r   r    s   z!LowLevelIRBuilder.bool_bitwise_opc                 C  s$   t d|j|}| |j||tj|S )Nr   )r+   r   r  r,   r  )r   r   r   maskr   r   r   	unary_not  s   zLowLevelIRBuilder.unary_notexpr_opc                 C  s   |j }t|st|r|dkr| ||S t|tr;|dkr!d}n	|dkr(d}nd}|r;|j|r;| ||g d |S t	
|g }| ||g|}|sQJ d| |S )Nr  -__neg__~
__invert__ zUnsupported unary operation: %s)r   rP   rO   r  r   rB   r   rs  rw  r   r  r  )r   r   r  r   r   rK  r  r   r   r   r   r    s   
zLowLevelIRBuilder.unary_opkey_value_pairsSequence[DictEntry]c                 C  s   d }g }g }|D ]9\}}|d ur,|d u r| | | | q| j|d||gd |d q|d u r7| |||}| jt||g|d q|d u rM| |||}|S )Nr  r   r   )r   r  r  r   rj   )r   r  r   r.  keysvaluesr   r   r   r   r   	make_dict  s$   

zLowLevelIRBuilder.make_dictr  c                 C     |  t|g|S )a  This function returns an uninitialized list.

        If the length is non-zero, the caller must initialize the list, before
        it can be made visible to user code -- otherwise the list object is broken.
        You might need further initialization with `new_list_set_item_op` op.

        Args:
            length: desired length of the new list. The rtype should be
                    c_pyssize_t_rprimitive
            line: line number
        )r   rx   r   r  r   r   r   r   new_list_op_with_length     z)LowLevelIRBuilder.new_list_op_with_lengthr  c              	     s   t t|t g}t|tkrt||  S t| }t|dkr'|S  fdd|D }t|t	d }t
t| }tt|D ])}|dkrS|}	nt t| t }
tt||
tj }	tt|	||   qJt|g |S )Nr   c                   r7  r   r8  )r%  r  r;  r   r   r<     r=  z1LowLevelIRBuilder.new_list_op.<locals>.<listcomp>ob_item)r+   r   rJ   !LIST_BUILDING_EXPANSION_THRESHOLDr   rv   rx   r   r)   r=   r1   r_   r  r   r,   ADDr7   r]   r-   )r   r  r   r  result_listr   ob_item_ptrob_item_baser\  item_addressoffsetr   r;  r   rx     s&   zLowLevelIRBuilder.new_list_opc                 C  s   |  t||S r   )r   r   )r   r  r   r   r   r   r     r   zLowLevelIRBuilder.new_set_op	expr_typeleftCallable[[], Value]rightc                 C  s   t |}t t t }}}	|dkr||fn||f\}
}| }| ||
| | | | |||}| t|| | |	 | | | }| |||}| t|| | |	 | |	 |S )Nand)r6   r!   add_bool_branchr   r   r   r   r   )r   r   r
  r  r  r   r   	left_body
right_body
next_block	true_body
false_body
left_valueleft_coercedright_valueright_coercedr   r   r   r     s    	




z%LowLevelIRBuilder.shortcircuit_helperc                 C  s  t |jtrtdt}| ||d|||j d S t|jtr(| 	t
|g|j}nt|jts4t|jtrI| ||j}td}| ||d|j}nt|jtrf|jjjrf|jjdrf| |dg t|j}nft|j}|d ur| ||  d|j}t|||tj}| | d}	t|tr|jds|jdrd}	|	st |_| |j |  |||j}
| !|
|| d S t"|jst#|js| 	t$|g|j}| t|||tj d S )Nr   r  __bool__r  FT)%r   r   rN   r+   r`   r  r   r   ra   r   r   rZ   rL   builtin_lenr  r   rB   r   r   rs  rw  rG   r^   r  r  r#   r  r   is_method_finalr!   r  r   r   r  rP   rO   ry   )r   r   r  r   r  r  
value_typeis_noner  always_truthy	remainingr   r   r   r  4  sR   





z!LowLevelIRBuilder.add_bool_branchdescr}   c                   s  g  t tt|t|jD ]}|j| }|| }| |||} | q|jdur<|jdu s2J  fdd|jD  d}|jdurft|j}t t|jt|D ]}|| }| ||j|} | qR|jD ]}	|	\}
}t	|
||} | qi|j
}|tkrt}| t|j |j|j|j|||}|jr D ]}t|t	tfs| j| q|j
tkrt|t	d|j|tj|}t|_
| | |jdu r|}n| t||j}|}|rt|j|st|r|  }|S | j||||jd}|S )zHCall function using C/native calling convention (not a Python callable).Nc                   s   g | ]} | qS r   r   r[  r   r   r   r<  v  rX  z,LowLevelIRBuilder.call_c.<locals>.<listcomp>r   r   r   )r  minr   	arg_typesr   r   orderingvar_arg_typeextra_int_constantsr+   
error_kindr|   r   r   r%   c_function_namereturn_typestealsr^  r   r0   r   r'   SGEr   truncated_typer8   r   r   rT   r}  )r   r   r   r   r   r\  formal_typer:  var_arg_idxr  r  r   extra_int_constantr'  r   compr.  truncater   r!  r   r   c  sl   	







zLowLevelIRBuilder.call_c
candidateslist[CFunctionDescription]c           	      C  s   d }|D ]9}t |jt |krqtdd t||jD r=|jr"|r=|r;|j|jks2J d|||j|jkr:|}q|}q|rJ| ||||}|S d S )Nc                 s  s     | ]\}}t |j|V  qd S r   )r   r   )r%  actualformalr   r   r   r&    s    
z4LowLevelIRBuilder.matching_call_c.<locals>.<genexpr>zAmbiguous:
1) {}
2) {})r   r#  r+  r-  r^  priorityformatr   )	r   r2  r   r   r   r   matchingr   r   r   r   r   r    s0   
z!LowLevelIRBuilder.matching_call_cr   c                 C  s   |  t|||||S r   )r   r,   )r   r   r  r  r   r   r   r   r   r    s   zLowLevelIRBuilder.int_opc                 C  s   |  t||||S r   )r   r'   )r   r  r  r   r   r   r   r   r    r   zLowLevelIRBuilder.comparison_opuse_pyssize_tc                 C  s  |j }d}t|st|st|r+| t|td}| tt|}| t	|g n7t
|rI| t|td}| tt|}| t	|g nt|rV| t|g|}nt|rb| t|g|}|durz|rj|S tdt|}| t||tj|S t|tr|rJ | |dg t|}| |t|}t t }	}
| |tdd|	|
| | |
 | ttjd| | t   | |	 |S |r| t!|g|S | t"|g|S )	zGenerate len(val).

        Return short_int_rprimitive by default.
        Return c_pyssize_t if use_pyssize_t is true (unshifted).
        Nob_sizeusedr   __len__r   z>=z__len__() should return >= 0)#r   rS   rY   rQ   r   r)   r@   r1   rJ   r-   rU   r?   rR   r   ri   rW   r   r+   r  r`   r,   
LEFT_SHIFTr   rB   rw  rN   r   r!   r  r   r5   VALUE_ERRORr;   rn   rm   )r   r  r   r9  r   
size_valueelem_addressr	  r  okfailr   r   r   r    sJ   


zLowLevelIRBuilder.builtin_lenitemsc                 C  s"   t t|t}| t|g| |S r   )r+   r   rJ   r   r   )r   rC  r   sizer   r   r   r	    s   zLowLevelIRBuilder.new_tuplec                 C  r  )a  This function returns an uninitialized tuple.

        If the length is non-zero, the caller must initialize the tuple, before
        it can be made visible to user code -- otherwise the tuple object is broken.
        You might need further initialization with `new_tuple_set_item_op` op.

        Args:
            length: desired length of the new tuple. The rtype should be
                    c_pyssize_t_rprimitive
            line: line number
        )r   r   r  r   r   r   new_tuple_with_length  r  z'LowLevelIRBuilder.new_tuple_with_lengthprocess_itemCallable[[Value], Value]c                 C  sB  g }g }|j D ]}t|tr|| q|| qt }	t|}
t|D ]Q\}}|t|d k p2|}|rP| ||j	|}t t }}| 
||| | | | |||}||}| |||}| t|
| | |	 |rv| | q%|r| j|t|dd}||}| |||}| t|
| | |	 | |	 |
S )al  Generate isinstance() + specialized operations for union items.

        Say, for Union[A, B] generate ops resembling this (pseudocode):

            if isinstance(obj, A):
                result = <result of process_item(cast(A, obj)>
            else:
                result = <result of process_item(cast(B, obj)>

        Args:
            obj: value with a union type
            rtype: the union type
            result_type: result of the operation
            process_item: callback to generate op for a single union item (arg is coerced
                to union item type)
            line: line number
        r   T)r   )rC  r   rB   r   r!   r6   	enumerater   r   r   r  r   r   r   r   r   r]   )r   r   r   r   rF  r   
fast_items
rest_itemsr  
exit_blockr.  r\  
more_typesr   
true_blockfalse_blockr   temptemp2r   r   r   r     s>   






z(LowLevelIRBuilder.decompose_union_helperbase_regc           	      C  s*   t |g }| j||g| |||d}|S )ar  Translate a method call which is handled nongenerically.

        These are special in the sense that we have code generated specifically for them.
        They tend to be method calls which have equivalents in C that are more direct
        than calling with the PyObject api.

        Return None if no translation found; otherwise return the target register.
        r   )r   r  r  )	r   rQ  r  r   r   r   r   r  	call_c_opr   r   r   r  U  s
   z/LowLevelIRBuilder.translate_special_method_callc           
      C  s   |j }|j }t|tr||ksdS |j}|d p%|d p%|jp%|j}|r*dS |ds?|dkr5dnd}	| |||	|S | 	|t
| |g||S )zeAdd a equality comparison operation.

        Args:
            expr_op: either '==' or '!='
        N__eq____ne__r  r  r  )r   r   rB   r   r  inherits_pythonis_augmentedrs  r  rw  r   )
r   r  r  r  r   r  r   r   cmp_varies_at_runtimeidentity_ref_opr   r   r   r  l  s$   

z"LowLevelIRBuilder.translate_eq_cmpc                 C  sD   |dkrt jnt j}| |t|}| |t|}| t ||||S )zCreate equality comparison operation between object identities

        Args:
            expr_op: either 'is' or 'is not'
        r  )r'   r   r  r   r]   r   )r   r  r  r  r   r   r  r  r   r   r   r    s   z!LowLevelIRBuilder.translate_is_opr  c                 C  sT   t |}|dkr#t|t}dd tt||D }| t|g| |S | tg |S )z9Create a dictionary(possibly empty) using keys and valuesr   c                 S  s   g | ]	}|D ]}|qqS r   r   )r%  tr\  r   r   r   r<    r=  z2LowLevelIRBuilder._create_dict.<locals>.<listcomp>)r   r+   rJ   r,  r-  r   rg   rh   )r   r  r  r   rD  r?  rC  r   r   r   r    s   
zLowLevelIRBuilder._create_dict)r   r   r   rb   r   re   r   r   )r   r4   r   r<   )r   r!   r   r   )r   r!   r   r   )r   r   r   r   )r   r   )r   r6   )r   r   )r   r<   r   r<   )
r   r<   r   rD   r   r   r   r   r   r<   )F)r   r<   r   rD   r   r   r   r   r   r   r   r<   )r   r<   r   rD   r   r   r   r<   )r   r<   r   r   r   rD   r   r   r   r   r   r<   )r   r<   r   rE   r   r   r   rD   r   r   r   r<   )r   r<   r   r   r   r   r   r<   )r   r<   r   r   r   r   r   r<   )r   r<   r   r   r   r<   )r   r<   r   r<   r   r   r   r<   )r   r<   r   r   r   r   r   r<   )
r   r   r   r   r   r   r   r   r   r   )NN)r  r<   r  r  r   r   r  r  r   r!  r   r<   )r  r<   r  r  r   r   r  r  r   r!  r   r2  )r   r!  r   r<   )r   r<   rG  r   r  r  r   r   r  r  r   r!  r   r<   )r   r<   rG  r   r  r  r   r   r  r  r   r!  r   r2  )rN  r   r   rO  r  rP  r   rQ  r   r   r   r<   )r   rO  r  rP  r   rQ  rS  r   r   r   r   r  )NNF)rk  r<   r  r   r  r  r   rl  r   r   r  r  r   rm  r   r   r   r<   )rk  r<   rx  rE   r  r   r  r  ry  rl  r   r   r  r  r   rm  r   r<   r   )r   r   r   r<   )r   r  r   r<   )r   r   r   r<   )r   r  r   r<   )r   r  r   r<   )r   rD   r  r   r  r  r  r   r   r   r  r  r   r<   )r  r   r   r<   )r  r   r   r<   )r  r   r   r<   )
r  r<   r  r<   r   r   r   r   r   r<   )r  r<   r   r   r  r   r   r<   )
r  r<   r  r<   r   r   r   r   r   r<   )r  r<   r  r<   r   r   r  r!   r   r!   r   r   r   r   )r   )
r  r<   r  r<   r   r   r   r   r   r<   )r   r<   r   r   r   r<   )r   r<   r  r   r   r   r   r<   )r  r  r   r   r   r<   )r  r<   r   r   r   r<   )r  r  r   r   r   r<   )r   r   r
  rD   r  r  r  r  r   r   r   r<   )r   r<   r  r!   r   r!   r   r   r   )
r   r}   r   r  r   r   r   rl  r   r<   )NF)r2  r3  r   r  r   r   r   rl  r   r   r   r2  )r   rD   r  r<   r  r<   r   r   r   r   r   r<   )
r  r<   r  r<   r   r   r   r   r   r<   )r  r<   r   r   r9  r   r   r<   )rC  r  r   r   r   r<   )r   r<   r   rE   r   rD   rF  rG  r   r   r   r<   )rQ  r<   r  r   r   r  r   rl  r   r   r   r   r   r2  )
r  r<   r  r<   r  r   r   r   r   r2  )
r  r<   r  r<   r  r   r   r   r   r<   )r  r  r  r  r   r   r   r<   )L__name__
__module____qualname__r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r1  r*  r?  rL  rI  rT  rR  rw  rv  r}  r  r   r  r  r  r   r  r  r   r  r  r   r  r  r  r  r  r  r  r  r  r  r  r  r  r   rx   r   r   r  r   r  r  r  r  r	  rE  r   r  r  r  r  r   r   r   r   r      s    
	&

 E%(,I;'#6."4P2F"r   r  r  r  r  r   r   c                 C  s2   |d u rt | S d}|D ]
}|tkr|d7 }q|S )Nr   r   )r   r	   )r  r  rC  r  r   r   r   r>    s   r>  N)r  r  r  r  r   r   )__doc__
__future__r   typingr   r   r   r   typing_extensionsr   mypy.argmapr   
mypy.nodesr	   r
   r   r   mypy.operatorsr   
mypy.typesr   r   mypyc.commonr   r   r   r   r   r   mypyc.ir.class_irr   r   mypyc.ir.func_irr   r   mypyc.ir.opsr   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r<   mypyc.ir.rtypesr=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   rM   rN   rO   rP   rQ   rR   rS   rT   rU   rV   rW   rX   rY   rZ   r[   r\   r]   r^   r_   r`   ra   mypyc.irbuild.mapperrb   mypyc.irbuild.utilrd   mypyc.optionsre   mypyc.primitives.bytes_opsrf   mypyc.primitives.dict_opsrg   rh   ri   rj   mypyc.primitives.exc_opsrk   rl   mypyc.primitives.generic_opsrm   rn   ro   rp   rq   rr   rs   rt   mypyc.primitives.int_opsru   mypyc.primitives.list_opsrv   rw   rx   mypyc.primitives.misc_opsry   rz   r{   mypyc.primitives.registryr|   r}   r~   r   r   mypyc.primitives.set_opsr   mypyc.primitives.str_opsr   r   r   mypyc.primitives.tuple_opsr   r   r   mypyc.rt_subtyper   mypyc.sametyper   mypyc.subtyper   	DictEntryr  r   __annotations__r   r>  r   r   r   r   <module>   s^    
 %'(
            