o
    ¡ØÆhvO  ã                   @   sø   d Z ddlmZ ddlmZ ddlmZmZ ddlm	Z	m
Z
mZmZmZmZmZmZmZmZmZmZmZ ddlmZ ddlmZ G dd	„ d	eƒZG d
d„ deƒZG dd„ deƒZdZG dd„ deƒZG dd„ deƒZ G dd„ de ƒZ!eeƒZ"eeƒZ"dS )zìA convenience which constructs expression trees from an easy-to-read syntax

Use this unless you have a compelling reason not to; it performs some
optimizations that would be tedious to do when constructing an expression tree
by hand.

é    )ÚOrderedDict)Údedent)Ú
BadGrammarÚUndefinedLabel)ÚLiteralÚRegexÚSequenceÚOneOfÚ	LookaheadÚ
QuantifierÚOptionalÚ
ZeroOrMoreÚ	OneOrMoreÚNotÚTokenMatcherÚ
expressionÚis_callable)ÚNodeVisitor)Úevaluate_stringc                       sj   e Zd ZdZd‡ fdd„	Zdd„ Z‡ fdd„Zd	d
„ Zddd„Zddd„Z	dd„ Z
dd„ Zdd„ Z‡  ZS )ÚGrammaraE  A collection of rules that describe a language

    You can start parsing from the default rule by calling ``parse()``
    directly on the ``Grammar`` object::

        g = Grammar('''
                    polite_greeting = greeting ", my good " title
                    greeting        = "Hi" / "Hello"
                    title           = "madam" / "sir"
                    ''')
        g.parse('Hello, my good sir')

    Or start parsing from any of the other rules; you can pull them out of the
    grammar as if it were a dictionary::

        g['title'].parse('sir')

    You could also just construct a bunch of ``Expression`` objects yourself
    and stitch them together into a language, but using a ``Grammar`` has some
    important advantages:

    * Languages are much easier to define in the nice syntax it provides.
    * Circular references aren't a pain.
    * It does all kinds of whizzy space- and time-saving optimizations, like
      factoring up repeated subexpressions into a single object, which should
      increase cache hit ratio. [Is this implemented yet?]

    Ú c                    s@   ‡ fdd„|  ¡ D ƒ}ˆ  ||¡\}}tƒ  |  ¡ ¡ |ˆ _dS )ay  Construct a grammar.

        :arg rules: A string of production rules, one per line.
        :arg default_rule: The name of the rule invoked when you call
            :meth:`parse()` or :meth:`match()` on the grammar. Defaults to the
            first rule. Falls back to None if there are no string-based rules
            in this grammar.
        :arg more_rules: Additional kwargs whose names are rule names and
            values are Expressions or custom-coded callables which accomplish
            things the built-in rule syntax cannot. These take precedence over
            ``rules`` in case of naming conflicts.

        c                    s*   i | ]\}}|t |ƒrt||ˆ ƒn|“qS © )r   r   )Ú.0ÚkÚv©Úselfr   úa/var/www/html/HyperOracle/crypto_trader/venv/lib/python3.10/site-packages/parsimonious/grammar.pyÚ
<dictcomp>>   s    ÿÿz$Grammar.__init__.<locals>.<dictcomp>N)ÚitemsÚ_expressions_from_rulesÚsuperÚ__init__Údefault_rule)r   ÚrulesÚ
more_rulesÚdecorated_custom_rulesÚexprsÚfirst©Ú	__class__r   r   r"   /   s   
þ
zGrammar.__init__c                 C   s   |   ¡ }|| |_|S )zAReturn a new Grammar whose :term:`default rule` is ``rule_name``.)Ú_copyr#   )r   Ú	rule_nameÚnewr   r   r   ÚdefaultF   s   
zGrammar.defaultc                    s*   t  t ¡}tt |ƒ |  ¡ ¡ | j|_|S )zßReturn a shallow copy of myself.

        Deep is unnecessary, since Expression trees are immutable. Subgrammars
        recreate all the Expressions from scratch, and AbstractGrammars have
        no Expressions.

        )r   Ú__new__r!   r"   r   r#   )r   r-   r)   r   r   r+   L   s   
zGrammar._copyc                 C   ó   t  |¡}t|ƒ |¡S )aÎ  Return a 2-tuple: a dict of rule names pointing to their
        expressions, and then the first rule.

        It's a web of expressions, all referencing each other. Typically,
        there's a single root to the web of references, and that root is the
        starting symbol for parsing, but there's nothing saying you can't have
        multiple roots.

        :arg custom_rules: A map of rule names to custom-coded rules:
            Expressions

        )Úrule_grammarÚparseÚRuleVisitorÚvisit©r   r$   Úcustom_rulesÚtreer   r   r   r    Y   s   
zGrammar._expressions_from_rulesr   c                 C   ó   |   ¡  | jj||d�S )zoParse some text with the :term:`default rule`.

        :arg pos: The index at which to start parsing

        ©Úpos)Ú_check_default_ruler#   r2   ©r   Útextr:   r   r   r   r2   i   s   zGrammar.parsec                 C   r8   )z¢Parse some text with the :term:`default rule` but not necessarily
        all the way to the end.

        :arg pos: The index at which to start parsing

        r9   )r;   r#   Úmatchr<   r   r   r   r>   r   s   zGrammar.matchc                 C   s   | j stdƒ‚dS )z7Raise RuntimeError if there is no default rule defined.z„Can't call parse() on a Grammar that has no default rule. Choose a specific rule instead, like some_grammar['some_rule'].parse(...).N)r#   ÚRuntimeErrorr   r   r   r   r;   |   s   ÿzGrammar._check_default_rulec                    sB   ˆ j rˆ j gng }| ‡ fdd„ˆ  ¡ D ƒ¡ d dd„ |D ƒ¡S )zbReturn a rule string that, when passed to the constructor, would
        reconstitute the grammar.c                 3   s   � | ]
}|ˆ j ur|V  qd S ©N)r#   ©r   Úexprr   r   r   Ú	<genexpr>‡   s   € 
ÿÿz"Grammar.__str__.<locals>.<genexpr>Ú
c                 s   s   � | ]}|  ¡ V  qd S r@   )Úas_rulerA   r   r   r   rC   ‰   s   € )r#   ÚextendÚvaluesÚjoin)r   r'   r   r   r   Ú__str__ƒ   s   zGrammar.__str__c                 C   s   d  t| ƒ¡S )z8Return an expression that will reconstitute the grammar.zGrammar({!r}))ÚformatÚstrr   r   r   r   Ú__repr__‹   s   zGrammar.__repr__)r   )r   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r"   r.   r+   r    r2   r>   r;   rI   rL   Ú__classcell__r   r   r)   r   r      s    

	
r   c                   @   ó   e Zd ZdZdd„ ZdS )ÚTokenGrammarzÐA Grammar which takes a list of pre-lexed tokens instead of text

    This is useful if you want to do the lexing yourself, as a separate pass:
    for example, to implement indentation-based languages.

    c                 C   r0   r@   )r1   r2   ÚTokenRuleVisitorr4   r5   r   r   r   r    —   s   
z$TokenGrammar._expressions_from_rulesN©rM   rN   rO   rP   r    r   r   r   r   rS   �   s    rS   c                   @   rR   )ÚBootstrappingGrammara  The grammar used to recognize the textual rules that describe other
    grammars

    This grammar gets its start from some hard-coded Expressions and claws its
    way from there to an expression tree that describes how to parse the
    grammar description syntax.

    c                 C   s|  t ddd�}tt dƒ|dd�}t|dd�}ttdƒ|dd�}tt d	ƒ|d
d�}t|t|ƒdd�}tt dƒ|dd�}	t ddddd�}
t|
|dd�}ttdƒ|t ddd�|dd�}t|||dd�}t||	dd�}t||dd�}ttdƒ||dd�}|f|j |_t|t|ƒdd�}ttdƒ||dd�}t|t|ƒdd�}t|||d d�}t|||d!d�}t|t|ƒd"d�}| |¡}t	ƒ  
|¡S )#zÒReturn the rules for parsing the grammar definition syntax.

        Return a 2-tuple: a dict of rule names pointing to their expressions,
        and then the top-level expression for the first rule.

        z	#[^\r\n]*Úcomment©Únamez\s+ÚmeaninglessnessÚ_Ú=Úequalsz[a-zA-Z_][a-zA-Z_0-9]*ÚlabelÚ	referencez[*+?]Ú
quantifierzu?r?"[^"\\]*(?:\\.[^"\\]*)*"TÚspaceless_literal)Úignore_caseÚdot_allrY   ÚliteralÚ~z
[ilmsuxa]*)rb   ÚregexÚatomÚ
quantifiedÚtermú!Únot_termÚsequenceú/Úor_termÚoredr   Úruler$   )r   r	   r   r   r   r   Úmembersr   r2   r3   r4   )r   Úrule_syntaxr6   rW   rZ   r[   r]   r^   r_   r`   ra   rd   rf   rg   rh   ri   rk   rl   rn   ro   r   rp   r$   Ú	rule_treer   r   r   r    ¥   s@   	ý
ü
z,BootstrappingGrammar._expressions_from_rulesNrU   r   r   r   r   rV   œ   s    rV   a+  
    # Ignored things (represented by _) are typically hung off the end of the
    # leafmost kinds of nodes. Literals like "/" count as leaves.

    rules = _ rule*
    rule = label equals expression
    equals = "=" _
    literal = spaceless_literal _

    # So you can't spell a regex like `~"..." ilm`:
    spaceless_literal = ~"u?r?b?\"[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*\""is /
                        ~"u?r?b?'[^'\\\\]*(?:\\\\.[^'\\\\]*)*'"is

    expression = ored / sequence / term
    or_term = "/" _ term
    ored = term or_term+
    sequence = term term+
    not_term = "!" term _
    lookahead_term = "&" term _
    term = not_term / lookahead_term / quantified / atom
    quantified = atom quantifier
    atom = reference / literal / regex / parenthesized
    regex = "~" spaceless_literal ~"[ilmsuxa]*"i _
    parenthesized = "(" _ expression ")" _
    quantifier = ~r"[*+?]|\{\d*,\d+\}|\{\d+,\d*\}|\{\d+\}" _
    reference = label !equals

    # A subsequent equal sign is the only thing that distinguishes a label
    # (which begins a new rule) from a reference (which is just a pointer to a
    # rule defined somewhere else):
    label = ~"[a-zA-Z_][a-zA-Z_0-9]*(?![\"'])" _

    # _ = ~r"\s*(?:#[^\r\n]*)?\s*"
    _ = meaninglessness*
    meaninglessness = ~r"\s+" / comment
    comment = ~r"#[^\r\n]*"
    c                   @   s$   e Zd ZdZdZdd„ Zdd„ ZdS )ÚLazyReferencezMA lazy reference to a rule, which we resolve after grokking all the
    rulesr   c                 C   sn   t ƒ }| }	 ||v rtd| j› d| › d�ƒ‚| |¡ z|t|ƒ }W n ty.   t|ƒ‚w t|tƒs6|S q)aÚ  
        Traverse the rule map following top-level lazy references,
        until we reach a cycle (raise an error) or a concrete expression.

        For example, the following is a circular reference:
            foo = bar
            baz = foo2
            foo2 = foo

        Note that every RHS of a grammar rule _must_ be either a
        LazyReference or a concrete expression, so the reference chain will
        eventually either terminate or find a cycle.
        TzCircular Reference resolving r\   Ú.)	Úsetr   rY   ÚaddrK   ÚKeyErrorr   Ú
isinstancert   )r   Úrule_mapÚseenÚcurr   r   r   Úresolve_refs	  s   
ÿ
özLazyReference.resolve_refsc                 C   s   d|  S )Nz<LazyReference to %s>r   r   r   r   r   Ú_as_rhs&  s   zLazyReference._as_rhsN)rM   rN   rO   rP   rY   r}   r~   r   r   r   r   rt     s
    rt   c                   @   s´   e Zd ZdZeeedœZej	 Z
 ZZd&dd„Zdd„ Zdd	„ Zd
d„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zd d!„ Zd"d#„ Zd$d%„ ZdS )'r3   zãTurns a parse tree of a grammar definition into a map of ``Expression``
    objects

    This is the magic piece that breathes life into a parsed bunch of parse
    rules, allowing them to go forth and parse other things.

    )Ú?Ú*ú+Nc                 C   s   |pi | _ d| _dS )zžConstruct.

        :arg custom_rules: A dict of {rule name: expression} holding custom
            rules which will take precedence over the others

        N)r6   Ú_last_literal_node_and_type)r   r6   r   r   r   r"   6  s   

zRuleVisitor.__init__c                 C   s   |\}}}}}|S )z’Treat a parenthesized subexpression as just its contents.

        Its position in the tree suffices to maintain its grouping semantics.

        r   )r   ÚnodeÚparenthesizedÚ
left_parenr[   r   Úright_parenr   r   r   Úvisit_parenthesized@  s   zRuleVisitor.visit_parenthesizedc                 C   ó   |\}}|S )z5Turn a quantifier into just its symbol-matching node.r   )r   rƒ   r`   Úsymbolr[   r   r   r   Úvisit_quantifierI  ó   zRuleVisitor.visit_quantifierc                 C   s¢   |\}}z	| j |j |ƒW S  tyP   |jdd…  d¡}t|ƒdkr-t|d ƒ }}n|d r7t|d ƒnd}|d rCt|d ƒntdƒ}t|||d� Y S w )Né   éÿÿÿÿú,r   Úinf)ÚminÚmax)Úquantifier_classesr=   rx   ÚsplitÚlenÚintÚfloatr   )r   rƒ   rh   rg   r`   Ú	min_matchÚ	max_matchr   r   r   Úvisit_quantifiedN  s   øzRuleVisitor.visit_quantifiedc                 C   ó   |\}}}t |ƒS r@   )r
   )r   rƒ   Úlookahead_termÚ	ampersandri   r[   r   r   r   Úvisit_lookahead_term\  ó   
z RuleVisitor.visit_lookahead_termc                 C   rš   r@   )r   )r   rƒ   rk   Úexclamationri   r[   r   r   r   Úvisit_not_term`  rž   zRuleVisitor.visit_not_termc                 C   s   |\}}}||_ |S )z.Assign a name to the Expression and return it.rX   )r   rƒ   rp   r^   r]   r   r   r   r   Ú
visit_ruled  s   
zRuleVisitor.visit_rulec                 C   ó   |\}}t |g|¢R Ž S )zfA parsed Sequence looks like [term node, OneOrMore node of
        ``another_term``s]. Flatten it out.)r   )r   rƒ   rl   ri   Úother_termsr   r   r   Úvisit_sequencej  s   zRuleVisitor.visit_sequencec                 C   r¢   r@   )r	   )r   rƒ   ro   Ú
first_termr£   r   r   r   Ú
visit_oredp  s   zRuleVisitor.visit_oredc                 C   s   |\}}}|S )z�Return just the term from an ``or_term``.

        We already know it's going to be ored, from the containing ``ored``.

        r   )r   rƒ   rn   Úslashr[   ri   r   r   r   Úvisit_or_termt  s   
zRuleVisitor.visit_or_termc                 C   s   |\}}|j S )z#Turn a label into a unicode string.)r=   )r   rƒ   r^   rY   r[   r   r   r   Úvisit_label}  s   zRuleVisitor.visit_labelc                 C   s   |\}}t |ƒS )zjStick a :class:`LazyReference` in the tree as a placeholder.

        We resolve them all later.

        )rt   )r   rƒ   r_   r^   Ú
not_equalsr   r   r   Úvisit_reference‚  s   zRuleVisitor.visit_referencec              
   C   sP   |\}}}}|j  ¡ }|j}t|d|v d|v d|v d|v d|v d|v d|v d�S )	zReturn a ``Regex`` expression.ÚIÚLÚMÚSÚUÚXÚA)rb   ÚlocaleÚ	multilinerc   ÚunicodeÚverboseÚascii)r=   Úupperrd   r   )r   rƒ   rf   Útilderd   Úflagsr[   Úpatternr   r   r   Úvisit_regex‹  s   

úzRuleVisitor.visit_regexc                 C   sj   t |jƒ}| jr*| j\}}|t|ƒkr*ttd|j› d|› d|j› dt|ƒ› d�	ƒƒ‚|t|ƒf| _t|ƒS )z<Turn a string literal into a ``Literal`` that recognizes it.z                    Found z (z) and zq) string literals.
                    All strings in a single grammar must be of the same type.
                )r   r=   r‚   Útyper   r   r   )r   ra   Úvisited_childrenÚliteral_valueÚ	last_nodeÚ	last_typer   r   r   Úvisit_spaceless_literal™  s   

ÿÿÿÿz#RuleVisitor.visit_spaceless_literalc                 C   rˆ   )z6Pick just the literal out of a literal-and-junk combo.r   )r   rƒ   rd   ra   r[   r   r   r   Úvisit_literal©  r‹   zRuleVisitor.visit_literalc                 C   s   |p|S )a   Replace childbearing nodes with a list of their children; keep
        others untouched.

        For our case, if a node has children, only the children are important.
        Otherwise, keep the node around for (for example) the flags of the
        regex rule. Most of these kept-around nodes are subsequently thrown
        away by the other visitor methods.

        We can't simply hang the visited children off the original node; that
        would be disastrous if the node occurred in more than one place in the
        tree.

        r   )r   rƒ   r¾   r   r   r   Úgeneric_visit®  s   zRuleVisitor.generic_visitc                 C   sz   |\}}t dd„ |D ƒƒ}| | j¡ t| ¡ ƒD ]\}}t|dƒr)| |¡||< q|t|tƒr:|r:||d j fS dfS )aµ  Collate all the rules into a map. Return (map, default rule).

        The default rule is the first one. Or, if you have more than one rule
        of that name, it's the last-occurring rule of that name. (This lets you
        override the default rule when you extend a grammar.) If there are no
        string-based rules, the default rule is None, because the custom rules,
        due to being kwarg-based, are unordered.

        c                 s   s   � | ]}|j |fV  qd S r@   rX   rA   r   r   r   rC   Î  s   € z*RuleVisitor.visit_rules.<locals>.<genexpr>r}   r   N)	r   Úupdater6   Úlistr   Úhasattrr}   ry   rY   )r   rƒ   Ú
rules_listr[   r$   rz   rY   rp   r   r   r   Úvisit_rules¾  s   

€ÿÿÿzRuleVisitor.visit_rulesr@   )rM   rN   rO   rP   r   r   r   r’   r   Ú
lift_childÚvisit_expressionÚ
visit_termÚ
visit_atomr"   r‡   rŠ   r™   r�   r    r¡   r¤   r¦   r¨   r©   r«   r¼   rÂ   rÃ   rÄ   rÉ   r   r   r   r   r3   *  s*    

			r3   c                   @   s    e Zd ZdZdd„ Zdd„ ZdS )rT   znA visitor which builds expression trees meant to work on sequences of
    pre-lexed tokens rather than stringsc                 C   s   t t|jƒƒS )zrTurn a string literal into a ``TokenMatcher`` that matches
        ``Token`` objects by their ``type`` attributes.)r   r   r=   )r   ra   r¾   r   r   r   rÂ   ç  s   z(TokenRuleVisitor.visit_spaceless_literalc                 C   s   |\}}}}t dƒ‚)NzsRegexes do not make sense in TokenGrammars, since TokenGrammars operate on pre-lexed tokens rather than characters.)r   )r   rƒ   rf   r¹   rd   rº   r[   r   r   r   r¼   ì  s   zTokenRuleVisitor.visit_regexN)rM   rN   rO   rP   rÂ   r¼   r   r   r   r   rT   ã  s    rT   N)#rP   Úcollectionsr   Útextwrapr   Úparsimonious.exceptionsr   r   Úparsimonious.expressionsr   r   r   r	   r
   r   r   r   r   r   r   r   r   Úparsimonious.nodesr   Úparsimonious.utilsr   r   rS   rV   rr   rK   rt   r3   rT   r1   r   r   r   r   Ú<module>   s"    <~@'' :