我一直在努力使这个问题的答案适用于 Android 上的 ANTLR4。我已确定添加正确的 Java 文件并将 jar 添加到项目中,但它没有向我显示输入的结果。一旦我点击我设备上的“评估”按钮,输出就是这个
5 * (8 + 2) 等于 []
我所做的唯一更改是语法和导入方法,以使它们在 ANTLR4 上工作。
这是语法(Exp.g4)代码:
grammar Exp;
@parser::header {
package bk.andabac2;
}
@lexer::header {
package bk.andabac2;
}
eval returns [double value]
: exp=additionExp {$value = $exp.value;}
;
additionExp returns [double value]
: m1=multiplyExp {$value = $m1.value;}
( '+' m2=multiplyExp {$value += $m2.value;}
| '-' m2=multiplyExp {$value -= $m2.value;}
)*
;
multiplyExp returns [double value]
: a1=atomExp {$value = $a1.value;}
( '*' a2=atomExp {$value *= $a2.value;}
| '/' a2=atomExp {$value /= $a2.value;}
)*
;
atomExp returns [double value]
: n=Number {$value = Double.parseDouble($n.text);}
| '(' exp=additionExp ')' {$value = $exp.value;}
;
Number
: ('0'..'9')+ ('.' ('0'..'9')+)?
;
WS
: (' ' | '\t' | '\r'| '\n') {skip();}
;
还有我在 Eclipse 中的 MainActivity.java 代码:
package bk.andabac2;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.RecognitionException;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button button = (Button)findViewById(R.id.parse_button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText in = (EditText)findViewById(R.id.input_text);
TextView out = (TextView)findViewById(R.id.output_text);
String source = in.getText().toString();
ExpLexer lexer = new ExpLexer(new ANTLRInputStream(source));
ExpParser parser = new ExpParser(new CommonTokenStream(lexer));
try {
out.setText(source + " evalúa a " + parser.eval());
}
catch (RecognitionException e) {
out.setText("Oops: " + e.getMessage());
}
}
});
}
}
我在日志中得到的是关于 TreeViewer 类的以下消息:
Unable to resolve superclass of Lorg/antlr/v4/runtime/tree/gui/TreeViewer; (763)
Link of class 'Lorg/antlr/v4/runtime/tree/gui/TreeViewer;' failed
Could not find class 'org.antlr.v4.runtime.tree.gui.TreeViewer', referenced from method org.antlr.v4.runtime.RuleContext.inspect
VFY: unable to resolve new-instance 1351 (Lorg/antlr/v4/runtime/tree/gui/TreeViewer;) in Lorg/antlr/v4/runtime/RuleContext;
VFY: replacing opcode 0x22 at 0x0000
Unable to resolve superclass of Lorg/antlr/v4/runtime/tree/gui/TreeViewer; (763)
Link of class 'Lorg/antlr/v4/runtime/tree/gui/TreeViewer;' failed
DexOpt: unable to opt direct call 0x21be at 0x02 in Lorg/antlr/v4/runtime/RuleContext;.inspect