嗯,我只是用“普通”的 ANTLR 版本做了一个小测试,一切都很顺利。
这就是我所做的:
1 个新的 Android 项目
创建一个名为AndAbac (Android-Abacus) 的新项目,其中包含一个名为bk.andabac 的包和一个名为AndAbac 的活动。
2 创建语法
在系统的任意位置创建一个名为Exp.g(解释here)的语法文件,并将以下内容粘贴到其中:
grammar Exp;
@parser::header {
package bk.andabac;
}
@lexer::header {
package bk.andabac;
}
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') {$channel=HIDDEN;}
;
3 下载 ANTLR 并生成 lexer/parser
在此处下载 ANTLR:http://www.antlr3.org/download/antlr-3.3-complete.jar 并将其放在与您的 Exp.g 文件相同的目录中。生成一个词法分析器和解析器(解释here)并将生成的.java 文件复制到您的Android 项目中的以下文件夹:src/bk/andabac。还将这个 ANTLR jar 放到你的 Android 项目的类路径中。
4 更改一些项目文件
将以下内容粘贴到res/layout/main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<EditText
android:id="@+id/input_text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="5 * (8 + 2)"
/>
<Button
android:id="@+id/parse_button"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:text="eval" />
<TextView
android:id="@+id/output_text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=""
/>
</LinearLayout>
以及src/bk/andabac/AndAbac.java中的以下内容:
package bk.andabac;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.antlr.runtime.ANTLRStringStream;
import org.antlr.runtime.CommonTokenStream;
import org.antlr.runtime.RecognitionException;
public class AndAbac extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.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 ANTLRStringStream(source));
ExpParser parser = new ExpParser(new CommonTokenStream(lexer));
try {
out.setText(source + " = " + parser.eval());
}
catch (RecognitionException e) {
out.setText("Oops: " + e.getMessage());
}
}
});
}
}
5 测试应用
要么在模拟器中运行该项目,要么创建一个 APK 文件并将其安装在 Android 设备上(我测试了两者,并且都工作)。按下 eval 按钮后,您将看到以下内容: