forked from prettier/prettier
/
ternary.js
356 lines (327 loc) · 10.1 KB
/
ternary.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
"use strict";
const { hasNewlineInRange } = require("../../common/util.js");
const {
isJsxNode,
getComments,
isCallExpression,
isMemberExpression,
isTSTypeExpression,
} = require("../utils/index.js");
const { locStart, locEnd } = require("../loc.js");
const isBlockComment = require("../utils/is-block-comment.js");
const {
builders: {
line,
softline,
group,
indent,
align,
ifBreak,
dedent,
breakParent,
},
} = require("../../document/index.js");
/**
* @typedef {import("../../document").Doc} Doc
* @typedef {import("../../common/ast-path")} AstPath
*
* @typedef {any} Options - Prettier options (TBD ...)
*/
// If we have nested conditional expressions, we want to print them in JSX mode
// if there's at least one JSXElement somewhere in the tree.
//
// A conditional expression chain like this should be printed in normal mode,
// because there aren't JSXElements anywhere in it:
//
// isA ? "A" : isB ? "B" : isC ? "C" : "Unknown";
//
// But a conditional expression chain like this should be printed in JSX mode,
// because there is a JSXElement in the last ConditionalExpression:
//
// isA ? "A" : isB ? "B" : isC ? "C" : <span className="warning">Unknown</span>;
//
// This type of ConditionalExpression chain is structured like this in the AST:
//
// ConditionalExpression {
// test: ...,
// consequent: ...,
// alternate: ConditionalExpression {
// test: ...,
// consequent: ...,
// alternate: ConditionalExpression {
// test: ...,
// consequent: ...,
// alternate: ...,
// }
// }
// }
function conditionalExpressionChainContainsJsx(node) {
// Given this code:
//
// // Using a ConditionalExpression as the consequent is uncommon, but should
// // be handled.
// A ? B : C ? D : E ? F ? G : H : I
//
// which has this AST:
//
// ConditionalExpression {
// test: Identifier(A),
// consequent: Identifier(B),
// alternate: ConditionalExpression {
// test: Identifier(C),
// consequent: Identifier(D),
// alternate: ConditionalExpression {
// test: Identifier(E),
// consequent: ConditionalExpression {
// test: Identifier(F),
// consequent: Identifier(G),
// alternate: Identifier(H),
// },
// alternate: Identifier(I),
// }
// }
// }
//
// We don't care about whether each node was the test, consequent, or alternate
// We are only checking if there's any JSXElements inside.
const conditionalExpressions = [node];
for (let index = 0; index < conditionalExpressions.length; index++) {
const conditionalExpression = conditionalExpressions[index];
for (const property of ["test", "consequent", "alternate"]) {
const node = conditionalExpression[property];
if (isJsxNode(node)) {
return true;
}
if (node.type === "ConditionalExpression") {
conditionalExpressions.push(node);
}
}
}
return false;
}
function printTernaryTest(path, options, print) {
const node = path.getValue();
const isConditionalExpression = node.type === "ConditionalExpression";
const alternateNodePropertyName = isConditionalExpression
? "alternate"
: "falseType";
const parent = path.getParentNode();
const printed = isConditionalExpression
? print("test")
: [print("checkType"), " ", "extends", " ", print("extendsType")];
/**
* a
* ? b
* : multiline
* test
* node
* ^^ align(2)
* ? d
* : e
*/
if (parent.type === node.type && parent[alternateNodePropertyName] === node) {
return align(2, printed);
}
return printed;
}
const ancestorNameMap = new Map([
["AssignmentExpression", "right"],
["VariableDeclarator", "init"],
["ReturnStatement", "argument"],
["ThrowStatement", "argument"],
["UnaryExpression", "argument"],
["YieldExpression", "argument"],
]);
function shouldExtraIndentForConditionalExpression(path) {
const node = path.getValue();
if (node.type !== "ConditionalExpression") {
return false;
}
let parent;
let child = node;
for (let ancestorCount = 0; !parent; ancestorCount++) {
const node = path.getParentNode(ancestorCount);
if (
(isCallExpression(node) && node.callee === child) ||
(isMemberExpression(node) && node.object === child) ||
(node.type === "TSNonNullExpression" && node.expression === child)
) {
child = node;
continue;
}
// Reached chain root
if (
(node.type === "NewExpression" && node.callee === child) ||
(isTSTypeExpression(node) && node.expression === child)
) {
parent = path.getParentNode(ancestorCount + 1);
child = node;
} else {
parent = node;
}
}
// Do not add indent to direct `ConditionalExpression`
if (child === node) {
return false;
}
return parent[ancestorNameMap.get(parent.type)] === child;
}
/**
* The following is the shared logic for
* ternary operators, namely ConditionalExpression
* and TSConditionalType
* @param {AstPath} path - The path to the ConditionalExpression/TSConditionalType node.
* @param {Options} options - Prettier options
* @param {Function} print - Print function to call recursively
* @returns {Doc}
*/
function printTernary(path, options, print) {
const node = path.getValue();
const isConditionalExpression = node.type === "ConditionalExpression";
const consequentNodePropertyName = isConditionalExpression
? "consequent"
: "trueType";
const alternateNodePropertyName = isConditionalExpression
? "alternate"
: "falseType";
const testNodePropertyNames = isConditionalExpression
? ["test"]
: ["checkType", "extendsType"];
const consequentNode = node[consequentNodePropertyName];
const alternateNode = node[alternateNodePropertyName];
const parts = [];
// We print a ConditionalExpression in either "JSX mode" or "normal mode".
// See `tests/format/jsx/conditional-expression.js` for more info.
let jsxMode = false;
const parent = path.getParentNode();
const isParentTest =
parent.type === node.type &&
testNodePropertyNames.some((prop) => parent[prop] === node);
let forceNoIndent = parent.type === node.type && !isParentTest;
// Find the outermost non-ConditionalExpression parent, and the outermost
// ConditionalExpression parent. We'll use these to determine if we should
// print in JSX mode.
let currentParent;
let previousParent;
let i = 0;
do {
previousParent = currentParent || node;
currentParent = path.getParentNode(i);
i++;
} while (
currentParent &&
currentParent.type === node.type &&
testNodePropertyNames.every(
(prop) => currentParent[prop] !== previousParent
)
);
const firstNonConditionalParent = currentParent || parent;
const lastConditionalParent = previousParent;
if (
isConditionalExpression &&
(isJsxNode(node[testNodePropertyNames[0]]) ||
isJsxNode(consequentNode) ||
isJsxNode(alternateNode) ||
conditionalExpressionChainContainsJsx(lastConditionalParent))
) {
jsxMode = true;
forceNoIndent = true;
// Even though they don't need parens, we wrap (almost) everything in
// parens when using ?: within JSX, because the parens are analogous to
// curly braces in an if statement.
const wrap = (doc) => [
ifBreak("("),
indent([softline, doc]),
softline,
ifBreak(")"),
];
// The only things we don't wrap are:
// * Nested conditional expressions in alternates
// * null
// * undefined
const isNil = (node) =>
node.type === "NullLiteral" ||
(node.type === "Literal" && node.value === null) ||
(node.type === "Identifier" && node.name === "undefined");
parts.push(
" ? ",
isNil(consequentNode)
? print(consequentNodePropertyName)
: wrap(print(consequentNodePropertyName)),
" : ",
alternateNode.type === node.type || isNil(alternateNode)
? print(alternateNodePropertyName)
: wrap(print(alternateNodePropertyName))
);
} else {
// normal mode
const part = [
line,
"? ",
consequentNode.type === node.type ? ifBreak("", "(") : "",
align(2, print(consequentNodePropertyName)),
consequentNode.type === node.type ? ifBreak("", ")") : "",
line,
": ",
alternateNode.type === node.type
? print(alternateNodePropertyName)
: align(2, print(alternateNodePropertyName)),
];
parts.push(
parent.type !== node.type ||
parent[alternateNodePropertyName] === node ||
isParentTest
? part
: options.useTabs
? dedent(indent(part))
: align(Math.max(0, options.tabWidth - 2), part)
);
}
// We want a whole chain of ConditionalExpressions to all
// break if any of them break. That means we should only group around the
// outer-most ConditionalExpression.
const comments = [
...testNodePropertyNames.map((propertyName) =>
getComments(node[propertyName])
),
getComments(consequentNode),
getComments(alternateNode),
].flat();
const shouldBreak = comments.some(
(comment) =>
isBlockComment(comment) &&
hasNewlineInRange(
options.originalText,
locStart(comment),
locEnd(comment)
)
);
const maybeGroup = (doc) =>
parent === firstNonConditionalParent
? group(doc, { shouldBreak })
: shouldBreak
? [doc, breakParent]
: doc;
// Break the closing paren to keep the chain right after it:
// (a
// ? b
// : c
// ).call()
const breakClosingParen =
!jsxMode &&
(isMemberExpression(parent) ||
(parent.type === "NGPipeExpression" && parent.left === node)) &&
!parent.computed;
const shouldExtraIndent = shouldExtraIndentForConditionalExpression(path);
const result = maybeGroup([
printTernaryTest(path, options, print),
forceNoIndent ? parts : indent(parts),
isConditionalExpression && breakClosingParen && !shouldExtraIndent
? softline
: "",
]);
return isParentTest || shouldExtraIndent
? group([indent([softline, result]), softline])
: result;
}
module.exports = { printTernary };