[antlr-interest] Tree grammar: How to handle rule arguments

Stephanie stephanie.balzer at gmail.com
Fri Oct 15 08:05:19 PDT 2010


Hello,

I have implemented a parser grammar as well as a tree parser for a little
Java-like language. I have encounter difficulties with the following
productions

parser grammar:

declList

: ( varDecl | methodDecl )+

;


varDecl

: varType=type identList[$varType.tree]

-> identList

;


identList[Object varType]

: id=Identifier ( ',' Identifier )*

-> ^( VarDecl[$id, "VarDecl"] { $varType } Identifier )+

;


I have checked the parser grammar using ANTLRWorks' debugger and it works as
expected. E.g., for the input


int x, y, z;


it creates three VarDecl nodes, whereby each node has int as its left child
and the identifier as its right child.



I use the following rules in the tree grammar:


tree grammar:


declList[ArrayList<Decl> members]

: ( v=varDecl { $members.add($v.var) } | m=methodDecl {
$members.add($m.mth); } )+

;


varDecl returns [VarDecl var]

: ^( VarDecl t=type n=Identifier )

{ $var = new VarDecl($t.text, $n.text); }

;

However, if I pass above example, i.e.,

int x, y, z;

as input to the walker, I get only one variable declaration: int z. The
variables x and y are lost (it turns out that only the last identifier is
kept).

I guess that there is a problem in my construction of the tree grammar
rules. In particular, I merged identList with varDecl and I removed '+' from
^(VarDecl ...). However, if I keep the '+', I get ambiguity.

What would the correct tree grammar rule be?

Thanks a lot for your help!

Stephanie


More information about the antlr-interest mailing list