LoginSignup
1
0

More than 5 years have passed since last update.

antlrつこてみる

Last updated at Posted at 2013-12-13

ANTLRはLLなパーサジェネレータ
LLとかLRとかどっちがよいのかよくわからないのだけど、なんとなくANTLRつかってみる

インストール

http://www.antlr.org/download.html
ここからantlr-4.1-complete.jarをダウンロードしてくる

http://www.antlr.org/wiki/display/ANTLR4/Getting+Started+with+ANTLR+v4
に従ってセットアップする。
うちはWindowsなので以下のようなバッチファイルを作る

antlr.bat
set CLASSPATH=.;.\lib\antlr-4.1-complete.jar;%CLASSPATH%

java org.antlr.v4.Tool %*
run.bat
set CLASSPATH=.;.\lib\antlr-4.1-complete.jar;%CLASSPATH%

java org.antlr.v4.runtime.misc.TestRig %*

Example

Hello.g4
// Define a grammar called Hello
grammar Hello;
r  : 'hello' ID ;         // match keyword hello followed by an identifier
ID : [a-z]+ ;             // match lower-case identifiers
WS : [ \t\r\n]+ -> skip ; // skip spaces, tabs, newlines

サンプルのgrammarを作成してコンパイルしてみる。hello.g4のように小文字になってるとエラーになるので注意!

$ antlr Hello.g4
$ javac Hello*.java

構文木を生成してみます

$ grun Hello r -tree
hello parrt
^Z
(r hello parrt)

^ZはControl-Zを入力してEnter
unix系なら^D
(r hello parrt)が出力です
LISPっぽく構文木が表現されています

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0