noThisAssignmentRule.js 6.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  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 ALLOW_THIS_DESTRUCTURING = "allow-destructuring";
  24. var ALLOWED_THIS_NAMES = "allowed-names";
  25. var parseConfigOptions = function (configOptions) {
  26. var allowedNames = [];
  27. var allowDestructuring = false;
  28. if (configOptions !== undefined) {
  29. allowDestructuring = !!configOptions[ALLOW_THIS_DESTRUCTURING];
  30. if (configOptions[ALLOWED_THIS_NAMES] !== undefined) {
  31. allowedNames.push.apply(allowedNames, configOptions[ALLOWED_THIS_NAMES]);
  32. }
  33. }
  34. return { allowedNames: allowedNames, allowDestructuring: allowDestructuring };
  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.FAILURE_STRING_FACTORY_IDENTIFIERS = function (name) {
  42. return "Assigning `this` reference to local variable not allowed: " + name + ".";
  43. };
  44. Rule.prototype.apply = function (sourceFile) {
  45. var options = parseConfigOptions(this.ruleArguments[0]);
  46. var noThisAssignmentWalker = new NoThisAssignmentWalker(sourceFile, this.ruleName, options);
  47. return this.applyWithWalker(noThisAssignmentWalker);
  48. };
  49. Rule.metadata = {
  50. description: "Disallows unnecessary references to `this`.",
  51. optionExamples: [
  52. true,
  53. [
  54. true,
  55. (_a = {},
  56. _a[ALLOWED_THIS_NAMES] = ["^self$"],
  57. _a[ALLOW_THIS_DESTRUCTURING] = true,
  58. _a),
  59. ],
  60. ],
  61. options: {
  62. additionalProperties: false,
  63. properties: (_b = {},
  64. _b[ALLOW_THIS_DESTRUCTURING] = {
  65. type: "boolean",
  66. },
  67. _b[ALLOWED_THIS_NAMES] = {
  68. listType: "string",
  69. type: "list",
  70. },
  71. _b),
  72. type: "object",
  73. },
  74. optionsDescription: Lint.Utils.dedent(templateObject_1 || (templateObject_1 = tslib_1.__makeTemplateObject(["\n Two options may be provided on an object:\n\n * `", "` allows using destructuring to access members of `this` (e.g. `{ foo, bar } = this;`).\n * `", "` may be specified as a list of regular expressions to match allowed variable names."], ["\n Two options may be provided on an object:\n\n * \\`", "\\` allows using destructuring to access members of \\`this\\` (e.g. \\`{ foo, bar } = this;\\`).\n * \\`", "\\` may be specified as a list of regular expressions to match allowed variable names."])), ALLOW_THIS_DESTRUCTURING, ALLOWED_THIS_NAMES),
  75. rationale: Lint.Utils.dedent(templateObject_2 || (templateObject_2 = tslib_1.__makeTemplateObject(["\n Assigning a variable to `this` instead of properly using arrow lambdas may be a symptom of pre-ES6 practices\n or not managing scope well.\n\n Instead of storing a reference to `this` and using it inside a `function () {`:\n\n ```\n const self = this;\n\n setTimeout(function () {\n self.doWork();\n });\n ```\n\n Use `() =>` arrow lambdas, as they preserve `this` scope for you:\n\n ```\n setTimeout(() => {\n this.doWork();\n });\n ```\n "], ["\n Assigning a variable to \\`this\\` instead of properly using arrow lambdas may be a symptom of pre-ES6 practices\n or not managing scope well.\n\n Instead of storing a reference to \\`this\\` and using it inside a \\`function () {\\`:\n\n \\`\\`\\`\n const self = this;\n\n setTimeout(function () {\n self.doWork();\n });\n \\`\\`\\`\n\n Use \\`() =>\\` arrow lambdas, as they preserve \\`this\\` scope for you:\n\n \\`\\`\\`\n setTimeout(() => {\n this.doWork();\n });\n \\`\\`\\`\n "]))),
  76. ruleName: "no-this-assignment",
  77. type: "functionality",
  78. typescriptOnly: false,
  79. };
  80. Rule.FAILURE_STRING_BINDINGS = "Don't assign members of `this` to local variables.";
  81. return Rule;
  82. }(Lint.Rules.AbstractRule));
  83. exports.Rule = Rule;
  84. var NoThisAssignmentWalker = /** @class */ (function (_super) {
  85. tslib_1.__extends(NoThisAssignmentWalker, _super);
  86. function NoThisAssignmentWalker() {
  87. var _this = _super !== null && _super.apply(this, arguments) || this;
  88. _this.allowedThisNameTesters = _this.options.allowedNames.map(function (allowedThisName) { return new RegExp(allowedThisName); });
  89. _this.visitNode = function (node) {
  90. if (utils.isVariableDeclaration(node)) {
  91. _this.visitVariableDeclaration(node);
  92. }
  93. ts.forEachChild(node, _this.visitNode);
  94. };
  95. return _this;
  96. }
  97. NoThisAssignmentWalker.prototype.walk = function (sourceFile) {
  98. ts.forEachChild(sourceFile, this.visitNode);
  99. };
  100. NoThisAssignmentWalker.prototype.visitVariableDeclaration = function (node) {
  101. if (node.initializer === undefined || node.initializer.kind !== ts.SyntaxKind.ThisKeyword) {
  102. return;
  103. }
  104. switch (node.name.kind) {
  105. case ts.SyntaxKind.Identifier:
  106. if (this.variableNameIsBanned(node.name.text)) {
  107. this.addFailureAtNode(node, Rule.FAILURE_STRING_FACTORY_IDENTIFIERS(node.name.text));
  108. }
  109. break;
  110. default:
  111. if (!this.options.allowDestructuring) {
  112. this.addFailureAtNode(node, Rule.FAILURE_STRING_BINDINGS);
  113. }
  114. }
  115. };
  116. NoThisAssignmentWalker.prototype.variableNameIsBanned = function (name) {
  117. for (var _i = 0, _a = this.allowedThisNameTesters; _i < _a.length; _i++) {
  118. var tester = _a[_i];
  119. if (tester.test(name)) {
  120. return false;
  121. }
  122. }
  123. return true;
  124. };
  125. return NoThisAssignmentWalker;
  126. }(Lint.AbstractWalker));
  127. var templateObject_1, templateObject_2;
  128. var _a, _b;