Download ANTLR Reference Manual

Transcript
generate correct code, ANTLR needs to pull in the base grammar and modify it according to the
overridden rules. To see this, consider the following grammar for a simple language:
class Simple;
stat:
|
;
expr ASSIGN expr
SEMICOLON
expr:
;
ID
Clearly, the ID token is the lookahead set that predicts the recognition of the first alternative of
stat. Now, examine a derived dialect of Simple:
class Derived extends Simple;
expr:
|
;
ID
INT
In this case, { ID, INT } predicts the first alternative of stat. Unfortunately, a derived grammar
affects the recognition of rules inherited from the base grammar! ANTLR must not only override
expr in Derived, but it must override stat.
Determinining which rules in the base grammar are affected is not easy, so our implementation
simply makes a copy of the base grammar and generates a whole new parser with the
appropriate modifications. From the programmer's perspective, code/grammar sharing would
have occurred, however, from an implementation perspective a copy of the base grammar
would be made.
Functionality
Grammar Derived inherits from Grammar Base all of the rules, options, and actions of Base
including formal/actual rule parameters and rule actions. Derived may override any option or
rule and specify new options, rules, and member action. The subgrammar does not inherit
actions outside of classes or file options. Consider rule Base defined as:
class Base extends Parser;
options {
k = 2;
}
{
int count = 0;
}
a : A B {an-action}
| A C
;
c : C
;
A new grammar may be derived as follows:
class Derived extends Base;
options {
k = 3;
// need more lookahead; override
buildAST=true;// add an option
131