|
| 1 | +import { VISITOR_KEYS } from "@babel/types"; |
| 2 | +import type * as t from "@babel/types"; |
| 3 | +import type { HubInterface, Visitor } from "../index.ts"; |
| 4 | +import { NodePath } from "../index.ts"; |
| 5 | +import { explode } from "../visitors.ts"; |
| 6 | +import { setScope } from "../path/context.ts"; |
| 7 | + |
| 8 | +export default function traverseForScope( |
| 9 | + path: NodePath, |
| 10 | + visitors: Visitor, |
| 11 | + state: any, |
| 12 | +) { |
| 13 | + const exploded = explode(visitors); |
| 14 | + |
| 15 | + if (exploded.enter || exploded.exit) { |
| 16 | + throw new Error("Should not be used with enter/exit visitors."); |
| 17 | + } |
| 18 | + |
| 19 | + _traverse( |
| 20 | + path.parentPath, |
| 21 | + path.parent, |
| 22 | + path.node, |
| 23 | + path.container, |
| 24 | + path.key, |
| 25 | + path.listKey, |
| 26 | + path.hub, |
| 27 | + path, |
| 28 | + ); |
| 29 | + |
| 30 | + function _traverse( |
| 31 | + parentPath: NodePath, |
| 32 | + parent: t.Node, |
| 33 | + node: t.Node, |
| 34 | + container: t.Node | t.Node[], |
| 35 | + key: string | number, |
| 36 | + listKey: string, |
| 37 | + hub?: HubInterface, |
| 38 | + inPath?: NodePath, |
| 39 | + ) { |
| 40 | + if (!node) { |
| 41 | + return; |
| 42 | + } |
| 43 | + |
| 44 | + const path = |
| 45 | + inPath || |
| 46 | + NodePath.get({ |
| 47 | + hub, |
| 48 | + parentPath, |
| 49 | + parent, |
| 50 | + container, |
| 51 | + listKey, |
| 52 | + key, |
| 53 | + }); |
| 54 | + |
| 55 | + setScope.call(path); |
| 56 | + |
| 57 | + const visitor = exploded[node.type]; |
| 58 | + if (visitor) { |
| 59 | + if (visitor.enter) { |
| 60 | + for (const visit of visitor.enter) { |
| 61 | + visit.call(state, path, state); |
| 62 | + } |
| 63 | + } |
| 64 | + if (visitor.exit) { |
| 65 | + for (const visit of visitor.exit) { |
| 66 | + visit.call(state, path, state); |
| 67 | + } |
| 68 | + } |
| 69 | + } |
| 70 | + if (path.shouldSkip) { |
| 71 | + return; |
| 72 | + } |
| 73 | + |
| 74 | + const keys = VISITOR_KEYS[node.type]; |
| 75 | + if (!keys?.length) { |
| 76 | + return; |
| 77 | + } |
| 78 | + |
| 79 | + for (const key of keys) { |
| 80 | + // @ts-expect-error key must present in node |
| 81 | + const prop = node[key]; |
| 82 | + if (!prop) continue; |
| 83 | + if (Array.isArray(prop)) { |
| 84 | + for (let i = 0; i < prop.length; i++) { |
| 85 | + const value = prop[i]; |
| 86 | + _traverse(path, node, value, prop, i, key); |
| 87 | + } |
| 88 | + } else { |
| 89 | + _traverse(path, node, prop, node, key, null); |
| 90 | + } |
| 91 | + } |
| 92 | + } |
| 93 | +} |
0 commit comments