[antlr-interest] Just plain var or $var.value?

Kay Röpke kroepke at classdump.org
Sat Feb 2 10:42:43 PST 2008


Hi Olivier!

On Jan 31, 2008, at 6:42 PM, Olivier Lefevre wrote:

> Still reading the book. Comparing tour/tree/Eval.g
> and tour/eval/Eval.g I was struck by the difference
> between, say, "a+b" in the former vs. "$e.value" in
> the latter. I tried changing accesses in the first
> file from the "var" to "$var.$value" form and vice-
> versa in the latter file and in both cases it seemed
> to work.

"seemed" :)

Indeed it is just coincidence that it did work. It's basically an  
implementation detail in the way the Java target behaves. See below.

>
> This is a bit confusing. Is it a kind of syntactic sugar?
> Clearly the two forms are not always equivalent since,
> e.g, replacing "$e.value" by "e" in the latter file is
> ok but if you replace "$expr.value" by "expr" antlr does
> not complain (maybe it should?) but EvalParser will not
> compile. What is going on here and in which section of
> the manual is it fully spec'ed out?

Every reference to a label (as in b=expr - b is the label here) is  
translated by ANTLR into the target language using special code  
generation templates.
It's basically up to the target author what the name of the variable  
will be in the generated code. You don't have to and you shouldn't care.
The Java target happens to just use the label you provided, but other  
targets might not do that (i.e. the ObjC target prefixes all all  
labels with a '_' character to prevent clashes with reserved words and  
types).
Thus, each time you reference a label in an action without using the  
$label syntax, it's an error, even though ANTLR cannot catch it. You  
are relying on implementation details that are opaque to you, in fact  
your code might break any time.
So I'd say the example in the book is wrong, unfortunately. I'm not  
sure if it is fixed in the second printing of the book, but to make  
sure it doesn't fall down, I'm cc'ing Terence here.

In short, ANTLR can't complain about the lack of the $ but you should  
always use it. That way ANTLR can check if the return value you are  
trying to access is valid.

Even more so, the example in the book should be:

expr returns [int value]
	:	^('+' a=expr b=expr) {$value = $a.value + $b.value;}
	...and so on...
	;

That would be the correct and future proof way of doing it.
tour/eval/Expr.g is correct, while tour/trees/Eval.g is not :(

HTH,
-k

-- 
Kay Röpke
http://classdump.org/








More information about the antlr-interest mailing list