From 0d9d17d5db7f86ea0a922deebb50e09f98fdf1b5 Mon Sep 17 00:00:00 2001 From: Simon Cruanes Date: Thu, 3 Nov 2016 15:36:25 +0100 Subject: [PATCH] add `CCFormat.Dump` for easy debugging (see #82) --- src/core/CCFormat.ml | 28 ++++++++++++++++++++++++++++ src/core/CCFormat.mli | 29 +++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+) diff --git a/src/core/CCFormat.ml b/src/core/CCFormat.ml index a2e567ac..8e356930 100644 --- a/src/core/CCFormat.ml +++ b/src/core/CCFormat.ml @@ -301,3 +301,31 @@ let ksprintf ~f fmt = Format.kfprintf (fun _ -> Format.pp_print_flush out (); f (Buffer.contents buf)) out fmt + + +module Dump = struct + type 'a t = 'a printer + let unit = unit + let int = int + let string = string_quoted + let bool = bool + let float = float + let char = char + let int32 = int32 + let int64 = int64 + let nativeint = nativeint + let list pp = hovbox (list ~start:"[" ~stop:"]" ~sep:";" pp) + let array pp = hovbox (array ~start:"[|" ~stop:"|]" ~sep:";" pp) + let option pp out x = match x with + | None -> Format.pp_print_string out "None" + | Some x -> Format.fprintf out "Some %a" pp x + let pair p1 p2 = pair p1 p2 + let triple p1 p2 p3 = triple p1 p2 p3 + let quad p1 p2 p3 p4 = quad p1 p2 p3 p4 +end + +(*$= & ~printer:(fun s->s) + "[1;2;3]" (to_string Dump.(list int) [1;2;3]) + "Some 1" (to_string Dump.(option int) (Some 1)) + "[None;Some \"a b\"]" (to_string Dump.(list (option string)) [None; Some "a b"]) +*) diff --git a/src/core/CCFormat.mli b/src/core/CCFormat.mli index 7d2fd22b..dd3f0194 100644 --- a/src/core/CCFormat.mli +++ b/src/core/CCFormat.mli @@ -172,3 +172,32 @@ val ksprintf : val to_file : string -> ('a, t, unit, unit) format4 -> 'a (** Print to the given file *) + +(** {2 Dump} + + Print structures as OCaml values, so that they can be parsed back + by OCaml (typically, in the toplevel, for debugging) + + @since NEXT_RELEASE *) + +module Dump : sig + type 'a t = 'a printer + val unit : unit t + val int : int t + val string : string t + val bool : bool t + val float : float t + val char : char t (** @since 0.14 *) + val int32 : int32 t (** @since 0.14 *) + val int64 : int64 t (** @since 0.14 *) + val nativeint : nativeint t (** @since 0.14 *) + + val list : 'a t -> 'a list t + val array : 'a t -> 'a array t + val option : 'a t -> 'a option t + val pair : 'a t -> 'b t -> ('a * 'b) t + val triple : 'a t -> 'b t -> 'c t -> ('a * 'b * 'c) t + val quad : + 'a t -> 'b t -> 'c t -> 'd t -> + ('a * 'b * 'c * 'd) t +end