ANTLR3解析表达式

时间:2016-01-13 05:06:07

标签: antlr3 antlrworks

我想通过antlr3解析表达式,但遇到了一些错误。以下是我的语法文件:

grammar Expr;

options {
  output       = AST;
  ASTLabelType = CommonTree;
  language     = Java;
  k =3;
// backtrack=true;
}

tokens {
    DIVIDE = '/' ;
    PLUS = '+' ;
    MINUS = '-' ;
    STAR = '*' ;
    MOD = '%' ;
    AMPERSAND = '&' ;
    TILDE = '~' ;
    BITWISEOR = '|' ;
    COMMA = ',';
    DOT = '.';
    LPAREN = '(' ;
    RPAREN = ')' ;
    THRESHOLD = '>';
    EQUIValence = '=';  
    AND = 'AND' ;
    OR = 'OR' ;
    TRUE = 'TRUE';
    FALSE = 'FALSE';
    DOUBLE_QUOTE = '\"';
    SINGLE_QUOTE = '\'';
}


// LITERALS
fragment
Letter
    : 'a'..'z' | 'A'..'Z'
    ;

fragment
Digit
    :
    '0'..'9'
    ;

fragment
Exponent
    :
    ('e' | 'E') ( PLUS|MINUS )? (Digit)+
    ;

Number
    :
    (Digit)+ ( DOT (Digit)* (Exponent)? | Exponent)?
    ;

fragment
UnquotedString
    :  
      ( ~(SINGLE_QUOTE|DOUBLE_QUOTE|' '|'\t'|'\n'|LPAREN|RPAREN|COMMA))+
    ;

fragment
QuotedLiteral
    :
    DOUBLE_QUOTE ( ~(DOUBLE_QUOTE|'\\') | ('\\' .) )* DOUBLE_QUOTE 
    ;

Parameter
    :
    UnquotedString | QuotedLiteral
    ;

WS  :  (' '|'\r'|'\t'|'\n'|'\u000C')* {$channel=HIDDEN;}
    ;


/********************************************rule******************************************/
searchCondition
    :
    // subCondition (( AND | OR ) subCondition)? EOF?
    andExpr (OR^ andExpr)*
    ;

andExpr
    :
    subCondition (AND^ subCondition)*
    ;

subCondition
    : 
      LPAREN searchCondition RPAREN 
    | atom  
    ;

atom returns [QueryBuilder result]
    :
    //p0=expression  (comparisonOperator expression)?
    p0=expression
    {
      $result = $p0.result;
    }        
    ;

comparisonOperator
    :
    THRESHOLD | EQUIValence
    ;

expression returns [QueryBuilder result]
    : 
    //p0=subExpression (binaryOperator subExpression)*
    p0=subExpression
    ;

subExpression returns [QueryBuilder result]
    :
      p0=Parameter 
    ;

输入QQ OR (UU AND WW) OR XX时,解析结果不完整,右括号后的内容不匹配。

enter image description here

1 个答案:

答案 0 :(得分:0)

最终的AST似乎很好。这只是antlworks的解释功能无法为您显示。正如它所说:“它不会运行动作也不会评估句法谓词”。虽然你没有明确地提到这些,但你有一个递归(searchCondition-> andExpr-> subCondition-> searchCondition)。

您是否尝试过调试器? 生成的AST将如下所示: enter image description here