ANTLR4:遵循什么设计模式?

问题描述

我有一个ANTR4规则“表达式”,可以是“数学”或“比较”,但是“比较”可以包含“数学”。这是一个具体的代码

expression
    : ID
    | maths
    | comparison
    ;

maths
    : maths_atom ((PLUS | MINUS) maths_atom) ? // "?" because in fact there is first multiplication then pow and I don't want to force a multiplication to make an addition
    ;

maths_atom
    : NUMBER
    | ID
    | OPEN_PAR expression CLOSE_PAR
    ;

comparison
    : comp_atom ((EQUALS | NOT_EQUALS) comp_atom) ?
    ;

comp_atom
    : ID
    | maths // here is the expression of interest
    | OPEN_PAR expression CLOSE_PAR
    ;
    

例如,如果我输入6作为输入,这对于分析树就很好了,因为它检测到maths。但是,在 Intellij Idea 的ANTLR4插件中,它将我的expression规则标记为红色-模糊。我应该告别一棵简短的分析树,只允许maths中的comparisonexpression到现在就不再那么模棱两可了吗?

解决方法

问题在于,当解析器看到6(即NUMBER)时,它有两种通过语法到达它的路径:

 expression - maths - maths_atom - NUMBER

 expression - comparison - comp_atom - NUMBER

这种模糊性会触发您看到的错误。

您可以通过展平解析器语法as shown in this tutorial来解决此问题:

start
    : expr | <EOF>
    ;
    
expr
    : expr (PLUS | MINUS) expr         # ADDGRP
    | expr (EQUALS | NOT_EQUALS) expr  # COMPGRP
    | OPEN_PAR expression CLOSE_PAR    # PARENGRP
    | NUMBER                           # NUM
    | ID                               # IDENT
    ;