B
    J\e                 @   sr  d Z ddlmZmZ ddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddlZddlZddlZddlZddlZejdkrddlmZmZmZ ddlZn:ddlmZmZmZ yddlZW n ek
r   dZY nX dZddd	d
dddgZejdkZdedfddZdedfddZdd
 Zdd	 Zdd Z dd Z!e" Z#dd Z$e$  dd Z%dd Z&G dd de'Z(e)e*e+e,e-dgZ.e/e(j0e1e(j2ej3e4iZ5ejdkre56ej7e8ej9e4ej:e*i e/e1e;gZ<e/e*kre5e/= e=edre(j>e5ej?< e<@eA ye(jBe5e;< W n eCk
r6   Y nX ejDd krNe.Ee* eFe<Z<d!d ZGG d"d# d#e'ZHdS )$a:  
ast.literal_eval() compatible object tree serialization.

Serpent serializes an object tree into bytes (utf-8 encoded string) that can
be decoded and then passed as-is to ast.literal_eval() to rebuild it as the
original object tree. As such it is safe to send serpent data to other
machines over the network for instance (because only 'safe' literals are
encoded).

Compatible with Python 2.7+ (including 3.x), IronPython 2.7+, Jython 2.7+.

Serpent handles several special Python types to make life easier:

 - str  --> promoted to unicode (see below why this is)
 - bytes, bytearrays, memoryview, buffer  --> string, base-64
   (you'll have to manually un-base64 them though)
 - uuid.UUID, datetime.{datetime, date, time, timespan}  --> appropriate string/number
 - decimal.Decimal  --> string (to not lose precision)
 - array.array typecode 'c'/'u' --> string/unicode
 - array.array other typecode --> list
 - Exception  --> dict with some fields of the exception (message, args)
 - collections module types  --> mostly equivalent primitive types or dict
 - enums --> the value of the enum (Python 3.4+ or enum34 library)
 - all other types  --> dict with  __getstate__  or vars() of the object

Notes:

All str will be promoted to unicode. This is done because it is the
default anyway for Python 3.x, and it solves the problem of the str/unicode
difference between different Python versions. Also it means the serialized
output doesn't have those problematic 'u' prefixes on strings.

The serializer is not thread-safe. Make sure you're not making changes
to the object tree that is being serialized, and don't use the same
serializer in different threads.

Because the serialized format is just valid Python source code, it can
contain comments.

Set literals are not supported on python <3.2 (ast.literal_eval
limitation). If you need Python < 3.2 compatibility, you'll have to use
set_literals=False when serializing. Since version 1.6 serpent chooses
this wisely for you by default, but you can still override it if needed.

Floats +inf and -inf are handled via a trick, Float 'nan' cannot be handled
and is represented by the special value:  {'__class__':'float','value':'nan'}
We chose not to encode it as just the string 'NaN' because that could cause
memory issues when used in multiplications.

Jython's ast module cannot properly parse some literal reprs of unicode strings.
This is a known bug http://bugs.jython.org/issue2008
It seems to work when your server is Python 2.x but safest is perhaps to make
sure your data to parse contains only ascii strings when dealing with Jython.
Serpent checks for possible problems and will raise an error if it finds one,
rather than continuing with string data that might be incorrect.

Copyright by Irmen de Jong (irmen@razorvine.net)
Software license: "MIT software license". See http://opensource.org/licenses/MIT
    )print_functiondivisionN)      )KeysView
ValuesView	ItemsViewz1.28dumpdumpsloadloadsregister_classunregister_classtobytes)r      Fc             C   s   t |||| S )zSerialize object tree to bytes)
Serializer	serialize)objindentset_literalsmodule_in_classname r   &lib/python3.7/site-packages/serpent.pyr
   ^   s    c             C   s   | t| |||d dS )zSerialize object tree to a file)r   r   r   N)writer
   )r   filer   r   r   r   r   r   r	   c   s    c             C   sR  t jdkrDt| tkr |  } nt| tkr8| dd } | d}n8tjdkrpt| tkrb|  } t	| d}nt	| d}d|krt
dtjdk rt|dd	tjtjjB d
}t jdkrxXt|D ]J}t|tjrt|jtrtdd |jD rt
d|jd|_qW z*t jdkr:tjdkr:t  t|S t  X dS )zDDeserialize bytes back to object tree. Uses ast.literal_eval (safe).javaNzutf-8cli zdThe serpent data contains 0-bytes so it cannot be parsed by ast.literal_eval. Has it been corrupted?)r   r   z	<serpent>eval)modeflagsc             s   s   | ]}|d kr|V  qdS )Nr   ).0cr   r   r   	<genexpr>   s    zloads.<locals>.<genexpr>zcannot properly parse unicode string with ast in Jython, see bug http://bugs.jython.org/issue2008 - use python 2.x server or convert strings to ascii yourself firstzunicode-escape)osnametype
memoryviewr   bufferdecodesysplatformcodecs
ValueErrorversion_infocompileastZPyCF_ONLY_AST
__future__Zunicode_literalsZcompiler_flagwalk
isinstanceZStrsstranygcdisableZliteral_evalenable)Zserialized_bytesZ
serializedZnoder   r   r   r   h   s4    


$
c             C   s   |   }t|S )zPDeserialize bytes from a file back to object tree. Uses ast.literal_eval (safe).)readr   )r   datar   r   r   r      s    c             C   s.   |j r
dndt|  d} || || d S )Nzcollections.OrderedDictOrderedDict)	__class__items)r   listr?   
_serialize)r   
serializeroutputstreamindentlevelr   r   r   _ser_OrderedDict   s    rE   c             C   s   | | || d S )N)ser_builtins_list)r   rB   rC   rD   r   r   r   _ser_DictView   s    rG   c              C   sR   t   tt t< tt t< tt t< tjdkr4tt t	j
< td k	rNdd } | t tj< d S )N)r      c             S   s   | | j|| d S )N)rA   value)r   rB   rC   rD   r   r   r   	_ser_Enum   s    z2_reset_special_classes_registry.<locals>._ser_Enum)_special_classes_registryclearrG   r   r   r   r+   r/   rE   collectionsr=   enumEnum)rJ   r   r   r   _reset_special_classes_registry   s    

rP   c             C   s   | t krt | = dS )z:Unregister the specialcase serializer for the given class.N)rK   )clazzr   r   r   r      s    c             C   s   |t | < dS )a  
    Register a special serializer function for objects of the given class.
    The function will be called with (object, serpent_serializer, outputstream, indentlevel) arguments.
    The function must write the serialized data to outputstream. It doesn't return a value.
    N)rK   )rQ   rB   r   r   r   r      s    c               @   sP   e Zd ZdZdd Zdd Zedd Zedd	 Zed
d Z	edd Z
dS )BytesWrapperz
    Wrapper for bytes, bytearray etc. to make them appear as base-64 encoded data.
    You can use the tobytes utility function to decode this back into the actual bytes (or do it manually)
    c             C   s
   || _ d S )N)r<   )selfr<   r   r   r   __init__   s    zBytesWrapper.__init__c             C   s|   t jdkrtt| j}n@tjdks0t jdk rPt	| jt
krPtt| j}nt| j}t	|tkrl|n|dddS )Nr   r   )r   rH   asciibase64)r<   encoding)r+   r,   rV   Z	b64encoder6   r<   r%   r&   r/   r'   	bytearraybytesr*   )rS   Zb64r   r   r   __getstate__   s    
"zBytesWrapper.__getstate__c             C   s   t | S )N)rR   )r<   r   r   r   
from_bytes   s    zBytesWrapper.from_bytesc             C   s   t | S )N)rR   )r<   r   r   r   from_bytearray   s    zBytesWrapper.from_bytearrayc             C   s   t |  S )N)rR   r   )r<   r   r   r   from_memoryview   s    zBytesWrapper.from_memoryviewc             C   s   t | S )N)rR   )r<   r   r   r   from_buffer   s    zBytesWrapper.from_bufferN)__name__
__module____qualname____doc__rT   rZ   staticmethodr[   r\   r]   r^   r   r   r   r   rR      s   rR   )r   r   
BufferTyper   c             C   sn   t | tr| S t | trbd| krb| ddkrbyt| d S  tk
r`   t| d dS X tddS )a0  
    Utility function to convert obj back to actual bytes if it is a serpent-encoded bytes dictionary
    (a dict with base-64 encoded 'data' in it and 'encoding'='base64').
    If obj is already bytes or a byte-like type, return obj unmodified.
    Will raise TypeError if obj is none of the above.
    r<   rW   rV   rU   z?argument is neither bytes nor serpent base64 encoded bytes dictN)r4   _bytes_typesdictgetrV   Z	b64decode	TypeErrorencode)r   r   r   r   r     s    
 c               @   s  e Zd ZdZi ZdedfddZdd Zee	e
eeeeegZdd Zd	d
 Zeee< dd Zeee	< dd Zeee
< ejdk rdd Zeee< ejdk rdd Zeee< dd Zeee< dd Zeee< dd Zdd Zeee< dd Zeee< dd Z eee< d d! Z!e!ee"j#< d"d# Z$e$ee%j%< d$d% Z&e&ee%j'< e(j)d&ksPejd'k rZd(d) Z*nd*d) Z*e*ee%j+< d+d, Z,e,ee%j-< d-d. Z.e.ee/j0< d/d0 Z1e1ee2< d1d2 Z3e3ee4j4< d3d4 Z5d5d6 Z6d7S )8r   z
    Serialize an object tree to a byte stream.
    It is not thread-safe: make sure you're not making changes to the
    object tree that is being serialized, and don't use the same serializer
    across different threads.
    Fc             C   s8   || _ || _|| _t | _d| _tt d d| _	dS )as  
        Initialize the serializer.
        indent=indent the output over multiple lines (default=false)
        setLiterals=use set-literals or not (set to False if you need compatibility with Python < 3.2).
        Serpent chooses a sensible default for you.
        module_in_classname = include module prefix for class names or only use the class name itself
        N   i  )
r   r   r   setserialized_obj_idsspecial_classes_registry_copyminr+   getrecursionlimitmaximum_level)rS   r   r   r   r   r   r   rT   %  s    zSerializer.__init__c             C   s   t  | _d}| jr|d7 }n|d7 }|g}tjdkrJt|tkrJt|}z6tjdkrht	j
dkrht  t | _| ||d W dt  X d| _| `d|d	S )
z#Serialize the object tree to bytes.z# serpent utf-8 z
python3.2
z
python2.6
r   r   r   N zutf-8)rK   copyrm   r   r%   r&   r'   r)   rX   r+   r,   r8   r9   rk   rl   rA   r:   joinri   )rS   r   headeroutr   r   r   r   4  s"    


zSerializer.serializec       	      C   s  || j krtdt|}|tkr6t| |}t|}|tkrP|t| d S || jkrn| j| | |||S | j	}x,|D ]$}t
||rz|| || || d S qzW y| j| }W n@ tk
r   x*|jD ]}|| jkr| j| }P qW tj}Y nX || ||| d S )NzObject graph nesting too deep. Increase serializer.maximum_level if you think you need more,  but this may cause a RecursionError instead if Python's recursion limit doesn't allow it.)rp   r.   r'   _translate_types_repr_typesappendrepr_shortcut_dispatch_typesdispatchrm   r4   KeyError__mro__r   ser_default_class)	rS   r   ru   leveltZspecial_classesrQ   funcZtype_r   r   r   rA   L  s2    





zSerializer._serializec             C   s   |  ||| d S )N)ser_builtins_unicode)rS   Zstr_objru   r   r   r   r   ser_builtins_strn  s    zSerializer.ser_builtins_strc             C   sR   t |r|d n8t |r@|dkr4|d qN|d n|t| d S )Nz#{'__class__':'float','value':'nan'}r   Z1e30000z-1e30000)mathZisnanrx   Zisinfry   )rS   Z	float_objru   r   r   r   r   ser_builtins_floats  s    

zSerializer.ser_builtins_floatc             C   sL   | d | |j|| |jdkr.| d | |j|| | d d S )N(r   +zj))rx   r   realimag)rS   Zcomplex_objru   r   r   r   r   ser_builtins_complex  s    


zSerializer.ser_builtins_complex)r   r   c             C   s.   t |}|d dkr |dd  }|| d S )Nr   u   )ry   rx   )rS   Zunicode_objru   r   zr   r   r   r     s    zSerializer.ser_builtins_unicodec             C   s   | t| d S )N)rx   r6   )rS   Zlong_objru   r   r   r   r   ser_builtins_long  s    zSerializer.ser_builtins_longc       	      C   s   |j }| j}| jr|rd| }|d }|d x,|D ]$}|| ||||d  |d q4W |d  |d< t|dkr~|d= |d| d  nH|d x$|D ]}||||d  |d	 qW t|dkr|d= |d d S )
Nz  z(
r   z,

)r   ,)rx   rA   r   rstriplen)	rS   Z	tuple_objru   r   rx   r   indent_charsindent_chars_insideeltr   r   r   ser_builtins_tuple  s*    


zSerializer.ser_builtins_tuplec       	      C   s   t || jkrtd| jt | |j}| j}| jr|rd| }|d }|d x,|D ]$}|| ||||d  |d qZW |d= |d| d  n@|d	 x$|D ]}||||d  |d
 qW |r|d= |d | jt | d S )Nz"Circular reference detected (list)z  z[
r   z,
r   r   ][r   )idrl   r.   addrx   rA   r   discard)	rS   Zlist_objru   r   rx   r   r   r   r   r   r   r   rF     s.    


zSerializer.ser_builtins_listc             C   sb   |t tttfkr^t|tjs^td k	r4t|tjr4d S t	j
dk rJ|tkrJd S tdt| d d S )N)r   r   zFone of the keys in a dict or set is not of a primitive hashable type: z?. Use simple types as keys or use a list or tuple as container.)boolrY   r6   tuple
issubclassnumbersNumberrN   rO   r+   r/   unicoderh   )rS   r   r   r   r   _check_hashable_type  s    zSerializer._check_hashable_typec             C   sx  t || jkrtd| jt | |j}| j}| jr|rd| }|d }|d | }yt|}	W n t	k
r   |}	Y nX xV|	D ]N\}
}|| | 
t|
 ||
||d  |d ||||d  |d qW |d= |d| d	  nr|d
 xT| D ]H\}
}| 
t|
 ||
||d  |d ||||d  |d qW |r\|d= |d	 | jt | d S )Nz"Circular reference detected (dict)z  z{
r   z: z,
r   r   }{:r   )r   rl   r.   r   rx   rA   r   r?   sortedrh   r   r'   r   )rS   Zdict_objru   r   rx   r   r   r   
dict_itemsZsorted_itemskeyrI   r   r   r   ser_builtins_dict  sD    

zSerializer.ser_builtins_dictc       
      C   s6  | j s*| jrt|}| t||| d S |j}| j}| jr|rd| }|d }|d yt|}W n tk
r|   |}Y nX x:|D ]2}	|| | t|	 ||	||d  |d qW |d= |d| d  n`|r$|d x2|D ]*}	| t|	 ||	||d  |d	 qW |d= |d n| 	d
|| d S )Nz  z{
r   z,
r   r   r   r   r   r   )
r   r   r   rA   r   rx   rh   r   r'   r   )
rS   set_objru   r   rx   r   r   r   Zsorted_eltsr   r   r   r   ser_builtins_set  s>    




zSerializer.ser_builtins_setc             C   s   |  ||| d S )N)r   )rS   r   ru   r   r   r   r   ser_builtins_frozenset   s    z!Serializer.ser_builtins_frozensetc             C   s   | tt| d S )N)rx   ry   r6   )rS   Zdecimal_objru   r   r   r   r   ser_decimal_Decimal$  s    zSerializer.ser_decimal_Decimalc             C   s   | t|  d S )N)rx   ry   	isoformat)rS   Zdatetime_objru   r   r   r   r   ser_datetime_datetime)  s    z Serializer.ser_datetime_datetimec             C   s   | t|  d S )N)rx   ry   r   )rS   Zdate_objru   r   r   r   r   ser_datetime_date-  s    zSerializer.ser_datetime_dater   )r   rH   c             C   s0   |j d |j d |j d }|t| d S )NiQ i@B )ZdaysZsecondsZmicrosecondsrx   ry   )rS   timedelta_objru   r   secsr   r   r   ser_datetime_timedelta2  s    z!Serializer.ser_datetime_timedeltac             C   s   |  }|t| d S )N)Ztotal_secondsrx   ry   )rS   r   ru   r   r   r   r   r   r   6  s    c             C   s   | tt| d S )N)rx   ry   r6   )rS   Ztime_objru   r   r   r   r   ser_datetime_time;  s    zSerializer.ser_datetime_timec             C   s   | tt| d S )N)rx   ry   r6   )rS   Zuuid_objru   r   r   r   r   ser_uuid_UUID?  s    zSerializer.ser_uuid_UUIDc             C   s,   |  |d|jt|d}| ||| d S )NT)r>   Z__exception__argsZ
attributes)get_class_namer   varsrA   )rS   Zexc_objru   r   rI   r   r   r   ser_exception_classC  s
    zSerializer.ser_exception_classc             C   sR   |j dkr| | || n0|j dkr<| | || n| | || d S )Nr#   r   )typecoderA   ZtostringZ	tounicodetolist)rS   Z	array_objru   r   r   r   r   ser_array_arrayM  s
    

zSerializer.ser_array_arrayc             C   sH  t || jkrtd| jt | zyV| }|d krbt|trb| |t|	 
 d}t|tr~| ||| d S W n tk
r   ytt|}| ||d< W nh tk
r   t|dri }x|jD ]}t||||< qW | ||d< ntdt|j d Y nX Y nX | ||| W d | jt | X d S )Nz#Circular reference detected (class))r>   r?   r>   	__slots__z"don't know how to serialize class z/. Give it vars() or an appropriate __getstate__)r   rl   r.   r   rZ   r4   r   r   r@   _asdictr?   rf   r   AttributeErrorr   rh   hasattrr   getattrr6   r>   rA   r   )rS   r   ru   r   rI   Zslotr   r   r   r~   V  s4    

 zSerializer.ser_default_classc             C   s&   | j rd|jj|jjf S |jjS d S )Nz%s.%s)r   r>   r`   r_   )rS   r   r   r   r   r   x  s    zSerializer.get_class_nameN)7r_   r`   ra   rb   r{   can_use_set_literalsrT   r   	frozensetfloatcomplexr   r@   rf   rk   rz   rA   r   r6   r   r   r+   r/   r   r   r   Zlongr   rF   r   r   r   r   r   decimalZDecimalr   datetimer   Zdater%   r&   r   Z	timedeltar   Ztimer   uuidZUUIDr   BaseExceptionr   arrayr~   r   r   r   r   r   r     sb   "

	$"







"r   )Irb   r2   r   r   r1   rV   r+   typesr%   r8   r   r   r   r   r   r   r-   rM   r/   Zcollections.abcr   r   r   rN   ImportError__version____all__r   r
   r	   r   r   rE   rG   r=   rK   rP   r   r   objectrR   rk   r6   intr   r'   rw   rY   r[   rX   r\   dequer@   rv   updateUserDictrf   UserList
UserStringr(   re   r   r^   rd   rx   r)   r]   	NameErrorr,   remover   r   r   r   r   r   r   <module>;   s   



%	%




