U
    k]eZP                     @   s  d Z ddlZddlZddlZddlZddlT ddlmZ ddddd	d
dddddge Z[ejej	ej
eeefZed ZdedfedfedffZed ZdZdd ZdVdddddZdWddddZdddd d!d"d#d$d%d&d'
Zd(d) Zd*d+ Zd,d Zd-d. Zddd/dZe d0d1Z!d2e!j"_ d3e!j_ d4e!j#_ d5e!j$_ d6e!j%_ d7e!j&_ d8e!j'_ d9e!j(_ d:Z)d;Z*G d<d de!Z+dd=d>dZ,d?d@ Z-dAdB Z.dXdCdDZ/dYdddFdZ0ddddGdHZ1dZdddIdJdKZ2dLdM Z3e0Z4dNdO Z5dPd Z6dQd
 Z7G dRd dZ8dSdT Z9e:dUkre9  dS )[z0Disassembler of Python byte code into mnemonics.    N)*)__all__	code_infodisdisassembledistbdiscofindlinestarts
findlabels	show_codeget_instructionsInstructionBytecodeFORMAT_VALUE)N strreprasciiMAKE_FUNCTION)defaultsZ
kwdefaultsZannotationsZclosurec                 C   s6   zt | |d}W n  tk
r0   t | |d}Y nX |S )zAttempts to compile the given source, first as an expression and
       then as a statement if the first approach fails.

       Utility function to accept strings in functions that otherwise
       expect code objects
    evalexec)compileSyntaxError)sourcenamec r   /usr/lib/python3.8/dis.py_try_compile   s
    r   filedepthc                C   sh  | dkrt |d dS t| dr&| j} t| dr8| j} n4t| drJ| j} n"t| dr\| j} nt| drl| j} t| drt| j	 }|D ]p\}}t
|trtd	| |d zt|||d
 W n0 tk
r } ztd||d W 5 d}~X Y nX t|d qnht| drt| ||d
 nLt
| ttfr6t| |d n.t
| trRt| ||d
 ntdt| j dS )a0  Disassemble classes, methods, functions, and other compiled objects.

    With no argument, disassemble the last traceback.

    Compiled objects currently include generator objects, async generator
    objects, and coroutine objects, all of which store their code object
    in a special attribute.
    Nr!   __func____code__gi_codeag_codecr_code__dict__zDisassembly of %s:r    zSorry:co_code(don't know how to disassemble %s objects)r   hasattrr$   r%   r&   r'   r(   sortedr)   items
isinstance
_have_codeprintr   	TypeError_disassemble_recursivebytes	bytearray_disassemble_bytesr   _disassemble_strtype__name__)xr!   r"   r.   r   Zx1msgr   r   r   r   +   s@    	







 r#   c                C   sX   | dkr@z
t j} W n tk
r0   tddY nX | jr@| j} q2t| jj| j|d dS )z2Disassemble a traceback (default: last traceback).Nz no last traceback to disassembler#   )	syslast_tracebackAttributeErrorRuntimeErrortb_nextr   tb_framef_codetb_lasti)tbr!   r   r   r   r   X   s    
 Z	OPTIMIZEDZ	NEWLOCALSZVARARGSZVARKEYWORDSZNESTEDZ	GENERATORZNOFREEZ	COROUTINEZITERABLE_COROUTINEZASYNC_GENERATOR)
                   @         i   c                 C   s`   g }t dD ]:}d|> }| |@ r|t|t| | |N } | s qVq|t|  d|S )z+Return pretty representation of code flags.rJ   rE   , )rangeappendCOMPILER_FLAG_NAMESgethexjoin)flagsnamesiflagr   r   r   pretty_flagsr   s    rY   c                 C   s   t | dr| j} t | dr"| j} n4t | dr4| j} n"t | drF| j} nt | drV| j} t| trjt| d} t | drx| S t	dt
| j d	S )
zDHelper to handle methods, compiled or raw code objects, and strings.r$   r%   r&   r'   r(   z<disassembly>r*   r+   N)r,   r$   r%   r&   r'   r(   r/   r   r   r2   r8   r9   r:   r   r   r   _get_code_object   s"    







r[   c                 C   s   t t| S )z1Formatted details of methods, functions, or code.)_format_code_infor[   rZ   r   r   r   r      s    c                 C   s  g }| d| j  | d| j  | d| j  | d| j  | d| j  | d| j  | d| j  | dt| j	  | j
r| d	 t| j
D ]}| d
|  q| jr| d t| jD ]}| d|  q| jr| d t| jD ]}| d|  q | jrH| d t| jD ]}| d|  q2| jrz| d t| jD ]}| d|  qdd|S )NzName:              %szFilename:          %szArgument count:    %szPositional-only arguments: %szKw-only arguments: %szNumber of locals:  %szStack size:        %szFlags:             %sz
Constants:z%4d: %rzNames:z%4d: %szVariable names:zFree variables:zCell variables:
)rP   co_nameco_filenameco_argcountco_posonlyargcountco_kwonlyargcount
co_nlocalsco_stacksizerY   co_flags	co_consts	enumerateco_namesco_varnamesco_freevarsco_cellvarsrT   )colinesZi_cZi_nr   r   r   r\      s<    




r\   c                C   s   t t| |d dS )z}Print details of methods, functions, or code to *file*.

    If *file* is not provided, the output is printed on stdout.
    r#   N)r1   r   )rl   r!   r   r   r   r      s    _InstructionzBopname opcode arg argval argrepr offset starts_line is_jump_targetz!Human readable name for operationzNumeric code for operationz6Numeric argument to operation (if any), otherwise Nonez4Resolved arg value (if known), otherwise same as argz0Human readable description of operation argumentz1Start index of operation within bytecode sequencez4Line started by this opcode (if any), otherwise Nonez1True if other code jumps to here, otherwise False      c                   @   s   e Zd ZdZdddZdS )	r   aK  Details for a bytecode operation

       Defined fields:
         opname - human readable name for operation
         opcode - numeric code for operation
         arg - numeric argument to operation (if any), otherwise None
         argval - resolved arg value (if known), otherwise same as arg
         argrepr - human readable description of operation argument
         offset - start index of operation within bytecode sequence
         starts_line - line started by this opcode (if any), otherwise None
         is_jump_target - True if other code jumps to here, otherwise False
       FrG   c                 C   s   g }|r:| j dk	r,d| }||| j   n|d|  |rJ|d n
|d | jrf|d n
|d |t| j| || jt | j	dk	r|t| j	t
 | jr|d| j d	  d| S )
a%  Format instruction details for inclusion in disassembly output

        *lineno_width* sets the width of the line number field (0 omits it)
        *mark_as_current* inserts a '-->' marker arrow as part of the line
        *offset_width* sets the width of the instruction offset field
        Nz%%%dd z-->z   z>>z  ())starts_linerP   is_jump_targetr   offsetrjustopnameljust_OPNAME_WIDTHarg_OPARG_WIDTHargreprrT   rstrip)selflineno_widthZmark_as_currentoffset_widthZfieldsZ
lineno_fmtr   r   r   _disassemble   s&    



zInstruction._disassembleN)rq   FrG   )r9   
__module____qualname____doc__r   r   r   r   r   r      s   )
first_linec                C   sT   t | }|j|j }tt|}|dk	r4||j }nd}t|j|j|j	|j
|||S )a  Iterator for the opcodes in methods, functions or code

    Generates a series of Instruction named tuples giving the details of
    each operations in the supplied code.

    If *first_line* is not None, it indicates the line number that should
    be reported for the first source line in the disassembled code.
    Otherwise, the source line information (if any) is taken directly from
    the disassembled code object.
    Nr   )r[   rk   rj   dictr	   co_firstlineno_get_instructions_bytesr*   ri   rh   rf   )r:   r   rl   
cell_names
linestartsline_offsetr   r   r   r     s      c                 C   s    | }|dk	r||  }|t |fS )zHelper to get optional details about const references

       Returns the dereferenced constant and its repr if the constant
       list is defined.
       Otherwise returns the constant index and its repr().
    Nr   )Zconst_indexZ
const_listargvalr   r   r   _get_const_info  s    r   c                 C   s*   | }|dk	r||  }|}nt |}||fS )zHelper to get optional details about named references

       Returns the dereferenced name as both value and repr if the name
       list is defined.
       Otherwise returns the name index and its repr().
    Nr   )Z
name_indexZ	name_listr   r~   r   r   r   _get_name_info'  s    r   c              
   #   s  t | }d}t| D ]r\}	}
 |dk	rD||	d}|dk	rD||7 }|	|k}d}d} dk	rl }|
tkrzt |\}}n|
tkrt |\}}n|
tkr|	d   }dt| }n|
t	krt |\}}n|
t
krt  }|}n|
tkrt |\}}nr|
tkrFt d@  \}}|t d@ f}|d rl|r<|d7 }|d	7 }n&|
tkrld fd
dttD }tt|
 |
 |||	||V  qdS )a&  Iterate over the instructions in a bytecode string.

    Generates a sequence of Instruction namedtuples giving the details of each
    opcode.  Additional information about the code's runtime environment
    (e.g. variable names, constants) can be specified using optional
    arguments.

    Nr   rF   zto rq   rG   rE   rN   zwith formatc                 3   s"   | ]\}} d |> @ r|V  qdS )rE   Nr   ).0rW   sr|   r   r   	<genexpr>g  s    z*_get_instructions_bytes.<locals>.<genexpr>)r
   _unpack_opargsrR   Zhasconstr   Zhasnamer   hasjrelr   ZhaslocalZ
hascompareZcmp_opZhasfreer   FORMAT_VALUE_CONVERTERSboolr   rT   rg   MAKE_FUNCTION_FLAGSr   ry   )codevarnamesrV   	constantscellsr   r   labelsru   rw   oprv   r   r~   r   r   r   r   7  sV    






    r   c             
   C   s<   | j | j }tt| }t| j|| j| j| j|||d dS )zDisassemble a code object.r#   N)	rk   rj   r   r	   r6   r*   ri   rh   rf   )rl   lastir!   r   r   r   r   r   r   m  s       c                C   sp   t | |d |d ks|dkrl|d k	r,|d }| jD ]8}t|dr2t|d td|f |d t|||d q2d S )Nr#   r   rE   r*   zDisassembly of %r:r    )r   rf   r,   r1   r3   )rl   r!   r"   r:   r   r   r   r3   t  s    


r3   )r!   r   c             	   C   s   |d k	}	|	r8t | | }
|
dkr2tt|
}q<d}nd}t| d }|dkr^tt|}nd}t| ||||||dD ]J}|	o|jd k	o|jdk}|rt|d |j|k}t|||||d qxd S )	Ni  rq   r   rF   i'  rG   r   r#   )	maxvalueslenr   r   ru   rw   r1   r   )r   r   r   rV   r   r   r   r!   r   Zshow_linenoZ	maxlinenor   Z	maxoffsetr   ZinstrZnew_source_lineZis_current_instrr   r   r   r6     s8      


r6   c                 K   s   t t| df| dS )z<Compile the source string, then disassemble the code object.z<dis>N)r3   r   )r   kwargsr   r   r   r7     s    r7   c                 c   sd   d}t dt| dD ]J}| | }|tkrN| |d  |B }|tkrH|d> nd}nd }|||fV  qd S )Nr   rF   rE   rH   )rO   r   ZHAVE_ARGUMENTZEXTENDED_ARG)r   Zextended_argrW   r   r|   r   r   r   r     s    r   c                 C   s\   g }t | D ]J\}}}|dk	r|tkr4|d | }n|tkr|}nq||kr|| q|S )z`Detect all offsets in a byte code which are jump targets.

    Return the list of offsets.

    NrF   )r   r   ZhasjabsrP   )r   r   rw   r   r|   Zlabelr   r   r   r
     s    c           	      c   s   | j ddd }| j ddd }t| j}d}| j}d}t||D ]P\}}|rz||krd||fV  |}||7 }||krz dS |dkr|d8 }||7 }qB||kr||fV  dS )zFind the offsets in a byte code which are start of lines in the source.

    Generate pairs (offset, lineno) as described in Python/compile.c.

    r   NrF   rE   rL   rM   )	co_lnotabr   r*   r   zip)	r   Zbyte_incrementsZline_incrementsZbytecode_lenZ
lastlinenolinenoZaddrZ	byte_incrZ	line_incrr   r   r   r	     s&    


c                   @   sL   e Zd ZdZdddddZdd Zdd	 Zed
d Zdd Z	dd Z
dS )r   a  The bytecode operations of a piece of code

    Instantiate this with a function, method, other compiled object, string of
    code, or a code object (as returned by compile()).

    Iterating over this yields the bytecode operations as Instruction instances.
    N)r   current_offsetc                C   sd   t | | _}|d kr&|j| _d| _n|| _||j | _|j|j | _tt	|| _
|| _|| _d S )Nr   )r[   codeobjr   r   _line_offsetrk   rj   _cell_namesr   r	   _linestarts_original_objectr   )r   r:   r   r   rl   r   r   r   __init__  s    zBytecode.__init__c              	   C   s*   | j }t|j|j|j|j| j| j| jdS )Nr   )	r   r   r*   ri   rh   rf   r   r   r   )r   rl   r   r   r   __iter__  s     zBytecode.__iter__c                 C   s   d | jj| jS )Nz{}({!r}))format	__class__r9   r   r   r   r   r   __repr__  s    
zBytecode.__repr__c                 C   s    |j r|j }q | |jj|jdS )z/ Construct a Bytecode from the given traceback )r   )r@   rA   rB   rC   )clsrD   r   r   r   from_traceback  s    zBytecode.from_tracebackc                 C   s
   t | jS )z3Return formatted information about the code object.)r\   r   r   r   r   r   info  s    zBytecode.infoc                 C   sl   | j }| jdk	r| j}nd}t >}t|j|j|j|j| j	| j
| j||d	 | W  5 Q R  S Q R X dS )z3Return a formatted view of the bytecode operations.Nr   )r   rV   r   r   r   r   r!   r   )r   r   ioStringIOr6   r*   ri   rh   rf   r   r   r   getvalue)r   rl   rw   outputr   r   r   r   
  s    


 zBytecode.dis)r9   r   r   r   r   r   r   classmethodr   r   r   r   r   r   r   r     s   
c               	   C   sf   ddl } |  }|jd| dddd | }|j}| }W 5 Q R X t||jjd}t	| dS )	z*Simple test program to disassemble a file.r   Ninfilerb?-)r8   nargsdefaultr   )
argparseArgumentParseradd_argumentZFileType
parse_argsr   readr   r   r   )r   parserargsr   r   r   r   r   r   _test  s    r   __main__)N)N)NNNNNr   )r   )r   NNNNN);r   r<   typescollectionsr   Zopcoder   Z_opcodes_all
MethodTypeFunctionTypeCodeTyper   staticmethodr8   r0   Zopmapr   r   r   r   r   r   r   r   r   r   rQ   rY   r[   r   r\   r   
namedtuplern   ry   r|   r   r~   rw   ru   rv   r{   r}   r   r   r   r   r   r   r3   r6   r7   r   r   r
   r	   r   r   r9   r   r   r   r   <module>   s   
      - 4      
6       =
