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