Home > OS >  Antlr4 problems with negativ sign and operator
Antlr4 problems with negativ sign and operator

Time:05-12

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.

CodePudding user response:

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

CodePudding user response:

    | '-'? 

should be:

    | '-'? NBR

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

  • Related