LoginSignup
15
9

More than 5 years have passed since last update.

RustでrustソースファイルのASTを構築するサンプル

Last updated at Posted at 2015-01-25

背景

rustでサンプルプログラム書いてたら、コンパイラのバグを踏んでしまいました。(ちなみにバグはすでに報告されてて、修正待ちの様子)

その関係でrustのコンパイル周りのソースを読んでいて、rustのソースファイルからASTを構築したくなったので、勉強ついでに書いてみました。

ASTを構築するサンプル

use std::os;

extern crate syntax;

use syntax::parse;
use syntax::ast;

fn main()
{
    let args = os::args();

    let cfg = Vec::new();
    let path = Path::new(&args[1]);
    let sess = syntax::parse::new_parse_sess();

    // parse_crate_from_file(input: &Path, cfg: CrateConfig, sess: &ParseSess) -> Crate
    let krate = syntax::parse::parse_crate_from_file(&path, cfg, &sess);
    print!("{:?}", krate.module); // crate のmodule を debug dump
}

cfg は用途がわからなかったので、とりあえず空にした。

コンパイルして、 ./parse 任意のrustソースファイル とすると、そのソースをパースしてASTを構築し、デバッグダンプする。
結構な出力が一行に出力されるので、簡単なlintツールをお気に入りの言語で書いてください。

rustc でASTをダンプする方法

ASTをダンプしたいだけなら、下記でjson形式でダンプできます。

rustc -Z ast-json <source>
または
rustc -Z ast-json-noexpand <source>

#上記2つの違いはちょっと調べ中。

その他のデバッグオプションを確認するには、rustc -Z helpとすれば一覧が表示できます。

15
9
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
15
9