由于左递归导致的ANTLR失败。怎么解决?

时间:2014-11-26 17:25:17

标签: recursion antlr ll left-recursion

这是SQL select语句的简单语法

grammar SQL;
@rulecatch {
    //We want to stop parsing when SyntaxException is encountered
    //So we re-throw the exception
    catch (SyntaxException e) {
        throw e;
    }
}

eval 
    :  sql_query
    ;

sql_query
    : select_statement from_statement
    | select_statement from_statement where_statement
    ;

select_statement
    : 'select' attribute_list
    ;

from_statement
    : 'from' table_name
    ;

where_statement
    : 'where' attribute_name operator constant
    ;

attribute_list
    : '*'
    | attribute_name
    | attribute_name ',' attribute_list?
    ;

table_name
    : string_literal
    ;

attribute_name
    : string_literal
    ;

operator
    : '=' | '!=' | '>' | '>=' | '<' | '<=' 
    ;

constant
    : INTEGER
    | '"' string_literal '"'
    ;

fragment DIGIT: '0'..'9';
INTEGER: DIGIT+ ; 
fragment LETTER: 'a'..'z'|'A'..'Z';
string_literal: LETTER | LETTER string_literal;
WS : (' ' | '\t' | '\n' | '\r' | '\f')+  {$channel=HIDDEN;};

该工具唠叨sql_query定义以及attribute_list定义。老实说,我的代码中没有看到任何左递归。

有人可以解释发生了什么吗?

1 个答案:

答案 0 :(得分:1)

不,ANTLR没有说你的语法是递归的。它抱怨一些规则由于递归规则调用而产生非LL(*)决策。重写以下规则如下,你会没事的:

sql_query
    : select_statement from_statement where_statement?
    ;

attribute_list
    : '*'
    | attribute_name (',' attribute_list?)?
    ;