是否可以禁止自递归?

Is it possible to disallow self-recursion?

我有规则:

expression
   : //...
   | expression (relative_operator expression)+
   | //...
   ;

理想情况下,当我输入 1=1=1 时,它会生成 expression(1, =, 1, =, 1) 树。然而,实际上它会产生 expression(1, =, expression(1, =, 1))。这是因为它更喜欢递归解析而不是一行。是否可以明确地告诉规则它要么不能递归自身,要么在尝试递归自身之前更愿意遵守 +/*

Is it possible to explicitly tell a rule that it either can't recurse on itself, or it should prefer to obey the +/* before trying to recurse on itself?

不,您必须像这样重写语法:

expr
 : add
 ;

add
 : mult ( ( '+' | '-' ) mult )*
 ;

mult
 : unary ( ( '*' | '/' ) unary )*
 ;

unary
 : '-'? atom
 ;

atom
 : '(' expr ')'
 | NUMBER
 | VARIABLE
 ;

它将像 1 + 2 + 3 * 4 * 5 / 6 这样的输入解析为以下树: