我想用antlr4解析數字(雙精度和整數),但未能成功。希望可以有人幫幫我。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}
[]
誰能告訴我什麼是錯的呢?
查看下面更新的答案。 – TomServo