o
    6dK                     @   s   d dl mZmZmZmZ d dlmZmZ d dl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mZ d dlmZmZmZ dZer_d dlmZ d dlZejejejf Zed	Zed
Zdd ZeeG dd de Z!G dd de!Z"dS )    )absolute_importdivisionprint_functionunicode_literals)ABCMetaabstractmethod)contextmanagerN)
doc_ref_re)is_aliasresolve_aliasesstrip_aliasF)ApiKVc                 C   s   | j  D ]}|jD ]}|}t|dr!t|j|_|j}t|dsq
q| j  D ]K}|jD ]}|jD ]}t| q2q-|j	D ]/}t|j
 t|j t|j t|j
rX|j
j|_
t|jrb|jj|_t|jrl|jj|_q=g |_i |_q(| S )N	data_type)
namespacesvaluesaliaseshasattrr   r   
data_typesfieldsr   ZroutesZarg_data_typeZresult_data_typeZerror_data_typer
   Zalias_by_name)api	namespacealiasZ	curr_typer   fieldZroute r   dC:\Users\jesus\OneDrive\Desktop\erpjis_fastapi\backend\jisbackend\Lib\site-packages\stone/backend.pyremove_aliases_from_api   s8   















r   c                   @   s   e Zd ZdZdZdZdZdd Zedd Z	e
d)d	d
Zdd Zdd Zdd Ze
d*ddZdd Ze
dd Zdd Zdd Zd+ddZ						d,dd Zd+d!d"Zd#d$ Zd%d& Zed'd( ZdS )-Backendaa  
    The parent class for all backends. All backends should extend this
    class to be recognized as such.

    You will want to implement the generate() function to do the generation
    that you need.

    Here's roughly what you need to do in generate().
    1. Use the context manager output_to_relative_path() to specify an output file.

        with output_to_relative_path('generated_code.py'):
            ...

    2. Use the family of emit*() functions to write to the output file.

    The target_folder_path attribute is the path to the folder where all
    generated files should be created.
    FNc                 C   s   t d| jj | _|| _g | _d| _d| _g | _	i | _
d| _| jrGt| jtjs0J d| j z
| j|| _W dS  tyF   td  w dS )z
        Args:
            target_folder_path (str): Path to the folder where all generated
                files should be created.
        zBackend<%s>   r   Nz4expected cmdline_parser to be ArgumentParser, got %rzdNote: This is for backend-specific arguments which follow arguments to Stone after a "--" delimiter.)logging	getLogger	__class____name__loggertarget_folder_pathoutputlineno
cur_indentpositional_placeholdersnamed_placeholdersargscmdline_parser
isinstanceargparseArgumentParser
parse_args
SystemExitprint)selfr%   r+   r   r   r   __init__g   s.   zBackend.__init__c                 C   s   t )z
        Subclasses should override this method. It's the entry point that is
        invoked by the rest of the toolchain.

        Args:
            api (stone.api.Api): The API specification.
        )NotImplementedError)r3   r   r   r   r   generate   s   
zBackend.generatewbc                 c   s    t j| j|}t j|}t j|s!| jd| t | | jd| | 	  dV  t
||}||  d W d   n1 sIw   Y  | 	  dS )z
        Sets up backend so that all emits are directed towards the new file
        created at :param:`relative_path`.

        Clears the output buffer on enter and exit.
        zCreating %szGenerating %sNzutf-8)ospathjoinr%   dirnameexistsr$   infomakedirsclear_output_bufferopenwriteoutput_buffer_to_stringencode)r3   Zrelative_pathmode	full_path	directoryfr   r   r   output_to_relative_path   s   	
zBackend.output_to_relative_pathc                 C   s   d | jj| ji | jS )z6Returns the contents of the output buffer as a string. )r:   r&   formatr)   r*   r3   r   r   r   rB      s
   zBackend.output_buffer_to_stringc                 C   s   g | _ g | _i | _d S N)r&   r)   r*   rK   r   r   r   r?      s   
zBackend.clear_output_bufferc                 C   s   | j rdS dS )z@
        Returns the size of a single indentation step.
        r      )tabs_for_indentsrK   r   r   r   indent_step      zBackend.indent_stepc                 c   sP    |du s|dksJ d|du r|   }|  j|7  _dV  |  j|8  _dS )a(  
        For the duration of the context manager, indentation will be increased
        by dent. Dent is in units of spaces or tabs depending on the value of
        the class variable tabs_for_indents. If dent is None, indentation will
        increase by either four spaces or one tab.
        Nr   zdent must be >= 0.)rO   r(   )r3   dentr   r   r   indent   s   	zBackend.indentc                 C   s   | j rd| j S d| j S )z
        Returns a string representing the current indentation. Indents can be
        either spaces or tabs, depending on the value of the class variable
        tabs_for_indents.
        	 )rN   r(   rK   r   r   r   make_indent   s   

zBackend.make_indentc                 c   s0    | j }g | _ d V  |d| j  || _ d S )NrI   )r&   rA   r:   )r3   Zoutput_bufferZoriginal_outputr   r   r   capture_emitted_output   s   
zBackend.capture_emitted_outputc                 C   sV   |  j |d7  _ | |dddd t|dkr'|d dkr)tdd	S d	S )
z
        Adds the input string to the output buffer. The string must end in a
        newline. It may contain any number of newline characters. No
        indentation is generated.
        
{z{{}z}}r   z1Input string to emit_raw must end with a newline.N)r'   count_append_outputreplacelenAssertionErrorr3   sr   r   r   emit_raw   s   zBackend.emit_rawc                 C   s   | j | d S rL   )r&   appendr`   r   r   r   r\      s   zBackend._append_outputrI   c                 C   sP   t |tjs
J dd|vsJ d|r!| d|  |f  dS | d dS )z
        Adds indentation, then the input string, and lastly a newline to the
        output buffer. If s is an empty string (default) then an empty line is
        created with no indentation.
        zs must be a unicode stringrW   z.String to emit cannot contain newline strings.z%s%s
N)r-   six	text_typerb   rU   r`   r   r   r   emit   s   
zBackend.emitP   c           	   
   C   s<   |   }|| }| tj||| || |||dd  dS )a  
        Adds the input string to the output buffer with indentation and
        wrapping. The wrapping is performed by the :func:`textwrap.fill` Python
        library function.

        Args:
            s (str): The input string to wrap.
            prefix (str): The string to prepend to *every* line.
            initial_prefix (str): The string to prepend to the first line of
                the wrapped string. Note that the current indentation is
                already added to each line.
            subsequent_prefix (str): The string to prepend to every line after
                the first. Note that the current indentation is already added
                to each line.
            width (int): The target width of each line including indentation
                and text.
            break_long_words (bool): Break words longer than width.  If false,
                those words will not be broken, and some lines might be longer
                than width.
            break_on_hyphens (bool): Allow breaking hyphenated words. If true,
                wrapping will occur preferably on whitespaces and right after
                hyphens part of compound words.
        )initial_indentsubsequent_indentwidthbreak_long_wordsbreak_on_hyphensrW   N)rU   rb   textwrapfill)	r3   ra   prefixZinitial_prefixZsubsequent_prefixrj   rk   rl   rR   r   r   r   emit_wrapped_text   s   "

zBackend.emit_wrapped_textc                 C   s   |  d|  dS )z_
        Emits replacements fields that can be used to format the output string later.
        z{%s}N)r\   r`   r   r   r   emit_placeholder-  s   zBackend.emit_placeholderc                 C   s   | j | dS )z]
        Format replacement fields corresponding to empty calls to emit_placeholder.
        N)r)   rc   r`   r   r   r   add_positional_placeholder4  s   z"Backend.add_positional_placeholderc                 C   s   || j |< dS )za
        Format replacement fields corresponding to non-empty calls to emit_placeholder.
        N)r*   )r3   namera   r   r   r   add_named_placeholder;  rP   zBackend.add_named_placeholderc                 C   s   t |tjsJ dt| d}g }t|D ]'}| \}}||||  |}|d}|d}	|||	}
||
 q|||d  d	|S )a5  
        Helper for parsing documentation references in Stone docstrings and
        replacing them with more suitable annotations for the generated output.

        Args:
            doc (str): A Stone docstring.
            handler: A function with the following signature:
                `(tag: str, value: str) -> str`. It will be called for every
                reference found in the docstring with the tag and value parsed
                for you. The returned string will be substituted in the
                docstring in place of the reference.
        z)Expected string (unicode in PY2), got %r.r   tagvalNrI   )
r-   rd   re   typer	   finditerspanrc   groupr:   )clsdochandlerZ	cur_indexpartsmatchstartendru   rv   subr   r   r   process_docB  s   




zBackend.process_doc)r7   rL   )rI   )rI   rI   rI   rg   FF)r#   
__module____qualname____doc__rN   r,   Zpreserve_aliasesr4   r   r6   r   rH   rB   r?   rO   rR   rU   rV   rb   r\   rf   rp   rq   rr   rt   classmethodr   r   r   r   r   r   F   sB    




-r   c                   @   sF   e Zd ZdZdd Z						dd	d
Ze					dddZdS )CodeBackendz
    Extend this instead of :class:`Backend` when generating source code.
    Contains helper functions specific to code generation.
    c                 C   s*   i }|  D ]\}}|dur|||< q|S )znGiven a dict, returns a new dict with all the same key/values except
        for keys that had values of None.N)items)r3   dZnew_dkvr   r   r   filter_out_none_valued_keysk  s   z'CodeBackend.filter_out_none_valued_keysrI   ()T,Fc                    s  t dkrtd tjrtd tjsJ dt |dkr1|d  d     dS t |dkrL|d  |d  d     dS |r|d  |d     fdd}|sld rt |t d   || W d   dS 1 sw   Y  dS || dS |sd r|d    ( t|D ]\}	}
|	t |d kr|r|
 q|
  qW d   n1 sw   Y  d s߈ rd    dS d rd  dS dS )a  
        Given a list of items, emits one item per line.

        This is convenient for function prototypes and invocations, as well as
        for instantiating arrays, sets, and maps in some languages.

        TODO(kelkabany): A backend that uses tabs cannot be used with this
            if compact is false.

        Args:
            items (list[str]): Should contain the items to generate a list of.
            before (str): The string to come before the list of items.
            after (str): The string to follow the list of items.
            delim (str, str): The first element is added immediately following
                `before`. The second element is added prior to `after`.
            compact (bool): In compact mode, the enclosing parentheses are on
                the same lines as the first and last list item.
            sep (str): The string that follows each list item when compact is
                true. If compact is false, the separator is omitted for the
                last item.
            skip_last_sep (bool): When compact is false, whether the last line
                should have a trailing separator. Ignored when compact is true.
           r   r   z-delim must be a tuple of two unicode strings.Nc                    sX   | dd  } t | D ]\}}|t| d kr"|d     q
|  q
d S )Nr   )	enumerater^   rf   )r   iitemafterdelimr3   sepr   r   	emit_list  s   z6CodeBackend.generate_multiline_list.<locals>.emit_list)r^   r-   rd   re   rf   rR   r   )r3   r   beforer   r   compactr   Zskip_last_sepr   r   r   r   r   r   generate_multiline_listu  sB   "&
"
z#CodeBackend.generate_multiline_listrX   rY   Nc                 c   s   t |dksJ dt|d tjtdfr#t|d tjtdfs'J d|rC|sC|d dur=| d||d  n| | n|rJ| | |d durW| |d  | | dV  W d   n1 sjw   Y  |d dur| |d |  dS | | dS )a+  
        A context manager that emits configurable lines before and after an
        indented block of text.

        This is convenient for class and function definitions in some
        languages.

        Args:
            before (str): The string to be output in the first line which is
                not indented..
            after (str): The string to be output in the last line which is
                not indented.
            delim (str, str): The first element is added immediately following
                `before` and a space. The second element is added prior to a
                space and then `after`.
            dent (int): The amount to indent the block. If none, the default
                indentation increment is used (four spaces or one tab).
            allman (bool): Indicates whether to use `Allman` style indentation,
                or the default `K&R` style. If there is no `before` string this
                is ignored. For more details about indent styles see
                http://en.wikipedia.org/wiki/Indent_style
        r   z!delim must be a tuple of length 2r   Nr   z.delim must be a tuple of two optional strings.z{} {})r^   r-   rd   re   rw   rf   rJ   rR   )r3   r   r   r   rQ   Zallmanr   r   r   block  s*    
zCodeBackend.block)rI   rI   r   Tr   F)rI   rI   r   NF)r#   r   r   r   r   r   r   r   r   r   r   r   r   d  s"    
Hr   )#
__future__r   r   r   r   abcr   r   
contextlibr   r.   r    r8   rd   rm   Zstone.frontend.ir_generatorr	   Zstone.irr
   r   r   Z_MYPYr   typingTupleTextZ
DelimTupleTypeVarr   r   r   add_metaclassobjectr   r   r   r   r   r   <module>   s.    

)  