跳到主要内容

查找节点

2024年11月10日
柏拉文
越努力,越幸运

一、认识


二、语法


const find = (ast, type) => {
const nodes = [];
visit(ast, {
[type]: (node) => {
nodes.push(node);
},
});
return nodes;
};

三、用法


3.1 过滤变量语句

const oxcParser = require("oxc-parser");

const { parseAsync } = oxcParser;

const parse = async (sourceCode) => {
try {
const result = await parseAsync(sourceCode);
return result;
} catch (error) {
console.error("Error parsing source code:", error);
return "";
}
};

const visit = (ast, visitor) => {
function traverse(node, parent) {
if (!node || typeof node !== "object") return;

if (visitor[node.type]) {
visitor[node.type](node, parent);
}

for (const key in node) {
if (!node.hasOwnProperty(key)) continue;

const child = node[key];
if (Array.isArray(child)) {
child.forEach((c) => traverse(c, node));
} else if (child && typeof child === "object") {
traverse(child, node);
}
}
}

traverse(ast, null);
};

const find = (ast, type) => {
const nodes = [];
visit(ast, {
[type]: (node) => {
nodes.push(node);
},
});
return nodes;
};

async function main() {
const ast = await parse(
`var a = 1; var b = 2; var c = ()=> { var d = 3; return d;};`
);

const variableDeclarations = find(ast, "VariableDeclaration");
console.log(JSON.stringify(variableDeclarations, null, 2));
}

main();