-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathno-misleading-unicode-character.ts
333 lines (292 loc) · 10.4 KB
/
no-misleading-unicode-character.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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
import type { RegExpVisitor } from "@eslint-community/regexpp/visitor"
import type { RegExpContext } from "../utils"
import { isEscapeSequence, createRule, defineRegexpVisitor } from "../utils"
import type { ReadonlyFlags } from "regexp-ast-analysis"
import { mention, mentionChar } from "../utils/mention"
import type {
CharacterClass,
CharacterClassElement,
Quantifier,
} from "@eslint-community/regexpp/ast"
import type { PatternRange } from "../utils/ast-utils/pattern-source"
import type { Rule } from "eslint"
const segmenter = new Intl.Segmenter()
/** Returns whether the given string starts with a valid surrogate pair. */
function startsWithSurrogate(s: string): boolean {
if (s.length < 2) {
return false
}
const h = s.charCodeAt(0)
const l = s.charCodeAt(1)
return h >= 0xd800 && h <= 0xdbff && l >= 0xdc00 && l <= 0xdfff
}
type Problem = "Multi" | "Surrogate"
/**
* Returns the problem (if any) with the given grapheme.
*/
function getProblem(grapheme: string, flags: ReadonlyFlags): Problem | null {
if (
grapheme.length > 2 ||
(grapheme.length === 2 && !startsWithSurrogate(grapheme))
) {
return "Multi"
} else if (
!flags.unicode &&
!flags.unicodeSets &&
startsWithSurrogate(grapheme)
) {
return "Surrogate"
}
return null
}
/** Returns the last grapheme of the quantified element. */
function getGraphemeBeforeQuant(quant: Quantifier): string {
const alt = quant.parent
// find the start index of the first character left of
// this quantifier
let start = quant.start
for (let i = alt.elements.indexOf(quant) - 1; i >= 0; i--) {
const e = alt.elements[i]
if (e.type === "Character" && !isEscapeSequence(e.raw)) {
start = e.start
} else {
break
}
}
const before = alt.raw.slice(
start - alt.start,
quant.element.end - alt.start,
)
const segments = [...segmenter.segment(before)]
const segment = segments[segments.length - 1]
return segment.segment
}
interface GraphemeProblem {
readonly grapheme: string
readonly problem: Problem
readonly start: number
readonly end: number
/** A sorted list of all unique elements that overlap with this grapheme */
readonly elements: CharacterClassElement[]
}
/** Returns all grapheme problem in the given character class. */
function getGraphemeProblems(
cc: CharacterClass,
flags: ReadonlyFlags,
): GraphemeProblem[] {
const offset = cc.negate ? 2 : 1
const ignoreElements = cc.elements.filter(
(element) =>
element.type === "CharacterClass" || // Nesting CharacterClass
element.type === "ExpressionCharacterClass" || // Nesting ExpressionCharacterClass
element.type === "ClassStringDisjunction",
)
const problems: GraphemeProblem[] = []
for (const { segment, index } of segmenter.segment(
cc.raw.slice(offset, -1),
)) {
const problem = getProblem(segment, flags)
if (problem !== null) {
const start = offset + index + cc.start
const end = start + segment.length
if (
ignoreElements.some(
(ignore) => ignore.start <= start && end <= ignore.end,
)
) {
continue
}
problems.push({
grapheme: segment,
problem,
start,
end,
elements: cc.elements.filter(
(e) => e.start < end && e.end > start,
),
})
}
}
return problems
}
/** Returns a fix for the given problems (if possible). */
function getGraphemeProblemsFix(
problems: readonly GraphemeProblem[],
cc: CharacterClass,
flags: ReadonlyFlags,
): string | null {
if (cc.negate) {
// we can't fix a negated character class
return null
}
if (
!problems.every(
(p) =>
p.start === p.elements[0].start &&
p.end === p.elements[p.elements.length - 1].end,
)
) {
// the graphemes don't line up with character class elements
return null
}
// The prefix of graphemes
const prefixGraphemes = problems.map((p) => p.grapheme)
// The rest of the character class
let ccRaw = cc.raw
for (let i = problems.length - 1; i >= 0; i--) {
const { start, end } = problems[i]
ccRaw = ccRaw.slice(0, start - cc.start) + ccRaw.slice(end - cc.start)
}
if (flags.unicodeSets) {
const prefix = prefixGraphemes.join("|")
return `[\\q{${prefix}}${ccRaw.slice(1, -1)}]`
}
if (ccRaw.startsWith("[^")) {
ccRaw = `[\\${ccRaw.slice(1)}`
}
const prefix = prefixGraphemes.sort((a, b) => b.length - a.length).join("|")
let fix = prefix
let singleAlternative = problems.length === 1
if (ccRaw !== "[]") {
fix += `|${ccRaw}`
singleAlternative = false
}
if (singleAlternative && cc.parent.type === "Alternative") {
return fix
}
if (cc.parent.type === "Alternative" && cc.parent.elements.length === 1) {
// The character class is the only
return fix
}
return `(?:${fix})`
}
export default createRule("no-misleading-unicode-character", {
meta: {
docs: {
description:
"disallow multi-code-point characters in character classes and quantifiers",
category: "Possible Errors",
recommended: true,
},
schema: [
{
type: "object",
properties: {
fixable: { type: "boolean" },
},
additionalProperties: false,
},
],
fixable: "code",
hasSuggestions: true,
messages: {
characterClass:
"The character(s) {{ graphemes }} are all represented using multiple {{ unit }}.{{ uFlag }}",
quantifierMulti:
"The character {{ grapheme }} is represented using multiple Unicode code points. The quantifier only applies to the last code point {{ last }} and not to the whole character.",
quantifierSurrogate:
"The character {{ grapheme }} is represented using a surrogate pair. The quantifier only applies to the tailing surrogate {{ last }} and not to the whole character.",
// suggestions
fixCharacterClass:
"Move the character(s) {{ graphemes }} outside the character class.",
fixQuantifier: "Wrap a group around {{ grapheme }}.",
},
type: "problem",
},
create(context) {
const fixable = context.options[0]?.fixable ?? false
function makeFix(
fix: Rule.ReportFixer,
messageId: string,
data?: Record<string, string>,
): Partial<Rule.ReportDescriptorOptions> {
if (fixable) {
return { fix }
}
return {
suggest: [{ messageId, data, fix }],
}
}
function createVisitor(
regexpContext: RegExpContext,
): RegExpVisitor.Handlers {
const {
node,
patternSource,
flags,
getRegexpLocation,
fixReplaceNode,
} = regexpContext
return {
onCharacterClassEnter(ccNode) {
const problems = getGraphemeProblems(ccNode, flags)
if (problems.length === 0) {
return
}
const range: PatternRange = {
start: problems[0].start,
end: problems[problems.length - 1].end,
}
const fix = getGraphemeProblemsFix(problems, ccNode, flags)
const graphemes = problems
.map((p) => mention(p.grapheme))
.join(", ")
const uFlag = problems.every(
(p) => p.problem === "Surrogate",
)
context.report({
node,
loc: getRegexpLocation(range),
messageId: "characterClass",
data: {
graphemes,
unit: flags.unicode ? "code points" : "char codes",
uFlag: uFlag ? " Use the `u` flag." : "",
},
...makeFix(
fixReplaceNode(ccNode, () => fix),
"fixCharacterClass",
{ graphemes },
),
})
},
onQuantifierEnter(qNode) {
if (qNode.element.type !== "Character") {
return
}
const grapheme = getGraphemeBeforeQuant(qNode)
const problem = getProblem(grapheme, flags)
if (problem === null) {
return
}
context.report({
node,
loc: getRegexpLocation(qNode),
messageId: `quantifier${problem}`,
data: {
grapheme: mention(grapheme),
last: mentionChar(qNode.element),
},
...makeFix(
(fixer) => {
const range = patternSource.getReplaceRange({
start: qNode.element.end - grapheme.length,
end: qNode.element.end,
})
if (!range) {
return null
}
return range.replace(fixer, `(?:${grapheme})`)
},
"fixQuantifier",
{ grapheme: mention(grapheme) },
),
})
},
}
}
return defineRegexpVisitor(context, {
createVisitor,
})
},
})