preferObjectSpreadRule.js 5.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  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 Rule = /** @class */ (function (_super) {
  24. tslib_1.__extends(Rule, _super);
  25. function Rule() {
  26. return _super !== null && _super.apply(this, arguments) || this;
  27. }
  28. Rule.prototype.apply = function (sourceFile) {
  29. return this.applyWithFunction(sourceFile, walk);
  30. };
  31. /* tslint:disable:object-literal-sort-keys */
  32. Rule.metadata = {
  33. ruleName: "prefer-object-spread",
  34. description: "Enforces the use of the ES2015 object spread operator over `Object.assign()` where appropriate.",
  35. rationale: "Object spread allows for better type checking and inference.",
  36. optionsDescription: "Not configurable.",
  37. options: null,
  38. optionExamples: [true],
  39. type: "functionality",
  40. typescriptOnly: false,
  41. hasFix: true,
  42. };
  43. /* tslint:enable:object-literal-sort-keys */
  44. Rule.FAILURE_STRING = "Use the object spread operator instead.";
  45. Rule.ASSIGNMENT_FAILURE_STRING = "'Object.assign' returns the first argument. Prefer object spread if you want a new object.";
  46. return Rule;
  47. }(Lint.Rules.AbstractRule));
  48. exports.Rule = Rule;
  49. function walk(ctx) {
  50. return ts.forEachChild(ctx.sourceFile, function cb(node) {
  51. if (tsutils_1.isCallExpression(node) && node.arguments.length !== 0 &&
  52. tsutils_1.isPropertyAccessExpression(node.expression) && node.expression.name.text === "assign" &&
  53. tsutils_1.isIdentifier(node.expression.expression) && node.expression.expression.text === "Object" &&
  54. !ts.isFunctionLike(node.arguments[0]) &&
  55. // Object.assign(...someArray) cannot be written as object spread
  56. !node.arguments.some(tsutils_1.isSpreadElement) &&
  57. /**
  58. * @TODO
  59. * Remove !node.arguments.some(isThisKeyword) when typescript get's
  60. * support for spread types.
  61. * PR: https://github.com/Microsoft/TypeScript/issues/10727
  62. */
  63. !node.arguments.some(isThisKeyword)) {
  64. if (node.arguments[0].kind === ts.SyntaxKind.ObjectLiteralExpression) {
  65. ctx.addFailureAtNode(node, Rule.FAILURE_STRING, createFix(node, ctx.sourceFile));
  66. }
  67. else if (tsutils_1.isExpressionValueUsed(node) && !tsutils_1.hasSideEffects(node.arguments[0], 2 /* Constructor */)) {
  68. ctx.addFailureAtNode(node, Rule.ASSIGNMENT_FAILURE_STRING, createFix(node, ctx.sourceFile));
  69. }
  70. }
  71. return ts.forEachChild(node, cb);
  72. });
  73. }
  74. function createFix(node, sourceFile) {
  75. var args = node.arguments;
  76. var objectNeedsParens = node.parent.kind === ts.SyntaxKind.ArrowFunction;
  77. var fix = [
  78. Lint.Replacement.replaceFromTo(node.getStart(sourceFile), args[0].getStart(sourceFile), (objectNeedsParens ? "(" : "") + "{"),
  79. new Lint.Replacement(node.end - 1, 1, "}" + (objectNeedsParens ? ")" : "")),
  80. ];
  81. for (var i = 0; i < args.length; ++i) {
  82. var arg = args[i];
  83. if (tsutils_1.isObjectLiteralExpression(arg)) {
  84. if (arg.properties.length === 0) {
  85. var end = arg.end;
  86. if (i !== args.length - 1) {
  87. end = args[i + 1].getStart(sourceFile);
  88. }
  89. else if (args.hasTrailingComma) {
  90. end = args.end;
  91. }
  92. // remove empty object iteral and the following comma if exists
  93. fix.push(Lint.Replacement.deleteFromTo(arg.getStart(sourceFile), end));
  94. }
  95. else {
  96. fix.push(
  97. // remove open brace
  98. Lint.Replacement.deleteText(arg.getStart(sourceFile), 1),
  99. // remove trailing comma if exists and close brace
  100. Lint.Replacement.deleteFromTo(arg.properties[arg.properties.length - 1].end, arg.end));
  101. }
  102. }
  103. else {
  104. var parens = needsParens(arg);
  105. fix.push(Lint.Replacement.appendText(arg.getStart(sourceFile), parens ? "...(" : "..."));
  106. if (parens) {
  107. fix.push(Lint.Replacement.appendText(arg.end, ")"));
  108. }
  109. }
  110. }
  111. return fix;
  112. }
  113. function isThisKeyword(node) {
  114. return node.kind === ts.SyntaxKind.ThisKeyword;
  115. }
  116. function needsParens(node) {
  117. switch (node.kind) {
  118. case ts.SyntaxKind.ConditionalExpression:
  119. case ts.SyntaxKind.BinaryExpression:
  120. return true;
  121. default:
  122. return false;
  123. }
  124. }