| 1 |
Semantic error recovery once again requires judgment on the part of the |
| 2 |
grammar-writer. For example, an assignment expression may be syntactically |
| 3 |
defined as |
| 4 |
verb( |
| 5 |
expr '=' expr |
| 6 |
) |
| 7 |
The assignment operator's left-hand side must be a so-called |
| 8 |
em(lvalue). An em(lvalue) is simply an addressable location, like a variable's |
| 9 |
identifier, a dereferenced pointer expression or some other |
| 10 |
address-expression. The right-hand side is a so-called em(rvalue): this may be |
| 11 |
any value: any expression will do. |
| 12 |
|
| 13 |
A rule like the above leaves room for many different semantic errors: |
| 14 |
itemization( |
| 15 |
it() Since the rule's LHS equals tt(expr), em(any) expression is accepted |
| 16 |
by the parser. E.g., |
| 17 |
verb( |
| 18 |
3 = 12 |
| 19 |
) |
| 20 |
So, the action associated with this rule should em(check) whether the |
| 21 |
expression's left-hand side is actually an lvalue. If not, a em(semantic) |
| 22 |
error should be reported; |
| 23 |
it() In a typed language (like bf(C++)), not all assignments are |
| 24 |
possible. E.g., it is not acceptable to assign a bf(std:string) value |
| 25 |
to a bf(double) variable. When conflicting types are used, a em(semantic) |
| 26 |
error should be reported; |
| 27 |
it() In a language requiring variables to be defined or declared before |
| 28 |
they are used (like bf(C++)) the parser should check whether a variable is |
| 29 |
actually defined or declared when it is used in an expression. If not, a |
| 30 |
em(semantic) error should be reported |
| 31 |
) |
| 32 |
A parser that should be able to detect semantic errors normally uses a |
| 33 |
counter counting the number of semantic errors, e.g., tt(size_t |
| 34 |
d_nSemanticErrors). It may be possible to test this counter's value once the |
| 35 |
input has been parsed, calling tt(ABORT()) (see section ref(PRIVMEM)) if the |
| 36 |
counter isn't zero anymore. When the grammar's start symbol itself has |
| 37 |
multiple alternatives, it is probably easiest to augment the grammar with an |
| 38 |
additional rule, becoming the augmented grammar's start symbol which simply |
| 39 |
calls the former start symbol. For example, if tt(input) was the name of the |
| 40 |
original start-symbol, augment the grammar as follows to ensure a |
| 41 |
bf(PARSE_ABORT) return value of the tt(parse()) member when either syntactic |
| 42 |
or semantic errors were detected: |
| 43 |
verb( |
| 44 |
semantic_input: // new start-symbol |
| 45 |
input |
| 46 |
{ |
| 47 |
if (d_nSemanticErrors) // return PARSE_ABORT |
| 48 |
ABORT(); // on semantic errors too. |
| 49 |
} |
| 50 |
) |
| 51 |
Returning from the parser's tt(parse()) member the number of syntactic |
| 52 |
and semantic errors could then be printed, whereupon the program might |
| 53 |
terminate. |