[英]How to implement a parser based on the following grammar?
如何基于以下语法实现解析器:
exp ::= exp + term|exp - term|term
term ::= (exp)|integer literal
我了解如何实现解析器:
exp ::= term + exp|term - exp|term
但我很困惑如何实现它:
exp ::= exp + term|exp - term|term
这是我到目前为止得到的:
private static Exp parseExp(Tokenizer t) throws ParseException {
// add code in this method for your solution
//<exp> ::= <exp> + <term>|<exp> - <term>|<term>
Exp term = parseTerm(t);
if (!t.done()){
if (t.current().isTheSymbol('+')){
t.next();
Exp exp = parseExp(t);
return new BinExp(exp,'+',term);
}
else if (t.current().isTheSymbol('-')){
t.next();
Exp exp = parseExp(t);
return new BinExp(exp,'-',term);
}
else return term;
}
else return term;
}
例如对于 2-1+3,它解析为 ((3+1)-2),但我期望 ((2-1)+3)
如果您将规则重写为:
exp ::= term (('+'|'-') term)*
private static Exp parseExp(Tokenizer t) throws ParseException {
// add code in this method for your solution
//<exp> ::= <exp> + <term>|<exp> - <term>|<term>
Exp exp = parseTerm(t);
while (!t.done()) {
char op;
if (t.current().isTheSymbol('+')) {
op = '+';
}
else if (t.current().isTheSymbol('-')){
op = '-';
}
else {
break;
}
t.next();
Exp exp2 = parseTerm(t);
exp = new BinExp(exp,op,exp2);
}
return exp;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.