views:

241

answers:

1

I have an AST generated via ANTLR, and I need to convert it to a DLR-compatible one (Expression Trees). However, it would seem that i can't use tree pattern matchers for this as expression trees need their subtrees at instantiation (which i can't get). What solution would be best for me to use?

+2  A: 

I did something very similar some years ago - I didn't build a DLR structure, but I built my own expression tree structure, which also needed the arguments at construction time (to achieve immutability).

Back then, I worked with ANTLR v2 - and I must admit, that I'm not familiar with the new v3 syntax, plus I don't remember every detail about how I did it back then - so instead of providing you with a fully worked out example, I'll just try to tell you my story (not sure, if it applies to your problem, too!):

First of all, it wasn't necessary to build my structure from the AST. I only used ANLTR's AST builder as a vehicle: Every AST building rule can return an Object in addition to the AST node itself. The return value can then be used in the outer rule as an argument for the constructor, and so on. So that structure is automatically built bottom up for you!

IOW, you build the final structure at the same time that the AST is built (the AST is only built to ensure the syntax rules, and can be thrown away.) This approach is very solid, and it's even faster than first building the AST, and then transforming that! But it still utilizes the power of the AST parser (as opposed to just using the normal Parser/Lexer alone). And if you need the AST, too - just save it somewhere.

If, however you want to walk a finished AST - I imagine you can use any programmatic routine to do that - just make sure, that it works bottom up to construct your result!

Hope this helps in some way!

Chris Lercher
I was afraid i might have to do the AST conversion manually, however i will look into using the AST builder to make a DLR version of an AST. Thanks!
RCIX
If you have any questions along the way - feel free to ask! I don't have my old code available, but maybe I can recall some of it, when asked about something specifically :-)
Chris Lercher
I just found the corresponding piece in the ANTLR v2 documentation: http://www.antlr2.org/doc/sor.html My code looked similar (though a little bit more complex) to the CalcTreeWalker on that page. Instead of `r=a+b;` I used something like `r = new Product(a, b);`
Chris Lercher
Cool, thanks :)
RCIX