Keyword Definition in ANTLR Grammar

I want to create a simple lexical analyzer for a specific language that has reserved words such as (if, else, etc.) using ANTLR. I went through several tutorials and was able to find ways to define all parameters except reserved keywords. How to define reserved keywords in a grammar file in ANTLR?

Thanks in advance Shamika

+4
source share
2 answers

Define them before a rule that can match these keywords.

For example, you have a rule that matches identifiers, where an identifier consists of one or more letters, then your reserved if keyword should be placed before the identifier rule in your lexer:

 grammar T; // parser rules here IF : 'if' ; IDENTIFIER : ('a'..'z')+ ; 

Thus, if will always become an if token, not an IDENTIFIER .

+8
source

This ANTLR 2.0 tutorial discusses how to work with keywords in ANTLR vocabulary. Just find the Keywords section.

At the top of the page there is a link to the video tutorial for ANTLR 3.0, if you like.

+2
source

All Articles