ocaml-ppx / ppxlib

Base library and tools for ppx rewriters
MIT License
246 stars 98 forks source link

Generating recursive definitions with metaquot #488

Closed francoisthire closed 2 months ago

francoisthire commented 5 months ago

I am writing a PPX deriver and I am tackling a recursive type such as

type foo = bar list 

and bar = foo option

I am using metaquot and I wanted to generate something like:

...
if is_recursive then 
  if first_binding then
    [%stri let rec v = expr]
  else
    [%stri and v' = expr']
else
  [%stri let v = expr]

This does not work because [%stri and] is forbidden. I guess I will have to use a smart constructor from Ast_builder module. However, I wonder whether it would be ok to make this expression well-typed with metaquote? I understand just accepting the and is not type-safe since there is no guarantee it is a valid expression.

NathanReb commented 4 months ago

Indeed, the [%stri ...] extension expects, as its name suggest, a structure item. In your case, and v' = expr' is not a structure item, just part of one. In you example the structure item would be the whole set of value bindings:

let rec v = expr
and v' = expr'
and v'' = expr''

Here you are trying to build a structure item with Pstr_value of rec_flag * value_binding list. It's probably simpler to propagate the rec_flag from the type definition and map each type_declaration to a value_binding.

NathanReb commented 2 months ago

I'm closing this, feel free to re-open if you deem it necessary