no-shadow.js 12 KB

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