不承认令牌

时间:2015-02-09 03:30:51

标签: antlr antlr4

我最近将我的SQL解析器代码从paraboiled移动到ANTLR,这是非常顺利的迁移,但是当我的SQL包含AND或OR条件运算符时,我特意收到此错误消息。我正在分享样本语法,非常感谢任何帮助。

如果我尝试解析此示例sql "SELECT Name,Age,Salary FROM Employee WHERE Age=12 AND Dept=15"

我得到1:50不匹配的输入'AND'期待{,OPAND,OPOR}

但是,如果我用以下规则替换它然后它工作,我试图实现不区分大小写的解析

binaryConditionalExp:binaryExp |                        binaryConditionalExp CONDOPERATOR =('AND'|'OR')binaryConditionalExp |                        binaryparenExp;

/**
 * Define a grammar called Hello
 */
grammar SQLParser;


@header
{
    package somu.parsers;   
}




prog  : sqlsyntax;         // match keyword hello followed by an identifier


sqlsyntax : (selectclause fromclause whereclause) | (selectclause fromclause ) ;
selectclause : 'SELECT' columnclause;

columnclause : columnName (',' columnName)*;

columnName : columnLiteral;
columnLiteral : ID | sqlsyntax;

fromclause : 'FROM' tableclause;
tableclause : (tableclausealiaswithas | tableclauseplainalias | tableclausenoalias);  
tableclausenoalias  : ID | ;
tableclausealiaswithas : ID 'as' ID;
tableclauseplainalias : ID ID;

whereclause : 'WHERE' binarystmt;

binarystmt : binaryConditionalExp;
binaryExp: columnName OPERATOR columnName; 
binaryparenExp: '(' binaryConditionalExp ')';
binaryConditionalExp:  binaryExp | 
                       binaryConditionalExp CONDOPERATOR=(OPAND | OPOR) binaryConditionalExp | 
                       binaryparenExp;



ID : [a-zA-Z0-9]+ ;             // match identifiers
WS : [ \t\r\n]+ -> skip ; // skip spaces, tabs, newlines 
OPERATOR: [=><]+ ;
OPAND : A N D ;
OPOR : O R;

fragment DIGIT : [0-9];
fragment A : [aA];
fragment B : [bB];
fragment C : [cC];
fragment D : [dD];
fragment E : [eE];
fragment F : [fF];
fragment G : [gG];
fragment H : [hH];
fragment I : [iI];
fragment J : [jJ];
fragment K : [kK];
fragment L : [lL];
fragment M : [mM];
fragment N : [nN];
fragment O : [oO];
fragment P : [pP];
fragment Q : [qQ];
fragment R : [rR];
fragment S : [sS];
fragment T : [tT];
fragment U : [uU];
fragment V : [vV];
fragment W : [wW];
fragment X : [xX];
fragment Y : [yY];
fragment Z : [zZ];

1 个答案:

答案 0 :(得分:2)

由于规则的排序,词法分析器将AND视为标识符,而不是关键字。如果将词法分析器规则部分更改为以下内容,则字符串“AND”将被正确标记为OPAND。

// match RESERVED WORDS first
OPAND : A N D ;
OPOR : O R;

// match IDENTIFIERS etc.
ID : [a-zA-Z0-9]+ ;
WS : [ \t\r\n]+ -> skip ; 
OPERATOR: [=><]+ ;
相关问题