How to Generate and display ParseTree for an expression in C# using Irony?

时光毁灭记忆、已成空白 提交于 2019-12-25 04:13:57

问题


I want to generate and display context free grammar using irony and so far I am able to write the context free grammar by following code

 public ExpressionGrammar()
            {
                    //// 1. Terminals
                    Terminal number = new NumberLiteral("number");
                    Terminal identifier = new IdentifierTerminal("identifier");

                    //// 2. Non-terminals
                    NonTerminal Stmt = new NonTerminal("Stmt");
                    NonTerminal Dec = new NonTerminal("Dec");
                    NonTerminal Datattype = new NonTerminal("Datatype");
                    NonTerminal Def = new NonTerminal("Def");
                    NonTerminal Var = new NonTerminal("Var");
                    NonTerminal Const = new NonTerminal("Const");
                    this.Root = Stmt;
                    ////3. BNF Rules
                    Stmt.Rule = "{"+Dec+"}";
                    Dec.Rule = Datattype + Def + ";";
                    Def.Rule = identifier | identifier + "=" + number;

                    //MarkPunctuation(""); ;
                   Datattype.Rule = ToTerm("int") | "char" | "float";
}

And in my form_load event I have

       ExpressionGrammar ex = new ExpressionGrammar(); 
       //Grammar grammar = new ExpressionGrammar();
       Parser parser = new Parser(ex);
       ParseTree parseTree = parser.Parse("{int a=5;}");
       if (!parseTree.HasErrors())
       {
            //foreach (string p in parseTree.) { }
            MessageBox.Show(parseTree.Status.ToString());
           // ParseTreeNodeList ls = new ParseTreeNodeList();
            //ls.Add(parseTree.Root);

       }
       else 
       {
           MessageBox.Show("Error in parsing"); 
       }

and i am getting parsed message so it work fine now i want to generate parse tree. How can i do so?


回答1:


You don't need to generate it, it's done for you. The ParseTree contains necessary information. This next code will print out the tree into console:

public static void PrintParseTree(ParseTreeNode node, int index = 0, int level = 0)
{
    for (var levelIndex = 0; levelIndex < level; levelIndex++)
    {
        Console.Write("\t");
    }

    Console.WriteLine(node + "[" + index + "]");

    var childIndex = 0;
    foreach (var child in node.ChildNodes)
    {
        PrintParseTree(child, childIndex, level + 1);
        childIndex++;
    }
}

and the usage would be PrintTree(parseTree.Root)

See Irony - Language Implementation Kit/Introduction for more information.



来源:https://stackoverflow.com/questions/26944857/how-to-generate-and-display-parsetree-for-an-expression-in-c-sharp-using-irony

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!