a
    zn„fûP  ã                   @  s´   d Z ddlmZ ddlZddlZddlZddlZeeedœZe d¡Z	dd„ Z
dd	„ Zd
d„ Ze d¡Ze d¡Zddd„Zdd„ Ze d¡Zddd„Zeed< G dd„ deƒZdS )a  
This module defines low-level routines for deserialization, including
:doc:`uproot.deserialization.compile_class`, which creates class objects from
``TStreamerInfo``-derived code, and
:doc:`uproot.deserialization.read_object_any`, which manages references to
previously read objects.
é    )ÚannotationsN)ÚstructÚnumpyÚuprootÚu1c                 C  s   t t| ddƒ|ƒ d S )Nz	<dynamic>Úexec)r   Úcompile)Ú
class_codeÚ	new_scope© r   úY/home/yuhw/wc/wire-cell-python/wcpy/lib/python3.9/site-packages/uproot/deserialization.pyÚ_actually_compile   s    r   c                 c  sZ   t  t j | j¡d ¡}|d ur&|V  t| dƒrV| jD ]\}}t|||ƒ|ƒE d H  q6d S )Nr   Úbase_names_versions)r   Zbehavior_ofÚmodelZclassname_decodeÚ__name__Úhasattrr   Ú_yield_all_behaviors)ÚclsÚcZbehavior_clsÚ	base_nameÚbase_versionr   r   r   r       s    
r   c           	   
     sP  t  ¡ ‰| ¡ D ]}|ˆ|j< qd‡‡fdd„	}|ˆd< tjˆd< tjjˆd< tjj	j
ˆd< tjj	jˆd< tjj	jˆd	< zt|ˆƒ W n: tyÀ } z"t|d
 t|ƒ ƒ|‚W Y d}~n
d}~0 0 ˆ| }||_d|_ttj|j|ƒ tt||ƒƒ}tdd„ |D ƒƒ‰ t‡ fdd„|D ƒƒ}||_t|ƒdk�rLtj |jg |¢|‘R i ¡}|S )a“  
    Args:
        file (:doc:`uproot.reading.ReadOnlyFile`): File to use to generate
            :doc:`uproot.model.Model` classes as needed from its
            :ref:`uproot.reading.ReadOnlyFile.streamers` and ``file_path``
            for error messages.
        classes (dict): MutableMapping in which to add the finished class.
        class_code (str): Python code string defining the new class.
        class_name (str): Python (encoded) name of the new class. See
            :doc:`uproot.model.classname_decode` and
            :doc:`uproot.model.classname_encode`.

    Compile a new class from Python code and insert it in the dict of classes.
    Nc                   sR   t j | ¡} ˆ t j | |¡¡}|d u r:ˆ t j | ¡¡}|d u rNˆ  | |¡}|S ©N)r   r   Zclassname_regularizeÚgetZclassname_encodeÚclass_named)ÚnameÚversionr   )Úfiler
   r   r   r   <   s    zcompile_class.<locals>.cr   ÚafÚDeserializationErrorÚCannotBeStridedÚCannotBeForthÚCannotBeAwkwardz

zuproot.dynamicc                 s  s(   | ] }t |d ƒr|jD ]
}|V  qqdS )Ú
no_inheritN)r   r"   )Ú.0r   Úbadr   r   r   Ú	<genexpr>W   s   z compile_class.<locals>.<genexpr>c                 3  s   | ]}|ˆ vr|V  qd S r   r   )r#   r   )Úexcluder   r   r%   Z   ó    r   )N)ÚscopeÚcopyÚvaluesr   r   Z_awkwardforthZdeserializationr   ZinterpretationÚobjectsr   r    r!   r   ÚSyntaxErrorÚstrr	   Ú
__module__ÚsetattrZdynamicÚtupler   Ú	behaviorsÚlenZ_utilÚ	new_class)	r   Úclassesr	   Ú
class_namer   r   ÚerrÚoutr1   r   )r&   r   r
   r   Úcompile_class)   s6    	
,ÿr8   z>IHz>HTc                 C  s’   |j | t|dd�\}}t |¡}|tjj@ rTt|tjj @ ƒd }|rj| tj	¡ nd}|j
| t||d�}|tjj@ }|rˆ|tjj @ }|||fS )a7  
    Args:
        chunk (:doc:`uproot.source.chunk.Chunk`): Buffer of contiguous data
            from the file :doc:`uproot.source.chunk.Source`.
        cursor (:doc:`uproot.source.cursor.Cursor`): Current position in
            that ``chunk``.
        context (dict): Auxiliary data used in deserialization.
        move (bool): If True, move the ``cursor`` to a position just past the
            bytes that were read. If False, don't move the ``cursor`` at all.

    Deserialize a number of bytes and version number, which is usually 6 bytes
    but may be 2 bytes if the number of bytes isn't given.

    Returns a 3-tuple of

    * number of bytes (int or None if unknown)
    * instance version (int)
    * is memberwise (bool): True if the memberwise bit is set in the version
      number; False otherwise.
    F)Úmoveé   N)ÚfieldsÚ_numbytes_version_1r   Úint64r   ÚconstÚkByteCountMaskÚintÚskipÚsizeÚfieldÚ_numbytes_version_2ZkStreamedMemberWise)ÚchunkÚcursorÚcontextr9   Ú	num_bytesr   Zis_memberwiser   r   r   Únumbytes_versiong   s    
rI   c                 C  sB   |dur>|  |¡}||kr>td|› d|› d|› d�| |||ƒ‚dS )aË  
    Args:
        chunk (:doc:`uproot.source.chunk.Chunk`): Buffer of contiguous data
            from the file :doc:`uproot.source.chunk.Source`.
        start_cursor (:doc:`uproot.source.cursor.Cursor`): Initial position in
            that ``chunk``.
        stop_cursor (:doc:`uproot.source.cursor.Cursor`): Current position in
            that ``chunk``.
        num_bytes (int or None): If an integer, the number of bytes to compare
            with the difference between ``start_cursor`` and ``stop_cursor``;
            if None, this function does nothing.
        classname (str): C++ (decoded) name of the class for error messages.
        context (dict): Auxiliary data used in deserialization.
        file_path (str): Name of the file for error messages.

    Verifies that the number of bytes matches the change in position of the
    cursor (if ``num_bytes`` is not None).

    Raises a :doc:`uproot.deserialization.DeserializationError` on failure.
    Nz	expected z bytes but cursor moved by z bytes (through ú))Údisplacementr   )rE   Zstart_cursorZstop_cursorrH   Ú	classnamerG   Ú	file_pathZobservedr   r   r   Únumbytes_check•   s    
ûrN   z>Ic                 C  sœ  |  ¡ }t | | t|¡¡}|tjj@ dks8|tjjkrJd}	d}
|}d}n(d}	|  ¡ }
t | | t|¡¡}t	|ƒ}|tjj
@ dkrô|dkrŽdS |dkrš|S ||jvrâ|tjj@ rÆt	|tjj @ ƒd }| |j| | d ¡ dS |jt	|ƒ S �n¤|tjjk�r´| | |¡}| |¡}|	dk�r6||j|
tjj < n||jt|jƒd < |du �rj| | |||||¡}n| | |||||¡}|	dk�rœ||j|tjj < n||jt|jƒd < |S t	|tjj
 @ ƒ}|du �rN||jv�r.t|ddƒdu �rôd}nd|j› �}td |d	 d
d„ |jD ƒ¡|¡| |||jƒ‚|j| }| | |||||¡}n| | |||||¡}|	dk�r€||j|tjj < n||jt|jƒd < |S dS )aY  
    Args:
        chunk (:doc:`uproot.source.chunk.Chunk`): Buffer of contiguous data
            from the file :doc:`uproot.source.chunk.Source`.
        cursor (:doc:`uproot.source.cursor.Cursor`): Current position in
            that ``chunk``.
        context (dict): Auxiliary data used in deserialization.
        file (:doc:`uproot.reading.ReadOnlyFile`): File to use to generate
            :doc:`uproot.model.Model` classes as needed from its
            :ref:`uproot.reading.ReadOnlyFile.streamers` and ``file_path``
            for error messages.
        selffile (:doc:`uproot.reading.CommonFileMethods`): A possibly
            :doc:`uproot.reading.DetachedFile` associated with the ``parent``.
        parent (None or calling object): The previous ``read`` in the
            recursive descent.
        as_class (None or :doc:`uproot.model.Model`): If None, use the class
            indicated in the byte stream; otherwise, use this class.

    Generic read function, which may deliver an instance of any class and may
    reference previously read objects.

    This function is the reason why :doc:`uproot.source.cursor.Cursor` has a
    :ref:`uproot.source.cursor.Cursor.refs`; that dictionary holds previously
    read objects that might need to be accessed later.

    The :doc:`uproot.source.cursor.Cursor` has an
    :ref:`uproot.source.cursor.Cursor.origin` to account for the fact that
    seek positions for keys in the reference dict are relative to the start of
    the :doc:`uproot.source.chunk.Chunk`, rather than the start of the file
    (as it would have to be for decompressed chunks).
    r   é   Nr:   rM   Ú z


in file z;invalid class-tag reference: {}

    Known references: {}{}ú, c                 s  s   | ]}t |ƒV  qd S r   )r-   )r#   Úxr   r   r   r%   /  r'   z"read_object_any.<locals>.<genexpr>)rK   r   r=   rC   Ú_read_object_any_format1r   r>   r?   ZkNewClassTagr@   Z
kClassMaskÚrefsÚmove_toÚoriginrL   r   Z
kMapOffsetr2   ÚreadÚgetattrrM   r   ÚformatÚjoin)rE   rF   rG   r   ZselffileÚparentZas_classÚbegZbcntÚversÚstartÚtagrL   r   ÚobjÚrefÚin_filer   r   r   Úread_object_any»   sr    $





ý÷

rc   c                   @  sP   e Zd ZdZdd„ Zdd„ Zddddejfdd	„Zde	fd
d„Z
edd„ ƒZdS )r   a•  
    Error raised when a ROOT file cannot be deserialized.

    If the first attempt in :ref:`uproot.reading.ReadOnlyKey.get` failed with
    predefined :doc:`uproot.model.Model` classes, this exception is caught
    and retried with ``TStreamerInfo``-derived classes, so
    :doc:`uproot.deserialization.DeserializationError` sometimes appears in an
    exception chain two levels deep. (Some ROOT files do have classes that don't
    match the standard ``TStreamerInfo``; they may have been produced from
    private builds of ROOT between official releases.)

    If a :doc:`uproot.deserialization.DeserializationError` is caught, the byte
    stream at the position where it failed can be inspected with

    * :ref:`uproot.deserialization.DeserializationError.debug`
    * :ref:`uproot.deserialization.DeserializationError.debug_array`
    * :ref:`uproot.deserialization.DeserializationError.partial_object`
    c                 C  s"   || _ || _|| _|| _|| _d S r   )ÚmessagerE   rF   rG   rM   )Úselfrd   rE   rF   rG   rM   r   r   r   Ú__init__\  s
    zDeserializationError.__init__c                 C  s˜  g }d}d }| j  dd¡D ]¢}| d ||j|jt|ƒjt|ƒj|j	d u rNdn|j	¡¡ |d }t
|dg ƒD ]}| |› d|›�¡ qlt
|di ƒ ¡ D ] \}}| |› |› d	|›�¡ q–|}q|d u�rt
|d
d ƒ}t
|dd ƒ}|d u�r||d u�r|dd„ |D ƒ}	|D ]L}
t
|
dd ƒ}|d u�r||	v �rBd| d |	|	 |¡< n|	 |d ¡ �qt|	ƒdk�r|| d |jd |	¡¡¡ t
|dd ƒ}t
|dd ƒ}|d u�r|d u�rt|ƒ}|D ]6}||v �rÚd| d || |¡< n| |d ¡ �q´t|ƒdk�r| d |jd |¡¡¡ d}d| j v �r8d | j d j¡}nd| j v �rVd | j d j¡}t|ƒdk�rz| j› d| j› |› �S d d |¡| j| j|¡S d S )Nz    Úbreadcrumbsr   z#{}{} version {} as {}.{} ({} bytes)ú?Z_basesz(base): Z_membersz: r   c                 S  s   g | ]\}}|‘qS r   r   )r#   ÚnÚvr   r   r   Ú
<listcomp>}  r'   z0DeserializationError.__str__.<locals>.<listcomp>rL   ú(rJ   r   zBase classes for {}: {}rQ   Úmember_nameszMembers for {}: {}rP   ZTBranchz
in TBranch {}ZTKeyz
in object {}z	
in file z"while reading

{}

{}
in file {}{}Ú
)rG   r   ÚappendrY   rL   Zinstance_versionÚtyper.   r   rH   rX   ÚitemsÚindexr2   rZ   ÚlistZobject_pathrd   rM   )re   ÚlinesÚindentÚlastr`   rj   Úkr   ÚbasesÚ
base_namesr   rL   rm   Úmembersri   Z	in_parentr   r   r   Ú__str__c  s„    úÿ




ÿÿÿ
ÿÿÿÿúzDeserializationError.__str__r   Nc                 C  s2   | j  ¡ }| |¡ |j| j| j||||d� dS )a9
  
        Args:
            skip_bytes (int): Number of bytes to skip before presenting the
                remainder of the :doc:`uproot.source.chunk.Chunk`. May be
                negative, to examine the byte stream leading up to the attempted
                deserialization.
            limit_bytes (None or int): Number of bytes to limit the output to.
                A line of debugging output (without any ``offset``) is 20 bytes,
                so multiples of 20 show full lines. If None, everything is
                shown to the end of the :doc:`uproot.source.chunk.Chunk`,
                which might be large.
            dtype (None, ``numpy.dtype``, or its constructor argument): If None,
                present only the bytes as decimal values (0-255). Otherwise,
                also interpret them as an array of a given NumPy type.
            offset (int): Number of bytes to skip before interpreting a ``dtype``;
                can be helpful if the numerical values are out of phase with
                the first byte shown. Not to be confused with ``skip_bytes``,
                which determines which bytes are shown at all. Any ``offset``
                values that are equivalent modulo ``dtype.itemsize`` show
                equivalent interpretations.
            stream (object with a ``write(str)`` method): Stream to write the
                debugging output to.

        Presents the byte stream at the point where deserialization failed.

        Example output with ``dtype=">f4"`` and ``offset=3``.

        .. code-block::

            --+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+-
            123 123 123  63 140 204 205  64  12 204 205  64  83  51  51  64 140 204 205  64
              {   {   {   ? --- --- ---   @ --- --- ---   @   S   3   3   @ --- --- ---   @
                                    1.1             2.2             3.3             4.4
                --+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+-
                176   0   0  64 211  51  51  64 246 102 102  65  12 204 205  65  30 102 102  66
                --- --- ---   @ ---   3   3   @ ---   f   f   A --- --- ---   A ---   f   f   B
                        5.5             6.6             7.7             8.8             9.9
                --+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+-
                202   0   0  67  74   0   0  67 151 128   0 123 123
                --- --- ---   C   J --- ---   C --- --- ---   {   {
                      101.0           202.0           303.0
        )rG   Úlimit_bytesÚdtypeÚoffsetÚstreamN)rF   r)   rA   ÚdebugrE   rG   )re   Ú
skip_bytesr|   r}   r~   r   rF   r   r   r   r€   ±  s    -

úzDeserializationError.debugc                 C  sT   t  |¡}| j ¡ }| |¡ | j |j|| j¡}|dt	|ƒ|j
 |j
 …  |¡S )av  
        Args:
            skip_bytes (int): Number of bytes to skip before presenting the
                remainder of the :doc:`uproot.source.chunk.Chunk`. May be
                negative, to examine the byte stream leading up to the attempted
                deserialization.
            dtype (``numpy.dtype`` or its constructor argument): Data type in
                which to interpret the data. (The size of the array returned is
                truncated to this ``dtype.itemsize``.)

        Like :ref:`uproot.deserialization.DeserializationError.debug`, but
        returns a NumPy array for further inspection.
        N)r   r}   rF   r)   rA   rE   Ú	remainderrr   rG   r2   ÚitemsizeÚview)re   r�   r}   rF   r7   r   r   r   Údebug_arrayé  s
    


z DeserializationError.debug_arrayc                 C  s    d| j v r| j d d S dS dS )zk
        The object, partially filled, which may contain some clues as to what
        went wrong.
        rg   éÿÿÿÿN)rG   )re   r   r   r   Úpartial_objectý  s    
z#DeserializationError.partial_object)r   r.   Ú__qualname__Ú__doc__rf   r{   ÚsysÚstdoutr€   Únp_uint8r…   Úpropertyr‡   r   r   r   r   r   H  s   Oÿ
8r   )T)N)r‰   Ú
__future__r   r   rŠ   r   r   r(   r}   rŒ   r   r   r8   ÚStructr<   rD   rI   rN   rS   rc   Ú	Exceptionr   r   r   r   r   Ú<module>   s,   ý
	:


.#

 