
    h3                     r    S SK Jr  S SKJr  S SKrSSKJrJr  SSKJr  SSK	J
r
  S r " S	 S
5      rS rS rg)    )OrderedDict)DecimalN   )JsonSchemaValueExceptionJsonSchemaDefinitionException)indent)RefResolverc                 6    [        U [        5      (       a  U $ U /$ N)
isinstancelist)variables    kC:\Users\julio\OneDrive\Documentos\Trabajo\Ideas Frescas\venv\Lib\site-packages\fastjsonschema/generator.pyenforce_listr   
   s    (D!!:    c                       \ rS rSrSrSrSS jr\S 5       r\S 5       r	\S 5       r
S	 rS
 rS rSS jrS rS rS r\S 5       rS rSSS.S jrS rS rS rS rS rSrg)CodeGenerator   a  
This class is not supposed to be used directly. Anything
inside of this class can be changed without noticing.

This class generates code of validation function from JSON
schema object as string. Example:

.. code-block:: python

    CodeGenerator(json_schema_definition).func_code
   Nc                    / U l         0 U l        0 U l        X0l        S/U l        S[
        0U l        [        5       U l        SU l	        S U l
        S U l        S U l        Xl        S U l        0 U l        [        5       U l        Uc  ["        R$                  " U0 S9nX l        U R&                  R)                  5       U R                  U R&                  R+                  5       '   [-        5       U l        g )Nzfrom decimal import Decimalr   r   )store)_code_compile_regexps_custom_formats_detailed_exceptions_extra_imports_linesr   _extra_imports_objectsset
_variables_indent_indent_last_line	_variable_variable_name_root_definition_definition_needed_validation_functions_validation_functions_doner	   from_schema	_resolverget_scope_nameget_urir   _json_keywords_to_function)self
definitionresolverdetailed_exceptionss       r   __init__CodeGenerator.__init__    s    
 "!$7! *%
! w'
# %!%" * -/)*-%'"..zDH! GKnnFcFcFe))$..*@*@*BC*5-'r   c                 X    U R                  5         SR                  U R                  5      $ )z@
Returns generated code of whole validation function as string.

)_generate_func_codejoinr   r-   s    r   	func_codeCodeGenerator.func_codeG   s#    
 	  "yy$$r   c                 |    U R                  5         [        S0 U R                  DU R                  [        [
        S.D6$ )z
Returns global variables for generating function from ``func_code``. Includes
compiled regular expressions and imports, so it does not have to do it every
time when validation function is called.
)REGEX_PATTERNSrer    )r5   dictr   r   r<   r   r7   s    r   global_stateCodeGenerator.global_stateP   s?     	  " 
))
00%=	
 	
r   c                     U R                  5         U R                  (       d   SR                  U R                  / SQ-   5      $ SR                  U R                  SSSSS[	        U R                  5      -   S/-   5      $ )z
Returns global variables for generating function from ``func_code`` as code.
Includes compiled regular expressions and imports.
r4   )3from fastjsonschema import JsonSchemaValueException rC   z	import rerB   rC   zREGEX_PATTERNS = )r5   r   r6   r   serialize_regexesr7   s    r   global_state_codeCodeGenerator.global_state_code`   s     	  "$$99T66 :   
 yy22A"3D4I4I"JJ6
 
  	r   c                 H    U R                   (       d  U R                  5         g g r   )r   generate_func_coder7   s    r   r5   !CodeGenerator._generate_func_codex   s    zz##% r   c                     U R                  S5        U R                  (       aA  U R                  R                  5       u  pU R                  X5        U R                  (       a  M@  gg)z\
Creates base code of validation function and calls helper
for creating code by definition.
zNoneType = type(None)N)lr&   popitemgenerate_validation_function)r-   urinames      r   rH    CodeGenerator.generate_func_code|   sN    
 	&'// 99AACIC--c8 ///r   c           	      d   U R                   R                  U5        U R                  S5        U R                  R	                  U5       nU R                  SU5         U R                  USSSS9  U R                  S5        SSS5        SSS5        g! , (       d  f       N= f! , (       d  f       g= f)z<
Generate validation function for given uri with given name
rC   z4def {}(data, custom_formats={{}}, name_prefix=None):dataT)clear_variableszreturn dataN)r'   addrK   r)   	resolvinggenerate_func_code_block)r-   rN   rO   r.   s       r   rM   *CodeGenerator.generate_validation_function   s     	''++C0r
^^%%c*jNPTU--j&&Z^-_}% V +*UU +*s$   B!$B?B!
B	B!!
B/c                 "   U R                   U R                  U R                  4nXUsU l         U l        U l        U(       a  U R                  n[	        5       U l        U R                  U5      nUu  U l         U l        U l        U(       a  WU l        U$ )zm
Creates validation rules for current definition.

Returns the number of validation rules generated as code.
)r%   r"   r#   r   r   _generate_func_code_block)r-   r.   r   variable_namerS   backupbackup_variablescounts           r   rV   &CodeGenerator.generate_func_code_block   s     !!4>>43F3FF@JVc=$.$*=#!eDO..z:@F=$.$*=.DOr   c                     [        U[        5      (       d  [        S5      eSU;   a  U R                  5       $ U R	                  U5      $ )Nzdefinition must be an object$ref)r   r>   r   generate_refrun_generate_functions)r-   r.   s     r   rY   'CodeGenerator._generate_func_code_block   sC    *d++/0NOOZ$$&&..z::r   c                 v    SnU R                   R                  5        H  u  p4X1;   d  M  U" 5         US-  nM     U$ )z<Returns the number of generate functions that were executed.r   r   )r,   items)r-   r.   r]   keyfuncs        r   rb   $CodeGenerator.run_generate_functions   s>    88>>@IC 
 A r   c                    U R                   R                  U R                  S   5         U R                   R                  5       nU R                   R	                  5       nX R
                  ;  a  XR                  U'   U R                  R                  S5      (       d   eU R                  SS nSR                  U5      nSU;   a  US-   nU R                  SXS	9  SSS5        g! , (       d  f       g= f)
a  
Ref can be link to remote or local definition.

.. code-block:: python

    {'$ref': 'http://json-schema.org/draft-04/schema#'}
    {
        'properties': {
            'foo': {'type': 'integer'},
            'bar': {'$ref': '#/properties/foo'}
        }
    }
r`   rR   r   Nz(name_prefix or "data") + "{}"{z.format(**locals())z*{}({variable}, custom_formats, {name_arg}))name_arg)r)   in_scoper%   r*   r+   r'   r&   r#   
startswithformatrK   )r-   rO   rN   pathrk   s        r   ra   CodeGenerator.generate_ref   s     ^^$$T%5%5f%=>>>002D..((*C9999=11#6&&11&9999&&qr*D7>>tDHh#&;;FF?FY ?>>s   B/C!!
C/c                    SU R                   -  U R                  -  nU R                  nU(       a+  UR                  S5      (       d   eSUSS -   nSU;   a  US-   n[	        U R
                  (       a  U R
                  SLa  U R
                  O0 4U R                  US	.UD6nUR                  " U0 UD6nUR                  S
S5      R                  SS5      nU R                  R                  XA-   5        U$ )a-  
Short-cut of line. Used for inserting line. It's formated with parameters
``variable``, ``variable_name`` (as ``name`` for short-cut), all keys from
current JSON schema ``definition`` and also passed arguments in ``args``
and named ``kwds``.

.. code-block:: python

    self.l('if {variable} not in {enum}: raise JsonSchemaValueException("Wrong!")')

When you want to indent block, use it as context manager. For example:

.. code-block:: python

    with self.l('if {variable} not in {enum}:'):
        self.l('raise JsonSchemaValueException("Wrong!")')
 rR   z" + (name_prefix or "data") + "r   Nrj   z".format(**locals()) + "T)r   rO   r4   z\nz\r)INDENTr    r#   rm   r>   r%   r"   rn   replacer   append)r-   lineargskwdsspacesrO   contexts          r   rK   CodeGenerator.l   s    & t{{"T\\1""??6****4tABx?Dd{88 $ 0 0T5E5ET5QDWY
^^
 	
 {{D,G,||D%(00u=

&-(r   c                 8    [        U5      R                  SS5      $ )z
Short-cut of escape. Used for inserting user values into a string message.

.. code-block:: python

    self.l('raise JsonSchemaValueException("Variable: {}")', self.e(variable))
"z\")strru   )r-   strings     r   eCodeGenerator.e   s     6{""3..r   )append_to_msgrulec                   U R                   (       d  U R                  " SU-   S-   /UQ76   gSU-   S-   nU(       a  USU-   S-   -  nSU-   S-   nU R                  U R                  5      nU R	                  [        U[        5      (       a  UR                  U5      OS5      nU R                  " U/UQ7[        U5      [        U5      US	.6  g)
z7
Short-cut for creating raising exception in the code.
z raise JsonSchemaValueException("z")Nr~   z + ()zraise JsonSchemaValueException(zH, value={variable}, name="{name}", definition={definition}, rule={rule}))r.   r   definition_rule)	r   rK   _expand_refsr%   r   r   r>   getrepr)r-   msgr   r   rx   argr.   r   s           r   excCodeGenerator.exc
  s     ((FF5c9$>FF#gck6M)C//C/34~~&&t'7'78
&&JPT9U9U!5[_`siTid:&6T$ZYhir   c                    [        U[        5      (       a!  U Vs/ s H  o R                  U5      PM     sn$ [        U[        5      (       d  U$ SU;   aB  [        US   [        5      (       a*  U R
                  R                  US   5       nUsS S S 5        $ UR                  5        VVs0 s H  u  pBX@R                  U5      _M     snn$ s  snf ! , (       d  f       NG= fs  snnf )Nr`   )r   r   r   r>   r   r)   rU   re   )r-   r.   vschemaks        r   r   CodeGenerator._expand_refs  s    j$''2<=*Q%%a(*==*d++ZJz&/A3$G$G))*V*<= >=4>4D4D4FG4FDA$$Q''4FGG > >=Gs   C

C)C 
Cc                     SR                  U R                  5      nXR                  ;   a  gU R                  R                  U5        U R	                  S5        g)z
Append code for creating variable with length of that variable
(for example length of list or dictionary) with name ``{variable}_len``.
It can be called several times and always it's done only when that variable
still does not exists.
z{}_lenNz {variable}_len = len({variable})rn   r"   r   rT   rK   r-   rZ   s     r   create_variable_with_length)CodeGenerator.create_variable_with_length$  sB     !7OO+M*12r   c                     SR                  U R                  5      nXR                  ;   a  gU R                  R                  U5        U R	                  S5        g)z
Append code for creating variable with keys of that variable (dictionary)
with a name ``{variable}_keys``. Similar to `create_variable_with_length`.
z{}_keysNz({variable}_keys = set({variable}.keys())r   r   s     r   create_variable_keys"CodeGenerator.create_variable_keys1  sD    
 "((8OO+M*9:r   c                     SR                  U R                  5      nXR                  ;   a  gU R                  R                  U5        U R	                  S5        g)z
Append code for creating variable with bool if it's instance of list
with a name ``{variable}_is_list``. Similar to `create_variable_with_length`.
z
{}_is_listNz:{variable}_is_list = isinstance({variable}, (list, tuple))r   r   s     r   create_variable_is_list%CodeGenerator.create_variable_is_list<  sD    
 %++DNN;OO+M*KLr   c                     SR                  U R                  5      nXR                  ;   a  gU R                  R                  U5        U R	                  S5        g)z
Append code for creating variable with bool if it's instance of list
with a name ``{variable}_is_dict``. Similar to `create_variable_with_length`.
z
{}_is_dictNz1{variable}_is_dict = isinstance({variable}, dict)r   r   s     r   create_variable_is_dict%CodeGenerator.create_variable_is_dictG  sD    
 %++DNN;OO+M*BCr   )r   r   r   r%   r   r   r   r    r!   r,   r&   r)   r$   r'   r"   r#   r   )NT)F)__name__
__module____qualname____firstlineno____doc__rt   r1   propertyr8   r?   rE   r5   rH   rM   rV   rY   rb   ra   r   rK   r   r   r   r   r   r   r   __static_attributes__r=   r   r   r   r      s    
 F%8N % % 
 
  .&9	&(;Z: % %N/ -1t j H3	;	M	Dr   r   c                 ^    S U R                  5        5       nSSR                  U5      -   S-   $ )Nc              3   Z   #    U  H!  u  p[        U5      S -   [        U5      -   v   M#     g7f)z: N)r   
repr_regex).0r   r   s      r   	<genexpr>$serialize_regexes.<locals>.<genexpr>V  s*      )DA 	Q$A&)s   )+z{
    z,
    z
})re   r6   )patterns_dictregex_patternss     r   rD   rD   S  s5    !'')N y~~n55==r   c                    ^  SnSR                  U 4S jU 5       5      nU(       a  SU-   OSnSR                  T R                  U5      $ )N)AIDEBUGLMSXz | c              3   v   >#    U  H.  nTR                   [        [        U5      -  (       d  M'  S U 3v   M0     g7f)zre.N)flagsgetattrr<   )r   fregexs     r   r   repr_regex.<locals>.<genexpr>_  s+     T)Qu{{WRQR^7SyQCy)s   &99z, rC   zre.compile({!r}{}))r6   rn   pattern)r   	all_flagsr   s   `  r   r   r   ]  s@    7IJJT)TTE!D5LrE&&u}}e<<r   )collectionsr   decimalr   r<   
exceptionsr   r   r   ref_resolverr	   r   r   rD   r   r=   r   r   <module>r      s5    #  	 O  %D DD
>=r   