I would like to realize a “branch” in ANTLR3.
I figured using
branch[boolean is_a]
: ({ $is_a}? => a)
| ({!$is_a}? => b);
would do the trick, but I get the compiling errors “cannot find symbol” and “illegal start of type”, because in the in the generated source i.e. DFA45.specialStateTransition(...) does not have a parameter is_a.
I tried omitting the =>¹, and/or omitting the $ of $is_a.
The FIRST sets of a and b are not disjoint.
In fact b is of type ((C) => c) | a.
¹) as I don’t understand the difference between {...}? => ... and {...}? ...
I’m not 100% sure why you get that error: I’d need to see your entire grammar for that. Anyway, there is no need to check for both
is_aand!is_a. And both$is_aandis_aare valid.Let’s say you’re parsing a list of numbers, and every 4th number, you want to handle through a different “branch”. A grammar for that would look like:
(note that the
%is a reserved character inside ANTLR grammars (not inside String literals and comments though), so it needs escaping with a backslash)And can be tested with the class:
Now generate a parser/lexer (A), compile all source files (B) and run the main class (C):
(on Windows, run it by doing
java -cp .;antlr-3.2.jar Main)which produces the following output:
So, yes, you needed a “gated semantic predicate” (
{boolean}?=>) in this case, not a “validating semantic predicate” ({boolean}?). The difference between the two predicates is explained in this previous SO Q&A: What is a ‘semantic predicate’ in ANTLR?