| 1 |
import { VISITOR_KEYS } from "../definitions"; |
| 2 |
import type * as t from ".."; |
| 3 |
|
| 4 |
export type TraversalAncestors = Array<{ |
| 5 |
node: t.Node; |
| 6 |
key: string; |
| 7 |
index?: number; |
| 8 |
}>; |
| 9 |
|
| 10 |
export type TraversalHandler<T> = ( |
| 11 |
this: undefined, |
| 12 |
node: t.Node, |
| 13 |
parent: TraversalAncestors, |
| 14 |
state: T, |
| 15 |
) => void; |
| 16 |
|
| 17 |
export type TraversalHandlers<T> = { |
| 18 |
enter?: TraversalHandler<T>; |
| 19 |
exit?: TraversalHandler<T>; |
| 20 |
}; |
| 21 |
|
| 22 |
/** |
| 23 |
* A general AST traversal with both prefix and postfix handlers, and a |
| 24 |
* state object. Exposes ancestry data to each handler so that more complex |
| 25 |
* AST data can be taken into account. |
| 26 |
*/ |
| 27 |
export default function traverse<T>( |
| 28 |
node: t.Node, |
| 29 |
handlers: TraversalHandler<T> | TraversalHandlers<T>, |
| 30 |
state?: T, |
| 31 |
): void { |
| 32 |
if (typeof handlers === "function") { |
| 33 |
handlers = { enter: handlers }; |
| 34 |
} |
| 35 |
|
| 36 |
const { enter, exit } = handlers; |
| 37 |
|
| 38 |
traverseSimpleImpl(node, enter, exit, state, []); |
| 39 |
} |
| 40 |
|
| 41 |
function traverseSimpleImpl<T>( |
| 42 |
node: any, |
| 43 |
enter: Function | undefined, |
| 44 |
exit: Function | undefined, |
| 45 |
state: T | undefined, |
| 46 |
ancestors: TraversalAncestors, |
| 47 |
) { |
| 48 |
const keys = VISITOR_KEYS[node.type]; |
| 49 |
if (!keys) return; |
| 50 |
|
| 51 |
if (enter) enter(node, ancestors, state); |
| 52 |
|
| 53 |
for (const key of keys) { |
| 54 |
const subNode = node[key]; |
| 55 |
|
| 56 |
if (Array.isArray(subNode)) { |
| 57 |
for (let i = 0; i < subNode.length; i++) { |
| 58 |
const child = subNode[i]; |
| 59 |
if (!child) continue; |
| 60 |
|
| 61 |
ancestors.push({ |
| 62 |
node, |
| 63 |
key, |
| 64 |
index: i, |
| 65 |
}); |
| 66 |
|
| 67 |
traverseSimpleImpl(child, enter, exit, state, ancestors); |
| 68 |
|
| 69 |
ancestors.pop(); |
| 70 |
} |
| 71 |
} else if (subNode) { |
| 72 |
ancestors.push({ |
| 73 |
node, |
| 74 |
key, |
| 75 |
}); |
| 76 |
|
| 77 |
traverseSimpleImpl(subNode, enter, exit, state, ancestors); |
| 78 |
|
| 79 |
ancestors.pop(); |
| 80 |
} |
| 81 |
} |
| 82 |
|
| 83 |
if (exit) exit(node, ancestors, state); |
| 84 |
} |