Not able to use %{d}_to_yojson in different path

Hey Team,

I am trying using to_yojson function on the type

and structure = structure_item list [@@deriving to_yojson]
the file path is : cst_viewer/bin/ml/

I am using structure_to_yojson in my file
the file path : cst_viewer/bin/

open Res_driver
open Parsetree
(* open Yojson.Basic *)

let store_person_as_json_file filename person =
  let json_str = Yojson.Safe.to_string (Parsetree.structure_to_yojson person) in
  let oc = open_out filename in
  output_string oc json_str;
  close_out oc

Error : unbound value Parsetree.structure_to_yojson

Here’s the dune file for both the path :
dune at

 (public_name cst_viewer)
 (name main)
 (libraries cst_viewer syntax)
 (preprocess (pps ppx_deriving_yojson)))

(dirs syntax ml js_parser ext)

   (:standard -O3 -unbox-closures)))
   (:standard -O3 -unbox-closures))))

dune at

 (name ml)
 (wrapped false)
   (run %{bin:cppo} %{env:CPPO_FLAGS=} %{input-file})))
  (:standard -w +a-4-42-40-41-44-45-9-48-67-70))
 (libraries ext js_parser))

(ocamllex lexer)

why am I not be able to use structure_to_yojson. can you guys please help me here?


Links would help.

I suppose that this boils down to something like

type structure = Parsetree.structure [@@deriving to_yojson]

In that case, the ppx will generate:

let structure_to_yojson = Parsetree.structure_to_yojson

To generate an “actual” function it needs to have access to the type definition. There’s a workaround which is using ppx_import. You should find some pointers in the ppxlib or ppx_deriving documentation.

Doing this for the Parsetree types is doable but tedious. If you want to consider alternatives, you can look at how does it (is supports ocaml syntax). Ppxlib has a sexp serializer also IIRC.