Sub topic 19
Syntax error detection and recovery
This chapter assumes you can build an LL(1) table and an LR ACTION/GOTO table, and that you know FIRST and FOLLOW sets. It covers how those parsers notice a bad input, and how they continue so that one mistake does not hide every later one.
Kinds of errors
A compiler meets four kinds of errors. Each is detected in a different phase.
| Kind | Example | Detected by |
|---|---|---|
| Lexical | illegal character, malformed number | lexer |
| Syntax | missing `)`, misplaced `else` | parser |
| Semantic | type mismatch, undeclared name | semantic analysis |
| Logical | `=` written where `==` was meant | usually nobody |
Only syntax errors concern the parser. A good error handler reports each one clearly, recovers quickly, and adds almost no cost to correct programs.
How parsers detect errors
LL(1) and LR parsers have the viable-prefix property. They report an error as soon as the input read so far cannot be extended to any valid sentence of the language. They never read past the first point where the prefix becomes impossible.
- LL(1): an error occurs when the top of the stack is a terminal that differs from the lookahead, or when the table cell
M[A, a]is empty. - LR: an error occurs when
ACTION[state, a]is blank. A blank cell is the only error signal. GOTO is consulted only after a reduction, so it never signals an error.
Canonical LR(1) detects the error before it does any reduction on the bad lookahead. SLR(1) and LALR(1) may perform a few extra reductions first. This happens because SLR uses FOLLOW sets and LALR merges states, so a reduce action can appear under lookaheads that the exact LR(1) item would reject. They still never shift the erroneous token, so the error is caught before the stack consumes it.
Recovery strategies
| Strategy | Idea | Cost and risk |
|---|---|---|
| Panic mode | Discard input until a synchronizing token appears | Simple, cannot loop if it always consumes input, may skip much code |
| Phrase-level | Replace the local input with a fix, such as inserting `;` | Needs hand-written routines, can loop if insertions never consume input |
| Error productions | Add rules for common mistakes to the grammar | Grammar grows, diagnostics are very specific |
| Global correction | Find the fewest insertions, deletions and changes that make the program valid | Too expensive in practice, mainly a theory benchmark |
Panic mode in an LL(1) parser
Mark some empty cells as synch. The usual choice puts the tokens of FOLLOW(A) in row A. On an error with nonterminal A on top of the stack and lookahead a:
- If
M[A, a]has a production, use it. - Otherwise, if
ais in FOLLOW(A), popA. The parser assumes the phrase forAwas left out. - Otherwise, skip
aand look at the next token. - If the top is a terminal that does not match, pop it. The parser assumes the terminal was missing.
The program below implements this for the expression grammar from the LL(1) chapter. Here id is a single token.
NONTERMS = {"E", "E'", "T", "T'", "F"}
FOLLOW = {
"E": {"$", ")"}, "E'": {"$", ")"},
"T": {"+", "$", ")"}, "T'": {"+", "$", ")"},
"F": {"*", "+", "$", ")"},
}
M = {
("E", "id"): ["T", "E'"], ("E", "("): ["T", "E'"],
("E'", "+"): ["+", "T", "E'"], ("E'", ")"): [], ("E'", "$"): [],
("T", "id"): ["F", "T'"], ("T", "("): ["F", "T'"],
("T'", "*"): ["*", "F", "T'"],
("T'", "+"): [], ("T'", ")"): [], ("T'", "$"): [],
("F", "id"): ["id"], ("F", "("): ["(", "E", ")"],
}
def parse(tokens):
toks = list(tokens) + ["$"]
stack = ["$", "E"]
i = 0
errors = []
while stack:
top, a = stack[-1], toks[i]
if top not in NONTERMS: # terminal or $
if top == a:
stack.pop()
i += 1
elif top == "$": # extra input after a complete parse
errors.append(f"position {i}: skip {a}")
i += 1
else: # assume top was left out
errors.append(f"position {i}: insert {top}")
stack.pop()
elif (top, a) in M:
stack.pop()
stack.extend(reversed(M[(top, a)]))
elif a in FOLLOW[top]: # synch entry
errors.append(f"position {i}: missing phrase {top}")
stack.pop()
else: # skip the token
errors.append(f"position {i}: skip {a}")
i += 1
return errors
print(parse(["id", "+", "*", "id"]))
print(parse(["(", "id"]))
print(parse(["id", "id"]))The output is:
['position 2: skip *']
['position 2: insert )']
['position 1: skip id']The loop terminates because every step either shrinks the stack or advances the input. The one exception is $, which belongs to every FOLLOW set here, so a nonterminal is popped instead of skipping forever.
Panic mode in an LR parser
When ACTION is blank, the parser does this:
- Pop states until it reaches a state
sthat has a GOTO on some nonterminalA. - Discard input tokens until one that can legally follow
A, usually a member of FOLLOW(A). - Push
GOTO[s, A]and resume parsing.
Yacc and Bison use a variant of this. A special terminal error appears in grammar rules, for example stmt -> error ';'. The parser pops states until one can shift error, then skips tokens until the rest of the rule matches.
Phrase-level recovery
Each blank table cell points to an error routine. A routine might insert a missing ;, delete a stray ,, or replace = with ==. The designer must make sure no routine can loop forever. For example, inserting a token without ever consuming input can cycle.
Common mistakes
- Claiming that SLR(1) may shift a wrong symbol. It may reduce first, but it never shifts one.
- Using FIRST(A) instead of FOLLOW(A) for synch entries. FOLLOW is the standard choice.
- Treating a missing semicolon as a lexical error. Every token is valid, so it is a syntax error.
Exercise
In the panic-mode parser above, trace the input id ) (tokens id and )). List each error reported and say what the final stack state is.
Show answer
After id is matched, T' sees ), which is in FOLLOW(T'), so T' expands to ε. E' also expands to ε on ). The stack is now just $ and the lookahead is ). The top is $ and does not match, so the parser reports "position 1: skip )" and advances. It then sees $ against $, matches, and the stack is empty. There is exactly one error.
Exercise
A canonical LR(1) parser, an SLR(1) parser and a LALR(1) parser all run on the same invalid input. Which of them may perform extra reductions before reporting the error, and which shifts the offending token?
Show answer
SLR(1) and LALR(1) may perform extra reductions before reporting, because their reduce actions can apply to lookaheads that exact LR(1) items would reject. Canonical LR(1) reports the error with no such reductions. None of the three shifts the offending token.