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/parsetree.ml

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

Main.ml

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 Main.ml

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

(dirs syntax ml js_parser ext)

(env
 (dev
  (env-vars
   (CPPO_FLAGS -U=RELEASE)))
 (release
  (env-vars
   (CPPO_FLAGS -D=RELEASE))
  (ocamlopt_flags
   (:standard -O3 -unbox-closures)))
 (static
  (env-vars
   (CPPO_FLAGS -D=RELEASE))
  (ocamlopt_flags
   (:standard -O3 -unbox-closures))))

dune at parsetree.ml

(library
 (name ml)
 (wrapped false)
 (preprocess
  (action
   (run %{bin:cppo} %{env:CPPO_FLAGS=} %{input-file})))
 (flags
  (: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?

Thanks

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 https://astexplorer.net/ does it (is supports ocaml syntax). Ppxlib has a sexp serializer also IIRC.