Skip to content

Improve regexp/no-invalid-regexp rule to check for unknown pattern flags. #583

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Sep 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/warm-ladybugs-wonder.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"eslint-plugin-regexp": minor
---

Improve `regexp/no-invalid-regexp` rule to check for unknown pattern flags.
33 changes: 31 additions & 2 deletions lib/rules/no-invalid-regexp.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { RegExpContextForInvalid } from "../utils"
import type { RegExpContextForInvalid, RegExpContextForUnknown } from "../utils"
import { createRule, defineRegexpVisitor } from "../utils"

/** Returns the position of the error */
Expand All @@ -22,6 +22,8 @@ export default createRule("no-invalid-regexp", {
schema: [],
messages: {
error: "{{message}}",
duplicateFlag: "Duplicate {{flag}} flag.",
uvFlag: "Regex 'u' and 'v' flags cannot be used together.",
},
type: "problem",
},
Expand Down Expand Up @@ -56,6 +58,33 @@ export default createRule("no-invalid-regexp", {
})
}

return defineRegexpVisitor(context, { visitInvalid })
/** Checks for the combination of `u` and `v` flags */
function visitUnknown(regexpContext: RegExpContextForUnknown): void {
const { node, flags, flagsString, getFlagsLocation } = regexpContext

const flagSet = new Set<string>()
for (const flag of flagsString ?? "") {
if (flagSet.has(flag)) {
context.report({
node,
loc: getFlagsLocation(),
messageId: "duplicateFlag",
data: { flag },
})
return
}
flagSet.add(flag)
}

if (flags.unicode && flags.unicodeSets) {
context.report({
node,
loc: getFlagsLocation(),
messageId: "uvFlag",
})
}
}

return defineRegexpVisitor(context, { visitInvalid, visitUnknown })
},
})
19 changes: 19 additions & 0 deletions tests/lib/rules/no-invalid-regexp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,5 +44,24 @@ tester.run("no-invalid-regexp", rule as any, {
},
],
},

{
code: "new RegExp(pattern, 'uu');",
errors: [
{
message: "Duplicate u flag.",
column: 22,
},
],
},
{
code: "new RegExp(pattern, 'uv');",
errors: [
{
message: "Regex 'u' and 'v' flags cannot be used together.",
column: 22,
},
],
},
],
})