[@@deriving sexp] of a type defined in other module

I’m trying to use [@@deriving sexp] in a type defined in a library module:

utop # type t = {
  startpos : Lexing.position;
  endpos : Lexing.position;
}[@@deriving sexp];;
Error: Unbound value Lexing.position_of_sexp

but the compiler complains that doesn’t know Module.type_of_sexp expression. What am I missing here?

[@@deriving sexp] relies on sexp_of_* and *_of_sexp being defined already. Since they don’t, you would need to define them yourself. I think in this case it would look like:

type lexing_position = Lexing.position

let sexp_of_lexing_position position = fill in function here ...
let lexing_position_of_sexp sexp = fill in function here ...

See this: https://github.com/janestreet/sexplib#sexplib---s-expressions-for-ocaml

So the type you need to convert to/from is:

type sexp = Atom of string | List of sexp list
1 Like

Thank you @BrendanLong! I’ll try to implement my own conversion functions.

But this doesn’t solve anything. You have to write those functions by hand.

Is there a way to actually derive them?

1 Like

In this case, the representation of Lexing.position is exposed, so I think you should be able to copy that representation and then do [@@deriving] as normal.

Edit: that is:

type lexing_position = Lexing.position =
  { pos_fname : string
  ; pos_lnum : int
  ; pos_bol : int
  ; pos_cnum : int
[@@deriving sexp]

Answering myself:

type lexing_position = [%import: Lexing.position] [@@deriving sexp]

(Modulo some weird warnings and the fact that ppx_import is not 4.08-compatible.)