ocamlcのパーサを使う

まず、ocamlソースコードをどっかに展開して、一度makeする。

$ tar xvfz ocaml-3.09.1
$ cd ocaml-3.09.1
$ ./configure
$ make world
$ make opt
$ make opt.opt

パーサを使いたいプログラムのMakefileを適当に書く。

$ cd src
$ cat Makefile
OCAMLMAKEFILE = OCamlMakefile

OCAMLDIR = ../ocaml-3.09.1
SOURCES = main.ml

RESULT = ocamlrefactor
TRASH = *~
PACKS = extlib

INCDIRS = $(OCAMLDIR)/utils $(OCAMLDIR)/parsing

OCAMLLIBS = misc tbl config clflags terminfo ccomp warnings consistbl \
	linenum location longident syntaxerr parser lexer parse printast

OCAMLBLDFLAGS = $(addsuffix .cmo, $(OCAMLLIBS))
OCAMLNLDFLAGS = $(addsuffix .cmx, $(OCAMLLIBS))

include $(OCAMLMAKEFILE)

main.mlの中身は、stdinからocamlのプログラムを読み込んで、Printastでstdoutに出力するというもの。

$ cat main.ml
let _ =
  let lexbuf = Lexing.from_channel stdin in
  let ss = Parse.implementation lexbuf in
  let fmt = Format.formatter_of_out_channel stdout in
    Printast.implementation fmt ss

実行例。

$ ocamlrefactor
let _ = Printf.sprintf "foobar"^D
structure_item (0..31)
  Pstr_eval
  expression (8..31)
    Pexp_apply
    expression (8..22)
      Pexp_ident "Printf.sprintf"
    <label> ""
      expression (23..31)
        Pexp_constant Const_string "foobar"

ちゃんと読めてるっぽい。

と、ここまでやってから思ったんだけど、camlp4を使ったほうが楽なのかも。使ったことないので、全然わからないのですが。