forked from eslint-community/eslint-plugin-eslint-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.js
521 lines (471 loc) · 20 KB
/
utils.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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
'use strict';
const { getStaticValue } = require('eslint-utils');
const estraverse = require('estraverse');
/**
* Determines whether a node is a 'normal' (i.e. non-async, non-generator) function expression.
* @param {ASTNode} node The node in question
* @returns {boolean} `true` if the node is a normal function expression
*/
function isNormalFunctionExpression (node) {
const functionTypes = [
'FunctionExpression',
'ArrowFunctionExpression',
'FunctionDeclaration',
];
return functionTypes.includes(node.type) && !node.generator && !node.async;
}
/**
* Determines whether a node is a reference to function expression.
* @param {ASTNode} node The node in question
* @param {ScopeManager} scopeManager The scope manager to use for resolving references
* @returns {boolean} `true` if the node is a reference to a function expression
*/
function isNormalFunctionExpressionReference (node, scopeManager) {
if (!node || !scopeManager) {
return false;
}
if (node.type !== 'Identifier') {
return false;
}
const scope = scopeManager.acquire(node) || scopeManager.globalScope;
const scopes = [scope];
let createReference;
while (scopes.length > 0) {
const currentScope = scopes.shift();
const found = currentScope.references.find(reference => {
return reference.resolved && reference.identifier === node;
});
if (found) {
createReference = found;
break;
}
scopes.push(...currentScope.childScopes);
}
if (!createReference) {
return false;
}
const definitions = createReference.resolved.defs;
if (!definitions || definitions.length === 0) {
return false;
}
// Assumes it is immediately initialized to a function
let definitionNode = definitions[0].node;
// If we find something like `const create = () => {}` then send the
// righthand side into the type check.
if (definitionNode.type === 'VariableDeclarator') {
definitionNode = definitionNode.init;
}
return isNormalFunctionExpression(definitionNode);
}
/**
* Determines whether a node is constructing a RuleTester instance
* @param {ASTNode} node The node in question
* @returns {boolean} `true` if the node is probably constructing a RuleTester instance
*/
function isRuleTesterConstruction (node) {
return node.type === 'NewExpression' && (
(node.callee.type === 'Identifier' && node.callee.name === 'RuleTester') ||
(node.callee.type === 'MemberExpression' &&
node.callee.property.type === 'Identifier' &&
node.callee.property.name === 'RuleTester')
);
}
const INTERESTING_RULE_KEYS = new Set(['create', 'meta']);
/**
* Collect properties from an object that have interesting key names into a new object
* @param {Node[]} properties
* @param {Set<String>} interestingKeys
* @returns Object
*/
function collectInterestingProperties (properties, interestingKeys) {
// eslint-disable-next-line unicorn/prefer-object-from-entries
return properties.reduce((parsedProps, prop) => {
const keyValue = module.exports.getKeyName(prop);
if (interestingKeys.has(keyValue)) {
// In TypeScript, unwrap any usage of `{} as const`.
parsedProps[keyValue] = prop.value.type === 'TSAsExpression' ? prop.value.expression : prop.value;
}
return parsedProps;
}, {});
}
/**
* Check if there is a return statement that returns an object somewhere inside the given node.
* @param {Node} node
* @returns {boolean}
*/
function hasObjectReturn (node) {
let foundMatch = false;
estraverse.traverse(node, {
enter (child) {
if (child.type === 'ReturnStatement' && child.argument && child.argument.type === 'ObjectExpression') {
foundMatch = true;
}
},
fallback: 'iteration', // Don't crash on unexpected node types.
});
return foundMatch;
}
/**
* Determine if the given node is likely to be a function-style rule.
* @param {*} node
* @returns {boolean}
*/
function isFunctionRule (node) {
return (
isNormalFunctionExpression(node) && // Is a function definition.
node.params.length === 1 && // The function has a single `context` argument.
hasObjectReturn(node) // Returns an object containing the visitor functions.
);
}
/**
* Helper for `getRuleInfo`. Handles ESM and TypeScript rules.
*/
function getRuleExportsESM (ast) {
return ast.body
.filter(statement => statement.type === 'ExportDefaultDeclaration')
.map(statement => statement.declaration)
// eslint-disable-next-line unicorn/prefer-object-from-entries
.reduce((currentExports, node) => {
if (node.type === 'ObjectExpression') {
// Check `export default { create() {}, meta: {} }`
return collectInterestingProperties(node.properties, INTERESTING_RULE_KEYS);
} else if (isFunctionRule(node)) {
// Check `export default function(context) { return { ... }; }`
return { create: node, meta: null, isNewStyle: false };
} else if (
node.type === 'CallExpression' &&
node.arguments.length === 1 &&
node.arguments[0].type === 'ObjectExpression' &&
// Check various TypeScript rule helper formats.
(
// createESLintRule({ ... })
node.callee.type === 'Identifier' ||
// util.createRule({ ... })
(node.callee.type === 'MemberExpression' && node.callee.object.type === 'Identifier' && node.callee.property.type === 'Identifier') ||
// ESLintUtils.RuleCreator(docsUrl)({ ... })
(node.callee.type === 'CallExpression' && node.callee.callee.type === 'MemberExpression' && node.callee.callee.object.type === 'Identifier' && node.callee.callee.property.type === 'Identifier')
)
) {
// Check `export default someTypeScriptHelper({ create() {}, meta: {} });
return collectInterestingProperties(node.arguments[0].properties, INTERESTING_RULE_KEYS);
}
return currentExports;
}, {});
}
/**
* Helper for `getRuleInfo`. Handles CJS rules.
*/
function getRuleExportsCJS (ast) {
let exportsVarOverridden = false;
let exportsIsFunction = false;
return ast.body
.filter(statement => statement.type === 'ExpressionStatement')
.map(statement => statement.expression)
.filter(expression => expression.type === 'AssignmentExpression')
.filter(expression => expression.left.type === 'MemberExpression')
// eslint-disable-next-line unicorn/prefer-object-from-entries
.reduce((currentExports, node) => {
if (
node.left.object.type === 'Identifier' && node.left.object.name === 'module' &&
node.left.property.type === 'Identifier' && node.left.property.name === 'exports'
) {
exportsVarOverridden = true;
if (isFunctionRule(node.right)) {
// Check `module.exports = function (context) { return { ... }; }`
exportsIsFunction = true;
return { create: node.right, meta: null, isNewStyle: false };
} else if (node.right.type === 'ObjectExpression') {
// Check `module.exports = { create: function () {}, meta: {} }`
return collectInterestingProperties(node.right.properties, INTERESTING_RULE_KEYS);
}
return {};
} else if (
!exportsIsFunction &&
node.left.object.type === 'MemberExpression' &&
node.left.object.object.type === 'Identifier' && node.left.object.object.name === 'module' &&
node.left.object.property.type === 'Identifier' && node.left.object.property.name === 'exports' &&
node.left.property.type === 'Identifier' && INTERESTING_RULE_KEYS.has(node.left.property.name)
) {
// Check `module.exports.create = () => {}`
currentExports[node.left.property.name] = node.right;
} else if (
!exportsVarOverridden &&
node.left.object.type === 'Identifier' && node.left.object.name === 'exports' &&
node.left.property.type === 'Identifier' && INTERESTING_RULE_KEYS.has(node.left.property.name)
) {
// Check `exports.create = () => {}`
currentExports[node.left.property.name] = node.right;
}
return currentExports;
}, {});
}
/**
* Find the value of a property in an object by its property key name.
* @param {Object} obj
* @param {String} keyName
* @returns property value
*/
function findObjectPropertyValueByKeyName (obj, keyName) {
const property = obj.properties.find(prop => prop.key.type === 'Identifier' && prop.key.name === keyName);
return property ? property.value : undefined;
}
module.exports = {
/**
* Performs static analysis on an AST to try to determine the final value of `module.exports`.
* @param {{ast: ASTNode, scopeManager?: ScopeManager}} sourceCode The object contains `Program` AST node, and optional `scopeManager`
* @returns {Object} An object with keys `meta`, `create`, and `isNewStyle`. `meta` and `create` correspond to the AST nodes
for the final values of `module.exports.meta` and `module.exports.create`. `isNewStyle` will be `true` if `module.exports`
is an object, and `false` if module.exports is just the `create` function. If no valid ESLint rule info can be extracted
from the file, the return value will be `null`.
*/
getRuleInfo ({ ast, scopeManager }) {
const exportNodes = ast.sourceType === 'module' ? getRuleExportsESM(ast) : getRuleExportsCJS(ast);
const createExists = Object.prototype.hasOwnProperty.call(exportNodes, 'create');
if (!createExists) {
return null;
}
const createIsFunction = isNormalFunctionExpression(exportNodes.create);
const createIsFunctionReference = isNormalFunctionExpressionReference(exportNodes.create, scopeManager);
if (!createIsFunction && !createIsFunctionReference) {
return null;
}
return Object.assign({ isNewStyle: true, meta: null }, exportNodes);
},
/**
* Gets all the identifiers referring to the `context` variable in a rule source file. Note that this function will
* only work correctly after traversing the AST has started (e.g. in the first `Program` node).
* @param {RuleContext} context The `context` variable for the source file itself
* @param {ASTNode} ast The `Program` node for the file
* @returns {Set<ASTNode>} A Set of all `Identifier` nodes that are references to the `context` value for the file
*/
getContextIdentifiers (context, ast) {
const ruleInfo = module.exports.getRuleInfo({ ast });
if (!ruleInfo || ruleInfo.create.params.length === 0 || ruleInfo.create.params[0].type !== 'Identifier') {
return new Set();
}
return new Set(
context.getDeclaredVariables(ruleInfo.create)
.find(variable => variable.name === ruleInfo.create.params[0].name)
.references
.map(ref => ref.identifier)
);
},
/**
* Gets the key name of a Property, if it can be determined statically.
* @param {ASTNode} node The `Property` node
* @returns {string|null} The key name, or `null` if the name cannot be determined statically.
*/
getKeyName (property) {
if (!property.key) {
// likely a SpreadElement or another non-standard node
return null;
}
if (!property.computed && property.key.type === 'Identifier') {
return property.key.name;
}
if (property.key.type === 'Literal') {
return '' + property.key.value;
}
if (property.key.type === 'TemplateLiteral' && property.key.quasis.length === 1) {
return property.key.quasis[0].value.cooked;
}
return null;
},
/**
* Performs static analysis on an AST to try to find test cases
* @param {RuleContext} context The `context` variable for the source file itself
* @param {ASTNode} ast The `Program` node for the file.
* @returns {object} An object with `valid` and `invalid` keys containing a list of AST nodes corresponding to tests
*/
getTestInfo (context, ast) {
const runCalls = [];
const variableIdentifiers = new Set();
ast.body.forEach(statement => {
if (statement.type === 'VariableDeclaration') {
statement.declarations.forEach(declarator => {
if (declarator.init && isRuleTesterConstruction(declarator.init) && declarator.id.type === 'Identifier') {
context.getDeclaredVariables(declarator).forEach(variable => {
variable.references.filter(ref => ref.isRead()).forEach(ref => variableIdentifiers.add(ref.identifier));
});
}
});
}
if (
statement.type === 'ExpressionStatement' &&
statement.expression.type === 'CallExpression' &&
statement.expression.callee.type === 'MemberExpression' &&
(
isRuleTesterConstruction(statement.expression.callee.object) ||
variableIdentifiers.has(statement.expression.callee.object)
) &&
statement.expression.callee.property.type === 'Identifier' &&
statement.expression.callee.property.name === 'run'
) {
runCalls.push(statement.expression);
}
});
return runCalls
.filter(call => call.arguments.length >= 3 && call.arguments[2].type === 'ObjectExpression')
.map(call => call.arguments[2])
.map(run => {
const validProperty = run.properties.find(prop => module.exports.getKeyName(prop) === 'valid');
const invalidProperty = run.properties.find(prop => module.exports.getKeyName(prop) === 'invalid');
return {
valid: validProperty && validProperty.value.type === 'ArrayExpression' ? validProperty.value.elements.filter(Boolean) : [],
invalid: invalidProperty && invalidProperty.value.type === 'ArrayExpression' ? invalidProperty.value.elements.filter(Boolean) : [],
};
});
},
/**
* Gets information on a report, given the arguments passed to context.report().
* @param {ASTNode[]} reportArgs The arguments passed to context.report()
* @param {Context} context
*/
getReportInfo (reportArgs, context) {
// If there is exactly one argument, the API expects an object.
// Otherwise, if the second argument is a string, the arguments are interpreted as
// ['node', 'message', 'data', 'fix'].
// Otherwise, the arguments are interpreted as ['node', 'loc', 'message', 'data', 'fix'].
if (reportArgs.length === 0) {
return null;
}
if (reportArgs.length === 1) {
if (reportArgs[0].type === 'ObjectExpression') {
// eslint-disable-next-line unicorn/prefer-object-from-entries
return reportArgs[0].properties.reduce((reportInfo, property) => {
const propName = module.exports.getKeyName(property);
if (propName !== null) {
return Object.assign(reportInfo, { [propName]: property.value });
}
return reportInfo;
}, {});
}
return null;
}
let keys;
const secondArgStaticValue = getStaticValue(reportArgs[1], context.getScope());
if (
(secondArgStaticValue && typeof secondArgStaticValue.value === 'string') ||
reportArgs[1].type === 'TemplateLiteral'
) {
keys = ['node', 'message', 'data', 'fix'];
} else if (
reportArgs[1].type === 'ObjectExpression' ||
reportArgs[1].type === 'ArrayExpression' ||
(reportArgs[1].type === 'Literal' && typeof reportArgs[1].value !== 'string') ||
(secondArgStaticValue && ['object', 'number'].includes(typeof secondArgStaticValue.value))
) {
keys = ['node', 'loc', 'message', 'data', 'fix'];
} else {
// Otherwise, we can't statically determine what argument means what, so no safe fix is possible.
return null;
}
return Object.fromEntries(keys
.slice(0, reportArgs.length)
.map((key, index) => [key, reportArgs[index]]));
},
/**
* Gets a set of all `sourceCode` identifiers.
* @param {RuleContext} context The context for the rule file
* @param {ASTNode} ast The AST of the file. This must have `parent` properties.
* @returns {Set<ASTNode>} A set of all identifiers referring to the `SourceCode` object.
*/
getSourceCodeIdentifiers (context, ast) {
return new Set([...module.exports.getContextIdentifiers(context, ast)]
.filter(identifier => identifier.parent &&
identifier.parent.type === 'MemberExpression' &&
identifier === identifier.parent.object &&
identifier.parent.property.type === 'Identifier' &&
identifier.parent.property.name === 'getSourceCode' &&
identifier.parent.parent.type === 'CallExpression' &&
identifier.parent === identifier.parent.parent.callee &&
identifier.parent.parent.parent.type === 'VariableDeclarator' &&
identifier.parent.parent === identifier.parent.parent.parent.init &&
identifier.parent.parent.parent.id.type === 'Identifier'
)
.flatMap(identifier => context.getDeclaredVariables(identifier.parent.parent.parent))
.flatMap(variable => variable.references)
.map(ref => ref.identifier));
},
/**
* Insert a given property into a given object literal.
* @param {SourceCodeFixer} fixer The fixer.
* @param {Node} node The ObjectExpression node to insert a property.
* @param {string} propertyText The property code to insert.
* @returns {void}
*/
insertProperty (fixer, node, propertyText, sourceCode) {
if (node.properties.length === 0) {
return fixer.replaceText(node, `{\n${propertyText}\n}`);
}
return fixer.insertTextAfter(
sourceCode.getLastToken(node.properties[node.properties.length - 1]),
`,\n${propertyText}`
);
},
/**
* Collect all context.report({...}) violation/suggestion-related nodes into a standardized array for convenience.
* @param {Object} reportInfo - Result of getReportInfo().
* @returns {messageId?: String, message?: String, data?: Object, fix?: Function}[]
*/
collectReportViolationAndSuggestionData (reportInfo) {
return [
// Violation message
{
messageId: reportInfo.messageId,
message: reportInfo.message,
data: reportInfo.data,
fix: reportInfo.fix,
},
// Suggestion messages
...((reportInfo.suggest && reportInfo.suggest.elements) || [])
.map(suggestObjNode => {
return {
messageId: findObjectPropertyValueByKeyName(suggestObjNode, 'messageId'),
message: findObjectPropertyValueByKeyName(suggestObjNode, 'desc'), // Note: suggestion message named `desc`
data: findObjectPropertyValueByKeyName(suggestObjNode, 'data'),
fix: findObjectPropertyValueByKeyName(suggestObjNode, 'fix'),
};
}
),
];
},
/**
* Whether the provided node represents an autofixer function.
* @param {Node} node
* @param {Node[]} contextIdentifiers
* @returns {boolean}
*/
isAutoFixerFunction (node, contextIdentifiers) {
const parent = node.parent;
return ['FunctionExpression', 'ArrowFunctionExpression'].includes(node.type) &&
parent.parent.type === 'ObjectExpression' &&
parent.parent.parent.type === 'CallExpression' &&
contextIdentifiers.has(parent.parent.parent.callee.object) &&
parent.parent.parent.callee.property.name === 'report' &&
module.exports.getReportInfo(parent.parent.parent.arguments).fix === node;
},
/**
* Whether the provided node represents a suggestion fixer function.
* @param {Node} node
* @param {Node[]} contextIdentifiers
* @returns {boolean}
*/
isSuggestionFixerFunction (node, contextIdentifiers) {
const parent = node.parent;
return (node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression') &&
parent.type === 'Property' &&
parent.key.type === 'Identifier' &&
parent.key.name === 'fix' &&
parent.parent.type === 'ObjectExpression' &&
parent.parent.parent.type === 'ArrayExpression' &&
parent.parent.parent.parent.type === 'Property' &&
parent.parent.parent.parent.key.type === 'Identifier' &&
parent.parent.parent.parent.key.name === 'suggest' &&
parent.parent.parent.parent.parent.type === 'ObjectExpression' &&
parent.parent.parent.parent.parent.parent.type === 'CallExpression' &&
contextIdentifiers.has(parent.parent.parent.parent.parent.parent.callee.object) &&
parent.parent.parent.parent.parent.parent.callee.property.name === 'report' &&
module.exports.getReportInfo(parent.parent.parent.parent.parent.parent.arguments).suggest === parent.parent.parent;
},
};