Source file wadler_pretty.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
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
open Printf



(*
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
One Layout: Module Type
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*)

module type S0 =
sig
    type t

    val nil: t
    val text: string -> t
    val line: t
    val (<>): t -> t -> t
    val nest: int -> t -> t

    val layout: t -> string
end






(*
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
One Layout
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

   Inefficient recursion for nesting and concatenation.

   Concatenation

        (x <> y) <> z

        First x is traversed completely to append y to all line and text
        elemenst. And then x <> y is traversed completely to append z.

   Nesting

        nest i (nest j x)

        nest j x adds the indentation j to all lines in x and then nest i adds i
        again. This is quadratic complexity on the length of the document.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*)
module Doc0: S0 =
struct
    type t =
        | Nil
        | Text of string * t
        | Line of int * t

    let nil    = Nil

    let text s = Text (s, Nil)

    let line   = Line (0, Nil)


    let rec (<>) x y =
        match x with
        | Nil ->
            y
        | Text (s, Nil) -> Text (s, y)
        | Text (s, x)   -> Text (s, x <> y)
        | Line (i, Nil) -> Line (i, y)
        | Line (i, x)   -> Line (i, x <> y)


    let rec nest i = function
        | Nil -> Nil
        | Text (s, x) -> Text (s, nest i x)
        | Line (j, x) -> Line (i + j, nest i x)


    let rec layout = function
        | Nil         ->  ""
        | Text (s, x) -> s ^ layout x
        | Line (i, x) -> sprintf "\n%s%s" (String.make i ' ') (layout x)
end








(*
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
One Layout Lazy
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

   No gain in efficiency if layout is called. All lazy terms have to be forced.
   The inefficiency for nesting and concatenation remains.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*)
module Doc0_lazy:
sig
    type t

    val nil: t
    val text: string -> t
    val line: t
    val (<>): t -> t -> t
    val nest: int -> t -> t

    val layout: t -> string
end
=
struct
    type t =
        | Nil
        | Text of string * laz
        | Line of int * laz

    and laz = t Lazy.t

    let force = Lazy.force


    let nil    = Nil

    let text s = Text (s, lazy Nil)

    let line   = Line (0, lazy Nil)


    let rec (<>) x y =
        match x with
        | Nil -> y
        | Text (s, x) -> begin
                match force x with
                | Nil -> Text (s, lazy y)
                | x   -> Text (s, lazy (x <> y))
            end
        | Line (i, x) -> begin
                match force x with
                | Nil -> Line (i, lazy y)
                | x   -> Line (i, lazy (x <> y))
            end


    let rec nest i = function
        | Nil -> Nil
        | Text (s, x) -> Text (s,     lazy (nest i (force x)))
        | Line (j, x) -> Line (i + j, lazy (nest i (force x)))


    let rec layout = function (* document must not contain unions *)
        | Nil         ->  ""
        | Text (s, x) -> s ^ (force x |> layout)
        | Line (i, x) -> sprintf "\n%s%s" (String.make i ' ') (force x |> layout)
end






(*
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
One Layout Optimized
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    Key ideas to avoid the quadratic complexity for left associative
    concatenation and nested nesting:

    - Represent concatenation x <> y by an own constructor Cat (x, y) and layout
    x completely before laying out y.

    - Represent nest i x by an own constructor Nest (i, x) and cumulate
   the nesting levels.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*)
module Doc0_opt: S0 =
struct
    type t =
        | Nil
        | Text of string
        | Line
        | Cat  of t * t
        | Nest of int * t

    let nil    = Nil

    let text s = Text s

    let line   = Line

    let (<>) x y = Cat (x, y)

    let nest i x = Nest (i, x)


    let rec la: (int * t) list -> string = function
        | [] ->
            ""
        | (i, x) :: z ->
            match x with
            | Nil         -> ""
            | Text s      -> s
            | Line        -> sprintf "\n%s" (String.make i ' ')
            | Nest (j, x) -> la (((i + j), x) :: z)         (* cumulate *)
            | Cat (x, y)  -> la ((i, x) :: (i, y) :: z)     (* x first  *)


    let layout (x: t): string = la [0, x]
end










(*
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Module Type for Multiple Layouts
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

   One additional function group.

   Function pretty with a desired line width is exported instead of layout.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*)
module type S =
sig
    type t

    val nil: t
    val text: string -> t
    val line: t
    val (<>): t -> t -> t
    val nest: int -> t -> t
    val group: t -> t

    val pretty: int -> t -> string
end












(*
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Multiple Layouts (Inefficient)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    Each group doubles the documents i.e. for 10 groups we have 2^10 documents.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*)
module Doc1: S =
struct
    type t =
        | Nil
        | Text of string * t
        | Line of int * t
        | Union of t * t

    let rec flatten: t -> t = function
        | Nil          -> Nil
        | Text (s, x)  -> Text (s,   flatten x)
        | Line (_, x)  -> Text (" ", flatten x)
        | Union (x, _) -> flatten x


    let rec fits (w: int): t -> bool = function
        (* Document must not contain unions *)
        | Nil          -> true
        | Line (_, _)  -> true
        | Union _      -> assert false (* illegal call *)
        | Text (s, x)  ->
            assert (0 <= w);
            let w = w - String.length s in
            w < 0 || fits w x


    let rec best (w: int) (k: int): t -> t = function
        | Nil -> Nil
        | Text (s, x) -> Text (s, best w (k + String.length s) x)
        | Line (i, x) -> Line (i, best w i x)
        | Union (x, y) ->
            if fits (w - k) (best w k x) then
                x
            else
                best w k y


    let rec layout = function (* document must not contain unions *)
        | Nil         ->  ""
        | Text (s, x) -> s ^ layout x
        | Line (i, x) -> sprintf "\n%s%s" (String.make i ' ') (layout x)
        | Union _     -> assert false (* illegal call *)



    let nil = Nil

    let text s = Text (s, Nil)

    let line   = Line (0, Nil)

    let rec (<>) x y =
        match x with
        | Nil ->
            y
        | Text (s, Nil) -> Text (s, y)
        | Text (s, x)   -> Text (s, x <> y)
        | Line (i, Nil) -> Line (i, y)
        | Line (i, x)   -> Line (i, x <> y)
        | Union (x1, x2)  -> Union (x1 <> y, x2 <> y)

    let rec nest i = function
        | Nil -> Nil
        | Text (s, x) -> Text (s, nest i x)
        | Line (j, x) -> Line (i + j, nest i x)
        | Union (x, y) -> Union (nest i x, nest i y)


    let group (x: t): t =
        Union (flatten x, x)

    let pretty (w: int) (x: t): string =
        layout (best w 0 x)
end














(*
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Multiple Layouts Lazy Implementation
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    Basic idea:

        The constructors Text (s, x), Line (i, x), and Union (x, y) do not
        contain a document x, but a lazy document.

        The function fits forces the document x in Text (s, x) only as long as
        the document fits on the line.

        The function best is lazy as well and forces documents only through
        fits. If fits returns true, then the document is forced completely. This
        is not a problem, since it is selected and used in the layout.

        If fits fails the document is only partially forced until the failure is
        evident and then thrown away, because the unflatted version is the
        selected one.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*)
module Doc1_lazy: S =
struct
    type t =
        | Nil
        | Text of string * laz
        | Line of int * laz
        | Union of laz * t

    and laz = t Lazy.t

    let force = Lazy.force


    let rec flatten: t -> laz = function
        | Nil          -> lazy Nil
        | Text (s, x)  -> lazy (Text (s,   force x |> flatten))
        | Line (_, x)  -> lazy (Text (" ", force x |> flatten))
        | Union (x, _) -> force x |> flatten


    let rec fits (w: int): t -> bool = function
        (* Document must not contain unions *)
        | _ when w < 0 -> false
        | Nil | Line _ -> true
        | Union _      -> assert false (* illegal call *)
        | Text (s, x)  ->
            fits (w - String.length s) (force x)


    let rec best (w: int) (k: int): t -> t = function
        | Nil ->
            Nil

        | Text (s, x) ->
            Text (s, lazy (best w (k + String.length s) (force x)))

        | Line (i, x) ->
            Line (i, lazy (best w i (force x)))

        | Union (x, y) ->
            let x = force x |> best w k in
            if fits (w - k) x then
                x
            else
                best w k y


    let rec layout = function (* document must not contain unions *)
        | Nil         ->  ""
        | Text (s, x) -> s ^ layout (force x)
        | Line (i, x) -> sprintf "\n%s%s" (String.make i ' ') (layout (force x))
        | Union _     -> assert false (* illegal call *)



    let nil = Nil

    let text s = Text (s, lazy Nil)

    let line   = Line (0, lazy Nil)

    let rec (<>) x y =
        match x with
        | Nil ->
            y
        | Text (s, x) -> begin
                match force x with
                | Nil -> Text (s, lazy y)
                | x   -> Text (s, lazy (x <> y))
            end
        | Line (i, x) -> begin
                match force x with
                | Nil -> Line (i, lazy y)
                | x   -> Line (i, lazy (x <> y))
            end
        | Union (x1, x2)  ->
            Union (lazy (force x1 <> y), x2 <> y)

    let rec nest i = function
        | Nil -> Nil
        | Text (s, x)  -> Text (s,     lazy (nest i (force x)))
        | Line (j, x)  -> Line (i + j, lazy (nest i (force x)))
        | Union (x, y) -> Union (lazy (nest i (force x)), nest i y)


    let group (x: t): t =
        Union (flatten x, x)

    let pretty (w: int) (x: t): string =
        layout (best w 0 x)
end













(*
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Multiple Layouts Optimized Lazy Implementation
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*)
module Doc2_lazy: S =
struct
    let force = Lazy.force

    module Base =
    struct
        type t =
            | Nil
            | Text of string * laz
            | Line of int * laz

        and laz = t Lazy.t

        let rec fits (w: int): t -> bool = function
            | _ when w < 0      -> false
            | Nil | Line (_, _) -> true

            | Text (s, x) ->
                fits (w - String.length s) (force x)


        let rec layout: t -> string = function
            | Nil ->
                ""
            | Text (s, x) ->
                sprintf "%s%s" s (force x |> layout)

            | Line (i, x) ->
                sprintf "\n%s%s" (String.make i ' ') (force x |> layout)
    end

    type t =
        | Nil
        | Text of string
        | Line
        | Cat of laz * laz
        | Nest of int * laz
        | Union of laz * t

    and laz = t Lazy.t


    let rec flatten: t -> laz = function
        | Nil         ->  lazy Nil
        | Line        ->  lazy (Text " ")
        | Text _ as x ->  lazy x
        | Cat (x, y)  ->  lazy (Cat (flatlaz x, flatlaz y))
        | Nest (i, x) ->  lazy (Nest (i, flatlaz x))
        | Union (x, _) -> flatlaz x

    and flatlaz x = force x |> flatten


    let rec be (w: int) (k: int): (int * t) list -> Base.t = function
        | [] ->
            Nil

        | (i, x) :: z ->
            match x with
            | Nil ->
                be w k z

            | Text s ->
                Text (s, lazy (be w (k + String.length s) z))

            | Line ->
                Line (i, lazy (be w i z))

            | Cat (x, y) ->
                (* Make concatenation right associative *)
                be w k ((i, force x) :: (i, force y) :: z)

            | Nest (j, x) ->
                (* Accumulate nesting levels *)
                be w k (((i + j), force x) :: z)

            | Union (x, y) ->
                let x = be w k ((i, force x) :: z) in
                if Base.fits (w - k) x then
                    x
                else
                    be w k ((i, y) :: z)



    let nil = Nil

    let text s = Text s

    let line   = Line

    let (<>) x y = Cat (lazy x, lazy y)

    let nest i x = Nest (i, lazy x)

    let group = function
        | Union _ as x -> x (* group is idempotent *)
        | x            -> Union (flatten x, x)

    let pretty (w: int) (x: t): string =
        be w 0 [0, x] |> Base.layout
end











module Pretty_plus (Pretty: S):
sig
    include S

    val parent_child: int -> t -> t -> t
end
=
struct
    include Pretty

    let parent_child (i: int) (parent: t) (child: t): t =
        parent <> nest i (line <> group child) |> group
end



module Tree (Pretty: S) =
struct
    module P = Pretty_plus (Pretty)

    type t =
        { name: string; children: t list; }


    let leaf (name: string): t =
        {name; children = []}

    let tree (name: string) (children: t list): t =
        {name; children}



    let doc_tree (t: t): P.t =
        let open P
        in
        let rec doc is_top tree =
            match tree.children with
            | [] ->
                text tree.name
            | _ ->
                let d =
                    parent_child
                        2
                        (text tree.name)
                        (children tree.children)
                in
                if is_top then
                    d
                else
                    text "(" <> d <> text ")"
        and children lst =
            match lst with
            | [last] ->
                doc false last
            | head :: tail ->
                doc false head
                <> line
                <> children tail
            | [] ->
                assert false (* [lst] is never empty *)
        in
        doc true t

    let args2 = [leaf "a"; leaf "b"]
    let args3 = [leaf "a"; leaf "b"; leaf "c"]
    let args4 = [leaf "a"; leaf "b"; leaf "c"; leaf "d"]

    let tree0 =
        tree "ff" args3

    let tree1 =
        tree
            "ff"
            [leaf "a";
             tree "gf" args2;
             leaf "d"]

    let tree2 =
        tree
            "ff"
            [tree "gf" args2;
             tree "gf" args2;
             tree "gf" args2]


    let tree3 =
        tree
            "f"
            [tree "f" args2;
             tree "f" [tree "f" args4];
             tree "f" args4;
             tree "f" args3;]


    let string0 w =
        doc_tree tree0 |> P.pretty w

    let string1 w =
        doc_tree tree1 |> P.pretty w

    let string2 w =
        doc_tree tree2 |> P.pretty w

    let string3 w =
        doc_tree tree3 |> P.pretty w
end



let test0 (print: bool) (str: string) (expected: string): bool =
    let ok = str = expected in
    if not ok || print then
        printf "---\nstr\n%s\nexpected\n%s\n\n" str expected;
    ok


module Test (P: S) =
struct
    open Unit_test_support

    module Tree = Tree (P)

    let%test _ =
        let str = Tree.string0 3
        and expected = {|
            ff
              a
              b
              c
            |} |> quoted
        in
        test0 false str expected

    let%test _ =
        let str = Tree.string0 8
        and expected = "ff a b c"
        in
        test0 false str expected

    let%test _ =
        let str = Tree.string0 7
        and expected = {|
            ff
              a b c
            |} |> quoted
        in
        test0 false str expected


    let%test _ =
        let str = Tree.string2 27
        and expected = {|
            ff
              (gf a b)
              (gf a b)
              (gf a b)
            |} |> quoted
        in
        test0 false str expected


    let%test _ =
        let str = Tree.string3 47
                (*      01234567890123456789012345678901234567890123456 *)
        and expected = "f (f a b) (f (f a b c d)) (f a b c d) (f a b c)"
        in
        test0 false str expected


    let%test _ =
        let str = Tree.string3 46
        and expected = {|
            f
              (f a b)
              (f (f a b c d))
              (f a b c d)
              (f a b c)
            |} |> quoted
        in
        test0 false str expected


    let%test _ =
        let str = Tree.string3 16
        and expected =
            {|
            f
              (f a b)
              (f
                (f a b c d))
              (f a b c d)
              (f a b c)
            |} |> quoted
        in
        test0 false str expected


    let%test _ =
        let str = Tree.string3 13
        and expected =
            {|
            f
              (f a b)
              (f
                (f
                  a
                  b
                  c
                  d))
              (f a b c d)
              (f a b c)
            |} |> quoted
        in
        test0 false str expected


    let%test _ =
        let str = Tree.string3 5
        and expected =
            {|
            f
              (f
                a
                b)
              (f
                (f
                  a
                  b
                  c
                  d))
              (f
                a
                b
                c
                d)
              (f
                a
                b
                c)
            |} |> quoted
        in
        test0 false str expected
end

module Test_Doc1_lazy = Test (Doc1_lazy)
module Test_Doc2_lazy = Test (Doc2_lazy)