ANTLR4 解析结束时打印

ANTLR4 Print at the end of parsing

有没有办法在解析结束时在 ANTLR4 中打印@members?

grammar test;
@members{
int count = 0;
} 

sentence :  (a..z|A..Z)* r;
r        :  [\r\n]+ {count++;}; 

我不确定我是否答对了你的问题,但正如 StephanA 所说,你的语法不符合 ANTLR4。我稍微修改了你的语法:

grammar Test;

@members{
int count = 0;
} 

sentence :  WORD (r WORD)* {System.out.println(count);};
r        :  WS {count++;};

WORD : ('a'..'z'|'A'..'Z')+;
WS :  [ \r\n]+;

此语法将接受 This is a test(末尾为 count = 3)但会拒绝 This is a testThis is a test(末尾为 WS ).我添加了一个代表解析树根的 root 规则,并在此规则末尾显示 count

这是你想要的吗?

编辑

我只是重构了语法,root 规则实际上并不是很有用(我的错)。