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

ast-utils.ts

58 lines1.7 KB

1import type { Node } from 'oxc-parser'
2​
3/**
4 * Cache of keys that hold child nodes (objects/arrays) per AST node type.
5 * Since oxc-parser produces AST via JSON.parse, every instance of a given
6 * node type has the same set of keys, so we only need to discover them once.
7 */
8const childKeysCache = new Map<string, Array<string>>()
9​
10function getChildKeys(node: Node): Array<string> {
11 let keys = childKeysCache.get(node.type)
12 if (keys) return keys
13​
14 keys = []
15 for (const key in node) {
16 if (key === 'type' || key === 'start' || key === 'end') continue
17 // typeof null === 'object', so nullable node fields get cached too
18 if (typeof (node as any)[key] === 'object') {
19 keys.push(key)
20 }
21 }
22 childKeysCache.set(node.type, keys)
23 return keys
25​
26/**
27 * Iterate over the direct child nodes of an AST node.
28 * Uses a per-type cache of which keys hold child nodes to avoid
29 * allocating Object.entries() arrays on every call.
30 */
31export function forEachChild(node: Node, callback: (child: Node) => void) {
32 const keys = getChildKeys(node)
33 for (const key of keys) {
34 const value = (node as any)[key]
35 if (value === null) continue
36 if (Array.isArray(value)) {
37 for (const item of value) {
38 if (typeof item === 'object' && item !== null && 'type' in item) {
39 callback(item)
40 }
41 }
42 } else if ('type' in value) {
43 callback(value as Node)
44 }
45 }
47​
48/**
49 * Recursively walk AST nodes, calling `visitor` for each node with a `type`.
50 */
51export function walk(
52 node: Node,
53 visitor: (node: Node, parentNode?: Node) => void,
54 parentNode?: Node,
55) {
56 visitor(node, parentNode)
57 forEachChild(node, (child) => walk(child, visitor, node))