I can't post the whole grammar, cause it's far too long.
The following is more "readable" and does exactly the same as your original rule:
collection_name returns [MyType value]
: ID { $value = (MyType) database.get($ID.text); }
;
Perhaps do some sanity checks:
collection_name returns [MyType value]
: ID
{
Object v = database.get($ID.text);
if(v == null) {
throw new RuntimeException($ID.text + " unknown in database!");
}
$value = (MyType) v;
}
;
EDIT
As you already found out, accessing the .text
attribute of a rule is not possible in a tree grammar (only in a parser grammar). In tree grammars, every rule is of type Tree
and knows a .start
and .end
attributes instead. Tokens can be accessed the same in both parser- and tree-grammars. So $ID.text
works okay.