我是SableCC的新手。只需運行計算器示例http://sablecc.sourceforge.net/thesis/thesis.html#PAGE26。我原樣使用語法文件和解釋器文件,並嘗試解析簡單的算術表達式,如「45 * 5 + 2」。問題是,解釋器方法caseAMultFactor似乎沒有被擊中。如果我將「+」更改爲「 - 」,我發現它碰到caseAPlusExpr或caseAMinusExpr。那麼Start.apply(DepthFirstAdapter)方法只能通過頂層模式節點嗎?我怎樣才能遍歷所有的節點,就像示例代碼似乎要做的一樣?我正在使用Java 1.7,希望這不是問題。SableCC沒有打翻解釋方法
爲了您的方便,我在這裏粘貼了語法和解釋器代碼。謝謝你的幫助。
### 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());
}
}
感謝您的回答。對不起沒有看到它,因爲沒有人在我發佈的幾天內回覆它。 – user2045610 2015-03-09 01:31:50
當我嘗試你的代碼輸出:[1,1]未知的令牌:( – user2045610 2015-03-09 01:32:32
查看我的更新2015-03-09。 – mbmast 2015-03-10 03:02:59