.gitignore added
[dotfiles/.git] / .config / coc / extensions / node_modules / coc-prettier / node_modules / tslint / lib / rules / whitespaceRule.js
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 OPTION_POSTBRACE = "check-postbrace";
35 var Rule = /** @class */ (function (_super) {
36     tslib_1.__extends(Rule, _super);
37     function Rule() {
38         return _super !== null && _super.apply(this, arguments) || this;
39     }
40     Rule.prototype.apply = function (sourceFile) {
41         return this.applyWithFunction(sourceFile, walk, parseOptions(this.ruleArguments));
42     };
43     Rule.metadata = {
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."]))),
48         options: {
49             type: "array",
50             items: {
51                 type: "string",
52                 enum: [
53                     "check-branch",
54                     "check-decl",
55                     "check-operator",
56                     "check-module",
57                     "check-separator",
58                     "check-rest-spread",
59                     "check-type",
60                     "check-typecast",
61                     "check-type-operator",
62                     "check-preblock",
63                     "check-postbrace",
64                 ],
65             },
66             minLength: 0,
67             maxLength: 11,
68         },
69         optionExamples: [[true, "check-branch", "check-operator", "check-typecast"]],
70         type: "formatting",
71         typescriptOnly: false,
72         hasFix: true,
73     };
74     Rule.FAILURE_STRING_MISSING = "missing whitespace";
75     Rule.FAILURE_STRING_INVALID = "invalid whitespace";
76     return Rule;
77 }(Lint.Rules.AbstractRule));
78 exports.Rule = Rule;
79 function parseOptions(ruleArguments) {
80     return {
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),
92     };
93     function has(option) {
94         return ruleArguments.indexOf(option) !== -1;
95     }
96 }
97 function walk(ctx) {
98     var sourceFile = ctx.sourceFile, options = ctx.options;
99     ts.forEachChild(sourceFile, function cb(node) {
100         switch (node.kind) {
101             case ts.SyntaxKind.ArrowFunction:
102                 checkEqualsGreaterThanTokenInNode(node);
103                 break;
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());
110                 }
111                 break;
112             }
113             case ts.SyntaxKind.Block:
114                 if (options.preblock) {
115                     checkForTrailingWhitespace(node.getFullStart());
116                 }
117                 break;
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());
125                 }
126                 break;
127             case ts.SyntaxKind.ConstructorType:
128                 checkEqualsGreaterThanTokenInNode(node);
129                 break;
130             case ts.SyntaxKind.ExportAssignment:
131                 if (options.module) {
132                     var exportKeyword = node.getChildAt(0);
133                     var position = exportKeyword.getEnd();
134                     checkForTrailingWhitespace(position);
135                 }
136                 break;
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());
144                         }
145                         if (idx === 0) {
146                             var startPos = element.getStart() - 1;
147                             checkForTrailingWhitespace(startPos, startPos + 1);
148                         }
149                     });
150                 }
151                 break;
152             case ts.SyntaxKind.FunctionType:
153                 checkEqualsGreaterThanTokenInNode(node);
154                 break;
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());
170                                     }
171                                     if (idx === 0) {
172                                         var startPos = element.getStart() - 1;
173                                         checkForTrailingWhitespace(startPos, startPos + 1);
174                                     }
175                                 }
176                             });
177                         }
178                         position = namedBindings_1.getEnd();
179                     }
180                     else if (importClause.name !== undefined) {
181                         position = importClause.name.getEnd();
182                     }
183                     if (position !== undefined) {
184                         checkForTrailingWhitespace(position);
185                     }
186                 }
187                 break;
188             }
189             case ts.SyntaxKind.ImportEqualsDeclaration:
190                 if (options.module) {
191                     var position = node.name.getEnd();
192                     checkForTrailingWhitespace(position);
193                 }
194                 break;
195             case ts.SyntaxKind.TypeAssertionExpression:
196                 if (options.typecast) {
197                     var position = node.expression.getFullStart();
198                     checkForTrailingWhitespace(position);
199                 }
200                 break;
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());
206                 }
207                 break;
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);
213                 }
214                 break;
215             case ts.SyntaxKind.SpreadAssignment:
216             case ts.SyntaxKind.SpreadElement:
217                 if (options.restSpread) {
218                     var position = node.expression.getFullStart();
219                     checkForExcessiveWhitespace(position);
220                 }
221                 break;
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) {
227                         if (index > 0) {
228                             checkForTrailingWhitespace(typeNode.getFullStart());
229                         }
230                         if (index < types_1.length - 1) {
231                             checkForTrailingWhitespace(typeNode.getEnd());
232                         }
233                     });
234                 }
235         }
236         ts.forEachChild(node, cb);
237     });
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;
244             return;
245         }
246         else if (prevTokenShouldBeFollowedByWhitespace) {
247             addMissingWhitespaceErrorAt(range.pos);
248             prevTokenShouldBeFollowedByWhitespace = false;
249         }
250         // check for trailing space after the given tokens
251         switch (tokenKind) {
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;
260                 }
261                 break;
262             case ts.SyntaxKind.CommaToken:
263                 if (options.separator) {
264                     prevTokenShouldBeFollowedByWhitespace = true;
265                 }
266                 break;
267             case ts.SyntaxKind.SemicolonToken:
268                 if (!options.separator) {
269                     break;
270                 }
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;
278                 }
279                 break;
280             case ts.SyntaxKind.EqualsToken:
281                 if (options.decl && parent.kind !== ts.SyntaxKind.JsxAttribute) {
282                     prevTokenShouldBeFollowedByWhitespace = true;
283                 }
284                 break;
285             case ts.SyntaxKind.ColonToken:
286                 if (options.type) {
287                     prevTokenShouldBeFollowedByWhitespace = true;
288                 }
289                 break;
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);
298                 }
299                 break;
300             case ts.SyntaxKind.ImportKeyword:
301                 if (utils.isCallExpression(parent) &&
302                     parent.expression.kind === ts.SyntaxKind.ImportKeyword) {
303                     return; // Don't check ImportCall
304                 }
305                 if (utils.isImportTypeNode(parent)) {
306                     return; // Don't check TypeQuery
307                 }
308             // falls through
309             case ts.SyntaxKind.ExportKeyword:
310             case ts.SyntaxKind.FromKeyword:
311                 if (options.typecast) {
312                     prevTokenShouldBeFollowedByWhitespace = true;
313                 }
314         }
315     });
316     function checkEqualsGreaterThanTokenInNode(node) {
317         if (!options.operator) {
318             return;
319         }
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) {
323             return;
324         }
325         checkForTrailingWhitespace(equalsGreaterThanToken.getFullStart());
326         checkForTrailingWhitespace(equalsGreaterThanToken.getEnd());
327     }
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);
333         }
334     }
335     function addMissingWhitespaceErrorAt(position) {
336         // TODO: this rule occasionally adds duplicate failures.
337         if (ctx.failures.some(function (f) { return f.getStartPosition().getPosition() === position; })) {
338             return;
339         }
340         var fix = Lint.Replacement.appendText(position, " ");
341         ctx.addFailureAt(position, 1, Rule.FAILURE_STRING_MISSING, fix);
342     }
343     function checkForExcessiveWhitespace(position) {
344         if (position !== sourceFile.end &&
345             Lint.isWhiteSpace(sourceFile.text.charCodeAt(position))) {
346             addInvalidWhitespaceErrorAt(position);
347         }
348     }
349     function addInvalidWhitespaceErrorAt(position) {
350         var fix = Lint.Replacement.deleteText(position, 1);
351         ctx.addFailureAt(position, 1, Rule.FAILURE_STRING_INVALID, fix);
352     }
353 }
354 var templateObject_1;