10.7. Panic-Mode Error Recovery

Bison supports an error recovery mode called panic-mode error recovery.

There is a special token, error, that is used in recovery from a syntax error. Use it in a production to give the parser an error recovery point.

For example, your grammar might say

  definition : TOK_DEF  idlist  '='  expr  TOK_END

             | error  TOK_END
             ;

In the event of an error, the parser starts a panic.

  1. When a syntax error occurs, yyparse calls yyerror("syntax error").

  2. Next, the parser begins popping its stack until it encounters a state that contains an LR(0) item of the form A error α.

  3. If α is an empty string,

    1. yyparse reduces by production Aerror, and performs the action associated with that production.

    2. yyparse throws away tokens in the input until it finds one on which normal parsing can resume.

    3. yyparse resumes parsing in provisional mode (see item 5).

  4. If α is not empty, then yyparse begins throwing away tokens until it finds a sequence of tokens that can match α.

    Normally, α is a sequence of tokens. After it has shifted α, yyparse reduces by production Aerror α and resumes parsing in provisional mode (see item 5).

  5. After error recovery, yyparse normally stays in a provisional error mode until it has successfully shifted three tokens.

    If another syntax error occurs before three successful shifts, yyparse does not call yyerror(). Instead, it just starts another panic. That avoids lots of syntax error reports as the parser recovers.

    Within an action you can use yyerrok; to exit provisional error mode and resume normal mode. For example:

      definition : error  TOK_END
                     {yyerrok;
                     }
    
    But only do that if you are sure that the parser has fully recovered.