
    gc                     x    d dl mZ d dlmZ d dlmZmZ  G d de      Z G d de      Zd Z	e
d	k(  r e	        y
y
)    )Nonterminal)ParserI)ImmutableTreeTreec                   t    e Zd ZdZddZd Zd Zd Zd ZddZ	d	 Z
dd
ZddZd Zd Zd Zd Zd ZddZy)RecursiveDescentParseraq  
    A simple top-down CFG parser that parses texts by recursively
    expanding the fringe of a Tree, and matching it against a
    text.

    ``RecursiveDescentParser`` uses a list of tree locations called a
    "frontier" to remember which subtrees have not yet been expanded
    and which leaves have not yet been matched against the text.  Each
    tree location consists of a list of child indices specifying the
    path from the root of the tree to a subtree or a leaf; see the
    reference documentation for Tree for more information
    about tree locations.

    When the parser begins parsing a text, it constructs a tree
    containing only the start symbol, and a frontier containing the
    location of the tree's root node.  It then extends the tree to
    cover the text, using the following recursive procedure:

      - If the frontier is empty, and the text is covered by the tree,
        then return the tree as a possible parse.
      - If the frontier is empty, and the text is not covered by the
        tree, then return no parses.
      - If the first element of the frontier is a subtree, then
        use CFG productions to "expand" it.  For each applicable
        production, add the expanded subtree's children to the
        frontier, and recursively find all parses that can be
        generated by the new tree and frontier.
      - If the first element of the frontier is a token, then "match"
        it against the next token from the text.  Remove the token
        from the frontier, and recursively find all parses that can be
        generated by the new tree and frontier.

    :see: ``nltk.grammar``
    c                      || _         || _        y)a  
        Create a new ``RecursiveDescentParser``, that uses ``grammar``
        to parse texts.

        :type grammar: CFG
        :param grammar: The grammar used to parse texts.
        :type trace: int
        :param trace: The level of tracing that should be used when
            parsing a text.  ``0`` will generate no tracing output;
            and higher numbers will produce more verbose tracing
            output.
        N)_grammar_trace)selfgrammartraces      P/var/www/openai/venv/lib/python3.12/site-packages/nltk/parse/recursivedescent.py__init__zRecursiveDescentParser.__init__5   s          c                     | j                   S Nr
   r   s    r   r   zRecursiveDescentParser.grammarE   s    }}r   c                     t        |      }| j                  j                  |       | j                  j                         j	                         }t        |g       }dg}| j                  r| j                  |||       | j                  |||      S N )	listr
   check_coveragestartsymbolr   r   _trace_start_parse)r   tokensr   initial_treefrontiers        r   parsezRecursiveDescentParser.parseH   sz     f$$V, ##%,,.E24;;lHf={{6<::r   c              #     K   t        |      dk(  r1t        |      dk(  r#| j                  r| j                  ||       | yt        |      dk(  r | j                  r| j                  ||       yyt	        ||d      t
              r| j                  |||      E d{    y| j                  |||      E d{    y7 !7 w)a2  
        Recursively expand and match each elements of ``tree``
        specified by ``frontier``, to cover ``remaining_text``.  Return
        a list of all parses found.

        :return: An iterator of all parses that can be generated by
            matching and expanding the elements of ``tree``
            specified by ``frontier``.
        :rtype: iter(Tree)
        :type tree: Tree
        :param tree: A partial structure for the text that is
            currently being parsed.  The elements of ``tree``
            that are specified by ``frontier`` have not yet been
            expanded or matched.
        :type remaining_text: list(str)
        :param remaining_text: The portion of the text that is not yet
            covered by ``tree``.
        :type frontier: list(tuple(int))
        :param frontier: A list of the locations within ``tree`` of
            all subtrees that have not yet been expanded, and all
            leaves that have not yet been matched.  This list sorted
            in left-to-right order of location within the tree.
        r   N)lenr   _trace_succeed_trace_backtrack
isinstancer   _expand_matchr   remaining_texttreer!   s       r   r   zRecursiveDescentParser._parseW   s     6 ~!#H(:{{##D(3J ]a{{%%dH5  Xa[)40||ND(CCC {{>4BBB	 D Cs$   BCB>C8C 9C Cc              #   Z  K   ||d      }t        |      dkD  rl||d   k(  rd|j                  d      }|d   ||d   <   | j                  r| j                  ||dd |d          | j	                  |dd ||dd       E d{    y| j                  r| j                  |||dd        yy7 )w)a  
        :rtype: iter(Tree)
        :return: an iterator of all parses that can be generated by
            matching the first element of ``frontier`` against the
            first token in ``rtext``.  In particular, if the first
            element of ``frontier`` has the same type as the first
            token in ``rtext``, then substitute the token into
            ``tree``; and return all parses that can be generated by
            matching and expanding the remaining elements of
            ``frontier``.  If the first element of ``frontier`` does not
            have the same type as the first token in ``rtext``, then
            return empty list.

        :type tree: Tree
        :param tree: A partial structure for the text that is
            currently being parsed.  The elements of ``tree``
            that are specified by ``frontier`` have not yet been
            expanded or matched.
        :type rtext: list(str)
        :param rtext: The portion of the text that is not yet
            covered by ``tree``.
        :type frontier: list of tuple of int
        :param frontier: A list of the locations within ``tree`` of
            all subtrees that have not yet been expanded, and all
            leaves that have not yet been matched.
        r   Tdeep   N)r$   copyr   _trace_matchr   r&   )r   rtextr,   r!   	tree_leafnewtrees         r   r)   zRecursiveDescentParser._match   s     8 !%	u:>i583 iiTi*G#(8GHQK {{!!'8AB<qB{{59gx|DDD {{%%dHeBQi@  Es   A=B+?B) *B+Nc           	   #   0  K   || j                   j                         }n|g}|D ]  }|j                         j                         }|||d      j	                         k(  s;| j                  |      }|d   dk(  r|}n|j                  d      }|||d   <   t        t        |j                                     D 	cg c]  }	|d   |	fz    }
}	| j                  r| j                  ||
|       | j                  |||
|dd z         E d{     yc c}	w 7 w)a(  
        :rtype: iter(Tree)
        :return: An iterator of all parses that can be generated by
            expanding the first element of ``frontier`` with
            ``production``.  In particular, if the first element of
            ``frontier`` is a subtree whose node type is equal to
            ``production``'s left hand side, then add a child to that
            subtree for each element of ``production``'s right hand
            side; and return all parses that can be generated by
            matching and expanding the remaining elements of
            ``frontier``.  If the first element of ``frontier`` is not a
            subtree whose node type is equal to ``production``'s left
            hand side, then return an empty list.  If ``production`` is
            not specified, then return a list of all parses that can
            be generated by expanding the first element of ``frontier``
            with *any* CFG production.

        :type tree: Tree
        :param tree: A partial structure for the text that is
            currently being parsed.  The elements of ``tree``
            that are specified by ``frontier`` have not yet been
            expanded or matched.
        :type remaining_text: list(str)
        :param remaining_text: The portion of the text that is not yet
            covered by ``tree``.
        :type frontier: list(tuple(int))
        :param frontier: A list of the locations within ``tree`` of
            all subtrees that have not yet been expanded, and all
            leaves that have not yet been matched.
        Nr   r   Tr.   r0   )r
   productionslhsr   label_production_to_treer1   ranger$   rhsr   _trace_expandr   )r   r+   r,   r!   
productionr7   r8   subtreer5   inew_frontiers              r   r(   zRecursiveDescentParser._expand   s&    @ --335K%,K%J.."))+Cd8A;'--//22:>A;"$%G"iiTi2G+2GHQK(05c*..:J6K0L 0L1HQK1$&0L    ;;&&wjI;;"G\HQRL-H   & 
s%   AD AD:D
=DDDc                    g }|j                         D ]M  }t        |t              r*|j                  t	        |j                         g              =|j                  |       O t	        |j                         j                         |      S )a  
        :rtype: Tree
        :return: The Tree that is licensed by ``production``.
            In particular, given the production ``[lhs -> elt[1] ... elt[n]]``
            return a tree that has a node ``lhs.symbol``, and
            ``n`` children.  For each nonterminal element
            ``elt[i]`` in the production, the tree token has a
            childless subtree with node value ``elt[i].symbol``; and
            for each terminal element ``elt[j]``, the tree token has
            a leaf token with type ``elt[j]``.

        :param production: The CFG production that licenses the tree
            token that should be returned.
        :type production: Production
        )r<   r'   r   appendr   r   r8   )r   r>   childrenelts       r   r:   z*RecursiveDescentParser._production_to_tree   sj      >>#C#{+SZZ\2 67 $ $ JNN$++-x88r   c                     || _         y)aP  
        Set the level of tracing output that should be generated when
        parsing a text.

        :type trace: int
        :param trace: The trace level.  A trace level of ``0`` will
            generate no tracing output; and higher trace levels will
            produce more verbose tracing output.
        :rtype: None
        N)r   )r   r   s     r   r   zRecursiveDescentParser.trace   s     r   c                    |dk(  rt        dd       t        |t              rt        |      dk(  r-t        t	        t        |j                                     d       t        t        |            D ]9  }|!||d   k(  r| j                  ||   |dd        &| j                  ||          ; yt        t	        |      d       y)z
        Print trace output displaying the fringe of ``tree``.  The
        fringe of ``tree`` consists of all of its leaves and all of
        its childless subtrees.

        :rtype: None
        r   * endr   Nr0   )	printr'   r   r$   reprr   r9   r;   _trace_fringe)r   r,   treelocr@   s       r   rN   z$RecursiveDescentParser._trace_fringe  s     b=#3dD!4yA~d;tzz|453?3t9%&1
?&&tAw<&&tAw/	 & $t*#&r   c                     | j                   dk(  rt        d|z  d       nt        dd       t        |      dkD  r| j                  ||d          n| j                  |       t        d       y)	z
        Print trace output displaying the parser's current state.

        :param operation: A character identifying the operation that
            generated the current state.
        :rtype: None
           z  %c [rI   rJ   z    [r   ]N)r   rL   r$   rN   )r   r,   r!   	operations       r   _trace_treez"RecursiveDescentParser._trace_tree!  s^     ;;!(Y&C0's#x=1tXa[1t$c
r   c                     t        ddj                  |      z         | j                  dkD  rt        d       | j                  dkD  r| j                  ||d       y y )Nz
Parsing %rrI   rQ   zStart:r0   )rL   joinr   rT   )r   r,   r!   texts       r   r   z#RecursiveDescentParser._trace_start3  sK    lSXXd^+,;;?(O;;?T8S1 r   c                     | j                   dkD  rt        d|z         | j                   dkD  r| j                  ||d       y y )NrQ   z
Expand: %sr0   Er   rL   rT   )r   r,   r!   r>   s       r   r=   z$RecursiveDescentParser._trace_expand:  s<    ;;?,+,;;?T8S1 r   c                     | j                   dkD  rt        d|z         | j                   dkD  r| j                  ||d       y y )NrQ   z	Match: %rr0   MrZ   )r   r,   r!   toks       r   r2   z#RecursiveDescentParser._trace_match@  s<    ;;?+#$;;?T8S1 r   c                     | j                   dkD  rt        d       | j                   dk(  rt        d|z         | j                   dkD  r| j                  ||d       y y )NrQ   zGOOD PARSE:r0   zFound a parse:
%s+rZ   )r   r,   r!   s      r   r%   z%RecursiveDescentParser._trace_succeedF  sQ    ;;?- ;;!&-.;;?T8S1 r   c                 b    | j                   dkD  r |rt        d|d   z         y t        d       y y )NrQ   zBacktrack: %r match failedr   	Backtrack)r   rL   )r   r,   r!   tokss       r   r&   z'RecursiveDescentParser._trace_backtrackN  s/    ;;?2T!W<=k"	 r   r   r   )rQ   )__name__
__module____qualname____doc__r   r   r"   r   r)   r(   r:   r   rN   rT   r   r=   r2   r%   r&   r   r   r   r   r      sX    !F ;+CZ(AT5n92',$2222#r   r   c                        e Zd ZdZd fd	Zd Zd Zd Zd Zd Z	d Z
d	 Zdd
Zd Zd Zd Zd Zd Zd Zd Zd Zd Z xZS )SteppingRecursiveDescentParsera  
    A ``RecursiveDescentParser`` that allows you to step through the
    parsing process, performing a single operation at a time.

    The ``initialize`` method is used to start parsing a text.
    ``expand`` expands the first element on the frontier using a single
    CFG production, and ``match`` matches the first element on the
    frontier against the next text token. ``backtrack`` undoes the most
    recent expand or match operation.  ``step`` performs a single
    expand, match, or backtrack operation.  ``parses`` returns the set
    of parses that have been found by the parser.

    :ivar _history: A list of ``(rtext, tree, frontier)`` tripples,
        containing the previous states of the parser.  This history is
        used to implement the ``backtrack`` operation.
    :ivar _tried_e: A record of all productions that have been tried
        for a given tree.  This record is used by ``expand`` to perform
        the next untried production.
    :ivar _tried_m: A record of what tokens have been matched for a
        given tree.  This record is used by ``step`` to decide whether
        or not to match a token.
    :see: ``nltk.grammar``
    c                     t         |   ||       d | _        d | _        dg| _        i | _        i | _        g | _        g | _        y r   )	superr   _rtext_tree	_frontier_tried_e_tried_m_history_parses)r   r   r   	__class__s      r   r   z'SteppingRecursiveDescentParser.__init__r  sE    %(
r   c                 L    |j                         }t        j                  |      S r   )r1   r   convert)r   r,   cs      r   _freezez&SteppingRecursiveDescentParser._freeze~  s     IIK $$Q''r   c                     t        |      }| j                  |       | j                         	 | j                         | j                         S r   )r   
initializestepparses)r   r   s     r   r"   z$SteppingRecursiveDescentParser.parse  s@    fiik% iik%{{}r   c                 H   || _         | j                  j                         j                         }t	        |g       | _        dg| _        i | _        i | _        g | _	        g | _
        | j                  r2| j                  | j
                  | j                  | j                          yy)z
        Start parsing a given text.  This sets the parser's tree to
        the start symbol, its frontier to the root node, and its
        remaining text to ``token['SUBTOKENS']``.
        r   N)rl   r
   r   r   r   rm   rn   ro   rp   rq   rr   r   r   )r   r   r   s      r   ry   z)SteppingRecursiveDescentParser.initialize  s     ##%,,.%_
;;djj$..$++F r   c                     | j                   S )z}
        :return: The portion of the text that is not yet covered by the
            tree.
        :rtype: list(str)
        )rl   r   s    r   r+   z-SteppingRecursiveDescentParser.remaining_text  s     {{r   c                     | j                   S )z
        :return: A list of the tree locations of all subtrees that
            have not yet been expanded, and all leaves that have not
            yet been matched.
        :rtype: list(tuple(int))
        )rn   r   s    r   r!   z'SteppingRecursiveDescentParser.frontier  s     ~~r   c                     | j                   S )z
        :return: A partial structure for the text that is
            currently being parsed.  The elements specified by the
            frontier have not yet been expanded or matched.
        :rtype: Tree
        )rm   r   s    r   r,   z#SteppingRecursiveDescentParser.tree  s     zzr   c                     | j                         r| j                         }||S | j                         }||S | j                         r'| j	                  | j
                  | j                         yy)aw  
        Perform a single parsing operation.  If an untried match is
        possible, then perform the match, and return the matched
        token.  If an untried expansion is possible, then perform the
        expansion, and return the production that it is based on.  If
        backtracking is possible, then backtrack, and return True.
        Otherwise, return None.

        :return: None if no operation was performed; a token if a match
            was performed; a production if an expansion was performed;
            and True if a backtrack operation was performed.
        :rtype: Production or String or bool
        NT)untried_matchmatchexpand	backtrackr&   rm   rn   )r   tokenr>   s      r   rz   z#SteppingRecursiveDescentParser.step  sk     JJLE  [[]
! >>!!$**dnn= r   c                    t        | j                        dk(  ryt        | j                  | j                  d      t              sy|| j                         }n|g}g }|D ]  }| j                  j                  | j                  | j                        g       j                  |       | j                  | j                  | j                  | j                  |      D ]  }|c c S   y)a  
        Expand the first element of the frontier.  In particular, if
        the first element of the frontier is a subtree whose node type
        is equal to ``production``'s left hand side, then add a child
        to that subtree for each element of ``production``'s right hand
        side.  If ``production`` is not specified, then use the first
        untried expandable production.  If all expandable productions
        have been tried, do nothing.

        :return: The production used to expand the frontier, if an
           expansion was performed.  If no expansion was performed,
           return None.
        :rtype: Production or None
        r   N)r$   rn   r'   rm   r   untried_expandable_productionsro   
setdefaultrw   rC   r(   rl   )r   r>   r7   r{   prod_results         r   r   z%SteppingRecursiveDescentParser.expand  s    " t~~!#$**T^^A%67> ==?K%,KDMM$$T\\$**%=rBII$O  <<TZZQUV W   r   c                    | j                   d   }| j                  j                  | j                  | j                        g       j                  |       t        | j                        dk(  ryt        | j                  | j                  d      t              ry| j                  | j                   | j                  | j                        D ]  }| j                  d   d   d   c S  y)ap  
        Match the first element of the frontier.  In particular, if
        the first element of the frontier has the same type as the
        next text token, then substitute the text token into the tree.

        :return: The token matched, if a match operation was
            performed.  If no match was performed, return None
        :rtype: str or None
        r   N)rl   rp   r   rw   rm   rC   r$   rn   r'   r   r)   rq   )r   r]   r   s      r   r   z$SteppingRecursiveDescentParser.match   s     kk!n  djj!92>EEcJ t~~!#djj!23T:{{4;;

DNNKG==$Q'** L r   c                     t        | j                        dk(  ry| j                  j                         \  | _        | _        | _        y)a|  
        Return the parser to its state before the most recent
        match or expand operation.  Calling ``undo`` repeatedly return
        the parser to successively earlier states.  If no match or
        expand operations have been performed, ``undo`` will make no
        changes.

        :return: true if an operation was successfully undone.
        :rtype: bool
        r   FT)r$   rq   poprl   rm   rn   r   s    r   r   z(SteppingRecursiveDescentParser.backtrack  s:     t}}"48MM4E4E4G1dj$.r   c                 z   t        | j                        dk(  rg S | j                  | j                  d      }t        | j                        dk(  st        |t              sg S | j
                  j                         D cg c]3  }|j                         j                         |j                         k(  r|5 c}S c c}w )z
        :return: A list of all the productions for which expansions
            are available for the current parser state.
        :rtype: list(Production)
        r   )
r$   rn   rm   r'   r   r
   r7   r8   r   r9   )r   frontier_childps      r   expandable_productionsz5SteppingRecursiveDescentParser.expandable_productions*  s     t~~!#IDNN1$56t~~!#:nd+KI ]]..0
0uuw~~>#7#7#99 0
 	
 
s   =8B8c                     | j                   j                  | j                  | j                        g       }| j	                         D cg c]	  }||vs| c}S c c}w )z
        :return: A list of all the untried productions for which
            expansions are available for the current parser state.
        :rtype: list(Production)
        )ro   getrw   rm   r   )r   tried_expansionsr   s      r   r   z=SteppingRecursiveDescentParser.untried_expandable_productions=  sS      ==,,T\\$**-ErJ668V8aAEU<U8VVVs   	AAc                     t        | j                        dk(  ry| j                  j                  | j	                  | j
                        g       }| j                  d   |vS )z
        :return: Whether the first element of the frontier is a token
            that has not yet been matched.
        :rtype: bool
        r   F)r$   rl   rp   r   rw   rm   )r   tried_matchess     r   r   z,SteppingRecursiveDescentParser.untried_matchG  sN     t{{q ))$,,tzz*BBG{{1~]22r   c                 f    t        | j                        dk(  xr t        | j                        dk(  S )z{
        :return: Whether the parser's current state represents a
            complete parse.
        :rtype: bool
        r   )r$   rn   rl   r   s    r   currently_completez1SteppingRecursiveDescentParser.currently_completeS  s+     4>>"a'AC,<,AAr   c                 d   | j                   j                  | j                  | j                  | j                  f       || _        || _        || _        t        |      dk(  rOt        |      dk(  rA| j                  j                  |       | j                  | j                  | j                         dgS )a  
        A stub version of ``_parse`` that sets the parsers current
        state to the given arguments.  In ``RecursiveDescentParser``,
        the ``_parse`` method is used to recursively continue parsing a
        text.  ``SteppingRecursiveDescentParser`` overrides it to
        capture these recursive calls.  It records the parser's old
        state in the history (to allow for backtracking), and updates
        the parser's new state using the given arguments.  Finally, it
        returns ``[1]``, which is used by ``match`` and ``expand`` to
        detect whether their operations were successful.

        :return: ``[1]``
        :rtype: list of int
        r   r0   )rq   rC   rl   rm   rn   r$   rr   r%   r*   s       r   r   z%SteppingRecursiveDescentParser._parse[  s     	dkk4::t~~FG$
! x=A#n"5":LL%

DNN;s
r   c                 ,    t        | j                        S )z
        :return: An iterator of the parses that have been found by this
            parser so far.
        :rtype: list of Tree
        )iterrr   r   s    r   r{   z%SteppingRecursiveDescentParser.parsesv  s     DLL!!r   c                     || _         y)z~
        Change the grammar used to parse texts.

        :param grammar: The new grammar.
        :type grammar: CFG
        Nr   )r   r   s     r   set_grammarz*SteppingRecursiveDescentParser.set_grammar~  s      r   rc   r   )rd   re   rf   rg   r   rw   r"   ry   r+   r!   r,   rz   r   r   r   r   r   r   r   r   r{   r   __classcell__)rs   s   @r   ri   ri   Y  sg    0(G$B&P4 
&W
3B6" r   ri   c                      ddl m} m} | j                  d      }|j	                         D ]  }t        |        dj                         }|j                  |d      }|j                  |      D ]  }t        |        y)z:
    A demonstration of the recursive descent parser.
    r   )CFGr"   z
    S -> NP VP
    NP -> Det N | Det N PP
    VP -> V NP | V NP PP
    PP -> P NP
    NP -> 'I'
    N -> 'man' | 'park' | 'telescope' | 'dog'
    Det -> 'the' | 'a'
    P -> 'in' | 'with'
    V -> 'saw'
    zI saw a man in the parkrQ   )r   N)nltkr   r"   
fromstringr7   rL   splitr   )r   r"   r   r   sentparserr   s          r   demor     su    
  nn
	G ##%d & %**,D))');F\\$a  r   __main__N)nltk.grammarr   nltk.parse.apir   	nltk.treer   r   r   ri   r   rd   r   r   r   <module>r      sH    % " )B#W B#P
l %; l h	< zF r   