本文介绍了特殊注释不能匹配词法分析器规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想解析的一个示例文本就是这样-
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.
您看到什么地方了吗?
推荐答案
我看到了两个问题:
- 您没有考虑
"@ comment"
和第一个"{"
之间的空格.请注意,对于解析器规则,空格位于HIDDEN通道上;对于词法分析器规则,空格位于 不是 ! - 带有
(options {greedy = false;}:.)+
,您只是在匹配第一个}"
,而不是大括号.
- 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! - 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)* '}'
;
这篇关于特殊注释不能匹配词法分析器规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!