2

I'm trying to create a calculator that supports also negative numbers, and create in the end a lisp-style tree.

I define the lexer rules like this :

INT :'-'? [0-9]+ ;
LBRACKET :  '(';
RBRACKET :  ')';
MULTIPLICATION : '*' ;
DIVISION: '/' ;
PLUS: '+' ;
MINUS: '-' ;

And I have a rule for each operation, for example:

 e13=exp MINUS e14=exp{
SPTree tempTree= new SPTree("-");
tempTree.insertChild($e13.tree);
tempTree.insertChild($e14.tree);
$tree=tempTree;
} 

But when I'm trying to enter the expression: 2-3 the lisp tree that comes out is (2).

Why does it ignore -3?

Lucas Trzesniewski
  • 50,214
  • 11
  • 107
  • 158
diana
  • 59
  • 1
  • 4

2 Answers2

3

You should not define INT as supporting negative numbers. Leave that to the subtraction operator.

Right now, the following input:

2-3

Will be tokenized like this: 2 -3, which is: INT INT. And you didn't define a parser rule that is able to handle that.

If you drop that '-'? from the INT definition, you'll get the expected result:
2 - 3, which is INT MINUS INT, and that is parsable.

So, just define the following:

INT : [0-9]+ ;

Additionally, you should add a required EOF to the root parser rule, so the parser will generate an error on unexpected additional input.

See my answer here for a simple working math example.

Community
  • 1
  • 1
Lucas Trzesniewski
  • 50,214
  • 11
  • 107
  • 158
  • Through that way 2 - 3 is working but -3 + 2 isn't. Why? it print 5 as a result, ignoring the minus. – SctALE Jan 13 '18 at 16:04
  • @SctALE this should work fine, you must have an issue with your rules (there are no parser rules in the question). See my linked answer which works fine, and it that doesn't help you, post a new question along with your code. You probably didn't include an unary minus rule. – Lucas Trzesniewski Jan 14 '18 at 16:41
  • https://stackoverflow.com/questions/48267834/antlr-parsing-and-code-generation-with-operator-and-number-sign Should I write something more to help understanding my problem? – SctALE Jan 15 '18 at 17:19
2

You can use a negation expression , not a negation number. For example :

additiveExpr 
    :   multExpr (('+' |'-' ) multExpr )*;  
multExpr 
    :   negationExpr (('*' |'/' ) negationExpr )*; 
negationExpr 
    :   ('-')? primary; 
primary  
    :   atom           
    |  '(' orExpr ')'; 
stasiaks
  • 1,268
  • 2
  • 14
  • 31
saber
  • 21
  • 1