-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathno-zero-quantifier.ts
79 lines (73 loc) · 3.08 KB
/
no-zero-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
import type { RegExpVisitor } from "@eslint-community/regexpp/visitor"
import type { Rule } from "eslint"
import { hasSomeDescendant } from "regexp-ast-analysis"
import type { RegExpContext } from "../utils"
import { canUnwrapped, createRule, defineRegexpVisitor } from "../utils"
export default createRule("no-zero-quantifier", {
meta: {
docs: {
description: "disallow quantifiers with a maximum of zero",
category: "Best Practices",
recommended: true,
},
schema: [],
messages: {
unexpected:
"Unexpected zero quantifier. The quantifier and its quantified element can be removed without affecting the pattern.",
withCapturingGroup:
"Unexpected zero quantifier. The quantifier and its quantified element do not affecting the pattern. Try to remove the elements but be careful because it contains at least one capturing group.",
// suggestions
remove: "Remove this zero quantifier.",
},
type: "suggestion", // "problem",
hasSuggestions: true,
},
create(context) {
function createVisitor(
regexpContext: RegExpContext,
): RegExpVisitor.Handlers {
const { node, getRegexpLocation, fixReplaceNode, patternAst } =
regexpContext
return {
onQuantifierEnter(qNode) {
if (qNode.max === 0) {
const containCapturingGroup = hasSomeDescendant(
qNode,
(n) => n.type === "CapturingGroup",
)
if (containCapturingGroup) {
context.report({
node,
loc: getRegexpLocation(qNode),
messageId: "withCapturingGroup",
})
} else {
const suggest: Rule.SuggestionReportDescriptor[] =
[]
if (patternAst.raw === qNode.raw) {
suggest.push({
messageId: "remove",
fix: fixReplaceNode(qNode, "(?:)"),
})
} else if (canUnwrapped(qNode, "")) {
suggest.push({
messageId: "remove",
fix: fixReplaceNode(qNode, ""),
})
}
context.report({
node,
loc: getRegexpLocation(qNode),
messageId: "unexpected",
suggest,
})
}
}
},
}
}
return defineRegexpVisitor(context, {
createVisitor,
})
},
})