遍历AST树并获得子节点值Irony
本文关键字:子节点 Irony AST 遍历 | 更新日期: 2023-09-27 18:05:18
我想通过AST树并获得ChildNode等于"IfStatement",但可能有很多ChildNode,如下面的代码。是否有一些方法可以递归地添加childNodes并检查值?
MyGrammar grammar = new MyGrammar ();
Parser parser = new Parser(grammar);
var result = parser.Parse(textBox.Text);
var IfNode=result.Root.ChildNodes[0].ChildNodes[0].ChildNodes[1].ChildNodes[0].ToString() == "IfStatement";
我正在尝试这样做,但它不工作
var IfCheck = result.Root.ChildNodes.FindAll(x => x.ChildNodes.ToString() == "IfStatement");
你可以遍历你的树:
/// <summary>
/// Parser extension methods
/// </summary>
public static class ParserExt
{
/// <summary>
/// Converts parser nodes tree to flat collection
/// </summary>
/// <param name="item"></param>
/// <param name="childSelector"></param>
/// <returns></returns>
public static IEnumerable<ParseTreeNode> Traverse(this ParseTreeNode item, Func<ParseTreeNode, IEnumerable<ParseTreeNode>> childSelector)
{
var stack = new Stack<ParseTreeNode>();
stack.Push(item);
while (stack.Any())
{
var next = stack.Pop();
yield return next;
var childs = childSelector(next).ToList();
for (var childId = childs.Count - 1; childId >= 0; childId--)
{
stack.Push(childs[childId]);
}
}
}
}
然后,循环通过:
var nodes = result.Root.Traverse(node => node.ChildNodes);
var ifStatements = nodes.Where(node => node.Term.Name.Equals("IfStatement"));