-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathno-useless-backreference.ts
198 lines (179 loc) · 6.4 KB
/
no-useless-backreference.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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
import type {
Node as RegExpNode,
Backreference,
Alternative,
CapturingGroup,
} from "@eslint-community/regexpp/ast"
import type { RegExpVisitor } from "@eslint-community/regexpp/visitor"
import type { ReadonlyFlags } from "regexp-ast-analysis"
import {
getClosestAncestor,
getMatchingDirection,
isZeroLength,
} from "regexp-ast-analysis"
import type { RegExpContext } from "../utils"
import { createRule, defineRegexpVisitor } from "../utils"
import { mention } from "../utils/mention"
type MessageId =
| "nested"
| "disjunctive"
| "intoNegativeLookaround"
| "forward"
| "backward"
| "empty"
/**
* Returns whether the list of ancestors from `from` to `to` contains a negated
* lookaround.
*/
function hasNegatedLookaroundInBetween(
from: CapturingGroup,
to: Alternative,
): boolean {
for (let p: RegExpNode | null = from.parent; p && p !== to; p = p.parent) {
if (
p.type === "Assertion" &&
(p.kind === "lookahead" || p.kind === "lookbehind") &&
p.negate
) {
return true
}
}
return false
}
/**
* Returns the problem information specifying the reason why the backreference is
* useless.
*/
function getUselessProblem(
backRef: Backreference,
flags: ReadonlyFlags,
): { messageId: MessageId; group: CapturingGroup; otherGroups: string } | null {
const groups = [backRef.resolved].flat()
const problems: { messageId: MessageId; group: CapturingGroup }[] = []
for (const group of groups) {
const messageId = getUselessMessageId(backRef, group, flags)
if (!messageId) {
return null
}
problems.push({ messageId, group })
}
if (problems.length === 0) {
return null
}
let problemsToReport
// Gets problems that appear in the same disjunction.
const problemsInSameDisjunction = problems.filter(
(problem) => problem.messageId !== "disjunctive",
)
if (problemsInSameDisjunction.length) {
// Only report problems that appear in the same disjunction.
problemsToReport = problemsInSameDisjunction
} else {
// If all groups appear in different disjunctions, report it.
problemsToReport = problems
}
const [{ messageId, group }, ...other] = problemsToReport
let otherGroups = ""
if (other.length === 1) {
otherGroups = " and another group"
} else if (other.length > 1) {
otherGroups = ` and other ${other.length} groups`
}
return {
messageId,
group,
otherGroups,
}
}
/**
* Returns the message id specifying the reason why the backreference is
* useless.
*/
function getUselessMessageId(
backRef: Backreference,
group: CapturingGroup,
flags: ReadonlyFlags,
): MessageId | null {
const closestAncestor = getClosestAncestor(backRef, group)
if (closestAncestor === group) {
return "nested"
} else if (closestAncestor.type !== "Alternative") {
// if the closest common ancestor isn't an alternative => they're disjunctive.
return "disjunctive"
}
if (hasNegatedLookaroundInBetween(group, closestAncestor)) {
// if there are negated lookarounds between the group and the closest ancestor
// => group has already failed when backRef starts to match.
// e.g. `/(?!(a))\w\1/`
return "intoNegativeLookaround"
}
const matchingDir = getMatchingDirection(closestAncestor)
if (matchingDir === "ltr" && backRef.end <= group.start) {
// backRef is left, group is right ('forward reference')
// => group hasn't matched yet when backRef starts to match.
return "forward"
} else if (matchingDir === "rtl" && group.end <= backRef.start) {
// the opposite of the previous when the regex is matching backwards
// in a lookbehind context.
return "backward"
}
if (isZeroLength(group, flags)) {
// if the referenced group does not consume characters, then any
// backreference will trivially be replaced with the empty string
return "empty"
}
// not useless
return null
}
export default createRule("no-useless-backreference", {
meta: {
docs: {
description:
"disallow useless backreferences in regular expressions",
category: "Possible Errors",
recommended: true,
},
schema: [],
messages: {
nested: "Backreference {{ bref }} will be ignored. It references group {{ group }}{{ otherGroups }} from within that group.",
forward:
"Backreference {{ bref }} will be ignored. It references group {{ group }}{{ otherGroups }} which appears later in the pattern.",
backward:
"Backreference {{ bref }} will be ignored. It references group {{ group }}{{ otherGroups }} which appears before in the same lookbehind.",
disjunctive:
"Backreference {{ bref }} will be ignored. It references group {{ group }}{{ otherGroups }} which is in another alternative.",
intoNegativeLookaround:
"Backreference {{ bref }} will be ignored. It references group {{ group }}{{ otherGroups }} which is in a negative lookaround.",
empty: "Backreference {{ bref }} will be ignored. It references group {{ group }}{{ otherGroups }} which always captures zero characters.",
},
type: "suggestion", // "problem",
},
create(context) {
function createVisitor({
node,
flags,
getRegexpLocation,
}: RegExpContext): RegExpVisitor.Handlers {
return {
onBackreferenceEnter(backRef) {
const problem = getUselessProblem(backRef, flags)
if (problem) {
context.report({
node,
loc: getRegexpLocation(backRef),
messageId: problem.messageId,
data: {
bref: mention(backRef),
group: mention(problem.group),
otherGroups: problem.otherGroups,
},
})
}
},
}
}
return defineRegexpVisitor(context, {
createVisitor,
})
},
})