package easy-format

  1. Overview
  2. Docs
Legend:
Page
Library
Module
Module type
Parameter
Class
Class type
Source

Source file easy_format.ml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
let rev_split l =
  let rec inner xs ys = function
    | (x, y) :: xys ->
       inner (x::xs) (y::ys) xys
    | [] -> (xs, ys)
  in
  inner [] [] l

type wrap = [
  | `Wrap_atoms
  | `Always_wrap
  | `Never_wrap
  | `Force_breaks
  | `Force_breaks_rec
  | `No_breaks
]

type label_break = [
  | `Auto
  | `Always
  | `Always_rec
  | `Never
]

type style_name = string
type style = {
  tag_open : string;
  tag_close : string
}

type atom_param = {
  atom_style : style_name option;
}

let atom = {
  atom_style = None
}

type list_param = {
  space_after_opening : bool;
  space_after_separator : bool;
  space_before_separator : bool;
  separators_stick_left : bool;
  space_before_closing : bool;
  stick_to_label : bool;
  align_closing : bool;
  wrap_body : wrap;
  indent_body : int;
  list_style : style_name option;
  opening_style : style_name option;
  body_style : style_name option;
  separator_style : style_name option;
  closing_style : style_name option;
}

let list = {
  space_after_opening = true;
  space_after_separator = true;
  space_before_separator = false;
  separators_stick_left = true;
  space_before_closing = true;
  stick_to_label = true;
  align_closing = true;
  wrap_body = `Wrap_atoms;
  indent_body = 2;
  list_style = None;
  opening_style = None;
  body_style = None;
  separator_style = None;
  closing_style = None;
}

type label_param = {
  label_break: label_break;
  space_after_label : bool;
  indent_after_label : int;
  label_style : style_name option;
}

let label = {
  label_break = `Auto;
  space_after_label = true;
  indent_after_label = 2;
  label_style = None;
}

type t =
    Atom of string * atom_param
  | List of (string * string * string * list_param) * t list
  | Label of (t * label_param) * t
  | Custom of (Format.formatter -> unit)

type escape =
    [ `None
    | `Escape of
        ((string -> int -> int -> unit) -> string -> int -> int -> unit)
    | `Escape_string of (string -> string) ]

type styles = (style_name * style) list

(*
   Transform a tree starting from the leaves, propagating and merging
   accumulators until reaching the root.
*)
let propagate_from_leaf_to_root
  ~init_acc  (* create initial accumulator for a leaf *)
  ~merge_acc (* merge two accumulators coming from child nodes *)
  ~map_node  (* (node, acc) -> (node, acc) *)
  x =

  let rec aux x =
    match x with
    | Atom _ ->
        let acc = init_acc x in
        map_node x acc
    | List (param, children) ->
        let new_children, accs = rev_split (List.rev_map aux children) in
        let acc = List.fold_left merge_acc (init_acc x) accs in
        map_node (List (param, new_children)) acc
    | Label ((x1, param), x2) ->
        let acc0 = init_acc x in
        let new_x1, acc1 = aux x1 in
        let new_x2, acc2 = aux x2 in
        let acc = merge_acc (merge_acc acc0 acc1) acc2 in
        map_node (Label ((new_x1, param), new_x2)) acc
    | Custom _ ->
        let acc = init_acc x in
        map_node x acc
  in
  aux x

(*
   Convert wrappable lists into vertical lists if any of their descendants
   has the attribute wrap_body = `Force_breaks_rec.
*)
let propagate_forced_breaks x =
  (* acc = whether to force breaks in wrappable lists or labels *)
  let init_acc = function
    | List ((_, _, _, { wrap_body = `Force_breaks_rec; _ }), _)
    | Label ((_, { label_break = `Always_rec; _ }), _) -> true
    | Atom _
    | Label _
    | Custom _
    | List _ -> false
  in
  let merge_acc force_breaks1 force_breaks2 =
    force_breaks1 || force_breaks2
  in
  let map_node x force_breaks =
    match x with
    | List ((_, _, _, { wrap_body = `Force_breaks_rec; _ }), _) -> x, true
    | List ((_, _, _, { wrap_body = `Force_breaks; _ }), _) -> x, force_breaks

    | List ((op, sep, cl, ({ wrap_body = (`Wrap_atoms
                                         | `Never_wrap
                                         | `Always_wrap); _ } as p)),
            children) ->
        if force_breaks then
          let p = { p with wrap_body = `Force_breaks } in
          List ((op, sep, cl, p), children), true
        else
          x, false

    | Label ((a, ({ label_break = `Auto; _ } as lp)), b) ->
        if force_breaks then
          let lp = { lp with label_break = `Always } in
          Label ((a, lp), b), true
        else
          x, false

    | List ((_, _, _, { wrap_body = `No_breaks; _ }), _)
    | Label ((_, { label_break = (`Always | `Always_rec | `Never); _ }), _)
    | Atom _
    | Custom _ -> x, force_breaks
  in
  let new_x, _forced_breaks =
    propagate_from_leaf_to_root
      ~init_acc
      ~merge_acc
      ~map_node
      x
  in
  new_x

module Pretty =
struct
  (*
     Rewrite the tree to be printed.
     Currently, this is used only to handle `Force_breaks_rec.
  *)
  let rewrite x = propagate_forced_breaks x

  (*
    Relies on the fact that mark_open_tag and mark_close_tag
    are called exactly once before calling pp_output_string once.
    It's a reasonable assumption although not guaranteed by the
    documentation of the Format module.
  *)
  let set_escape fmt escape =
    let print0, flush0 = Format.pp_get_formatter_output_functions fmt () in
    let tagf0 = Format.pp_get_formatter_stag_functions fmt () in

    let is_tag = ref false in

    let mot tag =
      is_tag := true;
      tagf0.mark_open_stag tag
    in

    let mct tag =
      is_tag := true;
      tagf0.mark_close_stag tag
    in

    let print s p n =
      if !is_tag then
        (print0 s p n;
         is_tag := false)
      else
        escape print0 s p n
    in

    let tagf = {
      tagf0 with
        mark_open_stag = mot;
        mark_close_stag = mct
    }
    in
    Format.pp_set_formatter_output_functions fmt print flush0;
    Format.pp_set_formatter_stag_functions fmt tagf


  let set_escape_string fmt esc =
    let escape print s p n =
      let s0 = String.sub s p n in
      let s1 = esc s0 in
      print s1 0 (String.length s1)
    in
    set_escape fmt escape


  let define_styles fmt escape l =
    if l <> [] then (
      Format.pp_set_tags fmt true;
      let tbl1 = Hashtbl.create (2 * List.length l) in
      let tbl2 = Hashtbl.create (2 * List.length l) in
      List.iter (
        fun (style_name, style) ->
          Hashtbl.add tbl1 style_name style.tag_open;
          Hashtbl.add tbl2 style_name style.tag_close
      ) l;
      let mark_open_tag = function
        | Format.String_tag style_name ->
            (try Hashtbl.find tbl1 style_name
             with Not_found -> "")
        | _ -> ""
      in
      let mark_close_tag = function
        | Format.String_tag style_name ->
            (try Hashtbl.find tbl2 style_name
             with Not_found -> "")
        | _ ->
            ""
      in

      let tagf = {
        (Format.pp_get_formatter_stag_functions fmt ()) with
          mark_open_stag = mark_open_tag;
          mark_close_stag = mark_close_tag
      }
      in
      Format.pp_set_formatter_stag_functions fmt tagf
    );

    (match escape with
         `None -> ()
       | `Escape esc -> set_escape fmt esc
       | `Escape_string esc -> set_escape_string fmt esc)


  let pp_open_xbox fmt p indent =
    match p.wrap_body with
        `Always_wrap
      | `Never_wrap
      | `Wrap_atoms -> Format.pp_open_hvbox fmt indent
      | `Force_breaks
      | `Force_breaks_rec -> Format.pp_open_vbox fmt indent
      | `No_breaks -> Format.pp_open_hbox fmt ()

  let extra_box p l =
    let wrap =
      match p.wrap_body with
          `Always_wrap -> true
        | `Never_wrap
        | `Force_breaks
        | `Force_breaks_rec
        | `No_breaks -> false
        | `Wrap_atoms ->
            List.for_all (function Atom _ -> true | _ -> false) l
    in
    if wrap then
      ((fun fmt -> Format.pp_open_hovbox fmt 0),
       (fun fmt -> Format.pp_close_box fmt ()))
    else
      ((fun _ -> ()),
       (fun _ -> ()))


  let pp_open_nonaligned_box fmt p indent l =
    match p.wrap_body with
        `Always_wrap -> Format.pp_open_hovbox fmt indent
      | `Never_wrap -> Format.pp_open_hvbox fmt indent
      | `Wrap_atoms ->
          if List.for_all (function Atom _ -> true | _ -> false) l then
            Format.pp_open_hovbox fmt indent
          else
            Format.pp_open_hvbox fmt indent
      | `Force_breaks
      | `Force_breaks_rec -> Format.pp_open_vbox fmt indent
      | `No_breaks -> Format.pp_open_hbox fmt ()


  let open_tag fmt = function
      None -> ()
    | Some s -> Format.pp_open_stag fmt (Format.String_tag s)

  let close_tag fmt = function
      None -> ()
    | Some _ -> Format.pp_close_stag fmt ()

  let tag_string fmt o s =
    match o with
        None -> Format.pp_print_string fmt s
      | Some tag ->
          Format.pp_open_stag fmt (Format.String_tag tag);
          Format.pp_print_string fmt s;
          Format.pp_close_stag fmt ()

  let rec fprint_t fmt = function
      Atom (s, p) ->
        tag_string fmt p.atom_style s;

    | List ((_, _, _, p) as param, l) ->
        open_tag fmt p.list_style;
        if p.align_closing then
          fprint_list fmt None param l
        else
          fprint_list2 fmt param l;
        close_tag fmt p.list_style

    | Label (label, x) -> fprint_pair fmt label x
    | Custom f -> f fmt

  and fprint_list_body_stick_left fmt p sep hd tl =
    open_tag fmt p.body_style;
    fprint_t fmt hd;
    List.iter (
      fun x ->
        if p.space_before_separator then
          Format.pp_print_string fmt " ";
        tag_string fmt p.separator_style sep;
        if p.space_after_separator then
          Format.pp_print_space fmt ()
        else
          Format.pp_print_cut fmt ();
        fprint_t fmt x
    ) tl;
    close_tag fmt p.body_style

  and fprint_list_body_stick_right fmt p sep hd tl =
    open_tag fmt p.body_style;
    fprint_t fmt hd;
    List.iter (
      fun x ->
        if p.space_before_separator then
          Format.pp_print_space fmt ()
        else
          Format.pp_print_cut fmt ();
        tag_string fmt p.separator_style sep;
        if p.space_after_separator then
          Format.pp_print_string fmt " ";
        fprint_t fmt x
    ) tl;
    close_tag fmt p.body_style

  and fprint_opt_label fmt = function
      None -> ()
    | Some (lab, lp) ->
        open_tag fmt lp.label_style;
        fprint_t fmt lab;
        close_tag fmt lp.label_style;
        if lp.space_after_label then
          Format.pp_print_string fmt " "

  (* Either horizontal or vertical list *)
  and fprint_list fmt label ((op, _sep, cl, p) as param) = function
      [] ->
        fprint_opt_label fmt label;
        tag_string fmt p.opening_style op;
        if p.space_after_opening || p.space_before_closing then
          Format.pp_print_string fmt " ";
        tag_string fmt p.closing_style cl

    | hd :: tl as l ->

        if tl = [] || p.separators_stick_left then
          fprint_list_stick_left fmt label param hd tl l
        else
          fprint_list_stick_right fmt label param hd tl l


  and fprint_list_stick_left fmt label (op, sep, cl, p) hd tl l =
    let indent = p.indent_body in
    pp_open_xbox fmt p indent;
    fprint_opt_label fmt label;

    tag_string fmt p.opening_style op;

    if p.space_after_opening then
      Format.pp_print_space fmt ()
    else
      Format.pp_print_cut fmt ();

    let open_extra, close_extra = extra_box p l in
    open_extra fmt;
    fprint_list_body_stick_left fmt p sep hd tl;
    close_extra fmt;

    if p.space_before_closing then
      Format.pp_print_break fmt 1 (-indent)
    else
      Format.pp_print_break fmt 0 (-indent);
    tag_string fmt p.closing_style cl;
    Format.pp_close_box fmt ()

  and fprint_list_stick_right fmt label (op, sep, cl, p) hd tl l =
    let base_indent = p.indent_body in
    let sep_indent =
      String.length sep + (if p.space_after_separator then 1 else 0)
    in
    let indent = base_indent + sep_indent in

    pp_open_xbox fmt p indent;
    fprint_opt_label fmt label;

    tag_string fmt p.opening_style op;

    if p.space_after_opening then
      Format.pp_print_space fmt ()
    else
      Format.pp_print_cut fmt ();

    let open_extra, close_extra = extra_box p l in
    open_extra fmt;

    fprint_t fmt hd;
    List.iter (
      fun x ->
        if p.space_before_separator then
          Format.pp_print_break fmt 1 (-sep_indent)
        else
          Format.pp_print_break fmt 0 (-sep_indent);
        tag_string fmt p.separator_style sep;
        if p.space_after_separator then
          Format.pp_print_string fmt " ";
        fprint_t fmt x
    ) tl;

    close_extra fmt;

    if p.space_before_closing then
      Format.pp_print_break fmt 1 (-indent)
    else
      Format.pp_print_break fmt 0 (-indent);
    tag_string fmt p.closing_style cl;
    Format.pp_close_box fmt ()



  (* align_closing = false *)
  and fprint_list2 fmt (op, sep, cl, p) = function
      [] ->
        tag_string fmt p.opening_style op;
        if p.space_after_opening || p.space_before_closing then
          Format.pp_print_string fmt " ";
        tag_string fmt p.closing_style cl

    | hd :: tl as l ->
        tag_string fmt p.opening_style op;
        if p.space_after_opening then
          Format.pp_print_string fmt " ";

        pp_open_nonaligned_box fmt p 0 l ;
        if p.separators_stick_left then
          fprint_list_body_stick_left fmt p sep hd tl
        else
          fprint_list_body_stick_right fmt p sep hd tl;
        Format.pp_close_box fmt ();

        if p.space_before_closing then
          Format.pp_print_string fmt " ";
        tag_string fmt p.closing_style cl


  (* Printing a label:value pair.

     The opening bracket stays on the same line as the key, no matter what,
     and the closing bracket is either on the same line
     or vertically aligned with the beginning of the key.
  *)
  and fprint_pair fmt ((lab, lp) as label) x =
    match x with
        List ((op, sep, cl, p), l) when p.stick_to_label && p.align_closing ->
          fprint_list fmt (Some label) (op, sep, cl, p) l

      | _ ->
          let indent = lp.indent_after_label in
          Format.pp_open_hvbox fmt 0;

          open_tag fmt lp.label_style;
          fprint_t fmt lab;
          close_tag fmt lp.label_style;

          (match lp.label_break with
           | `Auto ->
               if lp.space_after_label then
                 Format.pp_print_break fmt 1 indent
               else
                 Format.pp_print_break fmt 0 indent
           | `Always
           | `Always_rec ->
               Format.pp_force_newline fmt ();
               Format.pp_print_string fmt (String.make indent ' ')
           | `Never ->
               if lp.space_after_label then
                 Format.pp_print_char fmt ' '
               else
                 ()
          );
          fprint_t fmt x;
          Format.pp_close_box fmt ()

  let to_formatter fmt x =
    let x = rewrite x in
    fprint_t fmt x;
    Format.pp_print_flush fmt ()

  let to_buffer ?(escape = `None) ?(styles = []) buf x =
    let fmt = Format.formatter_of_buffer buf in
    define_styles fmt escape styles;
    to_formatter fmt x

  let to_string ?escape ?styles x =
    let buf = Buffer.create 500 in
    to_buffer ?escape ?styles buf x;
    Buffer.contents buf

  let to_channel ?(escape = `None) ?(styles = []) oc x =
    let fmt = Format.formatter_of_out_channel oc in
    define_styles fmt escape styles;
    to_formatter fmt x

  let to_stdout ?escape ?styles x = to_channel ?escape ?styles stdout x
  let to_stderr ?escape ?styles x = to_channel ?escape ?styles stderr x

end




module Compact =
struct
  open Printf

  let rec fprint_t buf = function
      Atom (s, _) -> Buffer.add_string buf s
    | List (param, l) -> fprint_list buf param l
    | Label (label, x) -> fprint_pair buf label x
    | Custom f ->
        (* Will most likely not be compact *)
        let fmt = Format.formatter_of_buffer buf in
        f fmt;
        Format.pp_print_flush fmt ()

  and fprint_list buf (op, sep, cl, _) = function
      [] -> bprintf buf "%s%s" op cl
    | x :: tl ->
        Buffer.add_string buf op;
        fprint_t buf x;
        List.iter (
          fun x ->
            Buffer.add_string buf sep;
            fprint_t buf x
        ) tl;
        Buffer.add_string buf cl

  and fprint_pair buf (label, _) x =
    fprint_t buf label;
    fprint_t buf x


  let to_buffer buf x = fprint_t buf x

  let to_string x =
    let buf = Buffer.create 500 in
    to_buffer buf x;
    Buffer.contents buf

  let to_formatter fmt x =
    let s = to_string x in
    Format.fprintf fmt "%s" s;
    Format.pp_print_flush fmt ()

  let to_channel oc x =
    let buf = Buffer.create 500 in
    to_buffer buf x;
    Buffer.output_buffer oc buf

  let to_stdout x = to_channel stdout x
  let to_stderr x = to_channel stderr x
end




(* Obsolete *)
module Param =
struct
  let list_true = {
    space_after_opening = true;
    space_after_separator = true;
    space_before_separator = true;
    separators_stick_left = true;
    space_before_closing = true;
    stick_to_label = true;
    align_closing = true;
    wrap_body = `Wrap_atoms;
    indent_body = 2;
    list_style = None;
    opening_style = None;
    body_style = None;
    separator_style = None;
    closing_style = None;
  }

  let list_false = {
    space_after_opening = false;
    space_after_separator = false;
    space_before_separator = false;
    separators_stick_left = false;
    space_before_closing = false;
    stick_to_label = false;
    align_closing = false;
    wrap_body = `Wrap_atoms;
    indent_body = 2;
    list_style = None;
    opening_style = None;
    body_style = None;
    separator_style = None;
    closing_style = None;
  }

  let label_true = {
    label_break = `Auto;
    space_after_label = true;
    indent_after_label = 2;
    label_style = None;
  }

  let label_false = {
    label_break = `Auto;
    space_after_label = false;
    indent_after_label = 2;
    label_style = None;
  }
end
OCaml

Innovation. Community. Security.