问题
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