Extraneous input '-' expecting in ANTLR4

2019-07-31 23:42发布

问题:

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:

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 ;


标签: antlr antlr4