根据您的 Antlr 语法区分不同输入类型的最简单方法是什么?

What's the easiest way to distinguish different input types based on your Antlr grammar?

在我的语法中有如下规则:

set_stmt
:SET  ID (DOT ID)?  TO  setExpr NEWLINE+
;

setExpr
: arithExpr
| ID (DOT ID)?
| STRINGLITERAL
; 

对于如下不同的输入类型,

set id to id
set id to ""
set id to id.id
set id to arithExpr

set id.id to id
set id.id to ""
set id.id to id.id
set id.id to arithExpr

我必须在访问者中实现不同的逻辑 class。对我来说最简单的方法是什么?

首先分解你的语法:

set_stmt
:SET  ID TO  setExpr NEWLINE+ #setvar
|SET  ID DOT ID  TO  setExpr NEWLINE+ #setatt
;

setExpr
: arithExpr # number
| STRINGLITERAL # string
| ID # getvar
| ID DOT ID #getatt
;

这将为每个标记的备选方案生成一个具有访问方法的访问者。这使您可以在每个访问者方法中编写不同的代码。