.gitignore added
[dotfiles/.git] / .config / coc / extensions / node_modules / coc-prettier / node_modules / tslint / lib / rules / preferForOfRule.js
1 "use strict";
2 /**
3  * @license
4  * Copyright 2018 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 ||
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))) {
72                 return;
73             }
74         }
75         ctx.addFailure(node.getStart(sourceFile), node.statement.pos, Rule.FAILURE_STRING);
76     }
77 }
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) ||
84         // `b[i]`
85         !nodeEquals(arrayExpr, utils_1.unwrapParentheses(parent.expression), sourceFile));
86 }
87 function nodeEquals(a, b, sourceFile) {
88     return a.getText(sourceFile) === b.getText(sourceFile);
89 }
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) {
94         return undefined;
95     }
96     // Must start with `var i = 0;` or `let i = 0;`
97     if (!utils.isVariableDeclarationList(initializer) || initializer.declarations.length !== 1) {
98         return undefined;
99     }
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")) {
104         return undefined;
105     }
106     // Must end with `i++`
107     if (!isIncremented(incrementor, indexVariable.text)) {
108         return undefined;
109     }
110     // Condition must be `i < arr.length;`
111     if (!utils.isBinaryExpression(condition)) {
112         return undefined;
113     }
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)) {
118         return undefined;
119     }
120     var arrayExpr = right.expression, name = right.name;
121     if (name.text !== "length") {
122         return undefined;
123     }
124     return { indexVariable: indexVariable, arrayExpr: arrayExpr };
125 }
126 function isIncremented(node, indexVariableName) {
127     switch (node.kind) {
128         case ts.SyntaxKind.PrefixUnaryExpression:
129         case ts.SyntaxKind.PostfixUnaryExpression: {
130             var _a = node, operator = _a.operator, operand = _a.operand;
131             // `++x` or `x++`
132             return operator === ts.SyntaxKind.PlusPlusToken && isVar(operand);
133         }
134         case ts.SyntaxKind.BinaryExpression:
135             var _b = node, operatorToken = _b.operatorToken, updatedVar = _b.left, rhs = _b.right;
136             if (!isVar(updatedVar)) {
137                 return false;
138             }
139             switch (operatorToken.kind) {
140                 case ts.SyntaxKind.PlusEqualsToken:
141                     // x += 1
142                     return isOne(rhs);
143                 case ts.SyntaxKind.EqualsToken: {
144                     if (!utils.isBinaryExpression(rhs)) {
145                         return false;
146                     }
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))));
151                 }
152                 default:
153                     return false;
154             }
155         default:
156             return false;
157     }
158     function isVar(id) {
159         return isIdentifierNamed(id, indexVariableName);
160     }
161 }
162 function isIdentifierNamed(node, text) {
163     return utils.isIdentifier(node) && node.text === text;
164 }
165 function isOne(node) {
166     return isNumber(node, "1");
167 }
168 function isNumber(node, value) {
169     return utils.isNumericLiteral(node) && node.text === value;
170 }