preferForOfRule.js 6.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. "use strict";
  2. /**
  3. * @license
  4. * Copyright 2016 Palantir Technologies, Inc.
  5. *
  6. * Licensed under the Apache License, Version 2.0 (the "License");
  7. * you may not use this file except in compliance with the License.
  8. * You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. */
  18. Object.defineProperty(exports, "__esModule", { value: true });
  19. var tslib_1 = require("tslib");
  20. var utils = require("tsutils");
  21. var ts = require("typescript");
  22. var Lint = require("../index");
  23. var utils_1 = require("../language/utils");
  24. var Rule = /** @class */ (function (_super) {
  25. tslib_1.__extends(Rule, _super);
  26. function Rule() {
  27. return _super !== null && _super.apply(this, arguments) || this;
  28. }
  29. Rule.prototype.apply = function (sourceFile) {
  30. return this.applyWithFunction(sourceFile, walk);
  31. };
  32. /* tslint:disable:object-literal-sort-keys */
  33. Rule.metadata = {
  34. ruleName: "prefer-for-of",
  35. description: "Recommends a 'for-of' loop over a standard 'for' loop if the index is only used to access the array being iterated.",
  36. rationale: "A for(... of ...) loop is easier to implement and read when the index is not needed.",
  37. optionsDescription: "Not configurable.",
  38. options: null,
  39. optionExamples: [true],
  40. type: "typescript",
  41. typescriptOnly: false,
  42. };
  43. /* tslint:enable:object-literal-sort-keys */
  44. Rule.FAILURE_STRING = "Expected a 'for-of' loop instead of a 'for' loop with this simple iteration";
  45. return Rule;
  46. }(Lint.Rules.AbstractRule));
  47. exports.Rule = Rule;
  48. function walk(ctx) {
  49. var sourceFile = ctx.sourceFile;
  50. var variables;
  51. return ts.forEachChild(sourceFile, function cb(node) {
  52. if (utils.isForStatement(node)) {
  53. visitForStatement(node);
  54. }
  55. return ts.forEachChild(node, cb);
  56. });
  57. function visitForStatement(node) {
  58. var arrayNodeInfo = getForLoopHeaderInfo(node);
  59. if (arrayNodeInfo === undefined) {
  60. return;
  61. }
  62. var indexVariable = arrayNodeInfo.indexVariable, arrayExpr = arrayNodeInfo.arrayExpr;
  63. if (variables === undefined) {
  64. variables = utils.collectVariableUsage(sourceFile);
  65. }
  66. for (var _i = 0, _a = variables.get(indexVariable).uses; _i < _a.length; _i++) {
  67. var location = _a[_i].location;
  68. if (location.pos < node.initializer.end || location.pos >= node.end || // bail out on use outside of for loop
  69. location.pos >= node.statement.pos && // only check uses in loop body
  70. isNonSimpleIncrementorUse(location, arrayExpr, sourceFile)) {
  71. return;
  72. }
  73. }
  74. ctx.addFailure(node.getStart(sourceFile), node.statement.pos, Rule.FAILURE_STRING);
  75. }
  76. }
  77. function isNonSimpleIncrementorUse(node, arrayExpr, sourceFile) {
  78. // check if iterator is used for something other than reading data from array
  79. var parent = node.parent;
  80. return !utils.isElementAccessExpression(parent)
  81. // `a[i] = ...` or similar
  82. || utils.isReassignmentTarget(parent)
  83. // `b[i]`
  84. || !nodeEquals(arrayExpr, utils_1.unwrapParentheses(parent.expression), sourceFile);
  85. }
  86. function nodeEquals(a, b, sourceFile) {
  87. return a.getText(sourceFile) === b.getText(sourceFile);
  88. }
  89. // returns the iterator and array of a `for` loop if the `for` loop is basic.
  90. function getForLoopHeaderInfo(forLoop) {
  91. var initializer = forLoop.initializer, condition = forLoop.condition, incrementor = forLoop.incrementor;
  92. if (initializer === undefined || condition === undefined || incrementor === undefined) {
  93. return undefined;
  94. }
  95. // Must start with `var i = 0;` or `let i = 0;`
  96. if (!utils.isVariableDeclarationList(initializer) || initializer.declarations.length !== 1) {
  97. return undefined;
  98. }
  99. var _a = initializer.declarations[0], indexVariable = _a.name, indexInit = _a.initializer;
  100. if (indexVariable.kind !== ts.SyntaxKind.Identifier || indexInit === undefined || !isNumber(indexInit, "0")) {
  101. return undefined;
  102. }
  103. // Must end with `i++`
  104. if (!isIncremented(incrementor, indexVariable.text)) {
  105. return undefined;
  106. }
  107. // Condition must be `i < arr.length;`
  108. if (!utils.isBinaryExpression(condition)) {
  109. return undefined;
  110. }
  111. var left = condition.left, operatorToken = condition.operatorToken, right = condition.right;
  112. if (!isIdentifierNamed(left, indexVariable.text) ||
  113. operatorToken.kind !== ts.SyntaxKind.LessThanToken ||
  114. !utils.isPropertyAccessExpression(right)) {
  115. return undefined;
  116. }
  117. var arrayExpr = right.expression, name = right.name;
  118. if (name.text !== "length") {
  119. return undefined;
  120. }
  121. return { indexVariable: indexVariable, arrayExpr: arrayExpr };
  122. }
  123. function isIncremented(node, indexVariableName) {
  124. switch (node.kind) {
  125. case ts.SyntaxKind.PrefixUnaryExpression:
  126. case ts.SyntaxKind.PostfixUnaryExpression: {
  127. var _a = node, operator = _a.operator, operand = _a.operand;
  128. // `++x` or `x++`
  129. return operator === ts.SyntaxKind.PlusPlusToken && isVar(operand);
  130. }
  131. case ts.SyntaxKind.BinaryExpression:
  132. var _b = node, operatorToken = _b.operatorToken, updatedVar = _b.left, rhs = _b.right;
  133. if (!isVar(updatedVar)) {
  134. return false;
  135. }
  136. switch (operatorToken.kind) {
  137. case ts.SyntaxKind.PlusEqualsToken:
  138. // x += 1
  139. return isOne(rhs);
  140. case ts.SyntaxKind.EqualsToken: {
  141. if (!utils.isBinaryExpression(rhs)) {
  142. return false;
  143. }
  144. var rhsOp = rhs.operatorToken, left = rhs.left, right = rhs.right;
  145. // `x = 1 + x` or `x = x + 1`
  146. return rhsOp.kind === ts.SyntaxKind.PlusToken && (isVar(left) && isOne(right) || isOne(left) && isVar(right));
  147. }
  148. default:
  149. return false;
  150. }
  151. default:
  152. return false;
  153. }
  154. function isVar(id) {
  155. return isIdentifierNamed(id, indexVariableName);
  156. }
  157. }
  158. function isIdentifierNamed(node, text) {
  159. return utils.isIdentifier(node) && node.text === text;
  160. }
  161. function isOne(node) {
  162. return isNumber(node, "1");
  163. }
  164. function isNumber(node, value) {
  165. return utils.isNumericLiteral(node) && node.text === value;
  166. }