Define Keywords in ANTLR grammar

antlr, compiler-construction, java

Solution

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`.

Problem

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

Original source