-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathno-extra-lookaround-assertions.ts
95 lines (90 loc) · 3.32 KB
/
no-extra-lookaround-assertions.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
import type { LookaroundAssertion } from "@eslint-community/regexpp/ast"
import type { RegExpVisitor } from "@eslint-community/regexpp/visitor"
import type { RegExpContext } from "../utils"
import { createRule, defineRegexpVisitor } from "../utils"
export default createRule("no-extra-lookaround-assertions", {
meta: {
docs: {
description: "disallow unnecessary nested lookaround assertions",
category: "Best Practices",
recommended: true,
},
fixable: "code",
schema: [],
messages: {
canBeInlined:
"This {{kind}} assertion is useless and can be inlined.",
canBeConvertedIntoGroup:
"This {{kind}} assertion is useless and can be converted into a group.",
},
type: "suggestion",
},
create(context) {
function createVisitor(
regexpContext: RegExpContext,
): RegExpVisitor.Handlers {
return {
onAssertionEnter(aNode) {
if (
aNode.kind === "lookahead" ||
aNode.kind === "lookbehind"
) {
verify(regexpContext, aNode)
}
},
}
}
function verify(
regexpContext: RegExpContext,
assertion: LookaroundAssertion,
) {
for (const alternative of assertion.alternatives) {
const nested = alternative.elements.at(
assertion.kind === "lookahead"
? // The last positive lookahead assertion within
// a lookahead assertion is the same without the assertion.
-1
: // The first positive lookbehind assertion within
// a lookbehind assertion is the same without the assertion.
0,
)
if (
nested?.type === "Assertion" &&
nested.kind === assertion.kind &&
!nested.negate
) {
reportLookaroundAssertion(regexpContext, nested)
}
}
}
function reportLookaroundAssertion(
{ node, getRegexpLocation, fixReplaceNode }: RegExpContext,
assertion: LookaroundAssertion,
) {
let messageId, replaceText
if (assertion.alternatives.length === 1) {
messageId = "canBeInlined"
// unwrap `(?=` and `)`, `(?<=` and `)`
replaceText = assertion.alternatives[0].raw
} else {
messageId = "canBeConvertedIntoGroup"
// replace `?=` with `?:`, or `?<=` with `?:`
replaceText = `(?:${assertion.alternatives
.map((alt) => alt.raw)
.join("|")})`
}
context.report({
node,
loc: getRegexpLocation(assertion),
messageId,
data: {
kind: assertion.kind,
},
fix: fixReplaceNode(assertion, replaceText),
})
}
return defineRegexpVisitor(context, {
createVisitor,
})
},
})