no-shadow.js 8.0 KB

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