Declarative S-expression codecs
README.md

sexp #

Declarative S-expression codecs for OCaml, with streaming I/O over bytesrw and structured errors.

Hand-written S-expression support usually means a parser and a printer for each type, and the two drift apart as the type changes. With sexp you describe the type once, as a codec, and use it in both directions. The design follows Daniel Bünzli's jsont. A decode error is a loc value with the source location and a path to the member, list index or variant case that failed.

When a file is read with ~meta:Full, writing it back with ~preserve:true` gives the same bytes, comments included. A tool can then change one field in a hand-written file and leave the rest of the file as it was.

Codecs for particular file formats are separate packages built on Sexp.Codec; nox-dune, for instance, covers the dune files.

Installation #

Install with opam:

$ opam install nox-sexp

The package may not be in the public opam-repository yet. In that case, add the overlay first:

$ 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. On failure the [Error] case carries a structured
   [Sexp.Error.t] with the line/column and the path context that
   pinpoints the failing member or list element. *)
let config =
  match Sexp.of_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.to_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.to_string ~indent:2 config_codec config

An error prints with Sexp.Error.to_string or Sexp.Error.pp, and a program can also match on it. Sexp.Loc, Sexp.Meta, Sexp.Path and Sexp.Error are the modules of the loc package, re-exported:

let describe input =
  match Sexp.of_string config_codec input with
  | Ok _ -> "valid"
  | Error e -> Sexp.Error.to_string e

A variant is written as a tagged list, and its codec has one case per constructor:

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);
    ])

S-expression format #

An S-expression is either an atom or a list. An atom is a bare token (foo, 42, 3.14) or a quoted string ("hello world"). A list sits between parentheses and can contain other lists.

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

; Variants as tagged values
(Some 42)
None

API #

The signatures are in sexp.mli and codec.mli. Sexp.Codec has the base codecs (string, int, int32, int64, float, bool, unit), combinators such as map, option, result, fix, pair, triple, list and array, and the Record, Variant and List builders. Sexp reads and writes strings (of_string, to_string) and Bytesrw streams (of_reader, to_writer), and decode and encode convert between a codec's type and a parsed value. Below the codecs, Value is the raw syntax tree with its queries and parsers, and Cursor is a zipper for editing a tree in place.

Every decoder takes ?max_depth (100 by default) and ?max_nodes (10_000_000 by default). A parse that goes past either limit fails with an error, so hostile input cannot use up the stack or the heap.

References #

  • jsont, the JSON codec library this one copies its design from.
  • bytesrw, byte stream readers and writers.
  • loc, the source locations and errors shared with other codec packages.
  • sexplib, Jane Street's S-expression library, which derives converters with a PPX.
  • csexp, canonical S-expressions, which Dune's RPC protocol uses.

Licence #

ISC. See LICENSE.md.