views:

30

answers:

2

Hi, 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

A: 

This ANTLR 2.0 tutorial discusses how to deal with keywords in an ANTLR lexer. Just search for the section entitled "Keywords".

There's a link at the top of the page to a video-based tutorial for ANTLR 3.0, if that is more to your liking.

Stephen C
A: 

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.

Bart Kiers