[antlr-interest] [newbie] AST Rewriting

Eric researcher0x00 at gmail.com
Mon Mar 19 08:33:34 PDT 2012


Hi Robin,

First off, it is very likely that what you want to do can be done by using
tree rewrite rules, I can not say positively because I haven't tried it for
your problem.

I personally have a hard time understanding rewrite rules when I am doing
multi-pass AST transformations, i.e. tree rewrites, as such I now do all
of my transformations via calls to the tree API. Also note that ANTLR
4.x will no longer be supporting tree rewrites in the grammar; currently
ANTLR 3.x be will the last version to support them.

Since you already know how to get the AST, all you have to do now is treat
the AST as any n-ary tree and manipulate.

Instead of jumping right into your problem, take some time to write a tree
walker, a print routine, and some search routines, i.e. find text, find
node type, return a node, return a branch with children, etc.. You will
need to write them because they will help you understand trees and for
debugging.

Next you will need to understand the basic methods in the tree API,
basically the BaseTree, and CommonTree classes.
If you take a look at the previous post "Help with compressin​g trees and
custom nodes" you will find some C# examples I give for using them.

This suggestion is light on examples because you need to work through it to
learn it.

Remember this is not the only solution, but how I would do it.

Eric





On Mon, Mar 19, 2012 at 7:04 AM, Robin <diabeteman at gmail.com> wrote:

> Hello list :)
>
> I am trying to rewrite an AST (by filtering out most of the nodes). From
> what i could read on antlr wiki and some interesting forums & other medias,
> you can do this with tree grammars and tree operators "->".
>
> The grammar I use to generate AST is here
> http://www.antlr.org/grammar/1207932239307/Java1_5Grammars and here is my
> test rig http://pastebin.com/LeR4miVu
>
> I modified JavaTreeParser.g and added the options output = AST; and rewrite
> = true; Also, just for testing purposes, I added "->" at the end of each
> rule in order to filter out all of the nodes. Here is what it looks like
> http://pastebin.com/u6UG7fEB
>
> The problem is that in my test rig, the returned tree is not rewrited at
> all.
>
> I am sure I'm doing something wrong. Could you help ?
>
> Thanks in advance,
> Robin
>
> List: http://www.antlr.org/mailman/listinfo/antlr-interest
> Unsubscribe:
> http://www.antlr.org/mailman/options/antlr-interest/your-email-address
>


More information about the antlr-interest mailing list