[antlr-interest] predicate and ambiguity
Kay Roepke
kroepke at classdump.org
Sun Jul 8 23:05:27 PDT 2007
On Jul 9, 2007, at 1:31 AM, Lloyd Dupont wrote:
> I have one more question about predicate.
> Yesterday I did write something like that (MyFunction(input.LT
> (2).Text)), validating the text of the token.
>
> But what if I should not validate a Token but a rule, as in:
>
> parserrule:
> { Function(otherparserrule) }? TOK1 otherparserrule TOK2
> | alternative
> ;
>
> what if I have a rule like that. How could I write that?
> I bet I cannot write input.LT(2) because I'm reading a parser rule
> and not a simple token..
That's correct, LT(2) will give you the second token in the
TokenStream from your current consumed position.
I don't believe there is a semantic predicate syntax for what you
would like to do, but you could use a
syntactic predicate combined with a semantic predicate in
'otherparserrule'.
Something like this:
parserrule:
(TOK1 otherparserrule)=> TOK1 otherparserrule TOK2
| alternative
;
otherparserrule:
{Function(input.LT(2))}? SOMETHING ID SOMETHINGELSE
;
That should work. On the other hand, wouldn't the semantic predicate
be hoisted to parserrule? (Someone?! Ter?! ;))
Alternatively, you could turn on backtracking for parserrule and let
ANTLR try the alternatives at runtime.
Other than that, parser rules have these predefined attributes you
could potentially use:
$rule.text - the entire text matched by rule (including all hidden
tokens!! i.e. whitespace etc)
$rule.start - the first non-hidden token that was matched by rule
$rule.stop - the last non-hidden token that was matched by rule
$rule.tree (if building ASTs) - the tree produced by rule
$rule.st (if building templates) - the ST instance produced by rule
But those probably won't do in your case, as you want predicates
really. I'd say backtracking or the combination
of synpreds and sempreds.
HTH,
-k
--
Kay Röpke
http://classdump.org/
More information about the antlr-interest
mailing list