-
-
Notifications
You must be signed in to change notification settings - Fork 4.7k
Expand file tree
/
Copy pathindex.js
More file actions
301 lines (258 loc) · 8.36 KB
/
index.js
File metadata and controls
301 lines (258 loc) · 8.36 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
import * as assert from "#universal/assert";
import { commentsPropertyInOptions } from "../../../constants.js";
import {
locEnd,
locEndWithFullText,
locStart,
shouldAddContentEnd,
} from "../../location/index.js";
import {
isBlockComment,
isLineComment,
} from "../../utilities/comment-types.js";
import { createTypeCheckFunction } from "../../utilities/create-type-check-function.js";
import { getRaw } from "../../utilities/get-raw.js";
import { isTypeCastComment } from "../../utilities/is-type-cast-comment.js";
import { stripComments } from "../../utilities/strip-comments.js";
import { mergeNestledJsdocComments } from "./merge-nestled-jsdoc-comments.js";
import visitNode from "./visit-node.js";
/**
@import {Node, Comment, NodeMap} from "../../types/estree.js"
*/
const isNodeWithRaw = createTypeCheckFunction([
// Babel
"RegExpLiteral",
"BigIntLiteral",
"NumericLiteral",
"StringLiteral",
// "NullLiteral",
// "BooleanLiteral",
"DirectiveLiteral",
// ESTree
"Literal",
"JSXText",
"TemplateElement",
// Flow
"StringLiteralTypeAnnotation",
"NumberLiteralTypeAnnotation",
"BigIntLiteralTypeAnnotation",
]);
/**
@param {{
text: string,
astType?: "espree" | "flow" | "hermes" | "meriyah" | "oxc-js" | "oxc-ts" | "typescript",
}} options
*/
function postprocess(ast, options) {
const { text, astType } = options;
const isOxcTs = astType === "oxc-ts";
const { comments } = ast;
mergeNestledJsdocComments(comments);
// `InterpreterDirective` from babel parser and flow parser
// Other parsers parse it as comment, babel treat it as comment too
// https://github.com/babel/babel/issues/15116
const program = ast.type === "File" ? ast.program : ast;
if (program.interpreter) {
comments.unshift(program.interpreter);
delete program.interpreter;
}
if (ast.hashbang) {
if (isOxcTs) {
comments.unshift(ast.hashbang);
}
delete ast.hashbang;
}
// In `typescript` and `flow`, `Program` doesn't count whitespace and comments
// See https://github.com/typescript-eslint/typescript-eslint/issues/11026
// See https://github.com/facebook/flow/issues/8537
if (ast.type === "Program") {
ast.range = [0, text.length];
}
let typeCastCommentsEnds;
ast = visitNode(ast, {
onEnter(node) {
setContentEnd(node, comments, text);
switch (node.type) {
case "ParenthesizedExpression": {
const { expression } = node;
const start = locStart(node);
// Align range with `flow`
if (expression.type === "TypeCastExpression") {
expression.range = [start, locEnd(node)];
return expression;
}
let shouldKeepParenthesizedExpression = false;
if (!isOxcTs) {
if (!typeCastCommentsEnds) {
typeCastCommentsEnds = [];
for (const comment of comments) {
if (isTypeCastComment(comment)) {
typeCastCommentsEnds.push(locEnd(comment));
}
}
}
// Keep ParenthesizedExpression nodes only if they have Closure-style type cast comments.
const previousCommentEnd = typeCastCommentsEnds.findLast(
(end) => end <= start,
);
shouldKeepParenthesizedExpression =
previousCommentEnd &&
// check that there are only white spaces between the comment and the parenthesis
text.slice(previousCommentEnd, start).trim().length === 0;
}
if (shouldKeepParenthesizedExpression) {
return;
}
expression.extra = { ...expression.extra, parenthesized: true };
return expression;
}
// This happened when use `oxc-parser` to parse `` `${foo satisfies bar}`; ``
// https://github.com/oxc-project/oxc/issues/11313
case "TemplateLiteral":
/* c8 ignore next 3 */
if (node.expressions.length !== node.quasis.length - 1) {
throw new Error("Malformed template literal.");
}
break;
case "TemplateElement":
// `flow`, `hermes`, `typescript`, and `oxc`(with `{astType: 'ts'}`) follows the `espree` style positions
// https://github.com/eslint/js/blob/5826877f7b33548e5ba984878dd4a8eac8448f87/packages/espree/lib/espree.js#L213
if (
astType === "flow" ||
astType === "hermes" ||
astType === "espree" ||
astType === "typescript" ||
isOxcTs
) {
const start = locStart(node) + 1;
const end = locEnd(node) - (node.tail ? 1 : 2);
node.range = [start, end];
}
break;
// remove redundant TypeScript nodes
case "TSParenthesizedType":
return node.typeAnnotation;
// For hack-style pipeline
case "TopicReference":
ast.extra = { ...ast.extra, __isUsingHackPipeline: true };
break;
// In Flow parser, it doesn't generate union/intersection types for single type
case "TSUnionType":
case "TSIntersectionType":
if (node.types.length === 1) {
return node.types[0];
}
break;
// babel-flow
case "TupleTypeAnnotation":
if (node.types && !node.elementTypes) {
node.elementTypes = node.types;
}
break;
case "ImportDeclaration":
if (astType === "hermes" && node.assertions && !node.attributes) {
node.attributes = node.assertions;
delete node.assertions;
}
break;
}
},
onLeave(node) {
switch (node.type) {
// Children can be parenthesized, need do this in `onLeave`
case "LogicalExpression":
// We remove unneeded parens around same-operator LogicalExpressions
if (isUnbalancedLogicalTree(node)) {
return rebalanceLogicalTree(node);
}
break;
}
/* c8 ignore next 3 */
if (process.env.NODE_ENV !== "production") {
assertRaw(node, text);
}
},
});
/* c8 ignore next 3 */
if (process.env.NODE_ENV !== "production") {
assertComments(comments, text);
}
return ast;
}
function isUnbalancedLogicalTree(node) {
return (
node.type === "LogicalExpression" &&
node.right.type === "LogicalExpression" &&
node.operator === node.right.operator
);
}
function rebalanceLogicalTree(node) {
if (!isUnbalancedLogicalTree(node)) {
return node;
}
return rebalanceLogicalTree({
type: "LogicalExpression",
operator: node.operator,
left: rebalanceLogicalTree({
type: "LogicalExpression",
operator: node.operator,
left: node.left,
right: node.right.left,
range: [locStart(node.left), locEnd(node.right.left)],
}),
right: node.right.right,
range: [locStart(node), locEnd(node)],
});
}
/* c8 ignore next */
function assertComments(comments, text) {
for (const comment of comments) {
const commentText = text.slice(locStart(comment), locEnd(comment));
if (isLineComment(comment)) {
const openingMark = text.slice(
0,
text.startsWith("<--") || text.startsWith("-->") ? 3 : 2,
);
assert.ok(openingMark + comment.value, commentText);
return;
}
if (isBlockComment(comment)) {
// Flow
const closingMark = commentText.endsWith("*-/") ? "*-/" : "*/";
assert.equal("/*" + comment.value + closingMark, commentText);
return;
}
throw new Error(`Unknown comment type '${comment.type}'.`);
}
}
/* c8 ignore next */
function assertRaw(node, text) {
if (!isNodeWithRaw(node)) {
return;
}
const raw = node.type === "TemplateElement" ? node.value.raw : getRaw(node);
assert.equal(raw, text.slice(locStart(node), locEnd(node)));
}
/**
@param {Node} node
@param {Comment[]} comments
@param {string} originalText
*/
function setContentEnd(node, comments, originalText) {
if (!shouldAddContentEnd(node)) {
return;
}
let end = locEndWithFullText(node);
if (originalText[end - 1] !== ";") {
return;
}
const text = stripComments({
[commentsPropertyInOptions]: comments,
originalText,
});
end -= 1;
const textBeforeSemicolon = text.slice(locStart(node), end);
const cleaned = textBeforeSemicolon.trimEnd();
node.__contentEnd = end - (textBeforeSemicolon.length - cleaned.length);
}
export default postprocess;