forked from OKEAMAH/prettier
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathattach.js
More file actions
416 lines (372 loc) · 12.6 KB
/
attach.js
File metadata and controls
416 lines (372 loc) · 12.6 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
import assert from "node:assert";
import { getChildren } from "../../utils/ast-utils.js";
import hasNewline from "../../utils/has-newline.js";
import isNonEmptyArray from "../../utils/is-non-empty-array.js";
import createGetVisitorKeysFunction from "../create-get-visitor-keys-function.js";
import {
addDanglingComment,
addLeadingComment,
addTrailingComment,
} from "./utils.js";
/**
* @typedef {import("../../common/ast-path.js").default} AstPath
*/
const childNodesCache = new WeakMap();
function getSortedChildNodes(node, options) {
if (childNodesCache.has(node)) {
return childNodesCache.get(node);
}
const {
printer: {
getCommentChildNodes,
canAttachComment,
getVisitorKeys: printerGetVisitorKeys,
},
locStart,
locEnd,
} = options;
if (!canAttachComment) {
return [];
}
const childNodes = (
getCommentChildNodes?.(node, options) ?? [
...getChildren(node, {
getVisitorKeys: createGetVisitorKeysFunction(printerGetVisitorKeys),
}),
]
).flatMap((node) =>
canAttachComment(node) ? [node] : getSortedChildNodes(node, options),
);
// Sort by `start` location first, then `end` location
childNodes.sort(
(nodeA, nodeB) =>
locStart(nodeA) - locStart(nodeB) || locEnd(nodeA) - locEnd(nodeB),
);
childNodesCache.set(node, childNodes);
return childNodes;
}
// As efficiently as possible, decorate the comment object with
// .precedingNode, .enclosingNode, and/or .followingNode properties, at
// least one of which is guaranteed to be defined.
function decorateComment(node, comment, options, enclosingNode) {
const { locStart, locEnd } = options;
const commentStart = locStart(comment);
const commentEnd = locEnd(comment);
const childNodes = getSortedChildNodes(node, options);
let precedingNode;
let followingNode;
// Time to dust off the old binary search robes and wizard hat.
let left = 0;
let right = childNodes.length;
while (left < right) {
const middle = (left + right) >> 1;
const child = childNodes[middle];
const start = locStart(child);
const end = locEnd(child);
// The comment is completely contained by this child node.
if (start <= commentStart && commentEnd <= end) {
// Abandon the binary search at this level.
return decorateComment(child, comment, options, child);
}
if (end <= commentStart) {
// This child node falls completely before the comment.
// Because we will never consider this node or any nodes
// before it again, this node must be the closest preceding
// node we have encountered so far.
precedingNode = child;
left = middle + 1;
continue;
}
if (commentEnd <= start) {
// This child node falls completely after the comment.
// Because we will never consider this node or any nodes after
// it again, this node must be the closest following node we
// have encountered so far.
followingNode = child;
right = middle;
continue;
}
/* c8 ignore next */
throw new Error("Comment location overlaps with node location");
}
// We don't want comments inside of different expressions inside of the same
// template literal to move to another expression.
if (enclosingNode?.type === "TemplateLiteral") {
const { quasis } = enclosingNode;
const commentIndex = findExpressionIndexForComment(
quasis,
comment,
options,
);
if (
precedingNode &&
findExpressionIndexForComment(quasis, precedingNode, options) !==
commentIndex
) {
precedingNode = null;
}
if (
followingNode &&
findExpressionIndexForComment(quasis, followingNode, options) !==
commentIndex
) {
followingNode = null;
}
}
return { enclosingNode, precedingNode, followingNode };
}
const returnFalse = () => false;
function attachComments(ast, options) {
const { comments } = ast;
delete ast.comments;
if (!isNonEmptyArray(comments) || !options.printer.canAttachComment) {
return;
}
const tiesToBreak = [];
const {
locStart,
locEnd,
printer: {
experimentalFeatures: {
// TODO: Make this as default behavior
avoidAstMutation = false,
} = {},
handleComments = {},
},
originalText: text,
} = options;
const {
ownLine: handleOwnLineComment = returnFalse,
endOfLine: handleEndOfLineComment = returnFalse,
remaining: handleRemainingComment = returnFalse,
} = handleComments;
const decoratedComments = comments.map((comment, index) => ({
...decorateComment(ast, comment, options),
comment,
text,
options,
ast,
isLastComment: comments.length - 1 === index,
}));
for (const [index, context] of decoratedComments.entries()) {
const {
comment,
precedingNode,
enclosingNode,
followingNode,
text,
options,
ast,
isLastComment,
} = context;
if (
options.parser === "json" ||
options.parser === "json5" ||
options.parser === "jsonc" ||
options.parser === "__js_expression" ||
options.parser === "__ts_expression" ||
options.parser === "__vue_expression" ||
options.parser === "__vue_ts_expression"
) {
if (locStart(comment) - locStart(ast) <= 0) {
addLeadingComment(ast, comment);
continue;
}
if (locEnd(comment) - locEnd(ast) >= 0) {
addTrailingComment(ast, comment);
continue;
}
}
let args;
if (avoidAstMutation) {
args = [context];
} else {
comment.enclosingNode = enclosingNode;
comment.precedingNode = precedingNode;
comment.followingNode = followingNode;
args = [comment, text, options, ast, isLastComment];
}
if (isOwnLineComment(text, options, decoratedComments, index)) {
comment.placement = "ownLine";
// If a comment exists on its own line, prefer a leading comment.
// We also need to check if it's the first line of the file.
if (handleOwnLineComment(...args)) {
// We're good
} else if (followingNode) {
// Always a leading comment.
addLeadingComment(followingNode, comment);
} else if (precedingNode) {
addTrailingComment(precedingNode, comment);
} else if (enclosingNode) {
addDanglingComment(enclosingNode, comment);
} else {
// There are no nodes, let's attach it to the root of the ast
/* c8 ignore next */
addDanglingComment(ast, comment);
}
} else if (isEndOfLineComment(text, options, decoratedComments, index)) {
comment.placement = "endOfLine";
if (handleEndOfLineComment(...args)) {
// We're good
} else if (precedingNode) {
// There is content before this comment on the same line, but
// none after it, so prefer a trailing comment of the previous node.
addTrailingComment(precedingNode, comment);
} else if (followingNode) {
addLeadingComment(followingNode, comment);
} else if (enclosingNode) {
addDanglingComment(enclosingNode, comment);
} else {
// There are no nodes, let's attach it to the root of the ast
/* c8 ignore next */
addDanglingComment(ast, comment);
}
} else {
comment.placement = "remaining";
if (handleRemainingComment(...args)) {
// We're good
} else if (precedingNode && followingNode) {
// Otherwise, text exists both before and after the comment on
// the same line. If there is both a preceding and following
// node, use a tie-breaking algorithm to determine if it should
// be attached to the next or previous node. In the last case,
// simply attach the right node;
const tieCount = tiesToBreak.length;
if (tieCount > 0) {
const lastTie = tiesToBreak[tieCount - 1];
if (lastTie.followingNode !== followingNode) {
breakTies(tiesToBreak, options);
}
}
tiesToBreak.push(context);
} else if (precedingNode) {
addTrailingComment(precedingNode, comment);
} else if (followingNode) {
addLeadingComment(followingNode, comment);
} else if (enclosingNode) {
addDanglingComment(enclosingNode, comment);
} else {
// There are no nodes, let's attach it to the root of the ast
/* c8 ignore next */
addDanglingComment(ast, comment);
}
}
}
breakTies(tiesToBreak, options);
if (!avoidAstMutation) {
for (const comment of comments) {
// These node references were useful for breaking ties, but we
// don't need them anymore, and they create cycles in the AST that
// may lead to infinite recursion if we don't delete them here.
delete comment.precedingNode;
delete comment.enclosingNode;
delete comment.followingNode;
}
}
}
const isAllEmptyAndNoLineBreak = (text) => !/[\S\n\u2028\u2029]/u.test(text);
function isOwnLineComment(text, options, decoratedComments, commentIndex) {
const { comment, precedingNode } = decoratedComments[commentIndex];
const { locStart, locEnd } = options;
let start = locStart(comment);
if (precedingNode) {
// Find first comment on the same line
for (let index = commentIndex - 1; index >= 0; index--) {
const { comment, precedingNode: currentCommentPrecedingNode } =
decoratedComments[index];
if (
currentCommentPrecedingNode !== precedingNode ||
!isAllEmptyAndNoLineBreak(text.slice(locEnd(comment), start))
) {
break;
}
start = locStart(comment);
}
}
return hasNewline(text, start, { backwards: true });
}
function isEndOfLineComment(text, options, decoratedComments, commentIndex) {
const { comment, followingNode } = decoratedComments[commentIndex];
const { locStart, locEnd } = options;
let end = locEnd(comment);
if (followingNode) {
// Find last comment on the same line
for (
let index = commentIndex + 1;
index < decoratedComments.length;
index++
) {
const { comment, followingNode: currentCommentFollowingNode } =
decoratedComments[index];
if (
currentCommentFollowingNode !== followingNode ||
!isAllEmptyAndNoLineBreak(text.slice(end, locStart(comment)))
) {
break;
}
end = locEnd(comment);
}
}
return hasNewline(text, end);
}
function breakTies(tiesToBreak, options) {
const tieCount = tiesToBreak.length;
if (tieCount === 0) {
return;
}
const { precedingNode, followingNode } = tiesToBreak[0];
let gapEndPos = options.locStart(followingNode);
// Iterate backwards through tiesToBreak, examining the gaps between the tied
// comments. In order to qualify as leading, a comment must be separated from
// followingNode by an unbroken series of gaps (or other comments). By
// default, gaps should only contain whitespace or open parentheses.
// printer.isGap can be used to define custom logic for checking gaps.
let indexOfFirstLeadingComment;
for (
indexOfFirstLeadingComment = tieCount;
indexOfFirstLeadingComment > 0;
--indexOfFirstLeadingComment
) {
const {
comment,
precedingNode: currentCommentPrecedingNode,
followingNode: currentCommentFollowingNode,
} = tiesToBreak[indexOfFirstLeadingComment - 1];
assert.strictEqual(currentCommentPrecedingNode, precedingNode);
assert.strictEqual(currentCommentFollowingNode, followingNode);
const gap = options.originalText.slice(options.locEnd(comment), gapEndPos);
if (options.printer.isGap?.(gap, options) ?? /^[\s(]*$/u.test(gap)) {
gapEndPos = options.locStart(comment);
} else {
// The gap string contained something other than whitespace or open
// parentheses.
break;
}
}
for (const [i, { comment }] of tiesToBreak.entries()) {
if (i < indexOfFirstLeadingComment) {
addTrailingComment(precedingNode, comment);
} else {
addLeadingComment(followingNode, comment);
}
}
for (const node of [precedingNode, followingNode]) {
if (node.comments && node.comments.length > 1) {
node.comments.sort((a, b) => options.locStart(a) - options.locStart(b));
}
}
tiesToBreak.length = 0;
}
function findExpressionIndexForComment(quasis, comment, options) {
const startPos = options.locStart(comment) - 1;
for (let i = 1; i < quasis.length; ++i) {
if (startPos < options.locStart(quasis[i])) {
return i - 1;
}
}
// We haven't found it, it probably means that some of the locations are off.
// Let's just return the first one.
/* c8 ignore next */
return 0;
}
export { attachComments, getSortedChildNodes };