ocamlabstract-syntax-treecamlp4

Is it possible the get the AST for an OCaml program?


I'd like to be able to get the AST for a given OCaml program (I'd like to walk the AST and generate an instrumented version of the code or do some kind of transformation, for example). Do any of the OCaml tools support this functionality?


Solution

  • Since OCaml 4.02.1 it is possible to use the PPX tools written bu Alain Frisch to precisely do this. Example:

    % ocamlfind ppx_tools/dumpast -e "1 + 2"
    1 + 2
    ==>
    {pexp_desc =
      Pexp_apply ({pexp_desc = Pexp_ident {txt = Lident "+"}},
       [("", {pexp_desc = Pexp_constant (Const_int 1)});
        ("", {pexp_desc = Pexp_constant (Const_int 2)})])}
    =========
    

    It is possible to use this program to dump the AST of a normal code file as well, and various options control the degree of precision of the dump. In the example above, for instance, the location parameters of the AST are hidden.