ocamlppx

How to handle different OCaml versions when generating AST with ppxlib


I am making a ppx extension rewriter as part of a code library

Ideally the library will be usable with some range of OCaml versions

I have noticed that when building AST nodes to output from my rewriter it is unavoidable to have to construct some records, whose structure is specific to a particular OCaml AST version

For example, when building a variant type declaration we have to define a record like:

    {
      pcd_name = {txt = name; loc};
      pcd_args = Pcstr_tuple [];
      pcd_res = None;
      pcd_loc = loc;
      pcd_attributes = [];
    }

Which is the constructor_declaration type

However this AST type differs between OCaml 4.13 and OCaml 4.14

I am hoping that mostly the ppxlib Ast_builder helpers take care of generating the correct AST version for whatever OCaml version I'm compiling my library under.

But in the places where I have to manually define one of these record instances then presumably I need to detect the current OCaml version and return the correct record format that way?

I found this:

utop # Sys.ocaml_version;;
- : string = "4.12.1"

So presumably I should parse this string into int * int * int so that I can do a safe comparison for versions newer than 4.14.0

Is there a better way, or something different I should do instead?


Solution

  • The very aim of ppxlib is to write ppx independently of the compiler version. If you end up matching on the compiler version, you are duplicating the work done by ppxlib.

    Ppxlib works by using an internal reference AST and migrating between this reference AST and the various versions of OCaml AST. In theory, you could write by hand the AST node corresponding to the reference AST, however this is very brittle. This is why ppxlib provides two version-independent paths to build AST nodes, and all of them result in ppx that works on all versions of the compiler supported by ppxlib:

    If you find a corner case where you are required to write an AST node by hand this is a bug in ppxlib that you should report.