forked from prettier/prettier
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprinter-estree.js
5256 lines (4751 loc) · 148 KB
/
printer-estree.js
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
"use strict";
const assert = require("assert");
// TODO(azz): anything that imports from main shouldn't be in a `language-*` dir.
const comments = require("../main/comments");
const {
getNextNonSpaceNonCommentCharacter,
hasNewline,
hasNewlineInRange,
getLast,
getStringWidth,
printString,
printNumber,
hasIgnoreComment,
hasNodeIgnoreComment,
getIndentSize,
getPreferredQuote,
} = require("../common/util");
const {
isNextLineEmpty,
getNextNonSpaceNonCommentCharacterIndex,
} = require("../common/util-shared");
const {
builders: {
concat,
join,
line,
hardline,
softline,
literalline,
group,
indent,
align,
conditionalGroup,
fill,
ifBreak,
lineSuffixBoundary,
addAlignmentToDoc,
},
utils: { willBreak, isLineNext, isEmpty, removeLines, normalizeParts },
printer: { printDocToString },
} = require("../document");
const embed = require("./embed");
const clean = require("./clean");
const { insertPragma } = require("./pragma");
const handleComments = require("./comments");
const pathNeedsParens = require("./needs-parens");
const {
printHtmlBinding,
isVueEventBindingExpression,
} = require("./html-binding");
const preprocess = require("./preprocess");
const {
classChildNeedsASIProtection,
classPropMayCauseASIProblems,
getFlowVariance,
getLeftSidePathName,
getParentExportDeclaration,
getTypeScriptMappedTypeModifier,
hasDanglingComments,
hasFlowAnnotationComment,
hasFlowShorthandAnnotationComment,
hasLeadingOwnLineComment,
hasNakedLeftSide,
hasNewlineBetweenOrAfterDecorators,
hasNgSideEffect,
hasPrettierIgnore,
hasTrailingComment,
hasTrailingLineComment,
identity,
isBinaryish,
isCallOrOptionalCallExpression,
isEmptyJSXElement,
isExportDeclaration,
isFlowAnnotationComment,
isFunctionNotation,
isGetterOrSetter,
isJestEachTemplateLiteral,
isJSXNode,
isJSXWhitespaceExpression,
isLastStatement,
isLiteral,
isMeaningfulJSXText,
isMemberExpressionChain,
isMemberish,
isNgForOf,
isNumericLiteral,
isObjectType,
isObjectTypePropertyAFunction,
isSimpleFlowType,
isSimpleNumber,
isSimpleTemplateLiteral,
isStringLiteral,
isStringPropSafeToUnquote,
isTemplateOnItsOwnLine,
isTestCall,
isTheOnlyJSXElementInMarkdown,
isTSXFile,
isTypeAnnotationAFunction,
matchJsxWhitespaceRegex,
needsHardlineAfterDanglingComment,
rawText,
returnArgumentHasLeadingComment,
shouldPrintComma,
shouldFlatten,
startsWithNoLookaheadToken,
} = require("./utils");
const printMemberChain = require("./print/member-chain");
const printCallArguments = require("./print/call-arguments");
const {
printOptionalToken,
printFunctionTypeParameters,
printMemberLookup,
printBindExpressionCallee,
} = require("./print/misc");
const { printModuleSource, printModuleSpecifiers } = require("./print/module");
const printTernaryOperator = require("./print/ternary");
const needsQuoteProps = new WeakMap();
let uid = 0;
function genericPrint(path, options, printPath, args) {
const node = path.getValue();
let needsParens = false;
const linesWithoutParens = printPathNoParens(path, options, printPath, args);
if (!node || isEmpty(linesWithoutParens)) {
return linesWithoutParens;
}
const parentExportDecl = getParentExportDeclaration(path);
const decorators = [];
if (
node.type === "ClassMethod" ||
node.type === "ClassPrivateMethod" ||
node.type === "ClassProperty" ||
node.type === "TSAbstractClassProperty" ||
node.type === "ClassPrivateProperty" ||
node.type === "MethodDefinition" ||
node.type === "TSAbstractMethodDefinition" ||
node.type === "TSDeclareMethod"
) {
// their decorators are handled themselves
} else if (
node.decorators &&
node.decorators.length > 0 &&
// If the parent node is an export declaration and the decorator
// was written before the export, the export will be responsible
// for printing the decorators.
!(
parentExportDecl &&
options.locStart(parentExportDecl, { ignoreDecorators: true }) >
options.locStart(node.decorators[0])
)
) {
const shouldBreak =
node.type === "ClassExpression" ||
node.type === "ClassDeclaration" ||
hasNewlineBetweenOrAfterDecorators(node, options);
const separator = shouldBreak ? hardline : line;
path.each((decoratorPath) => {
let decorator = decoratorPath.getValue();
if (decorator.expression) {
decorator = decorator.expression;
} else {
decorator = decorator.callee;
}
decorators.push(printPath(decoratorPath), separator);
}, "decorators");
if (parentExportDecl) {
decorators.unshift(hardline);
}
} else if (
isExportDeclaration(node) &&
node.declaration &&
node.declaration.decorators &&
node.declaration.decorators.length > 0 &&
// Only print decorators here if they were written before the export,
// otherwise they are printed by the node.declaration
options.locStart(node, { ignoreDecorators: true }) >
options.locStart(node.declaration.decorators[0])
) {
// Export declarations are responsible for printing any decorators
// that logically apply to node.declaration.
path.each(
(decoratorPath) => {
const decorator = decoratorPath.getValue();
const prefix = decorator.type === "Decorator" ? "" : "@";
decorators.push(prefix, printPath(decoratorPath), hardline);
},
"declaration",
"decorators"
);
} else {
// Nodes with decorators can't have parentheses, so we can avoid
// computing pathNeedsParens() except in this case.
needsParens = pathNeedsParens(path, options);
}
const parts = [];
if (needsParens) {
parts.unshift("(");
}
parts.push(linesWithoutParens);
if (needsParens) {
const node = path.getValue();
if (hasFlowShorthandAnnotationComment(node)) {
parts.push(" /*");
parts.push(node.trailingComments[0].value.trimStart());
parts.push("*/");
node.trailingComments[0].printed = true;
}
parts.push(")");
}
if (decorators.length > 0) {
return group(concat(decorators.concat(parts)));
}
return concat(parts);
}
function printDecorators(path, options, print) {
const node = path.getValue();
return group(
concat([
join(line, path.map(print, "decorators")),
hasNewlineBetweenOrAfterDecorators(node, options) ? hardline : line,
])
);
}
function printPathNoParens(path, options, print, args) {
const n = path.getValue();
const semi = options.semi ? ";" : "";
if (!n) {
return "";
}
if (typeof n === "string") {
return n;
}
const htmlBinding = printHtmlBinding(path, options, print);
if (htmlBinding) {
return htmlBinding;
}
let parts = [];
switch (n.type) {
case "JsExpressionRoot":
return path.call(print, "node");
case "JsonRoot":
return concat([path.call(print, "node"), hardline]);
case "File":
// Print @babel/parser's InterpreterDirective here so that
// leading comments on the `Program` node get printed after the hashbang.
if (n.program && n.program.interpreter) {
parts.push(
path.call(
(programPath) => programPath.call(print, "interpreter"),
"program"
)
);
}
parts.push(path.call(print, "program"));
return concat(parts);
case "Program": {
const hasContents =
!n.body.every(({ type }) => type === "EmptyStatement") || n.comments;
// Babel 6
if (n.directives) {
const directivesCount = n.directives.length;
path.map((childPath, index) => {
parts.push(print(childPath), semi, hardline);
if (
(index < directivesCount - 1 || hasContents) &&
isNextLineEmpty(
options.originalText,
childPath.getValue(),
options.locEnd
)
) {
parts.push(hardline);
}
}, "directives");
}
parts.push(
path.call((bodyPath) => {
return printStatementSequence(bodyPath, options, print);
}, "body")
);
parts.push(
comments.printDanglingComments(path, options, /* sameIndent */ true)
);
// Only force a trailing newline if there were any contents.
if (hasContents) {
parts.push(hardline);
}
return concat(parts);
}
// Babel extension.
case "EmptyStatement":
return "";
case "ExpressionStatement":
// Detect Flow and TypeScript directives
if (n.directive) {
return concat([nodeStr(n.expression, options, true), semi]);
}
if (options.parser === "__vue_event_binding") {
const parent = path.getParentNode();
if (
parent.type === "Program" &&
parent.body.length === 1 &&
parent.body[0] === n
) {
return concat([
path.call(print, "expression"),
isVueEventBindingExpression(n.expression) ? ";" : "",
]);
}
}
// Do not append semicolon after the only JSX element in a program
return concat([
path.call(print, "expression"),
isTheOnlyJSXElementInMarkdown(options, path) ? "" : semi,
]);
// Babel non-standard node. Used for Closure-style type casts. See postprocess.js.
case "ParenthesizedExpression": {
const shouldHug = !n.expression.comments;
if (shouldHug) {
return concat(["(", path.call(print, "expression"), ")"]);
}
return group(
concat([
"(",
indent(concat([softline, path.call(print, "expression")])),
softline,
")",
])
);
}
case "AssignmentExpression":
return printAssignment(
n.left,
path.call(print, "left"),
concat([" ", n.operator]),
n.right,
path.call(print, "right"),
options
);
case "BinaryExpression":
case "LogicalExpression":
case "NGPipeExpression": {
const parent = path.getParentNode();
const parentParent = path.getParentNode(1);
const isInsideParenthesis =
n !== parent.body &&
(parent.type === "IfStatement" ||
parent.type === "WhileStatement" ||
parent.type === "SwitchStatement" ||
parent.type === "DoWhileStatement");
const parts = printBinaryishExpressions(
path,
print,
options,
/* isNested */ false,
isInsideParenthesis
);
// if (
// this.hasPlugin("dynamicImports") && this.lookahead().type === tt.parenLeft
// ) {
//
// looks super weird, we want to break the children if the parent breaks
//
// if (
// this.hasPlugin("dynamicImports") &&
// this.lookahead().type === tt.parenLeft
// ) {
if (isInsideParenthesis) {
return concat(parts);
}
// Break between the parens in
// unaries or in a member or specific call expression, i.e.
//
// (
// a &&
// b &&
// c
// ).call()
if (
((parent.type === "CallExpression" ||
parent.type === "OptionalCallExpression") &&
parent.callee === n) ||
parent.type === "UnaryExpression" ||
((parent.type === "MemberExpression" ||
parent.type === "OptionalMemberExpression") &&
!parent.computed)
) {
return group(
concat([indent(concat([softline, concat(parts)])), softline])
);
}
// Avoid indenting sub-expressions in some cases where the first sub-expression is already
// indented accordingly. We should indent sub-expressions where the first case isn't indented.
const shouldNotIndent =
parent.type === "ReturnStatement" ||
parent.type === "ThrowStatement" ||
(parent.type === "JSXExpressionContainer" &&
parentParent.type === "JSXAttribute") ||
(n.operator !== "|" && parent.type === "JsExpressionRoot") ||
(n.type !== "NGPipeExpression" &&
((parent.type === "NGRoot" && options.parser === "__ng_binding") ||
(parent.type === "NGMicrosyntaxExpression" &&
parentParent.type === "NGMicrosyntax" &&
parentParent.body.length === 1))) ||
(n === parent.body && parent.type === "ArrowFunctionExpression") ||
(n !== parent.body && parent.type === "ForStatement") ||
(parent.type === "ConditionalExpression" &&
parentParent.type !== "ReturnStatement" &&
parentParent.type !== "ThrowStatement" &&
parentParent.type !== "CallExpression" &&
parentParent.type !== "OptionalCallExpression") ||
parent.type === "TemplateLiteral";
const shouldIndentIfInlining =
parent.type === "AssignmentExpression" ||
parent.type === "VariableDeclarator" ||
parent.type === "ClassProperty" ||
parent.type === "TSAbstractClassProperty" ||
parent.type === "ClassPrivateProperty" ||
parent.type === "ObjectProperty" ||
parent.type === "Property";
const samePrecedenceSubExpression =
isBinaryish(n.left) && shouldFlatten(n.operator, n.left.operator);
if (
shouldNotIndent ||
(shouldInlineLogicalExpression(n) && !samePrecedenceSubExpression) ||
(!shouldInlineLogicalExpression(n) && shouldIndentIfInlining)
) {
return group(concat(parts));
}
if (parts.length === 0) {
return "";
}
// If the right part is a JSX node, we include it in a separate group to
// prevent it breaking the whole chain, so we can print the expression like:
//
// foo && bar && (
// <Foo>
// <Bar />
// </Foo>
// )
const hasJSX = isJSXNode(n.right);
const firstGroupIndex = parts.findIndex((part) => part.type === "group");
// Separate the leftmost expression, possibly with its leading comments.
const headParts = parts.slice(
0,
firstGroupIndex === -1 ? 1 : firstGroupIndex + 1
);
const rest = concat(
parts.slice(headParts.length, hasJSX ? -1 : undefined)
);
const groupId = Symbol("logicalChain-" + ++uid);
const chain = group(
concat([
// Don't include the initial expression in the indentation
// level. The first item is guaranteed to be the first
// left-most expression.
...headParts,
indent(rest),
]),
{ id: groupId }
);
if (!hasJSX) {
return chain;
}
const jsxPart = getLast(parts);
return group(
concat([chain, ifBreak(indent(jsxPart), jsxPart, { groupId })])
);
}
case "AssignmentPattern":
return concat([
path.call(print, "left"),
" = ",
path.call(print, "right"),
]);
case "TSTypeAssertion": {
const shouldBreakAfterCast = !(
n.expression.type === "ArrayExpression" ||
n.expression.type === "ObjectExpression"
);
const castGroup = group(
concat([
"<",
indent(concat([softline, path.call(print, "typeAnnotation")])),
softline,
">",
])
);
const exprContents = concat([
ifBreak("("),
indent(concat([softline, path.call(print, "expression")])),
softline,
ifBreak(")"),
]);
if (shouldBreakAfterCast) {
return conditionalGroup([
concat([castGroup, path.call(print, "expression")]),
concat([castGroup, group(exprContents, { shouldBreak: true })]),
concat([castGroup, path.call(print, "expression")]),
]);
}
return group(concat([castGroup, path.call(print, "expression")]));
}
case "OptionalMemberExpression":
case "MemberExpression": {
const parent = path.getParentNode();
let firstNonMemberParent;
let i = 0;
do {
firstNonMemberParent = path.getParentNode(i);
i++;
} while (
firstNonMemberParent &&
(firstNonMemberParent.type === "MemberExpression" ||
firstNonMemberParent.type === "OptionalMemberExpression" ||
firstNonMemberParent.type === "TSNonNullExpression")
);
const shouldInline =
(firstNonMemberParent &&
(firstNonMemberParent.type === "NewExpression" ||
firstNonMemberParent.type === "BindExpression" ||
(firstNonMemberParent.type === "VariableDeclarator" &&
firstNonMemberParent.id.type !== "Identifier") ||
(firstNonMemberParent.type === "AssignmentExpression" &&
firstNonMemberParent.left.type !== "Identifier"))) ||
n.computed ||
(n.object.type === "Identifier" &&
n.property.type === "Identifier" &&
parent.type !== "MemberExpression" &&
parent.type !== "OptionalMemberExpression");
return concat([
path.call(print, "object"),
shouldInline
? printMemberLookup(path, options, print)
: group(
indent(
concat([softline, printMemberLookup(path, options, print)])
)
),
]);
}
case "MetaProperty":
return concat([
path.call(print, "meta"),
".",
path.call(print, "property"),
]);
case "BindExpression":
if (n.object) {
parts.push(path.call(print, "object"));
}
parts.push(
group(
indent(
concat([softline, printBindExpressionCallee(path, options, print)])
)
)
);
return concat(parts);
case "Identifier": {
return concat([
n.name,
printOptionalToken(path),
printTypeAnnotation(path, options, print),
]);
}
case "V8IntrinsicIdentifier":
return concat(["%", n.name]);
case "SpreadElement":
case "SpreadElementPattern":
case "SpreadProperty":
case "SpreadPropertyPattern":
case "RestElement":
case "ObjectTypeSpreadProperty":
return concat([
"...",
path.call(print, "argument"),
printTypeAnnotation(path, options, print),
]);
case "FunctionDeclaration":
case "FunctionExpression":
parts.push(printFunctionDeclaration(path, print, options));
if (!n.body) {
parts.push(semi);
}
return concat(parts);
case "ArrowFunctionExpression": {
if (n.async) {
parts.push("async ");
}
if (shouldPrintParamsWithoutParens(path, options)) {
parts.push(path.call(print, "params", 0));
} else {
parts.push(
group(
concat([
printFunctionParams(
path,
print,
options,
/* expandLast */ args &&
(args.expandLastArg || args.expandFirstArg),
/* printTypeParams */ true
),
printReturnType(path, print, options),
])
)
);
}
const dangling = comments.printDanglingComments(
path,
options,
/* sameIndent */ true,
(comment) => {
const nextCharacter = getNextNonSpaceNonCommentCharacterIndex(
options.originalText,
comment,
options.locEnd
);
return (
options.originalText.slice(nextCharacter, nextCharacter + 2) ===
"=>"
);
}
);
if (dangling) {
parts.push(" ", dangling);
}
parts.push(" =>");
const body = path.call((bodyPath) => print(bodyPath, args), "body");
// We want to always keep these types of nodes on the same line
// as the arrow.
if (
!hasLeadingOwnLineComment(options.originalText, n.body, options) &&
(n.body.type === "ArrayExpression" ||
n.body.type === "ObjectExpression" ||
n.body.type === "BlockStatement" ||
isJSXNode(n.body) ||
isTemplateOnItsOwnLine(n.body, options.originalText, options) ||
n.body.type === "ArrowFunctionExpression" ||
n.body.type === "DoExpression")
) {
return group(concat([concat(parts), " ", body]));
}
// We handle sequence expressions as the body of arrows specially,
// so that the required parentheses end up on their own lines.
if (n.body.type === "SequenceExpression") {
return group(
concat([
concat(parts),
group(
concat([" (", indent(concat([softline, body])), softline, ")"])
),
])
);
}
// if the arrow function is expanded as last argument, we are adding a
// level of indentation and need to add a softline to align the closing )
// with the opening (, or if it's inside a JSXExpression (e.g. an attribute)
// we should align the expression's closing } with the line with the opening {.
const shouldAddSoftLine =
((args && args.expandLastArg) ||
path.getParentNode().type === "JSXExpressionContainer") &&
!(n.comments && n.comments.length);
const printTrailingComma =
args && args.expandLastArg && shouldPrintComma(options, "all");
// In order to avoid confusion between
// a => a ? a : a
// a <= a ? a : a
const shouldAddParens =
n.body.type === "ConditionalExpression" &&
!startsWithNoLookaheadToken(n.body, /* forbidFunctionAndClass */ false);
return group(
concat([
concat(parts),
group(
concat([
indent(
concat([
line,
shouldAddParens ? ifBreak("", "(") : "",
body,
shouldAddParens ? ifBreak("", ")") : "",
])
),
shouldAddSoftLine
? concat([ifBreak(printTrailingComma ? "," : ""), softline])
: "",
])
),
])
);
}
case "YieldExpression":
parts.push("yield");
if (n.delegate) {
parts.push("*");
}
if (n.argument) {
parts.push(" ", path.call(print, "argument"));
}
return concat(parts);
case "AwaitExpression": {
parts.push("await");
if (n.argument) {
parts.push(" ", path.call(print, "argument"));
}
const parent = path.getParentNode();
if (
((parent.type === "CallExpression" ||
parent.type === "OptionalCallExpression") &&
parent.callee === n) ||
((parent.type === "MemberExpression" ||
parent.type === "OptionalMemberExpression") &&
parent.object === n)
) {
return group(
concat([indent(concat([softline, concat(parts)])), softline])
);
}
return concat(parts);
}
case "ImportSpecifier":
if (n.importKind) {
parts.push(path.call(print, "importKind"), " ");
}
parts.push(path.call(print, "imported"));
if (n.local && n.local.name !== n.imported.name) {
parts.push(" as ", path.call(print, "local"));
}
return concat(parts);
case "ExportSpecifier":
parts.push(path.call(print, "local"));
if (n.exported && n.exported.name !== n.local.name) {
parts.push(" as ", path.call(print, "exported"));
}
return concat(parts);
case "ImportNamespaceSpecifier":
parts.push("* as ");
parts.push(path.call(print, "local"));
return concat(parts);
case "ImportDefaultSpecifier":
return path.call(print, "local");
case "TSExportAssignment":
return concat(["export = ", path.call(print, "expression"), semi]);
case "ExportDefaultDeclaration":
case "ExportNamedDeclaration":
return printExportDeclaration(path, options, print);
case "DeclareExportDeclaration":
return concat(["declare ", printExportDeclaration(path, options, print)]);
case "ExportAllDeclaration":
parts.push("export");
if (n.exportKind === "type") {
parts.push(" type");
}
parts.push(" *");
if (n.exported) {
parts.push(" as ", path.call(print, "exported"));
}
parts.push(printModuleSource(path, options, print), semi);
return concat(parts);
case "ExportNamespaceSpecifier":
return concat(["* as ", path.call(print, "exported")]);
case "ExportDefaultSpecifier":
return path.call(print, "exported");
case "ImportDeclaration": {
parts.push("import");
if (n.importKind && n.importKind !== "value") {
parts.push(" ", n.importKind);
}
if (n.specifiers && n.specifiers.length > 0) {
parts.push(printModuleSpecifiers(path, options, print));
parts.push(printModuleSource(path, options, print));
} else if (
(n.importKind && n.importKind === "type") ||
// import {} from 'x'
/{\s*}/.test(
options.originalText.slice(
options.locStart(n),
options.locStart(n.source)
)
)
) {
parts.push(" {}", printModuleSource(path, options, print));
} else {
parts.push(" ", path.call(print, "source"));
}
if (Array.isArray(n.attributes) && n.attributes.length !== 0) {
parts.push(" with ", concat(path.map(print, "attributes")));
}
parts.push(semi);
return concat(parts);
}
case "ImportAttribute":
return concat([path.call(print, "key"), ": ", path.call(print, "value")]);
case "Import":
return "import";
case "TSModuleBlock":
case "BlockStatement": {
const naked = path.call((bodyPath) => {
return printStatementSequence(bodyPath, options, print);
}, "body");
const hasContent = n.body.some((node) => node.type !== "EmptyStatement");
const hasDirectives = n.directives && n.directives.length > 0;
const parent = path.getParentNode();
const parentParent = path.getParentNode(1);
if (
!hasContent &&
!hasDirectives &&
!hasDanglingComments(n) &&
(parent.type === "ArrowFunctionExpression" ||
parent.type === "FunctionExpression" ||
parent.type === "FunctionDeclaration" ||
parent.type === "ObjectMethod" ||
parent.type === "ClassMethod" ||
parent.type === "ClassPrivateMethod" ||
parent.type === "ForStatement" ||
parent.type === "WhileStatement" ||
parent.type === "DoWhileStatement" ||
parent.type === "DoExpression" ||
(parent.type === "CatchClause" && !parentParent.finalizer) ||
parent.type === "TSModuleDeclaration")
) {
return "{}";
}
parts.push("{");
// Babel 6
if (hasDirectives) {
path.each((childPath) => {
parts.push(indent(concat([hardline, print(childPath), semi])));
if (
isNextLineEmpty(
options.originalText,
childPath.getValue(),
options.locEnd
)
) {
parts.push(hardline);
}
}, "directives");
}
if (hasContent) {
parts.push(indent(concat([hardline, naked])));
}
parts.push(comments.printDanglingComments(path, options));
parts.push(hardline, "}");
return concat(parts);
}
case "ReturnStatement":
return concat([
"return",
printReturnAndThrowArgument(path, options, print),
]);
case "NewExpression":
case "ImportExpression":
case "OptionalCallExpression":
case "CallExpression": {
const isNew = n.type === "NewExpression";
const isDynamicImport = n.type === "ImportExpression";
const optional = printOptionalToken(path);
const args = isDynamicImport ? [n.source] : n.arguments;
if (
// We want to keep CommonJS- and AMD-style require calls, and AMD-style
// define calls, as a unit.
// e.g. `define(["some/lib", (lib) => {`
(!isDynamicImport &&
!isNew &&
n.callee.type === "Identifier" &&
(n.callee.name === "require" || n.callee.name === "define")) ||
// Template literals as single arguments
(args.length === 1 &&
isTemplateOnItsOwnLine(args[0], options.originalText, options)) ||
// Keep test declarations on a single line
// e.g. `it('long name', () => {`
(!isNew && isTestCall(n, path.getParentNode()))
) {
return concat([
isNew ? "new " : "",
path.call(print, "callee"),
optional,
printFunctionTypeParameters(path, options, print),
concat([
"(",
isDynamicImport
? path.call(print, "source")
: join(", ", path.map(print, "arguments")),
")",
]),
]);
}
// Inline Flow annotation comments following Identifiers in Call nodes need to
// stay with the Identifier. For example:
//
// foo /*:: <SomeGeneric> */(bar);
//
// Here, we ensure that such comments stay between the Identifier and the Callee.
const isIdentifierWithFlowAnnotation =
n.callee &&
n.callee.type === "Identifier" &&
hasFlowAnnotationComment(n.callee.trailingComments);
if (isIdentifierWithFlowAnnotation) {
n.callee.trailingComments[0].printed = true;
}
// We detect calls on member lookups and possibly print them in a
// special chain format. See `printMemberChain` for more info.
if (
!isDynamicImport &&
!isNew &&
isMemberish(n.callee) &&
!path.call((path) => pathNeedsParens(path, options), "callee")