获得错误通常是令人不愉快的,但有时当你期望错误并且没有得到它时也会感到不愉快。我的解析器不会为此字符串“2)”生成错误。请给我一个解决方案?
grammar BasicArithmetic;
options {
language = Java;
output = AST;
}
expression returns [double value]:
p1=pm{$value=$pm.value;};
// never never reference FRAGMENTS from parsers
pm returns [double value]:
p1=dm{$value = $p1.value;}
(PLUS^p2=dm{$value += $p2.value;}|
MINUS^p2=dm{$value -= $p2.value;}
)*;
dm returns [double value]:
p1=atom {$value = $p1.value;}
( DIV^ p2=atom {$value /= $p2.value;}|
MUL^ p2=atom {$value *= $p2.value;}|
POW^ p2=atom {$value = Math.pow($value, $p2.value);}
)*;
atom returns [double value]:
p1=Number {$value = Double.parseDouble($p1.text);}
| LP p2=pm RP{$value = $p2.value;};
Number: Digit+;
MUL : '*';
DIV : '/';
PLUS : '+';
MINUS : '-';
POW : '^';
LP : '(';
RP : ')';
fragment Digit:'0'..'9';
WS :('\t'| ' '| '\r'| '\n'| '\u000C')+{$channel = HIDDEN;};
答案 0 :(得分:1)
您需要更改语法,以指定在您的顶级规则完成后您期望EOF
令牌:
expression returns [double value]:
p1=pm EOF {$value=$pm.value;};