Reputation: 2578
I have this grammar:
grammar Test;
node:
BEGIN BLOCK
name=STRING
noOfKvp=INT
(
key_value_pair |
hasOptionalThing=OPTIONAL_THING
)*
END BLOCK
;
key_value_pair
: key=number value=number
;
number
: INT | FLOAT
;
BEGIN : 'BEGIN';
END : 'END';
BLOCK : 'BLOCK';
OPTIONAL_THING : 'OPTIONAL_THING' ;
STRING : '"' .*? '"';
INT
: MINUS? DIGIT+
;
FLOAT
: MINUS? ('0'..'9')+ '.' ('0'..'9')* EXPONENT? | MINUS? '.' ('0'..'9')+ EXPONENT? | MINUS? ('0'..'9')+ EXPONENT
;
fragment MINUS
: '-'
;
fragment EXPONENT
: ('e'|'E') ('+'|'-')? ('0'..'9')+
;
DIGIT
: '0'..'9'
;
WS : ( ' ' | '\t' | '\r' | '\n')+ -> skip;
And this sample file:
BEGIN BLOCK
"Blockname"
5
1 5
2 7.5
3.3 10
4 12.5
5.2 15
END BLOCK
Now when I parse it I don't seem to get the key value pairs in my listener:
public class MyListener extends TestBaseListener {
@Override
public void exitNode(TestParser.NodeContext ctx) {
super.exitNode(ctx);
List<TestParser.Key_value_pairContext> keyValuePairs = ctx.key_value_pair();
System.out.println(keyValuePairs.size());
}
}
Output is 0. I don't understand why...
edit: This is my code to run the parser
public static void main(String[] args) throws IOException {
ANTLRFileStream stream = new ANTLRFileStream("C:\\temp\\SimpleGrammarTest.txt");
TestLexer lexer = new TestLexer(stream);
TokenStream tokenStream = new CommonTokenStream(lexer);
TestParser parser = new TestParser(tokenStream);
parser.setBuildParseTree(false);
parser.addParseListener(new MyListener());
parser.node();
}
Upvotes: 2
Views: 605
Reputation: 170158
I cannot reproduce this. Given the class:
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.tree.*;
public class Main {
public static void main(String[] args) throws Exception {
TestLexer lexer = new TestLexer(new ANTLRFileStream("test.txt"));
// `test.txt` contains your input, btw
TestParser parser = new TestParser(new CommonTokenStream(lexer));
ParseTree tree = parser.node();
ParseTreeWalker walker = new ParseTreeWalker();
walker.walk(new MyListener(), tree);
}
}
and testing at follows:
java -cp antlr-4.2.1-complete.jar org.antlr.v4.Tool Test.g4 javac -cp .:antlr-4.2.1-complete.jar *.java java -cp .:antlr-4.2.1-complete.jar Main
I see 5
being printed on my console.
Upvotes: 2