no-shadow.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. /**
  2. * @fileoverview Rule to flag on declaring variables already declared in the outer scope
  3. * @author Ilya Volodin
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. const astUtils = require("./utils/ast-utils");
  10. //------------------------------------------------------------------------------
  11. // Helpers
  12. //------------------------------------------------------------------------------
  13. const FUNC_EXPR_NODE_TYPES = new Set(["ArrowFunctionExpression", "FunctionExpression"]);
  14. const CALL_EXPR_NODE_TYPE = new Set(["CallExpression"]);
  15. const FOR_IN_OF_TYPE = /^For(?:In|Of)Statement$/u;
  16. const SENTINEL_TYPE = /^(?:(?:Function|Class)(?:Declaration|Expression)|ArrowFunctionExpression|CatchClause|ImportDeclaration|ExportNamedDeclaration)$/u;
  17. //------------------------------------------------------------------------------
  18. // Rule Definition
  19. //------------------------------------------------------------------------------
  20. /** @type {import('../shared/types').Rule} */
  21. module.exports = {
  22. meta: {
  23. type: "suggestion",
  24. docs: {
  25. description: "Disallow variable declarations from shadowing variables declared in the outer scope",
  26. recommended: false,
  27. url: "https://eslint.org/docs/rules/no-shadow"
  28. },
  29. schema: [
  30. {
  31. type: "object",
  32. properties: {
  33. builtinGlobals: { type: "boolean", default: false },
  34. hoist: { enum: ["all", "functions", "never"], default: "functions" },
  35. allow: {
  36. type: "array",
  37. items: {
  38. type: "string"
  39. }
  40. },
  41. ignoreOnInitialization: { type: "boolean", default: false }
  42. },
  43. additionalProperties: false
  44. }
  45. ],
  46. messages: {
  47. noShadow: "'{{name}}' is already declared in the upper scope on line {{shadowedLine}} column {{shadowedColumn}}.",
  48. noShadowGlobal: "'{{name}}' is already a global variable."
  49. }
  50. },
  51. create(context) {
  52. const options = {
  53. builtinGlobals: context.options[0] && context.options[0].builtinGlobals,
  54. hoist: (context.options[0] && context.options[0].hoist) || "functions",
  55. allow: (context.options[0] && context.options[0].allow) || [],
  56. ignoreOnInitialization: context.options[0] && context.options[0].ignoreOnInitialization
  57. };
  58. /**
  59. * Checks whether or not a given location is inside of the range of a given node.
  60. * @param {ASTNode} node An node to check.
  61. * @param {number} location A location to check.
  62. * @returns {boolean} `true` if the location is inside of the range of the node.
  63. */
  64. function isInRange(node, location) {
  65. return node && node.range[0] <= location && location <= node.range[1];
  66. }
  67. /**
  68. * Searches from the current node through its ancestry to find a matching node.
  69. * @param {ASTNode} node a node to get.
  70. * @param {(node: ASTNode) => boolean} match a callback that checks whether or not the node verifies its condition or not.
  71. * @returns {ASTNode|null} the matching node.
  72. */
  73. function findSelfOrAncestor(node, match) {
  74. let currentNode = node;
  75. while (currentNode && !match(currentNode)) {
  76. currentNode = currentNode.parent;
  77. }
  78. return currentNode;
  79. }
  80. /**
  81. * Finds function's outer scope.
  82. * @param {Scope} scope Function's own scope.
  83. * @returns {Scope} Function's outer scope.
  84. */
  85. function getOuterScope(scope) {
  86. const upper = scope.upper;
  87. if (upper.type === "function-expression-name") {
  88. return upper.upper;
  89. }
  90. return upper;
  91. }
  92. /**
  93. * Checks if a variable and a shadowedVariable have the same init pattern ancestor.
  94. * @param {Object} variable a variable to check.
  95. * @param {Object} shadowedVariable a shadowedVariable to check.
  96. * @returns {boolean} Whether or not the variable and the shadowedVariable have the same init pattern ancestor.
  97. */
  98. function isInitPatternNode(variable, shadowedVariable) {
  99. const outerDef = shadowedVariable.defs[0];
  100. if (!outerDef) {
  101. return false;
  102. }
  103. const { variableScope } = variable.scope;
  104. if (!(FUNC_EXPR_NODE_TYPES.has(variableScope.block.type) && getOuterScope(variableScope) === shadowedVariable.scope)) {
  105. return false;
  106. }
  107. const fun = variableScope.block;
  108. const { parent } = fun;
  109. const callExpression = findSelfOrAncestor(
  110. parent,
  111. node => CALL_EXPR_NODE_TYPE.has(node.type)
  112. );
  113. if (!callExpression) {
  114. return false;
  115. }
  116. let node = outerDef.name;
  117. const location = callExpression.range[1];
  118. while (node) {
  119. if (node.type === "VariableDeclarator") {
  120. if (isInRange(node.init, location)) {
  121. return true;
  122. }
  123. if (FOR_IN_OF_TYPE.test(node.parent.parent.type) &&
  124. isInRange(node.parent.parent.right, location)
  125. ) {
  126. return true;
  127. }
  128. break;
  129. } else if (node.type === "AssignmentPattern") {
  130. if (isInRange(node.right, location)) {
  131. return true;
  132. }
  133. } else if (SENTINEL_TYPE.test(node.type)) {
  134. break;
  135. }
  136. node = node.parent;
  137. }
  138. return false;
  139. }
  140. /**
  141. * Check if variable name is allowed.
  142. * @param {ASTNode} variable The variable to check.
  143. * @returns {boolean} Whether or not the variable name is allowed.
  144. */
  145. function isAllowed(variable) {
  146. return options.allow.includes(variable.name);
  147. }
  148. /**
  149. * Checks if a variable of the class name in the class scope of ClassDeclaration.
  150. *
  151. * ClassDeclaration creates two variables of its name into its outer scope and its class scope.
  152. * So we should ignore the variable in the class scope.
  153. * @param {Object} variable The variable to check.
  154. * @returns {boolean} Whether or not the variable of the class name in the class scope of ClassDeclaration.
  155. */
  156. function isDuplicatedClassNameVariable(variable) {
  157. const block = variable.scope.block;
  158. return block.type === "ClassDeclaration" && block.id === variable.identifiers[0];
  159. }
  160. /**
  161. * Checks if a variable is inside the initializer of scopeVar.
  162. *
  163. * To avoid reporting at declarations such as `var a = function a() {};`.
  164. * But it should report `var a = function(a) {};` or `var a = function() { function a() {} };`.
  165. * @param {Object} variable The variable to check.
  166. * @param {Object} scopeVar The scope variable to look for.
  167. * @returns {boolean} Whether or not the variable is inside initializer of scopeVar.
  168. */
  169. function isOnInitializer(variable, scopeVar) {
  170. const outerScope = scopeVar.scope;
  171. const outerDef = scopeVar.defs[0];
  172. const outer = outerDef && outerDef.parent && outerDef.parent.range;
  173. const innerScope = variable.scope;
  174. const innerDef = variable.defs[0];
  175. const inner = innerDef && innerDef.name.range;
  176. return (
  177. outer &&
  178. inner &&
  179. outer[0] < inner[0] &&
  180. inner[1] < outer[1] &&
  181. ((innerDef.type === "FunctionName" && innerDef.node.type === "FunctionExpression") || innerDef.node.type === "ClassExpression") &&
  182. outerScope === innerScope.upper
  183. );
  184. }
  185. /**
  186. * Get a range of a variable's identifier node.
  187. * @param {Object} variable The variable to get.
  188. * @returns {Array|undefined} The range of the variable's identifier node.
  189. */
  190. function getNameRange(variable) {
  191. const def = variable.defs[0];
  192. return def && def.name.range;
  193. }
  194. /**
  195. * Get declared line and column of a variable.
  196. * @param {eslint-scope.Variable} variable The variable to get.
  197. * @returns {Object} The declared line and column of the variable.
  198. */
  199. function getDeclaredLocation(variable) {
  200. const identifier = variable.identifiers[0];
  201. let obj;
  202. if (identifier) {
  203. obj = {
  204. global: false,
  205. line: identifier.loc.start.line,
  206. column: identifier.loc.start.column + 1
  207. };
  208. } else {
  209. obj = {
  210. global: true
  211. };
  212. }
  213. return obj;
  214. }
  215. /**
  216. * Checks if a variable is in TDZ of scopeVar.
  217. * @param {Object} variable The variable to check.
  218. * @param {Object} scopeVar The variable of TDZ.
  219. * @returns {boolean} Whether or not the variable is in TDZ of scopeVar.
  220. */
  221. function isInTdz(variable, scopeVar) {
  222. const outerDef = scopeVar.defs[0];
  223. const inner = getNameRange(variable);
  224. const outer = getNameRange(scopeVar);
  225. return (
  226. inner &&
  227. outer &&
  228. inner[1] < outer[0] &&
  229. // Excepts FunctionDeclaration if is {"hoist":"function"}.
  230. (options.hoist !== "functions" || !outerDef || outerDef.node.type !== "FunctionDeclaration")
  231. );
  232. }
  233. /**
  234. * Checks the current context for shadowed variables.
  235. * @param {Scope} scope Fixme
  236. * @returns {void}
  237. */
  238. function checkForShadows(scope) {
  239. const variables = scope.variables;
  240. for (let i = 0; i < variables.length; ++i) {
  241. const variable = variables[i];
  242. // Skips "arguments" or variables of a class name in the class scope of ClassDeclaration.
  243. if (variable.identifiers.length === 0 ||
  244. isDuplicatedClassNameVariable(variable) ||
  245. isAllowed(variable)
  246. ) {
  247. continue;
  248. }
  249. // Gets shadowed variable.
  250. const shadowed = astUtils.getVariableByName(scope.upper, variable.name);
  251. if (shadowed &&
  252. (shadowed.identifiers.length > 0 || (options.builtinGlobals && "writeable" in shadowed)) &&
  253. !isOnInitializer(variable, shadowed) &&
  254. !(options.ignoreOnInitialization && isInitPatternNode(variable, shadowed)) &&
  255. !(options.hoist !== "all" && isInTdz(variable, shadowed))
  256. ) {
  257. const location = getDeclaredLocation(shadowed);
  258. const messageId = location.global ? "noShadowGlobal" : "noShadow";
  259. const data = { name: variable.name };
  260. if (!location.global) {
  261. data.shadowedLine = location.line;
  262. data.shadowedColumn = location.column;
  263. }
  264. context.report({
  265. node: variable.identifiers[0],
  266. messageId,
  267. data
  268. });
  269. }
  270. }
  271. }
  272. return {
  273. "Program:exit"() {
  274. const globalScope = context.getScope();
  275. const stack = globalScope.childScopes.slice();
  276. while (stack.length) {
  277. const scope = stack.pop();
  278. stack.push(...scope.childScopes);
  279. checkForShadows(scope);
  280. }
  281. }
  282. };
  283. }
  284. };