--- a/progs/compile_arr.scala Tue Nov 27 07:53:57 2018 +0000
+++ b/progs/compile_arr.scala Wed Nov 28 23:45:37 2018 +0000
@@ -12,12 +12,15 @@
case class If(a: BExp, bl1: Block, bl2: Block) extends Stmt
case class While(b: BExp, bl: Block) extends Stmt
case class Assign(s: String, a: AExp) extends Stmt
+case class AssignA(s: String, a1: AExp, a2: AExp) extends Stmt
case class Write(s: String) extends Stmt // writes out a variable
+case class Array(s: String, n: Int) extends Stmt
// arithmetic expressions
case class Var(s: String) extends AExp
case class Num(i: Int) extends AExp
case class Aop(o: String, a1: AExp, a2: AExp) extends AExp
+case class Ref(s: String, a1: AExp) extends AExp
// boolean expressions
case object True extends BExp
@@ -136,6 +139,24 @@
case Write(x) =>
(List("iload " + env(x) + "\n" +
"invokestatic XXX/XXX/write(I)V\n"), env)
+ case Array(s, n) => {
+ val index = if (env.isDefinedAt(s)) throw new Exception("Array already defined") else
+ env.keys.size.toString
+ (List("ldc " ++ n.toString ++ "\n",
+ "newarray int \n",
+ "astore " ++ index ++ "\n"), env + (s -> index))
+ }
+ case AssignA(s, a1, a2) => {
+ val index = if (env.isDefinedAt(s)) env(s) else
+ throw new Exception("Array not yet defined")
+ (List("aload " + index) ++
+ compile_aexp(a1, env) ++
+ compile_aexp(a2, env) ++
+ List("iastore"), env)
+
+ compile_aexp(a, env) ++
+ List("istore " + index + "\n"), env + (x -> index))
+ }
}
// compilation of a block (i.e. list of instructions)
@@ -217,6 +238,12 @@
compile_run(fib_test, "fib")
+val arr_test =
+ List(Assign("x", Num(0)),
+ Array("a", 10))
+
+compile_block(arr_test, Map())._1.mkString
+compile_run(arr_test, "arr")
val arr_test =