项目原始demo,不改动
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
Den här utvecklingskatalogen är arkiverad. Du kan se filer och klona katalogen, men inte öppna ärenden eller genomföra push- eller pull-förfrågningar.
 
 
 
 

330 rader
12 KiB

  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("../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. docs: {
  159. description: "require `let` or `const` instead of `var`",
  160. category: "ECMAScript 6",
  161. recommended: false,
  162. url: "https://eslint.org/docs/rules/no-var"
  163. },
  164. schema: [],
  165. fixable: "code"
  166. },
  167. create(context) {
  168. const sourceCode = context.getSourceCode();
  169. /**
  170. * Checks whether the variables which are defined by the given declarator node have their references in TDZ.
  171. *
  172. * @param {ASTNode} declarator - The VariableDeclarator node to check.
  173. * @returns {boolean} `true` if one of the variables which are defined by the given declarator node have their references in TDZ.
  174. */
  175. function hasSelfReferenceInTDZ(declarator) {
  176. if (!declarator.init) {
  177. return false;
  178. }
  179. const variables = context.getDeclaredVariables(declarator);
  180. return variables.some(hasReferenceInTDZ(declarator.init));
  181. }
  182. /**
  183. * Checks whether it can fix a given variable declaration or not.
  184. * It cannot fix if the following cases:
  185. *
  186. * - A variable is a global variable.
  187. * - A variable is declared on a SwitchCase node.
  188. * - A variable is redeclared.
  189. * - A variable is used from outside the scope.
  190. * - A variable is used from a closure within a loop.
  191. * - A variable might be used before it is assigned within a loop.
  192. * - A variable might be used in TDZ.
  193. * - A variable is declared in statement position (e.g. a single-line `IfStatement`)
  194. *
  195. * ## A variable is declared on a SwitchCase node.
  196. *
  197. * If this rule modifies 'var' declarations on a SwitchCase node, it
  198. * would generate the warnings of 'no-case-declarations' rule. And the
  199. * 'eslint:recommended' preset includes 'no-case-declarations' rule, so
  200. * this rule doesn't modify those declarations.
  201. *
  202. * ## A variable is redeclared.
  203. *
  204. * The language spec disallows redeclarations of `let` declarations.
  205. * Those variables would cause syntax errors.
  206. *
  207. * ## A variable is used from outside the scope.
  208. *
  209. * The language spec disallows accesses from outside of the scope for
  210. * `let` declarations. Those variables would cause reference errors.
  211. *
  212. * ## A variable is used from a closure within a loop.
  213. *
  214. * A `var` declaration within a loop shares the same variable instance
  215. * across all loop iterations, while a `let` declaration creates a new
  216. * instance for each iteration. This means if a variable in a loop is
  217. * referenced by any closure, changing it from `var` to `let` would
  218. * change the behavior in a way that is generally unsafe.
  219. *
  220. * ## A variable might be used before it is assigned within a loop.
  221. *
  222. * Within a loop, a `let` declaration without an initializer will be
  223. * initialized to null, while a `var` declaration will retain its value
  224. * from the previous iteration, so it is only safe to change `var` to
  225. * `let` if we can statically determine that the variable is always
  226. * assigned a value before its first access in the loop body. To keep
  227. * the implementation simple, we only convert `var` to `let` within
  228. * loops when the variable is a loop assignee or the declaration has an
  229. * initializer.
  230. *
  231. * @param {ASTNode} node - A variable declaration node to check.
  232. * @returns {boolean} `true` if it can fix the node.
  233. */
  234. function canFix(node) {
  235. const variables = context.getDeclaredVariables(node);
  236. const scopeNode = getScopeNode(node);
  237. if (node.parent.type === "SwitchCase" ||
  238. node.declarations.some(hasSelfReferenceInTDZ) ||
  239. variables.some(isGlobal) ||
  240. variables.some(isRedeclared) ||
  241. variables.some(isUsedFromOutsideOf(scopeNode))
  242. ) {
  243. return false;
  244. }
  245. if (astUtils.isInLoop(node)) {
  246. if (variables.some(isReferencedInClosure)) {
  247. return false;
  248. }
  249. if (!isLoopAssignee(node) && !isDeclarationInitialized(node)) {
  250. return false;
  251. }
  252. }
  253. if (
  254. !isLoopAssignee(node) &&
  255. !(node.parent.type === "ForStatement" && node.parent.init === node) &&
  256. !astUtils.STATEMENT_LIST_PARENTS.has(node.parent.type)
  257. ) {
  258. // If the declaration is not in a block, e.g. `if (foo) var bar = 1;`, then it can't be fixed.
  259. return false;
  260. }
  261. return true;
  262. }
  263. /**
  264. * Reports a given variable declaration node.
  265. *
  266. * @param {ASTNode} node - A variable declaration node to report.
  267. * @returns {void}
  268. */
  269. function report(node) {
  270. const varToken = sourceCode.getFirstToken(node);
  271. context.report({
  272. node,
  273. message: "Unexpected var, use let or const instead.",
  274. fix(fixer) {
  275. if (canFix(node)) {
  276. return fixer.replaceText(varToken, "let");
  277. }
  278. return null;
  279. }
  280. });
  281. }
  282. return {
  283. "VariableDeclaration:exit"(node) {
  284. if (node.kind === "var") {
  285. report(node);
  286. }
  287. }
  288. };
  289. }
  290. };