-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathgrapheme-string-literal.ts
65 lines (57 loc) · 2.27 KB
/
grapheme-string-literal.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
import type { RegExpVisitor } from "@eslint-community/regexpp/visitor"
import type { RegExpContext } from "../utils"
import { createRule, defineRegexpVisitor } from "../utils"
import type { StringAlternative } from "@eslint-community/regexpp/ast"
const segmenter = new Intl.Segmenter()
export default createRule("grapheme-string-literal", {
meta: {
docs: {
description: "enforce single grapheme in string literal",
category: "Stylistic Issues",
recommended: false,
},
schema: [],
messages: {
onlySingleCharacters:
"Only single characters and graphemes are allowed inside character classes. Use regular alternatives (e.g. `{{alternatives}}`) for strings instead.",
},
type: "suggestion",
},
create(context) {
function createVisitor(
regexpContext: RegExpContext,
): RegExpVisitor.Handlers {
const { node, getRegexpLocation } = regexpContext
function isMultipleGraphemes(saNode: StringAlternative) {
if (saNode.elements.length <= 1) return false
const string = String.fromCodePoint(
...saNode.elements.map((element) => element.value),
)
const segments = [...segmenter.segment(string)]
return segments.length > 1
}
function buildAlternativeExample(saNode: StringAlternative) {
const alternativeRaws = saNode.parent.alternatives
.filter(isMultipleGraphemes)
.map((alt) => alt.raw)
return `(?:${alternativeRaws.join("|")}|[...])`
}
return {
onStringAlternativeEnter(saNode) {
if (!isMultipleGraphemes(saNode)) return
context.report({
node,
loc: getRegexpLocation(saNode),
messageId: "onlySingleCharacters",
data: {
alternatives: buildAlternativeExample(saNode),
},
})
},
}
}
return defineRegexpVisitor(context, {
createVisitor,
})
},
})