Hello! I’m trying to learn current best practices for writing PPX transformers and am curious about the capabilities of ppxlib.metaquot
. I’m in a situation in which I want to generate a function for a type declaration. To simplify the example, suppose I want to transform
[%foo type 'a bar = 'a]
into
type 'a bar = 'a
let foo_bar (type a) (x : a bar) = failwith "foo!"
(I’m aware that the above would ordinarily be done with a deriver.) In my PPX, I’d love to be able to write something quite simple:
let create_function_from_type (tdecl : type_declaration) : structure_item =
... (* lots of looking at tdecl here *)
let tdecl_name = ... in
let tdecl_type = ??? in
[%stri
let [%p (Pat.var ~loc ({loc;txt=tdecl_name}))] (type a) (x : a [%t tdecl_type]) =
failwith "foo!"
]
I have three questions about the above:
- Am I going about this the right way with the
[%p ...]
extension above? That is: is there any other way to insert an identifier into escaped code other than to build a wrapper around it? - Is there any way to write a value for
tdecl_type
above that will allow the kind of parameterization I want? I’m pessimistic given the shape of the OCaml AST, but I’d feel better about that conclusion if other people could verify it. - What is wrong with the syntax of the
[%stri ...]
extension above? Even if I discard thetdecl_type
part and go with
I get a syntax error at the beginning of[%stri let [%p (Pat.var ~loc ({loc;txt=tdecl_name}))] (type a) (x : a) = failwith "foo!" ]
(type a)
. (There is no message;ocamlc
just says “syntax error”.) Do I have to instead go with
Is this just a limitation of the extension syntax?[%stri let [%p (Pat.var ~loc ({loc;txt=tdecl_name}))] = fun (type a) (x : a) -> failwith "foo!" ]
My understanding is that ppxlib.metaquot
should help me avoid writing ASTs by hand. I’m finding in my current project that I am constructing a lot of ASTs using Ast_helper
and destructing a lot of ASTs using match
. Based on my understanding, I conclude that I’m using these tools incorrectly. Any advice on style or approach is appreciated!