[antlr-interest] v3: going through the AST

Dieter Frej dieter_frej at gmx.net
Wed Aug 16 08:01:03 PDT 2006


that is the reason why I am asking: antlrworks shows immediately the
write way which seems to be different from the way a get it in my
program. How are they doing it? (cannot look since I do not have any
source code of it ;-)

- Didi



Thomas Brandon wrote:
> Without any restructuring the default tree output from a grammar will
> be a single tree node for each token, without any child or parent
> relationships. So a rule "a: A B C;" will simply produce the tree "A B
> C" which is basically a linked list. You need to add either tree
> rewrite rules or tree operators to structure the tree as you would
> like. For instance to make a give token the root suffix it with "^".
> So something like "a: A^ B C;"
> would produce the tree "(A B C)". Or you can use a rewrite rule. So
> "a: A B C -> ^(A C B);" would produce the tree "(A C B)".
> 
> Also, the Antlrworks debug functionality will allow you to view the
> AST tree in a visual form rather than having to print it out to text.
> 
> Tom.
> On 8/16/06, Dieter Frej <dieter_frej at gmx.net> wrote:
>> Hi,
>>
>> I added output=AST; to the options section of the latest java.g 
>> grammar in
>> order to get the AST. This makes a new method public Object getTree()
>> available.
>> What I would like to get was something like the tree structure visualised
>> in antlrworks. So I tried the following:
>>
>> CommonTree tree = (CommonTree) parser.compilationUnit().getTree();
>> String[] names = parser.getTokenNames();
>> int childCount = tree.getChildCount();
>> for(int i = 0; i < childCount; ++i) {
>>     CommonTree ct = (CommonTree) tree.getChild(i);
>>     System.out.println("childcount: " + ct.getChildCount());
>>     System.out.println("tree type: " + ct.getType() + "|" + 
>> names[ct.getType()]);
>>     System.out.println("text: " + ct.token.getText());
>>     System.out.println("line: " + ct.getLine());
>>     System.out.println("toString: " + ct.toString());
>>     System.out.println("toStringTree: " + ct.toStringTree());
>>     System.out.println();
>> }
>>
>> but tree.getChildCount() is always 1. It is more like a linked list 
>> than a
>> tree.
>>
>> Any suggestions? Or is my code wrong? (because of the lack of examples
>> that could also be the case ;-)
>>
>> - Didi
>> -- 
>>
>>
>> "Feel free" – 10 GB Mailbox, 100 FreeSMS/Monat ...
>> Jetzt GMX TopMail testen: http://www.gmx.net/de/go/topmail
>>
> 
> 



More information about the antlr-interest mailing list