noUnboundMethodRule.js 6.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  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 tsutils_1 = require("tsutils");
  21. var ts = require("typescript");
  22. var Lint = require("../index");
  23. var OPTION_IGNORE_STATIC = "ignore-static";
  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.applyWithProgram = function (sourceFile, program) {
  30. return this.applyWithFunction(sourceFile, walk, {
  31. ignoreStatic: this.ruleArguments.indexOf(OPTION_IGNORE_STATIC) !== -1,
  32. }, program.getTypeChecker());
  33. };
  34. /* tslint:disable:object-literal-sort-keys */
  35. Rule.metadata = {
  36. ruleName: "no-unbound-method",
  37. description: "Warns when a method is used outside of a method call.",
  38. optionsDescription: "You may optionally pass \"" + OPTION_IGNORE_STATIC + "\" to ignore static methods.",
  39. options: {
  40. type: "string",
  41. enum: [OPTION_IGNORE_STATIC],
  42. },
  43. optionExamples: [true, [true, OPTION_IGNORE_STATIC]],
  44. rationale: Lint.Utils.dedent(templateObject_1 || (templateObject_1 = 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 "]))),
  45. type: "functionality",
  46. typescriptOnly: true,
  47. requiresTypeInfo: true,
  48. };
  49. /* tslint:enable:object-literal-sort-keys */
  50. Rule.FAILURE_STRING = "Avoid referencing unbound methods which may cause unintentional scoping of 'this'.";
  51. return Rule;
  52. }(Lint.Rules.TypedRule));
  53. exports.Rule = Rule;
  54. function walk(ctx, tc) {
  55. return ts.forEachChild(ctx.sourceFile, function cb(node) {
  56. if (tsutils_1.isPropertyAccessExpression(node) && !isSafeUse(node)) {
  57. var symbol = tc.getSymbolAtLocation(node);
  58. var declaration = symbol === undefined ? undefined : symbol.valueDeclaration;
  59. if (declaration !== undefined && isMethod(declaration, ctx.options.ignoreStatic)) {
  60. ctx.addFailureAtNode(node, Rule.FAILURE_STRING);
  61. }
  62. }
  63. return ts.forEachChild(node, cb);
  64. });
  65. }
  66. function isMethod(node, ignoreStatic) {
  67. switch (node.kind) {
  68. case ts.SyntaxKind.MethodDeclaration:
  69. case ts.SyntaxKind.MethodSignature:
  70. return !(ignoreStatic && tsutils_1.hasModifier(node.modifiers, ts.SyntaxKind.StaticKeyword));
  71. default:
  72. return false;
  73. }
  74. }
  75. function isSafeUse(node) {
  76. var parent = node.parent;
  77. switch (parent.kind) {
  78. case ts.SyntaxKind.CallExpression:
  79. return parent.expression === node;
  80. case ts.SyntaxKind.TaggedTemplateExpression:
  81. return parent.tag === node;
  82. // E.g. `obj.method.bind(obj) or obj.method["prop"]`.
  83. case ts.SyntaxKind.PropertyAccessExpression:
  84. case ts.SyntaxKind.ElementAccessExpression:
  85. return true;
  86. // Allow most binary operators, but don't allow e.g. `myArray.forEach(obj.method || otherObj.otherMethod)`.
  87. case ts.SyntaxKind.BinaryExpression:
  88. return parent.operatorToken.kind !== ts.SyntaxKind.BarBarToken;
  89. case ts.SyntaxKind.NonNullExpression:
  90. case ts.SyntaxKind.AsExpression:
  91. case ts.SyntaxKind.TypeAssertionExpression:
  92. case ts.SyntaxKind.ParenthesizedExpression:
  93. return isSafeUse(parent);
  94. // Allow use in conditions
  95. case ts.SyntaxKind.ConditionalExpression:
  96. return parent.condition === node;
  97. case ts.SyntaxKind.IfStatement:
  98. case ts.SyntaxKind.WhileStatement:
  99. case ts.SyntaxKind.DoStatement:
  100. case ts.SyntaxKind.ForStatement:
  101. case ts.SyntaxKind.PrefixUnaryExpression:
  102. return true;
  103. default:
  104. return false;
  105. }
  106. }
  107. var templateObject_1;