3

I am working with ANTLR 3.4 .I have defined a lexer rule like

Description:
'description'
 ;

If I use this rule I will not be able to use 'description' in my language since it is now a keyword.Is there any way by which I can write a rule for non reserved keyword. The rules in grammar looks like-

Lexer rule

Description
:
'description'
;

Protocol
:
'protocol'
;
Define
:
'define'
;
Equal
:
'='
;




Parser rule


mainrule
:
Define Protocol stringrule descrule? fields* finishrule
;

descrule
:
Description? stringrule?
;

fields
:
type stringrule  Equal? stringrule?

stringrule
:
// rule which accept any string
;

Example:My language looks like this-

define protocol description 'Protocol for login'
int ip=192.168.0.0;
string description='remote user';
finish protocol;

Here ip and description are fields of protocol and protocol is having description(which is keyword).But I cannot use 'description' as field name as it is a keyword.

carlspring
  • 31,231
  • 29
  • 115
  • 197
bhavanak
  • 255
  • 1
  • 12
  • We need more context. Where in the language would you like to use `for` as not a keyword? What would the grammar look like? Some examples of what you mean would be helpful. – Jim Garrison Jul 19 '16 at 07:02
  • I have modified the question.Can you please help. – bhavanak Jul 19 '16 at 07:21
  • Why do you need to use exactly the same word for both? Can't you use a different word for the attribute name? Or explicitly write your grammar to allow certain keyword terminals to appear as attribute names? You need to write the complete grammar for your example so we have something to go on. – Jim Garrison Jul 19 '16 at 07:25

1 Answers1

2

Make stringrule match any keyword and your lexer's identifier rule:

stringrule
 : Description
 | Protocol
 | Define
 | Identifier
 ;

Description
 : 'description'
 ;

Protocol
 : 'protocol'
 ;

Define
 : 'define'
 ;

Identifier
 : ('a'..'z' | 'A'..'Z')+
 ;
Bart Kiers
  • 166,582
  • 36
  • 299
  • 288