11. Error Recovery
Parsing past mistakes
The one-error-at-a-time problem
You sit down, write fifty lines of code, hit compile, and the compiler says:
Error on line 3: Expected
;after statement.
You fix it. Recompile. Now it says:
Error on line 17: Undefined variable
reuslt.
Fix. Recompile. Line 34. Fix. Recompile. Line 48. You do this dance five more times before the code finally compiles. Every cycle costs you thirty seconds of waiting and a little bit of sanity.
Good parsers don't stop at the first mistake. They recover from the error and keep going, collecting as many diagnostics as possible in a single pass. That's what this article is about: the strategies parsers use to survive your typos.
Panic mode recovery
The oldest and most common strategy is called panic mode. The idea is simple: when the parser hits something unexpected, it throws away tokens until it finds a synchronization point — a token it recognizes as the start of a new, well-formed construct.
Think of it like fast-forwarding through static on a radio until you hit a clear signal again.
Synchronization tokens
What counts as a synchronization point depends on the language. Common choices:
- Semicolons (
;) — the end of a statement in C-like languages - Closing braces (
}) — the end of a block - Keywords like
function,class,if,return— the start of a new declaration or statement
The parser discards everything between the error and the sync token, then resumes parsing as if nothing happened.
Adding panic mode to recursive descent
Here's a sketch. We wrap statement parsing in a try/catch and advance to the next semicolon on failure:
function synchronize(parser) {
parser.advance(); // skip the bad token
while (!parser.isAtEnd()) {
// If we just passed a semicolon, we're at a statement boundary
if (parser.previous().type === 'SEMICOLON') return;
// If the next token starts a new statement, stop here
switch (parser.peek().type) {
case 'CLASS':
case 'FUNCTION':
case 'LET':
case 'FOR':
case 'IF':
case 'WHILE':
case 'RETURN':
return;
}
parser.advance();
}
}
And the parsing loop uses it like this:
function parseProgram(parser) {
const statements = [];
const errors = [];
while (!parser.isAtEnd()) {
try {
statements.push(parseStatement(parser));
} catch (err) {
errors.push(err);
synchronize(parser);
}
}
return { statements, errors };
}
After catching an error, we call synchronize() to skip ahead, then continue the loop. One pass, many errors.
Error productions
Panic mode is reactive — it kicks in after something goes wrong. Error productions are proactive. You add grammar rules that explicitly match common mistakes.
For example, say programmers often forget the parentheses around an if condition:
// Normal rule
ifStmt → "if" "(" expression ")" block
// Error production: missing parentheses
ifStmt → "if" expression block // report: "Expected '(' before condition"
When the parser matches the error production, it emits a diagnostic but still produces a valid AST node. No synchronization needed — the parser never lost its place.
Examples of useful error productions
| Mistake | Error production matches | Message |
|---|---|---|
if x > 3 { ... } |
if without ( |
Missing parentheses around condition |
x = ; |
Assignment with missing right-hand side | Expected expression after = |
fn foo() { return } |
Return without value where one's expected | Missing return value |
let x = 5 5; |
Two expressions with no operator | Missing operator between expressions |
The downside: you need to anticipate mistakes in advance, and too many error productions can make the grammar messy.
Inserting and deleting tokens
Some parsers go a step further and fix the input on the fly:
- Insertion: "I expected a semicolon here, so I'll pretend there is one and keep going."
- Deletion: "This token doesn't belong here. I'll skip it and retry."
function expect(parser, type, message) {
if (parser.check(type)) {
return parser.advance();
}
// Instead of throwing, insert a synthetic token
parser.reportError(message);
return { type: type, value: null, synthetic: true };
}
This is powerful but dangerous. If the parser guesses wrong about what's missing, it can misinterpret everything that follows.
The cascade problem
The biggest enemy of error recovery is cascading errors. One real mistake causes the parser to misunderstand the code, which triggers a second "error" that isn't actually wrong, which triggers a third, and so on.
Consider this input with one mistake (missing +):
let x = 3 4 + 5;
A naive parser might report:
- Expected
;after3(the real issue: missing operator) - Unexpected token
4(cascade) - Unexpected token
+(cascade) - Unexpected token
5(cascade)
Four errors, one bug. That's noise, not signal.
Strategies to reduce cascading
1. Error limits. Stop reporting after errors (often 10 or 20). GCC and Clang both do this.
const MAX_ERRORS = 20;
if (errors.length >= MAX_ERRORS) {
errors.push("Too many errors — aborting.");
return { statements, errors };
}
2. Suppression zones. After reporting an error, suppress further errors until the parser has successfully consumed a few tokens. If the parser hasn't "found its footing," any new errors are probably cascades.
function reportError(parser, message) {
if (!parser.inErrorState) {
parser.errors.push(message);
}
parser.inErrorState = true;
}
function advance(parser) {
// ... advance token ...
parser.tokensConsumedSinceError++;
if (parser.tokensConsumedSinceError > 3) {
parser.inErrorState = false;
}
}
3. Smart synchronization. Choose sync points carefully. Synchronizing to ; works well for statement-level errors. For expression-level errors inside parentheses, synchronizing to the matching ) is better.
Writing good error messages
Error recovery gives you the chance to report errors — but the messages themselves matter enormously.
Bad:
Syntax error at line 7.
Better:
Error [line 7, col 12]: Expected ')' to close function call
started at line 5, col 8.
Best:
Error: Expected ')' to close function call.
5 | result = compute(
6 | alpha,
7 | beta
| ^ expected ')' here
Note: opening '(' is at line 5, column 18.
Good error messages have:
- Location — line and column, ideally with a source snippet
- What was expected — not just "syntax error" but "expected
)" - Context — where the matching delimiter or construct started
- Suggestions — "Did you mean
===?" or "Add a;here?"
Putting it all together
Here's a more complete picture of a parser with recovery:
class Parser {
constructor(tokens) {
this.tokens = tokens;
this.pos = 0;
this.errors = [];
this.panicMode = false;
}
parse() {
const stmts = [];
while (!this.isAtEnd()) {
const stmt = this.declaration();
if (stmt) stmts.push(stmt);
}
return { ast: stmts, errors: this.errors };
}
declaration() {
try {
if (this.match('LET')) return this.letDeclaration();
return this.statement();
} catch (e) {
this.synchronize();
return null;
}
}
letDeclaration() {
const name = this.expect('IDENTIFIER', "Expected variable name");
this.expect('EQUALS', "Expected '=' after variable name");
const value = this.expression();
this.expect('SEMICOLON', "Expected ';' after value");
return { type: 'let', name, value };
}
expect(type, message) {
if (this.check(type)) return this.advance();
this.error(message);
}
error(message) {
if (!this.panicMode) {
const tok = this.peek();
this.errors.push({
message,
line: tok.line,
col: tok.col
});
}
this.panicMode = true;
throw new SyntaxError(message);
}
synchronize() {
this.panicMode = false;
this.advance();
while (!this.isAtEnd()) {
if (this.previous().type === 'SEMICOLON') return;
if (['LET','FUNCTION','IF','WHILE','RETURN']
.includes(this.peek().type)) return;
this.advance();
}
}
}
The key pieces: panicMode suppresses cascading errors, synchronize() fast-forwards to a safe place, and expect() reports what the parser wanted when it didn't get it.
Summary
| Strategy | How it works | Strength | Weakness |
|---|---|---|---|
| Panic mode | Skip to sync token | Simple, reliable | Loses AST nodes |
| Error productions | Grammar rules for common mistakes | Preserves AST | Needs anticipation |
| Token insertion | Pretend the missing token exists | Minimal disruption | Can misguess |
| Token deletion | Skip unexpected token | Simple | Can misguess |
| Suppression | Ignore errors until stable | Reduces cascades | Might hide real errors |
No parser uses just one of these. Real compilers like GCC, Clang, and Rust's rustc combine all of them, tuned over years of user feedback. The goal is always the same: show programmers as many real errors as possible, with as little noise as possible, in a single pass.
Try It Yourself — Error Recovery
Enter some code with deliberate syntax errors. The parser will attempt to recover from each one and report all errors it finds in a single pass. Watch how synchronization skips tokens to find the next safe point.