1

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 :)

Community
  • 1
  • 1
  • Welcome to SO. Your question is prefectly fine :-) (and I can assure you this is the first time ever I can say that for a first question here). However, I wonder why you want to create an AST at all. In order to evaluate expressions you can easily use the provided parse tree. In fact ASTs are inferior as they only show what input matched (you can get this info from the token stream already). Parse trees are much more, as they show what path the parse process has taken. My advice: get away from ASTs, now. – Mike Lischke Apr 28 '17 at 07:13
  • I'm following a course in school, and well it is more about learning and understanding what techniques you can use than it is what is most practically in the "real world". – Bastian RexLeo Bresson Apr 30 '17 at 21:25

0 Answers0