From 5a7ca4ca2ed845ac83e67f60d09b7cd73a594aed Mon Sep 17 00:00:00 2001 From: Simon Cruanes Date: Tue, 1 Nov 2022 22:20:56 -0400 Subject: [PATCH] feat(util): improve debug printer wrt newlines --- src/util/Log.ml | 5 ++++- src/util/Util.ml | 12 ++++++++++++ src/util/Util.mli | 1 + 3 files changed, 17 insertions(+), 1 deletion(-) diff --git a/src/util/Log.ml b/src/util/Log.ml index 0a116641..95c9df4a 100644 --- a/src/util/Log.ml +++ b/src/util/Log.ml @@ -15,13 +15,16 @@ let start_ = Unix.gettimeofday () let[@inline never] debug_real_ l k = k (fun fmt -> let now = Unix.gettimeofday () -. start_ in + (* print into buf_ in one go, so that outputs of nested debug calls + do not interleave on stdout *) Buffer.clear buf_; let once_done _fmt = Format.fprintf _fmt "@]@?"; let msg = Buffer.contents buf_ in (* forward to profiling *) if Profile.enabled () then Profile.instant msg; - Format.fprintf !debug_fmt_ "@[<2>@{[%d|%.3f]@}@ %s@]@." l now msg + Format.fprintf !debug_fmt_ "@[<2>@{[%d|%.3f]@}@ %a@]@." l now + Util.pp_string_with_lines msg in Format.fprintf buf_fmt_ "@[<2>"; diff --git a/src/util/Util.ml b/src/util/Util.ml index 8513f088..8d200ed2 100644 --- a/src/util/Util.ml +++ b/src/util/Util.ml @@ -10,6 +10,18 @@ let pp_sep sep out () = Format.fprintf out "%s@," sep let pp_list ?(sep = " ") pp out l = Fmt.list ~sep:(pp_sep sep) pp out l let pp_iter ?(sep = " ") pp out l = Fmt.iter ~sep:(pp_sep sep) pp out l +let pp_string_with_lines out (s : string) : unit = + Fmt.fprintf out "@["; + let i = ref 0 in + let n = String.length s in + while !i < n do + let j = try String.index_from s !i '\n' with Not_found -> n in + if !i > 0 then Fmt.fprintf out "@,"; + Fmt.substring out (s, !i, j - !i); + i := j + 1 + done; + Fmt.fprintf out "@]" + let pp_pair ?(sep = " ") pp1 pp2 out t = Fmt.pair ~sep:(pp_sep sep) pp1 pp2 out t diff --git a/src/util/Util.mli b/src/util/Util.mli index 2353ed04..514c2572 100644 --- a/src/util/Util.mli +++ b/src/util/Util.mli @@ -8,6 +8,7 @@ val pp_list : ?sep:string -> 'a printer -> 'a list printer val pp_iter : ?sep:string -> 'a printer -> 'a Iter.t printer val pp_array : ?sep:string -> 'a printer -> 'a array printer val pp_pair : ?sep:string -> 'a printer -> 'b printer -> ('a * 'b) printer +val pp_string_with_lines : string printer val flat_map_l_arr : ('a -> 'b array) -> 'a list -> 'b list val array_of_list_map : ('a -> 'b) -> 'a list -> 'b array