/
lines-around-comment.ts
456 lines (403 loc) · 13 KB
/
lines-around-comment.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
/* eslint-disable @typescript-eslint/no-non-null-assertion */
import type { TSESTree } from '@typescript-eslint/utils';
import { AST_NODE_TYPES, AST_TOKEN_TYPES } from '@typescript-eslint/utils';
import type {
InferMessageIdsTypeFromRule,
InferOptionsTypeFromRule,
} from '../util';
import { createRule, isCommentToken, isTokenOnSameLine } from '../util';
import { getESLintCoreRule } from '../util/getESLintCoreRule';
const baseRule = getESLintCoreRule('lines-around-comment');
export type Options = InferOptionsTypeFromRule<typeof baseRule>;
export type MessageIds = InferMessageIdsTypeFromRule<typeof baseRule>;
const COMMENTS_IGNORE_PATTERN =
/^\s*(?:eslint|jshint\s+|jslint\s+|istanbul\s+|globals?\s+|exported\s+|jscs)/u;
/**
* @returns an array with with any line numbers that are empty.
*/
function getEmptyLineNums(lines: string[]): number[] {
const emptyLines = lines
.map((line, i) => ({
code: line.trim(),
num: i + 1,
}))
.filter(line => !line.code)
.map(line => line.num);
return emptyLines;
}
/**
* @returns an array with with any line numbers that contain comments.
*/
function getCommentLineNums(comments: TSESTree.Comment[]): number[] {
const lines: number[] = [];
comments.forEach(token => {
const start = token.loc.start.line;
const end = token.loc.end.line;
lines.push(start, end);
});
return lines;
}
export default createRule<Options, MessageIds>({
name: 'lines-around-comment',
meta: {
deprecated: true,
replacedBy: ['@stylistic/ts/lines-around-comment'],
type: 'layout',
docs: {
description: 'Require empty lines around comments',
extendsBaseRule: true,
},
schema: [
{
type: 'object',
properties: {
beforeBlockComment: {
type: 'boolean',
default: true,
},
afterBlockComment: {
type: 'boolean',
default: false,
},
beforeLineComment: {
type: 'boolean',
default: false,
},
afterLineComment: {
type: 'boolean',
default: false,
},
allowBlockStart: {
type: 'boolean',
default: false,
},
allowBlockEnd: {
type: 'boolean',
default: false,
},
allowClassStart: {
type: 'boolean',
},
allowClassEnd: {
type: 'boolean',
},
allowObjectStart: {
type: 'boolean',
},
allowObjectEnd: {
type: 'boolean',
},
allowArrayStart: {
type: 'boolean',
},
allowArrayEnd: {
type: 'boolean',
},
allowInterfaceStart: {
type: 'boolean',
},
allowInterfaceEnd: {
type: 'boolean',
},
allowTypeStart: {
type: 'boolean',
},
allowTypeEnd: {
type: 'boolean',
},
allowEnumStart: {
type: 'boolean',
},
allowEnumEnd: {
type: 'boolean',
},
allowModuleStart: {
type: 'boolean',
},
allowModuleEnd: {
type: 'boolean',
},
ignorePattern: {
type: 'string',
},
applyDefaultIgnorePatterns: {
type: 'boolean',
},
},
additionalProperties: false,
},
],
fixable: baseRule.meta.fixable,
hasSuggestions: baseRule.meta.hasSuggestions,
messages: baseRule.meta.messages,
},
defaultOptions: [
{
beforeBlockComment: true,
},
],
create(context, [_options]) {
const options = _options!;
const defaultIgnoreRegExp = COMMENTS_IGNORE_PATTERN;
const customIgnoreRegExp = new RegExp(options.ignorePattern ?? '', 'u');
const comments = context.sourceCode.getAllComments();
const lines = context.sourceCode.lines;
const commentLines = getCommentLineNums(comments);
const emptyLines = getEmptyLineNums(lines);
const commentAndEmptyLines = new Set(commentLines.concat(emptyLines));
/**
* @returns whether comments are on lines starting with or ending with code.
*/
function codeAroundComment(token: TSESTree.Token): boolean {
let currentToken: TSESTree.Token | null = token;
do {
currentToken = context.sourceCode.getTokenBefore(currentToken, {
includeComments: true,
});
} while (currentToken && isCommentToken(currentToken));
if (currentToken && isTokenOnSameLine(currentToken, token)) {
return true;
}
currentToken = token;
do {
currentToken = context.sourceCode.getTokenAfter(currentToken, {
includeComments: true,
});
} while (currentToken && isCommentToken(currentToken));
if (currentToken && isTokenOnSameLine(token, currentToken)) {
return true;
}
return false;
}
/**
* @returns whether comments are inside a node type.
*/
function isParentNodeType<T extends TSESTree.AST_NODE_TYPES>(
parent: TSESTree.Node,
nodeType: T,
): parent is Extract<TSESTree.Node, { type: T }> {
return parent.type === nodeType;
}
/**
* @returns the parent node that contains the given token.
*/
function getParentNodeOfToken(token: TSESTree.Token): TSESTree.Node | null {
const node = context.sourceCode.getNodeByRangeIndex(token.range[0]);
return node;
}
/**
* @returns whether comments are at the parent start.
*/
function isCommentAtParentStart(
token: TSESTree.Token,
nodeType: TSESTree.AST_NODE_TYPES,
): boolean {
const parent = getParentNodeOfToken(token);
if (parent && isParentNodeType(parent, nodeType)) {
const parentStartNodeOrToken = parent;
return (
token.loc.start.line - parentStartNodeOrToken.loc.start.line === 1
);
}
return false;
}
/**
* @returns whether comments are at the parent end.
*/
function isCommentAtParentEnd(
token: TSESTree.Token,
nodeType: TSESTree.AST_NODE_TYPES,
): boolean {
const parent = getParentNodeOfToken(token);
return (
!!parent &&
isParentNodeType(parent, nodeType) &&
parent.loc.end.line - token.loc.end.line === 1
);
}
function isCommentAtInterfaceStart(token: TSESTree.Comment): boolean {
return isCommentAtParentStart(token, AST_NODE_TYPES.TSInterfaceBody);
}
function isCommentAtInterfaceEnd(token: TSESTree.Comment): boolean {
return isCommentAtParentEnd(token, AST_NODE_TYPES.TSInterfaceBody);
}
function isCommentAtTypeStart(token: TSESTree.Comment): boolean {
return isCommentAtParentStart(token, AST_NODE_TYPES.TSTypeLiteral);
}
function isCommentAtTypeEnd(token: TSESTree.Comment): boolean {
return isCommentAtParentEnd(token, AST_NODE_TYPES.TSTypeLiteral);
}
function isCommentAtEnumStart(token: TSESTree.Comment): boolean {
return isCommentAtParentStart(token, AST_NODE_TYPES.TSEnumDeclaration);
}
function isCommentAtEnumEnd(token: TSESTree.Comment): boolean {
return isCommentAtParentEnd(token, AST_NODE_TYPES.TSEnumDeclaration);
}
function isCommentAtModuleStart(token: TSESTree.Comment): boolean {
return isCommentAtParentStart(token, AST_NODE_TYPES.TSModuleBlock);
}
function isCommentAtModuleEnd(token: TSESTree.Comment): boolean {
return isCommentAtParentEnd(token, AST_NODE_TYPES.TSModuleBlock);
}
function isCommentNearTSConstruct(token: TSESTree.Comment): boolean {
return (
isCommentAtInterfaceStart(token) ||
isCommentAtInterfaceEnd(token) ||
isCommentAtTypeStart(token) ||
isCommentAtTypeEnd(token) ||
isCommentAtEnumStart(token) ||
isCommentAtEnumEnd(token) ||
isCommentAtModuleStart(token) ||
isCommentAtModuleEnd(token)
);
}
function checkForEmptyLine(
token: TSESTree.Comment,
{ before, after }: { before?: boolean; after?: boolean },
): void {
// the base rule handles comments away from TS constructs blocks correctly, we skip those
if (!isCommentNearTSConstruct(token)) {
return;
}
if (
options.applyDefaultIgnorePatterns !== false &&
defaultIgnoreRegExp.test(token.value)
) {
return;
}
if (options.ignorePattern && customIgnoreRegExp.test(token.value)) {
return;
}
const prevLineNum = token.loc.start.line - 1;
const nextLineNum = token.loc.end.line + 1;
// we ignore all inline comments
if (codeAroundComment(token)) {
return;
}
const interfaceStartAllowed =
Boolean(options.allowInterfaceStart) &&
isCommentAtInterfaceStart(token);
const interfaceEndAllowed =
Boolean(options.allowInterfaceEnd) && isCommentAtInterfaceEnd(token);
const typeStartAllowed =
Boolean(options.allowTypeStart) && isCommentAtTypeStart(token);
const typeEndAllowed =
Boolean(options.allowTypeEnd) && isCommentAtTypeEnd(token);
const enumStartAllowed =
Boolean(options.allowEnumStart) && isCommentAtEnumStart(token);
const enumEndAllowed =
Boolean(options.allowEnumEnd) && isCommentAtEnumEnd(token);
const moduleStartAllowed =
Boolean(options.allowModuleStart) && isCommentAtModuleStart(token);
const moduleEndAllowed =
Boolean(options.allowModuleEnd) && isCommentAtModuleEnd(token);
const exceptionStartAllowed =
interfaceStartAllowed ||
typeStartAllowed ||
enumStartAllowed ||
moduleStartAllowed;
const exceptionEndAllowed =
interfaceEndAllowed ||
typeEndAllowed ||
enumEndAllowed ||
moduleEndAllowed;
const previousTokenOrComment = context.sourceCode.getTokenBefore(token, {
includeComments: true,
});
const nextTokenOrComment = context.sourceCode.getTokenAfter(token, {
includeComments: true,
});
// check for newline before
if (
!exceptionStartAllowed &&
before &&
!commentAndEmptyLines.has(prevLineNum) &&
!(
isCommentToken(previousTokenOrComment!) &&
isTokenOnSameLine(previousTokenOrComment, token)
)
) {
const lineStart = token.range[0] - token.loc.start.column;
const range = [lineStart, lineStart] as const;
context.report({
node: token,
messageId: 'before',
fix(fixer) {
return fixer.insertTextBeforeRange(range, '\n');
},
});
}
// check for newline after
if (
!exceptionEndAllowed &&
after &&
!commentAndEmptyLines.has(nextLineNum) &&
!(
isCommentToken(nextTokenOrComment!) &&
isTokenOnSameLine(token, nextTokenOrComment)
)
) {
context.report({
node: token,
messageId: 'after',
fix(fixer) {
return fixer.insertTextAfter(token, '\n');
},
});
}
}
/**
* A custom report function for the baseRule to ignore false positive errors
* caused by TS-specific codes
*/
const customReport: typeof context.report = descriptor => {
if ('node' in descriptor) {
if (
descriptor.node.type === AST_TOKEN_TYPES.Line ||
descriptor.node.type === AST_TOKEN_TYPES.Block
) {
if (isCommentNearTSConstruct(descriptor.node)) {
return;
}
}
}
return context.report(descriptor);
};
const customContext = { report: customReport };
// we can't directly proxy `context` because its `report` property is non-configurable
// and non-writable. So we proxy `customContext` and redirect all
// property access to the original context except for `report`
const proxiedContext = new Proxy<typeof context>(
customContext as typeof context,
{
get(target, path, receiver): unknown {
if (path !== 'report') {
return Reflect.get(context, path, receiver);
}
return Reflect.get(target, path, receiver);
},
},
);
const rules = baseRule.create(proxiedContext);
return {
Program(): void {
rules.Program();
comments.forEach(token => {
if (token.type === AST_TOKEN_TYPES.Line) {
if (options.beforeLineComment || options.afterLineComment) {
checkForEmptyLine(token, {
after: options.afterLineComment,
before: options.beforeLineComment,
});
}
} else if (options.beforeBlockComment || options.afterBlockComment) {
checkForEmptyLine(token, {
after: options.afterBlockComment,
before: options.beforeBlockComment,
});
}
});
},
};
},
});