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

ast-utils.ts

315 lines9.0 KB

1import type { TSESLint, TSESTree } from '@typescript-eslint/utils'
2import type TSESLintScopeManager from '@typescript-eslint/scope-manager'
3import { AST_NODE_TYPES } from '@typescript-eslint/utils'
4import type { RuleContext } from '@typescript-eslint/utils/dist/ts-eslint'
5import { uniqueBy } from './unique-by'
6​
7export const ASTUtils = {
8 isNodeOfOneOf<T extends AST_NODE_TYPES>(
9 node: TSESTree.Node,
10 types: readonly 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 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: 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): TSESTree.Identifier[] {
52 const identifiers: 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: 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 }): 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 getReactComponentOrHookAncestor(
207 context: Readonly<RuleContext<string, readonly unknown[]>>,
208 ) {
209 return context.getAncestors().find((x) => {
210 return (
211 ASTUtils.isNodeOfOneOf(x, [
212 AST_NODE_TYPES.FunctionDeclaration,
213 AST_NODE_TYPES.FunctionExpression,
214 AST_NODE_TYPES.ArrowFunctionExpression,
215 ]) &&
216 x.id !== null &&
217 /^(use|[A-Z])/.test(x.id.name)
218 )
219 }) as
220 | TSESTree.FunctionDeclaration
221 | TSESTree.FunctionExpression
222 | TSESTree.ArrowFunctionExpression
223 | undefined
224 },
225 getReferencedExpressionByIdentifier(params: {
226 node: TSESTree.Node
227 context: Readonly<RuleContext<string, readonly unknown[]>>
228 }) {
229 const { node, context } = params
230​
231 const resolvedNode = context
232 .getScope()
233 .references.find((ref) => ref.identifier === node)?.resolved
234 ?.defs[0]?.node
235​
236 if (resolvedNode?.type !== AST_NODE_TYPES.VariableDeclarator) {
237 return null
238 }
239​
240 return resolvedNode.init
241 },
242 getNestedReturnStatements(node: TSESTree.Node): TSESTree.ReturnStatement[] {
243 const returnStatements: TSESTree.ReturnStatement[] = []
244​
245 if (node.type === AST_NODE_TYPES.ReturnStatement) {
246 returnStatements.push(node)
247 }
248​
249 if ('body' in node && node.body !== undefined && node.body !== null) {
250 Array.isArray(node.body)
251 ? node.body.forEach((x) => {
252 returnStatements.push(...ASTUtils.getNestedReturnStatements(x))
253 })
254 : returnStatements.push(
255 ...ASTUtils.getNestedReturnStatements(node.body),
256 )
257 }
258​
259 if ('consequent' in node) {
260 Array.isArray(node.consequent)
261 ? node.consequent.forEach((x) => {
262 returnStatements.push(...ASTUtils.getNestedReturnStatements(x))
263 })
264 : returnStatements.push(
265 ...ASTUtils.getNestedReturnStatements(node.consequent),
266 )
267 }
268​
269 if ('alternate' in node && node.alternate !== null) {
270 Array.isArray(node.alternate)
271 ? node.alternate.forEach((x) => {
272 returnStatements.push(...ASTUtils.getNestedReturnStatements(x))
273 })
274 : returnStatements.push(
275 ...ASTUtils.getNestedReturnStatements(node.alternate),
276 )
277 }
278​
279 if ('cases' in node) {
280 node.cases.forEach((x) => {
281 returnStatements.push(...ASTUtils.getNestedReturnStatements(x))
282 })
283 }
284​
285 if ('block' in node) {
286 returnStatements.push(...ASTUtils.getNestedReturnStatements(node.block))
287 }
288​
289 if ('handler' in node && node.handler !== null) {
290 returnStatements.push(...ASTUtils.getNestedReturnStatements(node.handler))
291 }
292​
293 if ('finalizer' in node && node.finalizer !== null) {
294 returnStatements.push(
295 ...ASTUtils.getNestedReturnStatements(node.finalizer),
296 )
297 }
298​
299 if (
300 'expression' in node &&
301 node.expression !== true &&
302 node.expression !== false
303 ) {
304 returnStatements.push(
305 ...ASTUtils.getNestedReturnStatements(node.expression),
306 )
307 }
308​
309 if ('test' in node && node.test !== null) {
310 returnStatements.push(...ASTUtils.getNestedReturnStatements(node.test))
311 }
312​
313 return returnStatements
314 },