[antlr-interest] Passing arguments to rules
Gavin Lambert
antlr at mirality.co.nz
Fri Oct 31 03:15:30 PDT 2008
At 22:41 31/10/2008, Hendrik Maryns wrote:
>I have a rule as follows:
>
>firstOrderAtomic returns [Formula result] :
>firstOrderAtomicHead[$first.result, $second.result] { $result =
>$firstOrderAtomicHead.result;}
>first=firstOrderVariable
>second=firstOrderVariable ;
>
>I hoped the rule firstOrderAtomicHead would receive the results
>from first and second, but looking at the produced code, it
>doesn't. How would I do this to be able to pass the two
>variables to the head.
I'm fairly certain that you can't do that,
because things are called in the order they're
found, so first and second aren't populated when
firstOrderAtomicHead is called. (Given that
firstOrderAtomic has no idea how much of the
input stream firstOrderAtomicHead will consume,
it couldn't work any other way.)
You could use a post-processing action, though:
firstOrderAtomic returns [Formula result]
: head=firstOrderAtomicHead
first=firstOrderVariable second=firstOrderVariable
{ $result = CreateFormula($head,
$first.result, $second.result); }
;
(You might need to specify an attribute on $head,
eg. $head.text or $head.result.)
>I think probably moving to an AST instead of trying to do this
>directly in the parser would be a solution, but you probably
>can judge this better, so that's why I'm asking
That's another option. It'd probably lead to
slightly cleaner code, and it'd be handy if you
wanted to do multiple passes or different sets of
actions for the same basic input -- but it is a
little extra overhead. Up to you to decide which you prefer :)
More information about the antlr-interest
mailing list