Open History to see the last commit
1import { AST_NODE_TYPES } from '@typescript-eslint/utils'
2import { uniqueBy } from './unique-by'
3import type { TSESLint, TSESTree } from '@typescript-eslint/utils'
4β
5export const ASTUtils = {
6 isNodeOfOneOf<T extends AST_NODE_TYPES>(
7 node: TSESTree.Node,
8 types: ReadonlyArray<T>,
9 ): node is TSESTree.Node & { type: T } {
10 return types.includes(node.type as T)
11 },
12 isIdentifier(node: TSESTree.Node): node is TSESTree.Identifier {
13 return node.type === AST_NODE_TYPES.Identifier
14 },
15 isIdentifierWithName(
16 node: TSESTree.Node,
17 name: string,
18 ): node is TSESTree.Identifier {
19 return ASTUtils.isIdentifier(node) && node.name === name
20 },
21 isIdentifierWithOneOfNames<T extends Array<string>>(
22 node: TSESTree.Node,
23 name: T,
24 ): node is TSESTree.Identifier & { name: T[number] } {
25 return ASTUtils.isIdentifier(node) && name.includes(node.name)
26 },
27 isProperty(node: TSESTree.Node): node is TSESTree.Property {
28 return node.type === AST_NODE_TYPES.Property
29 },
30 isObjectExpression(node: TSESTree.Node): node is TSESTree.ObjectExpression {
31 return node.type === AST_NODE_TYPES.ObjectExpression
32 },
33 isPropertyWithIdentifierKey(
34 node: TSESTree.Node,
35 key: string,
36 ): node is TSESTree.Property {
37 return (
38 ASTUtils.isProperty(node) && ASTUtils.isIdentifierWithName(node.key, key)
39 )
40 },
41 findPropertyWithIdentifierKey(
42 properties: Array<TSESTree.ObjectLiteralElement>,
43 key: string,
44 ): TSESTree.Property | undefined {
45 return properties.find((x) =>
46 ASTUtils.isPropertyWithIdentifierKey(x, key),
47 ) as TSESTree.Property | undefined
48 },
49 getNestedIdentifiers(node: TSESTree.Node): Array<TSESTree.Identifier> {
50 const identifiers: Array<TSESTree.Identifier> = []
51β
52 if (ASTUtils.isIdentifier(node)) {
53 identifiers.push(node)
54 }
55β
56 if ('arguments' in node) {
57 node.arguments.forEach((x) => {
58 identifiers.push(...ASTUtils.getNestedIdentifiers(x))
59 })
60 }
61β
62 if ('elements' in node) {
63 node.elements.forEach((x) => {
64 if (x !== null) {
65 identifiers.push(...ASTUtils.getNestedIdentifiers(x))
66 }
67 })
68 }
69β
70 if ('properties' in node) {
71 node.properties.forEach((x) => {
72 identifiers.push(...ASTUtils.getNestedIdentifiers(x))
73 })
74 }
75β
76 if ('expressions' in node) {
77 node.expressions.forEach((x) => {
78 identifiers.push(...ASTUtils.getNestedIdentifiers(x))
79 })
80 }
81β
82 if ('left' in node) {
83 identifiers.push(...ASTUtils.getNestedIdentifiers(node.left))
84 }
85β
86 if ('right' in node) {
87 identifiers.push(...ASTUtils.getNestedIdentifiers(node.right))
88 }
89β
90 if (node.type === AST_NODE_TYPES.Property) {
91 identifiers.push(...ASTUtils.getNestedIdentifiers(node.value))
92 }
93β
94 if (node.type === AST_NODE_TYPES.SpreadElement) {
95 identifiers.push(...ASTUtils.getNestedIdentifiers(node.argument))
96 }
97β
98 if (node.type === AST_NODE_TYPES.MemberExpression) {
99 identifiers.push(...ASTUtils.getNestedIdentifiers(node.object))
100 }
101β
102 if (node.type === AST_NODE_TYPES.UnaryExpression) {
103 identifiers.push(...ASTUtils.getNestedIdentifiers(node.argument))
104 }
105β
106 if (node.type === AST_NODE_TYPES.ChainExpression) {
107 identifiers.push(...ASTUtils.getNestedIdentifiers(node.expression))
108 }
109β
110 if (node.type === AST_NODE_TYPES.TSNonNullExpression) {
111 identifiers.push(...ASTUtils.getNestedIdentifiers(node.expression))
112 }
113β
114 if (node.type === AST_NODE_TYPES.ArrowFunctionExpression) {
115 identifiers.push(...ASTUtils.getNestedIdentifiers(node.body))
116 }
117β
118 if (node.type === AST_NODE_TYPES.FunctionExpression) {
119 identifiers.push(...ASTUtils.getNestedIdentifiers(node.body))
120 }
121β
122 if (node.type === AST_NODE_TYPES.BlockStatement) {
123 identifiers.push(
124 ...node.body.map((body) => ASTUtils.getNestedIdentifiers(body)).flat(),
125 )
126 }
127β
128 if (node.type === AST_NODE_TYPES.ReturnStatement && node.argument) {
129 identifiers.push(...ASTUtils.getNestedIdentifiers(node.argument))
130 }
131β
132 return identifiers
133 },
134 isAncestorIsCallee(identifier: TSESTree.Node) {
135 let previousNode = identifier
136 let currentNode = identifier.parent
137β
138 while (currentNode !== undefined) {
139 if (
140 currentNode.type === AST_NODE_TYPES.CallExpression &&
141 currentNode.callee === previousNode
142 ) {
143 return true
144 }
145β
146 if (currentNode.type !== AST_NODE_TYPES.MemberExpression) {
147 return false
148 }
149β
150 previousNode = currentNode
151 currentNode = currentNode.parent
152 }
153β
154 return false
155 },
156 traverseUpOnly(
157 identifier: TSESTree.Node,
158 allowedNodeTypes: Array<AST_NODE_TYPES>,
159 ): TSESTree.Node {
160 const parent = identifier.parent
161β
162 if (parent !== undefined && allowedNodeTypes.includes(parent.type)) {
163 return ASTUtils.traverseUpOnly(parent, allowedNodeTypes)
164 }
165β
166 return identifier
167 },
168 isDeclaredInNode(params: {
169 functionNode: TSESTree.Node
170 reference: TSESLint.Scope.Reference
171 scopeManager: TSESLint.Scope.ScopeManager
172 }) {
173 const { functionNode, reference, scopeManager } = params
174 const scope = scopeManager.acquire(functionNode)
175β
176 if (scope === null) {
177 return false
178 }
179β
180 return scope.set.has(reference.identifier.name)
181 },
182 getExternalRefs(params: {
183 scopeManager: TSESLint.Scope.ScopeManager
184 sourceCode: Readonly<TSESLint.SourceCode>
185 node: TSESTree.Node
186 }): Array<TSESLint.Scope.Reference> {
187 const { scopeManager, sourceCode, node } = params
188 const scope = scopeManager.acquire(node)
189β
190 if (scope === null) {
191 return []
192 }
193β
194 const references = scope.references
195 .filter((x) => x.isRead() && !scope.set.has(x.identifier.name))
196 .map((x) => {
197 const referenceNode = ASTUtils.traverseUpOnly(x.identifier, [
198 AST_NODE_TYPES.MemberExpression,
199 AST_NODE_TYPES.Identifier,
200 ])
201β
202 return {
203 variable: x,
204 node: referenceNode,
205 text: sourceCode.getText(referenceNode),
206 }
207 })
208β
209 const localRefIds = new Set(
210 [...scope.set.values()].map((x) => sourceCode.getText(x.identifiers[0])),
211 )
212β
213 const externalRefs = references.filter(
214 (x) => x.variable.resolved === null || !localRefIds.has(x.text),
215 )
216β
217 return uniqueBy(externalRefs, (x) => x.text).map((x) => x.variable)
218 },
219 mapKeyNodeToText(
220 node: TSESTree.Node,
221 sourceCode: Readonly<TSESLint.SourceCode>,
222 ) {
223 return sourceCode.getText(
224 ASTUtils.traverseUpOnly(node, [
225 AST_NODE_TYPES.MemberExpression,
226 AST_NODE_TYPES.Identifier,
227 ]),
228 )
229 },
230 isValidReactComponentOrHookName(
231 identifier: TSESTree.Identifier | null | undefined,
232 ) {
233 return (
234 identifier !== null &&
235 identifier !== undefined &&
236 /^(use|[A-Z])/.test(identifier.name)
237 )
238 },
239 getFunctionAncestor(
240 sourceCode: Readonly<TSESLint.SourceCode>,
241 node: TSESTree.Node,
242 ) {
243 for (const ancestor of sourceCode.getAncestors(node)) {
244 if (ancestor.type === AST_NODE_TYPES.FunctionDeclaration) {
245 return ancestor
246 }
247β
248 if (
249 ancestor.parent?.type === AST_NODE_TYPES.VariableDeclarator &&
250 ancestor.parent.id.type === AST_NODE_TYPES.Identifier &&
251 ASTUtils.isNodeOfOneOf(ancestor, [
252 AST_NODE_TYPES.FunctionDeclaration,
253 AST_NODE_TYPES.FunctionExpression,
254 AST_NODE_TYPES.ArrowFunctionExpression,
255 ])
256 ) {
257 return ancestor
258 }
259 }
260β
261 return undefined
262 },
263 getReferencedExpressionByIdentifier(params: {
264 node: TSESTree.Node
265 context: Readonly<TSESLint.RuleContext<string, ReadonlyArray<unknown>>>
266 }) {
267 const { node, context } = params
268β
269 // we need the fallbacks for backwards compat with eslint < 8.37.0
270 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
271 const sourceCode = context.sourceCode ?? context.getSourceCode()
272 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
273 const scope = context.sourceCode.getScope(node)
274 ? sourceCode.getScope(node)
275 : context.getScope()
276β
277 const resolvedNode = scope.references.find((ref) => ref.identifier === node)
278 ?.resolved?.defs[0]?.node
279β
280 if (resolvedNode?.type !== AST_NODE_TYPES.VariableDeclarator) {
281 return null
282 }
283β
284 return resolvedNode.init
285 },
286 getClosestVariableDeclarator(node: TSESTree.Node) {
287 let currentNode: TSESTree.Node | undefined = node
288β
289 while (currentNode.type !== AST_NODE_TYPES.Program) {
290 if (currentNode.type === AST_NODE_TYPES.VariableDeclarator) {
291 return currentNode
292 }
293β
294 currentNode = currentNode.parent
295 }
296β
297 return undefined
298 },
299 getNestedReturnStatements(
300 node: TSESTree.Node,
301 ): Array<TSESTree.ReturnStatement> {
302 const returnStatements: Array<TSESTree.ReturnStatement> = []
303β
304 if (node.type === AST_NODE_TYPES.ReturnStatement) {
305 returnStatements.push(node)
306 }
307β
308 if ('body' in node && node.body !== undefined && node.body !== null) {
309 Array.isArray(node.body)
310 ? node.body.forEach((x) => {
311 returnStatements.push(...ASTUtils.getNestedReturnStatements(x))
312 })
313 : returnStatements.push(
314 ...ASTUtils.getNestedReturnStatements(node.body),
315 )
316 }
317β
318 if ('consequent' in node) {
319 Array.isArray(node.consequent)
320 ? node.consequent.forEach((x) => {
321 returnStatements.push(...ASTUtils.getNestedReturnStatements(x))
322 })
323 : returnStatements.push(
324 ...ASTUtils.getNestedReturnStatements(node.consequent),
325 )
326 }
327β
328 if ('alternate' in node && node.alternate !== null) {
329 Array.isArray(node.alternate)
330 ? node.alternate.forEach((x) => {
331 returnStatements.push(...ASTUtils.getNestedReturnStatements(x))
332 })
333 : returnStatements.push(
334 ...ASTUtils.getNestedReturnStatements(node.alternate),
335 )
336 }
337β
338 if ('cases' in node) {
339 node.cases.forEach((x) => {
340 returnStatements.push(...ASTUtils.getNestedReturnStatements(x))
341 })
342 }
343β
344 if ('block' in node) {
345 returnStatements.push(...ASTUtils.getNestedReturnStatements(node.block))
346 }
347β
348 if ('handler' in node && node.handler !== null) {
349 returnStatements.push(...ASTUtils.getNestedReturnStatements(node.handler))
350 }
351β
352 if ('finalizer' in node && node.finalizer !== null) {
353 returnStatements.push(
354 ...ASTUtils.getNestedReturnStatements(node.finalizer),
355 )
356 }
357β
358 if (
359 'expression' in node &&
360 node.expression !== true &&
361 node.expression !== false
362 ) {
363 returnStatements.push(
364 ...ASTUtils.getNestedReturnStatements(node.expression),
365 )
366 }
367β
368 if ('test' in node && node.test !== null) {
369 returnStatements.push(...ASTUtils.getNestedReturnStatements(node.test))
370 }
371β
372 return returnStatements
373 },
374}