Ppx_sexp_conv for code generation?

Is it possible to use ppx_sexp_conv to generate source code?

I’m considering using s-expressions to interface between js_of_ocaml code and ReScript code, but there’s a question mark over the use of ppxes in ReScript long term (and apparently some short-term issues too).

If I could generate an .ml file from OCaml type definitions and use that on the ReScript side together with sexplib to read and write s-expressions, it seems it would almost eliminate the manual boilerplate interfacing effort compared with using say JSON. Of course there’s also the prospect of ReScript eventually dropping support for ML syntax, but I’m less concerned about that than their ppx support.

If not, is there any other means of doing something similar?

You can use ppxlib’s deriving_inline [1] feature to generate code at compile time. This will let you generate the encoder/decoder for s-expressions using ppx_sexp_conv while allowing you to drop the dependency on the ppx for the published library/application.

[1] ppxlib/ppx-for-end-users.rst at 278815e65d10fe86358cf0c9f78592fc8afe5b13 · ocaml-ppx/ppxlib · GitHub

Edit: As an example, base makes use of deriving_inline → base/option.ml at e8e658eded12b085bcca890dc035ffbe09460aec · janestreet/base · GitHub

4 Likes