UNPKG

6.87 kBJavaScriptView Raw
1/**
2 * @fileoverview Rule to flag on declaring variables already declared in the outer scope
3 * @author Ilya Volodin
4 */
5
6"use strict";
7
8//------------------------------------------------------------------------------
9// Requirements
10//------------------------------------------------------------------------------
11
12const astUtils = require("../ast-utils");
13
14//------------------------------------------------------------------------------
15// Rule Definition
16//------------------------------------------------------------------------------
17
18module.exports = {
19 meta: {
20 docs: {
21 description: "disallow variable declarations from shadowing variables declared in the outer scope",
22 category: "Variables",
23 recommended: false
24 },
25
26 schema: [
27 {
28 type: "object",
29 properties: {
30 builtinGlobals: { type: "boolean" },
31 hoist: { enum: ["all", "functions", "never"] },
32 allow: {
33 type: "array",
34 items: {
35 type: "string"
36 }
37 }
38 },
39 additionalProperties: false
40 }
41 ]
42 },
43
44 create(context) {
45
46 const options = {
47 builtinGlobals: Boolean(context.options[0] && context.options[0].builtinGlobals),
48 hoist: (context.options[0] && context.options[0].hoist) || "functions",
49 allow: (context.options[0] && context.options[0].allow) || []
50 };
51
52 /**
53 * Check if variable name is allowed.
54 *
55 * @param {ASTNode} variable The variable to check.
56 * @returns {boolean} Whether or not the variable name is allowed.
57 */
58 function isAllowed(variable) {
59 return options.allow.indexOf(variable.name) !== -1;
60 }
61
62 /**
63 * Checks if a variable of the class name in the class scope of ClassDeclaration.
64 *
65 * ClassDeclaration creates two variables of its name into its outer scope and its class scope.
66 * So we should ignore the variable in the class scope.
67 *
68 * @param {Object} variable The variable to check.
69 * @returns {boolean} Whether or not the variable of the class name in the class scope of ClassDeclaration.
70 */
71 function isDuplicatedClassNameVariable(variable) {
72 const block = variable.scope.block;
73
74 return block.type === "ClassDeclaration" && block.id === variable.identifiers[0];
75 }
76
77 /**
78 * Checks if a variable is inside the initializer of scopeVar.
79 *
80 * To avoid reporting at declarations such as `var a = function a() {};`.
81 * But it should report `var a = function(a) {};` or `var a = function() { function a() {} };`.
82 *
83 * @param {Object} variable The variable to check.
84 * @param {Object} scopeVar The scope variable to look for.
85 * @returns {boolean} Whether or not the variable is inside initializer of scopeVar.
86 */
87 function isOnInitializer(variable, scopeVar) {
88 const outerScope = scopeVar.scope;
89 const outerDef = scopeVar.defs[0];
90 const outer = outerDef && outerDef.parent && outerDef.parent.range;
91 const innerScope = variable.scope;
92 const innerDef = variable.defs[0];
93 const inner = innerDef && innerDef.name.range;
94
95 return (
96 outer &&
97 inner &&
98 outer[0] < inner[0] &&
99 inner[1] < outer[1] &&
100 ((innerDef.type === "FunctionName" && innerDef.node.type === "FunctionExpression") || innerDef.node.type === "ClassExpression") &&
101 outerScope === innerScope.upper
102 );
103 }
104
105 /**
106 * Get a range of a variable's identifier node.
107 * @param {Object} variable The variable to get.
108 * @returns {Array|undefined} The range of the variable's identifier node.
109 */
110 function getNameRange(variable) {
111 const def = variable.defs[0];
112
113 return def && def.name.range;
114 }
115
116 /**
117 * Checks if a variable is in TDZ of scopeVar.
118 * @param {Object} variable The variable to check.
119 * @param {Object} scopeVar The variable of TDZ.
120 * @returns {boolean} Whether or not the variable is in TDZ of scopeVar.
121 */
122 function isInTdz(variable, scopeVar) {
123 const outerDef = scopeVar.defs[0];
124 const inner = getNameRange(variable);
125 const outer = getNameRange(scopeVar);
126
127 return (
128 inner &&
129 outer &&
130 inner[1] < outer[0] &&
131
132 // Excepts FunctionDeclaration if is {"hoist":"function"}.
133 (options.hoist !== "functions" || !outerDef || outerDef.node.type !== "FunctionDeclaration")
134 );
135 }
136
137 /**
138 * Checks the current context for shadowed variables.
139 * @param {Scope} scope - Fixme
140 * @returns {void}
141 */
142 function checkForShadows(scope) {
143 const variables = scope.variables;
144
145 for (let i = 0; i < variables.length; ++i) {
146 const variable = variables[i];
147
148 // Skips "arguments" or variables of a class name in the class scope of ClassDeclaration.
149 if (variable.identifiers.length === 0 ||
150 isDuplicatedClassNameVariable(variable) ||
151 isAllowed(variable)
152 ) {
153 continue;
154 }
155
156 // Gets shadowed variable.
157 const shadowed = astUtils.getVariableByName(scope.upper, variable.name);
158
159 if (shadowed &&
160 (shadowed.identifiers.length > 0 || (options.builtinGlobals && "writeable" in shadowed)) &&
161 !isOnInitializer(variable, shadowed) &&
162 !(options.hoist !== "all" && isInTdz(variable, shadowed))
163 ) {
164 context.report({
165 node: variable.identifiers[0],
166 message: "'{{name}}' is already declared in the upper scope.",
167 data: variable
168 });
169 }
170 }
171 }
172
173 return {
174 "Program:exit"() {
175 const globalScope = context.getScope();
176 const stack = globalScope.childScopes.slice();
177
178 while (stack.length) {
179 const scope = stack.pop();
180
181 stack.push.apply(stack, scope.childScopes);
182 checkForShadows(scope);
183 }
184 }
185 };
186
187 }
188};