Reputation: 988
While learning ANTRL4 I tried to parse very basic pattern, which can have one or more digits.
Abc.g4
grammar Abc;
@header {
package antlr4;
}
fragment DIGIT : [0-9]+;
log : DIGIT;
Main method
public class OwnParser extends AbcBaseListener
{
public static void main(String args[])
{
String javaClassContent = "9";
AbcLexer abcLexer = new AbcLexer(CharStreams.fromString(javaClassContent));
CommonTokenStream tokens = new CommonTokenStream(abcLexer);
AbcParser parser = new AbcParser(tokens);
ParseTree tree = parser.log();
ParseTreeWalker walker = new ParseTreeWalker();
OwnParser listener= new OwnParser();
walker.walk(listener, tree);
}
}
But when I execute this, it says:
line 1:0 token recognition error at: '9'
line 1:1 missing DIGIT at ''
rule entered: <missing DIGIT>
Am I missing something ?
Upvotes: 0
Views: 87
Reputation: 370455
You get an error on the input 9
because you didn't define any lexer rule that matches 9
. In fact, you didn't define any lexer rules at all. Note that you defined DIGIT
as a fragment only and fragments don't produce tokens.
You should also have gotten a warning "implicit definition of token DIGIT in parser" in your grammar.
If you remove the fragment
keyword from the definition of DIGIT
, both of those problems will go away.
Upvotes: 2