LR parsing step by step

We parse n + n with the grammar below. Step forward with Next (or the arrow keys): the current state lights up in the automaton, the stack moves, and the table cell in use lights up.

0.S′ → E1.E → E + n2.E → n

The automaton (built once, from the rules)

E n + n 0 S′ → · EE → · E + nE → · n 1 S′ → E ·E → E · + n 2 E → n · 3 E → E + · n 4 E → E + n ·

The dot · splits what is already read from what is still expected. Dot at the end = complete rule = it can be reduced.

The stack (bottom on the left, top on the right)

Under each state: the symbol read to get there.

The input

$ = end of the text (Eof).

What happens

The ACTION and GOTO tables

staten+$GOTO E

s2 = shift to state 2, r1 = reduce by rule 1, acc = accept.

The tree built by the reduces


    

Why a GOTO right after the pop?

The GOTO is the second half of the reduce. A reduce replaces the right side of a rule with its left side: for E → n, the n goes away and an E takes its place. That happens in two moves:

  1. Pop: the states that stood for n leave the stack. We are back in the state we were in before the rule started, here state 0.
  2. GOTO: the E we just built must now be placed, as if we had just read it from state 0. In the automaton, state 0 has an arrow E to state 1: GOTO[0, E] = 1 is that arrow.

So a GOTO is a shift, but for a non-terminal. There are two tables because terminals (n, +, $) come from the text, and ACTION holds their arrows. Non-terminals (E) are never read from the text: only a reduce makes them, so GOTO, which holds their arrows, is used only there, right after the pop.

A reduce reads no token: the + is still the current token. Right after the GOTO, ACTION is looked up again with that same + (step 9), and this time it says shift.