|
| 1 | +import type { RegExpVisitor } from "@eslint-community/regexpp/visitor" |
| 2 | +import type { RegExpContext } from "../utils" |
| 3 | +import { createRule, defineRegexpVisitor } from "../utils" |
| 4 | +import type { StringAlternative } from "@eslint-community/regexpp/ast" |
| 5 | + |
| 6 | +const segmenter = new Intl.Segmenter() |
| 7 | + |
| 8 | +export default createRule("grapheme-string-literal", { |
| 9 | + meta: { |
| 10 | + docs: { |
| 11 | + description: "enforce single grapheme in string literal", |
| 12 | + category: "Stylistic Issues", |
| 13 | + recommended: false, |
| 14 | + }, |
| 15 | + schema: [], |
| 16 | + messages: { |
| 17 | + onlySingleCharacters: |
| 18 | + "Only single characters and graphemes are allowed inside character classes. Use regular alternatives (e.g. `{{alternatives}}`) for strings instead.", |
| 19 | + }, |
| 20 | + type: "suggestion", |
| 21 | + }, |
| 22 | + create(context) { |
| 23 | + function createVisitor( |
| 24 | + regexpContext: RegExpContext, |
| 25 | + ): RegExpVisitor.Handlers { |
| 26 | + const { node, getRegexpLocation } = regexpContext |
| 27 | + |
| 28 | + function isMultipleGraphemes(saNode: StringAlternative) { |
| 29 | + if (saNode.elements.length <= 1) return false |
| 30 | + const string = String.fromCodePoint( |
| 31 | + ...saNode.elements.map((element) => element.value), |
| 32 | + ) |
| 33 | + |
| 34 | + const segments = [...segmenter.segment(string)] |
| 35 | + return segments.length > 1 |
| 36 | + } |
| 37 | + |
| 38 | + function buildAlternativeExample(saNode: StringAlternative) { |
| 39 | + const alternativeRaws = saNode.parent.alternatives |
| 40 | + .filter(isMultipleGraphemes) |
| 41 | + .map((alt) => alt.raw) |
| 42 | + return `(?:${alternativeRaws.join("|")}|[...])` |
| 43 | + } |
| 44 | + |
| 45 | + return { |
| 46 | + onStringAlternativeEnter(saNode) { |
| 47 | + if (!isMultipleGraphemes(saNode)) return |
| 48 | + |
| 49 | + context.report({ |
| 50 | + node, |
| 51 | + loc: getRegexpLocation(saNode), |
| 52 | + messageId: "onlySingleCharacters", |
| 53 | + data: { |
| 54 | + alternatives: buildAlternativeExample(saNode), |
| 55 | + }, |
| 56 | + }) |
| 57 | + }, |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + return defineRegexpVisitor(context, { |
| 62 | + createVisitor, |
| 63 | + }) |
| 64 | + }, |
| 65 | +}) |
0 commit comments