Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

no-var.js 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. /**
  2. * @fileoverview Rule to check for the usage of var.
  3. * @author Jamund Ferguson
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. const astUtils = require("../util/ast-utils");
  10. //------------------------------------------------------------------------------
  11. // Helpers
  12. //------------------------------------------------------------------------------
  13. /**
  14. * Check whether a given variable is a global variable or not.
  15. * @param {eslint-scope.Variable} variable The variable to check.
  16. * @returns {boolean} `true` if the variable is a global variable.
  17. */
  18. function isGlobal(variable) {
  19. return Boolean(variable.scope) && variable.scope.type === "global";
  20. }
  21. /**
  22. * Finds the nearest function scope or global scope walking up the scope
  23. * hierarchy.
  24. *
  25. * @param {eslint-scope.Scope} scope - The scope to traverse.
  26. * @returns {eslint-scope.Scope} a function scope or global scope containing the given
  27. * scope.
  28. */
  29. function getEnclosingFunctionScope(scope) {
  30. let currentScope = scope;
  31. while (currentScope.type !== "function" && currentScope.type !== "global") {
  32. currentScope = currentScope.upper;
  33. }
  34. return currentScope;
  35. }
  36. /**
  37. * Checks whether the given variable has any references from a more specific
  38. * function expression (i.e. a closure).
  39. *
  40. * @param {eslint-scope.Variable} variable - A variable to check.
  41. * @returns {boolean} `true` if the variable is used from a closure.
  42. */
  43. function isReferencedInClosure(variable) {
  44. const enclosingFunctionScope = getEnclosingFunctionScope(variable.scope);
  45. return variable.references.some(reference =>
  46. getEnclosingFunctionScope(reference.from) !== enclosingFunctionScope);
  47. }
  48. /**
  49. * Checks whether the given node is the assignee of a loop.
  50. *
  51. * @param {ASTNode} node - A VariableDeclaration node to check.
  52. * @returns {boolean} `true` if the declaration is assigned as part of loop
  53. * iteration.
  54. */
  55. function isLoopAssignee(node) {
  56. return (node.parent.type === "ForOfStatement" || node.parent.type === "ForInStatement") &&
  57. node === node.parent.left;
  58. }
  59. /**
  60. * Checks whether the given variable declaration is immediately initialized.
  61. *
  62. * @param {ASTNode} node - A VariableDeclaration node to check.
  63. * @returns {boolean} `true` if the declaration has an initializer.
  64. */
  65. function isDeclarationInitialized(node) {
  66. return node.declarations.every(declarator => declarator.init !== null);
  67. }
  68. const SCOPE_NODE_TYPE = /^(?:Program|BlockStatement|SwitchStatement|ForStatement|ForInStatement|ForOfStatement)$/;
  69. /**
  70. * Gets the scope node which directly contains a given node.
  71. *
  72. * @param {ASTNode} node - A node to get. This is a `VariableDeclaration` or
  73. * an `Identifier`.
  74. * @returns {ASTNode} A scope node. This is one of `Program`, `BlockStatement`,
  75. * `SwitchStatement`, `ForStatement`, `ForInStatement`, and
  76. * `ForOfStatement`.
  77. */
  78. function getScopeNode(node) {
  79. for (let currentNode = node; currentNode; currentNode = currentNode.parent) {
  80. if (SCOPE_NODE_TYPE.test(currentNode.type)) {
  81. return currentNode;
  82. }
  83. }
  84. /* istanbul ignore next : unreachable */
  85. return null;
  86. }
  87. /**
  88. * Checks whether a given variable is redeclared or not.
  89. *
  90. * @param {eslint-scope.Variable} variable - A variable to check.
  91. * @returns {boolean} `true` if the variable is redeclared.
  92. */
  93. function isRedeclared(variable) {
  94. return variable.defs.length >= 2;
  95. }
  96. /**
  97. * Checks whether a given variable is used from outside of the specified scope.
  98. *
  99. * @param {ASTNode} scopeNode - A scope node to check.
  100. * @returns {Function} The predicate function which checks whether a given
  101. * variable is used from outside of the specified scope.
  102. */
  103. function isUsedFromOutsideOf(scopeNode) {
  104. /**
  105. * Checks whether a given reference is inside of the specified scope or not.
  106. *
  107. * @param {eslint-scope.Reference} reference - A reference to check.
  108. * @returns {boolean} `true` if the reference is inside of the specified
  109. * scope.
  110. */
  111. function isOutsideOfScope(reference) {
  112. const scope = scopeNode.range;
  113. const id = reference.identifier.range;
  114. return id[0] < scope[0] || id[1] > scope[1];
  115. }
  116. return function(variable) {
  117. return variable.references.some(isOutsideOfScope);
  118. };
  119. }
  120. /**
  121. * Creates the predicate function which checks whether a variable has their references in TDZ.
  122. *
  123. * The predicate function would return `true`:
  124. *
  125. * - if a reference is before the declarator. E.g. (var a = b, b = 1;)(var {a = b, b} = {};)
  126. * - if a reference is in the expression of their default value. E.g. (var {a = a} = {};)
  127. * - if a reference is in the expression of their initializer. E.g. (var a = a;)
  128. *
  129. * @param {ASTNode} node - The initializer node of VariableDeclarator.
  130. * @returns {Function} The predicate function.
  131. * @private
  132. */
  133. function hasReferenceInTDZ(node) {
  134. const initStart = node.range[0];
  135. const initEnd = node.range[1];
  136. return variable => {
  137. const id = variable.defs[0].name;
  138. const idStart = id.range[0];
  139. const defaultValue = (id.parent.type === "AssignmentPattern" ? id.parent.right : null);
  140. const defaultStart = defaultValue && defaultValue.range[0];
  141. const defaultEnd = defaultValue && defaultValue.range[1];
  142. return variable.references.some(reference => {
  143. const start = reference.identifier.range[0];
  144. const end = reference.identifier.range[1];
  145. return !reference.init && (
  146. start < idStart ||
  147. (defaultValue !== null && start >= defaultStart && end <= defaultEnd) ||
  148. (start >= initStart && end <= initEnd)
  149. );
  150. });
  151. };
  152. }
  153. //------------------------------------------------------------------------------
  154. // Rule Definition
  155. //------------------------------------------------------------------------------
  156. module.exports = {
  157. meta: {
  158. type: "suggestion",
  159. docs: {
  160. description: "require `let` or `const` instead of `var`",
  161. category: "ECMAScript 6",
  162. recommended: false,
  163. url: "https://eslint.org/docs/rules/no-var"
  164. },
  165. schema: [],
  166. fixable: "code"
  167. },
  168. create(context) {
  169. const sourceCode = context.getSourceCode();
  170. /**
  171. * Checks whether the variables which are defined by the given declarator node have their references in TDZ.
  172. *
  173. * @param {ASTNode} declarator - The VariableDeclarator node to check.
  174. * @returns {boolean} `true` if one of the variables which are defined by the given declarator node have their references in TDZ.
  175. */
  176. function hasSelfReferenceInTDZ(declarator) {
  177. if (!declarator.init) {
  178. return false;
  179. }
  180. const variables = context.getDeclaredVariables(declarator);
  181. return variables.some(hasReferenceInTDZ(declarator.init));
  182. }
  183. /**
  184. * Checks whether it can fix a given variable declaration or not.
  185. * It cannot fix if the following cases:
  186. *
  187. * - A variable is a global variable.
  188. * - A variable is declared on a SwitchCase node.
  189. * - A variable is redeclared.
  190. * - A variable is used from outside the scope.
  191. * - A variable is used from a closure within a loop.
  192. * - A variable might be used before it is assigned within a loop.
  193. * - A variable might be used in TDZ.
  194. * - A variable is declared in statement position (e.g. a single-line `IfStatement`)
  195. *
  196. * ## A variable is declared on a SwitchCase node.
  197. *
  198. * If this rule modifies 'var' declarations on a SwitchCase node, it
  199. * would generate the warnings of 'no-case-declarations' rule. And the
  200. * 'eslint:recommended' preset includes 'no-case-declarations' rule, so
  201. * this rule doesn't modify those declarations.
  202. *
  203. * ## A variable is redeclared.
  204. *
  205. * The language spec disallows redeclarations of `let` declarations.
  206. * Those variables would cause syntax errors.
  207. *
  208. * ## A variable is used from outside the scope.
  209. *
  210. * The language spec disallows accesses from outside of the scope for
  211. * `let` declarations. Those variables would cause reference errors.
  212. *
  213. * ## A variable is used from a closure within a loop.
  214. *
  215. * A `var` declaration within a loop shares the same variable instance
  216. * across all loop iterations, while a `let` declaration creates a new
  217. * instance for each iteration. This means if a variable in a loop is
  218. * referenced by any closure, changing it from `var` to `let` would
  219. * change the behavior in a way that is generally unsafe.
  220. *
  221. * ## A variable might be used before it is assigned within a loop.
  222. *
  223. * Within a loop, a `let` declaration without an initializer will be
  224. * initialized to null, while a `var` declaration will retain its value
  225. * from the previous iteration, so it is only safe to change `var` to
  226. * `let` if we can statically determine that the variable is always
  227. * assigned a value before its first access in the loop body. To keep
  228. * the implementation simple, we only convert `var` to `let` within
  229. * loops when the variable is a loop assignee or the declaration has an
  230. * initializer.
  231. *
  232. * @param {ASTNode} node - A variable declaration node to check.
  233. * @returns {boolean} `true` if it can fix the node.
  234. */
  235. function canFix(node) {
  236. const variables = context.getDeclaredVariables(node);
  237. const scopeNode = getScopeNode(node);
  238. if (node.parent.type === "SwitchCase" ||
  239. node.declarations.some(hasSelfReferenceInTDZ) ||
  240. variables.some(isGlobal) ||
  241. variables.some(isRedeclared) ||
  242. variables.some(isUsedFromOutsideOf(scopeNode))
  243. ) {
  244. return false;
  245. }
  246. if (astUtils.isInLoop(node)) {
  247. if (variables.some(isReferencedInClosure)) {
  248. return false;
  249. }
  250. if (!isLoopAssignee(node) && !isDeclarationInitialized(node)) {
  251. return false;
  252. }
  253. }
  254. if (
  255. !isLoopAssignee(node) &&
  256. !(node.parent.type === "ForStatement" && node.parent.init === node) &&
  257. !astUtils.STATEMENT_LIST_PARENTS.has(node.parent.type)
  258. ) {
  259. // If the declaration is not in a block, e.g. `if (foo) var bar = 1;`, then it can't be fixed.
  260. return false;
  261. }
  262. return true;
  263. }
  264. /**
  265. * Reports a given variable declaration node.
  266. *
  267. * @param {ASTNode} node - A variable declaration node to report.
  268. * @returns {void}
  269. */
  270. function report(node) {
  271. const varToken = sourceCode.getFirstToken(node);
  272. context.report({
  273. node,
  274. message: "Unexpected var, use let or const instead.",
  275. fix(fixer) {
  276. if (canFix(node)) {
  277. return fixer.replaceText(varToken, "let");
  278. }
  279. return null;
  280. }
  281. });
  282. }
  283. return {
  284. "VariableDeclaration:exit"(node) {
  285. if (node.kind === "var") {
  286. report(node);
  287. }
  288. }
  289. };
  290. }
  291. };