-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathno-obscure-range.ts
99 lines (92 loc) · 3.1 KB
/
no-obscure-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
88
89
90
91
92
93
94
95
96
97
98
99
import type { RegExpVisitor } from "@eslint-community/regexpp/visitor"
import type { ObjectOption } from "../types"
import type { RegExpContext } from "../utils"
import { createRule, defineRegexpVisitor } from "../utils"
import {
getAllowedCharRanges,
inRange,
getAllowedCharValueSchema,
} from "../utils/char-ranges"
import { mentionChar } from "../utils/mention"
import {
isControlEscape,
isEscapeSequence,
isOctalEscape,
isHexLikeEscape,
} from "../utils/regex-syntax"
export default createRule("no-obscure-range", {
meta: {
docs: {
description: "disallow obscure character ranges",
category: "Best Practices",
recommended: true,
},
schema: [
{
type: "object",
properties: {
allowed: getAllowedCharValueSchema(),
},
additionalProperties: false,
},
],
messages: {
unexpected:
"Unexpected obscure character range. The characters of {{range}} are not obvious.",
},
type: "suggestion", // "problem",
},
create(context) {
const allowedRanges = getAllowedCharRanges(
(context.options[0] as ObjectOption)?.allowed,
context,
)
function createVisitor({
node,
getRegexpLocation,
}: RegExpContext): RegExpVisitor.Handlers {
return {
onCharacterClassRangeEnter(rNode) {
const { min, max } = rNode
if (min.value === max.value) {
// we don't deal with that
return
}
if (isControlEscape(min.raw) && isControlEscape(max.raw)) {
// both min and max are control escapes
return
}
if (isOctalEscape(min.raw) && isOctalEscape(max.raw)) {
// both min and max are either octal
return
}
if (
(isHexLikeEscape(min.raw) || min.value === 0) &&
isHexLikeEscape(max.raw)
) {
// both min and max are hexadecimal (with a small exception for \0)
return
}
if (
!isEscapeSequence(min.raw) &&
!isEscapeSequence(max.raw) &&
inRange(allowedRanges, min.value, max.value)
) {
return
}
context.report({
node,
loc: getRegexpLocation(rNode),
messageId: "unexpected",
data: {
range: mentionChar(rNode),
},
})
},
}
}
return defineRegexpVisitor(context, {
createVisitor,
})
},
})