[英]getType() method not found in antlr4
以下規則是較大規則的摘錄。 注意語法尾部的可選部分。 解析輸入后,我們遍歷生成的解析樹以評估表達式。 第一條規則的偵聽器代碼也在下面給出。
arithmeticTerm
: arithmeticFactor (op=(MULT|DIVIDE) arithmeticFactor)*
;
arithmeticFactor: INTEGER /* For now , let it be simple terminal */
聽眾
import java.util.ArrayList;
import org.antlr.v4.runtime.misc.NotNull;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeProperty;
public class PredicateEvaluator extends PredicateGrammarBaseListener {
private ParseTreeProperty<Float> floatValues = new ParseTreeProperty<Float>();
private ArrayList<Float> arithmeticTermFactorList = null;
private void setFloatValue(ParseTree node, float value){
floatValues.put(node, value);
}
private float getFloatValue(ParseTree node){
return floatValues.get(node);
}
public void enterArithmeticTerm(
@NotNull PredicateGrammarParser.ArithmeticTermContext ctx)
{
arithmeticTermFactorList = new ArrayList<Float>();
}
目前,我正在以這種方式評估算術項。 我需要檢測op類型,並區分或乘以因子。 但是,我的編譯器找不到getType()方法。 我查看了antlr4生成的代碼,但它不存在。 我正在關注antlr4的創建者的書,他在類似的情況下使用getType()方法,但是同一件事在這里不起作用。 您的幫助將不勝感激。
public void exitArithmeticTerm(
@NotNull PredicateGrammarParser.ArithmeticTermContext ctx)
{
float evaluatedValue = 0.0f;
if (ctx.op == null){
evaluatedValue = getFloatValue(ctx.arithmeticFactor().get(0));
}else{
for(float value : arithmeticTermFactorList){
if(ctx.op.getType() == PredicateGrammarLexer.MULT) {
evaluatedValue *= value;
}else{
evaluatedValue /= value;
}
}
}
arithmeticExprTermList.add(evaluatedValue);
}
public void exitArithmeticFactor(
@NotNull PredicateGrammarParser.ArithmeticFactorContext ctx)
{
Float evaluatedValue = NEGATIVE * Integer.valueOf(ctx.INTEGER().getText());
arithmeticTermFactorList.add(evaluatedValue);
}
}
而不是做:
arithmeticTerm
: arithmeticFactor (op=(MULT|DIVIDE) arithmeticFactor)*
;
做這樣的事情:
expression
: MINUS expression #unaryMinusExpression
| expression MULT expression #multExpression
| expression DIVIDE expression #divideExpression
| expression ADD expression #addExpression
| expression MINUS expression #minusExpression
| INTEGER #integerExpression
| '(' expression ')' #parensExpression
;
然后在您的偵聽器中,您只需要重寫#...Expression
方法:
@Override
public void enterMultExpression(@NotNull PredicateGrammarParser.MultExpressionContext ctx)
{
...
}
請注意, MULT
和DIVIDE
表達式的優先級高於ADD
和MINUS
因為它們是在后者之前定義的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.