[antlr-interest] transforming AST nodes

Tom Smith yotommy at gmail.com
Fri Dec 7 12:22:23 PST 2007


In the absence of any advice to date, I've implemented Option 1, which
appears to work.  However any advice on improvements are still
welcome!

Thanks,
Tom.

On Dec 6, 2007 10:37 AM, Tom Smith <yotommy at gmail.com> wrote:
> Hello,
>
> I am seeking advice on good ways to transform the structure of some
> AST nodes.  My example involves translating a language that supports
> multiple assignment into one that does not.  The grammar (shown below)
> parses input of the form:
>
>     a, b = c, d
>
> into
>
>     ^(ASSIGN ^(LIST a b) ^(LIST c d))
>
> However I would like a structure more like:
>
>     ^(LIST ^(ASSIGN a c) ^(ASSIGN b d))
>
> I've considered two ways of accomplishing this.  I'd appreciate
> feedback on these, or suggestions for a better alternative.
>
> Option 1.  Change the rewrite expression for multAssign such that it
> uses custom Java code to create a new tree node with the desired
> structure.
>
> Option 2.  Create a tree grammar with output=AST that performs the
> desired transformation.  However if I understand correctly, this is
> only available in antlr 3.1.  Is that correct, and is it available
> somewhere?  And will I end up doing something like Option 1 in this
> grammar anyway?
>
> Thanks,
> Tom.
>
> grammar MultAssign;
>
> options {
>         output = AST;
> }
>
> tokens {
>         ASSIGN = '=';
>         LIST;
> }
>
> multAssign
>         :       assignList ASSIGN assignList
>         ->      ^(ASSIGN assignList assignList)
>         ;
>
> assignList
>         :       IDENT ( ',' IDENT )*
>         ->      ^(LIST IDENT+)
>         ;
>
> IDENT
>    :  ('a'..'z'|'A'..'Z'|'_'|'$') ('a'..'z'|'A'..'Z'|'_'|'0'..'9'|'$')*
>    ;
>
> WS  :  (' '|'\r'|'\t'|'\u000C'|'\n') {$channel=HIDDEN;}
>     ;
>


More information about the antlr-interest mailing list