This grammar allows "if if call call;" and "call if;".
grammar Pred;
prog: stat+ ;
stat: keyIF expr stat
| keyCALL ID ';'
| ';'
;
expr: ID
;
keyIF : {input.LT(1).getText().equals("if")}? ID ;
keyCALL : {input.LT(1).getText().equals("call")}? ID ;
ID : 'a'..'z'+ ;
WS : (' '|'\n')+ {$channel=HIDDEN;} ;
You can make those semantic predicates more efficient by intern'ing those strings so that you can do integer comparisons instead of string compares.
The other alternative is to do something like this
identifier : KEY1 | KEY2 | ... | ID ;
which is a set comparison and should be faster.
Labels:
2 Comments
Hide/Show CommentsSep 14, 2009
John Pool
Would it be possible to add an ANTLR option keyword_as_id = yes, which has the effect that an (unexpected) keyword, found at a place where an identifier would be legal, would be considered an identifier? (of course only if its shape conforms to the lexical pattern of an identifier)
Sep 14, 2009
Terence Parr
We'd have to identify what an identifier is
Good idea but I'm trying to avoid more and more options and stuff. Better to do things "manually" in this case. Multiple ways to handle it.