永远不会调用Antlr访问者方法

时间:2014-12-17 11:07:07

标签: antlr antlr4 visitor

我尝试创建一种简单的语言,可以使用预定义的const来评估if / else if / else语句和一些算术运算。定义如下:

grammar test;

ifStatement
:
    ifPart elseIfPart* elsePart
;

ifPart
:
    'if (' logicalExpression ') then ' retVal=basicElement
;

elseIfPart
:
    ' else if (' logicalExpression ') then ' retVal=basicElement
;

elsePart
:
    ' else ' retVal=basicElement
;

logicalExpression 
:
    logicalExpression ' and ' logicalExpression #andLogicalExpression
    |logicalExpression ' or ' logicalExpression #orLogicalExpression
    | compareExpression #compareLogicalExpression
    | '(' logicalExpression ')' #parensLogicalExpression
;

compareExpression
:
    basicElement '' basicElement #gt
    | basicElement '=' basicElement #eq
;


basicElement
:
    operation
    | atomicElement
;

operation
:
    operation op=('*'|'/') operation #mulDiv |
    operation op=('+'|'-') operation #addSub |
    atomicElement #atomic |
    '(' operation ')' #operationParens
;

atomicElement
:
    INT #decimal
    | 'resVal1' #reservedVariable
    | 'resVal2' #reservedVariable
;

INT
:
    [-]?[0-9]+('.'[0-9]+)? 
;

WS
:
    [ \t\r\n]+ -> skip
; // skip spaces, tabs, newlines

我生成了一个访问者并创建了一个测试句子,如下所示:

    if (3+3=6 or 12*3=37) then 10*10 else 4+1

它返回5,这是错误的。经过一些调试后,我发现从不调用visitOrLogicalExpression方法,而是调用了visitCompareLogicalExpression两次。我的语言定义有什么问题?

提前谢谢你!

1 个答案:

答案 0 :(得分:1)

语言定义没问题。我可以通过修改Visitor类来解决上述问题。

visitIfPartvisitElseIfPart方法(处理ifelse if节点的子树)中,我必须将visitChildren(ctx.logicalExpression())方法更改为{ {1}},因此我的代码能够捕获复合逻辑表达式。