Antlr 特殊注释不能与lexer规则匹配

Antlr 特殊注释不能与lexer规则匹配,antlr,Antlr,我喜欢解析的一个文本示例如下- @comment { { something } { something else } } 基本上,@comment是搜索的关键,之后是一对匹配的大括号。我不需要解析大括号之间的内容。由于这类似于C'多行注释,因此我的语法基于此: grammar tryit; tryit : top_cmd ; WS : ('\t' | ' ')+ {$channel = HIDDEN;}; New_Line : ('\r' | '\

我喜欢解析的一个文本示例如下-

@comment {
    { something }
    { something else }
}
基本上,@comment是搜索的关键,之后是一对匹配的大括号。我不需要解析大括号之间的内容。由于这类似于C'多行注释,因此我的语法基于此:

grammar tryit;


tryit : top_cmd 
        ;

WS : ('\t' | ' ')+  {$channel = HIDDEN;};

New_Line : ('\r' | '\n')+   {$channel = HIDDEN;};

top_cmd :cmds 
        ;

cmds
    : cmd+
    ;

cmd
    : Comment
    ;

Comment
    : AtComment    Open_Brace  ( options {greedy = false; }: . )+  Close_Brace
    ;

AtComment
    : '@comment'
    ;

Open_Brace
    : '{'
    ;

Close_Brace
    : '}'
    ;
但在AntlWorks中进行测试时,我立即得到了一个EarlyExit异常


你知道怎么回事吗?

我看到两个问题:

  • 您没有考虑
    “@comment”
    和第一个
    “{”
    之间的空格。请注意,这些空格是放在解析器规则的隐藏通道上,而不是放在lexer规则的隐藏通道上
  • 使用
    (选项{greedy=false;}:.)+
    只匹配第一个
    “}”
    ,而不是平衡大括号
  • 请尝试以下方法:

    tryit
     : top_cmd 
     ;
    
    top_cmd
     : cmds 
     ;
    
    cmds
     : cmd+
     ;
    
    cmd
     : Comment
     ;
    
    Comment
     : '@comment' ('\t' | ' ')* BalancedBraces
     ;
    
    WS
     : ('\t' | ' ')+  {$channel = HIDDEN;}
     ;
    
    New_Line
     : ('\r' | '\n')+   {$channel = HIDDEN;}
     ;
    
    fragment
    BalancedBraces
     : '{' (~('{' | '}') | BalancedBraces)* '}'
     ;
    

    我看到两个问题:

  • 您没有考虑
    “@comment”
    和第一个
    “{”
    之间的空格。请注意,这些空格是放在解析器规则的隐藏通道上,而不是放在lexer规则的隐藏通道上
  • 使用
    (选项{greedy=false;}:.)+
    只匹配第一个
    “}”
    ,而不是平衡大括号
  • 请尝试以下方法:

    tryit
     : top_cmd 
     ;
    
    top_cmd
     : cmds 
     ;
    
    cmds
     : cmd+
     ;
    
    cmd
     : Comment
     ;
    
    Comment
     : '@comment' ('\t' | ' ')* BalancedBraces
     ;
    
    WS
     : ('\t' | ' ')+  {$channel = HIDDEN;}
     ;
    
    New_Line
     : ('\r' | '\n')+   {$channel = HIDDEN;}
     ;
    
    fragment
    BalancedBraces
     : '{' (~('{' | '}') | BalancedBraces)* '}'
     ;