4 * Copyright 2018 Palantir Technologies, Inc.
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
10 * http://www.apache.org/licenses/LICENSE-2.0
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.
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);
27 return _super !== null && _super.apply(this, arguments) || this;
29 Rule.prototype.apply = function (sourceFile) {
30 return this.applyWithFunction(sourceFile, walk);
32 /* tslint:disable:object-literal-sort-keys */
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.",
39 optionExamples: [true],
41 typescriptOnly: false,
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";
46 }(Lint.Rules.AbstractRule));
49 var sourceFile = ctx.sourceFile;
51 return ts.forEachChild(sourceFile, function cb(node) {
52 if (utils.isForStatement(node)) {
53 visitForStatement(node);
55 return ts.forEachChild(node, cb);
57 function visitForStatement(node) {
58 var arrayNodeInfo = getForLoopHeaderInfo(node);
59 if (arrayNodeInfo === undefined) {
62 var indexVariable = arrayNodeInfo.indexVariable, arrayExpr = arrayNodeInfo.arrayExpr;
63 if (variables === undefined) {
64 variables = utils.collectVariableUsage(sourceFile);
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 ||
69 location.pos >= node.end || // bail out on use outside of for loop
70 (location.pos >= node.statement.pos && // only check uses in loop body
71 isNonSimpleIncrementorUse(location, arrayExpr, sourceFile))) {
75 ctx.addFailure(node.getStart(sourceFile), node.statement.pos, Rule.FAILURE_STRING);
78 function isNonSimpleIncrementorUse(node, arrayExpr, sourceFile) {
79 // check if iterator is used for something other than reading data from array
80 var parent = node.parent;
81 return (!utils.isElementAccessExpression(parent) ||
82 // `a[i] = ...` or similar
83 utils.isReassignmentTarget(parent) ||
85 !nodeEquals(arrayExpr, utils_1.unwrapParentheses(parent.expression), sourceFile));
87 function nodeEquals(a, b, sourceFile) {
88 return a.getText(sourceFile) === b.getText(sourceFile);
90 // returns the iterator and array of a `for` loop if the `for` loop is basic.
91 function getForLoopHeaderInfo(forLoop) {
92 var initializer = forLoop.initializer, condition = forLoop.condition, incrementor = forLoop.incrementor;
93 if (initializer === undefined || condition === undefined || incrementor === undefined) {
96 // Must start with `var i = 0;` or `let i = 0;`
97 if (!utils.isVariableDeclarationList(initializer) || initializer.declarations.length !== 1) {
100 var _a = initializer.declarations[0], indexVariable = _a.name, indexInit = _a.initializer;
101 if (indexVariable.kind !== ts.SyntaxKind.Identifier ||
102 indexInit === undefined ||
103 !isNumber(indexInit, "0")) {
106 // Must end with `i++`
107 if (!isIncremented(incrementor, indexVariable.text)) {
110 // Condition must be `i < arr.length;`
111 if (!utils.isBinaryExpression(condition)) {
114 var left = condition.left, operatorToken = condition.operatorToken, right = condition.right;
115 if (!isIdentifierNamed(left, indexVariable.text) ||
116 operatorToken.kind !== ts.SyntaxKind.LessThanToken ||
117 !utils.isPropertyAccessExpression(right)) {
120 var arrayExpr = right.expression, name = right.name;
121 if (name.text !== "length") {
124 return { indexVariable: indexVariable, arrayExpr: arrayExpr };
126 function isIncremented(node, indexVariableName) {
128 case ts.SyntaxKind.PrefixUnaryExpression:
129 case ts.SyntaxKind.PostfixUnaryExpression: {
130 var _a = node, operator = _a.operator, operand = _a.operand;
132 return operator === ts.SyntaxKind.PlusPlusToken && isVar(operand);
134 case ts.SyntaxKind.BinaryExpression:
135 var _b = node, operatorToken = _b.operatorToken, updatedVar = _b.left, rhs = _b.right;
136 if (!isVar(updatedVar)) {
139 switch (operatorToken.kind) {
140 case ts.SyntaxKind.PlusEqualsToken:
143 case ts.SyntaxKind.EqualsToken: {
144 if (!utils.isBinaryExpression(rhs)) {
147 var rhsOp = rhs.operatorToken, left = rhs.left, right = rhs.right;
148 // `x = 1 + x` or `x = x + 1`
149 return (rhsOp.kind === ts.SyntaxKind.PlusToken &&
150 ((isVar(left) && isOne(right)) || (isOne(left) && isVar(right))));
159 return isIdentifierNamed(id, indexVariableName);
162 function isIdentifierNamed(node, text) {
163 return utils.isIdentifier(node) && node.text === text;
165 function isOne(node) {
166 return isNumber(node, "1");
168 function isNumber(node, value) {
169 return utils.isNumericLiteral(node) && node.text === value;