-
-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
binaryish.js
317 lines (281 loc) · 9.23 KB
/
binaryish.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
"use strict";
const { printComments } = require("../../main/comments");
const { getLast } = require("../../common/util");
const {
builders: {
join,
line,
softline,
group,
indent,
align,
ifBreak,
indentIfBreak,
},
utils: { cleanDoc, getDocParts, isConcat },
} = require("../../document");
const {
hasLeadingOwnLineComment,
isBinaryish,
isJsxNode,
shouldFlatten,
hasComment,
CommentCheckFlags,
isCallExpression,
isMemberExpression,
isObjectProperty,
} = require("../utils");
/** @typedef {import("../../document").Doc} Doc */
let uid = 0;
function printBinaryishExpression(path, options, print) {
const node = path.getValue();
const parent = path.getParentNode();
const parentParent = path.getParentNode(1);
const isInsideParenthesis =
node !== 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 parts;
}
// Break between the parens in
// unaries or in a member or specific call expression, i.e.
//
// (
// a &&
// b &&
// c
// ).call()
if (
(isCallExpression(parent) && parent.callee === node) ||
parent.type === "UnaryExpression" ||
(isMemberExpression(parent) && !parent.computed)
) {
return group([indent([softline, ...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") ||
(node.operator !== "|" && parent.type === "JsExpressionRoot") ||
(node.type !== "NGPipeExpression" &&
((parent.type === "NGRoot" && options.parser === "__ng_binding") ||
(parent.type === "NGMicrosyntaxExpression" &&
parentParent.type === "NGMicrosyntax" &&
parentParent.body.length === 1))) ||
(node === parent.body && parent.type === "ArrowFunctionExpression") ||
(node !== parent.body && parent.type === "ForStatement") ||
(parent.type === "ConditionalExpression" &&
parentParent.type !== "ReturnStatement" &&
parentParent.type !== "ThrowStatement" &&
!isCallExpression(parentParent)) ||
parent.type === "TemplateLiteral";
const shouldIndentIfInlining =
parent.type === "AssignmentExpression" ||
parent.type === "VariableDeclarator" ||
parent.type === "ClassProperty" ||
parent.type === "PropertyDefinition" ||
parent.type === "TSAbstractClassProperty" ||
parent.type === "ClassPrivateProperty" ||
isObjectProperty(parent);
const samePrecedenceSubExpression =
isBinaryish(node.left) && shouldFlatten(node.operator, node.left.operator);
if (
shouldNotIndent ||
(shouldInlineLogicalExpression(node) && !samePrecedenceSubExpression) ||
(!shouldInlineLogicalExpression(node) && shouldIndentIfInlining)
) {
return group(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(node.right);
const firstGroupIndex = parts.findIndex(
(part) =>
typeof part !== "string" && !Array.isArray(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 = parts.slice(headParts.length, hasJsx ? -1 : undefined);
const groupId = Symbol("logicalChain-" + ++uid);
const chain = group(
[
// 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([chain, indentIfBreak(jsxPart, { groupId })]);
}
// 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 printBinaryishExpressions(
path,
print,
options,
isNested,
isInsideParenthesis
) {
/** @type{Doc[]} */
let parts = [];
const node = path.getValue();
// We treat BinaryExpression and LogicalExpression nodes the same.
if (isBinaryish(node)) {
// 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.operator, node.left.operator)) {
// Flatten them out by recursively calling this function.
parts = [
...parts,
...path.call(
(left) =>
printBinaryishExpressions(
left,
print,
options,
/* isNested */ true,
isInsideParenthesis
),
"left"
),
];
} else {
parts.push(group(print("left")));
}
const shouldInline = shouldInlineLogicalExpression(node);
const lineBeforeOperator =
(node.operator === "|>" ||
node.type === "NGPipeExpression" ||
(node.operator === "|" && options.parser === "__vue_expression")) &&
!hasLeadingOwnLineComment(options.originalText, node.right);
const operator = node.type === "NGPipeExpression" ? "|" : node.operator;
const rightSuffix =
node.type === "NGPipeExpression" && node.arguments.length > 0
? group(
indent([
softline,
": ",
join(
[softline, ":", ifBreak(" ")],
path.map(print, "arguments").map((arg) => align(2, group(arg)))
),
])
)
: "";
const right = shouldInline
? [operator, " ", print("right"), rightSuffix]
: [
lineBeforeOperator ? line : "",
operator,
lineBeforeOperator ? " " : line,
print("right"),
rightSuffix,
];
// 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.getParentNode();
const shouldBreak = hasComment(
node.left,
CommentCheckFlags.Trailing | CommentCheckFlags.Line
);
const shouldGroup =
shouldBreak ||
(!(isInsideParenthesis && node.type === "LogicalExpression") &&
parent.type !== node.type &&
node.left.type !== node.type &&
node.right.type !== node.type);
parts.push(
lineBeforeOperator ? "" : " ",
shouldGroup ? group(right, { shouldBreak }) : 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 BinaryExpression,
// only for the left and right parts
if (isNested && hasComment(node)) {
const printed = cleanDoc(printComments(path, parts, options));
/* istanbul ignore else */
if (isConcat(printed) || printed.type === "fill") {
parts = getDocParts(printed);
} else {
parts = [printed];
}
}
} else {
// Our stopping case. Simply print the node normally.
parts.push(group(print()));
}
return parts;
}
function shouldInlineLogicalExpression(node) {
if (node.type !== "LogicalExpression") {
return false;
}
if (
node.right.type === "ObjectExpression" &&
node.right.properties.length > 0
) {
return true;
}
if (node.right.type === "ArrayExpression" && node.right.elements.length > 0) {
return true;
}
if (isJsxNode(node.right)) {
return true;
}
return false;
}
module.exports = { printBinaryishExpression, shouldInlineLogicalExpression };