[antlr-interest] [antlr-dev] Need help with tree traversing in ANTLR 3.3!

Sam Harwell sharwell at pixelminegames.com
Fri Jun 10 12:06:38 PDT 2011

Hi Payam,

Any rule in a parser or tree parser can return 0 or more items. Since the
Java method implementing a rule can only return 0 or 1 items, some special
handling is in place to allow you to do what you're after. Consider a rule
"foo" which currently returns a single int:

foo returns [int x] : {$x = 3;} ;

In a regular parser (non-AST), the rule will be generated as:

private int foo();

When you add the "output=AST" option, the rule now returns 4 values:

options {

1. int x
2. ASTLabelType tree
3. LabelType start
4. LabelType stop

The function is generated as follows:

foo_return foo();

Which you can call like this to get the return values:

foo_return result = parser.foo();
int x = result.x;
CommonTree tree = result.tree;


On Jun 10, 2011, at 10:01 AM, Payam Fard wrote:

> Dear all,
> I have a grammar for a fairly small and simple language that I have
created for our project. Once every command in this language is parsed
through this grammar, a Java object is returned. Everything is working fine.
> Now, I have a requirement to read all the available rules/commands of the
language (I am only interested in the command/rule names). In order to do
so, I have been trying to get the AST tree working by adding options to my
grammar for AST tree. For some reason, when I add these options to my
grammar, I am getting compilation error complaining that my grammar rules
cannot return any Java objects! Can I have commands/rules of my grammar
return some Java objects and at the same time be able to build an AST tree
off of my grammar?
> Is there an easy way to read these grammar command/rule names using antlr
runtime API's?
> Any code sample out there that shows how do to the above (namely returning
objects from grammar rules and building the tree at the same time)?
> Any help here would be greatly appreciate.
> _______________________________________________
> antlr-dev mailing list
> antlr-dev at antlr.org
> http://www.antlr.org/mailman/listinfo/antlr-dev

List: http://www.antlr.org/mailman/listinfo/antlr-interest

More information about the antlr-interest mailing list