Attempting an LR(1) Parse Using an LR(1) Machine

We continued our discussion of LR(1) parsing by looking at some of the issues behind constructing an LR(1) parser.

Just as with LL(1) parsing, an LR(1) parser is constructed by first analyzing the grammar and building data structure that helps us parse. For LL parsing we computed First, Follow, and Predict sets on our way to building the LL(1) table that guides the construction of an LL(1) parser.

For LR(1) parsing we build what is called the LR(1) machine from the grammar.  This machine can be used to build two tables that are used in the construction of an LR(1) parser: the action table and the GOTO table.

We examined an LR(1) table first by way of the following example

The Example Grammar (taken from Crafting a Compiler by Fischer and LeBlanc)

S → E $
E → E + T
E → T
T → T * P
T → P
P → id
P → ( E )

Without going into the details of how the LR(1) machine is constructed for this grammar, we first just give it:

We note the following about this LR(1) machine

How this LR(1) machine is constructed is not the issue yet, but we can learn how to use it to parse a string.  Let's look at our original grammar again.

The Example Grammar

S → E $
E → E + T
E → T
T → T * P
T → P
P → id
P → ( E )

Again, let's parse the string

id + id * id $

where the $ represents the end of file marker.

In applying the LR(1) machine we use a stack.  There are two actions to take at each step of an LR(1) parse:

We use the lookahead symbol to determine which of these two actions to take.

We also keep track of which state we are in by way of the stack. 

.