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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With