README.md

sexp #

Declarative S-expression codecs for OCaml with streaming I/O via bytesrw and jsont-style structured errors.

Overview #

Sexp provides a bidirectional codec system for S-expressions, inspired by Daniel Bünzli's jsont library. Codecs are defined once and used for both encoding and decoding, eliminating the class of bug where serialisation and deserialisation logic drift apart.

Decode errors are reported via loc with a structural path context identifying the member, index, or variant case that failed.

Domain-specific codecs (e.g. dune build files) live in separate packages on top of [Sexp.Codec] — see nox-dune for the dune codec.

Installation #

Install with opam:

$ opam install nox-sexp

If opam cannot find the package, it may not yet be released in the public opam-repository. Add the overlay repository, then install it:

$ opam repo add samoht https://tangled.org/gazagnaire.org/opam-overlay.git
$ opam update
$ opam install nox-sexp

Usage #

type config = { host : string; port : int; debug : bool }

let config_codec =
  Sexp.Codec.Record.(
    obj (fun host port debug -> { host; port; debug })
    |> mem "host" Sexp.Codec.string ~enc:(fun c -> c.host)
    |> mem "port" Sexp.Codec.int ~enc:(fun c -> c.port)
    |> mem "debug" Sexp.Codec.bool ~enc:(fun c -> c.debug) ~dec_absent:false
    |> finish
  )

(* Decode. Error is a formatted string with line/column and the path
   context that pinpoints the failing member or list element. *)
let config =
  match Sexp.Codec.decode_string config_codec
    {|((host "localhost") (port 8080) (debug true))|}
  with
  | Ok c -> c
  | Error _ -> failwith "invalid S-expression"

(* Encode to a string. *)
let s =
  Sexp.Codec.encode_string config_codec
    { host = "example.com"; port = 443; debug = false }
(* "((host example.com) (port 443) (debug false))" *)

(* Pretty-printed encoding with configurable indentation. *)
let pretty = Sexp.Codec.encode_string_hum ~indent:2 config_codec config

For programmatic inspection of errors use the primed variants returning the structured Sexp.Error.t. Loc, Meta, Path, and Sort_kind are available directly as Sexp.Loc, Sexp.Meta, Sexp.Path, Sexp.Sort_kind:

let report input =
  match Sexp.Codec.decode_string config_codec input with
  | Ok _ -> ()
  | Error _ -> Format.eprintf "invalid S-expression@."

S-expression format #

Atoms and lists. Atoms are unquoted tokens (foo, 42, 3.14) or quoted strings ("hello world"). Lists are parenthesised and nest.

; Records as association lists
((name "Alice")
 (age 30)
 (active true))

; Variants as tagged values
(Some 42)
None

Base codecs #

Codec OCaml type S-expression
string string foo, "h"
int int 42, -17
int32 int32 100
int64 int64 1000
float float 3.14, -0.5
bool bool true, false
unit unit ()

Combinators #

let opt_int = Sexp.Codec.option Sexp.Codec.int
let int_list = Sexp.Codec.list Sexp.Codec.int
let pair_codec = Sexp.Codec.pair Sexp.Codec.string Sexp.Codec.int

Records #

type person = { name : string; age : int; email : string option }

let person_codec =
  Sexp.Codec.Record.(
    obj (fun name age email -> { name; age; email })
    |> mem "name" Sexp.Codec.string ~enc:(fun p -> p.name)
    |> mem "age" Sexp.Codec.int ~enc:(fun p -> p.age)
    |> opt_mem "email" Sexp.Codec.string ~enc:(fun p -> p.email)
    |> finish
  )

Variants #

type colour = Red | Green | Blue | Rgb of int * int * int

let colour_codec =
  Sexp.Codec.Variant.(
    variant [
      case "Red" Sexp.Codec.unit
        (fun () -> Red)
        (function Red -> Some () | _ -> None);
      case "Green" Sexp.Codec.unit
        (fun () -> Green)
        (function Green -> Some () | _ -> None);
      case "Blue" Sexp.Codec.unit
        (fun () -> Blue)
        (function Blue -> Some () | _ -> None);
      case "Rgb" (Sexp.Codec.triple Sexp.Codec.int Sexp.Codec.int Sexp.Codec.int)
        (fun (r, g, b) -> Rgb (r, g, b))
        (function Rgb (r, g, b) -> Some (r, g, b) | _ -> None);
    ])

API overview #

  • 'a t -- codec type (bidirectional)
  • Base codecs: string, atom, int, int32, int64, float, bool, unit
  • Combinators: map, const, option, list, array, pair, triple, rec', enum, result
  • Record -- obj, mem, opt_mem, skip_unknown, error_unknown, finish (with ?kind, ?doc, ?dec_absent, ?enc_omit)
  • Variant -- variant, case0, casev
  • Decoding: decode, decode', decode_string, decode_string', decode_string_exn -- all with ?max_depth (default 100) and ?max_nodes (default 10_000_000)
  • Encoding: encode, encode_string, encode_hum, encode_string_hum
  • Queries: mem (project a member out), list_codec
  • Sort module -- Atom | List with kinded / or_kind
  • Loc, Meta, Path, Sort_kind, Error -- shared source-location and structured-error infrastructure, available as Sexp.Loc, Sexp.Meta, Sexp.Path, Sexp.Sort_kind, Sexp.Error (same modules as in loc)
  • Invalid_utf8_encode of int -- raised by the encoder when a string atom is not well-formed UTF-8

Full signatures in sexp.mli and sexp.mli.

References #

  • jsont -- JSON codec library that inspired the approach
  • bytesrw -- composable byte stream readers and writers
  • loc -- shared source-location and error infrastructure
  • sexplib -- Jane Street's S-expression library with PPX derivers
  • csexp -- canonical S-expressions used by Dune's RPC protocol

License #

ISC. See LICENSE.md.