CS 330 Lecture 9 – Calculator + functions
Agenda
- evaluating expressions
- persistence of memory
- adding in functions
- avoiding reparsing with abstract syntax trees (ASTs)
Code
Flop.g
grammar Flop; @header { import java.util.HashMap; } @members { HashMap<String, Integer> memory; public void setMemory(HashMap<String, Integer> memory) { this.memory = memory; } } stat : ID EQUALS expr {memory.put($ID.text, $expr.value);} | expr {System.out.println($expr.value);} ; expr returns [int value] : e1=precedence10 {$value = $e1.value;} (PLUS e2=precedence10 {$value += $e2.value;})* ; precedence10 returns [int value] : e1=precedence20 {$value = $e1.value;} (TIMES e2=precedence20 {$value *= $e2.value;})* ; precedence20 returns [int value] : NUMBER {$value = Integer.parseInt($NUMBER.text);} | ID {$value = memory.get($ID.text);} | LEFTPAREN expr RIGHTPAREN {$value = $expr.value;} ; LEFTPAREN : '(' ; RIGHTPAREN : ')' ; ID : '$' ('A'..'Z'|'a'..'z') ('A'..'Z'|'a'..'z'|'0'..'9')* ; EQUALS : '=' ; PLUS : '+' ; TIMES : '*' ; NUMBER : '-'? '0'..'9'+ ; WHITESPACE : (' '|'\t'|'\r'|'\n')+ {skip();} ;
FlopInterpreter.java
import java.io.IOException; import org.antlr.runtime.*; import java.util.Scanner; import java.util.HashMap; public class FlopInterpreter { public static void main(String[] args) throws IOException, RecognitionException { Scanner lineReader = new Scanner(System.in); HashMap<String, Integer> memory = new HashMap<String, Integer>(); System.out.print("> "); while (lineReader.hasNextLine()) { ANTLRStringStream in = new ANTLRStringStream(lineReader.nextLine()); FlopLexer lexer = new FlopLexer(in); CommonTokenStream tokens = new CommonTokenStream(lexer); FlopParser parser = new FlopParser(tokens); parser.setMemory(memory); parser.stat(); System.out.print("> "); } } }
Haiku
Why new languages?
Someone else wrote the old ones.
That’s reason enough.
Someone else wrote the old ones.
That’s reason enough.