Antlr错误:输入'<eof>'没有可行的替代方案

时间:2017-03-20 13:46:42

标签: java antlr antlr4

我的antlr语法没有返回任何错误,但是当我尝试用我的java测试程序解析它时,它返回上面的错误。我对antlr编程比较陌生。

我的SQLite.g4是:

import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.misc.NotNull;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import java.util.ArrayList;
import java.util.List;

public class Main {

    public static void main(String[] args) throws Exception {

        // The list that will hold our function names.
        final List<String> functionNames = new ArrayList<String>();

        // The select-statement to be parsed.
        String sql = "SELECT log AS x FROM t1 \n" +
                "GROUP BY x\n" +
                "HAVING count(*) >= 4 \n" +
                "ORDER BY max(n) + 0";

        // Create a lexer and parser for the input.
        SQLiteLexer lexer = new SQLiteLexer(new ANTLRInputStream(sql));
        SQLiteParser parser = new SQLiteParser(new CommonTokenStream(lexer));

        // Invoke the `select_stmt` production.
        ParseTree tree = parser.select_stmt();

        // Walk the `select_stmt` production and listen when the parser
        // enters the `expr` production.
        ParseTreeWalker.DEFAULT.walk(new SQLiteBaseListener(){

            @Override
            public void enterExpr(@NotNull SQLiteParser.ExprContext ctx) {
                // Check if the expression is a function call.
                if (ctx.function_name() != null) {
                    // Yes, it was a function call: add the name of the function
                    // to out list.
                    functionNames.add(ctx.function_name().getText());
                }
            }
        }, tree);

        // Print the parsed functions.
        ParseTree treetry  = parser.ordering_term();

         ParseTreeWalker.DEFAULT.walk(new SQLiteBaseListener(){

            @Override
            public void enterExpr(@NotNull SQLiteParser.ExprContext ctx) {
                // Check if the expression is a function call.
                //if (ctx.function_name() != null) {
                    // Yes, it was a function call: add the name of the function
                    // to out list.
                    //functionNames.add(ctx.function_name().getText());
                //}

                System.out.println("Helloss");
            }
        }, treetry);

    }
}

我的Main.java是:

ProcessBuilder ps = new ProcessBuilder("perl","test.pl","test.txt","|", "test1.pl",">","result.txt");

1 个答案:

答案 0 :(得分:0)

您正在使用select_stmt而不是第一条规则(parse)开始解析。
由于EOF令牌不属于select_stmt,因此您收到了错误消息。

尝试在最顶层的规则中启动解析器并查看错误是否仍然存在(不应该):

ParseTree tree = parser.parse();