fix(javascript): classify assignment targets and retain compound-assignment reads (#537)

This commit is contained in:
morluto
2026-10-05 16:16:57 +08:00
committed by GitHub
parent 4c8dc39f43
commit 333d118c0f
4 changed files with 204 additions and 27 deletions
+23 -6
View File
@@ -1,19 +1,36 @@
import * as t from "@babel/types";
/** Visit every Babel AST node in deterministic source-tree order. */
/**
* Visit every Babel AST node in deterministic source-tree order.
*
* `ancestors` runs outermost-first and ends with the direct parent. Callers
* need it whenever meaning depends on where a node sits, not just what its
* immediate parent is — a binding inside `catch ({message})` or `({a} = o)`
* has an ObjectProperty parent, so the parent alone cannot say whether the
* identifier declares a binding or is assigned to.
*/
export const traverseJavaScriptAst = (
root: t.Node,
visitor: {
readonly enter: (node: t.Node, parent: t.Node | null) => void;
readonly enter: (
node: t.Node,
parent: t.Node | null,
ancestors: readonly t.Node[],
) => void;
readonly exit?: (node: t.Node, parent: t.Node | null) => void;
},
): void => {
const visit = (node: t.Node, parent: t.Node | null): void => {
visitor.enter(node, parent);
for (const child of childNodes(node)) visit(child, node);
const visit = (
node: t.Node,
parent: t.Node | null,
ancestors: readonly t.Node[],
): void => {
visitor.enter(node, parent, ancestors);
for (const child of childNodes(node))
visit(child, node, [...ancestors, node]);
visitor.exit?.(node, parent);
};
visit(root, null);
visit(root, null, []);
};
const childNodes = (node: t.Node): t.Node[] => {