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

AST Building with Terminals

Apr 25, 2016 at 4:40 PM
Edited Apr 26, 2016 at 9:41 AM

I have this in my grammar to enable me to set the AST builder for a terminal.
Dim bracedText = NewTerminal(Function() New QuotedValueLiteral("bracedString", "{", "}", TypeCode.String), GetType(StringExpr))

Private Function NewTerminal(Of TTerm As Terminal)(nodeCreator As Func(Of TTerm), astNodeType As Type) As TTerm

      Dim t = nodeCreator()
      t.AstConfig.NodeType = astNodeType
      Return t

End Function
However, I want to go one step further and be able to decide whether to instantiate a StringExpr or some other AST node dependent upon the contents between the braces. Previously I'd been creating specific NonTerminals to do this e.g.
bracedExpression.Rule =
       LBRACE + identifier + RBRACE Or
       LBRACE + functionExpression + RBRACE
I would then instantiate a StringExpr AST node for the identifier and a FuncExpr AST node for the function expression. Perhaps this is the better way to do this. But I am not sure.

What would I need to event handle/override on the terminal to enable me to decide which AST node I should chose dependent upon the contents of the string between the braces or should I stick with the bracedExpression-type approach?

If you could point me to some sample code, even better.

Many thx

Apr 30, 2016 at 10:19 PM
you could try using transient non-terminal(s), to end up with a single AST node that is either identifier or function. Something like:
idOrFunc.Rule = identifier | functionExpression;
bracedExpr = Lbrace + idOrFunc + RBrace;

MarkTransient(idOrFunc, braceExpr);

You provide AST node types for identifier and functionExpr, but not idOrFunc and bracedExpr - which are transient so should not have AST. At the end in the AST tree you should end up with AST node for one of functionExpr or identifier in all places where expected bracedExpr.
Try it, I did not test it, this is just from what I remember how it should work - and this is the case why transient nodes are there.
May 17, 2016 at 4:23 PM
Many thx. Very helpful . (Sorry it took so long to reply)