[antlr-interest] How to build parser for initialization statement in non LL(K) grammar

Pavel Ganelin ganelin at mail.com
Tue Jan 16 19:09:08 PST 2007


Hi,

(ANTLR version 2.7.7)

I have a question about writing grammar for a language with the 
following variable initialization statement.

Here is an example of the statement in this language.

x y z 1 m n 2 k l p q ;

Variables x,y,z are set to 1; m,n are set to 2 and k,l,p,q are set to 0. 
Please note that for the last list you may skip the initial value and it 
is interpreted as 0.

I want the resulting parsing tree for this example look like this:
( 1 x y z) ( 2 m n ) ( 0 k l p q)

i.e. initialization value at the beginning of the list and then a list 
of variables for this value;

Originally I had the following grammar with very long look ahead. It 
worked OK for a while

grammar:
( list ) * SEMI
;

list!:
( vars INT ) => v:vars i:INT {##=([NODE],#i,#v)};}
| vars {##=([NODE],[INT,”0”],#v);}
;

vars:
(IDENT) +
;

The approach broke down when I had to add semantic actions to the vars 
(to convert unreserved keywords to identifiers). Is there a better way 
to solve this problem without large (i.e. the full variable list) look 
ahead?

Alternative approach below with just single variable lookahead is good 
for parsing, but I do not know how to build the tree here.

list:
recursive
;

recursive:
IDENT
(
(IDENT) =>recursive
| INT // how to build the tree here I have just the last var in the list 
here
| //ditto
)
;

Sincerely,
Pavel




More information about the antlr-interest mailing list