blob: 68c07da4ed99e72e8866df0d473237e64037effa [file] [log] [blame]
Yang Guo4fd355c2019-09-19 10:59:03 +02001/**
2 * @fileoverview A rule to suggest using of const declaration for variables that are never reassigned after declared.
3 * @author Toru Nagashima
4 */
5
6"use strict";
7
8const astUtils = require("./utils/ast-utils");
9
10//------------------------------------------------------------------------------
11// Helpers
12//------------------------------------------------------------------------------
13
14const PATTERN_TYPE = /^(?:.+?Pattern|RestElement|SpreadProperty|ExperimentalRestProperty|Property)$/u;
15const DECLARATION_HOST_TYPE = /^(?:Program|BlockStatement|SwitchCase)$/u;
16const DESTRUCTURING_HOST_TYPE = /^(?:VariableDeclarator|AssignmentExpression)$/u;
17
18/**
19 * Checks whether a given node is located at `ForStatement.init` or not.
20 *
21 * @param {ASTNode} node - A node to check.
22 * @returns {boolean} `true` if the node is located at `ForStatement.init`.
23 */
24function isInitOfForStatement(node) {
25 return node.parent.type === "ForStatement" && node.parent.init === node;
26}
27
28/**
29 * Checks whether a given Identifier node becomes a VariableDeclaration or not.
30 *
31 * @param {ASTNode} identifier - An Identifier node to check.
32 * @returns {boolean} `true` if the node can become a VariableDeclaration.
33 */
34function canBecomeVariableDeclaration(identifier) {
35 let node = identifier.parent;
36
37 while (PATTERN_TYPE.test(node.type)) {
38 node = node.parent;
39 }
40
41 return (
42 node.type === "VariableDeclarator" ||
43 (
44 node.type === "AssignmentExpression" &&
45 node.parent.type === "ExpressionStatement" &&
46 DECLARATION_HOST_TYPE.test(node.parent.parent.type)
47 )
48 );
49}
50
51/**
52 * Checks if an property or element is from outer scope or function parameters
53 * in destructing pattern.
54 *
55 * @param {string} name - A variable name to be checked.
56 * @param {eslint-scope.Scope} initScope - A scope to start find.
57 * @returns {boolean} Indicates if the variable is from outer scope or function parameters.
58 */
59function isOuterVariableInDestructing(name, initScope) {
60
61 if (initScope.through.find(ref => ref.resolved && ref.resolved.name === name)) {
62 return true;
63 }
64
65 const variable = astUtils.getVariableByName(initScope, name);
66
67 if (variable !== null) {
68 return variable.defs.some(def => def.type === "Parameter");
69 }
70
71 return false;
72}
73
74/**
75 * Gets the VariableDeclarator/AssignmentExpression node that a given reference
76 * belongs to.
77 * This is used to detect a mix of reassigned and never reassigned in a
78 * destructuring.
79 *
80 * @param {eslint-scope.Reference} reference - A reference to get.
81 * @returns {ASTNode|null} A VariableDeclarator/AssignmentExpression node or
82 * null.
83 */
84function getDestructuringHost(reference) {
85 if (!reference.isWrite()) {
86 return null;
87 }
88 let node = reference.identifier.parent;
89
90 while (PATTERN_TYPE.test(node.type)) {
91 node = node.parent;
92 }
93
94 if (!DESTRUCTURING_HOST_TYPE.test(node.type)) {
95 return null;
96 }
97 return node;
98}
99
100/**
101 * Determines if a destructuring assignment node contains
102 * any MemberExpression nodes. This is used to determine if a
103 * variable that is only written once using destructuring can be
104 * safely converted into a const declaration.
105 * @param {ASTNode} node The ObjectPattern or ArrayPattern node to check.
106 * @returns {boolean} True if the destructuring pattern contains
107 * a MemberExpression, false if not.
108 */
109function hasMemberExpressionAssignment(node) {
110 switch (node.type) {
111 case "ObjectPattern":
112 return node.properties.some(prop => {
113 if (prop) {
114
115 /*
116 * Spread elements have an argument property while
117 * others have a value property. Because different
118 * parsers use different node types for spread elements,
119 * we just check if there is an argument property.
120 */
121 return hasMemberExpressionAssignment(prop.argument || prop.value);
122 }
123
124 return false;
125 });
126
127 case "ArrayPattern":
128 return node.elements.some(element => {
129 if (element) {
130 return hasMemberExpressionAssignment(element);
131 }
132
133 return false;
134 });
135
136 case "AssignmentPattern":
137 return hasMemberExpressionAssignment(node.left);
138
139 case "MemberExpression":
140 return true;
141
142 // no default
143 }
144
145 return false;
146}
147
148/**
149 * Gets an identifier node of a given variable.
150 *
151 * If the initialization exists or one or more reading references exist before
152 * the first assignment, the identifier node is the node of the declaration.
153 * Otherwise, the identifier node is the node of the first assignment.
154 *
155 * If the variable should not change to const, this function returns null.
156 * - If the variable is reassigned.
157 * - If the variable is never initialized nor assigned.
158 * - If the variable is initialized in a different scope from the declaration.
159 * - If the unique assignment of the variable cannot change to a declaration.
160 * e.g. `if (a) b = 1` / `return (b = 1)`
161 * - If the variable is declared in the global scope and `eslintUsed` is `true`.
162 * `/*exported foo` directive comment makes such variables. This rule does not
163 * warn such variables because this rule cannot distinguish whether the
164 * exported variables are reassigned or not.
165 *
166 * @param {eslint-scope.Variable} variable - A variable to get.
167 * @param {boolean} ignoreReadBeforeAssign -
168 * The value of `ignoreReadBeforeAssign` option.
169 * @returns {ASTNode|null}
170 * An Identifier node if the variable should change to const.
171 * Otherwise, null.
172 */
173function getIdentifierIfShouldBeConst(variable, ignoreReadBeforeAssign) {
174 if (variable.eslintUsed && variable.scope.type === "global") {
175 return null;
176 }
177
178 // Finds the unique WriteReference.
179 let writer = null;
180 let isReadBeforeInit = false;
181 const references = variable.references;
182
183 for (let i = 0; i < references.length; ++i) {
184 const reference = references[i];
185
186 if (reference.isWrite()) {
187 const isReassigned = (
188 writer !== null &&
189 writer.identifier !== reference.identifier
190 );
191
192 if (isReassigned) {
193 return null;
194 }
195
196 const destructuringHost = getDestructuringHost(reference);
197
198 if (destructuringHost !== null && destructuringHost.left !== void 0) {
199 const leftNode = destructuringHost.left;
200 let hasOuterVariables = false,
201 hasNonIdentifiers = false;
202
203 if (leftNode.type === "ObjectPattern") {
204 const properties = leftNode.properties;
205
206 hasOuterVariables = properties
207 .filter(prop => prop.value)
208 .map(prop => prop.value.name)
209 .some(name => isOuterVariableInDestructing(name, variable.scope));
210
211 hasNonIdentifiers = hasMemberExpressionAssignment(leftNode);
212
213 } else if (leftNode.type === "ArrayPattern") {
214 const elements = leftNode.elements;
215
216 hasOuterVariables = elements
217 .map(element => element && element.name)
218 .some(name => isOuterVariableInDestructing(name, variable.scope));
219
220 hasNonIdentifiers = hasMemberExpressionAssignment(leftNode);
221 }
222
223 if (hasOuterVariables || hasNonIdentifiers) {
224 return null;
225 }
226
227 }
228
229 writer = reference;
230
231 } else if (reference.isRead() && writer === null) {
232 if (ignoreReadBeforeAssign) {
233 return null;
234 }
235 isReadBeforeInit = true;
236 }
237 }
238
239 /*
240 * If the assignment is from a different scope, ignore it.
241 * If the assignment cannot change to a declaration, ignore it.
242 */
243 const shouldBeConst = (
244 writer !== null &&
245 writer.from === variable.scope &&
246 canBecomeVariableDeclaration(writer.identifier)
247 );
248
249 if (!shouldBeConst) {
250 return null;
251 }
252
253 if (isReadBeforeInit) {
254 return variable.defs[0].name;
255 }
256
257 return writer.identifier;
258}
259
260/**
261 * Groups by the VariableDeclarator/AssignmentExpression node that each
262 * reference of given variables belongs to.
263 * This is used to detect a mix of reassigned and never reassigned in a
264 * destructuring.
265 *
266 * @param {eslint-scope.Variable[]} variables - Variables to group by destructuring.
267 * @param {boolean} ignoreReadBeforeAssign -
268 * The value of `ignoreReadBeforeAssign` option.
269 * @returns {Map<ASTNode, ASTNode[]>} Grouped identifier nodes.
270 */
271function groupByDestructuring(variables, ignoreReadBeforeAssign) {
272 const identifierMap = new Map();
273
274 for (let i = 0; i < variables.length; ++i) {
275 const variable = variables[i];
276 const references = variable.references;
277 const identifier = getIdentifierIfShouldBeConst(variable, ignoreReadBeforeAssign);
278 let prevId = null;
279
280 for (let j = 0; j < references.length; ++j) {
281 const reference = references[j];
282 const id = reference.identifier;
283
284 /*
285 * Avoid counting a reference twice or more for default values of
286 * destructuring.
287 */
288 if (id === prevId) {
289 continue;
290 }
291 prevId = id;
292
293 // Add the identifier node into the destructuring group.
294 const group = getDestructuringHost(reference);
295
296 if (group) {
297 if (identifierMap.has(group)) {
298 identifierMap.get(group).push(identifier);
299 } else {
300 identifierMap.set(group, [identifier]);
301 }
302 }
303 }
304 }
305
306 return identifierMap;
307}
308
309/**
310 * Finds the nearest parent of node with a given type.
311 *
312 * @param {ASTNode} node – The node to search from.
313 * @param {string} type – The type field of the parent node.
314 * @param {Function} shouldStop – a predicate that returns true if the traversal should stop, and false otherwise.
315 * @returns {ASTNode} The closest ancestor with the specified type; null if no such ancestor exists.
316 */
317function findUp(node, type, shouldStop) {
318 if (!node || shouldStop(node)) {
319 return null;
320 }
321 if (node.type === type) {
322 return node;
323 }
324 return findUp(node.parent, type, shouldStop);
325}
326
327//------------------------------------------------------------------------------
328// Rule Definition
329//------------------------------------------------------------------------------
330
331module.exports = {
332 meta: {
333 type: "suggestion",
334
335 docs: {
336 description: "require `const` declarations for variables that are never reassigned after declared",
337 category: "ECMAScript 6",
338 recommended: false,
339 url: "https://eslint.org/docs/rules/prefer-const"
340 },
341
342 fixable: "code",
343
344 schema: [
345 {
346 type: "object",
347 properties: {
348 destructuring: { enum: ["any", "all"], default: "any" },
349 ignoreReadBeforeAssign: { type: "boolean", default: false }
350 },
351 additionalProperties: false
352 }
353 ],
354 messages: {
355 useConst: "'{{name}}' is never reassigned. Use 'const' instead."
356 }
357 },
358
359 create(context) {
360 const options = context.options[0] || {};
361 const sourceCode = context.getSourceCode();
362 const shouldMatchAnyDestructuredVariable = options.destructuring !== "all";
363 const ignoreReadBeforeAssign = options.ignoreReadBeforeAssign === true;
364 const variables = [];
365 let reportCount = 0;
366 let name = "";
367
368 /**
369 * Reports given identifier nodes if all of the nodes should be declared
370 * as const.
371 *
372 * The argument 'nodes' is an array of Identifier nodes.
373 * This node is the result of 'getIdentifierIfShouldBeConst()', so it's
374 * nullable. In simple declaration or assignment cases, the length of
375 * the array is 1. In destructuring cases, the length of the array can
376 * be 2 or more.
377 *
378 * @param {(eslint-scope.Reference|null)[]} nodes -
379 * References which are grouped by destructuring to report.
380 * @returns {void}
381 */
382 function checkGroup(nodes) {
383 const nodesToReport = nodes.filter(Boolean);
384
385 if (nodes.length && (shouldMatchAnyDestructuredVariable || nodesToReport.length === nodes.length)) {
386 const varDeclParent = findUp(nodes[0], "VariableDeclaration", parentNode => parentNode.type.endsWith("Statement"));
387 const isVarDecParentNull = varDeclParent === null;
388
389 if (!isVarDecParentNull && varDeclParent.declarations.length > 0) {
390 const firstDeclaration = varDeclParent.declarations[0];
391
392 if (firstDeclaration.init) {
393 const firstDecParent = firstDeclaration.init.parent;
394
395 /*
396 * First we check the declaration type and then depending on
397 * if the type is a "VariableDeclarator" or its an "ObjectPattern"
398 * we compare the name from the first identifier, if the names are different
399 * we assign the new name and reset the count of reportCount and nodeCount in
400 * order to check each block for the number of reported errors and base our fix
401 * based on comparing nodes.length and nodesToReport.length.
402 */
403
404 if (firstDecParent.type === "VariableDeclarator") {
405
406 if (firstDecParent.id.name !== name) {
407 name = firstDecParent.id.name;
408 reportCount = 0;
409 }
410
411 if (firstDecParent.id.type === "ObjectPattern") {
412 if (firstDecParent.init.name !== name) {
413 name = firstDecParent.init.name;
414 reportCount = 0;
415 }
416 }
417 }
418 }
419 }
420
421 let shouldFix = varDeclParent &&
422
423 // Don't do a fix unless the variable is initialized (or it's in a for-in or for-of loop)
424 (varDeclParent.parent.type === "ForInStatement" || varDeclParent.parent.type === "ForOfStatement" || varDeclParent.declarations[0].init) &&
425
426 /*
427 * If options.destructuring is "all", then this warning will not occur unless
428 * every assignment in the destructuring should be const. In that case, it's safe
429 * to apply the fix.
430 */
431 nodesToReport.length === nodes.length;
432
433 if (!isVarDecParentNull && varDeclParent.declarations && varDeclParent.declarations.length !== 1) {
434
435 if (varDeclParent && varDeclParent.declarations && varDeclParent.declarations.length >= 1) {
436
437 /*
438 * Add nodesToReport.length to a count, then comparing the count to the length
439 * of the declarations in the current block.
440 */
441
442 reportCount += nodesToReport.length;
443
444 shouldFix = shouldFix && (reportCount === varDeclParent.declarations.length);
445 }
446 }
447
448 nodesToReport.forEach(node => {
449 context.report({
450 node,
451 messageId: "useConst",
452 data: node,
453 fix: shouldFix ? fixer => fixer.replaceText(sourceCode.getFirstToken(varDeclParent), "const") : null
454 });
455 });
456 }
457 }
458
459 return {
460 "Program:exit"() {
461 groupByDestructuring(variables, ignoreReadBeforeAssign).forEach(checkGroup);
462 },
463
464 VariableDeclaration(node) {
465 if (node.kind === "let" && !isInitOfForStatement(node)) {
466 variables.push(...context.getDeclaredVariables(node));
467 }
468 }
469 };
470 }
471};