0

我想通过 AST 树并让 ChildNode 等于“IfStatement”,但可能有很多 Childnodes,如下面的代码所示。是否有一些方法可以以递归方式添加 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");
4

1 回答 1

0

你可以遍历你的树:

/// <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"));
于 2016-04-05T05:42:05.593 回答