Error detection and recovery in compilers
Error detection and recovery in compilers: how compilers find syntax/semantic mistakes and continue so they report useful errors and still produce useful output.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Compilers must report programming mistakes helpfully and continue processing to find more errors. Engineers use error detection and recovery when building front ends (lexers/parsers) and when integrating parser generators (YACC/Bison) so that students and users get meaningful diagnostics without the compiler crashing.
Key ideas
- Error detection — the process of recognising that an input does not conform to expected tokens/productions. In practice, detection happens in the lexer (illegal token) or the parser (no valid action in parse table). Assumption: the lexical and syntactic specifications are correct.
- Error recovery — the strategy a compiler uses after detecting an error to resume parsing so more errors can be reported or to produce a reasonable translation. The central trade-offs are between: reporting many errors vs reporting only correct errors, and between local fixes vs global consistency.
Exact desirable properties of a recovery strategy (stateable in an answer):
- Correctness — recovered parse must not produce an obviously inconsistent abstract syntax tree (AST) or invalid semantic actions. (We assume the parser can detect when recovery would violate invariants.)
- Locality — recovery should change as little of the input as possible near the error (so messages are meaningful).
- Minimality — the edits or token insertions/deletions to fix the error should be minimal.
- Fairness / Progress — recovery must advance input position so parsing does not loop.
Common recovery strategies (define each and state assumptions):
- Panic-mode recovery — on error, discard input tokens until a synchronising token from a set (for example
;,}) is found; then pop stack symbols until a state that accepts the synchronising token is reached and resume. Assumptions: synchronising tokens are chosen so skipping to them likely reaches a statement or block boundary. This is simple, guaranteed to terminate, but may skip many tokens (loss of locality). A common guideline is to select sync sets from FOLLOW sets of major nonterminals (e.g., FOLLOW(stmt), FOLLOW(decl)) so recovery lands at construct boundaries. - Phrase-level recovery — the parser applies local syntactic corrections using error productions or heuristics: insert a missing token, delete an unexpected token, or replace a token. These are implemented as grammar rules that include a special terminal
error. Assumption: common mistakes can be captured by small grammar additions. - Error productions — grammar rules explicitly allow erroneous constructs so the parser can reduce them and continue. Example:
stmt -> IF expr errorlets the parser recover from a missingthenpart. (Used often with YACC/Bison.) The assumption is that the error production does not make the grammar ambiguous in a harmful way. - Global correction (minimum edit distance) — find the smallest sequence of token insertions, deletions, or replacements that transforms the rest of the input to a valid sentence. This gives minimal fixes but is expensive in practice (for general context-free grammars it is solvable in polynomial time, typically O(n^3), via error-correcting parsing/weighted CYK or Earley-style dynamic programming; NP-hardness arises only in extended models or when the grammar is part of the input). Assumption: inputs are small enough or you use approximations/beam search to keep costs manageable.
Exact statement (minimum token edit distance): Given an input token sequence T[1..n] and a valid token sequence S[1..m], the edit distance D(i,j) is the minimal edits to convert T[1..i] to S[1..j]. See the recurrence in Formulas and its derivation below.
What to draw (for exam diagrams):
- Draw a parser stack (vertical boxes) labelled with states or nonterminals on the left, the input token stream (horizontal boxes with token names) on the right, and an arrow showing the current input pointer. If showing panic-mode, label the synchronising token to skip to, and show the stack popping until a state that allows that token. If showing phrase-level recovery, draw the inserted token drawn in a different colour (or labelled INSERT) before the input token in the stream.
Derivation universities ask for (minimum edit distance recurrence):
- Define D(0,0)=0, D(i,0)=i (i deletions), D(0,j)=j (j insertions).
- For i>0, j>0:
- If T[i]==S[j], D(i,j)=D(i-1,j-1).
- Else D(i,j)=1+min(D(i-1,j) [delete T[i]], D(i,j-1) [insert S[j]], D(i-1,j-1) [replace T[i] by S[j]]). This dynamic programming fills an (n+1)x(m+1) table and yields minimum edits.
Practical notes about implementation in compilers:
- Use the lexer to supply helpful token classes (e.g.
id,number,operator) so phrase-level fixes are simpler. - Combine strategies: e.g. try phrase-level small fixes first; if unsuccessful, fall back to panic-mode.
- When using parser generators (YACC/Bison), use the built-in
errortoken and a useryyerrorroutine. Keep error productions minimal to avoid ambiguity. In YACC/Bison, useyyerrok;to reset the error status andyyclearin;to discard the current lookahead token when appropriate during recovery.
Where professors test you: correctness proofs for the DP recurrence, drawing parser stack/input diagrams, writing sample error productions, and comparing strategies in terms of locality and worst-case cost.
Formulas
D(0,0) = 0 — base case: empty to empty requires zero edits.
D(i,0) = i — converting T[1..i] to empty needs i deletions. (i is unitless count of tokens.)
D(0,j) = j — converting empty to S[1..j] needs j insertions.
if T[i] == S[j] then D(i,j) = D(i-1,j-1) else D(i,j) = 1 + min(D(i-1,j), D(i,j-1), D(i-1,j-1)) — token edit-distance recurrence; i and j are token indices, D is number of edits.
Syntax to remember when using YACC/Bison for recovery:
yyerror(const char *s); — user-supplied error-reporting function called by parser. (C signature; adapt for other languages.)
%% stmt: expr ';' | error ';' /* error production: synchronise at semicolon */ ; %% — example grammar fragment showing error token in a production.
/* panic-mode skeleton */ while (current_token not in sync_set && current_token != EOF) current_token = next_token(); while (!parser_state_accepts_any(sync_set) && !stack_empty()) pop_stack(); — pseudocode to skip tokens until sync token.
Worked examples
Example 1 — LL(1) parser with panic-mode
Grammar (simplified):
S -> stmt_list
stmt_list -> stmt stmt_list | ε
stmt -> id '=' expr ';'
expr -> id expr_tail | number
expr_tail -> '+' id | ε
Input: id = id + id ; id = number (missing semicolon after second assignment)
Steps (numbered):
- Parse first statement OK until
;consumed. - Start second stmt; see tokens
id = numberthen EOF. When parser expects;afternumberit sees EOF => syntax error detected. - Panic-mode: choose sync set =
{ ';', EOF }. The parser sees EOF; since EOF in sync set, it treats the statement as terminated (or inserts;) and reports "missing ;". Then parsing ends. Recovery was local and cheap. Result: One error reported, parser terminates cleanly.
Example 2 — YACC error production
Grammar fragment:
if_stmt: IF '(' expr ')' stmt
| IF '(' expr ')' error /* recover from bad stmt */
Input tokens: IF ( x ) id = ; (bad stmt id = ;)
Steps:
- Parser reads
IF ( expr )and tries to parse stmt; seesid = ;and detects error inside stmt. - The second production reduces
IF '(' expr ')' errorso the parser can synchronise at that position, callyyerror("invalid statement in if"), and continue parsing following tokens. Result: Error reported at the inner stmt; parser continues.
Example 3 — minimum edit distance on tokens (DP table)
Let T = [id, =, id, +] (input with trailing +) and a valid continuation S = [id, =, id, ;]
Indices i,j from 0..4. Fill table D:
Row/col headings: j=0..4 for S; i=0..4 for T.
Base rows/cols: D(i,0)=i, D(0,j)=j.
Compute D(1,1): tokens equal (id), so D(1,1)=D(0,0)=0.
D(2,2): = equal => D(2,2)=0.
D(3,3): id equal => D(3,3)=0.
D(4,4): + vs ; unequal => D(4,4)=1+min(D(3,4)=1, D(4,3)=1, D(3,3)=0)=1.
So minimum edit distance = 1 (replace + by ; or delete + and insert ;). The compiler can suggest "replace + with ;".
Common mistakes
- Forgetting to advance input in panic-mode: leads to infinite loops. Always ensure recovery progresses (skip tokens or pop stack).
- Mixing token-level edits and character-level fixes: compilers usually operate at token level; doing character edits without re-lexing can be incorrect.
- Presenting minimum edit distance as always affordable: theoretically polynomial (often O(n^3)) for CFGs but with large constants; in practice it may be too costly on long inputs—clarify assumptions, limits, or approximations.
For your exam
Kinds of questions:
- Definitions: define syntax vs semantic error, error detection vs recovery, and the standard recovery strategies.
- Short notes: compare panic-mode, phrase-level recovery, error productions, and global correction; give pros/cons.
- Derivation: derive the DP recurrence for minimum edit distance and show correctness by induction.
- Algorithms/programs: write pseudocode for panic-mode recovery or for computing token edit distance and show a table on a small input.
- Diagrams: draw parser stack and input, show how synchronising token leads to stack pops.
What a full-marks answer includes:
- Clear definitions with bold terms (syntax/semantic/error recovery).
- Correct description of at least two recovery strategies, with a discussion of trade-offs (locality, minimality, cost).
- One worked example or a DP table derivation (if asked about edit distance).
- For parser-generator questions, include correct YACC/Bison syntax showing the
errortoken andyyerrorusage.
Quick check
- Name two synchronising tokens commonly used in panic-mode recovery.
- What does an error production look like in YACC/Bison? Give a short example.
- State the recurrence for token edit distance when tokens differ.
Answers: 1)
;and}(often statement and block delimiters). 2)stmt: error ';' ;(a production usingerrorto sync at semicolon). 3)D(i,j) = 1 + min(D(i-1,j), D(i,j-1), D(i-1,j-1))when T[i] != S[j].
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?