I'm working on an ANTLR project that should basically implement this simple grammar:
WS : ' '
;
MINUS : '-' ;
DIGIT : '0'..'9'
;
int4
@init{
int n = 0;
}
: (({n<4}?=> WS {n++;})* (MINUS{n++;})?({n<4}?=> DIGIT{n++;})*){n==4}? ;
numbers
: (int4)*;
int4 follow the format I4 of Fortran (stands for an integer with width four)
this code are giving me the following errors:
[10:17:20] C:\Users\guille\Documents\output\testParser.java:277: cannot find symbol
[10:17:20] symbol : variable n
[10:17:20] location: class testParser
[10:17:20] if ( (evalPredicate(n==4,"n==4")) ) {
[10:17:20] ^
[10:17:20] C:\Users\guille\Documents\output\testParser.java:283: cannot find symbol
[10:17:20] symbol : variable n
[10:17:20] location: class testParser
[10:17:20] else if ( (LA4_0==WS) && (evalPredicate(n<4,"n<4"))) {
[10:17:20] ^
[10:17:20] C:\Users\guille\Documents\output\testParser.java:289: cannot find symbol
[10:17:20] symbol : variable n
[10:17:20] location: class testParser
[10:17:20] else if ( (LA4_0==DIGIT) && (evalPredicate(n<4,"n<4"))) {
[10:17:20] ^
[10:17:20] 3 errors
Any Idea?
The local variable n
does no get passed to the location where the predicates get evaluated. You need to define a scope which can be used inside the predicates:
int4
scope { int n; }
@init { $int4::n = 0; }
: ( {$int4::n < 4}?=> WS {$int4::n++;} )*
( MINUS {$int4::n++;} )?
( {$int4::n < 4}?=> DIGIT{$int4::n++;} )*
{$int4::n == 4}?
;
Related:
For a better understanding, look at the generated source code of your grammar, and the generated code of the grammar using the scope.