.gitignore added
[dotfiles/.git] / .config / coc / extensions / node_modules / coc-prettier / node_modules / tslint / lib / rules / commentFormatRule.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 var utils = require("tsutils");
21 var ts = require("typescript");
22 var enableDisableRules_1 = require("../enableDisableRules");
23 var Lint = require("../index");
24 var utils_1 = require("../utils");
25 var OPTION_SPACE = "check-space";
26 var OPTION_LOWERCASE = "check-lowercase";
27 var OPTION_UPPERCASE = "check-uppercase";
28 var OPTION_ALLOW_TRAILING_LOWERCASE = "allow-trailing-lowercase";
29 var Rule = /** @class */ (function (_super) {
30     tslib_1.__extends(Rule, _super);
31     function Rule() {
32         return _super !== null && _super.apply(this, arguments) || this;
33     }
34     Rule.prototype.apply = function (sourceFile) {
35         var commentFormatWalker = new CommentFormatWalker(sourceFile, this.ruleName, parseOptions(this.ruleArguments));
36         return this.applyWithWalker(commentFormatWalker);
37     };
38     /* tslint:disable:object-literal-sort-keys */
39     Rule.metadata = {
40         ruleName: "comment-format",
41         description: "Enforces formatting rules for single-line comments.",
42         rationale: "Helps maintain a consistent, readable style in your codebase.",
43         optionsDescription: Lint.Utils.dedent(templateObject_1 || (templateObject_1 = tslib_1.__makeTemplateObject(["\n            Four arguments may be optionally provided:\n\n            * `\"", "\"` requires that all single-line comments must begin with a space, as in `// comment`\n                * note that for comments starting with multiple slashes, e.g. `///`, leading slashes are ignored\n                * TypeScript reference comments are ignored completely\n            * `\"", "\"` requires that the first non-whitespace character of a comment must be lowercase, if applicable.\n            * `\"", "\"` requires that the first non-whitespace character of a comment must be uppercase, if applicable.\n            * `\"", "\"` allows that only the first comment of a series of comments needs to be uppercase.\n                * requires `\"", "\"`\n                * comments must start at the same position\n\n            Exceptions to `\"", "\"` or `\"", "\"` can be managed with object that may be passed as last\n            argument.\n\n            One of two options can be provided in this object:\n\n            * `\"ignore-words\"`  - array of strings - words that will be ignored at the beginning of the comment.\n            * `\"ignore-pattern\"` - string - RegExp pattern that will be ignored at the beginning of the comment.\n            "], ["\n            Four arguments may be optionally provided:\n\n            * \\`\"", "\"\\` requires that all single-line comments must begin with a space, as in \\`// comment\\`\n                * note that for comments starting with multiple slashes, e.g. \\`///\\`, leading slashes are ignored\n                * TypeScript reference comments are ignored completely\n            * \\`\"", "\"\\` requires that the first non-whitespace character of a comment must be lowercase, if applicable.\n            * \\`\"", "\"\\` requires that the first non-whitespace character of a comment must be uppercase, if applicable.\n            * \\`\"", "\"\\` allows that only the first comment of a series of comments needs to be uppercase.\n                * requires \\`\"", "\"\\`\n                * comments must start at the same position\n\n            Exceptions to \\`\"", "\"\\` or \\`\"", "\"\\` can be managed with object that may be passed as last\n            argument.\n\n            One of two options can be provided in this object:\n\n            * \\`\"ignore-words\"\\`  - array of strings - words that will be ignored at the beginning of the comment.\n            * \\`\"ignore-pattern\"\\` - string - RegExp pattern that will be ignored at the beginning of the comment.\n            "])), OPTION_SPACE, OPTION_LOWERCASE, OPTION_UPPERCASE, OPTION_ALLOW_TRAILING_LOWERCASE, OPTION_UPPERCASE, OPTION_LOWERCASE, OPTION_UPPERCASE),
44         options: {
45             type: "array",
46             items: {
47                 anyOf: [
48                     {
49                         type: "string",
50                         enum: [
51                             OPTION_SPACE,
52                             OPTION_LOWERCASE,
53                             OPTION_UPPERCASE,
54                             OPTION_ALLOW_TRAILING_LOWERCASE,
55                         ],
56                     },
57                     {
58                         type: "object",
59                         properties: {
60                             "ignore-words": {
61                                 type: "array",
62                                 items: {
63                                     type: "string",
64                                 },
65                             },
66                             "ignore-pattern": {
67                                 type: "string",
68                             },
69                         },
70                         minProperties: 1,
71                         maxProperties: 1,
72                     },
73                 ],
74             },
75             minLength: 1,
76             maxLength: 5,
77         },
78         optionExamples: [
79             [true, OPTION_SPACE, OPTION_UPPERCASE, OPTION_ALLOW_TRAILING_LOWERCASE],
80             [true, OPTION_LOWERCASE, { "ignore-words": ["TODO", "HACK"] }],
81             [true, OPTION_LOWERCASE, { "ignore-pattern": "STD\\w{2,3}\\b" }],
82         ],
83         type: "style",
84         typescriptOnly: false,
85         hasFix: true,
86     };
87     /* tslint:enable:object-literal-sort-keys */
88     Rule.LOWERCASE_FAILURE = "comment must start with lowercase letter";
89     Rule.SPACE_LOWERCASE_FAILURE = "comment must start with a space and lowercase letter";
90     Rule.UPPERCASE_FAILURE = "comment must start with uppercase letter";
91     Rule.SPACE_UPPERCASE_FAILURE = "comment must start with a space and uppercase letter";
92     Rule.LEADING_SPACE_FAILURE = "comment must start with a space";
93     Rule.IGNORE_WORDS_FAILURE_FACTORY = function (words) {
94         return " or the word(s): " + words.join(", ");
95     };
96     Rule.IGNORE_PATTERN_FAILURE_FACTORY = function (pattern) {
97         return " or its start must match the regex pattern \"" + pattern + "\"";
98     };
99     return Rule;
100 }(Lint.Rules.AbstractRule));
101 exports.Rule = Rule;
102 function parseOptions(options) {
103     return tslib_1.__assign({ allowTrailingLowercase: has(OPTION_ALLOW_TRAILING_LOWERCASE), case: options.indexOf(OPTION_LOWERCASE) !== -1
104             ? 1 /* Lower */
105             : options.indexOf(OPTION_UPPERCASE) !== -1
106                 ? 2 /* Upper */
107                 : 0 /* None */, failureSuffix: "", space: has(OPTION_SPACE) }, composeExceptions(options[options.length - 1]));
108     function has(option) {
109         return options.indexOf(option) !== -1;
110     }
111 }
112 function composeExceptions(option) {
113     if (typeof option !== "object") {
114         return undefined;
115     }
116     var ignorePattern = option["ignore-pattern"];
117     if (ignorePattern !== undefined) {
118         return {
119             exceptions: new RegExp("^\\s*(" + ignorePattern + ")"),
120             failureSuffix: Rule.IGNORE_PATTERN_FAILURE_FACTORY(ignorePattern),
121         };
122     }
123     var ignoreWords = option["ignore-words"];
124     if (ignoreWords !== undefined && ignoreWords.length !== 0) {
125         return {
126             exceptions: new RegExp("^\\s*(?:" + ignoreWords.map(function (word) { return utils_1.escapeRegExp(word.trim()); }).join("|") + ")\\b"),
127             failureSuffix: Rule.IGNORE_WORDS_FAILURE_FACTORY(ignoreWords),
128         };
129     }
130     return undefined;
131 }
132 var CommentFormatWalker = /** @class */ (function (_super) {
133     tslib_1.__extends(CommentFormatWalker, _super);
134     function CommentFormatWalker() {
135         return _super !== null && _super.apply(this, arguments) || this;
136     }
137     CommentFormatWalker.prototype.walk = function (sourceFile) {
138         var _this = this;
139         utils.forEachComment(sourceFile, function (fullText, comment) {
140             var commentStatus = _this.checkComment(fullText, comment);
141             _this.handleFailure(commentStatus, comment.end);
142             // cache position of last comment
143             _this.prevComment = ts.getLineAndCharacterOfPosition(sourceFile, comment.pos);
144             _this.prevCommentIsValid = commentStatus.validForTrailingLowercase;
145         });
146     };
147     CommentFormatWalker.prototype.checkComment = function (fullText, _a) {
148         var kind = _a.kind, pos = _a.pos, end = _a.end;
149         var status = {
150             firstLetterPos: -1,
151             leadingSpaceError: false,
152             lowercaseError: false,
153             start: pos + 2,
154             text: "",
155             uppercaseError: false,
156             validForTrailingLowercase: false,
157         };
158         if (kind !== ts.SyntaxKind.SingleLineCommentTrivia ||
159             // exclude empty comments
160             status.start === end ||
161             // exclude /// <reference path="...">
162             (fullText[status.start] === "/" &&
163                 this.sourceFile.referencedFiles.some(function (ref) { return ref.pos >= pos && ref.end <= end; }))) {
164             return status;
165         }
166         // skip all leading slashes
167         while (fullText[status.start] === "/") {
168             ++status.start;
169         }
170         if (status.start === end) {
171             return status;
172         }
173         status.text = fullText.slice(status.start, end);
174         // whitelist //#region and //#endregion and JetBrains IDEs' "//noinspection ...", "//region", "//endregion"
175         if (/^(?:#?(?:end)?region|noinspection\s)/.test(status.text)) {
176             return status;
177         }
178         if (this.options.space && status.text[0] !== " ") {
179             status.leadingSpaceError = true;
180         }
181         if (this.options.case === 0 /* None */ ||
182             (this.options.exceptions !== undefined && this.options.exceptions.test(status.text)) ||
183             enableDisableRules_1.ENABLE_DISABLE_REGEX.test(status.text)) {
184             return status;
185         }
186         // search for first non-space character to check if lower or upper
187         var charPos = status.text.search(/\S/);
188         if (charPos === -1) {
189             return status;
190         }
191         // All non-empty and not whitelisted comments are valid for the trailing lowercase rule
192         status.validForTrailingLowercase = true;
193         status.firstLetterPos = charPos;
194         if (this.options.case === 1 /* Lower */ && !utils_1.isLowerCase(status.text[charPos])) {
195             status.lowercaseError = true;
196         }
197         else if (this.options.case === 2 /* Upper */ && !utils_1.isUpperCase(status.text[charPos])) {
198             status.uppercaseError = true;
199             if (this.options.allowTrailingLowercase &&
200                 this.prevComment !== undefined &&
201                 this.prevCommentIsValid) {
202                 var currentComment = ts.getLineAndCharacterOfPosition(this.sourceFile, pos);
203                 if (this.prevComment.line + 1 === currentComment.line &&
204                     this.prevComment.character === currentComment.character) {
205                     status.uppercaseError = false;
206                 }
207             }
208         }
209         return status;
210     };
211     CommentFormatWalker.prototype.handleFailure = function (status, end) {
212         // No failure detected
213         if (!status.leadingSpaceError && !status.lowercaseError && !status.uppercaseError) {
214             return;
215         }
216         // Only whitespace failure
217         if (status.leadingSpaceError && !status.lowercaseError && !status.uppercaseError) {
218             this.addFailure(status.start, end, Rule.LEADING_SPACE_FAILURE, Lint.Replacement.appendText(status.start, " "));
219             return;
220         }
221         var msg;
222         var firstLetterFix;
223         if (status.lowercaseError) {
224             msg = status.leadingSpaceError ? Rule.SPACE_LOWERCASE_FAILURE : Rule.LOWERCASE_FAILURE;
225             firstLetterFix = status.text[status.firstLetterPos].toLowerCase();
226         }
227         else {
228             msg = status.leadingSpaceError ? Rule.SPACE_UPPERCASE_FAILURE : Rule.UPPERCASE_FAILURE;
229             firstLetterFix = status.text[status.firstLetterPos].toUpperCase();
230         }
231         var fix = status.leadingSpaceError
232             ? new Lint.Replacement(status.start, 1, " " + firstLetterFix)
233             : new Lint.Replacement(status.start + status.firstLetterPos, 1, firstLetterFix);
234         this.addFailure(status.start, end, msg + this.options.failureSuffix, fix);
235     };
236     return CommentFormatWalker;
237 }(Lint.AbstractWalker));
238 var templateObject_1;