antlr - ANTLR3: Parameters and semantic predicates ("cannot find symbol", "illegal start of type") -
i realize "branch" in antlr3.
i figured using
branch[boolean is_a] : ({ $is_a}? => a) | ({!$is_a}? => b);
would trick, compiling errors "cannot find symbol" , "illegal start of type", because in in generated source i.e. dfa45.specialstatetransition(...)
not have parameter is_a
.
i tried omitting =>
¹, and/or omitting $
of $is_a
.
the first sets of a
, b
not disjoint.
in fact b
of type ((c) => c) | a
.
¹) don't understand difference between {...}? => ...
, {...}? ...
i'm not 100% sure why error: i'd need see entire grammar that. anyway, there no need check both is_a
and !is_a
. , both $is_a
, is_a
valid.
let's you're parsing list of numbers, , every 4th number, want handle through different "branch". grammar like:
grammar t; parse @init{int n = 1;} : (number[n\%4 == 0] {n++;})+ eof ; number [boolean multipleof4] : {multipleof4}?=> int {system.out.println("branch -> " + $int.text);} | int {system.out.println("branch b :: " + $int.text);} ; int : '0'..'9'+ ; space : (' ' | '\t' | '\r' | '\n') {skip();} ;
(note %
reserved character inside antlr grammars (not inside string literals , comments though), needs escaping backslash)
and can tested class:
import org.antlr.runtime.*; public class main { public static void main(string[] args) throws exception { antlrstringstream in = new antlrstringstream("11 22 33 44 55 66 77 88 99"); tlexer lexer = new tlexer(in); commontokenstream tokens = new commontokenstream(lexer); tparser parser = new tparser(tokens); parser.parse(); } }
now generate parser/lexer (a), compile source files (b) , run main class (c):
java -cp antlr-3.2.jar org.antlr.tool t.g // javac -cp antlr-3.2.jar *.java // b java -cp .:antlr-3.2.jar main // c
(on windows, run doing java -cp .;antlr-3.2.jar main
)
which produces following output:
branch b :: 11 branch b :: 22 branch b :: 33 branch -> 44 branch b :: 55 branch b :: 66 branch b :: 77 branch -> 88 branch b :: 99
so, yes, needed "gated semantic predicate" ({boolean}?=>
) in case, not "validating semantic predicate" ({boolean}?
). difference between 2 predicates explained in previous q&a: what 'semantic predicate' in antlr?
Comments
Post a Comment