LoginSignup
5
5

More than 5 years have passed since last update.

Booコンパイラを起動してBooプログラムの構文木を得るBooプログラム

Last updated at Posted at 2013-05-21

ソース

# pythonじゃないよ。Booだよ!
import Boo.Lang.Compiler
import Boo.Lang.Compiler.Steps
import Boo.Lang.Compiler.IO

# text = 何かお好きなBooプログラム
text = """
print "hello world!"
"""
# c = Booコンパイラ。ただし構文木生成だけするように。
c = BooCompiler()
p = c.Parameters
p.Pipeline = CompilerPipeline() # コンパイラパイプラインを空っぽにする。
p.Pipeline.Add( Parsing() )  # Parsing:構文木生成コンパイラステップを追加。
p.Input.Add( StringInput( "ファイル名の代わりの文字列", text ) ) # 文字列をコンパイラの入力に設定。
ctxt = c.Run() # コンパイル。パイプラインは Parsingだけなので構文木生成しかしない。

# CompileUnit は構文木のルートとなる構文木クラス
ast = ctxt.CompileUnit
print "CODE: " + ast + " type:" + ast.GetType()

文字列じゃなくてファイルを入力にしたい

StringInput のところを次のようにします。

p.Input.Add( FileInput( "ファイルパス" ) )

コンパイルエラー

コンパイルエラーはコンパイル結果(CompilerContext)のErrorsプロパティ(ICollection)です。

ctxt = c.Run()   # コンパイル
for err in ctxt.Errors:
    print err

結論

あとは、Boo.Lang.Compiler.Ast.DepthFirstVisitor を継承して構文木トラバーサーを実装し、上記 ast に Accept() すれば、自前Booプログラム解析機のできあがりです。

Unity

通常のランタイムコードとしては使えませんが(無理やり入れてもでかすぎて非現実的)、エディタプログラムとしてであれば使えます。

5
5
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
5
5