1
votes

Could you please tell me what could be the problem? It's expect {<EOF>, '(', NUMBER, VARIABLE}, but if i insert this rules after -, i got same error.

grammar Grammar;

@header {
    package parser;
}

program: line* EOF ;
line: (expression | assignment) ('\n' | EOF);
assignment : VARIABLE '=' expression ;
expression : '(' expression ')'        #parenthesisExpression
           | left=expression OP1 right=expression #firstPriorityExpression
           | left=expression OP2 right=expression #secondPriorityExpression
           | number=NUMBER                    #numericExpression
           | variable=VARIABLE                  #variableExpression
           ;

NUMBER : '-'? [0-9]+ ;
VARIABLE : [a-zA-Z][a-zA-Z0-9]* ;
OP1: '*' | '/' ;
OP2: '+' | '-' ;
WHITESPACE : (' ' | '\t' | '\n')+ -> skip ;
1
For which input do you get the error?sepp2k
sepp2k, for example: a=5 b=3 -(-a)*(b-2*(b-a))micromagicman
You're using - as a prefix operator in (-a). Your grammar only allows - as an infix operator.sepp2k
Can you please explain me, what i need to change in this grammar to support prefix '-'?micromagicman
sepp2k, BartKiers, I'm pretty impressed by your visionary abilities. Even after reading this question 5 times, I still don't know what the OP wants. Only the provided answer gives a hint as to what this is really about.Mike Lischke

1 Answers

1
votes

Remove the - from the NUMBER rule, and introduce an #unaryExpression in your expression rule.

Something like this ought to do it:

expression
 : '(' expression ')'                   #parenthesisExpression
 | MIN expression                       #unaryExpression
 | left=expression op1 right=expression #firstPriorityExpression
 | left=expression op2 right=expression #secondPriorityExpression
 | number=NUMBER                        #numericExpression
 | variable=VARIABLE                    #variableExpression
 ;

op1
 : MUL
 | DIV
 ;

op2
 : ADD
 | MIN
 ;

NUMBER     : [0-9]+ ;
VARIABLE   : [a-zA-Z][a-zA-Z0-9]* ;
MUL        : '*' ;
DIV        : '/' ;
ADD        : '+' ;
MIN        : '-' ;
WHITESPACE : [ \t\r\n]+ -> skip ;