我的ANTLR语法看起来像这样。
grammar ProgCalc;
options {
language = Java;
ASTLabelType=CommonTree;
output=AST;
backtrack=true;
}
/* Parser rules */
eval
: exp=add;
add
: term ( PLUS^ term | MINUS^ term ) *;
term
: factor ( MULT^ factor | MOD^ factor )*;
factor
: number
| VARIABLE
| '('! add^ ')'!
;
number
: DEC | HEX | OCT;
/* Lexer Rules*/
VARIABLE: ('a'..'z' |'A'..'Z')('a'..'z'|'A'..'Z' | '0'..'9'|'_')* ;
DEC : ('1'..'9')('0'..'9')+;
HEX : '0x' ('0'..'9' | 'a'..'f' | 'A'..'F')+;
OCT : '0' ('0'..'7')*;
PLUS : '+';
MINUS : '-';
MULT : '*';
MOD : '%';
WHITESPACE : ( '\t' | ' ' | '\r' | '\n'| '\u000C' )+ { $channel = HIDDEN; };
编译时,它成功了。 但是当我用表达式解析时(例如5%3 * 5),我得到一个错误。
line 1:1 required (...)+ loop did not match anything at character '%' line 1:3 required (...)+ loop did not match anything at character '*' line 1:5 required (...)+ loop did not match anything at character '<EOF>' line 1:5 no viable alternative at input '<EOF>'
有人可以检查我的语法并更正吗? 非常感谢你。
答案 0 :(得分:1)
由于DEC
运算符,您的+
词法分析器规则至少需要2位数。我相信你的意思是写:
DEC : ('1'..'9') ('0'..'9')*;