.gitignore added
[dotfiles/.git] / .config / coc / extensions / node_modules / coc-prettier / node_modules / tslint / lib / rules / noUnboundMethodRule.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 _a, _b;
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 = [
29     true,
30     (_a = {},
31         _a[OPTION_IGNORE_STATIC] = true,
32         _a[OPTION_WHITELIST] = ["expect"],
33         _a[OPTION_ALLOW_TYPEOF] = true,
34         _a),
35 ];
36 var Rule = /** @class */ (function (_super) {
37     tslib_1.__extends(Rule, _super);
38     function Rule() {
39         return _super !== null && _super.apply(this, arguments) || this;
40     }
41     Rule.prototype.applyWithProgram = function (sourceFile, program) {
42         return this.applyWithFunction(sourceFile, walk, parseArguments(this.ruleArguments), program.getTypeChecker());
43     };
44     /* tslint:disable:object-literal-sort-keys */
45     Rule.metadata = {
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),
49         options: {
50             anyOf: [
51                 {
52                     type: "string",
53                     enum: [OPTION_IGNORE_STATIC],
54                 },
55                 {
56                     type: "object",
57                     properties: (_b = {},
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] = {
62                             type: "array",
63                             items: { type: "string" },
64                             minLength: 1,
65                         },
66                         _b),
67                 },
68             ],
69         },
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",
73         typescriptOnly: true,
74         requiresTypeInfo: true,
75     };
76     /* tslint:enable:object-literal-sort-keys */
77     Rule.FAILURE_STRING = "Avoid referencing unbound methods which may cause unintentional scoping of 'this'.";
78     return Rule;
79 }(Lint.Rules.TypedRule));
80 exports.Rule = Rule;
81 function parseArguments(args) {
82     var options = {
83         allowDelete: false,
84         allowTypeof: false,
85         ignoreStatic: false,
86         whitelist: new Set(),
87     };
88     for (var _i = 0, args_1 = args; _i < args_1.length; _i++) {
89         var arg = args_1[_i];
90         if (typeof arg === "string") {
91             if (arg === OPTION_IGNORE_STATIC) {
92                 options.ignoreStatic = true;
93             }
94         }
95         else {
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]);
100         }
101     }
102     return options;
103 }
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);
113             }
114         }
115         return ts.forEachChild(node, cb);
116     });
117 }
118 function isMethod(node, ignoreStatic) {
119     switch (node.kind) {
120         case ts.SyntaxKind.MethodDeclaration:
121         case ts.SyntaxKind.MethodSignature:
122             return !(ignoreStatic && tsutils_1.hasModifier(node.modifiers, ts.SyntaxKind.StaticKeyword));
123         default:
124             return false;
125     }
126 }
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:
137             return true;
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:
154             return true;
155         default:
156             return false;
157     }
158 }
159 function isWhitelisted(node, options) {
160     var whitelist = options.whitelist, allowTypeof = options.allowTypeof, allowDelete = options.allowDelete;
161     if (tsutils_1.isDeleteExpression(node.parent)) {
162         return allowDelete;
163     }
164     if (tsutils_1.isTypeOfExpression(node.parent)) {
165         return allowTypeof;
166     }
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);
171     }
172     return false;
173 }
174 var templateObject_1, templateObject_2;