如何以非递归方式编写Antlr规则? [英] How to write Antlr rules in a non-recursive way?

查看:62
本文介绍了如何以非递归方式编写Antlr规则?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要解析以下表达式

and(true, false)
or(true, false, true)
not(or(true, false, true))
and(and(true, false), false)
or(or(true, false, true), true)

到目前为止,我有以下语法

so far I have the following grammar

expr
    : orExpr
    ;

orExpr
    : OR '(' andExpr (',' andExpr)+ ')'
    | andExpr
    ;

andExpr
    : AND '(' equalityExpr (',' equalityExpr)+ ')'
    | equalityExpr
    ;

equalityExpr
    : comparison ((EQUALS | NOT_EQUALS) comparison)*
    ;

comparison
    : notExpr ((GREATER_THAN_EQUALS | LESS_THAN_EQUALS | GREATER_THAN | LESS_THAN ) notExpr)?
    ;

notExpr
    : NOT '(' expr ')'
    | primary
    ;

primary
    : '(' expr ')'
    | true
    | false
    ;

我无法使用上述语法解析and(and(true, false), false)吗?我要去哪里错了?

I am not able to parse and(and(true, false), false) with the above grammar? where am I going wrong?

请假定在AND OR NOT之间有优先级(尽管我知道这看起来没有必要)

Please assume there is precedence between AND OR NOT (although I understand it may look not necessary)

推荐答案

但是现在,我需要能够解析true=and(5=5, 4=4, 3>2),反之亦然and(5=5, 4=4, 3>2)=true吗?

在这种情况下,绝对没有必要使事情复杂化.您所需要做的就是这个:

In that case, there is absolutely no need to complicate things. All you have to do is this:

grammar Test;

parse
 : expr EOF
 ;

expr
 : '(' expr ')'
 | OR '(' expr (',' expr)+ ')'
 | AND '(' expr (',' expr)+ ')'
 | NOT '(' expr ')'
 | expr (LT | LTE | GT | GTE) expr
 | expr (EQ | NEQ) expr
 | TRUE
 | FALSE
 | INT
 ;

LT    : '<';
LTE   : '<=';
GT    : '>';
GTE   : '>=';
NEQ   : '!=';
EQ    : '=';
NOT   : 'not';
TRUE  : 'true';
FALSE : 'false';
AND   : 'and';
OR    : 'or';

INT
 : [0-9]+
 ;

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

这篇关于如何以非递归方式编写Antlr规则?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆