[antlr-interest] simple arithmetic counter

Indhu Bharathi indhu.b at s7software.com
Wed Apr 8 21:23:15 PDT 2009


Use '@members' to store 'global' variables.

like
@members{
    int cnt;
}

and increase 'cnt' in 'species' production, like

species   
    : ret=atom NUMBER?
    {
        cnt += $ret.weight * Integer.parseInt($NUMBER.text)
    }
        ;

and print out the sum in file production, like

file    
    : species*
    {
        System.out.println(cnt);
    }
    ;

In ANTLRWorks, you'll see the printed out value in output tab.

- Indhu

Tobias Wunner wrote:
> Hello,
>
> I am a absolute beginner to ANTLR. I already worked through some 
> tutorials but couldn't solve my problem. I would like to add some 
> numbers encoded by strings and print them to STDOUT or display them in 
> the ANTLR Debug environment (to test if my calculations were correct). 
> Two things I didn't find out:
>
>     * how to display or print out used variables
>     * how to use a global variable as a counter and inrease it e.g. cnt+=a
>
>
> To start I found a simple grammar for chemical terms beeing able to 
> calculate the weight of things like "H2O" or "Cl2".
>
>     file : species*;
>     species : atom DIGITS? {};
>     atom returns [double weight]
>     : 'H' { $weight = 1.00794; }
>     | 'C' { $weight = 12.001; }
>     | 'Cl' { $weight = 35.453; }
>     | 'O' { $weight = 15.999; }
>     | 'S' { $weight = 32.06; }
>     ;
>     DIGITS : ('0'..'9');
>
>
> How could I embed a simple counter? For the beginning I would be happy 
> to sum up the weights ignoring the digits (e.g. H20 => 17.00694) How 
> can I display the result of the calculations in the debug environment?
>
> For any help I would be gladful!
>
> Regards,
> Toby 
> ------------------------------------------------------------------------
>
>
> List: http://www.antlr.org/mailman/listinfo/antlr-interest
> Unsubscribe: http://www.antlr.org/mailman/options/antlr-interest/your-email-address
>   

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.antlr.org/pipermail/antlr-interest/attachments/20090409/625e20c7/attachment.html 


More information about the antlr-interest mailing list