[英]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.