How to move typed abstract syntax tree in OCaml compiler

I am trying to dump the type information of all identifiers in an OCaml project, basically it is the same as traversing a typed abstract syntax tree ( https://github.com/ocaml/ocaml/blob/trunk/typing/typedtree.mli ). Since I'm new to the OCaml compiler code base, I'm not sure if the apis compiler was provided so we can easily write a plugin to complete the task or do we need to hack the compiler code? Also how does this interact with OCamlbuild? Thanks for any tips or advice.

+4
source share
2 answers

Suppose you already have a typed type AST structure.

The classic way is to simply write a large recursive function to go through the AST yourself.

But now there is a module TypedtreeIteravailable in the OCaml compiler source code, and it is exposed compiler-libs. For a simple workaround, this is very convenient.

TypedtreeIterprovides a functor for creating your own iterator over typed ASTs. Here is a very simple example to print all template identifiers with their types:

(* ocamlfind ocamlc -package compiler-libs.common -c example.ml *)
open Typedtree
open TypedtreeIter

module MyIteratorArgument = struct
  include DefaultIteratorArgument

  let enter_pattern p = match p.pat_desc with
    | Tpat_var (id, _) ->
        Format.printf "@[<2>%s@ : %a@]@."
          (Ident.name id)
          Printtyp.type_scheme p.pat_type
    | _ -> ()
end

module Iterator = TypedtreeIter.MakeIterator(MyIteratorArgument)

TypedtreeIter.IteratorArgument - , AST. : . , pattern enter_pattern exit_pattern. : MakeIterator. IteratorArgument, enter_* exit_* .

. DefaultIteratorArgument - , enter_* exit_* . IteratorArgument DefaultIteratorArgument, , , - .

, , TypedtreeMap TypedtreeIter. TypedtreeMap https://bitbucket.org/camlspotter/compiler-libs-hack/src/340072a7c14cbce624b98a57bf8c4c6509c40a31/overload/mod.ml?at=default.

( ocamlbuild, ).

+4

OCaml compiler-libs. , , , typedtree, .

, . utop merlin .

ocamlbuild compiler-libs, .

+3

All Articles