@tsrx/eslint-parser 0.6.2 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +88 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +430 -77
- package/dist/index.js.map +1 -1
- package/package.json +3 -2
- package/src/index.ts +551 -47
package/src/index.ts
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import type { Program } from 'estree';
|
|
2
|
-
import type { Linter } from 'eslint';
|
|
2
|
+
import type { AST, Linter } from 'eslint';
|
|
3
3
|
import {
|
|
4
4
|
analyzeTsrx as analyze_tsrx,
|
|
5
5
|
DIAGNOSTIC_CODES,
|
|
6
6
|
parseModule as parse_module,
|
|
7
7
|
} from '@tsrx/core';
|
|
8
|
+
import { Definition, Referencer, ScopeManager } from 'eslint-scope';
|
|
8
9
|
|
|
9
10
|
interface ParseResult {
|
|
10
11
|
ast: Program;
|
|
@@ -16,8 +17,8 @@ interface ParseResult {
|
|
|
16
17
|
const visitorKeys: Record<string, string[]> = {
|
|
17
18
|
Program: ['body'],
|
|
18
19
|
JSXElement: ['openingElement', 'children', 'closingElement'],
|
|
19
|
-
JSXOpeningElement: ['name', 'attributes'],
|
|
20
|
-
JSXClosingElement: ['name'],
|
|
20
|
+
JSXOpeningElement: ['name', 'tagExpression', 'attributes'],
|
|
21
|
+
JSXClosingElement: ['name', 'tagExpression'],
|
|
21
22
|
JSXFragment: ['openingFragment', 'children', 'closingFragment'],
|
|
22
23
|
JSXOpeningFragment: [],
|
|
23
24
|
JSXClosingFragment: [],
|
|
@@ -29,19 +30,199 @@ const visitorKeys: Record<string, string[]> = {
|
|
|
29
30
|
JSXNamespacedName: ['namespace', 'name'],
|
|
30
31
|
JSXText: [],
|
|
31
32
|
JSXStyleElement: ['openingElement', 'children', 'closingElement'],
|
|
32
|
-
JSXIfExpression: ['
|
|
33
|
-
JSXForExpression: ['
|
|
33
|
+
JSXIfExpression: ['statement'],
|
|
34
|
+
JSXForExpression: ['index', 'key', 'loop', 'empty'],
|
|
34
35
|
JSXSwitchExpression: ['discriminant', 'cases'],
|
|
35
|
-
|
|
36
|
+
JSXSwitchCase: ['test', 'consequent'],
|
|
37
|
+
JSXTryExpression: ['block', 'pending', 'handler', 'finalizer'],
|
|
36
38
|
JSXCodeBlock: ['body', 'render'],
|
|
37
39
|
StyleSheet: [],
|
|
38
40
|
ForOfStatement: ['left', 'right', 'body'],
|
|
41
|
+
// eslint-scope's default keys leave out `pending`, so without this, scope
|
|
42
|
+
// analysis would skip the `pending` block of a plain `try`.
|
|
43
|
+
TryStatement: ['block', 'pending', 'handler', 'finalizer'],
|
|
39
44
|
};
|
|
40
45
|
|
|
41
46
|
/**
|
|
42
|
-
*
|
|
47
|
+
* eslint-scope's referencer, plus the `@for` parts: the loop's `index` and
|
|
48
|
+
* `key` belong to the loop's scope, like its variable, and the `@empty` branch
|
|
49
|
+
* runs outside it. TSRX gives every iteration its own index. A `@catch` can
|
|
50
|
+
* also take a `reset` function after the error.
|
|
43
51
|
*/
|
|
44
|
-
|
|
52
|
+
class TSRXReferencer extends Referencer {
|
|
53
|
+
#tsrx_for_by_loop = new Map<any, any>();
|
|
54
|
+
#var_heads = new Set<any>();
|
|
55
|
+
|
|
56
|
+
JSXOpeningElement(node: any): void {
|
|
57
|
+
if (!node.tagExpression) {
|
|
58
|
+
super.JSXOpeningElement(node);
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
// A dynamic tag's expression holds its references, with or without JSX
|
|
62
|
+
// enabled. The name that mirrors it holds none.
|
|
63
|
+
this.visit(node.tagExpression);
|
|
64
|
+
node.attributes.forEach(this.visit, this);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// A closing tag repeats the opening tag's name, so it adds no references.
|
|
68
|
+
// With JSX enabled, eslint-scope read the `</style>` of a `<style>` element
|
|
69
|
+
// as one.
|
|
70
|
+
JSXClosingElement(): void {}
|
|
71
|
+
|
|
72
|
+
JSXForExpression(node: any): void {
|
|
73
|
+
this.#tsrx_for_by_loop.set(node.loop, node);
|
|
74
|
+
// TSRX runs each iteration in a callback, so the loop has a scope of its
|
|
75
|
+
// own whatever its head declares. eslint-scope opens one only for a
|
|
76
|
+
// `let` or `const` head.
|
|
77
|
+
const head = node.loop.type === 'ForStatement' ? node.loop.init : node.loop.left;
|
|
78
|
+
if (head?.type !== 'VariableDeclaration' || head.kind === 'var') {
|
|
79
|
+
(this as any).scopeManager.__nestForScope(node.loop);
|
|
80
|
+
}
|
|
81
|
+
if (head?.kind === 'var') this.#var_heads.add(head);
|
|
82
|
+
this.visit(node.loop);
|
|
83
|
+
if (node.empty) this.visit(node.empty);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
VariableDeclaration(node: any): void {
|
|
87
|
+
if (!this.#var_heads.has(node)) {
|
|
88
|
+
super.VariableDeclaration(node);
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
// A `var` head declares the variable in the loop's scope, as `let` does.
|
|
92
|
+
node.declarations.forEach((declaration: any, index: number) => {
|
|
93
|
+
this.visitVariableDeclaration(this.currentScope(), 'Variable', node, index);
|
|
94
|
+
if (declaration.init) this.visit(declaration.init);
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
CatchClause(node: any): void {
|
|
99
|
+
if (!node.resetParam) {
|
|
100
|
+
super.CatchClause(node);
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
// eslint-scope's `CatchClause`, with `reset` defined as the error is.
|
|
104
|
+
(this as any).scopeManager.__nestCatchScope(node);
|
|
105
|
+
for (const param of [node.param, node.resetParam]) {
|
|
106
|
+
this.visitPattern(param, { processRightHandNodes: true }, (pattern: any, info: any) => {
|
|
107
|
+
(this.currentScope() as any).__define(
|
|
108
|
+
pattern,
|
|
109
|
+
new (Definition as any)('CatchClause', pattern, node, null, null, null),
|
|
110
|
+
);
|
|
111
|
+
this.referencingDefaultValue(pattern, info.assignments, null, true);
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
this.visit(node.body);
|
|
115
|
+
this.close(node);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
close(node: any): void {
|
|
119
|
+
const tsrx_for = this.#tsrx_for_by_loop.get(node);
|
|
120
|
+
if (tsrx_for?.index) {
|
|
121
|
+
(this.currentScope() as any).__define(
|
|
122
|
+
tsrx_for.index,
|
|
123
|
+
new (Definition as any)('Variable', tsrx_for.index, tsrx_for, tsrx_for, null, null),
|
|
124
|
+
);
|
|
125
|
+
}
|
|
126
|
+
if (tsrx_for?.key) this.visit(tsrx_for.key);
|
|
127
|
+
super.close(node);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Scope analysis as ESLint runs it, with `TSRXReferencer`. A `.tsrx` file is
|
|
133
|
+
* always a module.
|
|
134
|
+
*/
|
|
135
|
+
function analyze_scope(ast: any, options: Linter.ParserOptions | undefined): any {
|
|
136
|
+
const ecma_features = options?.ecmaFeatures ?? {};
|
|
137
|
+
const scope_options = {
|
|
138
|
+
ignoreEval: true,
|
|
139
|
+
nodejsScope: ecma_features.globalReturn,
|
|
140
|
+
impliedStrict: ecma_features.impliedStrict,
|
|
141
|
+
ecmaVersion: typeof options?.ecmaVersion === 'number' ? options.ecmaVersion : 6,
|
|
142
|
+
sourceType: 'module',
|
|
143
|
+
childVisitorKeys: visitorKeys,
|
|
144
|
+
// eslint-visitor-keys' `getKeys`, which ESLint passes
|
|
145
|
+
fallback: (node: any) =>
|
|
146
|
+
Object.keys(node).filter(
|
|
147
|
+
(key) =>
|
|
148
|
+
key !== 'parent' &&
|
|
149
|
+
key !== 'leadingComments' &&
|
|
150
|
+
key !== 'trailingComments' &&
|
|
151
|
+
key[0] !== '_',
|
|
152
|
+
),
|
|
153
|
+
jsx: ecma_features.jsx,
|
|
154
|
+
};
|
|
155
|
+
const scope_manager = new ScopeManager(scope_options as any);
|
|
156
|
+
new TSRXReferencer(scope_options as any, scope_manager).visit(ast);
|
|
157
|
+
return scope_manager;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
const LOOP_FIELDS: Record<string, string[]> = {
|
|
161
|
+
ForStatement: ['init', 'test', 'update', 'body'],
|
|
162
|
+
ForInStatement: ['left', 'right', 'body'],
|
|
163
|
+
ForOfStatement: ['await', 'left', 'right', 'body'],
|
|
164
|
+
};
|
|
165
|
+
|
|
166
|
+
const STATEMENT_FIELDS: Record<string, { keyword: string; fields: string[] }> = {
|
|
167
|
+
JSXIfExpression: { keyword: 'if', fields: ['test', 'consequent', 'alternate'] },
|
|
168
|
+
};
|
|
169
|
+
|
|
170
|
+
const SIGNATURE_TYPES = new Set([
|
|
171
|
+
'TSFunctionType',
|
|
172
|
+
'TSConstructorType',
|
|
173
|
+
'TSCallSignatureDeclaration',
|
|
174
|
+
'TSConstructSignatureDeclaration',
|
|
175
|
+
'TSMethodSignature',
|
|
176
|
+
]);
|
|
177
|
+
|
|
178
|
+
/** The name rules see for a dynamic tag that no JSX name can mirror. */
|
|
179
|
+
const DYNAMIC_TAG_NAME = 'tsrx-dynamic-tag';
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* The JSX name rules see for a dynamic tag: a `JSXIdentifier` or
|
|
183
|
+
* `JSXMemberExpression` that mirrors its expression (`<{as}>` is `as`,
|
|
184
|
+
* `<{ui.Box}>` is `ui.Box`), or a synthetic `JSXIdentifier` for any other
|
|
185
|
+
* expression (`<{'div'}>`, `<{icons[key]}>`, `<{pick()}>`). The name spans the
|
|
186
|
+
* braces, so a rule that fixes the text before or after it keeps them.
|
|
187
|
+
*/
|
|
188
|
+
function dynamic_tag_name(container: any): any {
|
|
189
|
+
const name = mirror_tag_expression(container.expression) ?? {
|
|
190
|
+
type: 'JSXIdentifier',
|
|
191
|
+
name: DYNAMIC_TAG_NAME,
|
|
192
|
+
};
|
|
193
|
+
return { ...name, start: container.start, end: container.end };
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** The JSX name for an identifier or a chain of `.name` accesses, or `null`. */
|
|
197
|
+
function mirror_tag_expression(node: any): any {
|
|
198
|
+
if (node.type === 'Identifier') {
|
|
199
|
+
return { type: 'JSXIdentifier', name: node.name, start: node.start, end: node.end };
|
|
200
|
+
}
|
|
201
|
+
if (node.type !== 'MemberExpression' || node.computed || node.property.type !== 'Identifier') {
|
|
202
|
+
return null;
|
|
203
|
+
}
|
|
204
|
+
// `<this.Item>` is a JSX member name too.
|
|
205
|
+
const object =
|
|
206
|
+
node.object.type === 'ThisExpression'
|
|
207
|
+
? { type: 'JSXIdentifier', name: 'this', start: node.object.start, end: node.object.end }
|
|
208
|
+
: mirror_tag_expression(node.object);
|
|
209
|
+
return (
|
|
210
|
+
object && {
|
|
211
|
+
type: 'JSXMemberExpression',
|
|
212
|
+
object,
|
|
213
|
+
property: mirror_tag_expression(node.property),
|
|
214
|
+
start: node.start,
|
|
215
|
+
end: node.end,
|
|
216
|
+
}
|
|
217
|
+
);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* Keep this hook for small ESLint-only AST normalizations. Returns the `JSXText`
|
|
222
|
+
* nodes, which each get a token of their own.
|
|
223
|
+
*/
|
|
224
|
+
function normalize_tsrx_ast_for_eslint(ast: any, code: string): Span[] {
|
|
225
|
+
const texts: Span[] = [];
|
|
45
226
|
const seen = new Set<any>();
|
|
46
227
|
const visit = (node: any) => {
|
|
47
228
|
if (!node || typeof node !== 'object') return;
|
|
@@ -55,6 +236,112 @@ function normalize_tsrx_ast_for_eslint(ast: any): void {
|
|
|
55
236
|
delete node.metadata.styleApplies;
|
|
56
237
|
}
|
|
57
238
|
|
|
239
|
+
// ESLint's code path analysis handles every `SwitchCase` as a case of a
|
|
240
|
+
// `switch` statement and throws on one inside `@switch`. `@case` bodies
|
|
241
|
+
// never fall through, so they need no switch code paths.
|
|
242
|
+
if (node.type === 'JSXSwitchExpression') {
|
|
243
|
+
for (const switch_case of node.cases) switch_case.type = 'JSXSwitchCase';
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
// A comment in JSX text is a comment for ESLint, not a `{}` container:
|
|
247
|
+
// drop the placeholder node the parser keeps for it.
|
|
248
|
+
if (node.type === 'JSXElement' || node.type === 'JSXFragment') {
|
|
249
|
+
node.children = node.children.filter(
|
|
250
|
+
(child: any) =>
|
|
251
|
+
child.type !== 'JSXExpressionContainer' ||
|
|
252
|
+
child.expression.type !== 'JSXEmptyExpression' ||
|
|
253
|
+
child.start !== child.expression.start,
|
|
254
|
+
);
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
// The loop of a `@for` is a real for statement in `loop`, so rules such as
|
|
258
|
+
// `semi` and `init-declarations` know its head. ESLint's code path analysis
|
|
259
|
+
// allows a for statement no fields of its own, so `index`, `key` and the
|
|
260
|
+
// `@empty` branch stay on `JSXForExpression`.
|
|
261
|
+
if (node.type === 'JSXForExpression') {
|
|
262
|
+
const loop: any = {
|
|
263
|
+
type: node.statementType,
|
|
264
|
+
start: code.indexOf('for', node.start),
|
|
265
|
+
end: node.body.end,
|
|
266
|
+
};
|
|
267
|
+
for (const key of LOOP_FIELDS[node.statementType]) {
|
|
268
|
+
loop[key] = node[key];
|
|
269
|
+
delete node[key];
|
|
270
|
+
}
|
|
271
|
+
node.loop = loop;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
// An `@if` likewise keeps its if statement in `statement`, so code path
|
|
275
|
+
// analysis gives each arm a path of its own, as it does the branches of an
|
|
276
|
+
// `if`. A `@try` keeps its blocks, in source order: as a `try` statement,
|
|
277
|
+
// its body would be inside a `try`, though the React, Preact and Hono
|
|
278
|
+
// output has none.
|
|
279
|
+
// `react-hooks/rules-of-hooks` would then report as conditional every hook
|
|
280
|
+
// after the body's first call, member access or identifier, except `use()`,
|
|
281
|
+
// which 6.1.1 and 7.1.1 report anywhere in the body as inside a try/catch
|
|
282
|
+
// block.
|
|
283
|
+
// `@switch` keeps its cases: a `switch` would fall through from each case
|
|
284
|
+
// into the next.
|
|
285
|
+
if (node.type in STATEMENT_FIELDS) {
|
|
286
|
+
const { keyword, fields } = STATEMENT_FIELDS[node.type];
|
|
287
|
+
const statement: any = {
|
|
288
|
+
type: node.statementType,
|
|
289
|
+
start: code.indexOf(keyword, node.start),
|
|
290
|
+
end: node.end,
|
|
291
|
+
};
|
|
292
|
+
for (const key of fields) {
|
|
293
|
+
statement[key] = node[key];
|
|
294
|
+
delete node[key];
|
|
295
|
+
}
|
|
296
|
+
node.statement = statement;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
// The parser accepts a plain `try` with only a `pending` block. It compiles
|
|
300
|
+
// to a `try` with neither a `catch` nor a `finally`, which isn't JavaScript,
|
|
301
|
+
// and code path analysis throws on it.
|
|
302
|
+
if (node.type === 'TryStatement' && !node.handler && !node.finalizer) {
|
|
303
|
+
throw to_eslint_parse_error({
|
|
304
|
+
message: 'Missing catch or finally clause',
|
|
305
|
+
loc: node.loc,
|
|
306
|
+
start: node.start,
|
|
307
|
+
});
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
// Rules read a tag name as a JSX name, and crash on the expression
|
|
311
|
+
// container of a dynamic tag. They see a name that mirrors it instead, and
|
|
312
|
+
// the container moves to `tagExpression`, where rules still lint the code
|
|
313
|
+
// and scope analysis reads the opening tag's (see `TSRXReferencer`).
|
|
314
|
+
if (
|
|
315
|
+
(node.type === 'JSXOpeningElement' || node.type === 'JSXClosingElement') &&
|
|
316
|
+
node.name?.type === 'JSXExpressionContainer'
|
|
317
|
+
) {
|
|
318
|
+
node.tagExpression = node.name;
|
|
319
|
+
node.name = dynamic_tag_name(node.name);
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
// typescript-eslint names the parameters of a function type or signature
|
|
323
|
+
// `params`, and rules such as `max-params` read that name. It is not
|
|
324
|
+
// enumerable, so traversal still visits each parameter once.
|
|
325
|
+
if (SIGNATURE_TYPES.has(node.type) && node.parameters) {
|
|
326
|
+
Object.defineProperty(node, 'params', { value: node.parameters, configurable: true });
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
// Like espree, a template element spans its delimiters: `` `a${ ``, `` }b` ``.
|
|
330
|
+
if (node.type === 'TemplateElement') {
|
|
331
|
+
const end_offset = node.tail ? 1 : 2;
|
|
332
|
+
node.start -= 1;
|
|
333
|
+
node.end += end_offset;
|
|
334
|
+
node.range = [node.start, node.end];
|
|
335
|
+
node.loc = {
|
|
336
|
+
start: { line: node.loc.start.line, column: node.loc.start.column - 1 },
|
|
337
|
+
end: { line: node.loc.end.line, column: node.loc.end.column + end_offset },
|
|
338
|
+
};
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
if (node.type === 'JSXText' && node.end > node.start) {
|
|
342
|
+
texts.push({ type: 'JSXText', start: node.start, end: node.end });
|
|
343
|
+
}
|
|
344
|
+
|
|
58
345
|
for (const key of Object.keys(node)) {
|
|
59
346
|
if (key === 'parent' || key === 'loc' || key === 'range') continue;
|
|
60
347
|
const value = node[key];
|
|
@@ -67,13 +354,14 @@ function normalize_tsrx_ast_for_eslint(ast: any): void {
|
|
|
67
354
|
};
|
|
68
355
|
|
|
69
356
|
visit(ast);
|
|
357
|
+
return texts.sort((a, b) => a.start - b.start);
|
|
70
358
|
}
|
|
71
359
|
|
|
72
360
|
/**
|
|
73
361
|
* Recursively walks the AST and ensures all nodes have range and loc properties
|
|
74
362
|
* ESLint's scope analyzer requires these properties on ALL nodes
|
|
75
363
|
*/
|
|
76
|
-
function ensure_node_properties(node: any,
|
|
364
|
+
function ensure_node_properties(node: any, locate: Locate): void {
|
|
77
365
|
if (!node || typeof node !== 'object') {
|
|
78
366
|
return;
|
|
79
367
|
}
|
|
@@ -85,38 +373,7 @@ function ensure_node_properties(node: any, code: string): void {
|
|
|
85
373
|
|
|
86
374
|
// Ensure loc property exists
|
|
87
375
|
if (!node.loc && node.start !== undefined && node.end !== undefined) {
|
|
88
|
-
|
|
89
|
-
let current_pos = 0;
|
|
90
|
-
let start_line = 1;
|
|
91
|
-
let start_column = 0;
|
|
92
|
-
let end_line = 1;
|
|
93
|
-
let end_column = 0;
|
|
94
|
-
|
|
95
|
-
for (let i = 0; i < lines.length; i++) {
|
|
96
|
-
const line_length = lines[i].length + 1;
|
|
97
|
-
if (current_pos + line_length > node.start) {
|
|
98
|
-
start_line = i + 1;
|
|
99
|
-
start_column = node.start - current_pos;
|
|
100
|
-
break;
|
|
101
|
-
}
|
|
102
|
-
current_pos += line_length;
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
current_pos = 0;
|
|
106
|
-
for (let i = 0; i < lines.length; i++) {
|
|
107
|
-
const line_length = lines[i].length + 1;
|
|
108
|
-
if (current_pos + line_length > node.end) {
|
|
109
|
-
end_line = i + 1;
|
|
110
|
-
end_column = node.end - current_pos;
|
|
111
|
-
break;
|
|
112
|
-
}
|
|
113
|
-
current_pos += line_length;
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
node.loc = {
|
|
117
|
-
start: { line: start_line, column: start_column },
|
|
118
|
-
end: { line: end_line, column: end_column },
|
|
119
|
-
};
|
|
376
|
+
node.loc = locate(node.start, node.end);
|
|
120
377
|
}
|
|
121
378
|
|
|
122
379
|
for (const key in node) {
|
|
@@ -126,11 +383,249 @@ function ensure_node_properties(node: any, code: string): void {
|
|
|
126
383
|
|
|
127
384
|
const value = node[key];
|
|
128
385
|
if (Array.isArray(value)) {
|
|
129
|
-
value.forEach((child) => ensure_node_properties(child,
|
|
386
|
+
value.forEach((child) => ensure_node_properties(child, locate));
|
|
130
387
|
} else if (value && typeof value === 'object' && value.type) {
|
|
131
|
-
ensure_node_properties(value,
|
|
388
|
+
ensure_node_properties(value, locate);
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
/** The fields read from an acorn token recorded by the TSRX parser. */
|
|
394
|
+
interface LexerToken {
|
|
395
|
+
type: { label: string; keyword?: string };
|
|
396
|
+
value?: any;
|
|
397
|
+
start: number;
|
|
398
|
+
end: number;
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
/** A comment as the TSRX parser collects it. */
|
|
402
|
+
interface ParserComment {
|
|
403
|
+
type: 'Line' | 'Block';
|
|
404
|
+
start: number;
|
|
405
|
+
end: number;
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
interface ESLintToken extends AST.Token {
|
|
409
|
+
start: number;
|
|
410
|
+
end: number;
|
|
411
|
+
regex?: { pattern: string; flags: string };
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
interface ESLintComment {
|
|
415
|
+
type: 'Line' | 'Block';
|
|
416
|
+
value: string;
|
|
417
|
+
start: number;
|
|
418
|
+
end: number;
|
|
419
|
+
range: AST.Range;
|
|
420
|
+
loc: AST.SourceLocation;
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
interface Span {
|
|
424
|
+
type: AST.TokenType;
|
|
425
|
+
start: number;
|
|
426
|
+
end: number;
|
|
427
|
+
regex?: ESLintToken['regex'];
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
type Locate = (start: number, end: number) => AST.SourceLocation;
|
|
431
|
+
|
|
432
|
+
/**
|
|
433
|
+
* Builds `loc` objects from offsets, with the line terminators acorn and ESLint
|
|
434
|
+
* count.
|
|
435
|
+
*/
|
|
436
|
+
function create_locator(code: string): Locate {
|
|
437
|
+
const line_starts = [0];
|
|
438
|
+
for (const match of code.matchAll(/\r\n?|[\n\u2028\u2029]/g)) {
|
|
439
|
+
line_starts.push(match.index + match[0].length);
|
|
440
|
+
}
|
|
441
|
+
const position = (offset: number) => {
|
|
442
|
+
let low = 0;
|
|
443
|
+
let high = line_starts.length - 1;
|
|
444
|
+
while (low < high) {
|
|
445
|
+
const middle = (low + high + 1) >> 1;
|
|
446
|
+
if (line_starts[middle] <= offset) low = middle;
|
|
447
|
+
else high = middle - 1;
|
|
448
|
+
}
|
|
449
|
+
return { line: low + 1, column: offset - line_starts[low] };
|
|
450
|
+
};
|
|
451
|
+
return (start, end) => ({ start: position(start), end: position(end) });
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
/**
|
|
455
|
+
* Converts the parser's comments to ESLint comments, in source order. The value
|
|
456
|
+
* is read from the source: the parser strips the indentation from the value of
|
|
457
|
+
* a multi-line block comment.
|
|
458
|
+
*/
|
|
459
|
+
function to_eslint_comments(
|
|
460
|
+
code: string,
|
|
461
|
+
comments: ParserComment[],
|
|
462
|
+
locate: Locate,
|
|
463
|
+
): ESLintComment[] {
|
|
464
|
+
const result: ESLintComment[] = [];
|
|
465
|
+
for (const { type, start, end } of [...comments].sort((a, b) => a.start - b.start)) {
|
|
466
|
+
if (result.at(-1)?.start === start) continue;
|
|
467
|
+
const value_end = type === 'Block' && code.startsWith('*/', end - 2) ? end - 2 : end;
|
|
468
|
+
result.push({
|
|
469
|
+
type,
|
|
470
|
+
value: code.slice(start + 2, value_end),
|
|
471
|
+
start,
|
|
472
|
+
end,
|
|
473
|
+
range: [start, end],
|
|
474
|
+
loc: locate(start, end),
|
|
475
|
+
});
|
|
476
|
+
}
|
|
477
|
+
return result;
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
/**
|
|
481
|
+
* Converts the tokens the TSRX lexer reported into the token list ESLint
|
|
482
|
+
* expects: in source order, without overlaps, in espree's token types, and
|
|
483
|
+
* covering every character that is not whitespace or a comment.
|
|
484
|
+
*/
|
|
485
|
+
function to_eslint_tokens(
|
|
486
|
+
code: string,
|
|
487
|
+
lexer_tokens: LexerToken[],
|
|
488
|
+
texts: Span[],
|
|
489
|
+
comments: ESLintComment[],
|
|
490
|
+
locate: Locate,
|
|
491
|
+
): ESLintToken[] {
|
|
492
|
+
// The lexer reports a token again when it re-reads it after looking ahead.
|
|
493
|
+
const lexed: LexerToken[] = [];
|
|
494
|
+
for (const token of [...lexer_tokens].sort((a, b) => a.start - b.start || a.end - b.end)) {
|
|
495
|
+
const last = lexed.at(-1);
|
|
496
|
+
if (last?.start === token.start && last.end === token.end) {
|
|
497
|
+
lexed[lexed.length - 1] = token;
|
|
498
|
+
} else if (!last || token.start >= last.end) {
|
|
499
|
+
lexed.push(token);
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
const spans: Span[] = [];
|
|
504
|
+
for (let i = 0; i < lexed.length; i++) {
|
|
505
|
+
const token = lexed[i];
|
|
506
|
+
const label = token.type.label;
|
|
507
|
+
|
|
508
|
+
if (label === '`' || (label === '}' && is_template_part(lexed[i + 1]))) {
|
|
509
|
+
// Like espree, one token per template chunk: `` `a${ ``, `` }b${ ``, `` }c` ``.
|
|
510
|
+
let last = i + 1;
|
|
511
|
+
while (is_template_part(lexed[last])) last++;
|
|
512
|
+
const closer = lexed[last]?.type.label;
|
|
513
|
+
if (closer !== '${' && closer !== '`') last--;
|
|
514
|
+
spans.push({ type: 'Template', start: token.start, end: lexed[last].end });
|
|
515
|
+
i = last;
|
|
516
|
+
continue;
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
if (code.startsWith('</', token.start) && token.end > token.start + 1) {
|
|
520
|
+
// The lexer skips the body of a raw `<style>` or `<script>` element and
|
|
521
|
+
// reports its closing tag as one token.
|
|
522
|
+
for (const match of code.slice(token.start, token.end).matchAll(/([</>])|[^\s</>]+/g)) {
|
|
523
|
+
const start = token.start + match.index;
|
|
524
|
+
spans.push({
|
|
525
|
+
type: match[1] ? 'Punctuator' : 'JSXIdentifier',
|
|
526
|
+
start,
|
|
527
|
+
end: start + match[0].length,
|
|
528
|
+
});
|
|
529
|
+
}
|
|
530
|
+
continue;
|
|
132
531
|
}
|
|
532
|
+
|
|
533
|
+
if (label === 'eof' || token.start === token.end) continue;
|
|
534
|
+
spans.push({
|
|
535
|
+
type: token_type(token, lexed[i - 1], lexed[i - 2]),
|
|
536
|
+
start: token.start,
|
|
537
|
+
end: token.end,
|
|
538
|
+
regex:
|
|
539
|
+
label === 'regexp' ? { pattern: token.value.pattern, flags: token.value.flags } : undefined,
|
|
540
|
+
});
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
// Each JSX text node is one token. The lexer reports no token for
|
|
544
|
+
// whitespace-only text, and reads text after a template directive's block
|
|
545
|
+
// as code (`Identifier " hello"`).
|
|
546
|
+
const with_texts = [...outside(spans, texts), ...texts].sort((a, b) => a.start - b.start);
|
|
547
|
+
// Text the lexer read as part of a comment is left to the gap filling below.
|
|
548
|
+
const kept = outside(with_texts, comments);
|
|
549
|
+
|
|
550
|
+
const tokens: ESLintToken[] = [];
|
|
551
|
+
const add = (span: Span) => {
|
|
552
|
+
const token: ESLintToken = {
|
|
553
|
+
type: span.type,
|
|
554
|
+
value: code.slice(span.start, span.end),
|
|
555
|
+
start: span.start,
|
|
556
|
+
end: span.end,
|
|
557
|
+
range: [span.start, span.end],
|
|
558
|
+
loc: locate(span.start, span.end),
|
|
559
|
+
};
|
|
560
|
+
if (span.regex) token.regex = span.regex;
|
|
561
|
+
tokens.push(token);
|
|
562
|
+
};
|
|
563
|
+
|
|
564
|
+
// The lexer reports no token for the `@` of a template directive or the
|
|
565
|
+
// body of a raw `<style>` or `<script>` element.
|
|
566
|
+
const fill = (start: number, end: number) => {
|
|
567
|
+
const at = end > start && code[end - 1] === '@';
|
|
568
|
+
if (at) end--;
|
|
569
|
+
if (/\S/.test(code.slice(start, end))) add({ type: 'JSXText', start, end });
|
|
570
|
+
if (at) add({ type: 'Punctuator', start: end, end: end + 1 });
|
|
571
|
+
};
|
|
572
|
+
|
|
573
|
+
const covered: Array<Span | ESLintComment> = [...kept, ...comments];
|
|
574
|
+
let position = 0;
|
|
575
|
+
for (const item of covered.sort((a, b) => a.start - b.start)) {
|
|
576
|
+
fill(position, item.start);
|
|
577
|
+
if (!('value' in item)) add(item);
|
|
578
|
+
position = item.end;
|
|
579
|
+
}
|
|
580
|
+
fill(position, code.length);
|
|
581
|
+
|
|
582
|
+
return tokens;
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
/** The spans that overlap none of the sorted, disjoint `ranges`. */
|
|
586
|
+
function outside(spans: Span[], ranges: Array<{ start: number; end: number }>): Span[] {
|
|
587
|
+
let index = 0;
|
|
588
|
+
return spans.filter((span) => {
|
|
589
|
+
while (index < ranges.length && ranges[index].end <= span.start) index++;
|
|
590
|
+
return index === ranges.length || ranges[index].start >= span.end;
|
|
591
|
+
});
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
function is_template_part(token: LexerToken | undefined): boolean {
|
|
595
|
+
return token?.type.label === 'template' || token?.type.label === 'invalidTemplate';
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
/** The espree token type of an acorn token. */
|
|
599
|
+
function token_type(
|
|
600
|
+
token: LexerToken,
|
|
601
|
+
previous: LexerToken | undefined,
|
|
602
|
+
before_previous: LexerToken | undefined,
|
|
603
|
+
): AST.TokenType {
|
|
604
|
+
const { label, keyword } = token.type;
|
|
605
|
+
switch (label) {
|
|
606
|
+
case 'name':
|
|
607
|
+
return token.value === 'static' || token.value === 'yield' || token.value === 'let'
|
|
608
|
+
? 'Keyword'
|
|
609
|
+
: 'Identifier';
|
|
610
|
+
case 'privateId':
|
|
611
|
+
return 'PrivateIdentifier';
|
|
612
|
+
case 'jsxName':
|
|
613
|
+
return 'JSXIdentifier';
|
|
614
|
+
case 'jsxText':
|
|
615
|
+
return 'JSXText';
|
|
616
|
+
case 'num':
|
|
617
|
+
return 'Numeric';
|
|
618
|
+
case 'regexp':
|
|
619
|
+
return 'RegularExpression';
|
|
620
|
+
case 'string':
|
|
621
|
+
// A JSX attribute value, as in espree.
|
|
622
|
+
return previous?.type.label === '=' && before_previous?.type.label === 'jsxName'
|
|
623
|
+
? 'JSXText'
|
|
624
|
+
: 'String';
|
|
133
625
|
}
|
|
626
|
+
if (keyword === 'true' || keyword === 'false') return 'Boolean';
|
|
627
|
+
if (keyword === 'null') return 'Null';
|
|
628
|
+
return keyword ? 'Keyword' : 'Punctuator';
|
|
134
629
|
}
|
|
135
630
|
|
|
136
631
|
function is_fatal_parser_diagnostic(error: any): boolean {
|
|
@@ -170,8 +665,13 @@ export function parseForESLint(code: string, options?: Linter.ParserOptions): Pa
|
|
|
170
665
|
collect: true,
|
|
171
666
|
errors,
|
|
172
667
|
comments,
|
|
668
|
+
// Also records every token, as `tsrx_tokens`.
|
|
669
|
+
keywordTokens: true,
|
|
173
670
|
}) as any;
|
|
174
671
|
if (!ast) throw new Error('Parser returned null or undefined AST');
|
|
672
|
+
const lexer_tokens = ast.tsrx_tokens;
|
|
673
|
+
delete ast.tsrx_tokens;
|
|
674
|
+
delete ast.tsrx_keyword_tokens;
|
|
175
675
|
analyze_tsrx(ast, options?.filePath || 'ESLintParser.tsrx', {
|
|
176
676
|
collect: true,
|
|
177
677
|
errors,
|
|
@@ -184,10 +684,13 @@ export function parseForESLint(code: string, options?: Linter.ParserOptions): Pa
|
|
|
184
684
|
}
|
|
185
685
|
|
|
186
686
|
// Normalize for ESLint traversal (avoid duplicate node visits)
|
|
187
|
-
normalize_tsrx_ast_for_eslint(ast);
|
|
687
|
+
const texts = normalize_tsrx_ast_for_eslint(ast, code);
|
|
188
688
|
|
|
189
689
|
// Recursively ensure all nodes have range and loc properties
|
|
190
|
-
|
|
690
|
+
const locate = create_locator(code);
|
|
691
|
+
ensure_node_properties(ast, locate);
|
|
692
|
+
|
|
693
|
+
const eslint_comments = to_eslint_comments(code, comments, locate);
|
|
191
694
|
|
|
192
695
|
// Create a properly structured AST object ensuring all required properties exist
|
|
193
696
|
const result: any = {
|
|
@@ -201,8 +704,8 @@ export function parseForESLint(code: string, options?: Linter.ParserOptions): Pa
|
|
|
201
704
|
range: ast.range || [0, code.length],
|
|
202
705
|
body: ast.body || [],
|
|
203
706
|
sourceType: ast.sourceType || 'module',
|
|
204
|
-
comments:
|
|
205
|
-
tokens:
|
|
707
|
+
comments: eslint_comments,
|
|
708
|
+
tokens: to_eslint_tokens(code, lexer_tokens, texts, eslint_comments, locate),
|
|
206
709
|
};
|
|
207
710
|
|
|
208
711
|
return {
|
|
@@ -210,6 +713,7 @@ export function parseForESLint(code: string, options?: Linter.ParserOptions): Pa
|
|
|
210
713
|
services: {
|
|
211
714
|
tsrxDiagnostics: errors,
|
|
212
715
|
},
|
|
716
|
+
scopeManager: analyze_scope(result, options),
|
|
213
717
|
visitorKeys,
|
|
214
718
|
};
|
|
215
719
|
} catch (error: any) {
|