Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 define reserved keywords in the grammar file in ANTLR ?

Thanks in advance Shamika

like image 280
Aina Ari Avatar asked Oct 24 '10 13:10

Aina Ari


1 Answers

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.

like image 99
Bart Kiers Avatar answered Oct 13 '22 04:10

Bart Kiers