Questions about the use or developpement of PPXes (OCaml syntax extension)
PPX Syntax Extensions
ppx is the syntax extension format supported currently by OCaml. PPX rewriters are preprocessors for OCaml programs that are applied to the code before passing it on to the compiler. They work over the AST resulting from its parsing, and compute a new AST that will be actually compiled.
Extension Nodes
OCaml features syntax extensions that are meant to be used by external tools. The kind of extensions exist which are attributes and extension nodes.
- Attributes are “decorations” of the syntax tree which are mostly ignored by the type-checker but can be used by external tools.
- Extension nodes are generic placeholders in the syntax tree. They are rejected by the type-checker and are intended to be “expanded” by external tools such as -ppx rewriters.
The -ppx
option
ocamlc and ocamlopt both take a -ppx
command line option. This option takes as argument a program that is executed during the compilation of a file in order to transform it on the fly. This program is called a ppx rewriter. More precisely, once the OCaml compiler has parsed the source file and constructed the corresponding AST, it runs the ppx with this AST as input. The ppx returns a new transformed AST and the compiler continues the compilation process with this new AST, discarding the original one.
Several -ppx
options can be passed to the compiler. In this case, the compiler will apply the various ppx rewriters one by one, each one feeding its output to the next one.
Using dune
It is easy to integerate a PPX preprocessing to a workflow. If you want to pass command line flags that do not start with a -, you can separate library names from flags using --. So for instance from the following preprocess field:
(preprocess (pps ppx1 -foo ppx2 -- -bar 42))
ppxlib
The modern solution for writing PPX extensions. Without this library, writing PPX extensions is fragile and breaks with OCaml version changes. ppxlib merges several older projects together to provide a complete platform for writing efficient, resilient PPX extensions.
OCaml-migrate-parsetree
This library converts OCaml parsetrees between different major versions thus making a PPX written for a given version of OCaml portable with older versions.