Skip to content

Commit fed5588

Browse files
authored
Fix false negatives for split in regexp/no-unused-capturing-group rule (#75)
1 parent 5eae9de commit fed5588

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

lib/rules/no-unused-capturing-group.ts

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,10 @@ class CapturingData {
8989
this.unusedNames.clear()
9090
}
9191

92+
public usedAllUnnamed() {
93+
this.unused.clear()
94+
}
95+
9296
public isAllUsed() {
9397
return !this.unused.size && !this.unusedNames.size
9498
}
@@ -618,6 +622,19 @@ export default createRule("no-unused-capturing-group", {
618622
}
619623
}
620624

625+
/** Verify for String.prototype.split() */
626+
function verifyForSplit(node: KnownCall) {
627+
const capturingData = getCapturingData(node.arguments[0])
628+
if (capturingData == null || capturingData.isAllUsed()) {
629+
return
630+
}
631+
if (!typeTracer.isString(node.callee.object)) {
632+
return
633+
}
634+
capturingData.markAsUsed()
635+
capturingData.usedAllUnnamed()
636+
}
637+
621638
/**
622639
* Create RegExp visitor
623640
* @param node
@@ -654,6 +671,7 @@ export default createRule("no-unused-capturing-group", {
654671
replaceAll: 2,
655672
matchAll: 1,
656673
exec: 1,
674+
split: 1,
657675
})
658676
) {
659677
return
@@ -673,6 +691,8 @@ export default createRule("no-unused-capturing-group", {
673691
verifyForExec(node)
674692
} else if (node.callee.property.name === "matchAll") {
675693
verifyForMatchAll(node)
694+
} else if (node.callee.property.name === "split") {
695+
verifyForSplit(node)
676696
}
677697
},
678698
}

tests/lib/rules/no-unused-capturing-group.ts

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,14 @@ tester.run("no-unused-capturing-group", rule as any, {
7979
'2000-12-31 2000-12-31'.replace(reg, '$<y>/$<m>');
8080
'2000-12-31 2000-12-31'.replace(reg, '$<m>/$<d>');
8181
`,
82+
String.raw`
83+
const reg = /,/;
84+
'a,b,c'.split(reg)
85+
`,
86+
String.raw`
87+
const reg = /(,)/;
88+
'a,b,c'.split(reg)
89+
`,
8290
],
8391
invalid: [
8492
{
@@ -422,10 +430,18 @@ tester.run("no-unused-capturing-group", rule as any, {
422430
var m = groups.m // "12"
423431
// var d = matches[3] // "31"
424432
}
425-
426433
`,
427434
errors: ["Capturing group is defined but never used."],
428435
},
436+
{
437+
code: String.raw`
438+
const reg = /(?<comma>,)/;
439+
'a,b,c'.split(reg)
440+
`,
441+
errors: [
442+
"'comma' is defined for capturing group, but it name is never used.",
443+
],
444+
},
429445
{
430446
code: String.raw`var isDate = /(\d{4})-(\d{2})-(\d{2})/.test(foo)`,
431447
errors: [

0 commit comments

Comments
 (0)