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