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

ast-utils.ts

349 lines9.8 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 context: Readonly<TSESLint.RuleContext<string, ReadonlyArray<unknown>>>,
223 ) {
224 for (const ancestor of context.getAncestors()) {
225 if (ancestor.type === AST_NODE_TYPES.FunctionDeclaration) {
226 return ancestor
227 }
228​
229 if (
230 ancestor.parent?.type === AST_NODE_TYPES.VariableDeclarator &&
231 ancestor.parent.id.type === AST_NODE_TYPES.Identifier &&
232 ASTUtils.isNodeOfOneOf(ancestor, [
233 AST_NODE_TYPES.FunctionDeclaration,
234 AST_NODE_TYPES.FunctionExpression,
235 AST_NODE_TYPES.ArrowFunctionExpression,
236 ])
237 ) {
238 return ancestor
239 }
240 }
241​
242 return undefined
243 },
244 getReferencedExpressionByIdentifier(params: {
245 node: TSESTree.Node
246 context: Readonly<TSESLint.RuleContext<string, ReadonlyArray<unknown>>>
247 }) {
248 const { node, context } = params
249​
250 const resolvedNode = context
251 .getScope()
252 .references.find((ref) => ref.identifier === node)?.resolved?.defs[0]
253 ?.node
254​
255 if (resolvedNode?.type !== AST_NODE_TYPES.VariableDeclarator) {
256 return null
257 }
258​
259 return resolvedNode.init
260 },
261 getClosestVariableDeclarator(node: TSESTree.Node) {
262 let currentNode: TSESTree.Node | undefined = node
263​
264 while (currentNode.type !== AST_NODE_TYPES.Program) {
265 if (currentNode.type === AST_NODE_TYPES.VariableDeclarator) {
266 return currentNode
267 }
268​
269 currentNode = currentNode.parent
270 }
271​
272 return undefined
273 },
274 getNestedReturnStatements(
275 node: TSESTree.Node,
276 ): Array<TSESTree.ReturnStatement> {
277 const returnStatements: Array<TSESTree.ReturnStatement> = []
278​
279 if (node.type === AST_NODE_TYPES.ReturnStatement) {
280 returnStatements.push(node)
281 }
282​
283 if ('body' in node && node.body !== undefined && node.body !== null) {
284 Array.isArray(node.body)
285 ? node.body.forEach((x) => {
286 returnStatements.push(...ASTUtils.getNestedReturnStatements(x))
287 })
288 : returnStatements.push(
289 ...ASTUtils.getNestedReturnStatements(node.body),
290 )
291 }
292​
293 if ('consequent' in node) {
294 Array.isArray(node.consequent)
295 ? node.consequent.forEach((x) => {
296 returnStatements.push(...ASTUtils.getNestedReturnStatements(x))
297 })
298 : returnStatements.push(
299 ...ASTUtils.getNestedReturnStatements(node.consequent),
300 )
301 }
302​
303 if ('alternate' in node && node.alternate !== null) {
304 Array.isArray(node.alternate)
305 ? node.alternate.forEach((x) => {
306 returnStatements.push(...ASTUtils.getNestedReturnStatements(x))
307 })
308 : returnStatements.push(
309 ...ASTUtils.getNestedReturnStatements(node.alternate),
310 )
311 }
312​
313 if ('cases' in node) {
314 node.cases.forEach((x) => {
315 returnStatements.push(...ASTUtils.getNestedReturnStatements(x))
316 })
317 }
318​
319 if ('block' in node) {
320 returnStatements.push(...ASTUtils.getNestedReturnStatements(node.block))
321 }
322​
323 if ('handler' in node && node.handler !== null) {
324 returnStatements.push(...ASTUtils.getNestedReturnStatements(node.handler))
325 }
326​
327 if ('finalizer' in node && node.finalizer !== null) {
328 returnStatements.push(
329 ...ASTUtils.getNestedReturnStatements(node.finalizer),
330 )
331 }
332​
333 if (
334 'expression' in node &&
335 node.expression !== true &&
336 node.expression !== false
337 ) {
338 returnStatements.push(
339 ...ASTUtils.getNestedReturnStatements(node.expression),
340 )
341 }
342​
343 if ('test' in node && node.test !== null) {
344 returnStatements.push(...ASTUtils.getNestedReturnStatements(node.test))
345 }
346​
347 return returnStatements
348 },