[antlr-interest] Scopes and return values

Gavin Lambert antlr at mirality.co.nz
Thu Nov 30 16:18:13 PST 2006


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?

eg:

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

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

I've currently hacked something together using scopes, but this produces
an annoying variable duplication, so I'm sure there must be a better way:

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

fileItem
  : someOtherRule { $file::data.AddFileItem(...); }
  ;



More information about the antlr-interest mailing list