Error Messaging and Recovery
This document will lead you through a simple lex & yacc example which
shows one way to implement error recovery and error messaging. You
should be able to apply the basic principles below to your own project
with relative ease.
The Yacc File
This
yacc file
demonstrates a number of features you
may wish to use in your project. Among these features:
- Error Recovery Using the "error" rule
- The "main()" function has been overridden
- Error Messages Displaying:
- Current Line Number
- Text of the Bad Token
The Error Rule
The effect of the error rule is to make errors admissable in
the grammar. After recognizing an error, the "error" rule allows the
compiler to continue processing input. The "error" rule is triggered much
like a default (otherwise) action in a case statement in that it is
triggered by anything other than the expected token within a rule.
In the event of error within the sound rule, the printf next to "error"
is executed. Remember that the grammar will require three successive
"valid" tokens before it will reset itself and issue further errors.
The Lex File
Notice in this
Lex file
how the variable "linenum"
is incremented. This variable, defined near the bottom of the yacc file,
is used in the error messages.
Try It!
Go into the Lex and Yacc files and use "Save As" under the file menu
to save these files (error.l and error.y) into your home directory
along with the
makefile
then type "make." The grammar takes a
potentially endless string of "ding dong dell" rhymes.
Error Messaging and Recovery - Rev. 30 April '94 / Ben Steel