-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathno-useless-range.ts
87 lines (82 loc) · 3.35 KB
/
no-useless-range.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import type { RegExpVisitor } from "@eslint-community/regexpp/visitor"
import type { RegExpContext } from "../utils"
import { createRule, defineRegexpVisitor } from "../utils"
export default createRule("no-useless-range", {
meta: {
docs: {
description: "disallow unnecessary character ranges",
category: "Best Practices",
recommended: true,
},
fixable: "code",
schema: [],
messages: {
unexpected:
"Unexpected unnecessary character ranges. The hyphen is unnecessary.",
},
type: "suggestion", // "problem",
},
create(context) {
function createVisitor({
node,
fixReplaceNode,
getRegexpLocation,
}: RegExpContext): RegExpVisitor.Handlers {
return {
onCharacterClassRangeEnter(ccrNode) {
if (
ccrNode.min.value !== ccrNode.max.value &&
ccrNode.min.value + 1 !== ccrNode.max.value
) {
return
}
context.report({
node,
loc: getRegexpLocation(ccrNode),
messageId: "unexpected",
fix: fixReplaceNode(ccrNode, () => {
const parent = ccrNode.parent
const rawBefore = parent.raw.slice(
0,
ccrNode.start - parent.start,
)
const rawAfter = parent.raw.slice(
ccrNode.end - parent.start,
)
if (
/\\(?:x[\dA-Fa-f]?|u[\dA-Fa-f]{0,3})?$/u.test(
rawBefore,
)
) {
// It will not autofix because it is preceded
// by an incomplete escape sequence
return null
}
let text = ccrNode.min.raw
if (ccrNode.min.value < ccrNode.max.value) {
if (ccrNode.max.raw === "-") {
// This "-" might be interpreted as a range
// operator now, so we have to escape it
// e.g. /[,--b]/ -> /[,\-b]/
text += `\\-`
} else {
text += `${ccrNode.max.raw}`
}
}
if (rawAfter.startsWith("-")) {
// the next "-" might be interpreted as a range
// operator now, so we have to escape it
// e.g. /[a-a-z]/ -> /[a\-z]/
text += "\\"
}
return text
}),
})
},
}
}
return defineRegexpVisitor(context, {
createVisitor,
})
},
})