Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 234
aneccodeal Avatar asked Jun 29 '10 20:06

aneccodeal


2 Answers

camlp4 is a way to go. Here is a motivating example. The docs are sparse - true, but one can make his way reading through wiki, existing examples, tutorials, and maybe even camlp4 sources.

like image 108
ygrek Avatar answered Oct 12 '22 15:10

ygrek


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.

like image 30
Michaël Le Barbier Avatar answered Oct 12 '22 16:10

Michaël Le Barbier