[antlr-interest] V3 Rule Action allowing inline tree building?
Sam Harwell
sharwell at pixelminegames.com
Wed Mar 18 11:15:04 PDT 2009
Once you get the hang of it, you can do it by hand without too much
trouble. For example, in converting a v2 grammar to v3, I encountered
this in the members section:
stringAlias =
#(#[BLOCK], #(#[ALT], #[STRING_LITERAL], #[EOA]), #[EOB]);
Which became this (you can use CommonTree instead of GrammarAST). Note
that this uses the CSharp3 target so the function names are capitalized,
unlike the Java target.
/*
* stringAlias = ^(BLOCK[] ^(ALT[] STRING_LITERAL[] EOA[]) EOB[])
*/
stringAlias = (GrammarAST)adaptor.Create( BLOCK, "BLOCK" );
{
GrammarAST alt = (GrammarAST)adaptor.Create( ALT, "ALT" );
adaptor.AddChild( alt, adaptor.Create( STRING_LITERAL,
"STRING_LITERAL" ) );
adaptor.AddChild( alt, adaptor.Create( EOA, "EOA" ) );
adaptor.AddChild( stringAlias, alt );
}
adaptor.AddChild( stringAlias, adaptor.Create( EOB, "EOB" ) );
In your case, you'd use something like this:
CommonTree tree = (CommonTree)adaptor.Nil();
adaptor.AddChild( tree, adaptor.Create( LITERAL_enum, "enum" ) );
adaptor.AddChild( tree, adaptor.Create( ID, enumName ) );
Sam
From: antlr-interest-bounces at antlr.org
[mailto:antlr-interest-bounces at antlr.org] On Behalf Of Lucien Antlr
Sent: Wednesday, March 18, 2009 11:53 AM
To: antlr-interest at antlr.org
Subject: [antlr-interest] V3 Rule Action allowing inline tree building?
Hi folks,
I saw back in 2005 there was a bit of discussion around inline tree
building. ( linked here
http://markmail.org/message/7zigjknpakugflje
<http://markmail.org/message/7zigjknpakugflje> ). For practice I am
converting the freely available C v2 ANTLR .g and I came over a rule
that has me stuck...
It keeps the internal symbol-table by adding part of a tree into the
symbol table along with the C symbol (in this case enum).
Normally a v2 rewrite would look like below (from stdcparser.g)
enumerator[String enumName]
: i:ID { symbolTable.add( i.getText(),
#( null,
#[LITERAL_enum, "enum"],
#[ ID,
enumName]
)
);
}
(ASSIGN constExpr)?
;
#( ) under v2 calls ASTFactory.create(), but under v3 it just appears to
pass straight through into the Java target?
This is true even when re-written, as I guessed it should be below.
enumerator[String enumName]
: i=ID { symbolTable.add( $i.text,
^( NULL,
^(LITERAL_enum),
^(ID
$enumName.text)
)
);
}
(ASSIGN constExpr)?
;
The only thing I came up with is "rewriting" the rule, and creating a
dummy rule inside and using $dummy.tree inside the action.
Any thoughts from the more experienced community?
Kind Regards,
Luc
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.antlr.org/pipermail/antlr-interest/attachments/20090318/a1898ea7/attachment.html
More information about the antlr-interest
mailing list