forked from prettier/prettier
-
Notifications
You must be signed in to change notification settings - Fork 1
/
member-chain.js
454 lines (417 loc) · 13.8 KB
/
member-chain.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
"use strict";
const flat = require("lodash/flatten");
const comments = require("../../main/comments");
const {
getLast,
isNextLineEmpty,
isNextLineEmptyAfterIndex,
getNextNonSpaceNonCommentCharacterIndex,
} = require("../../common/util");
const pathNeedsParens = require("../needs-parens");
const {
hasLeadingComment,
hasTrailingComment,
isCallOrOptionalCallExpression,
isLiteralLikeValue,
isLongCurriedCallExpression,
isMemberish,
isNumericLiteral,
isSimpleCallArgument,
} = require("../utils");
const {
builders: {
concat,
join,
hardline,
group,
indent,
conditionalGroup,
breakParent,
},
utils: { willBreak },
} = require("../../document");
const printCallArguments = require("./call-arguments");
const {
printOptionalToken,
printFunctionTypeParameters,
printMemberLookup,
printBindExpressionCallee,
} = require("./misc");
// We detect calls on member expressions specially to format a
// common pattern better. The pattern we are looking for is this:
//
// arr
// .map(x => x + 1)
// .filter(x => x > 10)
// .some(x => x % 2)
//
// The way it is structured in the AST is via a nested sequence of
// MemberExpression and CallExpression. We need to traverse the AST
// and make groups out of it to print it in the desired way.
function printMemberChain(path, options, print) {
const parent = path.getParentNode();
const isExpressionStatement =
!parent || parent.type === "ExpressionStatement";
// The first phase is to linearize the AST by traversing it down.
//
// a().b()
// has the following AST structure:
// CallExpression(MemberExpression(CallExpression(Identifier)))
// and we transform it into
// [Identifier, CallExpression, MemberExpression, CallExpression]
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
function shouldInsertEmptyLineAfter(node) {
const { originalText } = options;
const nextCharIndex = getNextNonSpaceNonCommentCharacterIndex(
originalText,
node,
options.locEnd
);
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 (
nextCharIndex !== false &&
isNextLineEmptyAfterIndex(originalText, nextCharIndex + 1)
);
}
return isNextLineEmpty(originalText, node, options.locEnd);
}
function rec(path) {
const node = path.getValue();
if (
isCallOrOptionalCallExpression(node) &&
(isMemberish(node.callee) || isCallOrOptionalCallExpression(node.callee))
) {
printedNodes.unshift({
node,
printed: concat([
comments.printComments(
path,
() =>
concat([
printOptionalToken(path),
printFunctionTypeParameters(path, options, print),
printCallArguments(path, options, print),
]),
options
),
shouldInsertEmptyLineAfter(node) ? hardline : "",
]),
});
path.call((callee) => rec(callee), "callee");
} else if (isMemberish(node)) {
printedNodes.unshift({
node,
needsParens: pathNeedsParens(path, options),
printed: comments.printComments(
path,
() =>
node.type === "OptionalMemberExpression" ||
node.type === "MemberExpression"
? printMemberLookup(path, options, print)
: printBindExpressionCallee(path, options, print),
options
),
});
path.call((object) => rec(object), "object");
} else if (node.type === "TSNonNullExpression") {
printedNodes.unshift({
node,
printed: comments.printComments(path, () => "!", options),
});
path.call((expression) => rec(expression), "expression");
} else {
printedNodes.unshift({
node,
printed: path.call(print),
});
}
}
// Note: the comments of the root node have already been printed, so we
// need to extract this first call without printing them as they would
// if handled inside of the recursive call.
const node = path.getValue();
printedNodes.unshift({
node,
printed: concat([
printOptionalToken(path),
printFunctionTypeParameters(path, options, print),
printCallArguments(path, options, print),
]),
});
if (node.callee) {
path.call((callee) => rec(callee), "callee");
}
// Once we have a linear list of printed nodes, we want to create groups out
// of it.
//
// a().b.c().d().e
// will be grouped as
// [
// [Identifier, CallExpression],
// [MemberExpression, MemberExpression, CallExpression],
// [MemberExpression, CallExpression],
// [MemberExpression],
// ]
// 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 array accessors as possible
// < fn()[0][1][2] >.something()
// - then, as many MemberExpression as possible but the last one
// < this.items >.something()
const groups = [];
let currentGroup = [printedNodes[0]];
let i = 1;
for (; i < printedNodes.length; ++i) {
if (
printedNodes[i].node.type === "TSNonNullExpression" ||
isCallOrOptionalCallExpression(printedNodes[i].node) ||
((printedNodes[i].node.type === "MemberExpression" ||
printedNodes[i].node.type === "OptionalMemberExpression") &&
printedNodes[i].node.computed &&
isNumericLiteral(printedNodes[i].node.property))
) {
currentGroup.push(printedNodes[i]);
} else {
break;
}
}
if (!isCallOrOptionalCallExpression(printedNodes[0].node)) {
for (; i + 1 < printedNodes.length; ++i) {
if (
isMemberish(printedNodes[i].node) &&
isMemberish(printedNodes[i + 1].node)
) {
currentGroup.push(printedNodes[i]);
} else {
break;
}
}
}
groups.push(currentGroup);
currentGroup = [];
// Then, each following group is a sequence of MemberExpression 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
let hasSeenCallExpression = false;
for (; i < printedNodes.length; ++i) {
if (hasSeenCallExpression && isMemberish(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.computed &&
isNumericLiteral(printedNodes[i].node.property)
) {
currentGroup.push(printedNodes[i]);
continue;
}
groups.push(currentGroup);
currentGroup = [];
hasSeenCallExpression = false;
}
if (
isCallOrOptionalCallExpression(printedNodes[i].node) ||
printedNodes[i].node.type === "ImportExpression"
) {
hasSeenCallExpression = true;
}
currentGroup.push(printedNodes[i]);
if (
printedNodes[i].node.comments &&
printedNodes[i].node.comments.some((comment) => comment.trailing)
) {
groups.push(currentGroup);
currentGroup = [];
hasSeenCallExpression = false;
}
}
if (currentGroup.length > 0) {
groups.push(currentGroup);
}
// There are cases like Object.keys(), Observable.of(), _.values() where
// they are the subject of all the chained calls and therefore should
// be kept on the same line:
//
// Object.keys(items)
// .filter(x => x)
// .map(x => x)
//
// In order to detect those cases, we use an heuristic: if the first
// node is an identifier with the name starting with a capital
// letter or just a sequence of _$. The rationale is that they are
// likely to be factories.
function isFactory(name) {
return /^[A-Z]|^[$_]+$/.test(name);
}
// In case the Identifier is shorter than tab width, we can keep the
// first call in a single line, if it's an ExpressionStatement.
//
// d3.scaleLinear()
// .domain([0, 100])
// .range([0, width]);
//
function isShort(name) {
return name.length <= options.tabWidth;
}
function shouldNotWrap(groups) {
const hasComputed = groups[1].length && groups[1][0].node.computed;
if (groups[0].length === 1) {
const firstNode = groups[0][0].node;
return (
firstNode.type === "ThisExpression" ||
(firstNode.type === "Identifier" &&
(isFactory(firstNode.name) ||
(isExpressionStatement && isShort(firstNode.name)) ||
hasComputed))
);
}
const lastNode = getLast(groups[0]).node;
return (
(lastNode.type === "MemberExpression" ||
lastNode.type === "OptionalMemberExpression") &&
lastNode.property.type === "Identifier" &&
(isFactory(lastNode.property.name) || hasComputed)
);
}
const shouldMerge =
groups.length >= 2 && !groups[1][0].node.comments && shouldNotWrap(groups);
function printGroup(printedGroup) {
const printed = printedGroup.map((tuple) => tuple.printed);
// Checks if the last node (i.e. the parent node) needs parens and print
// accordingly
if (
printedGroup.length > 0 &&
printedGroup[printedGroup.length - 1].needsParens
) {
return concat(["(", ...printed, ")"]);
}
return concat(printed);
}
function printIndentedGroup(groups) {
if (groups.length === 0) {
return "";
}
return indent(
group(concat([hardline, join(hardline, groups.map(printGroup))]))
);
}
const printedGroups = groups.map(printGroup);
const oneLine = concat(printedGroups);
const cutoff = shouldMerge ? 3 : 2;
const flatGroups = flat(groups);
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));
// If we only have a single `.`, we shouldn't do anything fancy and just
// render everything concatenated together.
if (groups.length <= cutoff && !hasComment) {
if (isLongCurriedCallExpression(path)) {
return oneLine;
}
return group(oneLine);
}
// Find out the last node in the first group and check if it has an
// empty line after
const lastNodeBeforeIndent = getLast(groups[shouldMerge ? 1 : 0]).node;
const shouldHaveEmptyLineBeforeIndent =
!isCallOrOptionalCallExpression(lastNodeBeforeIndent) &&
shouldInsertEmptyLineAfter(lastNodeBeforeIndent);
const expanded = concat([
printGroup(groups[0]),
shouldMerge ? printGroup(groups[1]) : "",
shouldHaveEmptyLineBeforeIndent ? hardline : "",
printIndentedGroup(groups.slice(shouldMerge ? 2 : 1)),
]);
const callExpressions = printedNodes
.map(({ node }) => node)
.filter(isCallOrOptionalCallExpression);
function looksLikeFluentConfigurationPattern() {
if (
isExpressionStatement &&
callExpressions.length > 1 &&
// Keep simple chains like this on one line:
// req.checkBody("name").notEmpty().optional();
!(
callExpressions[0].arguments.length <= 1 &&
callExpressions.slice(1).every((expr) => expr.arguments.length === 0)
)
) {
const allArgs = flat(callExpressions.map((expr) => expr.arguments));
return allArgs.length > 0 && allArgs.every(isLiteralLikeValue);
}
return false;
}
function callHasComplexArguments(expr, index) {
return (
(index !== 0 && expr.arguments.length > 2) ||
!expr.arguments.every((arg) => isSimpleCallArgument(arg, 0))
);
}
/**
* If the last call's argument is a function, it's okay to inline if it fits and there is no other function arguments.
*
* This chain should be split:
*
* const mapped = scopes.filter(scope => scope.value !== '').map((scope, i) => {
* // multi line content
* });
*
* This chain can be inlined:
*
* const mapped = scopes.filter(myFilter).map((scope, i) => {
* // multi line content
* });
*
*/
function lastGroupWillBreakAndOtherCallsHaveComplexArguments() {
const lastGroupNode = getLast(getLast(groups)).node;
const lastGroupDoc = getLast(printedGroups);
return (
isCallOrOptionalCallExpression(lastGroupNode) &&
willBreak(lastGroupDoc) &&
callExpressions.some(
(expr, index) =>
index !== callExpressions.length - 1 &&
callHasComplexArguments(expr, index)
)
);
}
// We don't want to print in one line if at least one of these conditions occurs:
// * the chain has comments,
// * the head of the chain is a constructor call,
// * the chain is an expression statement and all the arguments are literal-like ("fluent configuration" pattern),
// * the chain is longer than 2 calls and has non-trivial arguments or more than 2 arguments in any call but the first one,
// * any group but the last one has a hard line,
// * the last call's arguments have a hard line and other calls have non-trivial arguments.
if (
hasComment ||
printedNodes[0].node.type === "NewExpression" ||
looksLikeFluentConfigurationPattern() ||
(callExpressions.length > 2 &&
callExpressions.some(callHasComplexArguments)) ||
printedGroups.slice(0, -1).some(willBreak) ||
lastGroupWillBreakAndOtherCallsHaveComplexArguments()
) {
return group(expanded);
}
return concat([
// 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]),
]);
}
module.exports = printMemberChain;