-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathno-useless-character-class.ts
313 lines (300 loc) · 13 KB
/
no-useless-character-class.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
import type {
CharacterClass,
CharacterClassElement,
ExpressionCharacterClass,
UnicodeSetsCharacterClass,
} from "@eslint-community/regexpp/ast"
import type { RegExpVisitor } from "@eslint-community/regexpp/visitor"
import type { ObjectOption } from "../types"
import type { RegExpContext } from "../utils"
import { canUnwrapped, createRule, defineRegexpVisitor } from "../utils"
import { RESERVED_DOUBLE_PUNCTUATOR_CHARS } from "../utils/regex-syntax"
const ESCAPES_OUTSIDE_CHARACTER_CLASS = new Set("$()*+./?[{|")
const ESCAPES_OUTSIDE_CHARACTER_CLASS_WITH_U = new Set([
...ESCAPES_OUTSIDE_CHARACTER_CLASS,
"}",
])
export default createRule("no-useless-character-class", {
meta: {
docs: {
description: "disallow character class with one character",
category: "Best Practices",
recommended: true,
},
fixable: "code",
schema: [
{
type: "object",
properties: {
ignores: {
type: "array",
items: {
type: "string",
minLength: 1,
},
uniqueItems: true,
},
},
additionalProperties: false,
},
],
messages: {
unexpectedCharacterClassWith:
"Unexpected character class with one {{type}}. Can remove brackets{{additional}}.",
unexpectedUnnecessaryNestingCharacterClass:
"Unexpected unnecessary nesting character class. Can remove brackets.",
},
type: "suggestion", // "problem",
},
create(context) {
const ignores: string[] = (context.options[0] as ObjectOption)
?.ignores ?? ["="]
function createVisitor({
node,
pattern,
flags,
fixReplaceNode,
getRegexpLocation,
}: RegExpContext): RegExpVisitor.Handlers {
const characterClassStack: (
| CharacterClass
| ExpressionCharacterClass
)[] = []
return {
onExpressionCharacterClassEnter(eccNode) {
characterClassStack.push(eccNode)
},
onExpressionCharacterClassLeave() {
characterClassStack.pop()
},
onCharacterClassEnter(ccNode) {
characterClassStack.push(ccNode)
},
onCharacterClassLeave(ccNode) {
characterClassStack.pop()
if (ccNode.negate) {
return
}
let messageId: string,
messageData: { type: string; additional?: string }
const unwrapped: string[] = ccNode.elements.map(
(_e, index) => {
const element = ccNode.elements[index]
return (
(index === 0
? getEscapedFirstRawIfNeeded(element)
: null) ??
(index === ccNode.elements.length - 1
? getEscapedLastRawIfNeeded(element)
: null) ??
element.raw
)
},
)
if (
ccNode.elements.length !== 1 &&
ccNode.parent.type === "CharacterClass"
) {
messageId = "unexpectedUnnecessaryNestingCharacterClass"
messageData = {
type: "unnecessary nesting character class",
}
if (!ccNode.elements.length) {
// empty character class
const nextElement =
ccNode.parent.elements[
ccNode.parent.elements.indexOf(
ccNode as UnicodeSetsCharacterClass,
) + 1
]
if (
nextElement &&
isNeedEscapedForFirstElement(nextElement)
) {
unwrapped.push("\\") // Add a backslash to escape the next character.
}
}
} else {
if (ccNode.elements.length !== 1) {
return
}
const element = ccNode.elements[0]
if (
ignores.length > 0 &&
ignores.includes(element.raw)
) {
return
}
if (element.type === "Character") {
if (element.raw === "\\b") {
// Backspace escape
return
}
if (
/^\\\d+$/u.test(element.raw) &&
!element.raw.startsWith("\\0")
) {
// Avoid back reference
return
}
if (
ignores.length > 0 &&
ignores.includes(
String.fromCodePoint(element.value),
)
) {
return
}
if (!canUnwrapped(ccNode, element.raw)) {
return
}
messageData = { type: "character" }
} else if (element.type === "CharacterClassRange") {
if (element.min.value !== element.max.value) {
return
}
messageData = {
type: "character class range",
additional: " and range",
}
unwrapped[0] =
getEscapedFirstRawIfNeeded(element.min) ??
getEscapedLastRawIfNeeded(element.min) ??
element.min.raw
} else if (element.type === "ClassStringDisjunction") {
if (!characterClassStack.length) {
// Only nesting character class
return
}
messageData = { type: "string literal" }
} else if (element.type === "CharacterSet") {
messageData = { type: "character class escape" }
} else if (
element.type === "CharacterClass" ||
element.type === "ExpressionCharacterClass"
) {
messageData = { type: "character class" }
} else {
return
}
messageId = "unexpectedCharacterClassWith"
}
context.report({
node,
loc: getRegexpLocation(ccNode),
messageId,
data: {
type: messageData.type,
additional: messageData.additional || "",
},
fix: fixReplaceNode(ccNode, unwrapped.join("")),
})
/**
* Checks whether an escape is required if the given element is placed first
* after character class replacement.
*/
function isNeedEscapedForFirstElement(
element: CharacterClassElement,
) {
const char =
element.type === "Character"
? element.raw
: element.type === "CharacterClassRange"
? element.min.raw
: null
if (char == null) {
return false
}
if (characterClassStack.length) {
// Nesting character class
// Avoid [A&&[&]] => [A&&&]
if (
RESERVED_DOUBLE_PUNCTUATOR_CHARS.has(char) &&
// The previous character is the same
pattern[ccNode.start - 1] === char
) {
return true
}
// Avoid [[]^] => [^]
return (
char === "^" &&
ccNode.parent.type === "CharacterClass" &&
ccNode.parent.elements[0] === ccNode
)
}
// Flat character class
return (
flags.unicode
? ESCAPES_OUTSIDE_CHARACTER_CLASS_WITH_U
: ESCAPES_OUTSIDE_CHARACTER_CLASS
).has(char)
}
/**
* Checks whether an escape is required if the given element is placed last
* after character class replacement.
*/
function needEscapedForLastElement(
element: CharacterClassElement,
) {
const char =
element.type === "Character"
? element.raw
: element.type === "CharacterClassRange"
? element.max.raw
: null
if (char == null) {
return false
}
if (characterClassStack.length) {
// Nesting character class
// Avoid [A[&]&B] => [A&&B]
return (
RESERVED_DOUBLE_PUNCTUATOR_CHARS.has(char) &&
// The next character is the same
pattern[ccNode.end] === char
)
}
return false
}
/**
* Returns the escaped raw text, if the given first element requires escaping.
* Otherwise, returns null.
*/
function getEscapedFirstRawIfNeeded(
firstElement: CharacterClassElement,
) {
if (isNeedEscapedForFirstElement(firstElement)) {
return `\\${firstElement.raw}`
}
return null
}
/**
* Returns the escaped raw text, if the given last element requires escaping.
* Otherwise, returns null.
*/
function getEscapedLastRawIfNeeded(
lastElement: CharacterClassElement,
) {
if (needEscapedForLastElement(lastElement)) {
const lastRaw =
lastElement.type === "Character"
? lastElement.raw
: lastElement.type === "CharacterClassRange"
? lastElement.max.raw
: "" // never
const prefix = lastElement.raw.slice(
0,
-lastRaw.length,
)
return `${prefix}\\${lastRaw}`
}
return null
}
},
}
}
return defineRegexpVisitor(context, {
createVisitor,
})
},
})