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 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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With