Ppxlib: preprocess structure and signature item simultaneously


I am trying to do a tricky manipulation of mli and ml with ppxlib.
I currently have a ppx_rewriter where I override the Ast_traverse.map:

class mapper =
  object (_self)
    inherit Ast_traverse.map as super

    method! structure_item stri = ..

    method! signature_item sigi = ..

let () =
  let mapper = new mapper in

But in a perfect world I would have a function of type:

val expand : structure_item -> signature_item option -> structure_item

Where I could have at the same time the structure and optionally the signature of any item in the code.
From what I understand the preprocessing is applied to the .mli and then the ml. I don’t know if there’s
any classy way to link any structure_item to its signature item.

PPX happens before type-checking, so you don’t have types: so can’t derive a sig_item from the str_item. And MLI and ML files are of course parsed separatedly, so that can’t be used, either. And even if they were somehow parsed in parallel, an ML file can be quite complicated, to the point where it’s nontrivial (again, entailing typechecking) to associate a sig_item in an MLI, with the associated str_item in the ML file. And of course, all of the above sort of assumes that you have well-typed code. But PPX can take code that isn’t well-typed (e.g. with extensions, or missing stuff) and convert it to well-typed code.

Shorter: what you’re asking for probably requires type-checking, and PPX is explicitly pre-type-checking.