In the previous article you saw that E → E + T | T, the most natural form for writing expressions, does not suit an LL(1) parser: left recursion sends it into a loop, and rewriting it changes the shape of the tree. A bottom-up parser does not have this problem, because it does not decide in advance which production to use: it reads the tokens, piles them up on a stack and reduces only when it has seen the whole body of a production. This article builds the automaton that guides that choice (the LR items), derives three different tables from it, SLR, canonical LR(1) and LALR(1), and measures where they stop: states, conflicts and accepted strings on three grammars.
You need the one-token descent of article 4: the files ll1.py (FIRST and FOLLOW) and oracolo.py (the Earley recognizer) are the ones from that article and here I import them without repeating them. The grammars are in the format you already know, and for the basics on derivations there is the article on context-free grammars. Python 3.14, no external libraries; every listing was run twice with the same output on 2026-11-13.
Shift-reduce: the stack instead of lookahead
An LR parser (left to right, rightmost derivation in reverse) keeps a stack of symbols and at every step chooses between two moves: shift, that is, moving the next token from the input to the stack, or reduce, that is, replacing the body of a production on top of the stack with its head. When the start symbol is on top and the input is finished, it accepts. The everyday comparison is reading a sentence: you accumulate words until you recognize a complete block ("the black cat" becomes "noun phrase") and only then do you replace it with its label. The recognized block, the one that can be reduced without ruining the derivation, is called the handle.
The difficulty is always the same: knowing when to reduce. Looking only at the symbols on the stack is not enough, because the same body can be reduced in one context and not in another. LR parsing was introduced by Knuth (1965, Information and Control). The way to implement it is to summarize the stack in a number, the state of a finite-state automaton that reads the stack from bottom to top. The states are sets of items, and the whole theory of LR parsers lies in deciding how much context to carry inside the items.
Here is how it works on the expression id + id * id, produced by the verification program you find further below. Look at the two points where, with E + T on top of the stack, the move depends on the token that follows: with * ahead you shift, because multiplication binds tighter; with $ you reduce. Operator precedence is not written anywhere in the parser: it lies in the shape of the grammar, which puts * on a lower level than +.
LR(0) items and the characteristic automaton
An LR(0) item is a production with a dot that marks how much of the body has already been seen: E → E + · T says "I have read E + and I expect to read a T". A state is a set of items. Two operations build it. The closure adds, for every item with the dot before a nonterminal B, all the items B → · γ: if I expect a T, I also expect everything a T starts with. The goto(state, X) function moves the dot past X in all the items that allow it and closes the result. Starting from the augmented item S' → · S and applying goto to all the symbols until no new states are found, you get the characteristic automaton.
The listing computes these sets for LR(0) and LR(1) with the same code, because an LR(1) item is an LR(0) item with one more lookahead: (production, dot, lookahead), with the lookahead None in the LR(0) case. In the closure, first_di_sequenza(rhs[d + 1:] + (la,), ...) computes which tokens what follows B can continue with: it is the line that distinguishes LR(1) from LR(0). fondi_nuclei builds the LALR automaton by merging the LR(1) states that have the same core (the items without lookahead), merging the lookaheads. tabella fills the action and goto cells, and esegui is the shift-reduce driver.
"""LR(0) and LR(1) items, characteristic automaton, SLR, canonical LR(1) and LALR(1) tables."""
from ll1 import calcola_first, calcola_follow, first_di_sequenza, FINE
class ErroreSintassi(Exception):
pass
def aumenta(g, start):
"""Production 0: S' -> S. The others follow in dictionary order."""
nuovo = start + "'"
prods = [(nuovo, (start,))] + [(a, tuple(alt)) for a, alts in g.items() for alt in alts]
return prods, nuovo
class Automa:
def __init__(self, g, start):
self.prods, self.start = aumenta(g, start)
self.nts = {a for a, _ in self.prods}
g2 = {self.start: [[start]], **g}
self.first, self.ann = calcola_first(g2)
self.follow = calcola_follow(g2, self.start, self.first, self.ann)
self.per_testa = {}
for p, (a, _) in enumerate(self.prods):
self.per_testa.setdefault(a, []).append(p)
self.simboli = list(dict.fromkeys(s for _, rhs in self.prods for s in rhs))
def chiusura(self, items, lr1):
"""An item is (production, dot, lookahead); the lookahead is None in LR(0)."""
res, lavoro = set(items), list(items)
while lavoro:
p, d, la = lavoro.pop()
rhs = self.prods[p][1]
if d < len(rhs) and rhs[d] in self.nts:
if lr1:
anticipi = first_di_sequenza(rhs[d + 1:] + (la,), self.first, self.ann)
else:
anticipi = {None}
for q in self.per_testa[rhs[d]]:
for t in anticipi:
if (q, 0, t) not in res:
res.add((q, 0, t))
lavoro.append((q, 0, t))
return frozenset(res)
def vai(self, stato, x, lr1):
mossi = {(p, d + 1, la) for (p, d, la) in stato
if d < len(self.prods[p][1]) and self.prods[p][1][d] == x}
return self.chiusura(mossi, lr1)
def collezione(self, lr1):
iniziale = self.chiusura({(0, 0, FINE if lr1 else None)}, lr1)
stati, indice, trans, da_fare = [iniziale], {iniziale: 0}, {}, [0]
while da_fare:
i = da_fare.pop(0)
for x in self.simboli:
nuovo = self.vai(stati[i], x, lr1)
if not nuovo:
continue
if nuovo not in indice:
indice[nuovo] = len(stati)
stati.append(nuovo)
da_fare.append(indice[nuovo])
trans[(i, x)] = indice[nuovo]
return stati, trans
def fondi_nuclei(stati, trans):
"""LALR: merges the LR(1) states that have the same core (items without lookahead)."""
gruppi, mappa, nuovi = {}, {}, []
for i, st in enumerate(stati):
nucleo = frozenset((p, d) for p, d, _ in st)
if nucleo not in gruppi:
gruppi[nucleo] = len(nuovi)
nuovi.append(set())
nuovi[gruppi[nucleo]] |= st
mappa[i] = gruppi[nucleo]
return [frozenset(s) for s in nuovi], {(mappa[i], x): mappa[j] for (i, x), j in trans.items()}
def tabella(a, metodo):
"""metodo: 'SLR', 'LR1' or 'LALR'. Returns (states, actions, goto, conflicts)."""
stati, trans = a.collezione(lr1=(metodo != "SLR"))
if metodo == "LALR":
stati, trans = fondi_nuclei(stati, trans)
azioni, vai = {}, {}
def metti(i, t, act):
celle = azioni.setdefault((i, t), [])
if act not in celle:
celle.append(act)
for (i, x), j in sorted(trans.items()):
if x in a.nts:
vai[(i, x)] = j
else:
metti(i, x, ("s", j))
for i, st in enumerate(stati):
for p, d, la in sorted(st, key=lambda it: (it[0], it[1], str(it[2]))):
testa, rhs = a.prods[p]
if d < len(rhs):
continue
if p == 0:
metti(i, FINE, ("acc",))
else:
for t in sorted(a.follow[testa] if metodo == "SLR" else {la}):
metti(i, t, ("r", p))
conflitti = sorted(((i, t), celle) for (i, t), celle in azioni.items() if len(celle) > 1)
return stati, azioni, vai, conflitti
def esegui(a, azioni, vai, tokens, traccia=None):
"""Shift-reduce driver. Returns the reduced productions, in order."""
ingresso, k = list(tokens) + [FINE], 0
stati, simboli, ridotte = [0], [], []
while True:
celle = azioni.get((stati[-1], ingresso[k]))
if not celle:
raise ErroreSintassi(f"no action in state {stati[-1]} on {ingresso[k]!r}")
if len(celle) > 1:
raise ErroreSintassi("table with a conflict: the parser is not deterministic")
act = celle[0]
if traccia is not None:
traccia.append((" ".join(simboli), " ".join(ingresso[k:]), act))
if act[0] == "s":
stati.append(act[1]); simboli.append(ingresso[k]); k += 1
elif act[0] == "r":
testa, rhs = a.prods[act[1]]
if rhs:
del stati[-len(rhs):]; del simboli[-len(rhs):]
stati.append(vai[(stati[-1], testa)]); simboli.append(testa)
ridotte.append(act[1])
else:
return ridotte
The line that decides the reductions is the for t in sorted(...) inside tabella: with metodo == "SLR" you reduce A → α on all the tokens of FOLLOW(A); with LR(1) and LALR you reduce only on the item's lookaheads. If you remove that sorting the program still works, but the order of the conflict messages changes from one run to the next, because sets of strings have no stable order: I had to add it to get two identical outputs. The esegui driver refuses to work with a cell that contains more than one action: a table with conflicts does not describe a deterministic parser.
Three tables from the same grammar
The three methods share the automaton and differ in the rule with which they fill the reduce cells. The table summarizes what each one looks at and what it costs in states on the program's grammars (the numbers come from the output shown further below):
| Method | When it reduces A → α | States: expressions | States: pointers | States: not LALR |
|---|---|---|---|---|
| SLR(1) | on the tokens of FOLLOW(A) | 12 | 10 | 13 |
| LALR(1) | on the item's lookaheads, merged among states with the same core | 12 | 10 | 13 |
| Canonical LR(1) | on the item's exact lookahead | 22 | 14 | 14 |
Power grows from SLR to LALR to LR(1), but so does size. SLR and LALR always have the same number of states, because merging the LR(1) states by core gives exactly the states of the LR(0) automaton: the equality of the numbers is not a coincidence of the three grammars, it is a consequence of the construction. Canonical LR(1) can have more: on the expressions 22 against 12, on the other two grammars 4 and 1 more. How large it becomes on grammars of real languages I have not measured, and for that reason I say nothing about it. DeRemer and Pennello (1982, ACM TOPLAS) published an efficient algorithm for computing the LALR(1) lookaheads; of that work I verified title, authors and venue on Crossref, not the content.
Conflicts: where SLR stops
A cell with two actions is a conflict. If the actions are shift and reduce it is called a shift/reduce conflict, if they are two reduces a reduce/reduce conflict. A conflict can depend on a true ambiguity of the grammar (no method resolves it) or on the fact that the method has little context. The program shows the second case with a grammar of assignments with pointers: S → L = R | R, L → * R | id, R → L, in which L is a value on the left of the equals sign and R a value on the right.
SLR finds a conflict in state 2, on the token =: the state contains S → L · = R (shift) and R → L · (reduce). Reducing on = looks legitimate to SLR because = is in FOLLOW(R): indeed R can close an L that precedes = (for example after the asterisk, in *R = R). But in state 2, which you reach by reading an L at the beginning of the sentence, that reduction is never valid: an R in that position can be followed only by the end of the input. The LR(1) lookahead of that item is $, not =, so LR(1) and LALR see no conflict, as you read in the output (conflicts 0 and 0). SLR is stopped by the fact that FOLLOW looks at the whole grammar, not at the context of that state.
The third grammar, S → a E a | b E b | a F b | b F a, E → e, F → e, shows that LALR too has a limit. The language has only four sentences (aea, beb, aeb, bea), but after reading a e the parser must reduce e to E if a follows and to F if b follows, while after b e it is the opposite. LR(1) keeps the two states separate, 14 in all. LALR sees them with the same core {E → e·, F → e·} and merges them, and in the merged state the two lookaheads get mixed: reduce/reduce conflict on a and on b, as the output shows (13 states, 2 conflicts). It is an illustration of the order of power: what LALR does not distinguish, LR(1) distinguishes.
The check: enumerated strings and an oracle
For each of the three grammars and for each method without conflicts, the verification program builds all the strings up to a given length (7 tokens for the expressions, 9 for the other two), has them recognized by the parser and by the Earley oracle, written for the previous article and checked there with a second computation, and counts the disagreements. There are 97,656 strings for the expressions and 29,524 for each of the other two. The oracle recognizes 60, 37 and 4 valid strings respectively. The four of the last one you already know.
"""Three grammars, three methods: states, conflicts, and a check on enumerated strings."""
from itertools import product
from lr import Automa, tabella, esegui, ErroreSintassi
from oracolo import riconosce
GRAMMATICHE = {
# Left-recursive: for an LR parser this is the natural form.
"expressions": ({"E": [["E", "+", "T"], ["T"]], "T": [["T", "*", "F"], ["F"]],
"F": [["(", "E", ")"], ["id"]]}, "E", ["id", "+", "*", "(", ")"], 7),
# Assignments with pointers: SLR fails, LR(1) and LALR do not.
"pointers": ({"S": [["L", "=", "R"], ["R"]], "L": [["*", "R"], ["id"]], "R": [["L"]]},
"S", ["id", "*", "="], 9),
# LR(1) but not LALR(1): merging the states creates a reduce/reduce conflict.
"not LALR": ({"S": [["a", "E", "a"], ["b", "E", "b"], ["a", "F", "b"], ["b", "F", "a"]],
"E": [["e"]], "F": [["e"]]}, "S", ["a", "b", "e"], 9),
}
def descrivi(a, c):
(i, t), celle = c
nomi = [("shift " + str(x[1])) if x[0] == "s" else ("reduce " + a.prods[x[1]][0] + " -> " + (" ".join(a.prods[x[1]][1]) or "ε"))
for x in celle]
return f"state {i} on {t!r}: " + " / ".join(nomi)
def accetta(a, az, vai, s):
try:
esegui(a, az, vai, s)
return True
except ErroreSintassi:
return False
if __name__ == "__main__":
for nome, (g, start, alfabeto, massimo) in GRAMMATICHE.items():
a = Automa(g, start)
tabelle = {m: tabella(a, m) for m in ("SLR", "LR1", "LALR")}
print(f"== {nome}")
for m, (stati, az, vai, conf) in tabelle.items():
print(f"{m:5} states: {len(stati):3} conflicts: {len(conf)}")
for c in conf:
print(" " + descrivi(a, c))
pulite = [m for m, t in tabelle.items() if not t[3]]
disaccordi = {m: 0 for m in pulite}
validi = totali = 0
for n in range(massimo + 1):
for s in map(list, product(alfabeto, repeat=n)):
o = riconosce(g, start, s)
totali += 1
validi += o
for m in pulite:
disaccordi[m] += (accetta(a, tabelle[m][1], tabelle[m][2], s) != o)
print(f"strings up to {massimo} tokens: {totali}, valid: {validi}, disagreements per method: {disaccordi}")
# The driver step by step, to see stack, input and action.
a = Automa(*GRAMMATICHE["expressions"][:2])
stati, az, vai, _ = tabella(a, "SLR")
traccia = []
esegui(a, az, vai, "id + id * id".split(), traccia)
print("== SLR trace on: id + id * id")
for pila, resto, act in traccia:
nome = ("shift" if act[0] == "s" else "accept" if act[0] == "acc"
else "reduce " + a.prods[act[1]][0] + " -> " + " ".join(a.prods[act[1]][1]))
print(f"{pila:14} | {resto:16} | {nome}")
# Mutation: remove every "reduce E -> T" action from LALR and count the disagreements.
_, az_l, vai_l, _ = tabella(a, "LALR")
guasta = {c: [x for x in v if x != ("r", 2)] for c, v in az_l.items()}
guasta = {c: v for c, v in guasta.items() if v}
g, start, alfabeto, massimo = GRAMMATICHE["expressions"]
brutte = sum(accetta(a, guasta, vai_l, list(s)) != riconosce(g, start, list(s))
for n in range(6) for s in product(alfabeto, repeat=n))
print("LALR table without 'reduce E -> T', disagreements on strings up to 5 tokens:", brutte)
# Output:
# == expressions
# SLR states: 12 conflicts: 0
# LR1 states: 22 conflicts: 0
# LALR states: 12 conflicts: 0
# strings up to 7 tokens: 97656, valid: 60, disagreements per method: {'SLR': 0, 'LR1': 0, 'LALR': 0}
# == pointers
# SLR states: 10 conflicts: 1
# state 2 on '=': shift 6 / reduce R -> L
# LR1 states: 14 conflicts: 0
# LALR states: 10 conflicts: 0
# strings up to 9 tokens: 29524, valid: 37, disagreements per method: {'LR1': 0, 'LALR': 0}
# == not LALR
# SLR states: 13 conflicts: 2
# state 6 on 'a': reduce E -> e / reduce F -> e
# state 6 on 'b': reduce E -> e / reduce F -> e
# LR1 states: 14 conflicts: 0
# LALR states: 13 conflicts: 2
# state 6 on 'a': reduce E -> e / reduce F -> e
# state 6 on 'b': reduce E -> e / reduce F -> e
# strings up to 9 tokens: 29524, valid: 4, disagreements per method: {'LR1': 0}
# == SLR trace on: id + id * id
# | id + id * id $ | shift
# id | + id * id $ | reduce F -> id
# F | + id * id $ | reduce T -> F
# T | + id * id $ | reduce E -> T
# E | + id * id $ | shift
# E + | id * id $ | shift
# E + id | * id $ | reduce F -> id
# E + F | * id $ | reduce T -> F
# E + T | * id $ | shift
# E + T * | id $ | shift
# E + T * id | $ | reduce F -> id
# E + T * F | $ | reduce T -> T * F
# E + T | $ | reduce E -> E + T
# E | $ | accept
# LALR table without 'reduce E -> T', disagreements on strings up to 5 tokens: 15
The output contains everything you need to read the article. On the expressions the three methods agree with the oracle on all 97,656 strings. On the pointer grammar SLR is excluded because it has a conflict, while LR(1) and LALR have zero disagreements on 29,524 strings. On the third only LR(1) is usable. Then the trace shows the moves of the SLR driver, and the last line is the proof that the check works: removing all the E → T reductions from the LALR table, the parser gets 15 of the strings up to 5 tokens wrong. A check that does not detect a known defect does not demonstrate the absence of unknown ones.
This too is verification by enumeration, not proof: it covers strings up to 7 or 9 tokens and says nothing about longer ones. The command to repeat the test is python3 verifica_lr.py, without the -I option because the files import the modules from their own folder; it takes about two seconds.
What changes in practice
Parser generators come from here: you write the grammar, the generator builds the automaton and the table, and reports the conflicts to you. Read properly, a conflict is a diagnostic: it tells you in which state and on which token the grammar does not determine the move, and it usually points to a true ambiguity (like the if-then-else of article 4) or to a grammar written without thinking about reduction. It is common for LALR(1) generators to let you resolve shift/reduce conflicts by declaring operator priority and associativity; this is a feature I did not run here and that has to be read in the documentation of the tool you use, together with its choice of algorithm, which I did not verify on a primary source in this revision.
The comparison with top-down is this. The LR parser accepts more grammars, tolerates left recursion and postpones the decision until the full context. The LL(1) parser is written by hand, is readable and produces more understandable errors, but forces you to rewrite the grammar. There is no winner: the choice depends on who maintains the grammar and how much freedom they want in writing it.
What you can do now
You can build the item automaton by machine, derive the SLR, LR(1) and LALR(1) tables from it and read a conflict as a precise question ("in this state, on this token, why does the grammar not decide?"). You can recognize whether the reason is too little context (SLR versus LR(1)), context merged too early (LALR versus LR(1)) or ambiguity, and you can check a parser on an enumerated set by comparing it with an oracle. In the sixth and last article the parser stops being the goal and becomes the first stage of a compiler: semantic analysis, intermediate code and optimization. If you want to review the other side of parsing, go back to the top-down parser.
Frequently asked questions
What is the difference between SLR, LALR and LR(1)?
It lies in the information used to decide a reduction. SLR uses the FOLLOW of the nonterminal, LR(1) the exact lookahead of each item, LALR the same lookahead after merging the states with the same core. On the three grammars of the listing the states are 12/12/22, 10/10/14 and 13/13/14.
Why does an LR parser accept left recursion?
Because it does not choose the production before having read the body: it accumulates the symbols on the stack and reduces at the end. Left recursion, which sends recursive descent into a loop, here corresponds to a repeated reduction of E + T to E.
Does a conflict mean the grammar is ambiguous?
Not always. It can be true ambiguity, or a limit of the method: the pointer grammar has a conflict in SLR but none in LR(1), and it is not ambiguous. If the conflict disappears when you move to LR(1), the problem was one of context, not of the grammar.
The same series also includes article 01, regular expressions and article 02, DFA, NFA and Thompson construction.
Sources
- Knuth, On the translation of languages from left to right, Information and Control, 1965 - title, author and journal verified on the Crossref registry, article not read: it is the source only for the attribution of the idea of LR parsing; consulted on 2026-11-13
- DeRemer and Pennello, Efficient Computation of LALR(1) Look-Ahead Sets, ACM TOPLAS, 1982 - title, authors and journal verified on the Crossref registry, article not read; consulted on 2026-11-13
- Earley, An efficient context-free parsing algorithm, Communications of the ACM, 1970 - Crossref metadata, not read; the oracle is my own implementation, checked with a second computation in the previous article; consulted on 2026-11-13
- The listing outputs come from
python3 verifica_lr.py, run twice on 2026-11-13 with Python 3.14 (about 2 seconds); the counts of states and conflicts are measures of that program on the three grammars shown, not general values.
Commenti
Caricamento commenti...
Sign in to comment