[antlr-interest] Write a token to the AST within an action
Gavin Lambert
antlr at mirality.co.nz
Mon Nov 10 11:32:17 PST 2008
At 05:24 10/11/2008, Chris Sekszczynska wrote:
>There, I like to achieve something like this:
>
> -> ^(PROGRAM ^(GLOBALS {«return the element of
>$SymbolTable::newGlobals»}) sourceElement*)
>
>The GLOBALS-subtree should look like ^(GLOBALS i x y) when "i",
>"x" and "y" are the token-names in my "newGlobals" ArrayList.
All the functions that ANTLR itself uses to
construct ASTs are available to your code.
This is air code, so might need a bit of
tweaking, but it ought to work:
program
scope SymbolTable;
@init {
// initialize the scope for this block
$SymbolTable::newGlobals = new ArrayList<String>();
CommonTree globalTree = null;
}
@after {
System.out.println("Number of globals: " +
$SymbolTable::newGlobals.size());
}
: sourceElement*
{
globalTree = (CommonTree)adaptor.becomeRoot(
adaptor.create(GLOBALS, "GLOBALS"), adaptor.nil());
foreach (String name in $SymbolTable::newGlobals)
{
adaptor.addChild(globalTree, adaptor.create(ID, name));
}
}
-> ^(PROGRAM {globalTree} sourceElement*)
;
More information about the antlr-interest
mailing list