【发布时间】:2017-12-07 18:49:54
【问题描述】:
我正在尝试使用 antlr4 解析数字(双精度和整数),但未能成功。希望有人可以帮助我。
我的测试代码是:
public class TestAntlr4 {
@Test
public void test() throws IOException {
String input = "30";
CharStream inputCharStream = new ANTLRInputStream(new StringReader(input));
// create a lexer that feeds off of input CharStream
TokenSource tokenSource = new GqlLexer(inputCharStream);
// create a buffer of tokens pulled from the lexer
TokenStream inputTokenStream = new CommonTokenStream(tokenSource);
// create a parser that feeds off the tokens buffer
TestAntlr4Parser parser = new TestAntlr4Parser(inputTokenStream);
parser.removeErrorListeners(); // remove ConsoleErrorListener
parser.addErrorListener(new VerboseListener());
parser.getInterpreter().setPredictionMode(PredictionMode.LL_EXACT_AMBIG_DETECTION);
NumberContext context = parser.number();
System.out.println(context.toString());
}
}
我的antlr4语法是:
grammar TestAntlr4 ;
number
: INT_NUMBER
| DOUBLE_NUMBER ;
DOUBLE_NUMBER
: ('+'|'-')? INTEGER '.' INTEGER? ;
INT_NUMBER
: ('+'|'-')? INTEGER ;
WS
: [ \t\r\n]+ -> skip ; // skip spaces, tabs, newlines
fragment INTEGER
: '0'
| '1'..'9' ('0'..'9')* ;
fragment DIGIT
: [0-9] ;
结果是:
rule stack: [number]
line 1:0 at [@0,0:1='30',<31>,1:0]: mismatched input '30' expecting {DOUBLE_NUMBER, INT_NUMBER}
[]
谁能告诉我这有什么问题?
【问题讨论】:
-
查看下面的更新答案。