保留空格并在ANTLR4中注释

保留空格并在ANTLR4中注释

问题描述:

当我在ANTLR4游览源包(https://pragprog.com/titles/tpantlr2/source_code)中运行InsertSerialID.java或ExtractInterfaceTool.java时,我发现输出中未包含所有空格和注释。所以输出源代码不能编译或读取。如何保持他们?保留空格并在ANTLR4中注释

嗯,我发现重定向到一个额外的通道将让他们在Token,而不是使用skip

WS : [ \t\r\n\u000C]+ -> channel(2) // -> skip 
    ; 

COMMENT 
    : '/*' .*? '*/' -> channel(2) // -> skip 
    ; 

LINE_COMMENT 
    : '//' ~[\r\n]* -> channel(2) // -> skip 
    ; 

它们保存在ParserRuleContext.getSourceInterval()Interval,虽然我不知道如何映射到Interval thier语法类型。