5. Error handling
The parser produced so far has a major drawback: on receiving an input program with syntactic errors, such as ErroneousProgram.mjava, it will stop with a Fatal Syntax Error Exception on the first error occurrence, as shown in ErroneousProgramResult.txt.
This behavior is quite unkind to the user, who would like to have all the errors reported, not just the first one.
Cup supports a local error recovery mechanism, based on a special error symbol, to allow the parser to continue when a syntactic error occurs: whenever the error symbol appears in a grammar rule, it can match a sequence of erroneous input symbols.
On encountering an error action, the parser:
1. pops the stack until a state including an item obtained from an error rule A ::= error a is reached
2. shifts a fictitious error token onto the stack, as though error was found on input
3. skips ahead on the input, discarding symbols until a substring is found that can be reduced to a
4. reduces error a to A
5. emits a diagnostic message
6. resumes normal parsing.
Unfortunately this error recovery mechanism is not powerful enough to correctly report any kind of syntactic error: error rules cannot be inserted anywhere into an LALR grammar because they may introduce both shift/reduce and reduce/reduce conflicts.
A parser with error rules for mjava is specified in mjava.cup.