How can I allow keywords as identifiers?

Skip to end of metadata
Go to start of metadata

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.

  1. Sep 14, 2009

    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)

  2. Sep 14, 2009

    We'd have to identify what an identifier is (wink) 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.