在简单的语法antlr4不匹配输入错误(Mismatched input error in simp

2019-07-17 11:13发布

我试图解析使用antlr4 SQL的一个简单的子集。

我的语法如下:

grammar Query;
query : select;
select : 'select' colname (','  colname)* 'from' tablename;
colname : COLNAME;
tablename : TABLENAME;
COLNAME: [a-z]+ ;
TABLENAME : [a-z]+;
WS : [ \t\n\r]+ -> skip ; // skip spaces, tabs, newlines

我用一个简单的Java应用程序,如下测试这样的:

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.tree.*;

public class Test {
    public static void main(String[] args) throws Exception {
        // create a CharStream that reads from standard input

        InputStream is = new ByteArrayInputStream("select one,two ,three from table".getBytes());

        ANTLRInputStream input = new ANTLRInputStream(is);

        // create a lexer that feeds off of input CharStream
        QueryLexer lexer = new QueryLexer(input);


        // create a buffer of tokens pulled from the lexer
        CommonTokenStream tokens = new CommonTokenStream(lexer);

        // create a parser that feeds off the tokens buffer
        QueryParser parser = new QueryParser(tokens);

        ParseTree tree = parser.query(); // begin parsing at init rule

        System.out.println(tree.toStringTree(parser)); // print LISP-style tree

    }
}

我得到的输出如下:

line 1:27 mismatched input 'table' expecting TABLENAME
(query (select select (colname one) , (colname two) , (colname three) from (tablename table)))

我不明白的是为什么解析器似乎是捡了“表”作为解析器树中的表名,但是呢我也得到一个错误抛出。 我在想什么?

谢谢

安德鲁

Answer 1:

你不能匹配相同的两个词法规则(至少不是在同一个模式/状态...):

...
COLNAME: [a-z]+ ;
TABLENAME : [a-z]+;
...

做到这一点,而不是:

grammar Query;
query     : select;
select    : 'select' colname (',' colname)* 'from' tablename;
colname   : ID;
tablename : ID;
ID        : [a-z]+;
WS        : [ \t\n\r]+ -> skip;


文章来源: Mismatched input error in simple antlr4 grammar
标签: antlr antlr4