[antlr-interest] Newbie Q: Duplicating nodes from parse into AST
Austin Hastings
Austin_Hastings at Yahoo.com
Mon Oct 1 21:32:40 PDT 2007
FWIW,
I see on the archive that "Christian Andersson" had essentially the same
problem as me, wrt splitting a declaration like:
int a,b;
into an AST like ^(int a) ^(int b).
FWIW, Christian and others, I worked around the problem by doing the
trick detailed under "Creating Nodes with Arbitrary Actions" in the
Definitive ANTLR Reference. Here's what my solution looks like, abbreviated:
declaration
: type=decl_type_spec!
declarator[$type.tree]
(',' declarator[$type.tree])*
;
decl_type_spec : 'int' ; /* or whatever */
declarator[CommonTree type]
: decl_prefix_expr -> ^(DECL {$type} decl_prefix_expr)
;
decl_prefix_expr : /* Matches identifiers, pointers, blah blah blah. */
The key to this trick is the parameterized rule "declarator," which
accepts the type information as an argument. The "declaration" rule
matches the type name, qualifiers, storage class, yadda yadda yadda,
groups it into a "type" subtree, and passes that subtree to "declarator"
every time it matches one. The declarator node emits the AST including
type data.
Yes, as I posted the other day, I think it should be possible to do this
with a rewrite rule. Certainly there is an example in Parr's book that
indicates this should be possible. But this works today.
Enjoy,
=Austin
More information about the antlr-interest
mailing list