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?
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.
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.
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.
You can use compiler-libs
to achieve this. See Parsetree
, Asttypes
, and Ast_helper
.
© 2022 - 2024 — McMap. All rights reserved.
ppx
s orcompiler-libs
. – Tye