[antlr-interest] ANTLR3 How to transform trees
Terence Parr
parrt at cs.usfca.edu
Tue Mar 20 13:10:15 PDT 2007
On Mar 20, 2007, at 7:17 AM, Kailey Joanette wrote:
> Hey Guys,
>
> I'm extremely new to ANTLR. I first tried my hand at JavaCC until I
> found ANTLR and realized how much more powerful it is than JavaCC.
> In any case...
>
> I know how to build a basic grammar to read in stuff (in my case
> though I'm using the Java 1.5 parser). I even know how to build a
> basic tree out of what I get.
>
> What I'm trying to do now is to take the tree that I originally
> create and transform it a little. Basically I'm trying to write a
> Java to C++ translator. I realize this is a bit of a large
> undertaking, but not everything has to be perfect. I only need to
> worry about a subset of the language for my purposes. But this
> should be able to convert say a simple Java class into a C++ class.
>
>
> If my grammar rule looks like this:
> type
> : Identifier (typeArguments)? ('.' Identifier (typeArguments)? )*
> ('[' ']')*
> -> ^(TYPE_IDENTIFIER ^(ARRAY_DECLARE '[' ']')* Identifier+)
> | primitiveType ('[' ']')*
> -> ^(TYPE_PRIMITIVE ^(ARRAY_DECLARE '[' ']')* primitiveType)
> ;
>
> Say all I want to do is change the contents of the ARRAY_DECLARE.
> How do I go about doing this?
>
> On that same note, say I wanted to swap the order of ARRAY_DECLARE
> and Identifiers in the tree, can I do that as well? and how what
> would the rule look like to do so?
>
>
> Any help would be greatly appreciated!
Just use
options {
rewrite=true;
output=template;
}
and then rewrite the constructs you want with -> rewrites. Use a
regular grammar, no trees. The rewrite option alters the token
buffer inline. toString it later to get altered buffer.
Ter
More information about the antlr-interest
mailing list