[antlr-interest] Scopes and return values

Kay Roepke kroepke at classdump.org
Thu Nov 30 16:25:08 PST 2006


On 1. Dec 2006, at 1:18 , Gavin Lambert wrote:

> In ANTLR v3, if I've got a top-level rule that I want to return an  
> object
> from (to the calling code, not another grammar rule), how do I make  
> that
> object accessible to subrules so it can be modified as its parsed?

Depending on how many rules are affected, I'd pass the object in via  
a parameter:

file
returns [ FileData data ]
@init {
   $data = new FileData();
}
   : fileItem[data]* EOF
   ;

fileItem [ FileData data ]
   : someOtherRule { $data.AddFileItem(...); }
   ;

Otherwise use a @member directive and a @finally action in rule file:

@members {
FileData currentData;
}
@init {
currentData = null;
}

file
returns [ FileData data ]
@init {
   currentData = new FileData();
}
@finally {
   $data = currentData;
}
   : fileItem* EOF
   ;

fileItem [ FileData data ]
   : someOtherRule { if (currentData != null) currentData.AddFileItem 
(...); }
   ;

HTH,
-k
-- 
Kay Röpke
http://classdump.org/






More information about the antlr-interest mailing list