Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

ast-utils.ts

356 lines10.1 KB

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 return identifiers
115 },
116 isAncestorIsCallee(identifier: TSESTree.Node) {
117 let previousNode = identifier
118 let currentNode = identifier.parent
119​
120 while (currentNode !== undefined) {
121 if (
122 currentNode.type === AST_NODE_TYPES.CallExpression &&
123 currentNode.callee === previousNode
124 ) {
125 return true
126 }
127​
128 if (currentNode.type !== AST_NODE_TYPES.MemberExpression) {
129 return false
130 }
131​
132 previousNode = currentNode
133 currentNode = currentNode.parent
134 }
135​
136 return false
137 },
138 traverseUpOnly(
139 identifier: TSESTree.Node,
140 allowedNodeTypes: Array<AST_NODE_TYPES>,
141 ): TSESTree.Node {
142 const parent = identifier.parent
143​
144 if (parent !== undefined && allowedNodeTypes.includes(parent.type)) {
145 return ASTUtils.traverseUpOnly(parent, allowedNodeTypes)
146 }
147​
148 return identifier
149 },
150 isDeclaredInNode(params: {
151 functionNode: TSESTree.Node
152 reference: TSESLint.Scope.Reference
153 scopeManager: TSESLint.Scope.ScopeManager
154 }) {
155 const { functionNode, reference, scopeManager } = params
156 const scope = scopeManager.acquire(functionNode)
157​
158 if (scope === null) {
159 return false
160 }
161​
162 return scope.set.has(reference.identifier.name)
163 },
164 getExternalRefs(params: {
165 scopeManager: TSESLint.Scope.ScopeManager
166 sourceCode: Readonly<TSESLint.SourceCode>
167 node: TSESTree.Node
168 }): Array<TSESLint.Scope.Reference> {
169 const { scopeManager, sourceCode, node } = params
170 const scope = scopeManager.acquire(node)
171​
172 if (scope === null) {
173 return []
174 }
175​
176 const references = scope.references
177 .filter((x) => x.isRead() && !scope.set.has(x.identifier.name))
178 .map((x) => {
179 const referenceNode = ASTUtils.traverseUpOnly(x.identifier, [
180 AST_NODE_TYPES.MemberExpression,
181 AST_NODE_TYPES.Identifier,
182 ])
183​
184 return {
185 variable: x,
186 node: referenceNode,
187 text: sourceCode.getText(referenceNode),
188 }
189 })
190​
191 const localRefIds = new Set(
192 [...scope.set.values()].map((x) => sourceCode.getText(x.identifiers[0])),
193 )
194​
195 const externalRefs = references.filter(
196 (x) => x.variable.resolved === null || !localRefIds.has(x.text),
197 )
198​
199 return uniqueBy(externalRefs, (x) => x.text).map((x) => x.variable)
200 },
201 mapKeyNodeToText(
202 node: TSESTree.Node,
203 sourceCode: Readonly<TSESLint.SourceCode>,
204 ) {
205 return sourceCode.getText(
206 ASTUtils.traverseUpOnly(node, [
207 AST_NODE_TYPES.MemberExpression,
208 AST_NODE_TYPES.Identifier,
209 ]),
210 )
211 },
212 isValidReactComponentOrHookName(
213 identifier: TSESTree.Identifier | null | undefined,
214 ) {
215 return (
216 identifier !== null &&
217 identifier !== undefined &&
218 /^(use|[A-Z])/.test(identifier.name)
219 )
220 },
221 getFunctionAncestor(
222 sourceCode: Readonly<TSESLint.SourceCode>,
223 node: TSESTree.Node,
224 ) {
225 for (const ancestor of sourceCode.getAncestors(node)) {
226 if (ancestor.type === AST_NODE_TYPES.FunctionDeclaration) {
227 return ancestor
228 }
229​
230 if (
231 ancestor.parent?.type === AST_NODE_TYPES.VariableDeclarator &&
232 ancestor.parent.id.type === AST_NODE_TYPES.Identifier &&
233 ASTUtils.isNodeOfOneOf(ancestor, [
234 AST_NODE_TYPES.FunctionDeclaration,
235 AST_NODE_TYPES.FunctionExpression,
236 AST_NODE_TYPES.ArrowFunctionExpression,
237 ])
238 ) {
239 return ancestor
240 }
241 }
242​
243 return undefined
244 },
245 getReferencedExpressionByIdentifier(params: {
246 node: TSESTree.Node
247 context: Readonly<TSESLint.RuleContext<string, ReadonlyArray<unknown>>>
248 }) {
249 const { node, context } = params
250​
251 // we need the fallbacks for backwards compat with eslint < 8.37.0
252 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
253 const sourceCode = context.sourceCode ?? context.getSourceCode()
254 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
255 const scope = context.sourceCode.getScope(node)
256 ? sourceCode.getScope(node)
257 : context.getScope()
258​
259 const resolvedNode = scope.references.find((ref) => ref.identifier === node)
260 ?.resolved?.defs[0]?.node
261​
262 if (resolvedNode?.type !== AST_NODE_TYPES.VariableDeclarator) {
263 return null
264 }
265​
266 return resolvedNode.init
267 },
268 getClosestVariableDeclarator(node: TSESTree.Node) {
269 let currentNode: TSESTree.Node | undefined = node
270​
271 while (currentNode.type !== AST_NODE_TYPES.Program) {
272 if (currentNode.type === AST_NODE_TYPES.VariableDeclarator) {
273 return currentNode
274 }
275​
276 currentNode = currentNode.parent
277 }
278​
279 return undefined
280 },
281 getNestedReturnStatements(
282 node: TSESTree.Node,
283 ): Array<TSESTree.ReturnStatement> {
284 const returnStatements: Array<TSESTree.ReturnStatement> = []
285​
286 if (node.type === AST_NODE_TYPES.ReturnStatement) {
287 returnStatements.push(node)
288 }
289​
290 if ('body' in node && node.body !== undefined && node.body !== null) {
291 Array.isArray(node.body)
292 ? node.body.forEach((x) => {
293 returnStatements.push(...ASTUtils.getNestedReturnStatements(x))
294 })
295 : returnStatements.push(
296 ...ASTUtils.getNestedReturnStatements(node.body),
297 )
298 }
299​
300 if ('consequent' in node) {
301 Array.isArray(node.consequent)
302 ? node.consequent.forEach((x) => {
303 returnStatements.push(...ASTUtils.getNestedReturnStatements(x))
304 })
305 : returnStatements.push(
306 ...ASTUtils.getNestedReturnStatements(node.consequent),
307 )
308 }
309​
310 if ('alternate' in node && node.alternate !== null) {
311 Array.isArray(node.alternate)
312 ? node.alternate.forEach((x) => {
313 returnStatements.push(...ASTUtils.getNestedReturnStatements(x))
314 })
315 : returnStatements.push(
316 ...ASTUtils.getNestedReturnStatements(node.alternate),
317 )
318 }
319​
320 if ('cases' in node) {
321 node.cases.forEach((x) => {
322 returnStatements.push(...ASTUtils.getNestedReturnStatements(x))
323 })
324 }
325​
326 if ('block' in node) {
327 returnStatements.push(...ASTUtils.getNestedReturnStatements(node.block))
328 }
329​
330 if ('handler' in node && node.handler !== null) {
331 returnStatements.push(...ASTUtils.getNestedReturnStatements(node.handler))
332 }
333​
334 if ('finalizer' in node && node.finalizer !== null) {
335 returnStatements.push(
336 ...ASTUtils.getNestedReturnStatements(node.finalizer),
337 )
338 }
339​
340 if (
341 'expression' in node &&
342 node.expression !== true &&
343 node.expression !== false
344 ) {
345 returnStatements.push(
346 ...ASTUtils.getNestedReturnStatements(node.expression),
347 )
348 }
349​
350 if ('test' in node && node.test !== null) {
351 returnStatements.push(...ASTUtils.getNestedReturnStatements(node.test))
352 }
353​
354 return returnStatements
355 },