-
-
Notifications
You must be signed in to change notification settings - Fork 138
Expand file tree
/
Copy pathprinter.mjs
More file actions
2966 lines (2654 loc) · 78.7 KB
/
printer.mjs
File metadata and controls
2966 lines (2654 loc) · 78.7 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
import { util as prettierUtil, doc } from "prettier";
import {
printAllComments,
hasTrailingComment,
hasLeadingComment,
printDanglingComments,
printComments,
isBlockComment,
hasLeadingOwnLineComment,
} from "./comments.mjs";
import pathNeedsParens from "./needs-parens.mjs";
import { locStart, locEnd } from "./loc.mjs";
import {
getLast,
getPenultimate,
lineShouldEndWithSemicolon,
printNumber,
shouldFlatten,
maybeStripLeadingSlashFromUse,
fileShouldEndWithHardline,
hasDanglingComments,
docShouldHaveTrailingNewline,
isLookupNode,
isFirstChildrenInlineNode,
shouldPrintHardLineAfterStartInControlStructure,
shouldPrintHardLineBeforeEndInControlStructure,
getAlignment,
isProgramLikeNode,
getNodeKindIncludingLogical,
useDoubleQuote,
hasEmptyBody,
isNextLineEmptyAfterNamespace,
shouldPrintHardlineBeforeTrailingComma,
isDocNode,
getAncestorNode,
isReferenceLikeNode,
normalizeMagicMethodName,
isSimpleCallArgument,
} from "./util.mjs";
const {
breakParent,
join,
line,
lineSuffix,
group,
conditionalGroup,
indent,
dedent,
ifBreak,
hardline,
softline,
literalline,
align,
dedentToRoot,
} = doc.builders;
const { willBreak } = doc.utils;
const {
isNextLineEmptyAfterIndex,
hasNewline,
hasNewlineInRange,
getNextNonSpaceNonCommentCharacterIndex,
isNextLineEmpty,
isPreviousLineEmpty,
} = prettierUtil;
/**
* Determine if we should print a trailing comma based on the config & php version
*
* @param options {object} Prettier Options
* @param requiredVersion {number}
* @returns {boolean}
*/
function shouldPrintComma(options, requiredVersion) {
if (!options.trailingCommaPHP) {
return false;
}
return options.phpVersion >= requiredVersion;
}
function shouldPrintHardlineForOpenBrace(options) {
switch (options.braceStyle) {
case "1tbs":
return false;
case "psr-2":
case "per-cs":
default:
return true;
}
}
function genericPrint(path, options, print) {
const { node } = path;
if (typeof node === "string") {
return node;
}
const printedWithoutParens = printNode(path, options, print);
const parts = [];
const needsParens = pathNeedsParens(path, options);
if (needsParens) {
parts.unshift("(");
}
parts.push(printedWithoutParens);
if (needsParens) {
parts.push(")");
}
if (lineShouldEndWithSemicolon(path)) {
parts.push(";");
}
if (fileShouldEndWithHardline(path)) {
parts.push(hardline);
}
return parts;
}
function printPropertyLookup(path, options, print, nullsafe = false) {
return [nullsafe ? "?" : "", "->", print("offset")];
}
function printNullsafePropertyLookup(path, options, print) {
return printPropertyLookup(path, options, print, true);
}
function printStaticLookup(path, options, print) {
const { node } = path;
const needCurly = !["variable", "identifier"].includes(node.offset.kind);
return ["::", needCurly ? "{" : "", print("offset"), needCurly ? "}" : ""];
}
function printOffsetLookup(path, options, print) {
const { node } = path;
const shouldInline =
(node.offset && node.offset.kind === "number") ||
getAncestorNode(path, "encapsed");
return [
"[",
node.offset
? group([
indent([shouldInline ? "" : softline, print("offset")]),
shouldInline ? "" : softline,
])
: "",
"]",
];
}
// We detect calls on member expressions specially to format a
// common pattern better. The pattern we are looking for is this:
//
// $arr
// ->map(function(x) { return $x + 1; })
// ->filter(function(x) { return $x > 10; })
// ->some(function(x) { return $x % 2; });
//
// The way it is structured in the AST is via a nested sequence of
// propertylookup, staticlookup, offsetlookup and call.
// We need to traverse the AST and make groups out of it
// to print it in the desired way.
function printMemberChain(path, options, print) {
// The first phase is to linearize the AST by traversing it down.
//
// Example:
// a()->b->c()->d();
// has the AST structure
// call (isLookupNode d (
// call (isLookupNode c (
// isLookupNode b (
// call (variable a)
// )
// ))
// ))
// and we transform it into (notice the reversed order)
// [identifier a, call, isLookupNode b, isLookupNode c, call,
// isLookupNode d, call]
const printedNodes = [];
// Here we try to retain one typed empty line after each call expression or
// the first group whether it is in parentheses or not
//
// Example:
// $a
// ->call()
//
// ->otherCall();
//
// ($foo ? $a : $b)
// ->call()
// ->otherCall();
function shouldInsertEmptyLineAfter(node) {
const { originalText } = options;
const nextCharIndex = getNextNonSpaceNonCommentCharacterIndex(
originalText,
locEnd(node)
);
const nextChar = originalText.charAt(nextCharIndex);
// if it is cut off by a parenthesis, we only account for one typed empty
// line after that parenthesis
if (nextChar === ")") {
return isNextLineEmptyAfterIndex(
originalText,
nextCharIndex + 1,
options
);
}
return isNextLineEmpty(originalText, locEnd(node));
}
function traverse(path) {
const { node } = path;
if (
node.kind === "call" &&
(isLookupNode(node.what) || node.what.kind === "call")
) {
printedNodes.unshift({
node,
printed: [
printAllComments(
path,
() => printArgumentsList(path, options, print),
options
),
shouldInsertEmptyLineAfter(node) ? hardline : "",
],
});
path.call((what) => traverse(what), "what");
} else if (isLookupNode(node)) {
// Print *lookup nodes as we standard print them outside member chain
let printedMemberish = null;
if (node.kind === "propertylookup") {
printedMemberish = printPropertyLookup(path, options, print);
} else if (node.kind === "nullsafepropertylookup") {
printedMemberish = printNullsafePropertyLookup(path, options, print);
} else if (node.kind === "staticlookup") {
printedMemberish = printStaticLookup(path, options, print);
} else {
printedMemberish = printOffsetLookup(path, options, print);
}
printedNodes.unshift({
node,
needsParens: pathNeedsParens(path, options),
printed: printAllComments(path, () => printedMemberish, options),
});
path.call((what) => traverse(what), "what");
} else {
printedNodes.unshift({
node,
printed: print(),
});
}
}
const { node } = path;
printedNodes.unshift({
node,
printed: printArgumentsList(path, options, print),
});
path.call((what) => traverse(what), "what");
// Restore parens around `propertylookup` and `staticlookup` nodes with call.
// $value = ($object->foo)();
// $value = ($object::$foo)();
for (let i = 0; i < printedNodes.length; ++i) {
if (
printedNodes[i].node.kind === "call" &&
printedNodes[i - 1] &&
["propertylookup", "nullsafepropertylookup", "staticlookup"].includes(
printedNodes[i - 1].node.kind
) &&
printedNodes[i - 1].needsParens
) {
printedNodes[0].printed = ["(", printedNodes[0].printed];
printedNodes[i - 1].printed = [printedNodes[i - 1].printed, ")"];
}
}
// create groups from list of nodes, i.e.
// [identifier a, call, isLookupNode b, isLookupNode c, call,
// isLookupNode d, call]
// will be grouped as
// [
// [identifier a, Call],
// [isLookupNode b, isLookupNode c, call],
// [isLookupNode d, call]
// ]
// so that we can print it as
// a()
// ->b->c()
// ->d();
const groups = [];
let currentGroup = [printedNodes[0]];
let i = 1;
for (; i < printedNodes.length; ++i) {
if (
printedNodes[i].node.kind === "call" ||
(isLookupNode(printedNodes[i].node) &&
printedNodes[i].node.offset &&
printedNodes[i].node.offset.kind === "number")
) {
currentGroup.push(printedNodes[i]);
} else {
break;
}
}
if (printedNodes[0].node.kind !== "call") {
for (; i + 1 < printedNodes.length; ++i) {
if (
isLookupNode(printedNodes[i].node) &&
isLookupNode(printedNodes[i + 1].node)
) {
currentGroup.push(printedNodes[i]);
} else {
break;
}
}
}
groups.push(currentGroup);
currentGroup = [];
// Then, each following group is a sequence of propertylookup followed by
// a sequence of call. To compute it, we keep adding things to the
// group until we have seen a call in the past and reach a
// propertylookup
let hasSeenCallExpression = false;
for (; i < printedNodes.length; ++i) {
if (hasSeenCallExpression && isLookupNode(printedNodes[i].node)) {
// [0] should be appended at the end of the group instead of the
// beginning of the next one
if (
printedNodes[i].node.kind === "offsetlookup" &&
printedNodes[i].node.offset &&
printedNodes[i].node.offset.kind === "number"
) {
currentGroup.push(printedNodes[i]);
continue;
}
groups.push(currentGroup);
currentGroup = [];
hasSeenCallExpression = false;
}
if (printedNodes[i].node.kind === "call") {
hasSeenCallExpression = true;
}
currentGroup.push(printedNodes[i]);
if (
printedNodes[i].node.comments &&
hasTrailingComment(printedNodes[i].node)
) {
groups.push(currentGroup);
currentGroup = [];
hasSeenCallExpression = false;
}
}
if (currentGroup.length > 0) {
groups.push(currentGroup);
}
// Merge next nodes when:
//
// 1. We have `$this` variable before
//
// Example:
// $this->method()->property;
//
// 2. When we have offsetlookup after *lookup node
//
// Example:
// $foo->Data['key']("foo")
// ->method();
//
// 3. expression statements with variable names shorter than the tab width
//
// Example:
// $foo->bar()
// ->baz()
// ->buzz()
function shouldNotWrap(groups) {
const hasComputed =
groups[1].length && groups[1][0].node.kind === "offsetlookup";
if (groups[0].length === 1) {
const firstNode = groups[0][0].node;
return (
(firstNode.kind === "variable" &&
(firstNode.name === "this" ||
(isExpressionStatement && isShort(firstNode.name)))) ||
isReferenceLikeNode(firstNode)
);
}
function isShort(name) {
return name.length < options.tabWidth;
}
const lastNode = getLast(groups[0]).node;
return (
isLookupNode(lastNode) &&
(lastNode.offset.kind === "identifier" ||
lastNode.offset.kind === "variable") &&
hasComputed
);
}
const isExpressionStatement = path.parent.kind === "expressionstatement";
const shouldMerge =
groups.length >= 2 && !groups[1][0].node.comments && shouldNotWrap(groups);
function printGroup(printedGroup) {
const result = [];
for (let i = 0; i < printedGroup.length; i++) {
// Checks if the next node (i.e. the parent node) needs parens
// and print accordingl y
if (printedGroup[i + 1] && printedGroup[i + 1].needsParens) {
result.push(
"(",
printedGroup[i].printed,
printedGroup[i + 1].printed,
")"
);
i++;
} else {
result.push(printedGroup[i].printed);
}
}
return result;
}
function printIndentedGroup(groups) {
if (groups.length === 0) {
return "";
}
return indent(group([hardline, join(hardline, groups.map(printGroup))]));
}
const printedGroups = groups.map(printGroup);
const oneLine = printedGroups;
// Indicates how many we should merge
//
// Example (true):
// $this->method()->otherMethod(
// 'argument'
// );
//
// Example (false):
// $foo
// ->method()
// ->otherMethod();
const cutoff = shouldMerge ? 3 : 2;
const flatGroups = groups.slice(0, cutoff).flat();
const hasComment =
flatGroups.slice(1, -1).some((node) => hasLeadingComment(node.node)) ||
flatGroups.slice(0, -1).some((node) => hasTrailingComment(node.node)) ||
(groups[cutoff] && hasLeadingComment(groups[cutoff][0].node));
const hasEncapsedAncestor = getAncestorNode(path, "encapsed");
// If we only have a single `->`, we shouldn't do anything fancy and just
// render everything concatenated together.
// In `encapsed` node we always print in one line.
if ((groups.length <= cutoff && !hasComment) || hasEncapsedAncestor) {
return group(oneLine);
}
// Find out the last node in the first group and check if it has an
// empty line after
const lastNodeBeforeIndent = getLast(
shouldMerge ? groups.slice(1, 2)[0] : groups[0]
).node;
const shouldHaveEmptyLineBeforeIndent =
lastNodeBeforeIndent.kind !== "call" &&
shouldInsertEmptyLineAfter(lastNodeBeforeIndent);
const expanded = [
printGroup(groups[0]),
shouldMerge ? groups.slice(1, 2).map(printGroup) : "",
shouldHaveEmptyLineBeforeIndent ? hardline : "",
printIndentedGroup(groups.slice(shouldMerge ? 2 : 1)),
];
const callExpressions = printedNodes.filter(
(tuple) => tuple.node.kind === "call"
);
// We don't want to print in one line if there's:
// * A comment.
// * 3 or more chained calls.
// * Any group but the last one has a hard line.
// If the last group is a function it's okay to inline if it fits.
if (
hasComment ||
(callExpressions.length > 2 &&
callExpressions.some(
(exp) => !exp.node.arguments.every((arg) => isSimpleCallArgument(arg))
)) ||
printedGroups.slice(0, -1).some(willBreak)
) {
return group(expanded);
}
return [
// We only need to check `oneLine` because if `expanded` is chosen
// that means that the parent group has already been broken
// naturally
willBreak(oneLine) || shouldHaveEmptyLineBeforeIndent ? breakParent : "",
conditionalGroup([oneLine, expanded]),
];
}
function couldGroupArg(arg) {
return (
(arg.kind === "array" && (arg.items.length > 0 || arg.comments)) ||
arg.kind === "function" ||
arg.kind === "method" ||
arg.kind === "closure"
);
}
function shouldGroupLastArg(args) {
const lastArg = getLast(args);
const penultimateArg = getPenultimate(args);
return (
!hasLeadingComment(lastArg) &&
!hasTrailingComment(lastArg) &&
couldGroupArg(lastArg) &&
// If the last two arguments are of the same type,
// disable last element expansion.
(!penultimateArg || penultimateArg.kind !== lastArg.kind)
);
}
function shouldGroupFirstArg(args) {
if (args.length !== 2) {
return false;
}
const [firstArg, secondArg] = args;
return (
(!firstArg.comments || !firstArg.comments.length) &&
(firstArg.kind === "function" ||
firstArg.kind === "method" ||
firstArg.kind === "closure") &&
secondArg.kind !== "retif" &&
!couldGroupArg(secondArg)
);
}
function printArgumentsList(path, options, print, argumentsKey = "arguments") {
const args = path.node[argumentsKey];
if (args.length === 0) {
return [
"(",
printDanglingComments(path, options, /* sameIndent */ true),
")",
];
}
let anyArgEmptyLine = false;
let hasEmptyLineFollowingFirstArg = false;
const printedArguments = path.map(({ node: arg, isLast, isFirst }) => {
const parts = [print()];
if (isLast) {
// do nothing
} else if (isNextLineEmpty(options.originalText, locEnd(arg))) {
if (isFirst) {
hasEmptyLineFollowingFirstArg = true;
}
anyArgEmptyLine = true;
parts.push(",", hardline, hardline);
} else {
parts.push(",", line);
}
return parts;
}, argumentsKey);
const { node } = path;
const lastArg = getLast(args);
const maybeTrailingComma =
(shouldPrintComma(options, 7.3) &&
["call", "new", "unset", "isset"].includes(node.kind)) ||
(shouldPrintComma(options, 8.0) &&
["function", "closure", "method", "arrowfunc", "attribute"].includes(
node.kind
))
? indent([
lastArg && shouldPrintHardlineBeforeTrailingComma(lastArg)
? hardline
: "",
",",
])
: "";
function allArgsBrokenOut() {
return group(
["(", indent([line, ...printedArguments]), maybeTrailingComma, line, ")"],
{ shouldBreak: true }
);
}
const shouldGroupFirst = shouldGroupFirstArg(args);
const shouldGroupLast = shouldGroupLastArg(args);
if (shouldGroupFirst || shouldGroupLast) {
const shouldBreak =
(shouldGroupFirst
? printedArguments.slice(1).some(willBreak)
: printedArguments.slice(0, -1).some(willBreak)) || anyArgEmptyLine;
// We want to print the last argument with a special flag
let printedExpanded;
path.each(({ isLast, isFirst }) => {
if (shouldGroupFirst && isFirst) {
printedExpanded = [
print([], { expandFirstArg: true }),
printedArguments.length > 1 ? "," : "",
hasEmptyLineFollowingFirstArg ? hardline : line,
hasEmptyLineFollowingFirstArg ? hardline : "",
printedArguments.slice(1),
];
}
if (shouldGroupLast && isLast) {
printedExpanded = [
...printedArguments.slice(0, -1),
print([], { expandLastArg: true }),
];
}
}, argumentsKey);
const somePrintedArgumentsWillBreak = printedArguments.some(willBreak);
const simpleConcat = ["(", ...printedExpanded, ")"];
return [
somePrintedArgumentsWillBreak ? breakParent : "",
conditionalGroup(
[
!somePrintedArgumentsWillBreak
? simpleConcat
: ifBreak(allArgsBrokenOut(), simpleConcat),
shouldGroupFirst
? [
"(",
group(printedExpanded[0], { shouldBreak: true }),
...printedExpanded.slice(1),
")",
]
: [
"(",
...printedArguments.slice(0, -1),
group(getLast(printedExpanded), {
shouldBreak: true,
}),
")",
],
group(
[
"(",
indent([line, ...printedArguments]),
ifBreak(maybeTrailingComma),
line,
")",
],
{ shouldBreak: true }
),
],
{ shouldBreak }
),
];
}
return group(
[
"(",
indent([softline, ...printedArguments]),
ifBreak(maybeTrailingComma),
softline,
")",
],
{
shouldBreak: printedArguments.some(willBreak) || anyArgEmptyLine,
}
);
}
function shouldInlineRetifFalseExpression(node) {
return node.kind === "array" && node.items.length !== 0;
}
function shouldInlineLogicalExpression(node) {
return node.right.kind === "array" && node.right.items.length !== 0;
}
// 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 `+`.
function printBinaryExpression(
path,
print,
options,
isNested,
isInsideParenthesis
) {
let parts = [];
const { node } = path;
if (node.kind === "bin") {
// 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. (This doesn't hold for the `**` operator,
// which is unique in that it is right-associative.)
if (shouldFlatten(node.type, node.left.type)) {
// Flatten them out by recursively calling this function.
parts = parts.concat(
path.call(
() =>
printBinaryExpression(
path,
print,
options,
/* isNested */ true,
isInsideParenthesis
),
"left"
)
);
} else {
parts.push(print("left"));
}
const shouldInline = shouldInlineLogicalExpression(node);
const right = shouldInline
? [node.type, " ", print("right")]
: [node.type, line, print("right")];
// If there's only a single binary expression, we want to create a group
// in order to avoid having a small right part like -1 be on its own line.
const { parent } = path;
const shouldGroup =
!(isInsideParenthesis && ["||", "&&"].includes(node.type)) &&
getNodeKindIncludingLogical(parent) !==
getNodeKindIncludingLogical(node) &&
getNodeKindIncludingLogical(node.left) !==
getNodeKindIncludingLogical(node) &&
getNodeKindIncludingLogical(node.right) !==
getNodeKindIncludingLogical(node);
const shouldNotHaveWhitespace =
isDocNode(node.left) ||
(node.left.kind === "bin" && isDocNode(node.left.right));
parts.push(
shouldNotHaveWhitespace ? "" : " ",
shouldGroup ? group(right) : right
);
// The root comments are already printed, but we need to manually print
// the other ones since we don't call the normal print on bin,
// only for the left and right parts
if (isNested && node.comments) {
parts = printAllComments(path, () => parts, options);
}
} else {
// Our stopping case. Simply print the node normally.
parts.push(print());
}
return parts;
}
function printLookupNodes(path, options, print) {
const { node } = path;
switch (node.kind) {
case "propertylookup":
return printPropertyLookup(path, options, print);
case "nullsafepropertylookup":
return printNullsafePropertyLookup(path, options, print);
case "staticlookup":
return printStaticLookup(path, options, print);
case "offsetlookup":
return printOffsetLookup(path, options, print);
/* c8 ignore next 2 */
default:
throw new Error(`Have not implemented lookup kind ${node.kind} yet.`);
}
}
function getEncapsedQuotes(node, { opening = true } = {}) {
if (node.type === "heredoc") {
return opening ? `<<<${node.label}` : node.label;
}
const quotes = {
string: '"',
shell: "`",
};
if (quotes[node.type]) {
return quotes[node.type];
}
/* c8 ignore next */
throw new Error(`Unimplemented encapsed type ${node.type}`);
}
function printArrayItems(path, options, print) {
const printedElements = [];
let separatorParts = [];
path.each(({ node }) => {
printedElements.push(separatorParts);
printedElements.push(group(print()));
separatorParts = [",", line];
if (node && isNextLineEmpty(options.originalText, locEnd(node))) {
separatorParts.push(softline);
}
}, "items");
return printedElements;
}
// Wrap parts into groups by indexes.
// It is require to have same indent on lines for all parts into group.
// The value of `alignment` option indicates how many spaces must be before each part.
//
// Example:
// <div>
// <?php
// echo '1';
// echo '2';
// echo '3';
// ?>
// </div>
function wrapPartsIntoGroups(parts, indexes) {
if (indexes.length === 0) {
return parts;
}
let lastEnd = 0;
return indexes.reduce((accumulator, index) => {
const { start, end, alignment, before, after } = index;
const printedPartsForGrouping = [
before || "",
...parts.slice(start, end),
after || "",
];
const newArray = accumulator.concat(
parts.slice(lastEnd, start),
alignment
? dedentToRoot(
group(
align(new Array(alignment).join(" "), printedPartsForGrouping)
)
)
: group(printedPartsForGrouping),
end === parts.length - 1 ? parts.slice(end) : ""
);
lastEnd = end;
return newArray;
}, []);
}
function printLines(path, options, print, childrenAttribute = "children") {
const { node, parent: parentNode } = path;
let lastInlineIndex = -1;
const parts = [];
const groupIndexes = [];
path.map(() => {
const {
node: childNode,
next: nextNode,
isFirst: isFirstNode,
isLast: isLastNode,
index,
} = path;
const isInlineNode = childNode.kind === "inline";
const printedPath = print();
const canPrintBlankLine =
!isLastNode &&
!isInlineNode &&
(nextNode && nextNode.kind === "case"
? !isFirstChildrenInlineNode(path)
: nextNode && nextNode.kind !== "inline");
let printed = [
printedPath,
canPrintBlankLine ? hardline : "",
canPrintBlankLine &&
isNextLineEmpty(options.originalText, locEnd(childNode))
? hardline
: "",
];
const isBlockNestedNode =
node.kind === "block" &&
parentNode &&
["function", "closure", "method", "try", "catch"].includes(
parentNode.kind
);
let beforeCloseTagInlineNode = isBlockNestedNode && isFirstNode ? "" : " ";
if (isInlineNode || (!isInlineNode && isLastNode && lastInlineIndex >= 0)) {
const prevLastInlineIndex = lastInlineIndex;
if (isInlineNode) {
lastInlineIndex = index;
}
const shouldCreateGroup =
(isInlineNode && !isFirstNode) || (!isInlineNode && isLastNode);
if (shouldCreateGroup) {
const start =
(isInlineNode ? prevLastInlineIndex : lastInlineIndex) + 1;
const end = isLastNode && !isInlineNode ? index + 1 : index;
const prevInlineNode =
path.siblings[isInlineNode ? prevLastInlineIndex : lastInlineIndex];
const alignment = prevInlineNode
? getAlignment(prevInlineNode.raw)
: "";
const shouldBreak = end - start > 1;
const before = shouldBreak
? (isBlockNestedNode && !prevInlineNode) ||
(isProgramLikeNode(node) && start === 0)
? ""
: hardline
: "";
const after =
shouldBreak && childNode.kind !== "halt"
? isBlockNestedNode && isLastNode
? ""
: hardline
: "";
if (shouldBreak) {
beforeCloseTagInlineNode = "";