我是 SableCC 的新手。刚刚在http://sablecc.sourceforge.net/thesis/thesis.html#PAGE26上运行了计算器示例。我按原样使用语法文件和解释器文件,并尝试解析简单的算术表达式,如“45 * 5 + 2”。问题是,解释器方法 caseAMultFactor 似乎没有被命中。如果我将“+”更改为“-”,我看到它命中 caseAPlusExpr 或 caseAMinusExpr。那么 Start.apply(DepthFirstAdapter) 方法是否只通过顶部模式节点?如何像示例代码似乎那样遍历所有节点?我正在使用 Java 1.7,希望这不是问题。
为了您的方便,我在这里粘贴了语法和解释器代码。谢谢你的帮助。
### Grammar:
Package postfix;
Tokens
number = ['0' .. '9']+;
plus = '+';
minus = '-';
mult = '*';
div = '/';
mod = '%';
l_par = '(';
r_par = ')';
blank = (' ' | 13 | 10)+;
Ignored Tokens
blank;
Productions
expr =
{factor} factor |
{plus} expr plus factor |
{minus} expr minus factor;
factor =
{term} term |
{mult} factor mult term |
{div} factor div term |
{mod} factor mod term;
term =
{number} number |
{expr} l_par expr r_par;
### Interpreter:
package postfix.interpret;
import postfix.analysis.DepthFirstAdapter;
import postfix.node.ADivFactor;
import postfix.node.AMinusExpr;
import postfix.node.AModFactor;
import postfix.node.AMultFactor;
import postfix.node.APlusExpr;
import postfix.node.TNumber;
public class Interpreter extends DepthFirstAdapter
{
public void caseTNumber(TNumber node)
{// When we see a number, we print it.
System.out.print(node);
}
public void caseAPlusExpr(APlusExpr node)
{
System.out.println(node);
}
public void caseAMinusExpr(AMinusExpr node)
{
System.out.println(node);
}
public void caseAMultFactor(AMultFactor node)
{// out of alternative {mult} in Factor, we print the mult.
System.out.print(node.getMult());
}
public void outAMultFactor(AMultFactor node)
{// out of alternative {mult} in Factor, we print the mult.
System.out.print(node.getMult());
}
public void outADivFactor(ADivFactor node)
{// out of alternative {div} in Factor, we print the div.
System.out.print(node.getDiv());
}
public void outAModFactor(AModFactor node)
{// out of alternative {mod} in Factor, we print the mod.
System.out.print(node.getMod());
}
}