no-shadow.js 6.8 KB

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