whitespaceRule.js 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  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. // tslint:disable object-literal-sort-keys
  21. var utils = require("tsutils");
  22. var ts = require("typescript");
  23. var Lint = require("../index");
  24. var OPTION_BRANCH = "check-branch";
  25. var OPTION_DECL = "check-decl";
  26. var OPTION_OPERATOR = "check-operator";
  27. var OPTION_MODULE = "check-module";
  28. var OPTION_SEPARATOR = "check-separator";
  29. var OPTION_REST_SPREAD = "check-rest-spread";
  30. var OPTION_TYPE = "check-type";
  31. var OPTION_TYPECAST = "check-typecast";
  32. var OPTION_TYPE_OPERATOR = "check-type-operator";
  33. var OPTION_PREBLOCK = "check-preblock";
  34. var Rule = /** @class */ (function (_super) {
  35. tslib_1.__extends(Rule, _super);
  36. function Rule() {
  37. return _super !== null && _super.apply(this, arguments) || this;
  38. }
  39. Rule.prototype.apply = function (sourceFile) {
  40. return this.applyWithFunction(sourceFile, walk, parseOptions(this.ruleArguments));
  41. };
  42. Rule.metadata = {
  43. ruleName: "whitespace",
  44. description: "Enforces whitespace style conventions.",
  45. rationale: "Helps maintain a readable, consistent style in your codebase.",
  46. optionsDescription: Lint.Utils.dedent(templateObject_1 || (templateObject_1 = tslib_1.__makeTemplateObject(["\n Ten arguments may be optionally provided:\n\n * `\"check-branch\"` checks branching statements (`if`/`else`/`for`/`while`) are followed by whitespace.\n * `\"check-decl\"`checks that variable declarations have whitespace around the equals token.\n * `\"check-operator\"` checks for whitespace around operator tokens.\n * `\"check-module\"` checks for whitespace in import & export statements.\n * `\"check-separator\"` checks for whitespace after separator tokens (`,`/`;`).\n * `\"check-rest-spread\"` checks that there is no whitespace after rest/spread operator (`...`).\n * `\"check-type\"` checks for whitespace before a variable type specification.\n * `\"check-typecast\"` checks for whitespace between a typecast and its target.\n * `\"check-type-operator\"` checks for whitespace between type operators `|` and `&`.\n * `\"check-preblock\"` checks for whitespace before the opening brace of a block"], ["\n Ten arguments may be optionally provided:\n\n * \\`\"check-branch\"\\` checks branching statements (\\`if\\`/\\`else\\`/\\`for\\`/\\`while\\`) are followed by whitespace.\n * \\`\"check-decl\"\\`checks that variable declarations have whitespace around the equals token.\n * \\`\"check-operator\"\\` checks for whitespace around operator tokens.\n * \\`\"check-module\"\\` checks for whitespace in import & export statements.\n * \\`\"check-separator\"\\` checks for whitespace after separator tokens (\\`,\\`/\\`;\\`).\n * \\`\"check-rest-spread\"\\` checks that there is no whitespace after rest/spread operator (\\`...\\`).\n * \\`\"check-type\"\\` checks for whitespace before a variable type specification.\n * \\`\"check-typecast\"\\` checks for whitespace between a typecast and its target.\n * \\`\"check-type-operator\"\\` checks for whitespace between type operators \\`|\\` and \\`&\\`.\n * \\`\"check-preblock\"\\` checks for whitespace before the opening brace of a block"]))),
  47. options: {
  48. type: "array",
  49. items: {
  50. type: "string",
  51. enum: [
  52. "check-branch", "check-decl", "check-operator", "check-module", "check-separator",
  53. "check-rest-spread", "check-type", "check-typecast", "check-type-operator", "check-preblock",
  54. ],
  55. },
  56. minLength: 0,
  57. maxLength: 10,
  58. },
  59. optionExamples: [[true, "check-branch", "check-operator", "check-typecast"]],
  60. type: "style",
  61. typescriptOnly: false,
  62. hasFix: true,
  63. };
  64. Rule.FAILURE_STRING_MISSING = "missing whitespace";
  65. Rule.FAILURE_STRING_INVALID = "invalid whitespace";
  66. return Rule;
  67. }(Lint.Rules.AbstractRule));
  68. exports.Rule = Rule;
  69. function parseOptions(ruleArguments) {
  70. return {
  71. branch: has(OPTION_BRANCH),
  72. decl: has(OPTION_DECL),
  73. operator: has(OPTION_OPERATOR),
  74. module: has(OPTION_MODULE),
  75. separator: has(OPTION_SEPARATOR),
  76. restSpread: has(OPTION_REST_SPREAD),
  77. type: has(OPTION_TYPE),
  78. typecast: has(OPTION_TYPECAST),
  79. typeOperator: has(OPTION_TYPE_OPERATOR),
  80. preblock: has(OPTION_PREBLOCK),
  81. };
  82. function has(option) {
  83. return ruleArguments.indexOf(option) !== -1;
  84. }
  85. }
  86. function walk(ctx) {
  87. var sourceFile = ctx.sourceFile, options = ctx.options;
  88. ts.forEachChild(sourceFile, function cb(node) {
  89. switch (node.kind) {
  90. case ts.SyntaxKind.ArrowFunction:
  91. checkEqualsGreaterThanTokenInNode(node);
  92. break;
  93. // check for spaces between the operator symbol (except in the case of comma statements)
  94. case ts.SyntaxKind.BinaryExpression: {
  95. var _a = node, left = _a.left, operatorToken = _a.operatorToken, right = _a.right;
  96. if (options.operator && operatorToken.kind !== ts.SyntaxKind.CommaToken) {
  97. checkForTrailingWhitespace(left.getEnd());
  98. checkForTrailingWhitespace(right.getFullStart());
  99. }
  100. break;
  101. }
  102. case ts.SyntaxKind.Block:
  103. if (options.preblock) {
  104. checkForTrailingWhitespace(node.getFullStart());
  105. }
  106. break;
  107. // check for spaces between ternary operator symbols
  108. case ts.SyntaxKind.ConditionalExpression:
  109. if (options.operator) {
  110. var _b = node, condition = _b.condition, whenTrue = _b.whenTrue;
  111. checkForTrailingWhitespace(condition.getEnd());
  112. checkForTrailingWhitespace(whenTrue.getFullStart());
  113. checkForTrailingWhitespace(whenTrue.getEnd());
  114. }
  115. break;
  116. case ts.SyntaxKind.ConstructorType:
  117. checkEqualsGreaterThanTokenInNode(node);
  118. break;
  119. case ts.SyntaxKind.ExportAssignment:
  120. if (options.module) {
  121. var exportKeyword = node.getChildAt(0);
  122. var position = exportKeyword.getEnd();
  123. checkForTrailingWhitespace(position);
  124. }
  125. break;
  126. case ts.SyntaxKind.FunctionType:
  127. checkEqualsGreaterThanTokenInNode(node);
  128. break;
  129. case ts.SyntaxKind.ImportDeclaration: {
  130. var importClause = node.importClause;
  131. if (options.module && importClause !== undefined) {
  132. // an import clause can have _both_ named bindings and a name (the latter for the default import)
  133. // but the named bindings always come last, so we only need to check that for whitespace
  134. var position = void 0;
  135. var namedBindings_1 = importClause.namedBindings;
  136. if (namedBindings_1 !== undefined) {
  137. if (namedBindings_1.kind !== ts.SyntaxKind.NamespaceImport) {
  138. namedBindings_1.elements.forEach(function (element, idx, arr) {
  139. var internalName = element.name;
  140. if (internalName !== undefined) {
  141. if (idx === arr.length - 1) {
  142. var token = namedBindings_1.getLastToken();
  143. checkForTrailingWhitespace(token.getFullStart());
  144. }
  145. if (idx === 0) {
  146. var startPos = internalName.getStart() - 1;
  147. checkForTrailingWhitespace(startPos, startPos + 1);
  148. }
  149. }
  150. });
  151. }
  152. position = namedBindings_1.getEnd();
  153. }
  154. else if (importClause.name !== undefined) {
  155. position = importClause.name.getEnd();
  156. }
  157. if (position !== undefined) {
  158. checkForTrailingWhitespace(position);
  159. }
  160. }
  161. break;
  162. }
  163. case ts.SyntaxKind.ImportEqualsDeclaration:
  164. if (options.module) {
  165. var position = node.name.getEnd();
  166. checkForTrailingWhitespace(position);
  167. }
  168. break;
  169. case ts.SyntaxKind.TypeAssertionExpression:
  170. if (options.typecast) {
  171. var position = node.expression.getFullStart();
  172. checkForTrailingWhitespace(position);
  173. }
  174. break;
  175. case ts.SyntaxKind.VariableDeclaration:
  176. case ts.SyntaxKind.PropertyDeclaration:
  177. var _c = node, name = _c.name, type = _c.type, initializer = _c.initializer;
  178. if (options.decl && initializer !== undefined) {
  179. checkForTrailingWhitespace((type !== undefined ? type : name).getEnd());
  180. }
  181. break;
  182. case ts.SyntaxKind.BindingElement:
  183. case ts.SyntaxKind.Parameter:
  184. var dotDotDotToken = node.dotDotDotToken;
  185. if (options.restSpread && dotDotDotToken !== undefined) {
  186. checkForExcessiveWhitespace(dotDotDotToken.end);
  187. }
  188. break;
  189. case ts.SyntaxKind.SpreadAssignment:
  190. case ts.SyntaxKind.SpreadElement:
  191. if (options.restSpread) {
  192. var position = node.expression.getFullStart();
  193. checkForExcessiveWhitespace(position);
  194. }
  195. break;
  196. case ts.SyntaxKind.UnionType:
  197. case ts.SyntaxKind.IntersectionType:
  198. if (options.typeOperator) {
  199. var types_1 = node.types;
  200. types_1.forEach(function (typeNode, index) {
  201. if (index > 0) {
  202. checkForTrailingWhitespace(typeNode.getFullStart());
  203. }
  204. if (index < types_1.length - 1) {
  205. checkForTrailingWhitespace(typeNode.getEnd());
  206. }
  207. });
  208. }
  209. }
  210. ts.forEachChild(node, cb);
  211. });
  212. var prevTokenShouldBeFollowedByWhitespace = false;
  213. utils.forEachTokenWithTrivia(sourceFile, function (_text, tokenKind, range, parent) {
  214. if (tokenKind === ts.SyntaxKind.WhitespaceTrivia ||
  215. tokenKind === ts.SyntaxKind.NewLineTrivia ||
  216. tokenKind === ts.SyntaxKind.EndOfFileToken) {
  217. prevTokenShouldBeFollowedByWhitespace = false;
  218. return;
  219. }
  220. else if (prevTokenShouldBeFollowedByWhitespace) {
  221. addMissingWhitespaceErrorAt(range.pos);
  222. prevTokenShouldBeFollowedByWhitespace = false;
  223. }
  224. // check for trailing space after the given tokens
  225. switch (tokenKind) {
  226. case ts.SyntaxKind.CatchKeyword:
  227. case ts.SyntaxKind.ForKeyword:
  228. case ts.SyntaxKind.IfKeyword:
  229. case ts.SyntaxKind.SwitchKeyword:
  230. case ts.SyntaxKind.WhileKeyword:
  231. case ts.SyntaxKind.WithKeyword:
  232. if (options.branch) {
  233. prevTokenShouldBeFollowedByWhitespace = true;
  234. }
  235. break;
  236. case ts.SyntaxKind.CommaToken:
  237. if (options.separator) {
  238. prevTokenShouldBeFollowedByWhitespace = true;
  239. }
  240. break;
  241. case ts.SyntaxKind.SemicolonToken:
  242. if (!options.separator) {
  243. break;
  244. }
  245. var nextPosition = range.pos + 1;
  246. var semicolonInTrivialFor = parent.kind === ts.SyntaxKind.ForStatement &&
  247. nextPosition !== sourceFile.end &&
  248. (sourceFile.text[nextPosition] === ";" || sourceFile.text[nextPosition] === ")");
  249. if (!semicolonInTrivialFor) {
  250. prevTokenShouldBeFollowedByWhitespace = true;
  251. }
  252. break;
  253. case ts.SyntaxKind.EqualsToken:
  254. if (options.decl && parent.kind !== ts.SyntaxKind.JsxAttribute) {
  255. prevTokenShouldBeFollowedByWhitespace = true;
  256. }
  257. break;
  258. case ts.SyntaxKind.ColonToken:
  259. if (options.type) {
  260. prevTokenShouldBeFollowedByWhitespace = true;
  261. }
  262. break;
  263. case ts.SyntaxKind.ImportKeyword:
  264. if (parent.kind === ts.SyntaxKind.CallExpression &&
  265. parent.expression.kind === ts.SyntaxKind.ImportKeyword) {
  266. return; // Don't check ImportCall
  267. }
  268. // falls through
  269. case ts.SyntaxKind.ExportKeyword:
  270. case ts.SyntaxKind.FromKeyword:
  271. if (options.typecast) {
  272. prevTokenShouldBeFollowedByWhitespace = true;
  273. }
  274. }
  275. });
  276. function checkEqualsGreaterThanTokenInNode(node) {
  277. if (!options.operator) {
  278. return;
  279. }
  280. var equalsGreaterThanToken = utils.getChildOfKind(node, ts.SyntaxKind.EqualsGreaterThanToken, sourceFile);
  281. // condition so we don't crash if the arrow is somehow missing
  282. if (equalsGreaterThanToken === undefined) {
  283. return;
  284. }
  285. checkForTrailingWhitespace(equalsGreaterThanToken.getFullStart());
  286. checkForTrailingWhitespace(equalsGreaterThanToken.getEnd());
  287. }
  288. function checkForTrailingWhitespace(position, whiteSpacePos) {
  289. if (whiteSpacePos === void 0) { whiteSpacePos = position; }
  290. if (position !== sourceFile.end && !Lint.isWhiteSpace(sourceFile.text.charCodeAt(position))) {
  291. addMissingWhitespaceErrorAt(whiteSpacePos);
  292. }
  293. }
  294. function addMissingWhitespaceErrorAt(position) {
  295. // TODO: this rule occasionally adds duplicate failures.
  296. if (ctx.failures.some(function (f) { return f.getStartPosition().getPosition() === position; })) {
  297. return;
  298. }
  299. var fix = Lint.Replacement.appendText(position, " ");
  300. ctx.addFailureAt(position, 1, Rule.FAILURE_STRING_MISSING, fix);
  301. }
  302. function checkForExcessiveWhitespace(position) {
  303. if (position !== sourceFile.end && Lint.isWhiteSpace(sourceFile.text.charCodeAt(position))) {
  304. addInvalidWhitespaceErrorAt(position);
  305. }
  306. }
  307. function addInvalidWhitespaceErrorAt(position) {
  308. var fix = Lint.Replacement.deleteText(position, 1);
  309. ctx.addFailureAt(position, 1, Rule.FAILURE_STRING_INVALID, fix);
  310. }
  311. }
  312. var templateObject_1;