[antlr-interest] Returns name

Austin Hastings Austin_Hastings at Yahoo.com
Wed Feb 27 08:07:41 PST 2008


Ian,

There are two different things going on, and you're conflating them.

You can say things in ANTLR like:

foo : a=bar;

where bar is another rule, and that means "create a temporary name, 'a', 
for this 'bar' thingy, so that I can reference it later in this same 
(foo) rule."

The reason for doing that is when you have more than one 'bar' in the 
same rule, and you want to discriminate a particular one. Your own 
example might be best written as:

expr :
  b_expr=binary { do_something_with($b_expr.value); }
  | u_expr=unary { do_something_with($u_expr.value); }
 ;

On the other hand, you can declare parameters to the rules, using either 
name[param, ...] or name returns [type result]

When you do this, you create named entities that you can use inside your 
code blocks, not in the "grammar" part itself.

expr returns [Register result]
   binary { $result = $binary.register; }
  | unary { $result = $unary.register; }
  ;


Note that because the two clauses use different sub-rules (binary/unary) 
I don't HAVE to put in a name.

=Austin


Ian Moor wrote:
>  I have a rule in  tree grammar:
> expr returns [ Register result ] :
> 	result=binary
> 	| result=unary ;
> where binary and unary also return registers.
>
> Antlr says 
>   "label result conflicts with rule expr's return value or parameter with same name"
>
>   I am working round this by writing
>   expr  returns  [Register result  ] 
>    @after{result=res;}
>      : res = binaryexpr 
>      | res = unaryexpr
>
> which seems to work. Shouldn't the first case work as well ?
>      Ian W Moor                    Department of Computing,
> iwm at doc.ic.ac.uk           Imperial College.
>                                     180 Queensgate
>                                      London SW7 2AZ UK.
>   
>
>
>   




More information about the antlr-interest mailing list