| 1 | import { VISITOR_KEYS } from "@babel/types"; |
| 2 | import type * as t from "@babel/types"; |
| 3 | |
| 4 | type StackItem = { |
| 5 | node: t.Node; |
| 6 | parent: t.Node | null; |
| 7 | }; |
| 8 | export default function checkDuplicateNodes(ast: t.Node) { |
| 9 | if (arguments.length !== 1) { |
| 10 | throw new Error("checkDuplicateNodes accepts only one argument: ast"); |
| 11 | } |
| 12 | // A Map from node to its parent |
| 13 | const parentsMap = new Map(); |
| 14 | |
| 15 | const hidePrivateProperties = (key: string, val: unknown) => { |
| 16 | // Hides properties like _shadowedFunctionLiteral, |
| 17 | // which makes the AST circular |
| 18 | if (key[0] === "_") return "[Private]"; |
| 19 | return val; |
| 20 | }; |
| 21 | |
| 22 | const stack: StackItem[] = [{ node: ast, parent: null }]; |
| 23 | let item; |
| 24 | |
| 25 | while ((item = stack.pop()) !== undefined) { |
| 26 | const { node, parent } = item; |
| 27 | if (!node) continue; |
| 28 | |
| 29 | const keys = VISITOR_KEYS[node.type]; |
| 30 | if (!keys) continue; |
| 31 | |
| 32 | if (parentsMap.has(node)) { |
| 33 | const parents = [parentsMap.get(node), parent]; |
| 34 | throw new Error( |
| 35 | "Do not reuse nodes. Use `t.cloneNode` (or `t.clone`/`t.cloneDeep` if using babel@6) to copy them.\n" + |
| 36 | JSON.stringify(node, hidePrivateProperties, 2) + |
| 37 | "\nParent:\n" + |
| 38 | JSON.stringify(parents, hidePrivateProperties, 2), |
| 39 | ); |
| 40 | } |
| 41 | parentsMap.set(node, parent); |
| 42 | |
| 43 | for (const key of keys) { |
| 44 | const subNode = |
| 45 | // @ts-expect-error visitor keys must present in node |
| 46 | node[key]; |
| 47 | |
| 48 | if (Array.isArray(subNode)) { |
| 49 | for (const child of subNode) { |
| 50 | stack.push({ node: child, parent: node }); |
| 51 | } |
| 52 | } else if (typeof subNode === "object" && subNode !== null) { |
| 53 | stack.push({ node: subNode, parent: node }); |
| 54 | } |
| 55 | } |
| 56 | } |
| 57 | } |