I'm trying to build an AST with ANTLR4. I have followed Lucas Trzesniewski's answer here: How to create AST with ANTLR4?, and it has ben very helpful. (I'm writing in C# using Sam Harwell's "Antlr Language Support").
My problem is that I have 3 rules, instead of the one 'expr' rule in above link and I do not know how to link them into one AST-builder. To understand my problem, here is a simple version of my grammar (with only 2 rules):
program
: dcl stmt EOF
;
dcl
: 'number' id=identifier #numberDcl
;
stmt
: id=identifier '=' expr #assignStmt
| IF expression ... #conditionStmt
;
expr
: left=expr op=('+' | '-') right=expr #infixExpr
;
Now I understand how to build an AST-builder for 'expr' and 'dcl', but I don't know how to build an AST-builder for 'program', so it is capable of visiting both rule (dcl and stmt), aswell as building an AST-builder for 'stmt', that is linked to 'expr'.
I have made my AST-nodes is similar fashion as Lucas Trzesniewski in his answer. What I'm trying to do I will explain in the following code:
internal class BuildAstDclVisitor : ParserBaseVisitor<DeclarationNode> {
public override DeclarationNode VisitProgram...
public override DeclarationNode VisitNumberDcl..
}
internal class BuildAstStmtVisitor : ParserBaseVisitor<StatementNode> {
public override StatementNode VisitProgram...
public override StatementNode VisitAssignStmt... //Unsure how link to an expression
}
internal class BuildAstExprVisitor : ParserBaseVisitor<ExpressionNode> {
public override ExpressionNode VisitInfixExpr...
}
Now in my 'AssignNode' I have an 'IdentifierNode' and an 'ExpressionNode' and I don't know how set my 'ExpressionNode' from my context aswell as in the end have an overall AST builder.
I hope I have been clear enough describing my problem. I have tried to find a solution but so far Lucas Trzesniewski's answer has been the best, but doesn't help me understand how to build my AST when I have more than one rule.
This is my first post, and hope I have done everything correctly, otherwise feel free to educate me how to use StackOverflow :)