
    /h@                     v    S SK Jr  S SKJr  S SKJr   " S S\5      r " S S\5      rS r\	S	:X  a  \" 5         g
g
)    )Nonterminal)ParserI)Treec                   j    \ rS rSrSrSS jrS rS rS rS r	SS	 jr
SS
 jrSS jrS rS rS rSrg)ShiftReduceParser   a%  
A simple bottom-up CFG parser that uses two operations, "shift"
and "reduce", to find a single parse for a text.

``ShiftReduceParser`` maintains a stack, which records the
structure of a portion of the text.  This stack is a list of
strings and Trees that collectively cover a portion of
the text.  For example, while parsing the sentence "the dog saw
the man" with a typical grammar, ``ShiftReduceParser`` will produce
the following stack, which covers "the dog saw"::

   [(NP: (Det: 'the') (N: 'dog')), (V: 'saw')]

``ShiftReduceParser`` attempts to extend the stack to cover the
entire text, and to combine the stack elements into a single tree,
producing a complete parse for the sentence.

Initially, the stack is empty.  It is extended to cover the text,
from left to right, by repeatedly applying two operations:

  - "shift" moves a token from the beginning of the text to the
    end of the stack.
  - "reduce" uses a CFG production to combine the rightmost stack
    elements into a single Tree.

Often, more than one operation can be performed on a given stack.
In this case, ``ShiftReduceParser`` uses the following heuristics
to decide which operation to perform:

  - Only shift if no reductions are available.
  - If multiple reductions are available, then apply the reduction
    whose CFG production is listed earliest in the grammar.

Note that these heuristics are not guaranteed to choose an
operation that leads to a parse of the text.  Also, if multiple
parses exists, ``ShiftReduceParser`` will return at most one of
them.

:see: ``nltk.grammar``
c                 <    Xl         X l        U R                  5         g)ab  
Create a new ``ShiftReduceParser``, that uses ``grammar`` to
parse texts.

:type grammar: Grammar
: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_check_grammar)selfgrammartraces      N/var/www/auris/envauris/lib/python3.13/site-packages/nltk/parse/shiftreduce.py__init__ShiftReduceParser.__init__;   s          c                     U R                   $ Nr
   r   s    r   r   ShiftReduceParser.grammarL   s    }}r   c              #   H  #    [        U5      nU R                  R                  U5        / nUnU R                  (       a.  [	        SSR                  U5      -  5        U R                  X#5        [        U5      S:  aQ  U R                  X#5        U R                  X#5      (       a   U R                  X#5      (       a  M  [        U5      S:  a  MQ  [        U5      S:X  aF  US   R                  5       U R                  R                  5       R                  5       :X  a  US   v   g g g 7f)Nz
Parsing %r r      )listr
   check_coverager   printjoin_trace_stacklen_shift_reducelabelstartsymbol)r   tokensstackremaining_texts       r   parseShiftReduceParser.parseO   s     f$$V,  ;;,&!112e4 .!A%KK.,,u55 ,,u55 .!A% u:?Qx~~4==#6#6#8#?#?#AAAh B s   B7D";D"AD"c                     UR                  US   5        UR                  US   5        U R                  (       a  U R                  X5        gg)af  
Move a token from the beginning of ``remaining_text`` to the
end of ``stack``.

:type stack: list(str and Tree)
:param stack: A list of strings and Trees, encoding
    the structure of the text that has been parsed so far.
:type remaining_text: list(str)
:param remaining_text: The portion of the text that is not yet
    covered by ``stack``.
:rtype: None
r   N)appendremover   _trace_shiftr   r(   r)   s      r   r"   ShiftReduceParser._shifti   sB     	^A&'nQ/0;;e4 r   c                 j   [        U5      [        U5      :w  a  g[        [        U5      5       H  n[        X#   [        5      (       aC  [        X   [        5      (       d    gX#   R                  5       X   R                  5       :w  a    gM]  [        X   [        5      (       a    gX#   X   :w  d  M    g   g)a  
:rtype: bool
:return: true if the right hand side of a CFG production
    matches the rightmost elements of the stack.  ``rhs``
    matches ``rightmost_stack`` if they are the same length,
    and each element of ``rhs`` matches the corresponding
    element of ``rightmost_stack``.  A nonterminal element of
    ``rhs`` matches any Tree whose node value is equal
    to the nonterminal's symbol.  A terminal element of ``rhs``
    matches any string whose type is equal to the terminal.
:type rhs: list(terminal and Nonterminal)
:param rhs: The right hand side of a CFG production.
:type rightmost_stack: list(string and Tree)
:param rightmost_stack: The rightmost elements of the parser's
    stack.
FT)r!   range
isinstancer   r   r$   r&   )r   rhsrightmost_stackis       r   
_match_rhsShiftReduceParser._match_rhs{   s    $ 3s8+s?+,A/,d33!#&+66 "%++-@  A cfk22 "%/  - r   Nc                    Uc  U R                   R                  5       nOU/nU H  n[        UR                  5       5      nU R	                  UR                  5       X* S 5      (       d  MF  [        UR                  5       R                  5       X* S 5      nU/X* S& U R                  (       a  U R                  XU5        Us  $    g)a  
Find a CFG production whose right hand side matches the
rightmost stack elements; and combine those stack elements
into a single Tree, with the node specified by the
production's left-hand side.  If more than one CFG production
matches the stack, then use the production that is listed
earliest in the grammar.  The new Tree replaces the
elements in the stack.

:rtype: Production or None
:return: If a reduction is performed, then return the CFG
    production that the reduction is based on; otherwise,
    return false.
:type stack: list(string and Tree)
:param stack: A list of strings and Trees, encoding
    the structure of the text that has been parsed so far.
:type remaining_text: list(str)
:param remaining_text: The portion of the text that is not yet
    covered by ``stack``.
N)
r
   productionsr!   r5   r8   r   lhsr&   r   _trace_reduce)r   r(   r)   
productionr;   rhslentrees          r   r#   ShiftReduceParser._reduce   s    * --335K%,K &J)*F z~~/wxAAJNN,335uWXG#'&gh ;;&&u.I!! & r   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   ShiftReduceParser.trace   s	     r   c                    SU-   S-   nU HS  n[        U[        5      (       a*  U[        [        UR	                  5       5      5      S-   -  nMB  U[        U5      S-   -  nMU     USSR                  U5      -   S-   -  n[        U5        g)z
Print trace output displaying the given stack and text.

:rtype: None
:param marker: A character that is printed to the left of the
    stack.  This is used with trace level 2 to print 'S'
    before shifted stacks and 'R' before reduced stacks.
z  z [ r   z* ]N)r4   r   reprr   r$   r   r   )r   r(   r)   markerselts         r   r    ShiftReduceParser._trace_stack   s     6ME!C#t$$T+ciik23c99T#Y_$	 
 	
TCHH^,,s22ar   c                     U R                   S:  a  [        SUS   -  5        U R                   S:X  a  U R                  XS5        gU R                   S:  a  U R                  X5        gg)zL
Print trace output displaying that a token has been shifted.

:rtype: None
   z	Shift %r:Sr   N)r   r   r    r0   s      r   r/   ShiftReduceParser._trace_shift   sZ     ;;?+b	)*;;!eS9[[1_e4 r   c                 ,   U R                   S:  a?  SR                  UR                  5       5      n[        SUR	                  5       < SU 35        U R                   S:X  a  U R                  XS5        gU R                   S:  a  U R                  X5        gg)z_
Print trace output displaying that ``production`` was used to
reduce ``stack``.

:rtype: None
rL   r   zReduce z <- Rr   N)r   r   r5   r   r<   r    )r   r(   r>   r)   r5   s        r   r=   ShiftReduceParser._trace_reduce   s{     ;;?((:>>+,CGJNN,/tC59:;;!eS9[[1_e4 r   c                 <   U R                   R                  5       n[        [        U5      5       Hj  n[        US-   [        U5      5       HK  nX   R	                  5       nX   R	                  5       nUS[        U5       U:X  d  M;  [        SX   -  5        MM     Ml     g)z
Check to make sure that all of the CFG productions are
potentially useful.  If any productions can never be used,
then print a warning.

:rtype: None
r   NzWarning: %r will never be used)r
   r;   r3   r!   r5   r   )r   r;   r7   jrhs1rhs2s         r   r    ShiftReduceParser._check_grammar  s     mm//1 s;'(A1q5#k"23"~))+"~))+#d)$,:[^KL	 4 )r   )r
   r   r   r   )rL   )r   )__name__
__module____qualname____firstlineno____doc__r   r   r*   r"   r8   r#   r   r    r/   r=   r   __static_attributes__ r   r   r   r      sB    'R"45$B*X $55Mr   r   c                   v   ^  \ 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S
 jrS rS rS rS rSrU =r$ )SteppingShiftReduceParseri  a  
A ``ShiftReduceParser`` that allows you to setp through the parsing
process, performing a single operation at a time.  It also allows
you to change the parser's grammar midway through parsing a text.

The ``initialize`` method is used to start parsing a text.
``shift`` performs a single shift operation, and ``reduce`` performs
a single reduce operation.  ``step`` will perform a single reduce
operation if possible; otherwise, it will perform a single shift
operation.  ``parses`` returns the set of parses that have been
found by the parser.

:ivar _history: A list of ``(stack, remaining_text)`` pairs,
    containing all of the previous states of the parser.  This
    history is used to implement the ``undo`` operation.
:see: ``nltk.grammar``
c                 N   > [         TU ]  X5        S U l        S U l        / U l        g r   )superr   _stack_remaining_text_history)r   r   r   	__class__s      r   r   "SteppingShiftReduceParser.__init__0  s&    (#r   c                     [        U5      nU R                  U5        U R                  5       (       a   U R                  5       (       a  M  U R                  5       $ r   )r   
initializestepparsesr   r'   s     r   r*   SteppingShiftReduceParser.parse6  s>    fiikk iikk{{}r   c                     U R                   $ )z9
:return: The parser's stack.
:rtype: list(str and Tree)
)rd   r   s    r   r(   SteppingShiftReduceParser.stack=  s    
 {{r   c                     U R                   $ )z^
:return: The portion of the text that is not yet covered by the
    stack.
:rtype: list(str)
)re   r   s    r   r)   (SteppingShiftReduceParser.remaining_textD  s     ###r   c                 ,    / U l         Xl        / U l        g)zp
Start parsing a given text.  This sets the parser's stack to
``[]`` and sets its remaining text to ``tokens``.
N)rd   re   rf   rm   s     r   rj   $SteppingShiftReduceParser.initializeL  s    
 %r   c                 P    U R                  5       =(       d    U R                  5       $ )a  
Perform a single parsing operation.  If a reduction is
possible, then perform that reduction, and return the
production that it is based on.  Otherwise, if a shift is
possible, then perform it, and return True.  Otherwise,
return False.

:return: False if no operation was performed; True if a shift was
    performed; and the CFG production used to reduce if a
    reduction was performed.
:rtype: Production or bool
)reduceshiftr   s    r   rk   SteppingShiftReduceParser.stepU  s     {{},

,r   c                     [        U R                  5      S:X  a  gU R                  R                  U R                  SS U R                  SS 45        U R                  U R                  U R                  5        g)z
Move a token from the beginning of the remaining text to the
end of the stack.  If there are no more tokens in the
remaining text, then do nothing.

:return: True if the shift operation was successful.
:rtype: bool
r   FNT)r!   re   rf   r-   rd   r"   r   s    r   rw   SteppingShiftReduceParser.shiftd  s_     t##$)dkk!nd.B.B1.EFGDKK!5!56r   c                    U R                   R                  U R                  SS U R                  SS 45        U R	                  U R                  U R                  U5      nU(       d  U R                   R                  5         U$ )aC  
Use ``production`` to combine the rightmost stack elements into
a single Tree.  If ``production`` does not match the
rightmost stack elements, then do nothing.

:return: The production used to reduce the stack, if a
    reduction was performed.  If no reduction was performed,
    return None.

:rtype: Production or None
N)rf   r-   rd   re   r#   pop)r   r>   
return_vals      r   rv    SteppingShiftReduceParser.reduces  sc     	dkk!nd.B.B1.EFG\\$++t/C/CZP
MMr   c                     [        U R                  5      S:X  a  gU R                  R                  5       u  U l        U l        g)a<  
Return the parser to its state before the most recent
shift or reduce operation.  Calling ``undo`` repeatedly return
the parser to successively earlier states.  If no shift or
reduce operations have been performed, ``undo`` will make no
changes.

:return: true if an operation was successfully undone.
:rtype: bool
r   FT)r!   rf   r|   rd   re   r   s    r   undoSteppingShiftReduceParser.undo  s7     t}}".2mm.?.?.A+d*r   c                 
   / nU R                   R                  5        Hb  n[        UR                  5       5      nU R	                  UR                  5       U R
                  U* S 5      (       d  MQ  UR                  U5        Md     U$ )z
:return: A list of the productions for which reductions are
    available for the current parser state.
:rtype: list(Production)
N)r
   r;   r!   r5   r8   rd   r-   )r   r;   r>   r?   s       r   reducible_productions/SteppingShiftReduceParser.reducible_productions  sl     --335J)*Fz~~/fWX1FGG"":. 6 r   c              #   &  #    [        U R                  5      S:X  at  [        U R                  5      S:X  aZ  U R                  S   R                  5       U R                  R                  5       R                  5       :X  a  U R                  S   v   gggg7f)zg
:return: An iterator of the parses that have been found by this
    parser so far.
:rtype: iter(Tree)
r   r   N)r!   re   rd   r$   r
   r%   r&   r   s    r   rl    SteppingShiftReduceParser.parses  sx      $$%*DKK A%A$$&$--*=*=*?*F*F*HH++a.  I & +s   BB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%SteppingShiftReduceParser.set_grammar  s	      r   )r
   rf   re   rd   rX   r   )rY   rZ   r[   r\   r]   r   r*   r(   r)   rj   rk   rw   rv   r   r   rl   r   r^   __classcell__)rg   s   @r   ra   ra     sI    $$-& !   r   ra   c                      SSK Jn Jn  U R                  S5      nSR	                  5       nUR                  USS9nUR                  U5       H  n[        U5        M     g)z-
A demonstration of the shift-reduce 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 parkrL   )r   N)nltkr   r*   
fromstringsplitr   r   )r   r*   r   sentparserps         r   demor     sY    
  nn
	G %**,D$$WA$6F\\$a  r   __main__N)
nltk.grammarr   nltk.parse.apir   	nltk.treer   r   ra   r   rY   r_   r   r   <module>r      sJ    % " FM FMX\  1 \ H8 zF r   