[antlr-interest] tree transformation question (if-elif-else ->
if-else)
Bryan Ewbank
ewbank at gmail.com
Fri Jul 1 08:52:18 PDT 2005
I solve this by building the tree differently. I think you are using
a flat grammar to consume these - perhaps something like this:
if_s : "if"^ expr statements ( elif_s )* ( else_s )? ;
elif_s : "elif"^ expr statements ;
else_s : "else"! statements ;
I use a recursive grammar instead, drilling into the elif_s production
to build the tree. It produces the tree you want, and recognizes the
same language (if I wrote it correctly):
if_s : "if"^ expr statements ( elif_s )? ;
elif_s : "elif"^ expr statements ( elif_s | else_s )? ;
else_s : "else"^ statement ;
The resulting tree looks like this (again, if I wrote the above correctly):
#( "if"
expr
statements
#( "elif"
expr
statements
#( "else"
statements
)
)
)
On 7/1/05, Klaas Hofstra <antlr at klaashofstra.com> wrote:
> Hi,
>
> I have a problem with tree transformations that must have been solved before
> because it seems to me that it occurs frequently when converting one language
> to another.
>
> I need to convert the following pseudo-code:
>
> if expression
> statements
> elif expression
> statements
> elif expression
> statements
> else
> statements
>
> into:
>
> if expression
> statements
> else
> if expression
> statements
> else
> if expression
> statements
> else
> statements
>
> Translated into trees, I need to transform the tree :
>
> tree1 =
> (IFBLOCK (IF E1 S1) (ELIF E2 S2) (ELIF E3 S3) (ELSE S4))
>
> into:
>
> tree2 =
> (IFBLOCK (IF E1 S1) (ELSE (IFBLOCK (IF E2 S2) (ELSE
> (IFBLOCK (IF E3 S3) (ELSE S4))))))
>
> , where E=EXPRESSION, S=STATEMENTS
>
> My problem is that the rewrite rule for ELIF is something like:
>
> (ELIF E S) -> (ELSE (IFBLOCK (IF E S) subtree_of_next_elif_or_else)
>
> When traversing the tree from left to right with a treeparser,
> 'subtree_of_next_elif_or_else' is not available when it is needed.
>
> How can this problem be solved?
>
> Thanks in advance,
>
> Klaas
>
>
More information about the antlr-interest
mailing list