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?
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:and the usage would be
PrintTree(parseTree.Root)
See Irony - Language Implementation Kit/Introduction for more information.