--- a/progs/compile.scala Thu Nov 14 01:21:02 2019 +0000
+++ b/progs/compile.scala Thu Nov 14 13:17:02 2019 +0000
@@ -118,6 +118,9 @@
def l(args: Any*): String = sc.s(args:_*) ++ ":\n"
}
+// this allows you to write things like
+// i"add" and l"Lable"
+
// environments
type Env = Map[String, Int]
@@ -132,16 +135,17 @@
// 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 Var(s) => i"iload ${env(s)} \t\t; $s"
case Aop(op, a1, a2) =>
compile_aexp(a1, env) ++ compile_aexp(a2, env) ++ compile_op(op)
}
// boolean expression compilation
+// - the jump-label is for where to jump if the condition is not true
def compile_bexp(b: BExp, env : Env, jmp: String) : String = b match {
case True => ""
case False => i"goto $jmp"
- case Bop("=", a1, a2) =>
+ case Bop("==", a1, a2) =>
compile_aexp(a1, env) ++ compile_aexp(a2, env) ++ i"if_icmpne $jmp"
case Bop("!=", a1, a2) =>
compile_aexp(a1, env) ++ compile_aexp(a2, env) ++ i"if_icmpeq $jmp"
@@ -153,8 +157,8 @@
def compile_stmt(s: Stmt, env: Env) : (String, Env) = s match {
case Skip => ("", env)
case Assign(x, a) => {
- val index = if (env.isDefinedAt(x)) env(x) else env.keys.size
- (compile_aexp(a, env) ++ i"istore $index", env + (x -> index))
+ val index = env.getOrElse(x, env.keys.size)
+ (compile_aexp(a, env) ++ i"istore $index \t\t; $x", env + (x -> index))
}
case If(b, bl1, bl2) => {
val if_else = Fresh("If_else")
@@ -179,12 +183,12 @@
l"$loop_end", env1)
}
case Write(x) =>
- (i"iload ${env(x)}" ++
+ (i"iload ${env(x)} \t\t; $x" ++
i"invokestatic XXX/XXX/write(I)V", env)
case Read(x) => {
- val index = if (env.isDefinedAt(x)) env(x) else env.keys.size
+ val index = env.getOrElse(x, env.keys.size)
(i"invokestatic XXX/XXX/read()I" ++
- i"istore $index", env + (x -> index))
+ i"istore $index \t\t; $x", env + (x -> index))
}
}
@@ -266,6 +270,11 @@
Write("minus1")) // write minus1
+// the compiled file as string
+//
+//println(compile(fib_test, "fib"))
+
+
compile_run(fib_test, "fib")