Allow generation of type definitions using expression nodes
Suppose, I want to expand
type t = A [@len 2]
[@@deriving abc]
to
type t = A0 | A1
This is straightforward using ppxlib since 2 is a known constant. However, I was wondering if it's possible to generate type definitions based on expressions:
let x = Int.of_string "2" (* some arbitrary expression *)
type t = A [@len x]
[@@deriving abc]
I am able to generate let bindings. But type declarations, to the best of my knowledge, seem to be impossible since the OCaml AST doesn't allow constructing a core_type using expressions.
I'm not quite sure I understood what you are trying to do but I'll answer to each of your questions individually.
Using ppxlib context free rules you cannot expand:
type t = A [@len 2]
[@@deriving abc]
into:
type t = A0 | A1
[@@deriving ...] nodes are used to generate new code from a type declaration, you can't modify the type declaration itself with it.
You can write a ppx that would generate such a type definition with an extension rule though. Something like:
[%%gen_variant_type type t = A [@len 2]]
That would then be expanded into:
type t = A0 | A1
Regarding your other problem, i.e. whether you can pass an expression and have the ppx behave based on this expression's evaluation, it's unfortunately not how ppx-es work. Ppx rewriters only receive the AST so unless you evaluate the expression yourself in your ppx's code (which I wouldn't advise you to do), this won't work. The payload of the [@len ...] attribute will just be a variable named x. You can inject that variable in generated code but you cannot interpret it here since the rewriter won't know about the previous binding of x.
If you give me a bit more context here I might be able to help you figure out a solution.
I'm closing this, please feel free to re-open if you deem it necessary.