ANTLR4 注释、预处理器或指令解析

ANTLR4 comments, preprocessor or directives parsing

我需要解析 ANTLR4 中的 Delphi 指令。例如,

{$MODE Delphi}{$ifdef net}
net,
{$else}
NewKernel,
{$ifndef st}
{$ifndef neter}
hyper,
{$endif}
{$endif}
{$endif}
但同时,在 Delphi 中,花括号内的 { } 可能是注释。那么,如何创建 ANTLR4 语法,它的工作方式如下:"file: not to parse text { parsing } not to parse text ;" ?

很难从 Q 的措辞中确定。听起来您正在寻找:

directive : LDrctv .... RBrace ; // replace .... with appropriate rule terms
comment   : LBrace .*? RBrace  ;
skip      : . ; // aggregates all tokens not included in above rules

LDrctv : '{$' ;
LBrace : '{'  ;
RBrace : '}'  ;

// other token rules

更新:skip 规则捕获所有未被其他规则使用的令牌。如果只对 directive 规则感兴趣,则只需要评估解析树中相应的 DirectiveContext 节点。