trailingCommaRule.js 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. "use strict";
  2. /**
  3. * @license
  4. * Copyright 2013 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 defaultOptions = fillOptions("ignore");
  24. function fillOptions(value) {
  25. return {
  26. arrays: value,
  27. exports: value,
  28. functions: value,
  29. imports: value,
  30. objects: value,
  31. typeLiterals: value,
  32. };
  33. }
  34. function normalizeOptions(options) {
  35. return { multiline: normalize(options.multiline), singleline: normalize(options.singleline), specCompliant: !!options.esSpecCompliant };
  36. }
  37. function normalize(value) {
  38. return typeof value === "string" ? fillOptions(value) : tslib_1.__assign({}, defaultOptions, value);
  39. }
  40. /* tslint:disable:object-literal-sort-keys */
  41. var metadataOptionShape = {
  42. anyOf: [
  43. {
  44. type: "string",
  45. enum: ["always", "never"],
  46. },
  47. {
  48. type: "object",
  49. properties: fillOptions({
  50. type: "string",
  51. enum: ["always", "never", "ignore"],
  52. }),
  53. },
  54. ],
  55. };
  56. /* tslint:enable:object-literal-sort-keys */
  57. var Rule = /** @class */ (function (_super) {
  58. tslib_1.__extends(Rule, _super);
  59. function Rule() {
  60. return _super !== null && _super.apply(this, arguments) || this;
  61. }
  62. Rule.prototype.apply = function (sourceFile) {
  63. var options = normalizeOptions(this.ruleArguments[0]);
  64. return this.applyWithWalker(new TrailingCommaWalker(sourceFile, this.ruleName, options));
  65. };
  66. Rule.prototype.isEnabled = function () {
  67. return _super.prototype.isEnabled.call(this) && this.ruleArguments.length !== 0;
  68. };
  69. /* tslint:disable:object-literal-sort-keys */
  70. Rule.metadata = {
  71. ruleName: "trailing-comma",
  72. description: Lint.Utils.dedent(templateObject_1 || (templateObject_1 = tslib_1.__makeTemplateObject(["\n Requires or disallows trailing commas in array and object literals, destructuring assignments, function typings,\n named imports and exports and function parameters."], ["\n Requires or disallows trailing commas in array and object literals, destructuring assignments, function typings,\n named imports and exports and function parameters."]))),
  73. hasFix: true,
  74. optionsDescription: Lint.Utils.dedent(templateObject_2 || (templateObject_2 = tslib_1.__makeTemplateObject(["\n One argument which is an object with the keys `multiline` and `singleline`.\n Both can be set to a string (`\"always\"` or `\"never\"`) or an object.\n\n The object can contain any of the following keys: `\"arrays\"`, `\"objects\"`, `\"functions\"`,\n `\"imports\"`, `\"exports\"`, and `\"typeLiterals\"`; each key can have one of the following\n values: `\"always\"`, `\"never\"`, and `\"ignore\"`. Any missing keys will default to `\"ignore\"`.\n\n * `\"multiline\"` checks multi-line object literals.\n * `\"singleline\"` checks single-line object literals.\n\n An array is considered \"multiline\" if its closing bracket is on a line\n after the last array element. The same general logic is followed for\n object literals, function typings, named import statements\n and function parameters.\n\n To align this rule with the ECMAScript specification that is implemented in modern JavaScript VMs,\n there is a third option `esSpecCompliant`. Set this option to `true` to disallow trailing comma on\n object and array rest and rest parameters.\n "], ["\n One argument which is an object with the keys \\`multiline\\` and \\`singleline\\`.\n Both can be set to a string (\\`\"always\"\\` or \\`\"never\"\\`) or an object.\n\n The object can contain any of the following keys: \\`\"arrays\"\\`, \\`\"objects\"\\`, \\`\"functions\"\\`,\n \\`\"imports\"\\`, \\`\"exports\"\\`, and \\`\"typeLiterals\"\\`; each key can have one of the following\n values: \\`\"always\"\\`, \\`\"never\"\\`, and \\`\"ignore\"\\`. Any missing keys will default to \\`\"ignore\"\\`.\n\n * \\`\"multiline\"\\` checks multi-line object literals.\n * \\`\"singleline\"\\` checks single-line object literals.\n\n An array is considered \"multiline\" if its closing bracket is on a line\n after the last array element. The same general logic is followed for\n object literals, function typings, named import statements\n and function parameters.\n\n To align this rule with the ECMAScript specification that is implemented in modern JavaScript VMs,\n there is a third option \\`esSpecCompliant\\`. Set this option to \\`true\\` to disallow trailing comma on\n object and array rest and rest parameters.\n "]))),
  75. options: {
  76. type: "object",
  77. properties: {
  78. multiline: metadataOptionShape,
  79. singleline: metadataOptionShape,
  80. esSpecCompliant: { type: "boolean" },
  81. },
  82. additionalProperties: false,
  83. },
  84. optionExamples: [
  85. [true, { multiline: "always", singleline: "never" }],
  86. [
  87. true,
  88. {
  89. multiline: {
  90. objects: "always",
  91. arrays: "always",
  92. functions: "never",
  93. typeLiterals: "ignore",
  94. },
  95. esSpecCompliant: true,
  96. },
  97. ],
  98. ],
  99. type: "maintainability",
  100. typescriptOnly: false,
  101. };
  102. /* tslint:enable:object-literal-sort-keys */
  103. Rule.FAILURE_STRING_NEVER = "Unnecessary trailing comma";
  104. Rule.FAILURE_STRING_FORBIDDEN = "Forbidden trailing comma";
  105. Rule.FAILURE_STRING_ALWAYS = "Missing trailing comma";
  106. return Rule;
  107. }(Lint.Rules.AbstractRule));
  108. exports.Rule = Rule;
  109. var TrailingCommaWalker = /** @class */ (function (_super) {
  110. tslib_1.__extends(TrailingCommaWalker, _super);
  111. function TrailingCommaWalker() {
  112. return _super !== null && _super.apply(this, arguments) || this;
  113. }
  114. TrailingCommaWalker.prototype.walk = function (sourceFile) {
  115. var _this = this;
  116. var cb = function (node) {
  117. switch (node.kind) {
  118. case ts.SyntaxKind.ArrayLiteralExpression:
  119. _this.checkList(node.elements, node.end, "arrays", isArrayRest);
  120. break;
  121. case ts.SyntaxKind.ArrayBindingPattern:
  122. _this.checkList(node.elements, node.end, "arrays", isDestructuringRest);
  123. break;
  124. case ts.SyntaxKind.ObjectBindingPattern:
  125. _this.checkList(node.elements, node.end, "objects", isDestructuringRest);
  126. break;
  127. case ts.SyntaxKind.NamedImports:
  128. _this.checkList(node.elements, node.end, "imports", noRest);
  129. break;
  130. case ts.SyntaxKind.NamedExports:
  131. _this.checkList(node.elements, node.end, "exports", noRest);
  132. break;
  133. case ts.SyntaxKind.ObjectLiteralExpression:
  134. _this.checkList(node.properties, node.end, "objects", isObjectRest);
  135. break;
  136. case ts.SyntaxKind.EnumDeclaration:
  137. _this.checkList(node.members, node.end, "objects", noRest);
  138. break;
  139. case ts.SyntaxKind.NewExpression:
  140. if (node.arguments === undefined) {
  141. break;
  142. }
  143. // falls through
  144. case ts.SyntaxKind.CallExpression:
  145. _this.checkList(node.arguments, node.end, "functions", noRest);
  146. break;
  147. case ts.SyntaxKind.ArrowFunction:
  148. // don't check arrow functions without parens around the parameter
  149. if (tsutils_1.getChildOfKind(node, ts.SyntaxKind.OpenParenToken, _this.sourceFile) === undefined) {
  150. break;
  151. }
  152. // falls through
  153. case ts.SyntaxKind.Constructor:
  154. case ts.SyntaxKind.FunctionDeclaration:
  155. case ts.SyntaxKind.FunctionExpression:
  156. case ts.SyntaxKind.MethodDeclaration:
  157. case ts.SyntaxKind.SetAccessor:
  158. case ts.SyntaxKind.MethodSignature:
  159. case ts.SyntaxKind.ConstructSignature:
  160. case ts.SyntaxKind.ConstructorType:
  161. case ts.SyntaxKind.FunctionType:
  162. case ts.SyntaxKind.CallSignature:
  163. _this.checkList(node.parameters, tsutils_1.getChildOfKind(node, ts.SyntaxKind.CloseParenToken, _this.sourceFile).end, "functions", isRestParameter);
  164. break;
  165. case ts.SyntaxKind.TypeLiteral:
  166. _this.checkTypeLiteral(node);
  167. break;
  168. default:
  169. }
  170. return ts.forEachChild(node, cb);
  171. };
  172. return ts.forEachChild(sourceFile, cb);
  173. };
  174. TrailingCommaWalker.prototype.checkTypeLiteral = function (node) {
  175. var members = node.members;
  176. if (members.length === 0) {
  177. return;
  178. }
  179. var sourceText = this.sourceFile.text;
  180. for (var _i = 0, members_1 = members; _i < members_1.length; _i++) {
  181. var member = members_1[_i];
  182. // PropertySignature in TypeLiteral can end with semicolon or comma. If one ends with a semicolon don't check for trailing comma
  183. if (sourceText[member.end - 1] === ";") {
  184. return;
  185. }
  186. }
  187. // The trailing comma is part of the last member and therefore not present as hasTrailingComma on the NodeArray
  188. var hasTrailingComma = sourceText[members.end - 1] === ",";
  189. return this.checkComma(hasTrailingComma, members, node.end, "typeLiterals", noRest);
  190. };
  191. TrailingCommaWalker.prototype.checkList = function (list, closeElementPos, optionKey, isRest) {
  192. if (list.length === 0) {
  193. return;
  194. }
  195. return this.checkComma(list.hasTrailingComma, list, closeElementPos, optionKey, isRest);
  196. };
  197. /* Expects `list.length !== 0` */
  198. TrailingCommaWalker.prototype.checkComma = function (hasTrailingComma, list, closeTokenPos, optionKey, isRest) {
  199. var last = list[list.length - 1];
  200. if (this.options.specCompliant && isRest(last)) {
  201. if (hasTrailingComma) {
  202. this.addFailureAt(list.end - 1, 1, Rule.FAILURE_STRING_FORBIDDEN, Lint.Replacement.deleteText(list.end - 1, 1));
  203. }
  204. return;
  205. }
  206. var options = tsutils_1.isSameLine(this.sourceFile, last.end, closeTokenPos)
  207. ? this.options.singleline
  208. : this.options.multiline;
  209. var option = options[optionKey];
  210. if (option === "always" && !hasTrailingComma) {
  211. this.addFailureAt(list.end, 0, Rule.FAILURE_STRING_ALWAYS, Lint.Replacement.appendText(list.end, ","));
  212. }
  213. else if (option === "never" && hasTrailingComma) {
  214. this.addFailureAt(list.end - 1, 1, Rule.FAILURE_STRING_NEVER, Lint.Replacement.deleteText(list.end - 1, 1));
  215. }
  216. };
  217. return TrailingCommaWalker;
  218. }(Lint.AbstractWalker));
  219. function isRestParameter(node) {
  220. return node.dotDotDotToken !== undefined;
  221. }
  222. function isDestructuringRest(node) {
  223. return node.kind === ts.SyntaxKind.BindingElement && node.dotDotDotToken !== undefined;
  224. }
  225. function isObjectRest(node) {
  226. return node.kind === ts.SyntaxKind.SpreadAssignment && tsutils_1.isReassignmentTarget(node.expression);
  227. }
  228. function isArrayRest(node) {
  229. return node.kind === ts.SyntaxKind.SpreadElement && tsutils_1.isReassignmentTarget(node);
  230. }
  231. function noRest() {
  232. return false;
  233. }
  234. var templateObject_1, templateObject_2;