[antlr-interest] [ANTLR2] post-rule action?

Christopher Schultz chris at christopherschultz.net
Thu Apr 26 18:38:00 PDT 2012


All,

(Apologies is this turns out to be a re-post. After a few hours, I
hadn't seen it come across the mailing list, so I'm trying again).

I'm looking for something like an init-action for a rule, except that I
want it to go after the rule body just before the return.

Here's a concrete example of a rule I have: it takes text separated by
commas and returns a List of those things. It works just fine:

argumentlist returns [java.util.List list = new java.util.ArrayList()]
throws EvaluationException
    {
        Expression arg;
    }
    :
        arg=argument { if(null != arg) { list.add(arg); } }
        (COMMA! arg=argument { if(null != arg) { list.add(arg); } })*
    ;


But, I'd like to make it so that the resulting ArrayList gets trimmed
before the return, like this:

....
....
((ArrayList)list).trimToSize();

return list;

It turns out that I have a lot of ArrayLists being created that only
contain a single element, but an ArrayList created with no size
constraint defaults to 10 elements. Believe it or not, this results in a
significant memory usage for me.

(As further performance optimizations, I could even do something like this:

switch(list.size()) {
  case 0: list = Collections.emptyList(); break;
  case 1: list = Collections.singletonList(list.get(0)); break;
  default: ((ArrayList)list).trimToSize();
}

In any case, I didn't see a way to include such a "postamble" or
anything like that in the ANTLR .g file.

Any suggestions?

-chris




More information about the antlr-interest mailing list