
    /hc                     z    S SK Jr  S SKJr  S SKJrJr   " S S\5      r " S S\5      rS r	\
S	:X  a  \	" 5         g
g
)    )Nonterminal)ParserI)ImmutableTreeTreec                       \ rS rSrSrSS jrS rS rS rS r	SS	 jr
S
 rSS jrSS jrS rS rS rS rS rSS jrSrg)RecursiveDescentParser   a  
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                     Xl         X l        g)ac  
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      S/var/www/auris/envauris/lib/python3.13/site-packages/nltk/parse/recursivedescent.py__init__RecursiveDescentParser.__init__5   s          c                     U R                   $ Nr   r   s    r   r   RecursiveDescentParser.grammarE   s    }}r   c                 &   [        U5      nU R                  R                  U5        U R                  R                  5       R	                  5       n[        U/ 5      nS/nU R                  (       a  U R                  X4U5        U R                  XU5      $ N )	listr   check_coveragestartsymbolr   r   _trace_start_parse)r   tokensr   initial_treefrontiers        r   parseRecursiveDescentParser.parseH   sv     f$$V, ##%,,.E24;;lf={{6::r   c              #     #    [        U5      S:X  a6  [        U5      S:X  a'  U R                  (       a  U R                  X#5        Uv   g[        U5      S:X  a$  U R                  (       a  U R                  X#5        gg[	        X#S      [
        5      (       a  U R                  XU5       Sh  vN   gU R                  XU5       Sh  vN   g N  N7f)a  
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"   RecursiveDescentParser._parseW   s     6 ~!#H(:{{##D3J ]a{{%%d5  a[)400||N(CCC {{>BBB	 D Cs$   B(C*C+CCCCc              #   `  #    X#S      n[        U5      S:  ak  XAS   :X  ac  UR                  SS9nUS   XSS   '   U R                  (       a  U R                  XSSS US   5        U R	                  USS XSSS 5       Sh  vN   gU R                  (       a  U R                  X#USS 5        gg N-7f)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   rtextr1   r%   	tree_leafnewtrees         r   r.   RecursiveDescentParser._match   s     8 !%	u:>i83 iiTi*G#(8GQK {{!!'AB<qB{{59g|DDD {{%%deBQi@  Es   A<B.>B,?.B.Nc           	   #   :  #    Uc  U R                   R                  5       nOU/nU H  nUR                  5       R                  5       nXbUS      R	                  5       :X  d  M<  U R                  U5      nUS   S:X  a  UnOUR                  SS9nXxUS   '   [        [        UR                  5       5      5       V	s/ s H  oS   U	4-   PM     n
n	U R                  (       a  U R                  XU5        U R                  XXSS -   5       Sh  vN   M     gs  sn	f  N7f)aH  
: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   Tr4   r6   )r   productionslhsr    label_production_to_treer7   ranger)   rhsr   _trace_expandr"   )r   r0   r1   r%   
productionr>   r?   subtreer;   inew_frontiers              r   r-   RecursiveDescentParser._expand   s    @ --335K%,K%J.."))+C8A;'--//22:>A;"$%G"iiTi2G+2HQK(05c*..:J6K0L 0L1QK1$&0L    ;;&&wjI;;"\QRL-H   & 
s%   AD"AD9D?D
DDc                 &   / nUR                  5        HT  n[        U[        5      (       a+  UR                  [	        UR                  5       / 5      5        MC  UR                  U5        MV     [	        UR                  5       R                  5       U5      $ )aI  
: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
)rC   r,   r   appendr   r    r?   )r   rE   childrenelts       r   rA   *RecursiveDescentParser._production_to_tree   sm      >>#C#{++SZZ\2 67 $ $ JNN$++-x88r   c                     Xl         g)a  
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   RecursiveDescentParser.trace   s	     r   c                    US:X  a
  [        SSS9  [        U[        5      (       a  [        U5      S:X  a*  [        [	        [        UR                  5       5      5      SS9  [        [        U5      5       H:  nUb!  X2S   :X  a  U R                  X   USS 5        M'  U R                  X   5        M<     g[        [	        U5      SS9  g)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   Nr6   )	printr,   r   r)   reprr   r@   rB   _trace_fringe)r   r1   treelocrG   s       r   rX   $RecursiveDescentParser._trace_fringe  s     b=#3dD!!4yA~d;tzz|453?3t9%&1
?&&tw<&&tw/	 & $t*#&r   c                     U R                   S:X  a  [        SU-  SS9  O
[        SSS9  [        U5      S:  a  U R                  XS   5        OU R                  U5        [        S5        g)	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 [rS   rT   z    [r   ]N)r   rV   r)   rX   )r   r1   r%   	operations       r   _trace_tree"RecursiveDescentParser._trace_tree!  s\     ;;!(Y&C0's#x=1ta[1t$c
r   c                     [        SSR                  U5      -  5        U R                  S:  a  [        S5        U R                  S:  a  U R                  XS5        g g )Nz
Parsing %rrS   r\   zStart:r6   )rV   joinr   r_   )r   r1   r%   texts       r   r!   #RecursiveDescentParser._trace_start3  sI    lSXXd^+,;;?(O;;?TS1 r   c                     U R                   S:  a  [        SU-  5        U R                   S:  a  U R                  XS5        g g )Nr\   z
Expand: %sr6   Er   rV   r_   )r   r1   r%   rE   s       r   rD   $RecursiveDescentParser._trace_expand:  s:    ;;?,+,;;?TS1 r   c                     U R                   S:  a  [        SU-  5        U R                   S:  a  U R                  XS5        g g )Nr\   z	Match: %rr6   Mrg   )r   r1   r%   toks       r   r8   #RecursiveDescentParser._trace_match@  s:    ;;?+#$;;?TS1 r   c                     U R                   S:  a  [        S5        U R                   S:X  a  [        SU-  5        U R                   S:  a  U R                  XS5        g g )Nr\   zGOOD PARSE:r6   zFound a parse:
%s+rg   )r   r1   r%   s      r   r*   %RecursiveDescentParser._trace_succeedF  sO    ;;?- ;;!&-.;;?TS1 r   c                 n    U R                   S:  a%  U(       a  [        SUS   -  5        g [        S5        g g )Nr\   zBacktrack: %r match failedr   	Backtrack)r   rV   )r   r1   r%   tokss       r   r+   'RecursiveDescentParser._trace_backtrackN  s/    ;;?2T!W<=k"	 r   r   r   r   )r\   )__name__
__module____qualname____firstlineno____doc__r   r   r&   r"   r.   r-   rA   r   rX   r_   r!   rD   r8   r*   r+   __static_attributes__r   r   r   r   r      sX    !F ;+CZ(AT5n92',$2222#r   r   c                      ^  \ rS rSrSrSU 4S jjrS rS rS rS r	S r
S	 rS
 rSS jrS rS rS rS rS rS rS rS rS rSrU =r$ )SteppingRecursiveDescentParseriY  aB  
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U ]  X5        S U l        S U l        S/U l        0 U l        0 U l        / U l        / U l        g r   )	superr   _rtext_tree	_frontier_tried_e_tried_m_history_parses)r   r   r   	__class__s      r   r   'SteppingRecursiveDescentParser.__init__r  sC    (
r   c                 N    UR                  5       n[        R                  " U5      $ r   )r7   r   convert)r   r1   cs      r   _freeze&SteppingRecursiveDescentParser._freeze~  s     IIK $$Q''r   c                     [        U5      nU R                  U5        U R                  5       b   U R                  5       b  M  U R                  5       $ r   )r   
initializestepparses)r   r#   s     r   r&   $SteppingRecursiveDescentParser.parse  s@    fiik% iik%{{}r   c                 P   Xl         U R                  R                  5       R                  5       n[	        U/ 5      U l        S/U l        0 U l        0 U l        / U l	        / U l
        U R                  (       a2  U R                  U R
                  U R                  U R                   5        gg)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)r   r   r   r    r   r   r   r   r   r   r   r   r!   )r   r#   r   s      r   r   )SteppingRecursiveDescentParser.initialize  s     ##%,,.%_
;;djj$..$++F r   c                     U R                   $ )z]
:return: The portion of the text that is not yet covered by the
    tree.
:rtype: list(str)
)r   r   s    r   r0   -SteppingRecursiveDescentParser.remaining_text  s     {{r   c                     U R                   $ )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))
)r   r   s    r   r%   'SteppingRecursiveDescentParser.frontier  s     ~~r   c                     U R                   $ )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
)r   r   s    r   r1   #SteppingRecursiveDescentParser.tree  s     zzr   c                     U R                  5       (       a  U R                  5       nUb  U$ U R                  5       nUb  U$ U R                  5       (       a'  U R	                  U R
                  U R                  5        gg)a  
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+   r   r   )r   tokenrE   s      r   r   #SteppingRecursiveDescentParser.step  sq     JJLE  [[]
! >>!!$**dnn= r   c                    [        U R                  5      S:X  a  g[        U R                  U R                  S      [        5      (       d  gUc  U R                  5       nOU/n/ nU H  nU R                  R                  U R                  U R                  5      / 5      R                  U5        U R                  U R                  U R                  U R                  U5       H  nUs  s  $    M     g)a7  
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)   r   r,   r   r   untried_expandable_productionsr   
setdefaultr   rK   r-   r   )r   rE   r>   r   prod_results         r   r   %SteppingRecursiveDescentParser.expand  s    " t~~!#$**T^^A%67>> ==?K%,KDMM$$T\\$**%=rBII$O  <<TZZQUV W   r   c                    U R                   S   nU R                  R                  U R                  U R                  5      / 5      R                  U5        [        U R                  5      S:X  a  g[        U R                  U R                  S      [        5      (       a  gU R                  U R                   U R                  U R                  5       H  nU R                  S   S   S   s  $    g)a8  
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)r   r   r   r   r   rK   r)   r   r,   r   r.   r   )r   rk   r   s      r   r   $SteppingRecursiveDescentParser.match   s     kk!n  djj!92>EEcJ t~~!#djj!23T::{{4;;

DNNKG==$Q'** L r   c                     [        U R                  5      S:X  a  gU R                  R                  5       u  U l        U l        U l        g)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)   r   popr   r   r   r   s    r   r   (SteppingRecursiveDescentParser.backtrack  s:     t}}"48MM4E4E4G1dj$.r   c                    [        U R                  5      S:X  a  / $ U R                  U R                  S      n[        U R                  5      S:X  d  [        U[        5      (       d  / $ U R
                  R                  5        Vs/ s H7  nUR                  5       R                  5       UR                  5       :X  d  M5  UPM9     sn$ s  snf )z
:return: A list of all the productions for which expansions
    are available for the current parser state.
:rtype: list(Production)
r   )
r)   r   r   r,   r   r   r>   r?   r    r@   )r   frontier_childps      r   expandable_productions5SteppingRecursiveDescentParser.expandable_productions*  s     t~~!#IDNN1$56t~~!#:nd+K+KI ]]..0
0uuw~~>#7#7#99 0
 	
 
s   4C<Cc                     U R                   R                  U R                  U R                  5      / 5      nU R	                  5        Vs/ s H  o"U;  d  M
  UPM     sn$ s  snf )z
:return: A list of all the untried productions for which
    expansions are available for the current parser state.
:rtype: list(Production)
)r   getr   r   r   )r   tried_expansionsr   s      r   r   =SteppingRecursiveDescentParser.untried_expandable_productions=  sQ      ==,,T\\$**-ErJ668V8aEU<U8VVVs   	AAc                     [        U R                  5      S:X  a  gU R                  R                  U R	                  U R
                  5      / 5      nU R                  S   U;  $ )zo
:return: Whether the first element of the frontier is a token
    that has not yet been matched.
:rtype: bool
r   F)r)   r   r   r   r   r   )r   tried_matchess     r   r   ,SteppingRecursiveDescentParser.untried_matchG  sN     t{{q ))$,,tzz*BBG{{1~]22r   c                 p    [        U R                  5      S:H  =(       a    [        U R                  5      S:H  $ )z[
:return: Whether the parser's current state represents a
    complete parse.
:rtype: bool
r   )r)   r   r   r   s    r   currently_complete1SteppingRecursiveDescentParser.currently_completeS  s+     4>>"a'AC,<,AAr   c                 b   U R                   R                  U R                  U R                  U R                  45        Xl        X l        X0l        [        U5      S:X  aP  [        U5      S:X  aA  U R                  R                  U5        U R                  U R                  U R                  5        S/$ )aB  
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   r6   )r   rK   r   r   r   r)   r   r*   r/   s       r   r"   %SteppingRecursiveDescentParser._parse[  s     	dkk4::t~~FG$
! x=A#n"5":LL%

DNN;s
r   c                 ,    [        U R                  5      $ )zi
:return: An iterator of the parses that have been found by this
    parser so far.
:rtype: list of Tree
)iterr   r   s    r   r   %SteppingRecursiveDescentParser.parsesv  s     DLL!!r   c                     Xl         g)z^
Change the grammar used to parse texts.

:param grammar: The new grammar.
:type grammar: CFG
Nr   )r   r   s     r   set_grammar*SteppingRecursiveDescentParser.set_grammar~  s	      r   )r   r   r   r   r   r   r   r   rt   r   )ru   rv   rw   rx   ry   r   r   r&   r   r0   r%   r1   r   r   r   r   r   r   r   r   r"   r   r   rz   __classcell__)r   s   @r   r|   r|   Y  sl    0(G$B&P4 
&W
3B6"   r   r|   c                      SSK Jn Jn  U R                  S5      nUR	                  5        H  n[        U5        M     SR                  5       nUR                  USS9nUR                  U5       H  n[        U5        M     g)z2
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 parkr\   )r   N)nltkr   r&   
fromstringr>   rV   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   r|   r   ru   r   r   r   <module>r      sH    % " )B#W B#P
l %; l h	< zF r   