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

Jim Idle jimi at temporal-wave.com
Thu Apr 26 19:22:29 PDT 2012


@after

Or (my preference)

rule : ( alt | alt | alt) { actions(); } ;

Jim

On Apr 26, 2012, at 6:38 PM, Christopher Schultz <chris at christopherschultz.net> wrote:

> 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
> 
> 
> 
> List: http://www.antlr.org/mailman/listinfo/antlr-interest
> Unsubscribe: http://www.antlr.org/mailman/options/antlr-interest/your-email-address


More information about the antlr-interest mailing list