ocamlcamlp4

OCaml - preprocessing with type information


I want to pre-process an OCaml snippet and make some modifications on the snippet, based on the type of certain expressions. For example, if the snippet has:

(f [1;2;3])

I would add another parameter to f like:

(f [1;2;3] [[0]])

.

But if I see something like:

(f ["a"; "b"])

Then I might want to:

(f ["a"; "b"] [[""]])

I was looking at camlp4, though I am not thorough with it; I think camlp4 doesn't have type information about the expressions.

Is there any way I can do this? Thanks!


Solution

  • CamlP4 is a preprocessor in the parse tree level which is not yet type-checked. Therefore writing type-dependent behaviour is ... not impossible but very hard: you need to send P4 parse tree to your probably modified OCaml type-checker then retrieve the typed AST from it, then translate it back to P4's untyped tree, somehow. P4's special AST data type makes this extremely hard to implement. In addition, people are now moving away from P4 :-(

    OCaml preprocessing with types is much easier with its new -ppx framework, since it has better accesses to the compiler internals. It is not very easy but enough feasible. If you really want your type dependent preprocessing I recommend to use ppx. Main taksks are:

    https://bitbucket.org/camlspotter/compiler-libs-hack explains how to implement such a typeful ppx preprocessor. I hope it helps you.