progs/compile.scala
changeset 674 e0a41a1f24cf
parent 668 9ce78065f68d
child 687 8865f4f2be59
--- a/progs/compile.scala	Sun Oct 27 13:03:58 2019 +0000
+++ b/progs/compile.scala	Sun Oct 27 13:32:15 2019 +0000
@@ -1,5 +1,5 @@
 // A Small Compiler for the WHILE Language
-// (it does not use a parser and lexer)
+// (it does not use a parser nor lexer)
 
 
 // the abstract syntax trees
@@ -122,16 +122,19 @@
 // environments 
 type Env = Map[String, Int]
 
+
+def compile_op(op: String) = op match {
+  case "+" => i"iadd"
+  case "-" => i"isub"
+  case "*" => i"imul"
+}
+
 // arithmetic expression compilation
 def compile_aexp(a: AExp, env : Env) : String = a match {
   case Num(i) => i"ldc $i"
   case Var(s) => i"iload ${env(s)}"
-  case Aop("+", a1, a2) => 
-    compile_aexp(a1, env) ++ compile_aexp(a2, env) ++ i"iadd"
-  case Aop("-", a1, a2) => 
-    compile_aexp(a1, env) ++ compile_aexp(a2, env) ++ i"isub"
-  case Aop("*", a1, a2) => 
-    compile_aexp(a1, env) ++ compile_aexp(a2, env) ++ i"imul"
+  case Aop(op, a1, a2) => 
+    compile_aexp(a1, env) ++ compile_aexp(a2, env) ++ compile_op(op)
 }
 
 // boolean expression compilation
@@ -248,7 +251,7 @@
 }
 
 
-// Fibonacci numbers as a test-case
+// Fibonacci numbers as a bare-bone test-case
 val fib_test = 
   List(Assign("n", Num(10)),            //  n := 10;                     
        Assign("minus1",Num(0)),         //  minus1 := 0;