Generating Code for Procedures TopConstructing the LR(0) Machine for a GrammarUsing the LR(0) machine

Using the LR(0) machine

  1. The key fact about the LR(0) machine for a grammar is:
    Theorem
    [ N 1 . 2 ] ( 0, ) iff [ N 1 . 2 ] is valid for .
  2. If the LR(0) set associated with some state includes an item of the form [ N . ] That implies that might be the handle. We will call such an item a reduce item.
  3. If the only item in the LR(0) set associated with some state is an item of the form [ N . ] then, must be the handle.
  4. If in the LR(0) machine for a grammar G, any state that contains a reduce item contains only that item, then the action that should be performed by a parser is determined as follows. Run the LR(0) machine on the string stored in the parser's stack. Then,

    In this case, we say that G is an LR(0) grammar.

  5. Note that we don't have to start our FSM over at the bottom of the stack after each reduction to continue parsing. We can avoid this by recording the state of the FSM as it scans each symbol on the stack with the symbol on the stack. Then, after reducing a suffix of the stack, we just start the LR(0) machine in the state associated with the top symbol left in the stack (rather than starting over from scratch).
  6. The "trick" is simply to keep another stack (parallel to the stack that store the head of the sentential form we are working on) that stores the state the LR(0) machine would enter for each character in the "regular" stack.
  7. In fact, we can completely replace the stack of symbols by a stack of the FSM states that would have been associated with them.
  8. To make this clearer, let's walk through the parse of an input string using the LR(0) machine shown in Figure *. I have numbered each state in the diagram of the machine and used these number to identify states in the stack snapshots.

    Stack Contents Remaining Input
    ("real" and "virtual")
    1 c a c b a c a c b b
    1 3 a c b a c a c b b
    c
    1 2 a c b a c a c b b
    S
    1 2 5 c b a c a c b b
    S a
    1 2 5 3 b a c a c b b
    S a c
    1 2 5 6 b a c a c b b
    S a S
    1 2 5 6 7 a c a c b b
    S a S b
    1 2 a c a c b b
    S
    1 2 5 c a c b b
    S a
    1 2 5 3 a c b b
    S a c
    1 2 5 6 a c b b
    S a S
    1 2 5 6 5 c b b
    S a S a
    1 2 5 6 5 3 b b
    S a S a c
    1 2 5 6 5 6 b b
    S a S a S
    1 2 5 6 5 6 7 b
    S a S a S b
    1 2 5 6 b
    S a S
    1 2 5 6 7
    S a S b
    1 2
    S

    LR(0) parser stack trace
     

Computer Science 434
Department of Computer Science
Williams College

Generating Code for Procedures TopConstructing the LR(0) Machine for a GrammarUsing the LR(0) machine