.gitignore added
[dotfiles/.git] / .config / coc / extensions / node_modules / coc-prettier / node_modules / tslint / lib / rules / preferReadonlyRule.js
1 "use strict";
2 /**
3  * @license
4  * Copyright 2017 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 typeUtils_1 = require("../language/typeUtils");
24 var utils_1 = require("../utils");
25 var OPTION_ONLY_INLINE_LAMBDAS = "only-inline-lambdas";
26 var Rule = /** @class */ (function (_super) {
27     tslib_1.__extends(Rule, _super);
28     function Rule() {
29         return _super !== null && _super.apply(this, arguments) || this;
30     }
31     Rule.prototype.applyWithProgram = function (sourceFile, program) {
32         var options = {
33             onlyInlineLambdas: this.ruleArguments.indexOf(OPTION_ONLY_INLINE_LAMBDAS) !== -1,
34         };
35         return this.applyWithFunction(sourceFile, walk, options, program.getTypeChecker());
36     };
37     Rule.metadata = {
38         description: "Requires that private variables are marked as `readonly` if they're never modified outside of the constructor.",
39         descriptionDetails: Lint.Utils.dedent(templateObject_1 || (templateObject_1 = tslib_1.__makeTemplateObject(["\n            If a private variable is only assigned to in the constructor, it should be declared as `readonly`.\n        "], ["\n            If a private variable is only assigned to in the constructor, it should be declared as \\`readonly\\`.\n        "]))),
40         optionExamples: [true, [true, OPTION_ONLY_INLINE_LAMBDAS]],
41         options: {
42             enum: [OPTION_ONLY_INLINE_LAMBDAS],
43             type: "string",
44         },
45         optionsDescription: Lint.Utils.dedent(templateObject_2 || (templateObject_2 = tslib_1.__makeTemplateObject(["\n            If `", "` is specified, only immediately-declared arrow functions are checked."], ["\n            If \\`", "\\` is specified, only immediately-declared arrow functions are checked."])), OPTION_ONLY_INLINE_LAMBDAS),
46         rationale: Lint.Utils.dedent(templateObject_3 || (templateObject_3 = tslib_1.__makeTemplateObject(["\n            Marking never-modified variables as readonly helps enforce the code's intent of keeping them as never-modified.\n            It can also help prevent accidental changes of members not meant to be changed."], ["\n            Marking never-modified variables as readonly helps enforce the code's intent of keeping them as never-modified.\n            It can also help prevent accidental changes of members not meant to be changed."]))),
47         requiresTypeInfo: true,
48         ruleName: "prefer-readonly",
49         type: "maintainability",
50         typescriptOnly: true,
51     };
52     return Rule;
53 }(Lint.Rules.TypedRule));
54 exports.Rule = Rule;
55 function walk(context, typeChecker) {
56     if (context.sourceFile.isDeclarationFile) {
57         return;
58     }
59     var scope;
60     ts.forEachChild(context.sourceFile, visitNode);
61     function visitNode(node) {
62         if (utils.hasModifier(node.modifiers, ts.SyntaxKind.DeclareKeyword)) {
63             return;
64         }
65         switch (node.kind) {
66             case ts.SyntaxKind.ClassDeclaration:
67             case ts.SyntaxKind.ClassExpression:
68                 handleClassDeclarationOrExpression(node);
69                 break;
70             case ts.SyntaxKind.Constructor:
71                 handleConstructor(node);
72                 break;
73             case ts.SyntaxKind.PropertyDeclaration:
74                 handlePropertyDeclaration(node);
75                 break;
76             case ts.SyntaxKind.PropertyAccessExpression:
77                 if (scope !== undefined) {
78                     handlePropertyAccessExpression(node, node.parent);
79                 }
80                 break;
81             default:
82                 // tslint:disable:deprecation This is needed for https://github.com/palantir/tslint/pull/4274 and will be fixed once TSLint
83                 // requires tsutils > 3.0.
84                 if (utils_1.isFunctionScopeBoundary(node)) {
85                     // tslint:enable:deprecation
86                     handleFunctionScopeBoundary(node);
87                 }
88                 else {
89                     ts.forEachChild(node, visitNode);
90                 }
91         }
92     }
93     function handleFunctionScopeBoundary(node) {
94         if (scope === undefined) {
95             ts.forEachChild(node, visitNode);
96             return;
97         }
98         scope.enterNonConstructorScope();
99         ts.forEachChild(node, visitNode);
100         scope.exitNonConstructorScope();
101     }
102     function handleClassDeclarationOrExpression(node) {
103         var parentScope = scope;
104         var childScope = (scope = new ClassScope(node, typeChecker));
105         ts.forEachChild(node, visitNode);
106         finalizeScope(childScope);
107         scope = parentScope;
108     }
109     function handleConstructor(node) {
110         scope.enterConstructor();
111         for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
112             var parameter = _a[_i];
113             if (utils.isModifierFlagSet(parameter, ts.ModifierFlags.Private)) {
114                 scope.addDeclaredVariable(parameter);
115             }
116         }
117         ts.forEachChild(node, visitNode);
118         scope.exitConstructor();
119     }
120     function handlePropertyDeclaration(node) {
121         if (!shouldPropertyDeclarationBeIgnored(node)) {
122             scope.addDeclaredVariable(node);
123         }
124         ts.forEachChild(node, visitNode);
125     }
126     function handlePropertyAccessExpression(node, parent) {
127         switch (parent.kind) {
128             case ts.SyntaxKind.BinaryExpression:
129                 handleParentBinaryExpression(node, parent);
130                 break;
131             case ts.SyntaxKind.DeleteExpression:
132                 handleDeleteExpression(node);
133                 break;
134             case ts.SyntaxKind.PostfixUnaryExpression:
135             case ts.SyntaxKind.PrefixUnaryExpression:
136                 handleParentPostfixOrPrefixUnaryExpression(parent);
137         }
138         ts.forEachChild(node, visitNode);
139     }
140     function handleParentBinaryExpression(node, parent) {
141         if (parent.left === node && utils.isAssignmentKind(parent.operatorToken.kind)) {
142             scope.addVariableModification(node);
143         }
144     }
145     function handleParentPostfixOrPrefixUnaryExpression(node) {
146         if (node.operator === ts.SyntaxKind.PlusPlusToken ||
147             node.operator === ts.SyntaxKind.MinusMinusToken) {
148             scope.addVariableModification(node.operand);
149         }
150     }
151     function handleDeleteExpression(node) {
152         scope.addVariableModification(node);
153     }
154     function shouldPropertyDeclarationBeIgnored(node) {
155         if (!context.options.onlyInlineLambdas) {
156             return false;
157         }
158         return (node.initializer === undefined || node.initializer.kind !== ts.SyntaxKind.ArrowFunction);
159     }
160     function finalizeScope(childScope) {
161         for (var _i = 0, _a = childScope.finalizeUnmodifiedPrivateNonReadonlys(); _i < _a.length; _i++) {
162             var violatingNode = _a[_i];
163             complainOnNode(violatingNode);
164         }
165     }
166     function complainOnNode(node) {
167         var fix = Lint.Replacement.appendText(node.modifiers.end, " readonly");
168         context.addFailureAtNode(node.name, createFailureString(node), fix);
169     }
170 }
171 function createFailureString(node) {
172     var accessibility = utils.isModifierFlagSet(node, ts.ModifierFlags.Static)
173         ? "static"
174         : "member";
175     var text = node.name.getText();
176     return "Private " + accessibility + " variable '" + text + "' is never reassigned; mark it as 'readonly'.";
177 }
178 var OUTSIDE_CONSTRUCTOR = -1;
179 var DIRECTLY_INSIDE_CONSTRUCTOR = 0;
180 var ClassScope = /** @class */ (function () {
181     function ClassScope(classNode, typeChecker) {
182         this.privateModifiableMembers = new Map();
183         this.privateModifiableStatics = new Map();
184         this.memberVariableModifications = new Set();
185         this.staticVariableModifications = new Set();
186         this.constructorScopeDepth = OUTSIDE_CONSTRUCTOR;
187         this.classType = typeChecker.getTypeAtLocation(classNode);
188         this.typeChecker = typeChecker;
189     }
190     ClassScope.prototype.addDeclaredVariable = function (node) {
191         if (!utils.isModifierFlagSet(node, ts.ModifierFlags.Private) ||
192             utils.isModifierFlagSet(node, ts.ModifierFlags.Readonly) ||
193             node.name.kind === ts.SyntaxKind.ComputedPropertyName) {
194             return;
195         }
196         if (utils.isModifierFlagSet(node, ts.ModifierFlags.Static)) {
197             this.privateModifiableStatics.set(node.name.getText(), node);
198         }
199         else {
200             this.privateModifiableMembers.set(node.name.getText(), node);
201         }
202     };
203     ClassScope.prototype.addVariableModification = function (node) {
204         var modifierType = this.typeChecker.getTypeAtLocation(node.expression);
205         if (modifierType.symbol === undefined ||
206             !typeUtils_1.typeIsOrHasBaseType(modifierType, this.classType)) {
207             return;
208         }
209         var toStatic = utils.isObjectType(modifierType) &&
210             utils.isObjectFlagSet(modifierType, ts.ObjectFlags.Anonymous);
211         if (!toStatic && this.constructorScopeDepth === DIRECTLY_INSIDE_CONSTRUCTOR) {
212             return;
213         }
214         var variable = node.name.text;
215         (toStatic ? this.staticVariableModifications : this.memberVariableModifications).add(variable);
216     };
217     ClassScope.prototype.enterConstructor = function () {
218         this.constructorScopeDepth = DIRECTLY_INSIDE_CONSTRUCTOR;
219     };
220     ClassScope.prototype.exitConstructor = function () {
221         this.constructorScopeDepth = OUTSIDE_CONSTRUCTOR;
222     };
223     ClassScope.prototype.enterNonConstructorScope = function () {
224         if (this.constructorScopeDepth !== OUTSIDE_CONSTRUCTOR) {
225             this.constructorScopeDepth += 1;
226         }
227     };
228     ClassScope.prototype.exitNonConstructorScope = function () {
229         if (this.constructorScopeDepth !== OUTSIDE_CONSTRUCTOR) {
230             this.constructorScopeDepth -= 1;
231         }
232     };
233     ClassScope.prototype.finalizeUnmodifiedPrivateNonReadonlys = function () {
234         var _this = this;
235         this.memberVariableModifications.forEach(function (variableName) {
236             _this.privateModifiableMembers.delete(variableName);
237         });
238         this.staticVariableModifications.forEach(function (variableName) {
239             _this.privateModifiableStatics.delete(variableName);
240         });
241         return Array.from(this.privateModifiableMembers.values()).concat(Array.from(this.privateModifiableStatics.values()));
242     };
243     return ClassScope;
244 }());
245 var templateObject_1, templateObject_2, templateObject_3;