/
prefer-string-starts-ends-with.ts
676 lines (617 loc) · 22.4 KB
/
prefer-string-starts-ends-with.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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
import type { TSESLint, TSESTree } from '@typescript-eslint/utils';
import { AST_NODE_TYPES } from '@typescript-eslint/utils';
import type { AST as RegExpAST } from 'regexpp';
import { RegExpParser } from 'regexpp';
import {
createRule,
getParserServices,
getPropertyName,
getStaticValue,
getTypeName,
isNotClosingParenToken,
nullThrows,
NullThrowsReasons,
} from '../util';
const EQ_OPERATORS = /^[=!]=/;
const regexpp = new RegExpParser();
export default createRule({
name: 'prefer-string-starts-ends-with',
defaultOptions: [],
meta: {
type: 'suggestion',
docs: {
description:
'Enforce using `String#startsWith` and `String#endsWith` over other equivalent methods of checking substrings',
recommended: 'strict',
requiresTypeChecking: true,
},
messages: {
preferStartsWith: "Use 'String#startsWith' method instead.",
preferEndsWith: "Use the 'String#endsWith' method instead.",
},
schema: [],
fixable: 'code',
},
create(context) {
const globalScope = context.getScope();
const sourceCode = context.getSourceCode();
const service = getParserServices(context);
const typeChecker = service.program.getTypeChecker();
/**
* Check if a given node is a string.
* @param node The node to check.
*/
function isStringType(node: TSESTree.Expression): boolean {
const objectType = typeChecker.getTypeAtLocation(
service.esTreeNodeToTSNodeMap.get(node),
);
return getTypeName(typeChecker, objectType) === 'string';
}
/**
* Check if a given node is a `Literal` node that is null.
* @param node The node to check.
*/
function isNull(node: TSESTree.Node): node is TSESTree.Literal {
const evaluated = getStaticValue(node, globalScope);
return evaluated != null && evaluated.value === null;
}
/**
* Check if a given node is a `Literal` node that is a given value.
* @param node The node to check.
* @param value The expected value of the `Literal` node.
*/
function isNumber(
node: TSESTree.Node,
value: number,
): node is TSESTree.Literal {
const evaluated = getStaticValue(node, globalScope);
return evaluated != null && evaluated.value === value;
}
/**
* Check if a given node is a `Literal` node that is a character.
* @param node The node to check.
* @param kind The method name to get a character.
*/
function isCharacter(node: TSESTree.Node): node is TSESTree.Literal {
const evaluated = getStaticValue(node, globalScope);
return (
evaluated != null &&
typeof evaluated.value === 'string' &&
// checks if the string is a character long
evaluated.value[0] === evaluated.value
);
}
/**
* Check if a given node is `==`, `===`, `!=`, or `!==`.
* @param node The node to check.
*/
function isEqualityComparison(
node: TSESTree.Node,
): node is TSESTree.BinaryExpression {
return (
node.type === AST_NODE_TYPES.BinaryExpression &&
EQ_OPERATORS.test(node.operator)
);
}
/**
* Check if two given nodes are the same meaning.
* @param node1 A node to compare.
* @param node2 Another node to compare.
*/
function isSameTokens(node1: TSESTree.Node, node2: TSESTree.Node): boolean {
const tokens1 = sourceCode.getTokens(node1);
const tokens2 = sourceCode.getTokens(node2);
if (tokens1.length !== tokens2.length) {
return false;
}
for (let i = 0; i < tokens1.length; ++i) {
const token1 = tokens1[i];
const token2 = tokens2[i];
if (token1.type !== token2.type || token1.value !== token2.value) {
return false;
}
}
return true;
}
/**
* Check if a given node is the expression of the length of a string.
*
* - If `length` property access of `expectedObjectNode`, it's `true`.
* E.g., `foo` → `foo.length` / `"foo"` → `"foo".length`
* - If `expectedObjectNode` is a string literal, `node` can be a number.
* E.g., `"foo"` → `3`
*
* @param node The node to check.
* @param expectedObjectNode The node which is expected as the receiver of `length` property.
*/
function isLengthExpression(
node: TSESTree.Node,
expectedObjectNode: TSESTree.Node,
): boolean {
if (node.type === AST_NODE_TYPES.MemberExpression) {
return (
getPropertyName(node, globalScope) === 'length' &&
isSameTokens(node.object, expectedObjectNode)
);
}
const evaluatedLength = getStaticValue(node, globalScope);
const evaluatedString = getStaticValue(expectedObjectNode, globalScope);
return (
evaluatedLength != null &&
evaluatedString != null &&
typeof evaluatedLength.value === 'number' &&
typeof evaluatedString.value === 'string' &&
evaluatedLength.value === evaluatedString.value.length
);
}
/**
* Check if a given node is a negative index expression
*
* E.g. `s.slice(- <expr>)`, `s.substring(s.length - <expr>)`
*
* @param node The node to check.
* @param expectedIndexedNode The node which is expected as the receiver of index expression.
*/
function isNegativeIndexExpression(
node: TSESTree.Node,
expectedIndexedNode: TSESTree.Node,
): boolean {
return (
(node.type === AST_NODE_TYPES.UnaryExpression &&
node.operator === '-') ||
(node.type === AST_NODE_TYPES.BinaryExpression &&
node.operator === '-' &&
isLengthExpression(node.left, expectedIndexedNode))
);
}
/**
* Check if a given node is the expression of the last index.
*
* E.g. `foo.length - 1`
*
* @param node The node to check.
* @param expectedObjectNode The node which is expected as the receiver of `length` property.
*/
function isLastIndexExpression(
node: TSESTree.Node,
expectedObjectNode: TSESTree.Node,
): boolean {
return (
node.type === AST_NODE_TYPES.BinaryExpression &&
node.operator === '-' &&
isLengthExpression(node.left, expectedObjectNode) &&
isNumber(node.right, 1)
);
}
/**
* Get the range of the property of a given `MemberExpression` node.
*
* - `obj[foo]` → the range of `[foo]`
* - `obf.foo` → the range of `.foo`
* - `(obj).foo` → the range of `.foo`
*
* @param node The member expression node to get.
*/
function getPropertyRange(
node: TSESTree.MemberExpression,
): [number, number] {
const dotOrOpenBracket = sourceCode.getTokenAfter(
node.object,
isNotClosingParenToken,
)!;
return [dotOrOpenBracket.range[0], node.range[1]];
}
/**
* Parse a given `RegExp` pattern to that string if it's a static string.
* @param pattern The RegExp pattern text to parse.
* @param uFlag The Unicode flag of the RegExp.
*/
function parseRegExpText(pattern: string, uFlag: boolean): string | null {
// Parse it.
const ast = regexpp.parsePattern(pattern, undefined, undefined, uFlag);
if (ast.alternatives.length !== 1) {
return null;
}
// Drop `^`/`$` assertion.
const chars = ast.alternatives[0].elements;
const first = chars[0];
if (first.type === 'Assertion' && first.kind === 'start') {
chars.shift();
} else {
chars.pop();
}
// Check if it can determine a unique string.
if (!chars.every(c => c.type === 'Character')) {
return null;
}
// To string.
return String.fromCodePoint(
...chars.map(c => (c as RegExpAST.Character).value),
);
}
/**
* Parse a given node if it's a `RegExp` instance.
* @param node The node to parse.
*/
function parseRegExp(
node: TSESTree.Node,
): { isStartsWith: boolean; isEndsWith: boolean; text: string } | null {
const evaluated = getStaticValue(node, globalScope);
if (evaluated == null || !(evaluated.value instanceof RegExp)) {
return null;
}
const { source, flags } = evaluated.value;
const isStartsWith = source.startsWith('^');
const isEndsWith = source.endsWith('$');
if (
isStartsWith === isEndsWith ||
flags.includes('i') ||
flags.includes('m')
) {
return null;
}
const text = parseRegExpText(source, flags.includes('u'));
if (text == null) {
return null;
}
return { isEndsWith, isStartsWith, text };
}
function getLeftNode(
node: TSESTree.Expression | TSESTree.PrivateIdentifier,
): TSESTree.MemberExpression {
if (node.type === AST_NODE_TYPES.ChainExpression) {
return getLeftNode(node.expression);
}
let leftNode;
if (node.type === AST_NODE_TYPES.CallExpression) {
leftNode = node.callee;
} else {
leftNode = node;
}
if (leftNode.type !== AST_NODE_TYPES.MemberExpression) {
throw new Error(`Expected a MemberExpression, got ${leftNode.type}`);
}
return leftNode;
}
/**
* Fix code with using the right operand as the search string.
* For example: `foo.slice(0, 3) === 'bar'` → `foo.startsWith('bar')`
* @param fixer The rule fixer.
* @param node The node which was reported.
* @param kind The kind of the report.
* @param isNegative The flag to fix to negative condition.
*/
function* fixWithRightOperand(
fixer: TSESLint.RuleFixer,
node: TSESTree.BinaryExpression,
kind: 'start' | 'end',
isNegative: boolean,
isOptional: boolean,
): IterableIterator<TSESLint.RuleFix> {
// left is CallExpression or MemberExpression.
const leftNode = getLeftNode(node.left);
const propertyRange = getPropertyRange(leftNode);
if (isNegative) {
yield fixer.insertTextBefore(node, '!');
}
yield fixer.replaceTextRange(
[propertyRange[0], node.right.range[0]],
`${isOptional ? '?.' : '.'}${kind}sWith(`,
);
yield fixer.replaceTextRange([node.right.range[1], node.range[1]], ')');
}
/**
* Fix code with using the first argument as the search string.
* For example: `foo.indexOf('bar') === 0` → `foo.startsWith('bar')`
* @param fixer The rule fixer.
* @param node The node which was reported.
* @param kind The kind of the report.
* @param negative The flag to fix to negative condition.
*/
function* fixWithArgument(
fixer: TSESLint.RuleFixer,
node: TSESTree.BinaryExpression,
callNode: TSESTree.CallExpression,
calleeNode: TSESTree.MemberExpression,
kind: 'start' | 'end',
negative: boolean,
isOptional: boolean,
): IterableIterator<TSESLint.RuleFix> {
if (negative) {
yield fixer.insertTextBefore(node, '!');
}
yield fixer.replaceTextRange(
getPropertyRange(calleeNode),
`${isOptional ? '?.' : '.'}${kind}sWith`,
);
yield fixer.removeRange([callNode.range[1], node.range[1]]);
}
function getParent(node: TSESTree.Node): TSESTree.Node {
return nullThrows(
node.parent?.type === AST_NODE_TYPES.ChainExpression
? node.parent.parent
: node.parent,
NullThrowsReasons.MissingParent,
);
}
return {
// foo[0] === "a"
// foo.charAt(0) === "a"
// foo[foo.length - 1] === "a"
// foo.charAt(foo.length - 1) === "a"
[[
'BinaryExpression > MemberExpression.left[computed=true]',
'BinaryExpression > CallExpression.left > MemberExpression.callee[property.name="charAt"][computed=false]',
'BinaryExpression > ChainExpression.left > MemberExpression[computed=true]',
'BinaryExpression > ChainExpression.left > CallExpression > MemberExpression.callee[property.name="charAt"][computed=false]',
].join(', ')](node: TSESTree.MemberExpression): void {
let parentNode = getParent(node);
let indexNode: TSESTree.Node | null = null;
if (parentNode?.type === AST_NODE_TYPES.CallExpression) {
if (parentNode.arguments.length === 1) {
indexNode = parentNode.arguments[0];
}
parentNode = getParent(parentNode);
} else {
indexNode = node.property;
}
if (
indexNode == null ||
!isEqualityComparison(parentNode) ||
!isStringType(node.object)
) {
return;
}
const isEndsWith = isLastIndexExpression(indexNode, node.object);
const isStartsWith = !isEndsWith && isNumber(indexNode, 0);
if (!isStartsWith && !isEndsWith) {
return;
}
const eqNode = parentNode;
context.report({
node: parentNode,
messageId: isStartsWith ? 'preferStartsWith' : 'preferEndsWith',
fix(fixer) {
// Don't fix if it can change the behavior.
if (!isCharacter(eqNode.right)) {
return null;
}
return fixWithRightOperand(
fixer,
eqNode,
isStartsWith ? 'start' : 'end',
eqNode.operator.startsWith('!'),
node.optional,
);
},
});
},
// foo.indexOf('bar') === 0
[[
'BinaryExpression > CallExpression.left > MemberExpression.callee[property.name="indexOf"][computed=false]',
'BinaryExpression > ChainExpression.left > CallExpression > MemberExpression.callee[property.name="indexOf"][computed=false]',
].join(', ')](node: TSESTree.MemberExpression): void {
const callNode = getParent(node) as TSESTree.CallExpression;
const parentNode = getParent(callNode);
if (
callNode.arguments.length !== 1 ||
!isEqualityComparison(parentNode) ||
!isNumber(parentNode.right, 0) ||
!isStringType(node.object)
) {
return;
}
context.report({
node: parentNode,
messageId: 'preferStartsWith',
fix(fixer) {
return fixWithArgument(
fixer,
parentNode,
callNode,
node,
'start',
parentNode.operator.startsWith('!'),
node.optional,
);
},
});
},
// foo.lastIndexOf('bar') === foo.length - 3
// foo.lastIndexOf(bar) === foo.length - bar.length
[[
'BinaryExpression > CallExpression.left > MemberExpression.callee[property.name="lastIndexOf"][computed=false]',
'BinaryExpression > ChainExpression.left > CallExpression > MemberExpression.callee[property.name="lastIndexOf"][computed=false]',
].join(', ')](node: TSESTree.MemberExpression): void {
const callNode = getParent(node) as TSESTree.CallExpression;
const parentNode = getParent(callNode);
if (
callNode.arguments.length !== 1 ||
!isEqualityComparison(parentNode) ||
parentNode.right.type !== AST_NODE_TYPES.BinaryExpression ||
parentNode.right.operator !== '-' ||
!isLengthExpression(parentNode.right.left, node.object) ||
!isLengthExpression(parentNode.right.right, callNode.arguments[0]) ||
!isStringType(node.object)
) {
return;
}
context.report({
node: parentNode,
messageId: 'preferEndsWith',
fix(fixer) {
return fixWithArgument(
fixer,
parentNode,
callNode,
node,
'end',
parentNode.operator.startsWith('!'),
node.optional,
);
},
});
},
// foo.match(/^bar/) === null
// foo.match(/bar$/) === null
[[
'BinaryExpression > CallExpression.left > MemberExpression.callee[property.name="match"][computed=false]',
'BinaryExpression > ChainExpression.left > CallExpression > MemberExpression.callee[property.name="match"][computed=false]',
].join(', ')](node: TSESTree.MemberExpression): void {
const callNode = getParent(node) as TSESTree.CallExpression;
const parentNode = getParent(callNode) as TSESTree.BinaryExpression;
if (
!isEqualityComparison(parentNode) ||
!isNull(parentNode.right) ||
!isStringType(node.object)
) {
return;
}
const parsed =
callNode.arguments.length === 1
? parseRegExp(callNode.arguments[0])
: null;
if (parsed == null) {
return;
}
const { isStartsWith, text } = parsed;
context.report({
node: callNode,
messageId: isStartsWith ? 'preferStartsWith' : 'preferEndsWith',
*fix(fixer) {
if (!parentNode.operator.startsWith('!')) {
yield fixer.insertTextBefore(parentNode, '!');
}
yield fixer.replaceTextRange(
getPropertyRange(node),
`${node.optional ? '?.' : '.'}${
isStartsWith ? 'start' : 'end'
}sWith`,
);
yield fixer.replaceText(
callNode.arguments[0],
JSON.stringify(text),
);
yield fixer.removeRange([callNode.range[1], parentNode.range[1]]);
},
});
},
// foo.slice(0, 3) === 'bar'
// foo.slice(-3) === 'bar'
// foo.slice(-3, foo.length) === 'bar'
// foo.substring(0, 3) === 'bar'
// foo.substring(foo.length - 3) === 'bar'
// foo.substring(foo.length - 3, foo.length) === 'bar'
[[
'BinaryExpression > CallExpression.left > MemberExpression.callee[property.name="slice"][computed=false]',
'BinaryExpression > CallExpression.left > MemberExpression.callee[property.name="substring"][computed=false]',
'BinaryExpression > ChainExpression.left > CallExpression > MemberExpression.callee[property.name="slice"][computed=false]',
'BinaryExpression > ChainExpression.left > CallExpression > MemberExpression.callee[property.name="substring"][computed=false]',
].join(', ')](node: TSESTree.MemberExpression): void {
const callNode = getParent(node) as TSESTree.CallExpression;
const parentNode = getParent(callNode);
if (!isEqualityComparison(parentNode) || !isStringType(node.object)) {
return;
}
const isEndsWith =
(callNode.arguments.length === 1 ||
(callNode.arguments.length === 2 &&
isLengthExpression(callNode.arguments[1], node.object))) &&
isNegativeIndexExpression(callNode.arguments[0], node.object);
const isStartsWith =
!isEndsWith &&
callNode.arguments.length === 2 &&
isNumber(callNode.arguments[0], 0) &&
!isNegativeIndexExpression(callNode.arguments[1], node.object);
if (!isStartsWith && !isEndsWith) {
return;
}
const eqNode = parentNode;
const negativeIndexSupported =
(node.property as TSESTree.Identifier).name === 'slice';
context.report({
node: parentNode,
messageId: isStartsWith ? 'preferStartsWith' : 'preferEndsWith',
fix(fixer) {
// Don't fix if it can change the behavior.
if (
eqNode.operator.length === 2 &&
(eqNode.right.type !== AST_NODE_TYPES.Literal ||
typeof eqNode.right.value !== 'string')
) {
return null;
}
// code being checked is likely mistake:
// unequal length of strings being checked for equality
// or reliant on behavior of substring (negative indices interpreted as 0)
if (isStartsWith) {
if (!isLengthExpression(callNode.arguments[1], eqNode.right)) {
return null;
}
} else {
const posNode = callNode.arguments[0];
const posNodeIsAbsolutelyValid =
(posNode.type === AST_NODE_TYPES.BinaryExpression &&
posNode.operator === '-' &&
isLengthExpression(posNode.left, node.object) &&
isLengthExpression(posNode.right, eqNode.right)) ||
(negativeIndexSupported &&
posNode.type === AST_NODE_TYPES.UnaryExpression &&
posNode.operator === '-' &&
isLengthExpression(posNode.argument, eqNode.right));
if (!posNodeIsAbsolutelyValid) {
return null;
}
}
return fixWithRightOperand(
fixer,
parentNode,
isStartsWith ? 'start' : 'end',
parentNode.operator.startsWith('!'),
node.optional,
);
},
});
},
// /^bar/.test(foo)
// /bar$/.test(foo)
'CallExpression > MemberExpression.callee[property.name="test"][computed=false]'(
node: TSESTree.MemberExpression,
): void {
const callNode = getParent(node) as TSESTree.CallExpression;
const parsed =
callNode.arguments.length === 1 ? parseRegExp(node.object) : null;
if (parsed == null) {
return;
}
const { isStartsWith, text } = parsed;
const messageId = isStartsWith ? 'preferStartsWith' : 'preferEndsWith';
const methodName = isStartsWith ? 'startsWith' : 'endsWith';
context.report({
node: callNode,
messageId,
*fix(fixer) {
const argNode = callNode.arguments[0];
const needsParen =
argNode.type !== AST_NODE_TYPES.Literal &&
argNode.type !== AST_NODE_TYPES.TemplateLiteral &&
argNode.type !== AST_NODE_TYPES.Identifier &&
argNode.type !== AST_NODE_TYPES.MemberExpression &&
argNode.type !== AST_NODE_TYPES.CallExpression;
yield fixer.removeRange([callNode.range[0], argNode.range[0]]);
if (needsParen) {
yield fixer.insertTextBefore(argNode, '(');
yield fixer.insertTextAfter(argNode, ')');
}
yield fixer.insertTextAfter(
argNode,
`${node.optional ? '?.' : '.'}${methodName}(${JSON.stringify(
text,
)}`,
);
},
});
},
};
},
});