Simple Error Recovery
Previous: <Infix Calc=>InfixCalc> * Next: <Multi-function Calc=>Multifunct> * Up: <Examples=>Examples>

#Wrap on
{fH3}Simple Error Recovery{f}

Up to this point, this manual has not addressed the issue of {fUnderline}error
recovery{f}---how to continue parsing after the parser detects a syntax
error.  All we have handled is error reporting with {fCode}yyerror{f}.  Recall
that by default {fCode}yyparse{f} returns after calling {fCode}yyerror{f}.  This
means that an erroneous input line causes the calculator program to exit.
Now we show how to rectify this deficiency.

The Bison language itself includes the reserved word {fCode}error{f}, which
may be included in the grammar rules.  In the example below it has
been added to one of the alternatives for {fCode}line{f}:

#Wrap off
#fCode
line:     '\\n'
        | exp '\\n'   \{ printf ("\\t%.10g\\n", $1); \}
        | error '\\n' \{ yyerrok;                  \}
;
#f
#Wrap on

This addition to the grammar allows for simple error recovery in the event
of a parse error.  If an expression that cannot be evaluated is read, the
error will be recognized by the third rule for {fCode}line{f}, and parsing
will continue.  (The {fCode}yyerror{f} function is still called upon to print
its message as well.)  The action executes the statement {fCode}yyerrok{f}, a
macro defined automatically by Bison; its meaning is that error recovery is
complete (\*Note <Error Recovery=>ErrorRecov>).  Note the difference between
{fCode}yyerrok{f} and {fCode}yyerror{f}; neither one is a misprint.

This form of error recovery deals with syntax errors.  There are other
kinds of errors; for example, division by zero, which raises an exception
signal that is normally fatal.  A real calculator program must handle this
signal and use {fCode}longjmp{f} to return to {fCode}main{f} and resume parsing
input lines; it would also have to discard the rest of the current line of
input.  We won't discuss this issue further because it is not specific to
Bison programs.

