B
    ÔùÓ`É)  ã               @   s^   d dl mZ d dlZd dlZddlmZmZ ddlmZ ddlm	Z	 dd„ Z
G d	d
„ d
ƒZdS )é    )ÚOrderedDictNé   )ÚJsonSchemaValueExceptionÚJsonSchemaDefinitionException)Úindent)ÚRefResolverc             C   s   t | tƒr| S | gS )N)Ú
isinstanceÚlist)Úvariable© r   ú</tmp/pip-unpacked-wheel-qoh_jfy7/fastjsonschema/generator.pyÚenforce_list
   s    
r   c               @   s¾   e Zd ZdZdZd*dd„Zedd„ ƒZedd	„ ƒZed
d„ ƒZ	dd„ Z
dd„ Zdd„ Zd+dd„Zdd„ Zdd„ Zdd„ Zedd„ ƒZdd„ Zddœd d!„Zd"d#„ Zd$d%„ Zd&d'„ Zd(d)„ ZdS ),ÚCodeGeneratora7  
    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             C   sŒ   g | _ i | _g | _i | _tƒ | _d| _d | _d | _d | _	|| _
d | _i | _tƒ | _|d krdt |¡}|| _| j ¡ | j| j ¡ < tƒ | _d S )Nr   )Ú_codeÚ_compile_regexpsÚ_extra_imports_linesÚ_extra_imports_objectsÚsetÚ
_variablesÚ_indentZ_indent_last_lineÚ	_variableÚ_variable_nameZ_root_definitionÚ_definitionÚ_needed_validation_functionsÚ_validation_functions_doner   Zfrom_schemaÚ	_resolverÚget_scope_nameÚget_urir   Ú_json_keywords_to_function)ÚselfÚ
definitionÚresolverr   r   r   Ú__init__    s$    
zCodeGenerator.__init__c             C   s   |   ¡  d | j¡S )zP
        Returns generated code of whole validation function as string.
        Ú
)Ú_generate_func_codeÚjoinr   )r    r   r   r   Ú	func_codeA   s    zCodeGenerator.func_codec             C   s"   |   ¡  tf | j| jttdœ—ŽS )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.
        )ZREGEX_PATTERNSÚrer   )r%   Údictr   r   r(   r   )r    r   r   r   Úglobal_stateJ   s    zCodeGenerator.global_statec             C   sT   |   ¡  | js$d | jdddg ¡S d | jdddddtt | j¡ƒ d dg ¡S )z™
        Returns global variables for generating function from ``func_code`` as code.
        Includes compiled regular expressions and imports.
        r$   z3from fastjsonschema import JsonSchemaValueExceptionÚ zimport re, picklezREGEX_PATTERNS = pickle.loads(ú))r%   r   r&   r   ÚstrÚpickleÚdumps)r    r   r   r   Úglobal_state_codeZ   s    
zCodeGenerator.global_state_codec             C   s   | j s|  ¡  d S )N)r   Úgenerate_func_code)r    r   r   r   r%   r   s    z!CodeGenerator._generate_func_codec             C   s4   |   d¡ x$| jr.| j ¡ \}}|  ||¡ qW dS )zt
        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Únamer   r   r   r1   v   s    
z CodeGenerator.generate_func_codec          
   C   sf   | j  |¡ |  d¡ | j |¡�:}|  d|¡�" | j|dddd� |  d¡ W dQ R X W dQ R X dS )zL
        Generate validation function for given uri with given name
        r+   zdef {}(data):ÚdataT)Úclear_variableszreturn dataN)r   Úaddr2   r   Z	resolvingÚgenerate_func_code_block)r    r5   r6   r!   r   r   r   r4   „   s    
z*CodeGenerator.generate_validation_functionFc             C   s`   | j | j| jf}|||  | _ | _| _|r8| j}tƒ | _|  |¡ |\| _ | _| _|r\|| _dS )zB
        Creates validation rules for current definition.
        N)r   r   r   r   r   Ú_generate_func_code_block)r    r!   r
   Úvariable_namer8   ÚbackupZbackup_variablesr   r   r   r:   �   s    
z&CodeGenerator.generate_func_code_blockc             C   s2   t |tƒstdƒ‚d|kr$|  ¡  n
|  |¡ d S )Nzdefinition must be an objectz$ref)r   r)   r   Úgenerate_refÚrun_generate_functions)r    r!   r   r   r   r;   Ÿ   s
    

z'CodeGenerator._generate_func_code_blockc             C   s*   x$| j  ¡ D ]\}}||kr|ƒ  qW d S )N)r   Úitems)r    r!   ÚkeyÚfuncr   r   r   r?   ¨   s    z$CodeGenerator.run_generate_functionsc          	   C   sV   | j  | jd ¡�: | j  ¡ }| j  ¡ }|| jkr<|| j|< |  d|¡ W dQ R X dS )aW  
        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'}
                }
            }
        z$refz{}({variable})N)r   Zin_scoper   r   r   r   r   r2   )r    r6   r5   r   r   r   r>   ­   s    



zCodeGenerator.generate_refc             O   s€   d| j  | j }| j}|r.d|kr.d | j¡}t| jp8i f| j|dœ|—Ž}|j||Ž}| dd¡ dd¡}| j 	|| ¡ |S )	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!")')
        ú Ú{z"+"{}".format(**locals())+")r
   r6   r$   z\núz\r)
ÚINDENTr   r   Úformatr)   r   r   Úreplacer   Úappend)r    ÚlineÚargsÚkwdsÚspacesr6   Úcontextr   r   r   r2   Å   s    
zCodeGenerator.lc             C   s   t |ƒ dd¡S )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\")r-   rH   )r    Ústringr   r   r   Úeé   s    zCodeGenerator.e)Úrulec            G   sV   d| d }|   t| jtƒr(| j |¡nd¡}| j|f|žt| jƒt|ƒ|dœŽ dS )zG
        Short-cut for creating raising exception in the code.
        z raise JsonSchemaValueException("zI", value={variable}, name="{name}", definition={definition}, rule={rule})N)r!   rR   Údefinition_rule)rQ   r   r   r)   Úgetr2   Úrepr)r    ÚmsgrR   rK   rS   r   r   r   Úexcó   s    "zCodeGenerator.excc             C   s4   d  | j¡}|| jkrdS | j |¡ |  d¡ dS )a  
        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}))rG   r   r   r9   r2   )r    r<   r   r   r   Úcreate_variable_with_lengthû   s
    
z)CodeGenerator.create_variable_with_lengthc             C   s4   d  | j¡}|| jkrdS | j |¡ |  d¡ dS )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()))rG   r   r   r9   r2   )r    r<   r   r   r   Úcreate_variable_keys  s
    
z"CodeGenerator.create_variable_keysc             C   s4   d  | j¡}|| jkrdS | j |¡ |  d¡ dS )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)))rG   r   r   r9   r2   )r    r<   r   r   r   Úcreate_variable_is_list  s
    
z%CodeGenerator.create_variable_is_listc             C   s4   d  | j¡}|| jkrdS | j |¡ |  d¡ dS )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))rG   r   r   r9   r2   )r    r<   r   r   r   Úcreate_variable_is_dict  s
    
z%CodeGenerator.create_variable_is_dict)N)F)Ú__name__Ú
__module__Ú__qualname__Ú__doc__rF   r#   Úpropertyr'   r*   r0   r%   r1   r4   r:   r;   r?   r>   r   r2   rQ   rW   rX   rY   rZ   r[   r   r   r   r   r      s(   
!	
	$
r   )Úcollectionsr   r(   r.   Ú
exceptionsr   r   r   Zref_resolverr   r   r   r   r   r   r   Ú<module>   s   