I've read several papers, articles, and section 4.1.4, chapter 4 of Compilers: Principles, Techniques, and Tools (2nd Edition) (a.k.a "The Dragon Book") which all discuss the topic of syntactical compiler error recovery. However, after experimenting with several modern compilers, I've seen that they also recover from semantic errors, as well as syntactic errors.
I understand fairly well the algorithms and techniques behind compilers recovering from syntacticly related errors, however I don't exactly understand how a compiler can recover from a semantic error.
I'm currently using a slight variation of the visitor pattern to generate code from my abstract syntax tree. Consider my compiler compiling the following expressions:
1 / (2 * (3 + "4"))
The compiler would generate the following abstract syntax tree:
op(/) | ------- / \ int(1) op(*) | ------- / \ int(2) op(+) | ------- / \ int(3) str(4)
The code-generation phase would then use the visitor pattern to recursively traverse the abstract syntax tree and perform type checking. The abstract syntax tree would be traversed until the compiler came to the innermost part of the expression;
(3 + "4"). The compiler then checks each side of the expressions and sees that they're not semantically equivalent. The compiler raises a type error. Here is where the problem lies. What now should the compiler do?
For the compiler to recover from this error and continue type checking the outer parts of the expressions, it would have to return some type (
str) from evaluating the innermost part of the expression, to the next innermost part of the expression. But it simply doesn't have a type to return. Since a type error occurred, no type was deduced.
One possible solution I've postulated, is that if a type error does occur, an error should be raised, and a special value that signifies that a type error occurred, should be returned to previous abstract syntax tree traversal calls. If previous traversal calls encounter this value, they know that a type error occurred deeper in the abstract syntax tree, and should avoid trying to deduce a type. While this method does seem to work, it seems to be very inefficient. If the innermost part of an expression is deep in the abstract syntax tree, then the compiler will have to make many recursive calls only to realize that no real work can be done, and simply return from each one.
Is the method I described above used (I doubt it). If so, is it not efficient? If not, what exactly are the methods used when compilers recover from semantic errors?