Using ppx for code generation

I will share my recent finding into this topic, but since I am quiet new to Ocaml and its ecosystem there must be a better way.

The relevant official documentation on Inria site is at "Chapter 27 The compiler front-end". Ast_helper, Parsetree, Pprintast, and Asttypes are the most relevant.

To view parsetree of any Ocaml file, you can either use ocamlfind ppx_tools/dumpast <filename> or use -dparsetree option of ocamlc/ocamlopt.

To generate code, using Ast_helper and Parsetree directly is possible but very tedious, the following block of code generates [5] :

let e_const = Ast_helper.Exp.constant (Pconst_integer ("5", None))  
let loc = { Asttypes.txt = Longident.Lident "[]"; loc = Location.none }
let my_tuple = Ast_helper.Exp.tuple [e_const; Ast_helper.Exp.construct loc None]
let concat_id = Longident.Lident "::"
let concat_loc = { Asttypes.txt = concat_id; loc = Location.none }
let concat_construct = Ast_helper.Exp.construct concat_loc (Some my_tuple)

‘ppx_tools/ast_convenience’ simplify the above code to:

Ast_convenience.list [(Ast_convenience.int 5)]

Though it does not seem to have abstraction for all parts of Parsetree, so familiarity with Parsetree is probably needed even when using ppx_tools. I have not experiment with ppx_metaquot, so I can’t comment on this topic.