我是antlr的初学者我试图在我的代码中使用访客,并按照网上的说明.但是,我发现访客没有进入我创建的方法.有人可以告诉我我做错了什么吗?
这是我的访客
import java.util.LinkedList; import org.antlr.v4.runtime.misc.NotNull; /* * To change this template,choose Tools | Templates * and open the template in the editor. */ /** * * @author Sherwood */ public class ExtractMicroBaseVisitor extends MicroBaseVisitor<Integer> { //LinkedList<IR> ll = new LinkedList<IR>(); //MicroParser parser; //System.out.println("11"); @Override public Integer visitPgm_body(@NotNull MicroParser.Pgm_bodyContext ctx){ System.out.println(ctx.getText()); return 467; } @Override public Integer visitProgram(@NotNull MicroParser.ProgramContext ctx){ System.out.println("11"); return 456; } }
如您所见,当输入方法“visitProgram”时,stdout应打印11.但是输出画面给了我什么(一个null类型).
这是我的主要代码:
import java.io.IOException; import org.antlr.v4.runtime.*; import org.antlr.v4.runtime.tree.*; /** * * @author Sherwood */ public class Compiler { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here //SymbolTable table = new SymbolTable(); try { ANTLRFileStream reader = new ANTLRFileStream("TestCases/step4_testcase3.micro"); MicroLexer lexer = new MicroLexer((CharStream)reader); TokenStream tokens = new CommonTokenStream(lexer); MicroParser parser = new MicroParser(tokens); parser.setErrorHandler(new MyErrorStrategy()); ParseTree tree = parser.program(); //ParseTreeWalker walker = new ParseTreeWalker(); // create standard walker //ExtractMicroBaseListener extractor = new ExtractMicroBaseListener(parser); //walker.walk(extractor,tree); // initiate walk of tree with listener ExtractMicroBaseVisitor visitor = new ExtractMicroBaseVisitor(); int t = visitor.visit(tree); //for(String str : extractor.table.checkDuplicate()){ // System.out.println("SHADOW WARNING " + str); //} //System.out.println(extractor.table.checkDuplicate().toString()); //System.out.println(extractor.table.toString()); //System.out.println("Accepted"); }catch (IOException e) { System.out.println("Not Accepted"); }catch(IllegalArgumentException e){ System.out.println(e.getMessage()); } } }
这是我的语法文件(部分):
grammar Micro; options { language = Java; } //Program program : ('PROGRAM' id 'BEGIN' pgm_body 'END') ; id : IDENTIFIER; pgm_body : (decl func_declarations); decl : (string_decl_list | var_decl_list)* ;
解决方法
如果你想要ANTLR4来访问孩子,你必须打电话给super.喜欢这个:
@Override public Integer visitPgm_body(@NotNull MicroParser.Pgm_bodyContext ctx){ super.visitPgm_body(ctx); System.out.println(ctx.getText()); return 467; } @Override public Integer visitProgram(@NotNull MicroParser.ProgramContext ctx){ super.visitProgram(ctx); System.out.println("11"); return 456; }
你必须考虑在哪里放你的逻辑:超级或之后.