This project has moved and is read-only. For the latest updates, please go here.

Got a grammar. Now what?

Oct 7, 2011 at 5:43 PM

I've had fun creating a grammar.

Now I need to build my domain-specific object graph from the parse tree. How do I do that? I just need confirmation that the following is the correct approach:

  foreach (ParseTreeNode node in tree.Root.ChildNodes.Where(node => node.Term.Name == "Declaration")) {
    variables.Add(new Variable(node.ChildNodes[1].Token.Text, node.ChildNodes[2].FirstChild.Token.Text)); 

It seems a little strange to be hardcoding indexes like this. Would you generally use constants to identify these indexes, or is there an alternative way?


ps Is there a twitter account I can follow? 

Oct 7, 2011 at 8:42 PM

Now it's up to you. You can use built-in facility to build AST (abstract syntax) nodes, similar to what interpreter/expression evaluator is doing. You need to define AstNode classes for your DSL and provide your grammar non-terminals with types of AST nodes.

In this case Irony parser will create the AST tree for you. There is one facility recently added, to identify child nodes for some AST node. The idea is that AST node set might be a generic set (like AST nodes in Irony Interpreter), but particular language might have constructs that map to this set with some specifics, like "if" expression has slightly different structure than assumed in IfAstNode. To align AST nodes with your language, you can set AstPartsMap property for a grammatic construct like non-terminal. See BnfTerm.AstPartsMap property, there's some explanation there.

Or you can implement your own construction by building parse tree visitors, or directly iterating the tree - like SearchGrammar does when converting search query.

Hope this helps