ocaml

OCaml runtime error when parsing sexp using ppx


I tried to use ppx to autogenerate an sexp parser for a type that I define, and it compiles without errors, yet it gives runtime error when I actually run it by entering "(1 2)" as an sexp:

Fatal error: exception (Of_sexp_error "lib/a.ml.exp_of_sexp: unexpected variant constructor"
  (invalid_sexp (1 2)))
Raised at Sexplib0__Sexp_conv.of_sexp_error in file "src/sexp_conv.ml", line 154, characters 30-72

The file a.ml contains the following type definition:

open Sexplib.Std
type var = string [@@deriving sexp]

type const =
  | CNum of int
  | CStr of string
  | CBool of bool [@@deriving sexp]
 
type exp =
  | E1
  | E2
  | EConst of const
  | EVar of var
  | EList of exp list [@@deriving sexp]

and the error shows up when I tried to call: exp_of_sexp (Core.Sexp.of_string (read_line ())) to read a line and parse it.


Solution

  • What exp value are you expecting the s-expression (1 2) to represent?

    I think your code is fine, but your expectations are off.

    I would expect input like (EVar "foo") or (EConst (CNum 42)) to parse just fine, though. To gain more insight, try printing string representations of the s-expressions generated by functions like sexp_of_exp to see what exp_of_sexp is looking for.