OCaml Code-generation Toolbox
OCaml 91%
6%
Dune 3%

README.md

octx #

OCaml Code-generation Toolbox -- a CLI tool for generating useful OCaml code.

$ octx -d jsont,sexp_of --str "type t = { name : name; age : int } and name = string" | ocamlformat --impl -
let name_jsont = Jsont.string

let jsont =
  let make name age = { name; age } in
  Jsont.Object.map ~kind:"T" make
  |> Jsont.Object.mem "name" name_jsont ~enc:(fun t -> t.name)
  |> Jsont.Object.mem "age" Jsont.int ~enc:(fun t -> t.age)
  |> Jsont.Object.finish

let rec sexp_of_t =
  (fun { name = name__002_; age = age__004_ } ->
     let bnds__001_ = ([] : _ Stdlib.List.t) in
     let bnds__001_ =
       let arg__005_ = sexp_of_int age__004_ in
       (Sexplib0.Sexp.List [ Sexplib0.Sexp.Atom "age"; arg__005_ ] :: bnds__001_
         : _ Stdlib.List.t)
     in
     let bnds__001_ =
       let arg__003_ = sexp_of_name name__002_ in
       (Sexplib0.Sexp.List [ Sexplib0.Sexp.Atom "name"; arg__003_ ]
        :: bnds__001_
         : _ Stdlib.List.t)
     in
     Sexplib0.Sexp.List bnds__001_
    : t -> Sexplib0.Sexp.t)

and sexp_of_name = (sexp_of_string : name -> Sexplib0.Sexp.t)

There is also a built-in "destruct" deriver. It is a little more verbose than Merlin's.

$ octx -d destruct --str "type t = A of bool | B | C of string option" | ocamlformat --impl -
let destruct = function
  | A true -> assert false
  | A false -> assert false
  | B -> assert false
  | C None -> assert false
  | C (Some _) -> assert false
$ octx -d "destruct:type=string * int" --str "type t = A of bool | B | C of string option" | ocamlformat --impl -
let destruct = function
  | A true -> ("", 0)
  | A false -> ("", 0)
  | B -> ("", 0)
  | C None -> ("", 0)
  | C (Some _) -> ("", 0)

Another useful tool is the pattern-matching inverter.

$ cat > main.ml <<EOF \
> let f some_arg = function\
> | "-f" -> Some F\
> | "-e" -> Some E\
> | "-g" -> Some G\
> | _ -> None\
> EOF
$ octx --invert main.ml
let f some_arg =
  function
  | Some (F) -> "-f"
  | Some (E) -> "-e"
  | Some (G) -> "-g"
  | None -> assert false