Reputation: 3209
I am trying out a grammar in the ANTLR 4 book (p. 48-9), but the grammar isn't behaving as advertised.
The input is a series of integers. One integer indicates the number of following integers. For example, the first 2 in the following input indicates that there are two following integers and then the 3 indicates that there are three following integers:
2 9 10 3 1 2 3
At the bottom of this post is the grammar given in the book. When I run the ANTLR test rig (grun) with the -tree
flag, using the grammar and the above input:
grun Data file -tree
I get this incorrect output tree:
(file (group 2 (sequence 9 10 3)) (group 1 (sequence 2 3)))
Through some experimentation I discovered that if I change the grammar from using this semantic predicate:
{$i<=$n}?
to using this incorrect semantic predicate:
{$i<$n}?
then I get the correct output tree:
(file (group 2 (sequence 9 10)) (group 3 (sequence 1 2 3)))
I am baffled. Any ideas on why this is happening? Is it a bug in the test rig (grun)? Or (more likely) am I not understanding something about the workings of ANTLR's semantic predicates and actions?
grammar Data;
file: group+ ;
group: INT sequence[$INT.int] ;
sequence[int n]
locals [int i = 1;]
: ( {$i<=$n}? INT {$i++;} )* // match n integers
;
INT : [0-9]+ ;
WS : [ \t\r\n]+ -> skip ;
Upvotes: 0
Views: 462
Reputation: 720
Your local variable i
is starting off uninitialized (at 0) instead of 1 because of a bug introduced in ANTLR 4.3.
The bug is described in more detail at https://github.com/antlr/antlr4/issues/672.
Upvotes: 1