简体   繁体   English

如何在ANTLR语法中用括号定义逻辑运算符

[英]How to define logical operator with parenthesis in ANTLR grammar

I am defining a grammar in ANTLR that will express an expression which includes logical operator and parenthesis together. 我正在ANTLR中定义一个语法,该语法将表达一个包含逻辑运算符和括号的表达式。
Here is the grammar 这是语法

grammar simpleGrammar; 

/* This will be the entry point of the parser. */ 

parse 
    :   
        expression EOF 
    ; 
expression 
    :   
        expression binOp expression | ID | unOp (expression) | '(' expression ')' 
    ; 
binOp 
    : 
        ('AND' | 'OR')  
    ; 
unOp 
    : 
        'NOT' 
    ; 
ID      :   
        ('a'..'z' | 'A'..'Z')+  
    ; 

The defined grammar can able to express parse tree without parenthesis but when I input an example with parenthesis for example, (Apple OR Bananana)AND Orange It is showing MismatchedTokenException 定义的语法能够在没有括号的情况下表示语法分析树,但是当我输入带有括号的示例时,例如(Apple OR Bananana)AND Orange它显示MismatchedTokenException
So, It will be really appreciated if someone explains how to define the grammar in order to express the parenthesis. 因此,如果有人解释如何定义语法以表达括号,将不胜感激。

You forgot to tell ANTLR what to do with whitespace. 您忘了告诉ANTLR如何处理空白。 For example: 例如:

WS : [ \t\r\n] -> skip;

Add this and you grammar will work. 加上这个,语法就会起作用。

As a side note, your grammar has the same precedence for the AND and OR operators. 附带说明一下,您的语法对于ANDOR运算符具有相同的优先级。 And these operators have higher precedence than NOT . 这些运算符的优先级高于NOT As this goes against conventional rules, I'd advise you to write your expression rule like this instead: 由于这违反了常规规则,因此建议您这样编写expression规则:

expression 
    :   '(' expression ')'            # parenExp
    |   'NOT' expression              # notExpr
    |   expression 'AND' expression   # andExpr
    |   expression 'OR' expression    # orExpr
    |   ID                            # atomExpr
    ;

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

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