wiki

ppx

also: ppx rewriter, extension point, deriver, ppxlib, deriving

A preprocessor that rewrites the OCaml syntax tree between parsing and type checking. Derivers generate code from type declarations tagged [@@deriving name]; extension points expand nodes written [%name payload]. Neither sees any types.

OCaml's syntax has two hooks reserved for preprocessors. Attributes, [@...] and [@@...], annotate existing syntax and are ignored by the compiler if nothing handles them. Extension nodes, [%...], stand for syntax that must be expanded, and the compiler rejects any that are left.

Using a deriver from dune: preprocess names the rewriters, and the attribute says which types to derive for.

(library
(name shapes)
(preprocess (pps ppx_deriving.show)))
type shape = Circle of float | Rect of float * float
[@@deriving show]
(* generates pp_shape and show_shape *)

ppxlib is the library rewriters are written against. It gives a stable view of the AST across compiler versions, builds AST fragments from quotations like [%expr ...], and runs every registered rewriter in one pass over each file.

A rewriter runs before type checking, so it knows the shape of a type declaration but not what any expression's type is. Code that needs types either takes them from the declaration it was attached to, or is written so that the type checker resolves what the ppx could not.

see also

referenced by

further reading

  • The OCaml manual, “Attributes” and “Extension nodes”.
  • The ppxlib manual.