-
Notifications
You must be signed in to change notification settings - Fork 67
Expand file tree
/
Copy pathprinter.sk
More file actions
1946 lines (1861 loc) · 55.8 KB
/
Copy pathprinter.sk
File metadata and controls
1946 lines (1861 loc) · 55.8 KB
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) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
module SkipPrinter;
type ParseTree = ParseTree.ParseTree;
class Context{
contents: String,
alreadyPrintedLeadingComments: UnorderedSet<HashableToken> = UnorderedSet[],
parents: List<ParseTree> = List[],
loopElseBranch: Bool = false,
} {
fun isAlreadyPrintedLeadingComments(token: Token.Token): Bool {
this.alreadyPrintedLeadingComments.contains(HashableToken(token))
}
fun withAlreadyPrintedLeadingComments(token: Token.Token): Context {
this with {
alreadyPrintedLeadingComments => {
newSet = this.alreadyPrintedLeadingComments.clone();
newSet.add(HashableToken(token));
freeze(newSet)
},
}
}
fun getParent(n: Int): ParseTree {
try {
this.parents.getNth(n)
} catch {
| _ -> ParseTree.EmptyTree{range => TextRange.none}
}
}
}
// Workaround to be able to hash the token based on the range only
value class HashableToken(token: Token.Token) uses Hashable, Equality {
fun hash(): Int {
this.token.range.hash()
}
fun ==(other: HashableToken): Bool {
this.token.range == other.token.range
}
}
fun printJustComments(ctx: Context, t: ParseTree): Doc {
t match {
| ParseTree.TokenTree{token} ->
Doc.Concat[
if (!ctx.isAlreadyPrintedLeadingComments(token)) {
printLeadingComments(t, token.leadingComments)
} else {
Doc.Empty()
},
printTrailingComments(t, token.trailingComments),
]
| _ ->
invariant_violation("Should not call printJustComments without a TokenTree")
}
}
fun printTreeToString(
parseTree: ParseTree.ParseTree,
contents: String = "",
): String {
ctx = SkipPrinter.Context{contents};
doc = SkipPrinter.print(ctx, parseTree);
// debug(Doc.simplifyDoc(doc));
result = mutable Vector[];
Doc.printDoc(doc, x -> result.push(x));
result.join("")
}
fun printTreeList(
c: Context,
t: ParseTree,
beforeSeparator: Doc,
afterSeparator: Doc,
indent: Bool = false,
trailingSeparator: Bool = false,
shouldGroup: Bool = true,
marker: ?Doc.Marker = None(),
): Doc {
line = if (
beforeSeparator is Doc.HardLine() ||
afterSeparator is Doc.HardLine()
) {
Doc.HardLine()
} else {
Doc.SoftLine()
};
printTreeWithComments(c, t, (ctx, treeList) -> {
treeList match {
| ParseTree.ParseTreeList{
startDelimiter,
elements,
separators,
endDelimiter,
separatorKind,
} ->
if (elements.size() == 0) {
Doc.Concat[print(ctx, startDelimiter), print(ctx, endDelimiter)]
} else {
printedElements = mutable Vector<Doc>[];
// Avoid O(n^2) behavior because of random access
elementsVec = elements;
separatorsVec = separators;
elementsVec.eachWithIndex((i, element) -> {
printedElements.push(
Doc.Concat[
if (
i > 0 &&
element.getRangeWithComments().start.line() >
1 +
(if (separatorsVec.size() >= i) {
separatorsVec[i - 1]
} else {
elementsVec[i - 1]
})
.getRangeWithComments()
.end.line()
) {
line
} else {
Doc.Empty()
},
print(ctx, element),
if (i == elementsVec.size() - 1) {
if (trailingSeparator) {
if (separatorsVec.size() == elementsVec.size()) {
Doc.IfBreak(
print(ctx, separatorsVec[i]),
printJustComments(ctx, separatorsVec[i]),
)
} else {
Doc.IfBreak(Doc.Str(separatorKind.fromSome().toString()))
}
} else {
if (separatorsVec.size() == elementsVec.size()) {
printJustComments(ctx, separatorsVec[i])
} else {
Doc.Empty()
}
}
} else {
Doc.Concat[
beforeSeparator,
if (separatorsVec.size() == 0) {
Doc.Empty()
} else {
print(ctx, separatorsVec[i])
},
afterSeparator,
]
},
],
)
});
if (indent) {
// We want to print the last comment of a block as trailing of the
// last element rather than leading of the end delimiter
(
printedEndDelimiterComments,
printedEndDelimiter,
) = endDelimiter.getFirstToken() match {
| Some(firstToken) ->
(
Doc.Concat[
printTrailingComments(
elements.last(),
firstToken.leadingComments,
),
firstToken.leadingComments.maybeLast() match {
| Some(Token.Comment{kind => Token.LineComment()}) ->
Doc.IfBreak(Doc.Empty(), Doc.HardLine())
| _ -> Doc.Empty()
},
],
print(
ctx.withAlreadyPrintedLeadingComments(firstToken),
endDelimiter,
),
)
| None() -> (Doc.Empty(), Doc.Empty())
};
contents = Doc.Concat[
print(ctx, startDelimiter),
Doc.Indent[
line,
Doc.Concat(freeze(printedElements)),
printedEndDelimiterComments,
],
line,
];
Doc.Concat[
if (shouldGroup) {
Doc.Group(contents, /* break */ false, marker)
} else {
contents
},
printedEndDelimiter,
]
} else {
Doc.Concat[
print(ctx, startDelimiter),
Doc.Concat(freeze(printedElements)),
print(ctx, endDelimiter),
]
}
}
| ParseTree.EmptyTree{} -> Doc.Empty()
| _ ->
invariant_violation(
"Expecting a ParseTreeList but got " + treeList.toDebugString(),
)
}
})
}
fun printCommaList(
ctx: Context,
treeList: ParseTree,
shouldGroup: Bool = true,
marker: ?Doc.Marker = None(),
): Doc {
printTreeList(
ctx,
treeList,
Doc.Empty(), // beforeSeparator
Doc.Line(), // afterSeparator
true, // indent
true, // trailingSeparator
shouldGroup, // shouldGroup
marker, // marker
)
}
fun printHardlineList(
ctx: Context,
treeList: ParseTree,
trailingSeparator: Bool = false,
): Doc {
printTreeList(
ctx,
treeList,
Doc.Empty(), // beforeSeparator
Doc.HardLine(), // afterSeparator
false, // indent
trailingSeparator,
)
}
fun printBarList(
c: Context,
bar: ?ParseTree,
t: ParseTree,
line: Doc,
shouldFill: Bool = false,
): Doc {
printTreeWithComments(c, t, (ctx, treeList) -> {
treeList match {
| ParseTree.ParseTreeList{elements, separators, separatorKind} ->
if (elements.size() == 0) {
Doc.Empty()
} else {
printedElements = mutable Vector<Doc>[];
// Avoid O(n^2) behavior because of random access
elementsVec = elements;
separatorsVec = separators;
elementsVec.eachWithIndex((i, element) -> {
printedElements.push(print(ctx, element));
printedElements.push(
Doc.Concat[
if (i != elementsVec.size() - 1) {
Doc.Concat[
if (
separatorsVec[i].getRangeWithComments().start.line() >
element.getRangeWithComments().end.line() + 1
) {
line
} else {
Doc.Empty()
},
line,
print(ctx, separatorsVec[i]),
Doc.space,
]
} else {
Doc.Empty()
},
],
)
});
Doc.Concat[
if (bar.isSome()) {
Doc.Concat[
printFallback(
ctx,
bar.fromSome(),
Doc.Str(separatorKind.fromSome().toString()),
),
Doc.space,
]
} else {
Doc.Empty()
},
if (shouldFill) {
Doc.Fill(freeze(printedElements))
} else {
Doc.Concat(freeze(printedElements))
},
]
}
| _ ->
invariant_violation(
"Expecting a ParseTreeList but got " + treeList.toDebugString(),
)
}
})
}
fun join(ctx: Context, separator: Doc, elems: Array<ParseTree>): Doc {
res = mutable Vector<Doc>[];
elems.eachWithIndex((i, elem) -> {
res.push(print(ctx, elem));
if (i != elems.size() - 1) {
res.push(separator)
}
});
Doc.Concat(freeze(res))
}
fun printModifiers(ctx: Context, t: ParseTree): Doc {
elements = t.asList().elements;
if (elements.isEmpty()) {
Doc.Empty()
} else {
Doc.Concat(
elements
.map(element -> {
Doc.Concat[
print(ctx, element),
if (element is ParseTree.AnnotationTree _) {
Doc.HardLine()
} else {
Doc.space
},
]
})
.collect(Vector),
)
}
}
fun printFallback(ctx: Context, t: ParseTree, fallback: Doc): Doc {
t match {
| ParseTree.EmptyTree _ -> fallback
| _ -> print(ctx, t)
}
}
fun printComment(comment: Token.Comment): Doc {
res = mutable Vector<Doc>[];
lines = comment.value.split("\n");
isAllStar =
comment.value.startsWith("/*") &&
lines.slice(1).all(line ~> line.matches(Regex::create("^[ \t]*\\*")));
lines.eachWithIndex((i, line) -> {
// Each line will be printed at the current level of indentation. Since the
// comment uses raw spaces for indentation, we need to subtract as many
// spaces as the current level of indentation to be a no-op.
dedentedLine = if (i > 0) {
// This removes the first `comment.range.start.column()` spaces:
pos = line.getIter();
index = 0;
for (_ in Range(0, comment.range.start.column())) {
pos.current() match {
| Some(' ') ->
_ = pos.next();
!index = index + 1
| _ ->
// This is the case where a non-first line in a multi-line comment is
// indented less than the first line.
break void
}
};
// For /** comments, if a line starts with *, we want to indent it
// at the start of the star with one more space
if (isAllStar) {
starIndex = index;
loop {
pos.current() match {
| Some(' ')
| Some('\t') ->
_ = pos.next();
!starIndex = starIndex + 1
| Some('*') ->
break " " + line.getIter().forward(starIndex).collectString()
| _ -> break line.getIter().forward(index).collectString()
}
}
} else {
line.getIter().forward(index).collectString()
}
} else {
line
};
res.push(Doc.Str(dedentedLine));
if (i != lines.size() - 1) {
res.push(Doc.HardLine())
}
});
Doc.Concat(freeze(res))
}
fun printLeadingComments(tree: ParseTree, comments: Array<Token.Comment>): Doc {
if (comments.size() > 0) {
Doc.Concat[
Doc.LineSuffixBoundary(),
Doc.Concat(
comments
.mapWithIndex((i, comment) -> {
nextRange = if (i == comments.size() - 1) {
tree.range
} else {
comments[i + 1].range
};
currentRange = comment.range;
Doc.Concat[
printComment(comment),
if (
i == comments.size() - 1 &&
tree.matchTreeKind(TokenKind.END_OF_FILE())
) {
Doc.Empty()
} else {
Doc.Concat[
if (
nextRange.start.line() > currentRange.end.line() ||
// Even if the ranges are wrong (which can happen with
// codemods), we always want to add a trailing newline for
// "// comments"
comment.kind is Token.LineComment()
) {
Doc.HardLine()
} else {
Doc.space
},
if (nextRange.start.line() > currentRange.end.line() + 1) {
Doc.HardLine()
} else {
Doc.Empty()
},
]
},
]
})
.collect(Vector),
),
]
} else {
Doc.Empty()
}
}
fun printTrailingComments(
tree: ParseTree,
comments: Array<Token.Comment>,
): Doc {
if (comments.size() > 0) {
Doc.Concat(
comments
.mapWithIndex((i, comment) -> {
previousRange = if (i == 0) {
tree.range
} else {
comments[i - 1].range
};
currentRange = comment.range;
printedComment = printComment(comment);
if (previousRange.end.line() != currentRange.start.line()) {
Doc.Concat[Doc.HardLine(), printedComment]
} else {
res = Doc.Concat[Doc.space, printedComment];
if (comment.kind is Token.LineComment _) {
Doc.LineSuffix(res)
} else {
res
}
}
})
.collect(Vector),
)
} else {
Doc.Empty()
}
}
fun printTreeWithComments(
ctx: Context,
t: ParseTree,
cb: (Context, ParseTree) -> Doc,
): Doc {
leadingComments = if (t is ParseTree.PatternBranchListTree _) {
Array[]
} else {
// This is going to be O(n^2), where n is the depth of the tree. It should be
// fine but a bit unfortunate.
t.getFirstToken() match {
| Some(
firstToken,
) if (
!ctx.isAlreadyPrintedLeadingComments(firstToken) &&
firstToken.leadingComments.size() > 0
) ->
!ctx = ctx.withAlreadyPrintedLeadingComments(firstToken);
firstToken.leadingComments
| _ -> Array[]
}
};
if (
leadingComments.any(comment -> comment.value.contains("printer-ignore"))
) {
Doc.Str(
TextRange.contentFromLines(
t.getRangeWithComments(),
ctx.contents.split("\n"),
),
)
} else {
!ctx = ctx with {parents => List.Cons(t, ctx.parents)};
content = cb(ctx, t);
Doc.Concat[printLeadingComments(t, leadingComments), content]
}
}
// For binary expressions to be consistent, we need to group
// subsequent operators with the same precedence level under a single
// group. Otherwise they will be nested such that some of them break
// onto new lines but not all. Operators with the same precedence
// level should either all break or not. Because we group them by
// precedence level and the AST is structured based on precedence
// level, things are naturally broken up correctly, i.e. `&&` is
// broken before `+`.
fun printBinaryExpression(
ctx: Context,
t: ParseTree,
shouldExpand: Bool,
): mutable Vector<Doc> {
parts = mutable Vector[];
t match {
| ParseTree.BinaryExpressionTree{left, operator, right} ->
// Put all operators with the same precedence level in the same
// group. The reason we only need to do this with the `left`
// expression is because given an expression like `1 + 2 - 3`, it
// is always parsed like `((1 + 2) - 3)`, meaning the `left` side
// is where the rest of the expression will exist. Binary
// expressions on the right side mean they have a difference
// precedence level and should be treated as a separate group, so
// print them normally.
left match {
| ParseTree.BinaryExpressionTree{
operator => leftOperator,
} if (
operator.getTokenKind().precedence() ==
leftOperator.getTokenKind().precedence()
) ->
// Flatten them out by recursively calling this function.
for (part in printBinaryExpression(
ctx with {parents => List.Cons(t, ctx.parents)},
left,
shouldExpand,
)) parts.push(part)
| _ -> parts.push(print(ctx, left))
};
isLogicalExpression =
operator.matchTreeKind(TokenKind.AMPERSAND_AMPERSAND()) ||
operator.matchTreeKind(TokenKind.BAR_BAR());
nodeKind = t.getKind();
shouldGroup =
!(shouldExpand && isLogicalExpression) &&
ctx.getParent(1).getKind() != nodeKind &&
left.getKind() != nodeKind &&
right.getKind() != nodeKind;
printedRight = Doc.Concat[
print(ctx, operator),
Doc.Line(),
print(ctx, right),
];
parts.push(Doc.space);
if (shouldGroup) {
parts.push(Doc.Group(printedRight))
} else {
parts.push(printedRight)
}
| _ ->
// Our stopping case. Simply print the node normally.
parts.push(print(ctx, t))
};
parts
}
fun isMemberish(t: ParseTree): Bool {
t is ParseTree.MemberSelectionExpressionTree _ ||
t is ParseTree.CallArrayExpressionTree _
}
fun isCallArrayInteger(t: ParseTree): Bool {
t match {
| ParseTree.CallArrayExpressionTree{
arguments => ParseTree.ParseTreeList{elements},
} if (
elements.size() == 1 &&
elements[0] is ParseTree.TokenTree{
token => Token.Token{kind => TokenKind.INTEGER_LITERAL()},
}
) ->
true
| _ -> false
}
}
fun printMemberNode(ctx: Context, t: ParseTree): Doc {
// Note(vjeux): should ctx be fixed to preserve parents?
t match {
| ParseTree.MemberSelectionExpressionTree{operator, member} ->
Doc.Concat[print(ctx, operator), print(ctx, member)]
| ParseTree.CallExpressionTree{typeArguments, arguments} ->
Doc.Concat[printCommaList(ctx, typeArguments), print(ctx, arguments)]
| ParseTree.CallArrayExpressionTree{typeArguments, bang, arguments} ->
Doc.Concat[
print(ctx, typeArguments),
print(ctx, bang),
printCommaList(ctx, arguments),
]
| _ -> print(ctx, t)
}
}
fun isFactory(t: ParseTree): Bool {
t is ParseTree.GenericTypeNameTree{
name => ParseTree.TokenTree{
token => Token.Token{kind => TokenKind.TYPE_IDENTIFIER()},
},
} ||
t is ParseTree.TokenTree{token => Token.Token{kind => TokenKind.THIS()}} ||
t is ParseTree.TokenTree{token => Token.Token{kind => TokenKind.STATIC()}}
}
fun printMemberChain(ctx: Context, t: ParseTree): Doc {
// The first phase is to linearize the AST by traversing it down.
//
// a().b()
// has the following AST structure:
// CallExpression(MemberSelectionExpression(CallExpression(Token)))
// and we transform it into
// [Token, CallExpression, MemberSelectionExpression, CallExpression]
nodes = mutable Vector[];
elem = t;
while ({
nodes.push(elem);
elem match {
| ParseTree.MemberSelectionExpressionTree{object => next}
| ParseTree.CallExpressionTree{func => next}
| ParseTree.CallArrayExpressionTree{func => next} ->
!elem = next;
true
| _ -> false
}
}) void;
nodes.reverse();
// Once we have a linear list of nodes, we want to create groups out
// of it.
//
// a().b.c().d().e
// will be grouped as
// [
// [Identifier, CallExpression],
// [MemberSelectionExpressionTree, MemberSelectionExpressionTree, CallExpression],
// [MemberSelectionExpressionTree, CallExpression],
// [MemberSelectionExpressionTree],
// ]
// so that we can print it as
// a()
// .b.c()
// .d()
// .e
// The first group is the first node followed by
// - as many CallExpression as possible
// < fn()()() >.something()
// - as many numeric CallArrayExpressionTree as possible
// < fn()[0][1][2] >.something()
groups = mutable Vector[];
currentGroup = mutable Vector[nodes[0]];
i = 1;
while ({
if (i >= nodes.size()) {
false
} else if (
nodes[i] is ParseTree.CallExpressionTree _ ||
isCallArrayInteger(nodes[i])
) {
currentGroup.push(nodes[i]);
!i = i + 1;
true
} else {
false
}
}) void;
// - then, as many MemberSelectionExpressionTree as possible but the last one
// < this.items >.something()
if (!(nodes[0] is ParseTree.CallExpressionTree _)) {
while ({
if (i + 1 >= nodes.size()) {
false
} else if (isMemberish(nodes[i]) && isMemberish(nodes[i + 1])) {
currentGroup.push(nodes[i]);
!i = i + 1;
true
} else {
false
}
}) void;
};
groups.push(currentGroup);
!currentGroup = mutable Vector[];
// Then, each following group is a sequence of MemberSelectionExpression followed by
// a sequence of CallExpression. To compute it, we keep adding things to the
// group until we has seen a CallExpression in the past and reach a
// MemberExpression
hasSeenCallExpression = false;
while ({
if (i >= nodes.size()) {
false
} else if (hasSeenCallExpression && isCallArrayInteger(nodes[i])) {
// [0] should be appended at the end of the group instead of the
// beginning of the next one
currentGroup.push(nodes[i]);
!i = i + 1;
true
} else {
if (hasSeenCallExpression && isMemberish(nodes[i])) {
groups.push(currentGroup);
!currentGroup = mutable Vector[];
!hasSeenCallExpression = false
};
if (nodes[i] is ParseTree.CallExpressionTree _) {
!hasSeenCallExpression = true
};
currentGroup.push(nodes[i]);
!i = i + 1;
true
}
}) void;
if (currentGroup.size() > 0) {
groups.push(currentGroup)
};
printedGroups = groups.map(group -> {
Doc.Concat(group.map(node -> printMemberNode(ctx, node)))
});
// In case that we have Uppercase.call() or this.call() we don't want to put
// a newline before the `.`
shouldMerge = isFactory(nodes[0]);
// If we only have a single `.`, we shouldn't do anything fancy and just
// render everything concatenated together.
if (groups.size() <= if (shouldMerge) 3 else 2) {
Doc.Group(Doc.Concat(printedGroups))
} else {
// If there's a lambda anywhere in the chain we don't want to inline
noLambda = nodes.slice(0, -1).all(node ->
node match {
| ParseTree.CallExpressionTree{
arguments => ParseTree.PositionalArgumentsTree{
arguments => ParseTree.ParseTreeList{elements},
},
} if (
elements.any(element -> element is ParseTree.LambdaExpressionTree _)
) ->
false
| _ -> true
}
);
marker = if (noLambda) {
nodes.last() match {
| ParseTree.CallExpressionTree{
arguments => tree @ ParseTree.PositionalArgumentsTree{arguments},
} if (lastLambdaShouldInline(arguments)) ->
Some(Doc.Marker(tree.range))
| _ -> None()
}
} else {
None()
};
Doc.Group(
Doc.Concat[
printedGroups[0],
if (shouldMerge) printedGroups[1] else Doc.Empty(),
Doc.Indent[
Doc.Concat(
printedGroups
.slice(if (shouldMerge) 2 else 1, printedGroups.size())
.map(printedGroup -> Doc.Concat[Doc.SoftLine(), printedGroup]),
),
],
],
/* break */ false,
marker,
)
}
}
fun shouldExpandBinary(ctx: Context, n: Int = 0): Bool {
ctx.getParent(n + 1) is ParseTree.IfExpressionTree _ ||
ctx.getParent(n + 1) is ParseTree.WhileLoopExpressionTree _ ||
ctx.getParent(n + 1) is ParseTree.InfiniteLoopExpressionTree _ ||
ctx.getParent(n + 1) is ParseTree.IfClauseTree _ ||
ctx.getParent(n + 1) is ParseTree.SimpleBindingExpressionTree _ ||
(ctx.getParent(n + 1) is ParseTree.UnaryExpressionTree _ &&
ctx.getParent(n + 2) is ParseTree.SimpleBindingExpressionTree _)
}
fun lastLambdaShouldInline(t: ParseTree): Bool {
args = t.asList().elements;
!args.isEmpty() &&
(args.last() is ParseTree.LambdaExpressionTree _) &&
args.filter(x -> x is ParseTree.LambdaExpressionTree _).size() == 1
}
fun printBody(ctx: Context, body: ParseTree, isOnlyBranch: Bool): Doc {
body match {
| ParseTree.BlockTree _ ->
Doc.Concat[
Doc.space,
print(ctx, body),
if (isOnlyBranch) Doc.Empty() else Doc.space,
]
| _ ->
Doc.Group[
Doc.IfBreak(Doc.Concat[Doc.space, Doc.Str("{")]),
Doc.Indent[Doc.Line(), print(ctx, body)],
if (isOnlyBranch) Doc.SoftLine() else Doc.Line(),
Doc.IfBreak(
Doc.Concat[Doc.Str("}"), if (!isOnlyBranch) Doc.space else Doc.Empty()],
),
]
}
}
fun print(ctx: Context, t: ParseTree): Doc {
printTreeWithComments(ctx, t, printTree)
}
fun printTree(ctx: Context, t: ParseTree): Doc {
t match {
| ParseTree.LazyTree _ ->
invariant_violation("ICE: the printer should not be using lazy parsing")
| ParseTree.SourceUnitTree{begin, moduleAliases, declarations, end} ->
// debug(t);
moduleAliasesRange = moduleAliases.getRangeWithComments();
declarationsRange = declarations.getRangeWithComments();
endRange = end.getRangeWithComments();
Doc.Group[
print(ctx, begin),
printHardlineList(ctx, moduleAliases),
if (!moduleAliases.isEmptyList() && !declarations.isEmptyList()) {
Doc.Concat[
Doc.HardLine(),
if (
declarationsRange.start.line() >
moduleAliasesRange.end.line() + 1
) {
Doc.HardLine()
} else {
Doc.Empty()
},
]
} else {
Doc.Empty()
},
printHardlineList(ctx, declarations),
if (!end.getFirstToken().fromSome().leadingComments.isEmpty()) {
Doc.Concat[
if (endRange.start.line() > declarationsRange.end.line()) {
Doc.HardLine()
} else {
Doc.Empty()
},
if (endRange.start.line() > declarationsRange.end.line() + 1) {
Doc.HardLine()
} else {
Doc.Empty()
},
]
} else {
Doc.Empty()
},
print(ctx, end),
]
| ParseTree.TokenTree{token} ->
Doc.Concat[
if (!ctx.isAlreadyPrintedLeadingComments(token)) {
printLeadingComments(t, token.leadingComments)
} else {
Doc.Empty()
},
Doc.Str(token.value),
printTrailingComments(t, token.trailingComments),
]
| ParseTree.EmptyTree{} -> Doc.Empty()
| ParseTree.ThisTypeTree{token} -> print(ctx, token)
| ParseTree.VoidTypeTree{token} -> print(ctx, token)
| ParseTree.FrozenTypeTree{token} -> print(ctx, token)
| ParseTree.UnderscoreTypeTree{token} -> print(ctx, token)
| ParseTree.InstTypeTree{token} -> print(ctx, token)
| ParseTree.ModuleAliasTree{
moduleKeyword,
aliasKeyword,
equals,
name,
value,
semiColon,
} ->
Doc.Concat[
print(ctx, moduleKeyword),
Doc.space,
print(ctx, aliasKeyword),
Doc.space,
print(ctx, name),
Doc.space,
print(ctx, equals),
Doc.space,
print(ctx, value),
print(ctx, semiColon),
]
| ParseTree.LambdaTypeSpecifierTree{
modifierOpt,
arguments,
arrow,
returnType,
} ->
Doc.Concat[
print(ctx, modifierOpt),
if (modifierOpt.isEmpty()) Doc.Empty() else Doc.space,
print(ctx, arguments),
Doc.space,
print(ctx, arrow),
Doc.space,
print(ctx, returnType),
]
| ParseTree.WithExpressionTree{value, withKeyword, arguments} ->
Doc.Concat[
print(ctx, value),
Doc.space,
print(ctx, withKeyword),
Doc.space,
print(ctx, arguments),
]
| ParseTree.ParenTypeSpecifierTree{openParen, element, closeParen} ->
Doc.Concat[
print(ctx, openParen),
print(ctx, element),