forked from typescript-eslint/typescript-eslint
-
Notifications
You must be signed in to change notification settings - Fork 1
/
validator.ts
497 lines (440 loc) · 12.6 KB
/
validator.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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
import type { TSESTree } from '@typescript-eslint/utils';
import { AST_NODE_TYPES } from '@typescript-eslint/utils';
import type * as ts from 'typescript';
import * as util from '../../util';
import type { SelectorsString } from './enums';
import {
MetaSelectors,
Modifiers,
PredefinedFormats,
Selectors,
TypeModifiers,
UnderscoreOptions,
} from './enums';
import { PredefinedFormatToCheckFunction } from './format';
import {
isMetaSelector,
isMethodOrPropertySelector,
selectorTypeToMessageString,
} from './shared';
import type { Context, NormalizedSelector } from './types';
function createValidator(
type: SelectorsString,
context: Context,
allConfigs: NormalizedSelector[],
): (
node: TSESTree.Identifier | TSESTree.PrivateIdentifier | TSESTree.Literal,
) => void {
// make sure the "highest priority" configs are checked first
const selectorType = Selectors[type];
const configs = allConfigs
// gather all of the applicable selectors
.filter(
c =>
(c.selector & selectorType) !== 0 ||
c.selector === MetaSelectors.default,
)
.sort((a, b) => {
if (a.selector === b.selector) {
// in the event of the same selector, order by modifier weight
// sort descending - the type modifiers are "more important"
return b.modifierWeight - a.modifierWeight;
}
const aIsMeta = isMetaSelector(a.selector);
const bIsMeta = isMetaSelector(b.selector);
// non-meta selectors should go ahead of meta selectors
if (aIsMeta && !bIsMeta) {
return 1;
}
if (!aIsMeta && bIsMeta) {
return -1;
}
const aIsMethodOrProperty = isMethodOrPropertySelector(a.selector);
const bIsMethodOrProperty = isMethodOrPropertySelector(b.selector);
// for backward compatibility, method and property have higher precedence than other meta selectors
if (aIsMethodOrProperty && !bIsMethodOrProperty) {
return -1;
}
if (!aIsMethodOrProperty && bIsMethodOrProperty) {
return 1;
}
// both aren't meta selectors
// sort descending - the meta selectors are "least important"
return b.selector - a.selector;
});
return (
node: TSESTree.Identifier | TSESTree.PrivateIdentifier | TSESTree.Literal,
modifiers: Set<Modifiers> = new Set<Modifiers>(),
): void => {
const originalName =
node.type === AST_NODE_TYPES.Identifier ||
node.type === AST_NODE_TYPES.PrivateIdentifier
? node.name
: `${node.value}`;
// return will break the loop and stop checking configs
// it is only used when the name is known to have failed or succeeded a config.
for (const config of configs) {
if (config.filter?.regex.test(originalName) !== config.filter?.match) {
// name does not match the filter
continue;
}
if (config.modifiers?.some(modifier => !modifiers.has(modifier))) {
// does not have the required modifiers
continue;
}
if (!isCorrectType(node, config, context, selectorType)) {
// is not the correct type
continue;
}
let name: string | null = originalName;
name = validateUnderscore('leading', config, name, node, originalName);
if (name === null) {
// fail
return;
}
name = validateUnderscore('trailing', config, name, node, originalName);
if (name === null) {
// fail
return;
}
name = validateAffix('prefix', config, name, node, originalName);
if (name === null) {
// fail
return;
}
name = validateAffix('suffix', config, name, node, originalName);
if (name === null) {
// fail
return;
}
if (!validateCustom(config, name, node, originalName)) {
// fail
return;
}
if (
!validatePredefinedFormat(config, name, node, originalName, modifiers)
) {
// fail
return;
}
// it's valid for this config, so we don't need to check any more configs
return;
}
};
// centralizes the logic for formatting the report data
function formatReportData({
affixes,
formats,
originalName,
processedName,
position,
custom,
count,
}: {
affixes?: string[];
formats?: PredefinedFormats[];
originalName: string;
processedName?: string;
position?: 'leading' | 'trailing' | 'prefix' | 'suffix';
custom?: NonNullable<NormalizedSelector['custom']>;
count?: 'one' | 'two';
}): Record<string, unknown> {
return {
type: selectorTypeToMessageString(type),
name: originalName,
processedName,
position,
count,
affixes: affixes?.join(', '),
formats: formats?.map(f => PredefinedFormats[f]).join(', '),
regex: custom?.regex?.toString(),
regexMatch:
custom?.match === true
? 'match'
: custom?.match === false
? 'not match'
: null,
};
}
/**
* @returns the name with the underscore removed, if it is valid according to the specified underscore option, null otherwise
*/
function validateUnderscore(
position: 'leading' | 'trailing',
config: NormalizedSelector,
name: string,
node: TSESTree.Identifier | TSESTree.PrivateIdentifier | TSESTree.Literal,
originalName: string,
): string | null {
const option =
position === 'leading'
? config.leadingUnderscore
: config.trailingUnderscore;
if (!option) {
return name;
}
const hasSingleUnderscore =
position === 'leading'
? (): boolean => name.startsWith('_')
: (): boolean => name.endsWith('_');
const trimSingleUnderscore =
position === 'leading'
? (): string => name.slice(1)
: (): string => name.slice(0, -1);
const hasDoubleUnderscore =
position === 'leading'
? (): boolean => name.startsWith('__')
: (): boolean => name.endsWith('__');
const trimDoubleUnderscore =
position === 'leading'
? (): string => name.slice(2)
: (): string => name.slice(0, -2);
switch (option) {
// ALLOW - no conditions as the user doesn't care if it's there or not
case UnderscoreOptions.allow: {
if (hasSingleUnderscore()) {
return trimSingleUnderscore();
}
return name;
}
case UnderscoreOptions.allowDouble: {
if (hasDoubleUnderscore()) {
return trimDoubleUnderscore();
}
return name;
}
case UnderscoreOptions.allowSingleOrDouble: {
if (hasDoubleUnderscore()) {
return trimDoubleUnderscore();
}
if (hasSingleUnderscore()) {
return trimSingleUnderscore();
}
return name;
}
// FORBID
case UnderscoreOptions.forbid: {
if (hasSingleUnderscore()) {
context.report({
node,
messageId: 'unexpectedUnderscore',
data: formatReportData({
originalName,
position,
count: 'one',
}),
});
return null;
}
return name;
}
// REQUIRE
case UnderscoreOptions.require: {
if (!hasSingleUnderscore()) {
context.report({
node,
messageId: 'missingUnderscore',
data: formatReportData({
originalName,
position,
count: 'one',
}),
});
return null;
}
return trimSingleUnderscore();
}
case UnderscoreOptions.requireDouble: {
if (!hasDoubleUnderscore()) {
context.report({
node,
messageId: 'missingUnderscore',
data: formatReportData({
originalName,
position,
count: 'two',
}),
});
return null;
}
return trimDoubleUnderscore();
}
}
}
/**
* @returns the name with the affix removed, if it is valid according to the specified affix option, null otherwise
*/
function validateAffix(
position: 'prefix' | 'suffix',
config: NormalizedSelector,
name: string,
node: TSESTree.Identifier | TSESTree.PrivateIdentifier | TSESTree.Literal,
originalName: string,
): string | null {
const affixes = config[position];
if (!affixes || affixes.length === 0) {
return name;
}
for (const affix of affixes) {
const hasAffix =
position === 'prefix' ? name.startsWith(affix) : name.endsWith(affix);
const trimAffix =
position === 'prefix'
? (): string => name.slice(affix.length)
: (): string => name.slice(0, -affix.length);
if (hasAffix) {
// matches, so trim it and return
return trimAffix();
}
}
context.report({
node,
messageId: 'missingAffix',
data: formatReportData({
originalName,
position,
affixes,
}),
});
return null;
}
/**
* @returns true if the name is valid according to the `regex` option, false otherwise
*/
function validateCustom(
config: NormalizedSelector,
name: string,
node: TSESTree.Identifier | TSESTree.PrivateIdentifier | TSESTree.Literal,
originalName: string,
): boolean {
const custom = config.custom;
if (!custom) {
return true;
}
const result = custom.regex.test(name);
if (custom.match && result) {
return true;
}
if (!custom.match && !result) {
return true;
}
context.report({
node,
messageId: 'satisfyCustom',
data: formatReportData({
originalName,
custom,
}),
});
return false;
}
/**
* @returns true if the name is valid according to the `format` option, false otherwise
*/
function validatePredefinedFormat(
config: NormalizedSelector,
name: string,
node: TSESTree.Identifier | TSESTree.PrivateIdentifier | TSESTree.Literal,
originalName: string,
modifiers: Set<Modifiers>,
): boolean {
const formats = config.format;
if (formats === null || formats.length === 0) {
return true;
}
if (!modifiers.has(Modifiers.requiresQuotes)) {
for (const format of formats) {
const checker = PredefinedFormatToCheckFunction[format];
if (checker(name)) {
return true;
}
}
}
context.report({
node,
messageId:
originalName === name
? 'doesNotMatchFormat'
: 'doesNotMatchFormatTrimmed',
data: formatReportData({
originalName,
processedName: name,
formats,
}),
});
return false;
}
}
const SelectorsAllowedToHaveTypes =
Selectors.variable |
Selectors.parameter |
Selectors.classProperty |
Selectors.objectLiteralProperty |
Selectors.typeProperty |
Selectors.parameterProperty |
Selectors.accessor;
function isCorrectType(
node: TSESTree.Node,
config: NormalizedSelector,
context: Context,
selector: Selectors,
): boolean {
if (config.types === null) {
return true;
}
if ((SelectorsAllowedToHaveTypes & selector) === 0) {
return true;
}
const services = util.getParserServices(context);
const checker = services.program.getTypeChecker();
const type = services
.getTypeAtLocation(node)
// remove null and undefined from the type, as we don't care about it here
.getNonNullableType();
for (const allowedType of config.types) {
switch (allowedType) {
case TypeModifiers.array:
if (
isAllTypesMatch(
type,
t => checker.isArrayType(t) || checker.isTupleType(t),
)
) {
return true;
}
break;
case TypeModifiers.function:
if (isAllTypesMatch(type, t => t.getCallSignatures().length > 0)) {
return true;
}
break;
case TypeModifiers.boolean:
case TypeModifiers.number:
case TypeModifiers.string: {
const typeString = checker.typeToString(
// this will resolve things like true => boolean, 'a' => string and 1 => number
checker.getWidenedType(checker.getBaseTypeOfLiteralType(type)),
);
const allowedTypeString = TypeModifiers[allowedType];
if (typeString === allowedTypeString) {
return true;
}
break;
}
}
}
return false;
}
/**
* @returns `true` if the type (or all union types) in the given type return true for the callback
*/
function isAllTypesMatch(
type: ts.Type,
cb: (type: ts.Type) => boolean,
): boolean {
if (type.isUnion()) {
return type.types.every(t => cb(t));
}
return cb(type);
}
export { createValidator };