我有以下antlr4词法分析器语法,目的是如果字符串不以' - '开始,则从字符串生成令牌STRING_MODE。
我正在使用testAssertion code来实施预测测试。
因为我想为字符串本身添加更多代码,并希望添加其他前缀而不仅仅是' - '在适用不同规则的情况下,我想立即推出一种模式并继续在那里进行。
lexer grammar StrStrLexer;
@members {
public boolean testAssertion(int assertionMode, int passingRule) {
int index = _input.index();
int mark = _input.mark();
try {
LexerATNSimulator interp = new LexerATNSimulator(this, _ATN, _decisionToDFA, _sharedContextCache);
interp.copyState(_interp);
int result = interp.match(_input, assertionMode);
return result == passingRule;
} finally {
_input.seek(index);
_input.release(mark);
}
}
DETECT : { testAssertion(DETECT_STRING,DETECT_STRING_PASS) }? ->
pushMode(STRING);
mode DETECT_STRING;
DETECT_STRING_PASS: ~[-];
DETECT_STRING_FAIL: .;
mode STRING;
STRING_MODE : .+;
使用此语法接收每个输入字符错误消息,如:
token recognition error at: 'X'
如果我重写语法并删除pushMode,它可以正常工作:
lexer grammar StrStrLexer;
@members {
public boolean testAssertion(int assertionMode, int passingRule) {
int index = _input.index();
int mark = _input.mark();
try {
LexerATNSimulator interp = new LexerATNSimulator(this, _ATN, _decisionToDFA, _sharedContextCache);
interp.copyState(_interp);
int result = interp.match(_input, assertionMode);
return result == passingRule;
} finally {
_input.seek(index);
_input.release(mark);
}
}
STRING_MODE : { testAssertion(DETECT_STRING,DETECT_STRING_PASS) }? .+;
mode DETECT_STRING;
DETECT_STRING_PASS: ~[-];
DETECT_STRING_FAIL: .;