1

I am trying to recognize real values (such as xxx.xx)

This grammar does not work

grammar Test;

realValue:
    NUMBER DOT DECIMALS
;  


DOT:
    '.'
;

NUMBER:
    '0' | ('1'..'9')('0'..'9')*
;

DECIMALS:
    ('0'..'9')('0'..'9')*
;


WS:
    (' '|'\r'|'\t'|'\n') -> skip
;

OTHER:
     .
;

When I run TestRig with following input

123.45

I get a

line 1:4 mismatched input '45' expecting DECIMALS

What am I missing ?

YaFred
  • 9,698
  • 3
  • 28
  • 40

2 Answers2

2

line 1:4 mismatched input '45' expecting DECIMALS

You get that error because 45 is tokenised as a NUMBER. A NUMBER is defined before a DECIMALS so NUMBER gets precedence. The lexer does not "listen" to what the parser might need at a given time.

This would work:

realValue
 : NUMBER DOT NUMBER
 ;  

But, you don't want to glue the tokens together in a parser rule to create a realValue. Otherwise input like this: 123 .45 might become a single realValue.

A real should really be a lexer rule:

number
 : INT
 | REAL
 ;

INT
 : '0'
 | [1-9] [0-9]*
 ;

REAL
 : [0-9]* '.' [0-9]+
 ;

WS
 : [ \t\r\n] -> skip
 ;

OTHER
 : .
 ;
Bart Kiers
  • 166,582
  • 36
  • 299
  • 288
0

For E, use scientific notation. For example, Accepted Real are:
1.0,
1e-12,
1.0e-12,
0.000000001

I have test tested so far for the GRAMMAR ANTLR v4 of Real Number as

fragment DIGIT : [0-9] ;
INT : DIGIT+ ;
SUBREAL : (INT)('e')?('+'|'-')?(INT)*;
DOT: '.';
REAL : SUBREAL DOT SUBREAL;
ID : (REAL)*;
David Buck
  • 3,752
  • 35
  • 31
  • 35