4 * Copyright 2017 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 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);
29 return _super !== null && _super.apply(this, arguments) || this;
31 Rule.prototype.applyWithProgram = function (sourceFile, program) {
33 onlyInlineLambdas: this.ruleArguments.indexOf(OPTION_ONLY_INLINE_LAMBDAS) !== -1,
35 return this.applyWithFunction(sourceFile, walk, options, program.getTypeChecker());
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]],
42 enum: [OPTION_ONLY_INLINE_LAMBDAS],
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",
53 }(Lint.Rules.TypedRule));
55 function walk(context, typeChecker) {
56 if (context.sourceFile.isDeclarationFile) {
60 ts.forEachChild(context.sourceFile, visitNode);
61 function visitNode(node) {
62 if (utils.hasModifier(node.modifiers, ts.SyntaxKind.DeclareKeyword)) {
66 case ts.SyntaxKind.ClassDeclaration:
67 case ts.SyntaxKind.ClassExpression:
68 handleClassDeclarationOrExpression(node);
70 case ts.SyntaxKind.Constructor:
71 handleConstructor(node);
73 case ts.SyntaxKind.PropertyDeclaration:
74 handlePropertyDeclaration(node);
76 case ts.SyntaxKind.PropertyAccessExpression:
77 if (scope !== undefined) {
78 handlePropertyAccessExpression(node, node.parent);
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);
89 ts.forEachChild(node, visitNode);
93 function handleFunctionScopeBoundary(node) {
94 if (scope === undefined) {
95 ts.forEachChild(node, visitNode);
98 scope.enterNonConstructorScope();
99 ts.forEachChild(node, visitNode);
100 scope.exitNonConstructorScope();
102 function handleClassDeclarationOrExpression(node) {
103 var parentScope = scope;
104 var childScope = (scope = new ClassScope(node, typeChecker));
105 ts.forEachChild(node, visitNode);
106 finalizeScope(childScope);
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);
117 ts.forEachChild(node, visitNode);
118 scope.exitConstructor();
120 function handlePropertyDeclaration(node) {
121 if (!shouldPropertyDeclarationBeIgnored(node)) {
122 scope.addDeclaredVariable(node);
124 ts.forEachChild(node, visitNode);
126 function handlePropertyAccessExpression(node, parent) {
127 switch (parent.kind) {
128 case ts.SyntaxKind.BinaryExpression:
129 handleParentBinaryExpression(node, parent);
131 case ts.SyntaxKind.DeleteExpression:
132 handleDeleteExpression(node);
134 case ts.SyntaxKind.PostfixUnaryExpression:
135 case ts.SyntaxKind.PrefixUnaryExpression:
136 handleParentPostfixOrPrefixUnaryExpression(parent);
138 ts.forEachChild(node, visitNode);
140 function handleParentBinaryExpression(node, parent) {
141 if (parent.left === node && utils.isAssignmentKind(parent.operatorToken.kind)) {
142 scope.addVariableModification(node);
145 function handleParentPostfixOrPrefixUnaryExpression(node) {
146 if (node.operator === ts.SyntaxKind.PlusPlusToken ||
147 node.operator === ts.SyntaxKind.MinusMinusToken) {
148 scope.addVariableModification(node.operand);
151 function handleDeleteExpression(node) {
152 scope.addVariableModification(node);
154 function shouldPropertyDeclarationBeIgnored(node) {
155 if (!context.options.onlyInlineLambdas) {
158 return (node.initializer === undefined || node.initializer.kind !== ts.SyntaxKind.ArrowFunction);
160 function finalizeScope(childScope) {
161 for (var _i = 0, _a = childScope.finalizeUnmodifiedPrivateNonReadonlys(); _i < _a.length; _i++) {
162 var violatingNode = _a[_i];
163 complainOnNode(violatingNode);
166 function complainOnNode(node) {
167 var fix = Lint.Replacement.appendText(node.modifiers.end, " readonly");
168 context.addFailureAtNode(node.name, createFailureString(node), fix);
171 function createFailureString(node) {
172 var accessibility = utils.isModifierFlagSet(node, ts.ModifierFlags.Static)
175 var text = node.name.getText();
176 return "Private " + accessibility + " variable '" + text + "' is never reassigned; mark it as 'readonly'.";
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;
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) {
196 if (utils.isModifierFlagSet(node, ts.ModifierFlags.Static)) {
197 this.privateModifiableStatics.set(node.name.getText(), node);
200 this.privateModifiableMembers.set(node.name.getText(), node);
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)) {
209 var toStatic = utils.isObjectType(modifierType) &&
210 utils.isObjectFlagSet(modifierType, ts.ObjectFlags.Anonymous);
211 if (!toStatic && this.constructorScopeDepth === DIRECTLY_INSIDE_CONSTRUCTOR) {
214 var variable = node.name.text;
215 (toStatic ? this.staticVariableModifications : this.memberVariableModifications).add(variable);
217 ClassScope.prototype.enterConstructor = function () {
218 this.constructorScopeDepth = DIRECTLY_INSIDE_CONSTRUCTOR;
220 ClassScope.prototype.exitConstructor = function () {
221 this.constructorScopeDepth = OUTSIDE_CONSTRUCTOR;
223 ClassScope.prototype.enterNonConstructorScope = function () {
224 if (this.constructorScopeDepth !== OUTSIDE_CONSTRUCTOR) {
225 this.constructorScopeDepth += 1;
228 ClassScope.prototype.exitNonConstructorScope = function () {
229 if (this.constructorScopeDepth !== OUTSIDE_CONSTRUCTOR) {
230 this.constructorScopeDepth -= 1;
233 ClassScope.prototype.finalizeUnmodifiedPrivateNonReadonlys = function () {
235 this.memberVariableModifications.forEach(function (variableName) {
236 _this.privateModifiableMembers.delete(variableName);
238 this.staticVariableModifications.forEach(function (variableName) {
239 _this.privateModifiableStatics.delete(variableName);
241 return Array.from(this.privateModifiableMembers.values()).concat(Array.from(this.privateModifiableStatics.values()));
245 var templateObject_1, templateObject_2, templateObject_3;