Compiling a Parsetree

Hi all,

How would one go about compiling a Parsetree directly? Currently I can parse my DSL to a Parsetree -> Pretty print it as ocaml -> compile the generated ocaml to get a native exec. This works but it feels clunky as surely the ocaml compiler can take a Parsetree and directly compile it.

Ast_mapper doesn’t seem to be the tool for compiling a DSL with ocaml. It makes perfect sense to me if you want to make an extension as you can map the Parsetree nodes you want to modify and make your changes but not for compiling a DSL generated Parsetree.

Thanks,
Jason

The compiler will actually accept a marshalled parstree instead of the usual .ml (AFAICT this is used in particular by ppx rewriters, that output a parsetree that is then loaded by the compiler).

The code responsible for this is in driver/pparse.ml – you can see that there’s a “binary AST protocol” which you can follow to produce a file from a parsetree, that will then be accepted by the compiler as input (basically, just include compiler-libs and use Pparse.write_ast).

Note that the compiler-libs API is not guaranteed to be stable across versions of the compiler, and as the comment in pparse.ml notes these AST-writing/reading functions might move somewhere else in the future.

1 Like

Thank you very much!