我有以下Antlr4语法:
grammar Smarty;
/*
* Parser Rules
*/
parse: smartyBody
;
smartyBody: include
| bodyText?
;
include: INCLUDE fileName CB
;
bodyText: BODY_TEXT
;
fileName: FILENAME
;
/*
* Lexer Rules
*/
COMMENT: '{*' .*? '*}' -> skip;
INCLUDE: '{include' SPACE+ 'file='?;
BODY_TEXT: ANY_CHAR+;
CB: SPACE? '}';
FILENAME: ''' FILE_NAME '''
| '"' FILE_NAME '"';
SPACE: [ t];
NEW_LINE: [rn]+ -> skip;
fragment FILE_NAME: PATH_CHARACTERS+;
fragment PATH_CHARACTERS: ~[u0000-u001f"*:<>?\/|u007f-uffff];
fragment ANY_CHAR: [ -~];
现在,如果我尝试使用评论,它们会被传递回来,而不是被吞噬。
传递给分析器的文本:{*{include file='xxxxx'}*}zzzzzz
如果我重写EnterBodyText并将文本字符串传递给解析器,则侦听器中的text变量将获得包含注释的原始文本。
internal partial class BaseListener : SmartyBaseListener
{
public override void EnterBodyText( SmartyParser.BodyTextContext context )
{
var Text = context.BODY_TEXT().GetText();
// Text gets: {* {include file='xxxxx'} *} zzzzzzzz
// not just zzzzzzzz
}
}
感谢您的帮助。
ANTLR的lexer将尽可能多地匹配。因此,输入CCD_ 1与CCD_ 2完全匹配。
解决这个问题的一种方法是将BODY_TEXT
改为解析器规则:
body_text: ANY_CHAR+;
...
COMMENT: '{*' .*? '*}' -> skip;
...
// No fragment anymore. And keep this as the last lexer rule!
ANY_CHAR: [ -~];