Reputation: 1334
I am trying to use antlr4 to parse number (double and integer), but fail to success. Hope some one can help me.
My Test code is:
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());
}
}
My antlr4 grammar is:
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] ;
The result is:
rule stack: [number]
line 1:0 at [@0,0:1='30',<31>,1:0]: mismatched input '30' expecting {DOUBLE_NUMBER, INT_NUMBER}
[]
Can anyone tell me what is wrong with this?
Upvotes: 2
Views: 84
Reputation: 7409
The grammar seems to be okay. Lexes and parses fine for me with input "30":
[@0,0:1='30',<INT_NUMBER>,1:0]
[@1,2:1='<EOF>',<EOF>,1:2]
Tried also with a double:
[@0,0:6='30.3343',<DOUBLE_NUMBER>,1:0]
[@1,7:6='<EOF>',<EOF>,1:7]
Parses just fine.
Now, in my environment I'm using the C# target, so my code is a little different from yours.
My (C#) code using the visitor pattern:
AntlrInputStream inputStream = new AntlrInputStream(stream);
Grammar1Lexer lexer = new Grammar1Lexer(inputStream);
CommonTokenStream tokenStream = new CommonTokenStream(lexer);
Grammar1Parser parser = new Grammar1Parser(tokenStream);
IParseTree tree = parser.number();
Grammar1Visitor visitor = new Grammar1Visitor();
visitor.Visit(tree);
Compiles and works just fine.
UPDATE:
I noticed that your lexer and your parser are named differently, could you have a simple copy/paste error? Usually when you generate the classes all are named uniformly based on your grammar's name.
Upvotes: 1