Java 如何使用antlr4访客

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19472986/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 17:34:28  来源:igfitidea点击:

how to use antlr4 visitor

javaparsingantlr4visitor

提问by Sherwood Lee

I am a beginner of antlr. I was trying to use visitor in my code and following the instruction on the net. However, I found out that the visitor was not entering the method I create at all. May anyone tell me what I did wrong?

我是 antlr 的初学者。我试图在我的代码中使用访问者并按照网上的说明进行操作。但是,我发现访问者根本没有进入我创建的方法。谁能告诉我我做错了什么?

This is my visitor:

这是我的访客:

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;
    }

}

As you can see, the stdout should print 11 when the method "visitProgram" was entered. But the output screen gave me nothing (a null type).

如您所见,输入方法“visitProgram”时,标准输出应打印 11。但是输出屏幕什么也没给我(空类型)。

This is my main code:

这是我的主要代码:

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());
            }
    }
}

This is my grammar file(partially):

这是我的语法文件(部分):

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)* ;

回答by mikea

You have to call superif you want ANTLR4 to visit children. Like this:

super如果你想让ANTLR4探望孩子,你必须打电话。像这样:

@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;
}

You have to think about where to put your logic: before superor after.

你必须考虑把你的逻辑放在哪里:之前super还是之后。