[antlr-interest] adding node to AST
Martin Probst
mail at martin-probst.com
Fri Dec 2 06:22:30 PST 2005
Hi,
> I need to check that the SubscriptionManager token *does* end with :INT, and add it as a node.
So why is the (":" INT) block optional then? Better leave syntax
analysis and errors to ANTLR.
> subscriptionManager!
> { boolean oldSubMgr = true; }
> : x:"SubscriptionManager" (":" sm:INT { oldSubMgr = false; } )?
> {
> #subscriptionManager = #x;
>
> if(oldSubMgr) {
> throw new Exception("bad format");
> }
> }
> LBRACE!
> RBRACE!
> ;
Well, with the "!" no AST construction takes place in the rule, so the
ASTs for ":" and "sm:INT" are not attached anywhere. If you want them,
you have to add them manually in this case:
> x:"SubscriptionManager" col:":" sm:INT
> { #subscriptionManager = #(#x, #col, #sm); }
or, preferrably without action code
(and with construction on, e.g. no "!"):
> x:"SubscriptionManager"^ col:":" sm:INT
This will give you
x
/ \
col sm
(Do you really need the ":"?)
> I previously tried to add the node in the usual way, using '^' (with the '!' removed from the rule
> name and the line "#subscriptionManager = #x;" omitted).
The above should work.
> I tried all of the following, but no luck:
> x^:"SubscriptionManager" (":" sm:INT { oldSubMgr = false; } )?
> x:"SubscriptionManager" (":" sm:INT { oldSubMgr = false; } )?^
> x:("SubscriptionManager" (":" sm:INT { oldSubMgr = false; } )?)^
I think those are not syntactically correct in ANTLR, are they? There is
a section in the manual about tree construction, though it's quite
hidden.
Martin
More information about the antlr-interest
mailing list