Skip to content
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/quick-ties-bake.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"eslint-plugin-regexp": patch
---

fix: autofix for incorrect no-escaping in `regexp/no-useless-string-literal`
41 changes: 32 additions & 9 deletions lib/rules/no-useless-string-literal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,11 @@ export default createRule("no-useless-string-literal", {
.join("|")
if (!alternativesText.length) {
const escape =
isNeedEscapedInCharacterClass(
isNeedEscapeForAdjacentPreviousCharacter(
csdNode,
saNode,
) ||
isNeedEscapeForAdjacentNextCharacter(
csdNode,
saNode,
)
Expand All @@ -60,12 +64,13 @@ export default createRule("no-useless-string-literal", {
saNode.raw === "^" ? "\\" : ""
return String.raw`[${escape}${saNode.raw}\q{${alternativesText}}]`
}
const escape = isNeedEscapedInCharacterClass(
csdNode,
saNode,
)
? "\\"
: ""
const escape =
isNeedEscapeForAdjacentPreviousCharacter(
csdNode,
saNode,
)
? "\\"
: ""
return String.raw`${escape}${saNode.raw}\q{${alternativesText}}`
}),
})
Expand All @@ -74,9 +79,10 @@ export default createRule("no-useless-string-literal", {
}

/**
* Checks whether an escape is required if the given character when placed before a \q{...}
* Checks whether the given character requires escaping
* when adjacent to the previous character.
*/
function isNeedEscapedInCharacterClass(
function isNeedEscapeForAdjacentPreviousCharacter(
disjunction: ClassStringDisjunction,
character: StringAlternative,
) {
Expand All @@ -97,6 +103,23 @@ export default createRule("no-useless-string-literal", {
disjunction.parent.start === disjunction.start - 1
)
}

/**
* Checks whether the given character requires escaping
* when adjacent to the next character.
*/
function isNeedEscapeForAdjacentNextCharacter(
disjunction: ClassStringDisjunction,
character: StringAlternative,
) {
const char = character.raw
// Avoid [\q{&}&&A] => [&&&A]
return (
RESERVED_DOUBLE_PUNCTUATOR_CHARS.has(char) &&
// The next character is the same
pattern[disjunction.end] === char
)
}
}

return defineRegexpVisitor(context, {
Expand Down
5 changes: 5 additions & 0 deletions tests/lib/rules/no-useless-string-literal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,11 @@ tester.run("no-useless-string-literal", rule as any, {
output: String.raw`/[A&&\&]/v`,
errors: ["Unexpected string disjunction of single character."],
},
{
code: String.raw`/[\q{&}&&A]/v`,
output: String.raw`/[\&&&A]/v`,
errors: ["Unexpected string disjunction of single character."],
},
{
code: String.raw`/[A&&\q{^|ab}]/v`,
output: String.raw`/[A&&[\^\q{ab}]]/v`,
Expand Down