CS 331 Spring 2009  >  Additional Lecture Notes for Friday, February 20, 2009

CS 331 Spring 2009
Additional Lecture Notes for Friday, February 20, 2009

The following material was covered in class, in addition to the material from the text.

Constructing a Table for an LR Parser

We began with the following grammar.

S → C
C → Cb | b

The language generated by this grammar consist of the strings ab, abb, abbb, etc.

This grammar has a left-recursive rule, and so it cannot be handled by an LL parser (such as a recursive-descent parser).

For convenience, we write out the rules separately, and we number them.

  1. S → C
  2. C → Cb
  3. C → b

An LR parser is a state machine with a stack. As we noted when we wrote a lexical analyzer, two situations can be considered the same state if same input would lead to the same actions. Thus, in our lexical analyzer, the input “3.” led to the same state as “-.237”, because they would both lead to the same kind of token (NUMBER), and both had the same restrictions on the remainder of the input (string of digits). Similar reasoning applies to our parser.

Here are the finished Action and Goto tables.

State Action Goto
  a b $ S C
ε 0 S1     5  
a 1   S2     3
ab 2   R3 R3    
aC 3   S4 R1    
aCb 4   R2 R2    
S 5     accept    

Above, the string to the left of the state number is what might be on the stack when we are in this state. As in the text, in the Action table, “S” represents a shift operation, and is followed by the state number to push. “R” represents a reduce operation, and is followed by the number of the rule with which to reduce. Each entry in the Goto table is the state number to push. A blank entry indicates a syntax error.

Thus, for example, we are in state 0 when we have read nothing. If we read an a, then we go to state 1, because that is the “a” state. A syntactically correct string cannot begin with b or $, and so those entries in the state-0 row indicate syntax errors.

If we are in state 2 then we have read ab. We want to apply rule 2, which says that the b reduces to C. Thus, all legal entries indicate a reduction with rule 2. After this, we want to go to state 3, since aC will be on the stack. This is accomplished by putting 3 in the C column of the state 1 row, because state 1 is the “a” state, and that is what must have been on the stack below state 2.

Lastly, we note that a reduce operation is a reduction of a simple phrase to a single nonterminal. This always adds a single node to our parse tree. A shift operation does not modify the parse tree.


CS 331 Spring 2009: Additional Lecture Notes for Friday, February 20, 2009 / Updated: 20 Feb 2009 / Glenn G. Chappell / ffggc@uaf.edu Valid HTML 4.01!