0

I want to go through the AST tree and get the ChildNode equals "IfStatement" but there could be a lot of Childnodes like in code below. Is there some method to do it in recursive way to add childNodes and check the value ?

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";

I am trying something like this but it doesnt work

  var IfCheck = result.Root.ChildNodes.FindAll(x => x.ChildNodes.ToString() == "IfStatement");
Paweld_00
  • 81
  • 8

1 Answers1

0

You can traverse your tree:

/// <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]);
            }
        }
    }
}

Then, just loop through:

var nodes = result.Root.Traverse(node => node.ChildNodes);

var ifStatements = nodes.Where(node => node.Term.Name.Equals("IfStatement"));