ANTLR 4 and AST visitors

前端 未结 2 2077
情话喂你
情话喂你 2021-02-08 06:38

I\'m trying to use ASTs with ANTLR4, with this files:

Builder.java

import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CharStream;
         


        
2条回答
  •  佛祖请我去吃肉
    2021-02-08 07:34

    A tree label you could use, to set the context of the parse and then walks the leaves of the observed graph with a visitor class and trigger methods in order to create actions from the expressions in the language source code. Thus, at the initial visitation, the listener does not process the actual visitor pattern. The actual visitor pattern and the processing through visitation is done by the methods of the expressionbase listener class extension.

    The listener identifies the expression:

    @Override public void enterListener(ExprParser.EXPR_CONTEXTContext ctx) { 
      //some code to view the compilation process
    }
    

    The expression rule gets a name label:

    'EXPR_CONTEXT' expression             # EXPR_CONTEXT //the tree label
    

    The expression walker is implemented:

    public class ExprWalker extends ExprBaseListener {
    
      @Override 
      public void enterListener(ExprParser.EXPR_CONTEXTContext ctx) { 
    
        java.util.List e = ctx.expression();
    
        System.out.println("EXPRESSION: " //print action
        + e.get(0).getText() + ", " //first element
        + e.get(1).getText() //second element
        + ", " + ... + ", " //number of elements
        + e.get(N).getText()); //last element
    
    }
    

    The main file then walks with the walker:

    ParseTree tree = parser.parse(); //parse the tree
    

    intermezzo: before applying the walker visitation pattern one may imagine tree segment optimisation- or processing patterns. The parsed tree could be handled here as a seperate induction of the source code tree. This approach enables more complicated code- and tree processing patterns.

    ParseTreeWalker walker = new ParseTreeWalker(); //get the walker
    walker.walk(new ExprWalker(), tree); //start visiting
    

提交回复
热议问题