4 * Copyright 2013 Palantir Technologies, Inc.
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
10 * http://www.apache.org/licenses/LICENSE-2.0
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.
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 OPTION_POSTBRACE = "check-postbrace";
35 var Rule = /** @class */ (function (_super) {
36 tslib_1.__extends(Rule, _super);
38 return _super !== null && _super.apply(this, arguments) || this;
40 Rule.prototype.apply = function (sourceFile) {
41 return this.applyWithFunction(sourceFile, walk, parseOptions(this.ruleArguments));
44 ruleName: "whitespace",
45 description: "Enforces whitespace style conventions.",
46 rationale: "Helps maintain a readable, consistent style in your codebase.",
47 optionsDescription: Lint.Utils.dedent(templateObject_1 || (templateObject_1 = tslib_1.__makeTemplateObject(["\n Several 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 * `\"check-postbrace\"` checks for whitespace after an opening brace."], ["\n Several 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 * \\`\"check-postbrace\"\\` checks for whitespace after an opening brace."]))),
61 "check-type-operator",
69 optionExamples: [[true, "check-branch", "check-operator", "check-typecast"]],
71 typescriptOnly: false,
74 Rule.FAILURE_STRING_MISSING = "missing whitespace";
75 Rule.FAILURE_STRING_INVALID = "invalid whitespace";
77 }(Lint.Rules.AbstractRule));
79 function parseOptions(ruleArguments) {
81 branch: has(OPTION_BRANCH),
82 decl: has(OPTION_DECL),
83 operator: has(OPTION_OPERATOR),
84 module: has(OPTION_MODULE),
85 separator: has(OPTION_SEPARATOR),
86 restSpread: has(OPTION_REST_SPREAD),
87 type: has(OPTION_TYPE),
88 typecast: has(OPTION_TYPECAST),
89 typeOperator: has(OPTION_TYPE_OPERATOR),
90 preblock: has(OPTION_PREBLOCK),
91 postbrace: has(OPTION_POSTBRACE),
93 function has(option) {
94 return ruleArguments.indexOf(option) !== -1;
98 var sourceFile = ctx.sourceFile, options = ctx.options;
99 ts.forEachChild(sourceFile, function cb(node) {
101 case ts.SyntaxKind.ArrowFunction:
102 checkEqualsGreaterThanTokenInNode(node);
104 // check for spaces between the operator symbol (except in the case of comma statements)
105 case ts.SyntaxKind.BinaryExpression: {
106 var _a = node, left = _a.left, operatorToken = _a.operatorToken, right = _a.right;
107 if (options.operator && operatorToken.kind !== ts.SyntaxKind.CommaToken) {
108 checkForTrailingWhitespace(left.getEnd());
109 checkForTrailingWhitespace(right.getFullStart());
113 case ts.SyntaxKind.Block:
114 if (options.preblock) {
115 checkForTrailingWhitespace(node.getFullStart());
118 // check for spaces between ternary operator symbols
119 case ts.SyntaxKind.ConditionalExpression:
120 if (options.operator) {
121 var _b = node, condition = _b.condition, whenTrue = _b.whenTrue;
122 checkForTrailingWhitespace(condition.getEnd());
123 checkForTrailingWhitespace(whenTrue.getFullStart());
124 checkForTrailingWhitespace(whenTrue.getEnd());
127 case ts.SyntaxKind.ConstructorType:
128 checkEqualsGreaterThanTokenInNode(node);
130 case ts.SyntaxKind.ExportAssignment:
131 if (options.module) {
132 var exportKeyword = node.getChildAt(0);
133 var position = exportKeyword.getEnd();
134 checkForTrailingWhitespace(position);
137 case ts.SyntaxKind.ExportDeclaration:
138 var exportClause_1 = node.exportClause;
139 if (options.module && exportClause_1 !== undefined) {
140 exportClause_1.elements.forEach(function (element, idx, arr) {
141 if (idx === arr.length - 1) {
142 var token = exportClause_1.getLastToken();
143 checkForTrailingWhitespace(token.getFullStart());
146 var startPos = element.getStart() - 1;
147 checkForTrailingWhitespace(startPos, startPos + 1);
152 case ts.SyntaxKind.FunctionType:
153 checkEqualsGreaterThanTokenInNode(node);
155 case ts.SyntaxKind.ImportDeclaration: {
156 var importClause = node.importClause;
157 if (options.module && importClause !== undefined) {
158 // an import clause can have _both_ named bindings and a name (the latter for the default import)
159 // but the named bindings always come last, so we only need to check that for whitespace
160 var position = void 0;
161 var namedBindings_1 = importClause.namedBindings;
162 if (namedBindings_1 !== undefined) {
163 if (namedBindings_1.kind !== ts.SyntaxKind.NamespaceImport) {
164 namedBindings_1.elements.forEach(function (element, idx, arr) {
165 var internalName = element.name;
166 if (internalName !== undefined) {
167 if (idx === arr.length - 1) {
168 var token = namedBindings_1.getLastToken();
169 checkForTrailingWhitespace(token.getFullStart());
172 var startPos = element.getStart() - 1;
173 checkForTrailingWhitespace(startPos, startPos + 1);
178 position = namedBindings_1.getEnd();
180 else if (importClause.name !== undefined) {
181 position = importClause.name.getEnd();
183 if (position !== undefined) {
184 checkForTrailingWhitespace(position);
189 case ts.SyntaxKind.ImportEqualsDeclaration:
190 if (options.module) {
191 var position = node.name.getEnd();
192 checkForTrailingWhitespace(position);
195 case ts.SyntaxKind.TypeAssertionExpression:
196 if (options.typecast) {
197 var position = node.expression.getFullStart();
198 checkForTrailingWhitespace(position);
201 case ts.SyntaxKind.VariableDeclaration:
202 case ts.SyntaxKind.PropertyDeclaration:
203 var _c = node, name = _c.name, type = _c.type, initializer = _c.initializer;
204 if (options.decl && initializer !== undefined) {
205 checkForTrailingWhitespace((type !== undefined ? type : name).getEnd());
208 case ts.SyntaxKind.BindingElement:
209 case ts.SyntaxKind.Parameter:
210 var dotDotDotToken = node.dotDotDotToken;
211 if (options.restSpread && dotDotDotToken !== undefined) {
212 checkForExcessiveWhitespace(dotDotDotToken.end);
215 case ts.SyntaxKind.SpreadAssignment:
216 case ts.SyntaxKind.SpreadElement:
217 if (options.restSpread) {
218 var position = node.expression.getFullStart();
219 checkForExcessiveWhitespace(position);
222 case ts.SyntaxKind.UnionType:
223 case ts.SyntaxKind.IntersectionType:
224 if (options.typeOperator) {
225 var types_1 = node.types;
226 types_1.forEach(function (typeNode, index) {
228 checkForTrailingWhitespace(typeNode.getFullStart());
230 if (index < types_1.length - 1) {
231 checkForTrailingWhitespace(typeNode.getEnd());
236 ts.forEachChild(node, cb);
238 var prevTokenShouldBeFollowedByWhitespace = false;
239 utils.forEachTokenWithTrivia(sourceFile, function (_text, tokenKind, range, parent) {
240 if (tokenKind === ts.SyntaxKind.WhitespaceTrivia ||
241 tokenKind === ts.SyntaxKind.NewLineTrivia ||
242 tokenKind === ts.SyntaxKind.EndOfFileToken) {
243 prevTokenShouldBeFollowedByWhitespace = false;
246 else if (prevTokenShouldBeFollowedByWhitespace) {
247 addMissingWhitespaceErrorAt(range.pos);
248 prevTokenShouldBeFollowedByWhitespace = false;
250 // check for trailing space after the given tokens
252 case ts.SyntaxKind.CatchKeyword:
253 case ts.SyntaxKind.ForKeyword:
254 case ts.SyntaxKind.IfKeyword:
255 case ts.SyntaxKind.SwitchKeyword:
256 case ts.SyntaxKind.WhileKeyword:
257 case ts.SyntaxKind.WithKeyword:
258 if (options.branch) {
259 prevTokenShouldBeFollowedByWhitespace = true;
262 case ts.SyntaxKind.CommaToken:
263 if (options.separator) {
264 prevTokenShouldBeFollowedByWhitespace = true;
267 case ts.SyntaxKind.SemicolonToken:
268 if (!options.separator) {
271 var nextPosition = range.pos + 1;
272 var semicolonInTrivialFor = parent.kind === ts.SyntaxKind.ForStatement &&
273 nextPosition !== sourceFile.end &&
274 (sourceFile.text[nextPosition] === ";" ||
275 sourceFile.text[nextPosition] === ")");
276 if (!semicolonInTrivialFor) {
277 prevTokenShouldBeFollowedByWhitespace = true;
280 case ts.SyntaxKind.EqualsToken:
281 if (options.decl && parent.kind !== ts.SyntaxKind.JsxAttribute) {
282 prevTokenShouldBeFollowedByWhitespace = true;
285 case ts.SyntaxKind.ColonToken:
287 prevTokenShouldBeFollowedByWhitespace = true;
290 case ts.SyntaxKind.OpenBraceToken:
291 var nextPos = range.pos + 1;
292 if (options.postbrace &&
293 (sourceFile.text[nextPos] !== " " &&
294 sourceFile.text[nextPos] !== "\r" &&
295 sourceFile.text[nextPos] !== "\t" &&
296 sourceFile.text[nextPos] !== "\n")) {
297 addMissingWhitespaceErrorAt(nextPos);
300 case ts.SyntaxKind.ImportKeyword:
301 if (utils.isCallExpression(parent) &&
302 parent.expression.kind === ts.SyntaxKind.ImportKeyword) {
303 return; // Don't check ImportCall
305 if (utils.isImportTypeNode(parent)) {
306 return; // Don't check TypeQuery
309 case ts.SyntaxKind.ExportKeyword:
310 case ts.SyntaxKind.FromKeyword:
311 if (options.typecast) {
312 prevTokenShouldBeFollowedByWhitespace = true;
316 function checkEqualsGreaterThanTokenInNode(node) {
317 if (!options.operator) {
320 var equalsGreaterThanToken = utils.getChildOfKind(node, ts.SyntaxKind.EqualsGreaterThanToken, sourceFile);
321 // condition so we don't crash if the arrow is somehow missing
322 if (equalsGreaterThanToken === undefined) {
325 checkForTrailingWhitespace(equalsGreaterThanToken.getFullStart());
326 checkForTrailingWhitespace(equalsGreaterThanToken.getEnd());
328 function checkForTrailingWhitespace(position, whiteSpacePos) {
329 if (whiteSpacePos === void 0) { whiteSpacePos = position; }
330 if (position !== sourceFile.end &&
331 !Lint.isWhiteSpace(sourceFile.text.charCodeAt(position))) {
332 addMissingWhitespaceErrorAt(whiteSpacePos);
335 function addMissingWhitespaceErrorAt(position) {
336 // TODO: this rule occasionally adds duplicate failures.
337 if (ctx.failures.some(function (f) { return f.getStartPosition().getPosition() === position; })) {
340 var fix = Lint.Replacement.appendText(position, " ");
341 ctx.addFailureAt(position, 1, Rule.FAILURE_STRING_MISSING, fix);
343 function checkForExcessiveWhitespace(position) {
344 if (position !== sourceFile.end &&
345 Lint.isWhiteSpace(sourceFile.text.charCodeAt(position))) {
346 addInvalidWhitespaceErrorAt(position);
349 function addInvalidWhitespaceErrorAt(position) {
350 var fix = Lint.Replacement.deleteText(position, 1);
351 ctx.addFailureAt(position, 1, Rule.FAILURE_STRING_INVALID, fix);
354 var templateObject_1;