[antlr-interest] Summing values from "+="

Jim Idle jimi at temporal-wave.com
Thu Feb 12 08:13:58 PST 2009


Des Hartman wrote:
> I have a simple function to sum values, where expression is numbers 
> with operands, etc.
>
> sumStat    :    'SUM' '('  (e+=expression (',' e+=expression)+) ')' -> 
> ^('SUM' $e);
>
> What I need to know is how I write the action statements to add the 
> various numbers? Just to complicate it I am doing it using Flex 
> ActionScript? If I understand it correctly += returns a Java List, so 
> what would be returned with ActionScript?
>
> ^('SUM' e=expression) {$value =??????;}
Well, if there can only be two expressions ever then:


'SUM' '('  (e1=expression (',' e2=expression)+) ')' -> ^('SUM' $e1 $e2);

...
^(SUM e1=expression e2=expression)
{
    // Add values converted from string to int....
}


For a list though, you can do this:


r

@init
{
    int summation = 0;
}
: ^(SUM 
     ( e= expression
        {
            summation += // String value converted to int
         }
      )+
;

Actions can be anywhere, including in list iteration.

Jim




More information about the antlr-interest mailing list