'Antlr4 problems with negativ sign and operator

Hello we have this antlr4 Tree Parser:

grammar calc;

calculator: (d)*;

c
    : c '*' c
    | c '/' c
    | c '+' c
    | c '-' c
    | '(' c ')'
    | '-'? 
    | ID
    ;
d: ID '=' c;

NBR: [0-9]+; 
ID:  [a-zA-Z][a-zA-Z0-9]*;

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

The Problem is if I use a -, antlr4 doesn´t recognize, if is it ja sign or operator for sepcial inputs like: (-2-4)*4. For Inputs like this antlr4 doesn´t understand that the - befor the 2 belongs to the constant 2 and that the - is not a operator.



Solution 1:[1]

Just do something like this:

c
 : '-' c
 | c ('*' | '/') c
 | c ('+' | '-') c
 | '(' c ')'
 | ID
 | NBR
 ;

That way all these will be OK:

  • -1
  • - 2
  • -3-4
  • 5+-6
  • -(7*8)
  • (-2-4)*4

For example, (-3-10)*10 is parsed like this:

enter image description here

EDIT

This is what happens when I parse 9+38*(19+489*243/1)*1+3:

enter image description here

Solution 2:[2]

    | '-'? 

should be:

    | '-'? NBR

You need to specify that it's a NBR that may (or may not) be preceded by a -

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Mike Cargal