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): x is TSESTree.Property =>
46 ASTUtils.isPropertyWithIdentifierKey(x, key),
47 )
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 traverseUpOnly(
135 identifier: TSESTree.Node,
136 allowedNodeTypes: Array<AST_NODE_TYPES>,
137 ): TSESTree.Node {
138 const parent = identifier.parent
139β
140 if (parent !== undefined && allowedNodeTypes.includes(parent.type)) {
141 return ASTUtils.traverseUpOnly(parent, allowedNodeTypes)
142 }
143β
144 return identifier
145 },
146 traverseUpMemberExpression(node: TSESTree.Node): TSESTree.Node {
147 const parent = node.parent
148β
149 if (
150 parent !== undefined &&
151 ((parent.type === AST_NODE_TYPES.MemberExpression &&
152 parent.object === node) ||
153 parent.type === AST_NODE_TYPES.ChainExpression ||
154 parent.type === AST_NODE_TYPES.TSNonNullExpression)
155 ) {
156 return ASTUtils.traverseUpMemberExpression(parent)
157 }
158β
159 return node
160 },
161 isDeclaredInNode(params: {
162 functionNode: TSESTree.Node
163 reference: TSESLint.Scope.Reference
164 scopeManager: TSESLint.Scope.ScopeManager
165 }) {
166 const { functionNode, reference, scopeManager } = params
167 const scope = scopeManager.acquire(functionNode)
168β
169 if (scope === null) {
170 return false
171 }
172β
173 return scope.set.has(reference.identifier.name)
174 },
175 getExternalRefs(params: {
176 scopeManager: TSESLint.Scope.ScopeManager
177 sourceCode: Readonly<TSESLint.SourceCode>
178 node: TSESTree.Node
179 }): Array<TSESLint.Scope.Reference> {
180 const { scopeManager, sourceCode, node } = params
181 const scope = scopeManager.acquire(node)
182β
183 if (scope === null) {
184 return []
185 }
186β
187 const collectReferences = (
188 currentScope: TSESLint.Scope.Scope,
189 ): Array<TSESLint.Scope.Reference> => {
190 const references = [...currentScope.references]
191β
192 for (const childScope of currentScope.childScopes) {
193 references.push(...collectReferences(childScope))
194 }
195β
196 return references
197 }
198β
199 const references = collectReferences(scope)
200 .filter((x) => x.isRead() && !scope.set.has(x.identifier.name))
201 .map((x) => {
202 const memberPath = ASTUtils.traverseUpMemberExpression(x.identifier)
203 const memberExpression = memberPath.parent
204 const isComputedCallProperty =
205 memberExpression !== undefined &&
206 memberExpression.type === AST_NODE_TYPES.MemberExpression &&
207 memberExpression.computed &&
208 memberExpression.property === memberPath &&
209 memberExpression.parent.type === AST_NODE_TYPES.CallExpression &&
210 memberExpression.parent.callee === memberExpression
211β
212 const referenceNode = isComputedCallProperty
213 ? memberPath
214 : ASTUtils.traverseUpOnly(x.identifier, [
215 AST_NODE_TYPES.MemberExpression,
216 AST_NODE_TYPES.Identifier,
217 ])
218β
219 return {
220 variable: x,
221 node: referenceNode,
222 text: sourceCode.getText(referenceNode),
223 }
224 })
225β
226 const localRefIds = new Set(
227 [...scope.set.values()].map((x) => sourceCode.getText(x.identifiers[0])),
228 )
229β
230 const externalRefs = references.filter(
231 (x) => x.variable.resolved === null || !localRefIds.has(x.text),
232 )
233β
234 return uniqueBy(externalRefs, (x) => x.text).map((x) => x.variable)
235 },
236 mapKeyNodeToText(
237 node: TSESTree.Node,
238 sourceCode: Readonly<TSESLint.SourceCode>,
239 ) {
240 return sourceCode.getText(
241 ASTUtils.traverseUpOnly(node, [
242 AST_NODE_TYPES.MemberExpression,
243 AST_NODE_TYPES.TSNonNullExpression,
244 AST_NODE_TYPES.Identifier,
245 ]),
246 )
247 },
248 mapKeyNodeToBaseText(
249 node: TSESTree.Node,
250 sourceCode: Readonly<TSESLint.SourceCode>,
251 ) {
252 return ASTUtils.mapKeyNodeToText(node, sourceCode).replace(
253 /(?:\?(\.)|!)/g,
254 '$1',
255 )
256 },
257 isValidReactComponentOrHookName(
258 identifier: TSESTree.Identifier | null | undefined,
259 ) {
260 return (
261 identifier !== null &&
262 identifier !== undefined &&
263 /^(use|[A-Z])/.test(identifier.name)
264 )
265 },
266 getFunctionAncestor(
267 sourceCode: Readonly<TSESLint.SourceCode>,
268 node: TSESTree.Node,
269 ) {
270 for (const ancestor of sourceCode.getAncestors(node)) {
271 if (
272 ASTUtils.isNodeOfOneOf(ancestor, [
273 AST_NODE_TYPES.FunctionDeclaration,
274 AST_NODE_TYPES.FunctionExpression,
275 AST_NODE_TYPES.ArrowFunctionExpression,
276 ])
277 ) {
278 return ancestor
279 }
280β
281 if (
282 ancestor.parent?.type === AST_NODE_TYPES.VariableDeclarator &&
283 ancestor.parent.id.type === AST_NODE_TYPES.Identifier &&
284 ASTUtils.isNodeOfOneOf(ancestor, [
285 AST_NODE_TYPES.FunctionDeclaration,
286 AST_NODE_TYPES.FunctionExpression,
287 AST_NODE_TYPES.ArrowFunctionExpression,
288 ])
289 ) {
290 return ancestor
291 }
292 }
293β
294 return undefined
295 },
296 getReferencedExpressionByIdentifier(params: {
297 node: TSESTree.Node
298 context: Readonly<TSESLint.RuleContext<string, ReadonlyArray<unknown>>>
299 }) {
300 const { node, context } = params
301β
302 // we need the fallbacks for backwards compat with eslint < 8.37.0
303 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
304 const sourceCode = context.sourceCode ?? context.getSourceCode()
305 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
306 const scope = context.sourceCode.getScope(node)
307 ? sourceCode.getScope(node)
308 : context.getScope()
309β
310 const resolvedNode = scope.references.find((ref) => ref.identifier === node)
311 ?.resolved?.defs[0]?.node
312β
313 if (resolvedNode?.type !== AST_NODE_TYPES.VariableDeclarator) {
314 return null
315 }
316β
317 return resolvedNode.init
318 },
319 getClosestVariableDeclarator(node: TSESTree.Node) {
320 let currentNode: TSESTree.Node | undefined = node
321β
322 while (currentNode.type !== AST_NODE_TYPES.Program) {
323 if (currentNode.type === AST_NODE_TYPES.VariableDeclarator) {
324 return currentNode
325 }
326β
327 currentNode = currentNode.parent
328 }
329β
330 return undefined
331 },
332 getNestedReturnStatements(
333 node: TSESTree.Node,
334 ): Array<TSESTree.ReturnStatement> {
335 const returnStatements: Array<TSESTree.ReturnStatement> = []
336β
337 if (node.type === AST_NODE_TYPES.ReturnStatement) {
338 returnStatements.push(node)
339 }
340β
341 if ('body' in node && node.body !== undefined && node.body !== null) {
342 Array.isArray(node.body)
343 ? node.body.forEach((x) => {
344 returnStatements.push(...ASTUtils.getNestedReturnStatements(x))
345 })
346 : returnStatements.push(
347 ...ASTUtils.getNestedReturnStatements(node.body),
348 )
349 }
350β
351 if ('consequent' in node) {
352 Array.isArray(node.consequent)
353 ? node.consequent.forEach((x) => {
354 returnStatements.push(...ASTUtils.getNestedReturnStatements(x))
355 })
356 : returnStatements.push(
357 ...ASTUtils.getNestedReturnStatements(node.consequent),
358 )
359 }
360β
361 if ('alternate' in node && node.alternate !== null) {
362 Array.isArray(node.alternate)
363 ? node.alternate.forEach((x) => {
364 returnStatements.push(...ASTUtils.getNestedReturnStatements(x))
365 })
366 : returnStatements.push(
367 ...ASTUtils.getNestedReturnStatements(node.alternate),
368 )
369 }
370β
371 if ('cases' in node) {
372 node.cases.forEach((x) => {
373 returnStatements.push(...ASTUtils.getNestedReturnStatements(x))
374 })
375 }
376β
377 if ('block' in node) {
378 returnStatements.push(...ASTUtils.getNestedReturnStatements(node.block))
379 }
380β
381 if ('handler' in node && node.handler !== null) {
382 returnStatements.push(...ASTUtils.getNestedReturnStatements(node.handler))
383 }
384β
385 if ('finalizer' in node && node.finalizer !== null) {
386 returnStatements.push(
387 ...ASTUtils.getNestedReturnStatements(node.finalizer),
388 )
389 }
390β
391 if (
392 'expression' in node &&
393 node.expression !== true &&
394 node.expression !== false
395 ) {
396 returnStatements.push(
397 ...ASTUtils.getNestedReturnStatements(node.expression),
398 )
399 }
400β
401 if ('test' in node && node.test !== null) {
402 returnStatements.push(...ASTUtils.getNestedReturnStatements(node.test))
403 }
404β
405 return returnStatements
406 },
407}