-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathPrettyTabbedDoc.sml
1355 lines (1163 loc) · 44.7 KB
/
PrettyTabbedDoc.sml
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
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(** Copyright (c) 2022-2023 Sam Westrick
*
* See the file LICENSE for details.
*)
(** Functor argument CustomString could either be a standard string, or could
* be a TerminalColorString, etc.
*)
functor PrettyTabbedDoc
(structure CustomString:
sig
type t
val substring: t * int * int -> t
(* should be visually distinct, e.g., color the background.
* the integer argument is a depth; this can be ignored (in which
* case all depths will be emphasized the same) or can be used
* to distinguish different tab depths
*)
val emphasize: int -> t -> t
val fromString: string -> t
val toString: t -> string
val size: t -> int
val concat: t list -> t
end
structure Token:
sig
type t
val same: t * t -> bool
val desiredBlankLinesBefore: t -> int
val splitCommentsBefore: t -> t Seq.t
val splitCommentsAfter: t -> t Seq.t
val splitCommentsAfterAndBeforeNext: t -> t Seq.t * t Seq.t
end
datatype pieces =
OnePiece of CustomString.t
| ManyPieces of CustomString.t Seq.t
val tokenToPieces: {tabWidth: int} -> Token.t -> pieces) :>
sig
type doc
type t = doc
exception InvalidDoc
val empty: doc
val nospace: doc
val space: doc
val text: CustomString.t -> doc
val token: Token.t -> doc
val concat: doc * doc -> doc
val letdoc: doc -> (DocVar.t -> doc) -> doc
val var: DocVar.t -> doc
type style = Tab.Style.t
type tab
val root: tab
val newTabWithStyle: tab -> style * (tab -> doc) -> doc
val newTab: tab -> (tab -> doc) -> doc
val cond: tab -> {inactive: doc, active: doc} -> doc
val at: tab -> doc -> doc
val pretty:
{ ribbonFrac: real
, maxWidth: int
, indentWidth: int
, tabWidth: int
, debug: bool
}
-> doc
-> CustomString.t
val prettyJustComments:
{ ribbonFrac: real
, maxWidth: int
, indentWidth: int
, tabWidth: int
, debug: bool
}
-> Token.t Seq.t
-> CustomString.t
end =
struct
(* IDEA: lazily activate tabs. If size/ribbon are violated, then
* promote the outermost tab.
*
* Promotion follows this progression, which improves horizontal compaction:
* Flattened -> ActivatedInPlace -> ActivatedIndented
* -----------------> (horizontal compaction)
*)
structure TabDict = Dict(Tab)
structure TabSet = Set(Tab)
structure VarDict = Dict(DocVar)
(* ====================================================================== *)
exception InvalidDoc
type tab = Tab.t
type style = Tab.Style.t
val root = Tab.root
(* SAM_NOTE: small time/space tradeoff here. In comparison to SimplePromise,
* the MemoizedPromise implementation seems to be 5-10% faster using
* 10-20% more space. IMO the time improvement is a win, since smlfmt
* needs to be fast. *)
structure Promise = MemoizedPromise
(* structure Promise = SimplePromise *)
datatype doc =
Empty
| Space
| NoSpace
| Newline
| Concat of doc * doc
| Text of CustomString.t
| Token of Token.t
| At of tab * doc
| NewTab of {tab: tab, gen: doc Promise.t}
| Cond of {tab: tab, inactive: doc, active: doc}
| LetDoc of {var: DocVar.t, doc: doc, inn: doc}
| Var of DocVar.t
type t = doc
val empty = Empty
val newline = Newline
val nospace = NoSpace
val space = Space
val text = Text
val token = Token
fun at t d = At (t, d)
val letdoc = LetDoc
val var = Var
fun cond tab {inactive, active} =
Cond {tab = tab, inactive = inactive, active = active}
fun concat (d1, d2) =
case (d1, d2) of
(Empty, _) => d2
| (_, Empty) => d1
| _ => Concat (d1, d2)
fun letdoc d f =
let
val v = DocVar.new ()
val k = f v
in
LetDoc {var = v, doc = d, inn = k}
end
fun newTabWithStyle parent (style, genDocUsingTab: tab -> doc) =
let
val t = Tab.new {parent = parent, style = style}
fun gen () = genDocUsingTab t
in
NewTab {tab = t, gen = Promise.new gen}
end
fun newTab parent f = newTabWithStyle parent (Tab.Style.inplace, f)
(* ====================================================================== *)
fun firstToken doc =
let
fun error () =
raise Fail "PrettyTabbedDoc.firstToken: disagreement"
fun loop vars doc =
case doc of
Concat (d1, d2) =>
(case loop vars d1 of
NONE => loop vars d2
| t => t)
| Token t => SOME t
| At (_, d) => loop vars d
| NewTab {gen, ...} => loop vars (Promise.get gen)
| Cond {inactive, active, ...} =>
(case (loop vars inactive, loop vars active) of
(NONE, NONE) => NONE
| (SOME t, SOME t') =>
if Token.same (t, t') then SOME t else error ()
| _ => error ())
| LetDoc {var, doc, inn} =>
let
val x = loop vars doc
val vars = VarDict.insert vars (var, x)
in
loop vars inn
end
| Var v => VarDict.lookup vars v
| _ => NONE
in
loop VarDict.empty doc
end
(* ====================================================================== *)
fun spaces count =
CustomString.fromString (CharVector.tabulate (count, fn _ => #" "))
datatype sentry =
StartTabHighlight of {tab: tab, col: int}
| StartMaxWidthHighlight of {col: int}
datatype eentry =
EndTabHighlight of {tab: tab, col: int}
| EndMaxWidthHighlight of {col: int}
fun sentryCol se =
case se of
StartTabHighlight {col, ...} => col
| StartMaxWidthHighlight {col} => col
fun eentryCol ee =
case ee of
EndTabHighlight {col, ...} => col
| EndMaxWidthHighlight {col} => col
fun sentryCmp (se1, se2) =
case (se1, se2) of
( StartTabHighlight {tab = tab1, col = col1}
, StartTabHighlight {tab = tab2, col = col2}
) =>
(case Int.compare (col1, col2) of
EQUAL => Tab.compare (tab1, tab2)
| other => other)
| (StartTabHighlight {col = col1, ...}, StartMaxWidthHighlight {col = col2}) =>
(case Int.compare (col1, col2) of
EQUAL => LESS
| other => other)
| (StartMaxWidthHighlight {col = col1}, StartTabHighlight {col = col2, ...}) =>
(case Int.compare (col1, col2) of
EQUAL => GREATER
| other => other)
| _ => Int.compare (sentryCol se1, sentryCol se2)
fun eentryCmp (ee1, ee2) =
case (ee1, ee2) of
( EndTabHighlight {tab = tab1, col = col1}
, EndTabHighlight {tab = tab2, col = col2}
) =>
(case Int.compare (col1, col2) of
EQUAL => Tab.compare (tab1, tab2)
| other => other)
| (EndTabHighlight {col = col1, ...}, EndMaxWidthHighlight {col = col2}) =>
(case Int.compare (col1, col2) of
EQUAL => LESS
| other => other)
| (EndMaxWidthHighlight {col = col1}, EndTabHighlight {col = col2, ...}) =>
(case Int.compare (col1, col2) of
EQUAL => GREATER
| other => other)
| _ => Int.compare (eentryCol ee1, eentryCol ee2)
fun matchingStartEndEntries (se, ee) =
case (se, ee) of
( StartTabHighlight {tab = st, col = sc}
, EndTabHighlight {tab = et, col = ec, ...}
) => Tab.eq (st, et) andalso sc = ec
| (StartMaxWidthHighlight {col = sc}, EndMaxWidthHighlight {col = ec}) =>
sc = ec
| _ => false
fun sentryEmphasizer se =
case se of
StartTabHighlight {tab, ...} => CustomString.emphasize (Tab.depth tab)
| StartMaxWidthHighlight {...} => CustomString.emphasize 10000000
fun sentrytos se =
case se of
StartTabHighlight {tab = st, col = scol} =>
"StartTabHighlight {tab = " ^ Tab.name st ^ ", col = "
^ Int.toString scol ^ "}"
| StartMaxWidthHighlight {col} =>
"StartMaxWidthHighlight {col = " ^ Int.toString col ^ "}"
fun eentrytos ee =
case ee of
EndTabHighlight {tab = et, col = ecol} =>
"EndTabHighlight {tab = " ^ Tab.name et ^ ", col = " ^ Int.toString ecol
^ "}"
| EndMaxWidthHighlight {col} =>
"EndMaxWidthHighlight {col = " ^ Int.toString col ^ "}"
fun sentryInfo se =
case se of
StartTabHighlight {tab, ...} =>
sentryEmphasizer se (CustomString.fromString ("^" ^ Tab.name tab))
| StartMaxWidthHighlight _ =>
sentryEmphasizer se (CustomString.fromString "^maxWidth")
(* ====================================================================== *)
(* ====================================================================== *)
(* ====================================================================== *)
structure Item =
struct
datatype item =
Spaces of int
| Newline
| Stuff of CustomString.t
| StartDebug of sentry
| EndDebug of eentry
type t = item
fun width item =
case item of
Spaces n => n
| Stuff s => CustomString.size s
| _ => raise Fail "PrettyTabbedDoc.Item.width"
fun toString item =
case item of
Spaces n => "Spaces(" ^ Int.toString n ^ ")"
| Stuff s =>
if width item <= 5 then
"Stuff('" ^ CustomString.toString s ^ "')"
else
"Stuff('" ^ String.substring (CustomString.toString s, 0, 5)
^ "...')"
| _ => "???"
fun split item i =
if i < 0 orelse i + 1 > width item then
raise Fail "PrettyTabbedDoc.Item.split: size"
else
(* i+1 <= width item *)
case item of
Spaces n =>
(Spaces i, CustomString.fromString " ", Spaces (n - i - 1))
| Stuff s =>
let
val n = CustomString.size s
val left = CustomString.substring (s, 0, i)
val mid = CustomString.substring (s, i, 1)
val right = CustomString.substring (s, i + 1, n - i - 1)
in
(Stuff left, mid, Stuff right)
end
| _ => raise Fail "PrettyTabbedDoc.Item.split: bad item"
end
type item = Item.t
(* ====================================================================== *)
(* ====================================================================== *)
(* ====================================================================== *)
fun implementDebugs maxWidth items =
let
fun highlightActive accCurrLine acc startDebugs =
let
val orderedHighlightCols =
(* Mergesort.sort sentryCmp (Seq.fromList startDebugs) *)
Seq.fromList
(ListMergeSort.sort (Util.gtOfCmp sentryCmp) startDebugs)
fun processItem (item, (currCol, hi, acc)) =
let
val () = ()
(* val _ = print ("processItem " ^ itos item ^ "\n") *)
val nextHighlightCol =
if hi < Seq.length orderedHighlightCols then
sentryCol (Seq.nth orderedHighlightCols hi)
else
valOf Int.maxInt
val n = Item.width item
in
if nextHighlightCol < currCol then
processItem (item, (currCol, hi + 1, acc))
else if currCol + n <= nextHighlightCol then
(currCol + n, hi, item :: acc)
else
let
val emphasizer = sentryEmphasizer
(Seq.nth orderedHighlightCols hi)
val (left, mid, right) =
Item.split item (nextHighlightCol - currCol)
(*
val _ =
print ("item: " ^ itos item
^ " split into (" ^ itos left ^ ", _, " ^ itos right ^ ")"
^ " nextHightlightCol: " ^ Int.toString nextHighlightCol
^ " currCol: " ^ Int.toString currCol
^ " itemWidth: " ^ Int.toString n
^ " hi: " ^ Int.toString hi
^ "\n")
*)
in
processItem
( right
, ( nextHighlightCol + 1
, hi + 1
, Item.Stuff (emphasizer mid) :: left :: acc
)
)
end
end
val (currCol, hi, acc) =
List.foldr processItem (0, 0, acc) accCurrLine
(* finish out the columns to highlight, if any remaining *)
val (_, acc) =
Util.loop (hi, Seq.length orderedHighlightCols) (currCol, acc)
(fn ((currCol, acc), hi) =>
let
val sentry = Seq.nth orderedHighlightCols hi
val nextHighlightCol = sentryCol sentry
val emphasizer = sentryEmphasizer sentry
in
if currCol > nextHighlightCol then
(currCol, acc)
else
(* currCol <= nextHighlightCol *)
( nextHighlightCol + 1
, Item.Stuff (emphasizer (spaces 1))
:: Item.Spaces (nextHighlightCol - currCol) :: acc
)
end)
in
acc
end
fun newlineWithEndDebugs endDebugs startDebugs acc =
if List.null endDebugs then
(startDebugs, acc)
else
let
val orderedStarts =
(* Mergesort.sort sentryCmp (Seq.fromList startDebugs) *)
Seq.fromList
(ListMergeSort.sort (Util.gtOfCmp sentryCmp) startDebugs)
val orderedEnds =
(* Mergesort.sort eentryCmp (Seq.fromList endDebugs) *)
Seq.fromList
(ListMergeSort.sort (Util.gtOfCmp eentryCmp) endDebugs)
val _ = print
("newLineWithEndDebugs:\n" ^ " starts: "
^ Seq.toString sentrytos orderedStarts ^ "\n" ^ " ends: "
^ Seq.toString eentrytos orderedEnds ^ "\n")
(* This is a bit cumbersome, but actually is fairly straightforward:
* for each `(info, col)` in `EE`, output `info` at column `col`.
*
* There's some trickiness though, because multiple `(info, col)`
* entries might overlap. For this, we check if each entry fits,
* and if not, we add the entry to `didntFit`, and then process
* `didntFit` on the next line, repeating until all entries have been
* output.
*
* Update: and now there's more trickiness, because we need to filter
* starts as we go to get decent output...
*)
fun loop (i, SS: sentry Seq.t) (j, EE: eentry Seq.t)
(didntFitEE: eentry list)
(removedSSCurrLine: sentry list, remainingSS: sentry list)
(currCol: int) (accCurrLine: item list) (acc: item list) =
if j >= Seq.length EE then
if List.null didntFitEE then
let
val remainingSS' = Seq.toList (Seq.drop SS i) @ remainingSS
in
( remainingSS'
, highlightActive accCurrLine acc
(removedSSCurrLine @ remainingSS')
)
end
else
loop
(0, Seq.append (Seq.fromRevList remainingSS, Seq.drop SS i))
(0, Seq.fromRevList didntFitEE) [] (* didntFitEE *)
([], []) (* (removedSSCurrLine, remainingSS) *)
0 (* currCol *) [] (* accCurrLine *)
(Item.Newline
::
highlightActive accCurrLine acc
(Seq.toList (Seq.drop SS i) @ remainingSS
@ removedSSCurrLine))
else
let
val sentry = Seq.nth SS i
val eentry = Seq.nth EE j
val scol = sentryCol sentry
val ecol = eentryCol eentry
val info = sentryInfo sentry
val _ =
(* check invariant *)
if scol <= ecol then
()
else
( print
("sentry " ^ sentrytos sentry ^ "\n" ^ "eentry "
^ eentrytos eentry ^ "\n" ^ "i " ^ Int.toString i
^ "\n" ^ "j " ^ Int.toString j ^ "\n" ^ "SS "
^ Seq.toString sentrytos SS ^ "\n" ^ "EE "
^ Seq.toString eentrytos EE ^ "\n")
; raise Fail
"newlineWithEndDebugs.loop: invariant violated"
)
in
if
scol < ecol
orelse not (matchingStartEndEntries (sentry, eentry))
then
loop (i + 1, SS) (j, EE) didntFitEE
(removedSSCurrLine, sentry :: remainingSS) currCol
accCurrLine acc
else if
ecol < currCol
then
loop (i + 1, SS) (j + 1, EE) (eentry :: didntFitEE)
(removedSSCurrLine, sentry :: remainingSS) currCol
accCurrLine acc
else
let
val numSpaces = ecol - currCol
val newCol = currCol + numSpaces + CustomString.size info
in
loop (i + 1, SS) (j + 1, EE) didntFitEE
(sentry :: removedSSCurrLine, remainingSS) newCol
(Item.Stuff info :: Item.Spaces numSpaces :: accCurrLine)
acc
end
end
val (remainingSS, acc) =
loop (0, orderedStarts) (0, orderedEnds) [] ([], []) 0 []
(Item.Newline :: acc)
val acc = highlightActive [] (Item.Newline :: acc) remainingSS
in
(remainingSS, acc)
end
fun processItem (item, (accCurrLine, acc, endDebugs, startDebugs)) =
case item of
Item.EndDebug entry =>
(accCurrLine, acc, entry :: endDebugs, startDebugs)
| Item.StartDebug entry =>
(accCurrLine, acc, endDebugs, entry :: startDebugs)
| Item.Newline =>
let
val (remainingSS, acc) =
newlineWithEndDebugs endDebugs startDebugs
(highlightActive accCurrLine acc startDebugs)
in
([], Item.Newline :: acc, [], remainingSS)
end
| _ => (item :: accCurrLine, acc, endDebugs, startDebugs)
val init = ([], [], [], [])
val init = processItem
(Item.StartDebug (StartMaxWidthHighlight {col = maxWidth}), init)
val (accCurrLine, acc, endDebugs, startDebugs) =
List.foldr processItem init
(Item.EndDebug (EndMaxWidthHighlight {col = maxWidth}) :: items)
in
if List.null endDebugs then
accCurrLine @ acc
else
#2 (newlineWithEndDebugs endDebugs startDebugs
(highlightActive accCurrLine acc startDebugs))
end
(* ====================================================================== *)
(* ====================================================================== *)
(* ====================================================================== *)
fun revAndStripTrailingWhitespace (items: item list) =
let
fun loopStrip acc items =
case items of
[] => acc
| Item.Spaces _ :: items' => loopStrip acc items'
| _ => loopKeep acc items
and loopKeep acc items =
case items of
[] => acc
| Item.Newline :: items' => loopStrip (Item.Newline :: acc) items'
| x :: items' => loopKeep (x :: acc) items'
in
loopStrip [] items
end
exception DoPromote of tab
fun addNewlines n d =
if n = 0 then d else addNewlines (n - 1) (Concat (Newline, d))
fun concatDocs ds =
Seq.iterate concat empty ds
fun tokenToDoc {tabWidth} currentTab tok =
case tokenToPieces {tabWidth = tabWidth} tok of
OnePiece s => Text s
| ManyPieces pieces =>
let
val numPieces = Seq.length pieces
val tab = Tab.new
{ parent = currentTab
, style = Tab.Style.combine (Tab.Style.inplace, Tab.Style.rigid)
}
val doc =
(* a bit of a hack here: we concatenate a space on the end of
* each piece (except last), which guarantees that blank lines
* within the comment are preserved.
*)
Seq.iterate concat empty
(Seq.map (fn x => at tab (concat (Text x, space)))
(Seq.take pieces (numPieces - 1)))
val doc = concat (doc, at tab (Text (Seq.nth pieces (numPieces - 1))))
val doc = NewTab {tab = tab, gen = Promise.new (fn () => doc)}
in
doc
end
fun tokenToDocWithBlankLines {tabWidth} currentTab tok =
let
val doc = tokenToDoc {tabWidth = tabWidth} currentTab tok
val numBlanks = Token.desiredBlankLinesBefore tok
in
addNewlines numBlanks doc
end
fun pretty {ribbonFrac, maxWidth, indentWidth, tabWidth, debug} doc =
let
val t0 = Time.now ()
fun dbgprintln s =
if not debug then () else print (s ^ "\n")
val ribbonWidth = Int.max (0, Int.min (maxWidth, Real.round
(ribbonFrac * Real.fromInt maxWidth)))
val newline = CustomString.fromString "\n"
datatype activation_state = Flattened | Activated of int option
datatype state = Usable of activation_state | Completed
val tabstate = ref TabDict.empty
fun getTabState t =
TabDict.lookup (!tabstate) t
fun setTabState t x =
tabstate := TabDict.insert (!tabstate) (t, x)
val _ = setTabState Tab.root (Usable (Activated (SOME 0)))
fun isActivated t =
case getTabState t of
Usable (Activated _) => true
| Usable Flattened => false
| _ => raise Fail "PrettyTabbedDoc.pretty.isActivated: bad tab"
(* tab -> hit first break? *)
type debug_state = bool TabDict.t
(* debug state, current tab, current 'at's, delayed comments, line start, current col, lastItemIsSpacey, accumulator *)
datatype layout_state =
LS of
debug_state
* tab
* TabSet.t
* Token.t Seq.t
* int
* int
* bool
* (item list)
fun dbgInsert tab
(LS (dbgState, ct, cats, coms, s, c, sp, a) : layout_state) :
layout_state =
if not debug then
LS (dbgState, ct, cats, coms, s, c, sp, a)
else
LS (TabDict.insert dbgState (tab, false), ct, cats, coms, s, c, sp, a)
fun dbgBreak tab
(LS (dbgState, ct, cats, coms, s, c, sp, a) : layout_state) :
layout_state =
if not debug then
LS (dbgState, ct, cats, coms, s, c, sp, a)
else if TabDict.lookup dbgState tab then
LS (dbgState, ct, cats, coms, s, c, sp, a)
else
LS
( TabDict.insert dbgState (tab, true)
, ct
, cats
, coms
, s
, c
, sp
, Item.StartDebug (StartTabHighlight {tab = tab, col = c}) :: a
)
fun isPromotable' t =
case getTabState t of
Usable Flattened => true
| Usable (Activated NONE) => true
| Usable (Activated (SOME ti)) =>
(case Tab.parent t of
NONE => false
| SOME p =>
case getTabState p of
Usable (Activated (SOME pi)) =>
ti > pi + Int.max (indentWidth, Tab.minIndent t)
| _ =>
raise Fail
"PrettyTabbedDoc.pretty.isPromotable: bad parent tab")
| _ => raise Fail "PrettyTabbedDoc.pretty.isPromotable: bad tab"
fun isPromotable t =
let
val result = isPromotable' t
in
(* if not debug then () else
print ("PrettyTabbedDoc.debug: isPromotable " ^ Tab.infoString t ^ " = " ^ (if result then "true" else "false") ^ "\n"); *)
result
end
fun oldestPromotableParent t =
if not (isPromotable t) then
NONE
else
case Tab.parent t of
SOME p =>
if not (isPromotable p) then SOME t else oldestPromotableParent p
| NONE => SOME t
fun oldestInactiveParent t =
if isActivated t then
NONE
else
case Tab.parent t of
SOME p => if isActivated p then SOME t else oldestInactiveParent p
| NONE => SOME t
(* Below, the `check` function is used to check for layout violations.
* If any layout constraints are violated, it tries to promote a tab.
*
* The promotion strategy implemented here is simple: we always promote
* the outermost promotable tab. This strategy prefers full promotion of
* a tab before activating any of its children, which generally looks
* pretty good.
*
* However, there is room for improvement.
*
* Consider this document with tabs labeled 0..3:
*
* Functor (struct val x = 5 val y = 42 end)
* | || | | |
* 0 1| 3 3 2
* 2
*
* Then under the current strategy, we could have the output
* on the left, but not on the right:
*
* possible layout | impossible layout
* --------------------+-------------------------
* Functor | Functor (struct
* (struct | val x = 5
* val x = 5 | val y = 42
* val y = 42 | end)
* end) |
*
* The left layout is generated by the promotions [0,0,1,1,2,2,3,3].
* (Notice in this sequence, each tab is repeated twice: the first
* promotion activates the tab, and the second promotion relocates
* the tab by placing it on a new line and indenting)
*
* If we instead had an alternative promotion strategy which allowed
* for fully promoting a child before its parent, then it would be
* possible to see the layout on the right. The promotion sequence
* would need to be [0,0,1,2,3,3].
*
* UPDATE: tab styles (newly added) allow for some control over this.
*)
fun check (state as LS (_, ct, _, _, lnStart, col, _, _)) =
let
val widthOkay = col <= maxWidth
val ribbonOkay = (col - lnStart) <= ribbonWidth
val okay = widthOkay andalso ribbonOkay
(* val _ =
if not debug orelse okay then ()
else if not widthOkay then
print ("PrettyTabbedDoc.debug: width violated: ct=" ^ Tab.infoString ct ^ " lnStart=" ^ Int.toString lnStart ^ " col=" ^ Int.toString col ^ "\n")
else if not ribbonOkay then
print ("PrettyTabbedDoc.debug: ribbon violated: ct=" ^ Tab.infoString ct ^ " lnStart=" ^ Int.toString lnStart ^ " col=" ^ Int.toString col ^ "\n")
else
print ("PrettyTabbedDoc.debug: unknown violation?? ct=" ^ Tab.infoString ct ^ " lnStart=" ^ Int.toString lnStart ^ " col=" ^ Int.toString col ^ "\n") *)
in
if okay then
state
else
case oldestPromotableParent ct of
(* TODO: FIXME: there's a bug here. Even if the current tab (ct)
* doesn't have a promotable parent, there might be another
* promotable tab on the same line.
*
* For example: tabs s and t occupy the same line; tab s is
* fully promoted; tab t is inactive because it fits within the
* max width. After completing tab t, we return to tab s, and then
* get a width violation. However, tab s (the current tab) has
* no promotable parent.
*
* sssssssssstttttttttsss|s
* ^ ^ ^
* tab s: tab t: max width
* fully inactive
* promoted
*
* The fix in the above example is to promote tab t. So, perhaps
* we need to keep track of a set of promotable tabs on the
* current line and then choose one to promote (?)
*)
SOME p => raise DoPromote p
| NONE => state
end
fun parentTabCol tab =
case Tab.parent tab of
NONE => raise Fail "PrettyTabbedDoc.pretty.parentTabCol: no parent"
| SOME p =>
case getTabState p of
Usable (Activated (SOME i)) => i
| _ => raise Fail "PrettyTabbedDoc.pretty.parentTabCol: bad tab"
fun ensureAt tab state =
let
val LS (dbgState, _, cats, coms, lnStart, col, sp, acc) = state
val alreadyAtTab = TabSet.contains cats tab
fun goto i =
if alreadyAtTab then
dbgBreak tab (LS (dbgState, tab, cats, coms, lnStart, i, sp, acc))
else if Tab.isInplace tab andalso col <= i then
dbgBreak tab (check (LS
( dbgState
, tab
, if i = col then TabSet.insert cats tab
else TabSet.singleton tab
, coms
, lnStart
, i
, i <> col orelse sp
, if i = col then acc else Item.Spaces (i - col) :: acc
)))
(* else if i = col andalso Tab.isInplace tab then
dbgBreak tab (LS
(dbgState, tab, TabSet.insert cats tab, lnStart, i, sp, acc)) *)
else if i < col then
dbgBreak tab (check (LS
( dbgState
, tab
, TabSet.singleton tab
, coms
, i
, i
, true
, Item.Spaces i :: Item.Newline :: acc
)))
else if isPromotable tab then
(* force this tab to promote if possible, which should move
* it onto a new line and indent. *)
raise DoPromote tab
else if lnStart < i then
(* SAM_NOTE: TODO: This case might be unnecessary... we can use
* tab styles (inplace vs indented) to resolve this issue. Inplace
* can be allowed to advance, and indented require a fresh line.
* This would simplify the logic above, too; the case where
* i = col andalso Tab.isInplace tab
* would just be a special case of advancing on the current line.
*)
(* This avoids advancing the current line to meet the tab,
* if possible, which IMO results in strange layouts. *)
dbgBreak tab (check (LS
( dbgState
, tab
, if i = col then TabSet.insert cats tab
else TabSet.singleton tab
, coms
, i
, i
, true
, Item.Spaces i :: Item.Newline :: acc
)))
else
(* Fall back on advancing the current line to meet the tab,
* which is a little strange, but better than nothing. *)
dbgBreak tab (check (LS
( dbgState
, tab
, if i = col then TabSet.insert cats tab
else TabSet.singleton tab
, coms
, lnStart
, i
, i <> col orelse sp
, Item.Spaces (i - col) :: acc
)))
val state' =
case getTabState tab of
Usable Flattened =>
if Tab.isRigid tab then
raise DoPromote (valOf (oldestPromotableParent tab))
else
LS (dbgState, tab, cats, coms, lnStart, col, sp, acc)
| Usable (Activated (SOME i)) => goto i
| Usable (Activated NONE) =>
if Tab.isInplace tab then
if col < parentTabCol tab then
( setTabState tab (Usable (Activated
(SOME (parentTabCol tab))))
; goto (parentTabCol tab)
)
else
let
(* never let a tab begin at a place that needs a space *)
val desired = if sp then col else col + 1
in
( setTabState tab (Usable (Activated (SOME desired)))
; goto desired
)
end
else
let
val i =
parentTabCol tab
+
Int.min
( Int.max (indentWidth, Tab.minIndent tab)