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");
21 var tsutils_1 = require("tsutils");
22 var ts = require("typescript");
23 var Lint = require("../index");
24 var OPTION_IGNORE_STATIC = "ignore-static";
25 var OPTION_WHITELIST = "whitelist";
26 var OPTION_ALLOW_TYPEOF = "allow-typeof";
27 var OPTION_ALLOW_DELETE = "allow-delete";
28 var OPTION_WHITELIST_EXAMPLE = [
31 _a[OPTION_IGNORE_STATIC] = true,
32 _a[OPTION_WHITELIST] = ["expect"],
33 _a[OPTION_ALLOW_TYPEOF] = true,
36 var Rule = /** @class */ (function (_super) {
37 tslib_1.__extends(Rule, _super);
39 return _super !== null && _super.apply(this, arguments) || this;
41 Rule.prototype.applyWithProgram = function (sourceFile, program) {
42 return this.applyWithFunction(sourceFile, walk, parseArguments(this.ruleArguments), program.getTypeChecker());
44 /* tslint:disable:object-literal-sort-keys */
46 ruleName: "no-unbound-method",
47 description: "Warns when a method is used outside of a method call.",
48 optionsDescription: Lint.Utils.dedent(templateObject_1 || (templateObject_1 = tslib_1.__makeTemplateObject(["\n You may additionally pass \"", "\" to ignore static methods, or an options object.\n \n The object may have the following properties:\n \n * \"", "\" - to ignore static methods.\n * \"", "\" - ignore methods referenced in a delete expression.\n * \"", "\" - ignore methods referenced in a typeof expression.\n * \"", "\" - ignore method references in parameters of specifed function calls.\n \n "], ["\n You may additionally pass \"", "\" to ignore static methods, or an options object.\n \n The object may have the following properties:\n \n * \"", "\" - to ignore static methods.\n * \"", "\" - ignore methods referenced in a delete expression.\n * \"", "\" - ignore methods referenced in a typeof expression.\n * \"", "\" - ignore method references in parameters of specifed function calls.\n \n "])), OPTION_IGNORE_STATIC, OPTION_IGNORE_STATIC, OPTION_ALLOW_DELETE, OPTION_ALLOW_TYPEOF, OPTION_WHITELIST),
53 enum: [OPTION_IGNORE_STATIC],
58 _b[OPTION_ALLOW_DELETE] = { type: "boolean" },
59 _b[OPTION_ALLOW_TYPEOF] = { type: "boolean" },
60 _b[OPTION_IGNORE_STATIC] = { type: "boolean" },
61 _b[OPTION_WHITELIST] = {
63 items: { type: "string" },
70 optionExamples: [true, [true, OPTION_IGNORE_STATIC], OPTION_WHITELIST_EXAMPLE],
71 rationale: Lint.Utils.dedent(templateObject_2 || (templateObject_2 = tslib_1.__makeTemplateObject(["\n Class functions don't preserve the class scope when passed as standalone variables.\n For example, this code will log the global scope (`window`/`global`), not the class instance:\n\n ```\n class MyClass {\n public log(): void {\n console.log(this);\n }\n }\n\n const instance = new MyClass();\n const log = instance.log;\n\n log();\n ```\n\n You need to either use an arrow lambda (`() => {...}`) or call the function with the correct scope.\n\n ```\n class MyClass {\n public logArrowBound = (): void => {\n console.log(bound);\n };\n\n public logManualBind(): void {\n console.log(this);\n }\n }\n\n const instance = new MyClass();\n const logArrowBound = instance.logArrowBound;\n const logManualBind = instance.logManualBind.bind(instance);\n\n logArrowBound();\n logManualBind();\n ```\n "], ["\n Class functions don't preserve the class scope when passed as standalone variables.\n For example, this code will log the global scope (\\`window\\`/\\`global\\`), not the class instance:\n\n \\`\\`\\`\n class MyClass {\n public log(): void {\n console.log(this);\n }\n }\n\n const instance = new MyClass();\n const log = instance.log;\n\n log();\n \\`\\`\\`\n\n You need to either use an arrow lambda (\\`() => {...}\\`) or call the function with the correct scope.\n\n \\`\\`\\`\n class MyClass {\n public logArrowBound = (): void => {\n console.log(bound);\n };\n\n public logManualBind(): void {\n console.log(this);\n }\n }\n\n const instance = new MyClass();\n const logArrowBound = instance.logArrowBound;\n const logManualBind = instance.logManualBind.bind(instance);\n\n logArrowBound();\n logManualBind();\n \\`\\`\\`\n "]))),
72 type: "functionality",
74 requiresTypeInfo: true,
76 /* tslint:enable:object-literal-sort-keys */
77 Rule.FAILURE_STRING = "Avoid referencing unbound methods which may cause unintentional scoping of 'this'.";
79 }(Lint.Rules.TypedRule));
81 function parseArguments(args) {
88 for (var _i = 0, args_1 = args; _i < args_1.length; _i++) {
90 if (typeof arg === "string") {
91 if (arg === OPTION_IGNORE_STATIC) {
92 options.ignoreStatic = true;
96 options.allowDelete = arg[OPTION_ALLOW_DELETE] || false;
97 options.allowTypeof = arg[OPTION_ALLOW_TYPEOF] || false;
98 options.ignoreStatic = arg[OPTION_IGNORE_STATIC] || false;
99 options.whitelist = new Set(arg[OPTION_WHITELIST]);
104 function walk(ctx, tc) {
105 return ts.forEachChild(ctx.sourceFile, function cb(node) {
106 if (tsutils_1.isPropertyAccessExpression(node) && !isSafeUse(node)) {
107 var symbol = tc.getSymbolAtLocation(node);
108 var declaration = symbol === undefined ? undefined : symbol.valueDeclaration;
109 var isMethodAccess = declaration !== undefined && isMethod(declaration, ctx.options.ignoreStatic);
110 var shouldBeReported = isMethodAccess && !isWhitelisted(node, ctx.options);
111 if (shouldBeReported) {
112 ctx.addFailureAtNode(node, Rule.FAILURE_STRING);
115 return ts.forEachChild(node, cb);
118 function isMethod(node, ignoreStatic) {
120 case ts.SyntaxKind.MethodDeclaration:
121 case ts.SyntaxKind.MethodSignature:
122 return !(ignoreStatic && tsutils_1.hasModifier(node.modifiers, ts.SyntaxKind.StaticKeyword));
127 function isSafeUse(node) {
128 var parent = node.parent;
129 switch (parent.kind) {
130 case ts.SyntaxKind.CallExpression:
131 return parent.expression === node;
132 case ts.SyntaxKind.TaggedTemplateExpression:
133 return parent.tag === node;
134 // E.g. `obj.method.bind(obj) or obj.method["prop"]`.
135 case ts.SyntaxKind.PropertyAccessExpression:
136 case ts.SyntaxKind.ElementAccessExpression:
138 // Allow most binary operators, but don't allow e.g. `myArray.forEach(obj.method || otherObj.otherMethod)`.
139 case ts.SyntaxKind.BinaryExpression:
140 return parent.operatorToken.kind !== ts.SyntaxKind.BarBarToken;
141 case ts.SyntaxKind.NonNullExpression:
142 case ts.SyntaxKind.AsExpression:
143 case ts.SyntaxKind.TypeAssertionExpression:
144 case ts.SyntaxKind.ParenthesizedExpression:
145 return isSafeUse(parent);
146 // Allow use in conditions
147 case ts.SyntaxKind.ConditionalExpression:
148 return parent.condition === node;
149 case ts.SyntaxKind.IfStatement:
150 case ts.SyntaxKind.WhileStatement:
151 case ts.SyntaxKind.DoStatement:
152 case ts.SyntaxKind.ForStatement:
153 case ts.SyntaxKind.PrefixUnaryExpression:
159 function isWhitelisted(node, options) {
160 var whitelist = options.whitelist, allowTypeof = options.allowTypeof, allowDelete = options.allowDelete;
161 if (tsutils_1.isDeleteExpression(node.parent)) {
164 if (tsutils_1.isTypeOfExpression(node.parent)) {
167 if (tsutils_1.isCallExpression(node.parent) && tsutils_1.isIdentifier(node.parent.expression)) {
168 var expression = node.parent.expression;
169 var callingMethodName = expression.text;
170 return whitelist.has(callingMethodName);
174 var templateObject_1, templateObject_2;