[antlr-interest] squeeze some space out of ANTLR Java target

David J. Biesack David.Biesack at sas.com
Mon Sep 13 14:03:31 PDT 2010


I've noticed that when a rule in a template grammar does not have a 
'returns [...]' clause, ANTLR 3.2 still generates a default *_returns class:

    public static class my_rule_return extends ParserRuleReturnScope {
        public StringTemplate st;
        public Object getTemplate() { return st; }
        public String toString() { return st==null?null:st.toString(); }
    };

Several of my grammar rule accept a java.util collection input parameter
which they modify, so there is no returns value. Tus, I now have at least 
7 of these *_return classes which differ only in name.

Though each such class is small, I suggest putting a DefaultParserReturnScope
class in the ANTLR runtime and instead of these generated classes, use
DefaultParserReturnScope. It will save a bit of class data/byte code as well as
time to load and validate these classes.

Going further, the generated code for these rules allocate an instance of the
*_return class and sets fields (retval.start, retval.stop) in the instance, but
do nothing else with it. The call sites discard the value. This extra object
allocation on each call to the rule (and subsequent garbage collection) might
also be eliminated. If so, no DefaultParserReturnScope class would be needed.

I don't know if eliminating the instance is possible in all cases, but from the
generated Java for my example, it seems true that:

* The generated methods can be changed to void
* the local *_return instance declaration and instantiation can be removed
* the lines
        retval.start = input.LT(1);
        retval.stop = input.LT(-1);
  can be removed
* the 
       return retval;
  statement can be changed to
       return;

(Sorry if there is already an option to suppress these objects and I just don't
know about it.)

thanks,
djb


-- 
David J. Biesack, SAS
SAS Campus Dr. Cary, NC 27513
www.sas.com    (919) 531-7771


More information about the antlr-interest mailing list