[antlr-interest] Identifiers are not local to alternatives?

Raphael Reitzig r_reitzi at cs.uni-kl.de
Sun Jun 29 14:12:21 PDT 2008


Hi!

Please consider the following (pathological) grammar:

***

grammar Test;

test 
	:	v=a { System.out.println($v.s); }
	|	v=b { System.out.println($v.i); };
	
a returns [String s]	:	'A'  { $s = "a"; };
b returns [Integer i]	:	'B' { $i = 9; };

***

To me, ANTLR's syntax is suggesting that the identifier 'v' is declared
once in the first and once in the second alternative of rule 'test'. In the
generated code, however, this is not the case. Although grammar checking
(using ANTLRWorks here) succeeds, I am confronted with a not very helpful
error message during code generation:

*** error(116): Test.g:4:8: unknown attribute for rule b: s

4.8 does not point to any sensible location, at least not if you do not
know what to look for. Or am I counting in the wrong way? ?(

It turns out that 'v' is declared once for method 'test()', thus getting
one type it occurs with (here: Integer. Why, String occurs earlies?).
Requesting an attribute the first type does not have from it, leads to the
error, of course. But again, the error message is confusing, for nowhere is
attribute 's' on a 'b' rule accessed. The call I see in line 4 is 's' on a
rule 'a', which should succeed, not expecting v having the type of the
_later_ declaration.

I boldly suggest that one of the following measures be taken:

* enrich static grammar analysis and report the error at (grammar!)
development time (I am not sure wether this affects ANTLR or ANTLRWorks)
* pinpoint this type of error more precisely during code generation and
generate a more fitting error message
* recognise this type of error during code generation and introduce one
variable per type involved
* move declaration of those variable inside the "case"-Blocks, rendering
them kind of alternative-local.

I favor the latter alternative.

Greetings

Raphael

PS: Fireworks for Spain. In Kaiserslautern, Germany. World's strange.



More information about the antlr-interest mailing list