在 antlr4 的解析器中获取属性的索引

Getting the index of an attribute in parser in antlr4

我的语法看起来像

statement
     :  ME second_part
     {
           System.out.println($ME.getStartIndex());
           System.out.println($second_part.getStartIndex());
     }
     ;

ME   : 'me'
     ;
SPACES : [ \t\n\r] -> channel(HIDDEN);

我想得到我和second_part的起始索引。

当我运行上述antlr4语法

时出现错误

System.out.println($second_part.getStartIndex());

missing attribute access on rule reference second_part in $second_part

如何获取 second_part 的起始索引?

每个解析器规则都是一个 ParserRuleContext,它有一个 startstop 标记。所以,试试这个:

System.out.println($second_part.start.getStartIndex());