Define Keywords in ANTLR grammar
I want to build a simple lexical analyzer for a specific language which has reserved words like (if, else, etc.) using ANTLR. I went through several tutorials and was able to find the ways of defining all the options except reserved keywords. How to 开发者_JAVA技巧define reserved keywords in the grammar file in ANTLR ?
Thanks in advance Shamika
Define them before a rule that can possibly match those keywords.
For example, you have a rule that matches identifiers, where an identifier consists of one ore more letters, then your reserved if
keyword should be places before the identifier rule in your lexer:
grammar T;
// parser rules here
IF
: 'if'
;
IDENTIFIER
: ('a'..'z')+
;
That way, an if
will always become a IF
token and not an IDENTIFIER
.
精彩评论