Skip to content
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

prefer-w: Add support for v flag #578

Merged
merged 4 commits into from
Sep 14, 2023
Merged
Show file tree
Hide file tree
Changes from 3 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
13 changes: 6 additions & 7 deletions lib/rules/prefer-w.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import {
CP_DIGIT_NINE,
CP_LOW_LINE,
} from "../utils"
import { Chars, toCharSet } from "regexp-ast-analysis"
import { Chars, toUnicodeSet } from "regexp-ast-analysis"
import { mention } from "../utils/mention"

function isSmallLetterRange(node: CharacterClassElement) {
Expand All @@ -40,7 +40,7 @@ function isDigitRangeOrSet(node: CharacterClassElement) {
(node.type === "CharacterClassRange" &&
node.min.value === CP_DIGIT_ZERO &&
node.max.value === CP_DIGIT_NINE) ||
(node.type === "CharacterSet" && node.kind === "digit")
(node.type === "CharacterSet" && node.kind === "digit" && !node.negate)
)
}

Expand Down Expand Up @@ -73,14 +73,13 @@ export default createRule("prefer-w", {
}: RegExpContext): RegExpVisitor.Handlers {
return {
onCharacterClassEnter(ccNode: CharacterClass) {
// FIXME: TS Error
// @ts-expect-error -- FIXME
const charSet = toCharSet(ccNode, flags)
const charSet = toUnicodeSet(ccNode, flags)

let predefined: string | undefined = undefined
if (charSet.equals(Chars.word(flags))) {
const word = Chars.word(flags)
if (charSet.equals(word)) {
predefined = "\\w"
} else if (charSet.equals(Chars.word(flags).negate())) {
} else if (charSet.equals(word.negate())) {
predefined = "\\W"
}

Expand Down
18 changes: 16 additions & 2 deletions tests/lib/rules/prefer-w.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@ import rule from "../../../lib/rules/prefer-w"

const tester = new RuleTester({
parserOptions: {
ecmaVersion: 2020,
ecmaVersion: "latest",
sourceType: "module",
},
})

tester.run("prefer-w", rule as any, {
valid: ["/\\w/"],
valid: ["/\\w/", "/[\\Da-zA-Z_#]/", "/\\w/v", "/[\\Da-zA-Z_#]/v"],
invalid: [
{
code: "/[0-9a-zA-Z_]/",
Expand All @@ -35,6 +35,20 @@ tester.run("prefer-w", rule as any, {
},
],
},
{
code: "/[\\da-zA-Z_#]/",
output: "/[\\w#]/",
errors: [
"Unexpected character class ranges '[\\da-zA-Z_]'. Use '\\w' instead.",
],
},
{
code: "/[0-9a-z_[\\s&&\\p{ASCII}]]/iv",
output: "/[\\w[\\s&&\\p{ASCII}]]/iv",
errors: [
"Unexpected character class ranges '[0-9a-z_]'. Use '\\w' instead.",
],
},
{
code: "/[0-9a-z_]/i",
output: "/\\w/i",
Expand Down
Loading