no-shadow.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  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([
  14. "ArrowFunctionExpression",
  15. "FunctionExpression",
  16. ]);
  17. const CALL_EXPR_NODE_TYPE = new Set(["CallExpression"]);
  18. const FOR_IN_OF_TYPE = /^For(?:In|Of)Statement$/u;
  19. const SENTINEL_TYPE =
  20. /^(?:(?:Function|Class)(?:Declaration|Expression)|ArrowFunctionExpression|CatchClause|ImportDeclaration|ExportNamedDeclaration)$/u;
  21. // TS-specific node types
  22. const TYPES_HOISTED_NODES = new Set([
  23. "TSInterfaceDeclaration",
  24. "TSTypeAliasDeclaration",
  25. ]);
  26. // TS-specific function variable def types
  27. const ALLOWED_FUNCTION_VARIABLE_DEF_TYPES = new Set([
  28. "TSCallSignatureDeclaration",
  29. "TSFunctionType",
  30. "TSMethodSignature",
  31. "TSEmptyBodyFunctionExpression",
  32. "TSDeclareFunction",
  33. "TSConstructSignatureDeclaration",
  34. "TSConstructorType",
  35. ]);
  36. //------------------------------------------------------------------------------
  37. // Rule Definition
  38. //------------------------------------------------------------------------------
  39. /** @type {import('../types').Rule.RuleModule} */
  40. module.exports = {
  41. meta: {
  42. type: "suggestion",
  43. dialects: ["typescript", "javascript"],
  44. language: "javascript",
  45. defaultOptions: [
  46. {
  47. allow: [],
  48. builtinGlobals: false,
  49. hoist: "functions",
  50. ignoreOnInitialization: false,
  51. ignoreTypeValueShadow: true,
  52. ignoreFunctionTypeParameterNameValueShadow: true,
  53. },
  54. ],
  55. docs: {
  56. description:
  57. "Disallow variable declarations from shadowing variables declared in the outer scope",
  58. recommended: false,
  59. url: "https://eslint.org/docs/latest/rules/no-shadow",
  60. },
  61. schema: [
  62. {
  63. type: "object",
  64. properties: {
  65. builtinGlobals: { type: "boolean" },
  66. hoist: {
  67. enum: [
  68. "all",
  69. "functions",
  70. "never",
  71. "types",
  72. "functions-and-types",
  73. ],
  74. },
  75. allow: {
  76. type: "array",
  77. items: {
  78. type: "string",
  79. },
  80. },
  81. ignoreOnInitialization: { type: "boolean" },
  82. ignoreTypeValueShadow: { type: "boolean" },
  83. ignoreFunctionTypeParameterNameValueShadow: {
  84. type: "boolean",
  85. },
  86. },
  87. additionalProperties: false,
  88. },
  89. ],
  90. messages: {
  91. noShadow:
  92. "'{{name}}' is already declared in the upper scope on line {{shadowedLine}} column {{shadowedColumn}}.",
  93. noShadowGlobal: "'{{name}}' is already a global variable.",
  94. },
  95. },
  96. create(context) {
  97. const [
  98. {
  99. builtinGlobals,
  100. hoist,
  101. allow,
  102. ignoreOnInitialization,
  103. ignoreTypeValueShadow,
  104. ignoreFunctionTypeParameterNameValueShadow,
  105. },
  106. ] = context.options;
  107. const sourceCode = context.sourceCode;
  108. /**
  109. * Check if a scope is a TypeScript module augmenting the global namespace.
  110. * @param {Scope} scope The scope to check
  111. * @returns {boolean} Whether the scope is a global augmentation
  112. */
  113. function isGlobalAugmentation(scope) {
  114. return (
  115. scope.block.kind === "global" ||
  116. (!!scope.upper && isGlobalAugmentation(scope.upper))
  117. );
  118. }
  119. /**
  120. * Check if variable is a `this` parameter.
  121. * @param {Object} variable The variable to check
  122. * @returns {boolean} Whether the variable is a this parameter
  123. */
  124. function isThisParam(variable) {
  125. return variable.name === "this";
  126. }
  127. /**
  128. * Checks if type and value shadows each other
  129. * @param {Object} variable The variable to check
  130. * @param {Object} shadowedVariable The shadowed variable
  131. * @returns {boolean} Whether it's a type/value shadow case to ignore
  132. */
  133. function isTypeValueShadow(variable, shadowedVariable) {
  134. if (ignoreTypeValueShadow !== true) {
  135. return false;
  136. }
  137. if (!("isValueVariable" in variable)) {
  138. return false;
  139. }
  140. const firstDefinition = shadowedVariable.defs[0];
  141. // Check if shadowedVariable is a type import
  142. const isTypeImport =
  143. firstDefinition &&
  144. firstDefinition.parent?.type === "ImportDeclaration" &&
  145. (firstDefinition.parent.importKind === "type" ||
  146. firstDefinition.parent.specifiers.some(
  147. s => s.importKind === "type",
  148. ));
  149. const isShadowedValue =
  150. !firstDefinition ||
  151. (isTypeImport ? false : shadowedVariable.isValueVariable);
  152. return variable.isValueVariable !== isShadowedValue;
  153. }
  154. /**
  155. * Checks if it's a function type parameter shadow
  156. * @param {Object} variable The variable to check
  157. * @returns {boolean} Whether it's a function type parameter shadow case to ignore
  158. */
  159. function isFunctionTypeParameterNameValueShadow(variable) {
  160. if (ignoreFunctionTypeParameterNameValueShadow !== true) {
  161. return false;
  162. }
  163. return variable.defs.some(def =>
  164. ALLOWED_FUNCTION_VARIABLE_DEF_TYPES.has(def.node.type),
  165. );
  166. }
  167. /**
  168. * Checks if the variable is a generic of a static method
  169. * @param {Object} variable The variable to check
  170. * @returns {boolean} Whether the variable is a generic of a static method
  171. */
  172. function isTypeParameterOfStaticMethod(variable) {
  173. const typeParameter = variable.identifiers[0].parent;
  174. const typeParameterDecl = typeParameter.parent;
  175. if (typeParameterDecl.type !== "TSTypeParameterDeclaration") {
  176. return false;
  177. }
  178. const functionExpr = typeParameterDecl.parent;
  179. const methodDefinition = functionExpr.parent;
  180. return methodDefinition.static;
  181. }
  182. /**
  183. * Checks for static method generic shadowing class generic
  184. * @param {Object} variable The variable to check
  185. * @returns {boolean} Whether it's a static method generic shadowing class generic
  186. */
  187. function isGenericOfAStaticMethodShadow(variable) {
  188. return isTypeParameterOfStaticMethod(variable);
  189. }
  190. /**
  191. * Checks whether or not a given location is inside of the range of a given node.
  192. * @param {ASTNode} node An node to check.
  193. * @param {number} location A location to check.
  194. * @returns {boolean} `true` if the location is inside of the range of the node.
  195. */
  196. function isInRange(node, location) {
  197. return (
  198. node && node.range[0] <= location && location <= node.range[1]
  199. );
  200. }
  201. /**
  202. * Searches from the current node through its ancestry to find a matching node.
  203. * @param {ASTNode} node a node to get.
  204. * @param {(node: ASTNode) => boolean} match a callback that checks whether or not the node verifies its condition or not.
  205. * @returns {ASTNode|null} the matching node.
  206. */
  207. function findSelfOrAncestor(node, match) {
  208. let currentNode = node;
  209. while (currentNode && !match(currentNode)) {
  210. currentNode = currentNode.parent;
  211. }
  212. return currentNode;
  213. }
  214. /**
  215. * Finds function's outer scope.
  216. * @param {Scope} scope Function's own scope.
  217. * @returns {Scope} Function's outer scope.
  218. */
  219. function getOuterScope(scope) {
  220. const upper = scope.upper;
  221. if (upper && upper.type === "function-expression-name") {
  222. return upper.upper;
  223. }
  224. return upper;
  225. }
  226. /**
  227. * Checks if a variable and a shadowedVariable have the same init pattern ancestor.
  228. * @param {Object} variable a variable to check.
  229. * @param {Object} shadowedVariable a shadowedVariable to check.
  230. * @returns {boolean} Whether or not the variable and the shadowedVariable have the same init pattern ancestor.
  231. */
  232. function isInitPatternNode(variable, shadowedVariable) {
  233. const outerDef = shadowedVariable.defs[0];
  234. if (!outerDef) {
  235. return false;
  236. }
  237. const { variableScope } = variable.scope;
  238. if (
  239. !(
  240. FUNC_EXPR_NODE_TYPES.has(variableScope.block.type) &&
  241. getOuterScope(variableScope) === shadowedVariable.scope
  242. )
  243. ) {
  244. return false;
  245. }
  246. const fun = variableScope.block;
  247. const { parent } = fun;
  248. const callExpression = findSelfOrAncestor(parent, node =>
  249. CALL_EXPR_NODE_TYPE.has(node.type),
  250. );
  251. if (!callExpression) {
  252. return false;
  253. }
  254. let node = outerDef.name;
  255. const location = callExpression.range[1];
  256. while (node) {
  257. if (node.type === "VariableDeclarator") {
  258. if (isInRange(node.init, location)) {
  259. return true;
  260. }
  261. if (
  262. FOR_IN_OF_TYPE.test(node.parent.parent.type) &&
  263. isInRange(node.parent.parent.right, location)
  264. ) {
  265. return true;
  266. }
  267. break;
  268. } else if (node.type === "AssignmentPattern") {
  269. if (isInRange(node.right, location)) {
  270. return true;
  271. }
  272. } else if (SENTINEL_TYPE.test(node.type)) {
  273. break;
  274. }
  275. node = node.parent;
  276. }
  277. return false;
  278. }
  279. /**
  280. * Check if variable name is allowed.
  281. * @param {ASTNode} variable The variable to check.
  282. * @returns {boolean} Whether or not the variable name is allowed.
  283. */
  284. function isAllowed(variable) {
  285. return allow.includes(variable.name);
  286. }
  287. /**
  288. * Checks if a variable of the class name in the class scope of ClassDeclaration.
  289. *
  290. * ClassDeclaration creates two variables of its name into its outer scope and its class scope.
  291. * So we should ignore the variable in the class scope.
  292. * @param {Object} variable The variable to check.
  293. * @returns {boolean} Whether or not the variable of the class name in the class scope of ClassDeclaration.
  294. */
  295. function isDuplicatedClassNameVariable(variable) {
  296. const block = variable.scope.block;
  297. return (
  298. block.type === "ClassDeclaration" &&
  299. block.id === variable.identifiers[0]
  300. );
  301. }
  302. /**
  303. * Checks if a variable is inside the initializer of scopeVar.
  304. *
  305. * To avoid reporting at declarations such as `var a = function a() {};`.
  306. * But it should report `var a = function(a) {};` or `var a = function() { function a() {} };`.
  307. * @param {Object} variable The variable to check.
  308. * @param {Object} scopeVar The scope variable to look for.
  309. * @returns {boolean} Whether or not the variable is inside initializer of scopeVar.
  310. */
  311. function isOnInitializer(variable, scopeVar) {
  312. const outerScope = scopeVar.scope;
  313. const outerDef = scopeVar.defs[0];
  314. const outer = outerDef && outerDef.parent && outerDef.parent.range;
  315. const innerScope = variable.scope;
  316. const innerDef = variable.defs[0];
  317. const inner = innerDef && innerDef.name.range;
  318. return (
  319. outer &&
  320. inner &&
  321. outer[0] < inner[0] &&
  322. inner[1] < outer[1] &&
  323. ((innerDef.type === "FunctionName" &&
  324. innerDef.node.type === "FunctionExpression") ||
  325. innerDef.node.type === "ClassExpression") &&
  326. outerScope === innerScope.upper
  327. );
  328. }
  329. /**
  330. * Get a range of a variable's identifier node.
  331. * @param {Object} variable The variable to get.
  332. * @returns {Array|undefined} The range of the variable's identifier node.
  333. */
  334. function getNameRange(variable) {
  335. const def = variable.defs[0];
  336. return def && def.name.range;
  337. }
  338. /**
  339. * Get declared line and column of a variable.
  340. * @param {eslint-scope.Variable} variable The variable to get.
  341. * @returns {Object} The declared line and column of the variable.
  342. */
  343. function getDeclaredLocation(variable) {
  344. const identifier = variable.identifiers[0];
  345. let obj;
  346. if (identifier) {
  347. obj = {
  348. global: false,
  349. line: identifier.loc.start.line,
  350. column: identifier.loc.start.column + 1,
  351. };
  352. } else {
  353. obj = {
  354. global: true,
  355. };
  356. }
  357. return obj;
  358. }
  359. /**
  360. * Checks if a variable is in TDZ of scopeVar.
  361. * @param {Object} variable The variable to check.
  362. * @param {Object} scopeVar The variable of TDZ.
  363. * @returns {boolean} Whether or not the variable is in TDZ of scopeVar.
  364. */
  365. function isInTdz(variable, scopeVar) {
  366. const outerDef = scopeVar.defs[0];
  367. const inner = getNameRange(variable);
  368. const outer = getNameRange(scopeVar);
  369. if (!outer || inner[1] >= outer[0]) {
  370. return false;
  371. }
  372. if (hoist === "types") {
  373. return !TYPES_HOISTED_NODES.has(outerDef.node.type);
  374. }
  375. if (hoist === "functions-and-types") {
  376. return (
  377. outerDef.node.type !== "FunctionDeclaration" &&
  378. !TYPES_HOISTED_NODES.has(outerDef.node.type)
  379. );
  380. }
  381. return (
  382. inner &&
  383. outer &&
  384. inner[1] < outer[0] &&
  385. // Excepts FunctionDeclaration if is {"hoist":"function"}.
  386. (hoist !== "functions" ||
  387. !outerDef ||
  388. outerDef.node.type !== "FunctionDeclaration")
  389. );
  390. }
  391. /**
  392. * Checks if the initialization of a variable has the declare modifier in a
  393. * definition file.
  394. * @param {Object} variable The variable to check
  395. * @returns {boolean} Whether the variable is declared in a definition file
  396. */
  397. function isDeclareInDTSFile(variable) {
  398. const fileName = context.filename;
  399. if (
  400. !fileName.endsWith(".d.ts") &&
  401. !fileName.endsWith(".d.cts") &&
  402. !fileName.endsWith(".d.mts")
  403. ) {
  404. return false;
  405. }
  406. return variable.defs.some(
  407. def =>
  408. (def.type === "Variable" && def.parent.declare) ||
  409. (def.type === "ClassName" && def.node.declare) ||
  410. (def.type === "TSEnumName" && def.node.declare) ||
  411. (def.type === "TSModuleName" && def.node.declare),
  412. );
  413. }
  414. /**
  415. * Checks if a variable is a duplicate of an enum name in the enum scope
  416. * @param {Object} variable The variable to check
  417. * @returns {boolean} Whether it's a duplicate enum name variable
  418. */
  419. function isDuplicatedEnumNameVariable(variable) {
  420. const block = variable.scope.block;
  421. return (
  422. block.type === "TSEnumDeclaration" &&
  423. block.id === variable.identifiers[0]
  424. );
  425. }
  426. /**
  427. * Check if this is an external module declaration merging with a type import
  428. * @param {Scope} scope Current scope
  429. * @param {Object} variable Current variable
  430. * @param {Object} shadowedVariable Shadowed variable
  431. * @returns {boolean} Whether it's an external declaration merging
  432. */
  433. function isExternalDeclarationMerging(
  434. scope,
  435. variable,
  436. shadowedVariable,
  437. ) {
  438. const firstDefinition = shadowedVariable.defs[0];
  439. if (!firstDefinition || !firstDefinition.parent) {
  440. return false;
  441. }
  442. // Check if the shadowed variable is a type import
  443. const isTypeImport =
  444. firstDefinition.parent.type === "ImportDeclaration" &&
  445. (firstDefinition.parent.importKind === "type" ||
  446. firstDefinition.parent.specifiers?.some(
  447. s =>
  448. s.type === "ImportSpecifier" &&
  449. s.importKind === "type" &&
  450. s.local.name === shadowedVariable.name,
  451. ));
  452. if (!isTypeImport) {
  453. return false;
  454. }
  455. // Check if the current variable is within a module declaration
  456. const moduleDecl = findSelfOrAncestor(
  457. variable.identifiers[0]?.parent,
  458. node => node.type === "TSModuleDeclaration",
  459. );
  460. if (!moduleDecl) {
  461. return false;
  462. }
  463. /*
  464. * Module declaration merging should only happen within the same module
  465. * Check if the module name matches the import source
  466. */
  467. const importSource = firstDefinition.parent.source.value;
  468. const moduleName =
  469. moduleDecl.id.type === "Literal"
  470. ? moduleDecl.id.value
  471. : moduleDecl.id.name;
  472. return importSource === moduleName;
  473. }
  474. /**
  475. * Checks the current context for shadowed variables.
  476. * @param {Scope} scope Fixme
  477. * @returns {void}
  478. */
  479. function checkForShadows(scope) {
  480. // ignore global augmentation
  481. if (isGlobalAugmentation(scope)) {
  482. return;
  483. }
  484. const variables = scope.variables;
  485. for (let i = 0; i < variables.length; ++i) {
  486. const variable = variables[i];
  487. // Skips "arguments" or variables of a class name in the class scope of ClassDeclaration.
  488. if (
  489. variable.identifiers.length === 0 ||
  490. isDuplicatedClassNameVariable(variable) ||
  491. isDuplicatedEnumNameVariable(variable) ||
  492. isAllowed(variable) ||
  493. isDeclareInDTSFile(variable) ||
  494. isThisParam(variable)
  495. ) {
  496. continue;
  497. }
  498. // Gets shadowed variable.
  499. const shadowed = astUtils.getVariableByName(
  500. scope.upper,
  501. variable.name,
  502. );
  503. if (
  504. shadowed &&
  505. (shadowed.identifiers.length > 0 ||
  506. (builtinGlobals && "writeable" in shadowed)) &&
  507. !isOnInitializer(variable, shadowed) &&
  508. !(
  509. ignoreOnInitialization &&
  510. isInitPatternNode(variable, shadowed)
  511. ) &&
  512. !(hoist !== "all" && isInTdz(variable, shadowed)) &&
  513. !isTypeValueShadow(variable, shadowed) &&
  514. !isFunctionTypeParameterNameValueShadow(variable) &&
  515. !isGenericOfAStaticMethodShadow(variable, shadowed) &&
  516. !isExternalDeclarationMerging(scope, variable, shadowed)
  517. ) {
  518. const location = getDeclaredLocation(shadowed);
  519. const messageId = location.global
  520. ? "noShadowGlobal"
  521. : "noShadow";
  522. const data = { name: variable.name };
  523. if (!location.global) {
  524. data.shadowedLine = location.line;
  525. data.shadowedColumn = location.column;
  526. }
  527. context.report({
  528. node: variable.identifiers[0],
  529. messageId,
  530. data,
  531. });
  532. }
  533. }
  534. }
  535. return {
  536. "Program:exit"(node) {
  537. const globalScope = sourceCode.getScope(node);
  538. const stack = globalScope.childScopes.slice();
  539. while (stack.length) {
  540. const scope = stack.pop();
  541. stack.push(...scope.childScopes);
  542. checkForShadows(scope);
  543. }
  544. },
  545. };
  546. },
  547. };