-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathprefer-question-quantifier.ts
111 lines (108 loc) · 4.48 KB
/
prefer-question-quantifier.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
import type { Group, Quantifier } from "@eslint-community/regexpp/ast"
import type { RegExpVisitor } from "@eslint-community/regexpp/visitor"
import type { RegExpContext } from "../utils"
import { createRule, defineRegexpVisitor } from "../utils"
import { mention } from "../utils/mention"
import { getQuantifierOffsets } from "../utils/regexp-ast"
export default createRule("prefer-question-quantifier", {
meta: {
docs: {
description: "enforce using `?` quantifier",
category: "Stylistic Issues",
recommended: true,
},
fixable: "code",
schema: [],
messages: {
unexpected: "Unexpected quantifier '{{expr}}'. Use '?' instead.",
unexpectedGroup:
"Unexpected group {{expr}}. Use '{{instead}}' instead.",
},
type: "suggestion", // "problem",
},
create(context) {
function createVisitor({
node,
getRegexpLocation,
fixReplaceQuant,
fixReplaceNode,
}: RegExpContext): RegExpVisitor.Handlers {
return {
onQuantifierEnter(qNode) {
if (qNode.min === 0 && qNode.max === 1) {
const [startOffset, endOffset] =
getQuantifierOffsets(qNode)
const text = qNode.raw.slice(startOffset, endOffset)
if (text !== "?") {
context.report({
node,
loc: getRegexpLocation(qNode, [
startOffset,
endOffset,
]),
messageId: "unexpected",
data: {
expr: text,
},
fix: fixReplaceQuant(qNode, "?"),
})
}
}
},
onGroupEnter(gNode) {
const lastAlt =
gNode.alternatives[gNode.alternatives.length - 1]
if (!lastAlt.elements.length) {
// last alternative is empty. e.g /(?:a|)/, /(?:a|b|)/
const alternatives = gNode.alternatives.slice(0, -1)
while (alternatives.length > 0) {
if (
!alternatives[alternatives.length - 1].elements
.length
) {
// last alternative is empty.
alternatives.pop()
continue
}
break
}
if (!alternatives.length) {
// all empty
return
}
let reportNode: Group | Quantifier = gNode
const instead = `(?:${alternatives
.map((ne) => ne.raw)
.join("|")})?`
if (gNode.parent.type === "Quantifier") {
if (
gNode.parent.greedy &&
gNode.parent.min === 0 &&
gNode.parent.max === 1
) {
reportNode = gNode.parent
} else {
// It is possible to use group `(?:)` and `?`,
// but we will not report this as it makes the regex more complicated.
return
}
}
context.report({
node,
loc: getRegexpLocation(reportNode),
messageId: "unexpectedGroup",
data: {
expr: mention(reportNode),
instead,
},
fix: fixReplaceNode(reportNode, instead),
})
}
},
}
}
return defineRegexpVisitor(context, {
createVisitor,
})
},
})