特殊注释不能匹配词法分析器规则

特殊注释不能匹配词法分析器规则

本文介绍了特殊注释不能匹配词法分析器规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢解析的一个示例文本是这样的 -

One example text I like to parse is like this -

@comment {
    { something }
    { something else }
}

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

Basically "@comment" is the key to search, after that is a pair of matching braces. I do not need to parse what is between the braces. Since this is similar to C' multi-line comment, I have my grammar based on that:

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
    : '}'
    ;

但是在 ANTLRWORKS 中进行测试时,我立即收到了 EarlyExitException.

But in testing in ANTLRWORKS, I get a EarlyExitException immediately.

你看出哪里不对了吗?

推荐答案

我看到了两个问题:

  1. 您没有考虑 "@comment" 和第一个 "{" 之间的空格.请注意,空格放在 HIDDEN 通道上用于解析器规则,不是用于词法规则!
  2. 使用 ( options {greedy = false; }: . )+ 你只是匹配第一个 "}",而不是平衡大括号.
  1. you didn't account for the spaces between "@comment" and the first "{". Note that the spaces are put on the HIDDEN channel for parser rules, not for lexer rules!
  2. with ( options {greedy = false; }: . )+ you're just matching the first "}", not balanced braces.

试试这样的:

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)* '}'
 ;

这篇关于特殊注释不能匹配词法分析器规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 12:39