Skip to content

Commit

Permalink
Fix false positives for replacer function with rest arg in `regexp/no…
Browse files Browse the repository at this point in the history
…-unused-capturing-group` rule (#354)
  • Loading branch information
ota-meshi committed Oct 7, 2021
1 parent a227562 commit bc0a29e
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
5 changes: 4 additions & 1 deletion lib/utils/extract-capturing-group-references.ts
Original file line number Diff line number Diff line change
Expand Up @@ -524,7 +524,10 @@ function* iterateForReplacerFunction(
on: "replace" | "replaceAll",
ctx: ExtractCapturingGroupReferencesContext,
): Iterable<CapturingGroupReference> {
if (replacementNode.params.length < 2) {
if (
replacementNode.params.length < 2 &&
!replacementNode.params.some((arg) => arg.type === "RestElement")
) {
yield {
type: "WithoutRef",
node: argument,
Expand Down
19 changes: 19 additions & 0 deletions tests/lib/rules/no-unused-capturing-group.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,21 @@ tester.run("no-unused-capturing-group", rule as any, {
"var replaced = '2000-12-31'.replace(/(?<y>\\d{4})-(?<m>\\d{2})-(?<d>\\d{2})/, (_, y, m, d, o, s, g) => `${g.y}/${g.m}/${g.d}`)",
String.raw`'2000-12-31'.replace(/(?<y>\d{4})-(?<m>\d{2})-(?<d>\d{2})/u, '$1/$2/$3') // "2000/12/31"`,
String.raw`const [,y,m,d] = '2000-12-31'.match(/(?<y>\d{4})-(?<m>\d{2})-(?<d>\d{2})/)`,
// https://github.com/ota-meshi/eslint-plugin-regexp/issues/353
`const string = 'foo:abc,bar:def'.replace(/foo:(?<foo>\\w+),bar:(?<bar>\\w+)/, (...args) => {
const { foo, bar } = args.at(-1);
return \`\${ bar },\${ foo }\`;
});`,
String.raw`
const regexp = /(?<y>\d{4})-(?<m>\d{2})-(?<d>\d{2})/
let match
while(match = regexp.exec(foo)) {
const m = [...match]
}
`,
String.raw`
const matches = [...('2000-12-31 2000-12-31'.matchAll(/(\d{4})-(\d{2})-(\d{2})/g))]
`,
],
invalid: [
{
Expand Down Expand Up @@ -450,5 +465,9 @@ tester.run("no-unused-capturing-group", rule as any, {
},
],
},
{
code: `'str'.replace(/(?<foo>\\w+)/, () => {});`,
errors: ["Capturing group 'foo' is defined but never used."],
},
],
})

0 comments on commit bc0a29e

Please sign in to comment.