1

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?

Cyberguille
  • 1,552
  • 3
  • 28
  • 58
  • @BartKiers Basicaly this is my grammar, maybe adding `grammar test;` in the header. I did not use the options {...}. I have not used a driver class because I tested only with ANTLRWorks. This error is thrown by the ANTLRWorks tool – Cyberguille Dec 16 '14 at 16:26
  • @BartKiers Grammar is generated successfully, the problem is when I run debug the compiler failed and throw errors that show up in the question – Cyberguille Dec 17 '14 at 14:13
  • Ah, misunderstood. I thought when generating the grammar. Now I see that they are indeed compiler errors. Try the latest version of v3 (3.5.2) and if that is still an issue, checkout: http://www.antlr3.org/pipermail/antlr-interest/2007-August/023111.html – Bart Kiers Dec 17 '14 at 19:31

1 Answers1

1

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.

Community
  • 1
  • 1
Bart Kiers
  • 166,582
  • 36
  • 299
  • 288
  • thanks for your answer, answer my question. Although I found another problem and did another [question](http://stackoverflow.com/questions/27605243/semantic-predicates-antlr-dont-recognize-chain-of-integers-of-width-4) related to the same grammar – Cyberguille Dec 22 '14 at 15:15