如何使用Irony为C#中的表达式生成和显示ParseTree? [英] How to Generate and display ParseTree for an expression in C# using Irony?

查看:213
本文介绍了如何使用Irony为C#中的表达式生成和显示ParseTree?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用反讽来生成和显示上下文无关文法,到目前为止,我已经能够通过以下代码编写上下文无关文法

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

在我的form_load事件中,我有

       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?

推荐答案

您不需要生成它,它已为您完成. ParseTree包含必要的信息.接下来的代码将把树打印到控制台中:

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++;
    }
}

,用法为PrintTree(parseTree.Root)

有关更多信息,请参见 Irony-语言实施工具包/简介.

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

这篇关于如何使用Irony为C#中的表达式生成和显示ParseTree?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆