0

Hi guys I did this little grammar to implement a simple calculator , but I need to add IF - ELSE and DO WHILE to my grammar but I don't know how to work with the jumps and I don't really know what I need to add this new function.

code

grammar Calculadora;


@header {
   import java.util.HashMap;
}


@members {
   HashMap memory = new HashMap();
}


prog : stat+ 
     ;

stat : expr ';'            { System.out.println($expr.value); }
     | ID '=' expr ';'     { memory.put($ID.text, new Integer($expr.value)); 
                             System.out.println($ID.text + " = " + $expr.value); }
     ;

expr returns [int value]
    : e=multExpr { $value = $e.value; }
      ( '+' e=multExpr { $value += $e.value; }
        | 
        '-' e=multExpr { $value -= $e.value; }
      )*
    ;

multExpr returns [int value]
        : e=atom { $value = $e.value; } 
          ( '*' e=atom { $value *= $e.value; } )*
        ; 

atom returns [int value]
    : INT { $value = Integer.parseInt($INT.text); }
    | ID  { Integer v = (Integer)memory.get($ID.text);
            if ( v != null ) $value = v.intValue();
            else System.err.println("variable no definida " + $ID.text); }
    | '(' expr ')' { $value = $expr.value; }
    ;


ID : ('a'..'z'|'A'..'Z')+ 
   ;

INT : '0'..'9'+ 
    ;

NEWLINE : '\r'? '\n' 
        ;

WS : (' '|'\t')+ { skip(); } 
   ;
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • The [answer in this SO post](http://stackoverflow.com/questions/6598975/if-then-else-conditional-evaluation) has an example of an IF statement.. I think it should get you further.. – vmachan Feb 04 '16 at 17:03
  • Thanks a lot I will try to add it to my grammar :) , I just need the while now! – andresaurio Feb 04 '16 at 17:30

0 Answers0