6

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?

nlucaroni
  • 47,556
  • 6
  • 64
  • 86
aneccodeal
  • 8,531
  • 7
  • 45
  • 74
  • 2
    I think the accepted answer is outdated (camlp4 is not maintained since 2017); I would accept one of the last two answers mentioning `ppx`s or `compiler-libs`. – Ulugbek Abdullaev Jul 21 '19 at 07:53

4 Answers4

4

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.

ygrek
  • 6,656
  • 22
  • 29
  • What does that motivating example do? – aneccodeal Jun 30 '10 at 15:46
  • Insert calls co Camlp4prof.count (read "arbitrary") function at the beginning of each parsed function definition passing name and location parameters. – ygrek Jun 30 '10 at 16:32
  • An Active discussion on resources to learn camlp4: http://groups.google.com/group/fa.caml/browse_thread/thread/1751a2c308742ac3?hl=en – nlucaroni Sep 28 '10 at 13:29
4

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.

Michaël Le Barbier
  • 6,103
  • 5
  • 28
  • 57
2

What you're looking for is [camlp4][1]. I haven't used camlp4 before, so I can't attest to it's virtues as software. I have heard of people using camlp5 [http://pauillac.inria.fr/~ddr/camlp5/] which, according to wikipedia, has better documentation than the current version of camlp4.

Axle
  • 371
  • 2
  • 8
  • I thought camlp4 was used to modify & customize the OCaml syntax, but I suppose it makes sense that it can get to the AST somehow. – aneccodeal Jun 30 '10 at 03:03
2

You can use compiler-libs to achieve this. See Parsetree, Asttypes, and Ast_helper.

tekknolagi
  • 10,663
  • 24
  • 75
  • 119