简体   繁体   English

ANTLR因左递归而失败。 怎么解决?

[英]ANTLR failure due to left recursion. How to solve?

Here is a simple grammar for an SQL select statement 这是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;};

The Tool is nagging about the sql_query definition as well as the attribute_list definition. 该工具正在讨论sql_query定义以及attribute_list定义。 Honestly I do not see any left recursion in my code to start with. 老实说,我在代码中没有看到任何左递归。

Could anyone explain what's going on? 谁能解释这是怎么回事?

No, ANTLR did not say your grammar is left recursive. 不,ANTLR没有说您的语法是递归的。 It complained about the fact that some rules have non-LL(*) decisions due to recursive rule invocations. 它抱怨说,由于递归规则调用,某些规则具有非LL(*)决策。 Rewrite the following rules as follows and you'll be alright: 如下重写以下规则,您会没事的:

sql_query
    : select_statement from_statement where_statement?
    ;

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM