Skip to content

Commit 1fcf17f

Browse files
authored
Improve regexp/no-invalid-regexp rule to check for unknown pattern flags. (#583)
1 parent c157b8b commit 1fcf17f

File tree

3 files changed

+55
-2
lines changed

3 files changed

+55
-2
lines changed

.changeset/warm-ladybugs-wonder.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"eslint-plugin-regexp": minor
3+
---
4+
5+
Improve `regexp/no-invalid-regexp` rule to check for unknown pattern flags.

lib/rules/no-invalid-regexp.ts

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import type { RegExpContextForInvalid } from "../utils"
1+
import type { RegExpContextForInvalid, RegExpContextForUnknown } from "../utils"
22
import { createRule, defineRegexpVisitor } from "../utils"
33

44
/** Returns the position of the error */
@@ -22,6 +22,8 @@ export default createRule("no-invalid-regexp", {
2222
schema: [],
2323
messages: {
2424
error: "{{message}}",
25+
duplicateFlag: "Duplicate {{flag}} flag.",
26+
uvFlag: "Regex 'u' and 'v' flags cannot be used together.",
2527
},
2628
type: "problem",
2729
},
@@ -56,6 +58,33 @@ export default createRule("no-invalid-regexp", {
5658
})
5759
}
5860

59-
return defineRegexpVisitor(context, { visitInvalid })
61+
/** Checks for the combination of `u` and `v` flags */
62+
function visitUnknown(regexpContext: RegExpContextForUnknown): void {
63+
const { node, flags, flagsString, getFlagsLocation } = regexpContext
64+
65+
const flagSet = new Set<string>()
66+
for (const flag of flagsString ?? "") {
67+
if (flagSet.has(flag)) {
68+
context.report({
69+
node,
70+
loc: getFlagsLocation(),
71+
messageId: "duplicateFlag",
72+
data: { flag },
73+
})
74+
return
75+
}
76+
flagSet.add(flag)
77+
}
78+
79+
if (flags.unicode && flags.unicodeSets) {
80+
context.report({
81+
node,
82+
loc: getFlagsLocation(),
83+
messageId: "uvFlag",
84+
})
85+
}
86+
}
87+
88+
return defineRegexpVisitor(context, { visitInvalid, visitUnknown })
6089
},
6190
})

tests/lib/rules/no-invalid-regexp.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,5 +44,24 @@ tester.run("no-invalid-regexp", rule as any, {
4444
},
4545
],
4646
},
47+
48+
{
49+
code: "new RegExp(pattern, 'uu');",
50+
errors: [
51+
{
52+
message: "Duplicate u flag.",
53+
column: 22,
54+
},
55+
],
56+
},
57+
{
58+
code: "new RegExp(pattern, 'uv');",
59+
errors: [
60+
{
61+
message: "Regex 'u' and 'v' flags cannot be used together.",
62+
column: 22,
63+
},
64+
],
65+
},
4766
],
4867
})

0 commit comments

Comments
 (0)