[antlr-interest] How to communicate between rules in a tree grammar

Sanchay Harneja sanchay.h at gmail.com
Wed Apr 20 05:47:42 PDT 2011


Hi,

I am new to ANTLR, using it to create a DSL. So far I've been able to write
a parser grammar, a tree grammar & string template file. Its all working as
I expect.

But I have a niggling feeling that I may not be using the tree grammar & stg
in an idiomatic manner. I'll ask my question using an example, suppose the
tree grammar has rules a, b, c:

options {
    ...
    output=template;
}

a :
    // ...
    -> template( .. )

b : returns [ int x, int y ]
    // only return no string template

c : b (as+=a)+
    -> c(x={$b.x}, y={$b.y}, as={$as})

This works fine, but is it an "correct" way? In the generated code the type
of $b is b_return while the type of $as is List(containing StringTemplate
objects).

Now suppose I have a rule like:

d : a (bs+=b)+
     -> d(a={$a}, bs={$bs})

This doesn't work, as the type of $bs is List containing StringTemplate
objects, but not b_return objects. Since I haven't defined a StringTemplate
for b, this doesn't work.

Maybe this is the right thing to do, i.e., in rule c type of $b is b_return,
whereas in rule d type of $bs is List(containing StringTemplates as opposed
to b_returns).  But then how I communicate the structure of b (i.e. x, y) to
d ? One way is maintaining a global memory for this. Is there any other way?
How would you guys tackle this issue.

Thanks!
Sanchay


More information about the antlr-interest mailing list