ANTLR grammar issues with negative numbers

242 Views Asked by At

My ANTLR Grammar for simple expressions is as below: This grammar works for most of the scenarios except when I try to use negative numbers.

abs(1.324) is valid

abs(-1.324) is being thrown as an error. 

Or if the expression is just a negative number such as -1.344 I am having the following error in the console.

enter image description here

grammar ExpressionGrammar;

parse: expr EOF;

expr:
    MIN expr
    | expr ( MUL | DIV) expr
    | expr ( ADD | MIN) expr
    | expr  ( MOD )  expr
    | NUM
    | ID
    | STRING
    | function
    | '(' expr ')';

function: ID '(' arguments? ')';

arguments: expr ( ',' expr)*;

/* Tokens */

MUL: '*';
DIV: '/';
MIN: '-';
ADD: '+';
MOD: '%';
OPEN_PAR: '(';
CLOSE_PAR: ')';

NUM: ([0-9]*[.])?[0-9]+;
STRING: '"' ~ ["]* '"';
fragment ID_NODE: [a-zA-Z_$][a-zA-Z0-9_$]*;
ID: ID_NODE ('.' ID_NODE)*;
COMMENT: '/*' .*? '*/' -> skip;
LINE_COMMENT
    : '//' ~[\r\n]* -> skip
    ;
WS: [ \r\t\n]+ -> skip;
1

There are 1 best solutions below

0
On

The grammar seems fine to me. It could be a bug with the runtime you're using, but that seems odd to me, given you're not doing anything special.

With the Java runtime, this is what I get when parsing/lexing the input abs(-1.324):

The following tokens are produced:

ID                                  `abs`
OPEN_PAR                            `(`
MIN                                 `-`
NUM                                 `1.324`
CLOSE_PAR                           `)`
EOF                                 `<EOF>`

and the entry point parse gives:

enter image description here