no-shadow.js 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  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. },
  39. create(context) {
  40. const options = {
  41. builtinGlobals: context.options[0] && context.options[0].builtinGlobals,
  42. hoist: (context.options[0] && context.options[0].hoist) || "functions",
  43. allow: (context.options[0] && context.options[0].allow) || []
  44. };
  45. /**
  46. * Check if variable name is allowed.
  47. * @param {ASTNode} variable The variable to check.
  48. * @returns {boolean} Whether or not the variable name is allowed.
  49. */
  50. function isAllowed(variable) {
  51. return options.allow.indexOf(variable.name) !== -1;
  52. }
  53. /**
  54. * Checks if a variable of the class name in the class scope of ClassDeclaration.
  55. *
  56. * ClassDeclaration creates two variables of its name into its outer scope and its class scope.
  57. * So we should ignore the variable in the class scope.
  58. * @param {Object} variable The variable to check.
  59. * @returns {boolean} Whether or not the variable of the class name in the class scope of ClassDeclaration.
  60. */
  61. function isDuplicatedClassNameVariable(variable) {
  62. const block = variable.scope.block;
  63. return block.type === "ClassDeclaration" && block.id === variable.identifiers[0];
  64. }
  65. /**
  66. * Checks if a variable is inside the initializer of scopeVar.
  67. *
  68. * To avoid reporting at declarations such as `var a = function a() {};`.
  69. * But it should report `var a = function(a) {};` or `var a = function() { function a() {} };`.
  70. * @param {Object} variable The variable to check.
  71. * @param {Object} scopeVar The scope variable to look for.
  72. * @returns {boolean} Whether or not the variable is inside initializer of scopeVar.
  73. */
  74. function isOnInitializer(variable, scopeVar) {
  75. const outerScope = scopeVar.scope;
  76. const outerDef = scopeVar.defs[0];
  77. const outer = outerDef && outerDef.parent && outerDef.parent.range;
  78. const innerScope = variable.scope;
  79. const innerDef = variable.defs[0];
  80. const inner = innerDef && innerDef.name.range;
  81. return (
  82. outer &&
  83. inner &&
  84. outer[0] < inner[0] &&
  85. inner[1] < outer[1] &&
  86. ((innerDef.type === "FunctionName" && innerDef.node.type === "FunctionExpression") || innerDef.node.type === "ClassExpression") &&
  87. outerScope === innerScope.upper
  88. );
  89. }
  90. /**
  91. * Get a range of a variable's identifier node.
  92. * @param {Object} variable The variable to get.
  93. * @returns {Array|undefined} The range of the variable's identifier node.
  94. */
  95. function getNameRange(variable) {
  96. const def = variable.defs[0];
  97. return def && def.name.range;
  98. }
  99. /**
  100. * Checks if a variable is in TDZ of scopeVar.
  101. * @param {Object} variable The variable to check.
  102. * @param {Object} scopeVar The variable of TDZ.
  103. * @returns {boolean} Whether or not the variable is in TDZ of scopeVar.
  104. */
  105. function isInTdz(variable, scopeVar) {
  106. const outerDef = scopeVar.defs[0];
  107. const inner = getNameRange(variable);
  108. const outer = getNameRange(scopeVar);
  109. return (
  110. inner &&
  111. outer &&
  112. inner[1] < outer[0] &&
  113. // Excepts FunctionDeclaration if is {"hoist":"function"}.
  114. (options.hoist !== "functions" || !outerDef || outerDef.node.type !== "FunctionDeclaration")
  115. );
  116. }
  117. /**
  118. * Checks the current context for shadowed variables.
  119. * @param {Scope} scope Fixme
  120. * @returns {void}
  121. */
  122. function checkForShadows(scope) {
  123. const variables = scope.variables;
  124. for (let i = 0; i < variables.length; ++i) {
  125. const variable = variables[i];
  126. // Skips "arguments" or variables of a class name in the class scope of ClassDeclaration.
  127. if (variable.identifiers.length === 0 ||
  128. isDuplicatedClassNameVariable(variable) ||
  129. isAllowed(variable)
  130. ) {
  131. continue;
  132. }
  133. // Gets shadowed variable.
  134. const shadowed = astUtils.getVariableByName(scope.upper, variable.name);
  135. if (shadowed &&
  136. (shadowed.identifiers.length > 0 || (options.builtinGlobals && "writeable" in shadowed)) &&
  137. !isOnInitializer(variable, shadowed) &&
  138. !(options.hoist !== "all" && isInTdz(variable, shadowed))
  139. ) {
  140. context.report({
  141. node: variable.identifiers[0],
  142. message: "'{{name}}' is already declared in the upper scope.",
  143. data: variable
  144. });
  145. }
  146. }
  147. }
  148. return {
  149. "Program:exit"() {
  150. const globalScope = context.getScope();
  151. const stack = globalScope.childScopes.slice();
  152. while (stack.length) {
  153. const scope = stack.pop();
  154. stack.push(...scope.childScopes);
  155. checkForShadows(scope);
  156. }
  157. }
  158. };
  159. }
  160. };