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

ast-utils.ts

346 lines9.7 KB

1import { AST_NODE_TYPES } from '@typescript-eslint/utils'
2import { uniqueBy } from './unique-by'
3import type { TSESLint, TSESTree } from '@typescript-eslint/utils'
4import type TSESLintScopeManager from '@typescript-eslint/scope-manager'
5import type { RuleContext } from '@typescript-eslint/utils/dist/ts-eslint'
6​
7export const ASTUtils = {
8 isNodeOfOneOf<T extends AST_NODE_TYPES>(
9 node: TSESTree.Node,
10 types: ReadonlyArray<T>,
11 ): node is TSESTree.Node & { type: T } {
12 return types.includes(node.type as T)
13 },
14 isIdentifier(node: TSESTree.Node): node is TSESTree.Identifier {
15 return node.type === AST_NODE_TYPES.Identifier
16 },
17 isIdentifierWithName(
18 node: TSESTree.Node,
19 name: string,
20 ): node is TSESTree.Identifier {
21 return ASTUtils.isIdentifier(node) && node.name === name
22 },
23 isIdentifierWithOneOfNames<T extends Array<string>>(
24 node: TSESTree.Node,
25 name: T,
26 ): node is TSESTree.Identifier & { name: T[number] } {
27 return ASTUtils.isIdentifier(node) && name.includes(node.name)
28 },
29 isProperty(node: TSESTree.Node): node is TSESTree.Property {
30 return node.type === AST_NODE_TYPES.Property
31 },
32 isObjectExpression(node: TSESTree.Node): node is TSESTree.ObjectExpression {
33 return node.type === AST_NODE_TYPES.ObjectExpression
34 },
35 isPropertyWithIdentifierKey(
36 node: TSESTree.Node,
37 key: string,
38 ): node is TSESTree.Property {
39 return (
40 ASTUtils.isProperty(node) && ASTUtils.isIdentifierWithName(node.key, key)
41 )
42 },
43 findPropertyWithIdentifierKey(
44 properties: Array<TSESTree.ObjectLiteralElement>,
45 key: string,
46 ): TSESTree.Property | undefined {
47 return properties.find((x) =>
48 ASTUtils.isPropertyWithIdentifierKey(x, key),
49 ) as TSESTree.Property | undefined
50 },
51 getNestedIdentifiers(node: TSESTree.Node): Array<TSESTree.Identifier> {
52 const identifiers: Array<TSESTree.Identifier> = []
53​
54 if (ASTUtils.isIdentifier(node)) {
55 identifiers.push(node)
56 }
57​
58 if ('arguments' in node) {
59 node.arguments.forEach((x) => {
60 identifiers.push(...ASTUtils.getNestedIdentifiers(x))
61 })
62 }
63​
64 if ('elements' in node) {
65 node.elements.forEach((x) => {
66 if (x !== null) {
67 identifiers.push(...ASTUtils.getNestedIdentifiers(x))
68 }
69 })
70 }
71​
72 if ('properties' in node) {
73 node.properties.forEach((x) => {
74 identifiers.push(...ASTUtils.getNestedIdentifiers(x))
75 })
76 }
77​
78 if ('expressions' in node) {
79 node.expressions.forEach((x) => {
80 identifiers.push(...ASTUtils.getNestedIdentifiers(x))
81 })
82 }
83​
84 if (node.type === AST_NODE_TYPES.Property) {
85 identifiers.push(...ASTUtils.getNestedIdentifiers(node.value))
86 }
87​
88 if (node.type === AST_NODE_TYPES.SpreadElement) {
89 identifiers.push(...ASTUtils.getNestedIdentifiers(node.argument))
90 }
91​
92 if (node.type === AST_NODE_TYPES.MemberExpression) {
93 identifiers.push(...ASTUtils.getNestedIdentifiers(node.object))
94 }
95​
96 if (node.type === AST_NODE_TYPES.UnaryExpression) {
97 identifiers.push(...ASTUtils.getNestedIdentifiers(node.argument))
98 }
99​
100 if (node.type === AST_NODE_TYPES.ChainExpression) {
101 identifiers.push(...ASTUtils.getNestedIdentifiers(node.expression))
102 }
103​
104 if (node.type === AST_NODE_TYPES.TSNonNullExpression) {
105 identifiers.push(...ASTUtils.getNestedIdentifiers(node.expression))
106 }
107​
108 return identifiers
109 },
110 isAncestorIsCallee(identifier: TSESTree.Node) {
111 let previousNode = identifier
112 let currentNode = identifier.parent
113​
114 while (currentNode !== undefined) {
115 if (
116 currentNode.type === AST_NODE_TYPES.CallExpression &&
117 currentNode.callee === previousNode
118 ) {
119 return true
120 }
121​
122 if (currentNode.type !== AST_NODE_TYPES.MemberExpression) {
123 return false
124 }
125​
126 previousNode = currentNode
127 currentNode = currentNode.parent
128 }
129​
130 return false
131 },
132 traverseUpOnly(
133 identifier: TSESTree.Node,
134 allowedNodeTypes: Array<AST_NODE_TYPES>,
135 ): TSESTree.Node {
136 const parent = identifier.parent
137​
138 if (parent !== undefined && allowedNodeTypes.includes(parent.type)) {
139 return ASTUtils.traverseUpOnly(parent, allowedNodeTypes)
140 }
141​
142 return identifier
143 },
144 isDeclaredInNode(params: {
145 functionNode: TSESTree.Node
146 reference: TSESLintScopeManager.Reference
147 scopeManager: TSESLint.Scope.ScopeManager
148 }) {
149 const { functionNode, reference, scopeManager } = params
150 const scope = scopeManager.acquire(functionNode)
151​
152 if (scope === null) {
153 return false
154 }
155​
156 return scope.set.has(reference.identifier.name)
157 },
158 getExternalRefs(params: {
159 scopeManager: TSESLint.Scope.ScopeManager
160 sourceCode: Readonly<TSESLint.SourceCode>
161 node: TSESTree.Node
162 }): Array<TSESLint.Scope.Reference> {
163 const { scopeManager, sourceCode, node } = params
164 const scope = scopeManager.acquire(node)
165​
166 if (scope === null) {
167 return []
168 }
169​
170 const references = scope.references
171 .filter((x) => x.isRead() && !scope.set.has(x.identifier.name))
172 .map((x) => {
173 const referenceNode = ASTUtils.traverseUpOnly(x.identifier, [
174 AST_NODE_TYPES.MemberExpression,
175 AST_NODE_TYPES.Identifier,
176 ])
177​
178 return {
179 variable: x,
180 node: referenceNode,
181 text: sourceCode.getText(referenceNode),
182 }
183 })
184​
185 const localRefIds = new Set(
186 [...scope.set.values()].map((x) => sourceCode.getText(x.identifiers[0])),
187 )
188​
189 const externalRefs = references.filter(
190 (x) => x.variable.resolved === null || !localRefIds.has(x.text),
191 )
192​
193 return uniqueBy(externalRefs, (x) => x.text).map((x) => x.variable)
194 },
195 mapKeyNodeToText(
196 node: TSESTree.Node,
197 sourceCode: Readonly<TSESLint.SourceCode>,
198 ) {
199 return sourceCode.getText(
200 ASTUtils.traverseUpOnly(node, [
201 AST_NODE_TYPES.MemberExpression,
202 AST_NODE_TYPES.Identifier,
203 ]),
204 )
205 },
206 isValidReactComponentOrHookName(
207 identifier: TSESTree.Identifier | null | undefined,
208 ) {
209 return (
210 identifier !== null &&
211 identifier !== undefined &&
212 /^(use|[A-Z])/.test(identifier.name)
213 )
214 },
215 getFunctionAncestor(
216 context: Readonly<RuleContext<string, ReadonlyArray<unknown>>>,
217 ) {
218 for (const ancestor of context.getAncestors()) {
219 if (ancestor.type === AST_NODE_TYPES.FunctionDeclaration) {
220 return ancestor
221 }
222​
223 if (
224 ancestor.parent?.type === AST_NODE_TYPES.VariableDeclarator &&
225 ancestor.parent.id.type === AST_NODE_TYPES.Identifier &&
226 ASTUtils.isNodeOfOneOf(ancestor, [
227 AST_NODE_TYPES.FunctionDeclaration,
228 AST_NODE_TYPES.FunctionExpression,
229 AST_NODE_TYPES.ArrowFunctionExpression,
230 ])
231 ) {
232 return ancestor
233 }
234 }
235​
236 return undefined
237 },
238 getReferencedExpressionByIdentifier(params: {
239 node: TSESTree.Node
240 context: Readonly<RuleContext<string, ReadonlyArray<unknown>>>
241 }) {
242 const { node, context } = params
243​
244 const resolvedNode = context
245 .getScope()
246 .references.find((ref) => ref.identifier === node)?.resolved
247 ?.defs[0]?.node
248​
249 if (resolvedNode?.type !== AST_NODE_TYPES.VariableDeclarator) {
250 return null
251 }
252​
253 return resolvedNode.init
254 },
255 getClosestVariableDeclarator(node: TSESTree.Node) {
256 let currentNode: TSESTree.Node | undefined = node
257​
258 while (
259 currentNode !== undefined &&
260 currentNode.type !== AST_NODE_TYPES.Program
261 ) {
262 if (currentNode.type === AST_NODE_TYPES.VariableDeclarator) {
263 return currentNode
264 }
265​
266 currentNode = currentNode.parent
267 }
268​
269 return undefined
270 },
271 getNestedReturnStatements(
272 node: TSESTree.Node,
273 ): Array<TSESTree.ReturnStatement> {
274 const returnStatements: Array<TSESTree.ReturnStatement> = []
275​
276 if (node.type === AST_NODE_TYPES.ReturnStatement) {
277 returnStatements.push(node)
278 }
279​
280 if ('body' in node && node.body !== undefined && node.body !== null) {
281 Array.isArray(node.body)
282 ? node.body.forEach((x) => {
283 returnStatements.push(...ASTUtils.getNestedReturnStatements(x))
284 })
285 : returnStatements.push(
286 ...ASTUtils.getNestedReturnStatements(node.body),
287 )
288 }
289​
290 if ('consequent' in node) {
291 Array.isArray(node.consequent)
292 ? node.consequent.forEach((x) => {
293 returnStatements.push(...ASTUtils.getNestedReturnStatements(x))
294 })
295 : returnStatements.push(
296 ...ASTUtils.getNestedReturnStatements(node.consequent),
297 )
298 }
299​
300 if ('alternate' in node && node.alternate !== null) {
301 Array.isArray(node.alternate)
302 ? node.alternate.forEach((x) => {
303 returnStatements.push(...ASTUtils.getNestedReturnStatements(x))
304 })
305 : returnStatements.push(
306 ...ASTUtils.getNestedReturnStatements(node.alternate),
307 )
308 }
309​
310 if ('cases' in node) {
311 node.cases.forEach((x) => {
312 returnStatements.push(...ASTUtils.getNestedReturnStatements(x))
313 })
314 }
315​
316 if ('block' in node) {
317 returnStatements.push(...ASTUtils.getNestedReturnStatements(node.block))
318 }
319​
320 if ('handler' in node && node.handler !== null) {
321 returnStatements.push(...ASTUtils.getNestedReturnStatements(node.handler))
322 }
323​
324 if ('finalizer' in node && node.finalizer !== null) {
325 returnStatements.push(
326 ...ASTUtils.getNestedReturnStatements(node.finalizer),
327 )
328 }
329​
330 if (
331 'expression' in node &&
332 node.expression !== true &&
333 node.expression !== false
334 ) {
335 returnStatements.push(
336 ...ASTUtils.getNestedReturnStatements(node.expression),
337 )
338 }
339​
340 if ('test' in node && node.test !== null) {
341 returnStatements.push(...ASTUtils.getNestedReturnStatements(node.test))
342 }
343​
344 return returnStatements
345 },