How to write custom ppx decorator to rescript?

763 Views Asked by At

I need to generate a value with a different type from my passed type. This is the first time I write on ocaml-like, and for example, in a familiar me haskell I would use Data.Generics. How I have understood I need to use decorator and ppx. I wrote simple example

let recordHandler = (loc: Location.t, _recFlag: rec_flag, _t: type_declaration, fields: list(label_declaration)) => {
  let (module Builder) = Ast_builder.make(loc);

  let test = [%str
    let schema: Schema = { name: "", _type: String, properties: [] }
  ]
  let moduleExpr = Builder.pmod_structure(test);

  [%str
    module S = [%m moduleExpr]
  ]
}

let str_gen = (~loc, ~path as _, (_rec: rec_flag, t: list(type_declaration))) => {
  let t = List.hd(t)

  switch t.ptype_kind {
  | Ptype_record(fields) => recordHandler(loc, _rec, t, fields);
  | _ => Location.raise_errorf(~loc, "schema is used only for records.");
  };
};
let name = "my_schema";

let () = {
  let str_type_decl = Deriving.Generator.make_noarg(str_gen);
  Deriving.add(name, ~str_type_decl) |> Deriving.ignore;
};

And

open Ppxlib;

let _ = Driver.run_as_ppx_rewriter()

But in using in rescript code

module User = {
  @deriving(my_schema)
  type my_typ = {
    foo: int,
  };
};

I caught:

schema is not supported

. And I made myself sure me to connect it right when I had changed @deriving(my_schema) for @deriving(abcd) and @deriving(sschema). I got different error

Ppxlib.Deriving: 'abcd' is not a supported type deriving generator.

And my last experiment was to copy past existing library deriving accessors . ppx_accessor I copied-pasted it and renamed for accessors_2. And I got same error such as experiment.

accessors_2 is not supported

Also I haven't found examples "ppx rescript". Can you please help me. What am I doing wrong (ALL , I know)

1

There are 1 best solutions below

0
On

I have found answer in the article

Dropping support for custom PPXes such as ppx_deriving (the deriving attribute is now exclusively interpreted as bs.deriving)