Course contentsShow
← Computer Science
Lesson 1972 of 2,87244. Lexical Analysis and ParsingFree lesson

LR Parser Error Recovery

Strategies for detecting and recovering from syntax errors in bottom-up parsing.

LR Parser Error Recovery

What You'll Learn

You'll learn practical strategies for detecting and recovering from syntax errors during bottom-up LR parsing so your compiler can report multiple errors in one pass.

Why Error Recovery Matters

When an LR parser encounters invalid input, it detects an error the moment it cannot perform a valid shift or reduce action—there's no entry in the parsing table for the current state and input token. Without error recovery, the parser would simply halt at the first error. But professional compilers should identify multiple errors in a single compilation pass, helping developers fix issues faster.

Error Recovery Strategies

1. Panic Mode Recovery

The simplest approach: when an error occurs, discard input tokens until you find a synchronizing token (like semicolons, closing braces, or statement keywords). Then pop states from the parser stack until you reach one that can legally accept that synchronizing token. Resume parsing from there.

Analogy: Like a GPS recalculating when you miss a turn—it skips ahead to find the next known landmark.

2. Phrase-Level Recovery

Make local corrections by inserting, deleting, or replacing tokens. For example, if you expect a semicolon but find a keyword instead, insert the missing semicolon conceptually and continue. This is more sophisticated but requires careful design to avoid infinite loops.

3. Error Productions

Augment your grammar with productions that match common mistakes (like missing operators or mismatched parentheses). When the parser reduces using an error production, it reports the specific problem and continues.

4. State Stack Inspection

Examine the stack of LR parser states to determine what constructs are incomplete. This context helps generate meaningful error messages like "expected closing parenthesis for expression started on line 42."

Key Takeaway: LR parser error recovery uses strategies like panic mode (skip to synchronizing tokens), phrase-level corrections, error productions, and stack inspection to detect syntax errors immediately while continuing to find additional errors in the same pass.