| 609 |      1 | // A Small Compiler for the WHILE Language
 | 
| 611 |      2 | // (stub for including arrays)
 | 
| 609 |      3 | 
 | 
|  |      4 | // the abstract syntax trees
 | 
|  |      5 | abstract class Stmt
 | 
|  |      6 | abstract class AExp
 | 
|  |      7 | abstract class BExp 
 | 
|  |      8 | type Block = List[Stmt]
 | 
|  |      9 | 
 | 
|  |     10 | // statements
 | 
|  |     11 | case object Skip extends Stmt
 | 
|  |     12 | case class If(a: BExp, bl1: Block, bl2: Block) extends Stmt
 | 
|  |     13 | case class While(b: BExp, bl: Block) extends Stmt
 | 
|  |     14 | case class Assign(s: String, a: AExp) extends Stmt
 | 
| 612 |     15 | case class AssignA(s: String, a1: AExp, a2: AExp) extends Stmt
 | 
| 611 |     16 | case class Write(s: String) extends Stmt  // writes out a variable
 | 
| 612 |     17 | case class Array(s: String, n: Int) extends Stmt 
 | 
| 609 |     18 | 
 | 
|  |     19 | // arithmetic expressions
 | 
|  |     20 | case class Var(s: String) extends AExp
 | 
|  |     21 | case class Num(i: Int) extends AExp
 | 
|  |     22 | case class Aop(o: String, a1: AExp, a2: AExp) extends AExp
 | 
| 612 |     23 | case class Ref(s: String, a1: AExp) extends AExp
 | 
| 609 |     24 | 
 | 
|  |     25 | // boolean expressions
 | 
|  |     26 | case object True extends BExp
 | 
|  |     27 | case object False extends BExp
 | 
|  |     28 | case class Bop(o: String, a1: AExp, a2: AExp) extends BExp
 | 
|  |     29 | 
 | 
|  |     30 | 
 | 
|  |     31 | // compiler headers needed for the JVM
 | 
|  |     32 | // (contains an init method, as well as methods for read and write)
 | 
|  |     33 | val beginning = """
 | 
|  |     34 | .class public XXX.XXX
 | 
|  |     35 | .super java/lang/Object
 | 
|  |     36 | 
 | 
|  |     37 | .method public <init>()V
 | 
|  |     38 |    aload_0
 | 
|  |     39 |    invokenonvirtual java/lang/Object/<init>()V
 | 
|  |     40 |    return
 | 
|  |     41 | .end method
 | 
|  |     42 | 
 | 
|  |     43 | .method public static write(I)V 
 | 
|  |     44 |     .limit locals 1 
 | 
|  |     45 |     .limit stack 2 
 | 
|  |     46 |     getstatic java/lang/System/out Ljava/io/PrintStream; 
 | 
|  |     47 |     iload 0
 | 
|  |     48 |     invokevirtual java/io/PrintStream/println(I)V 
 | 
|  |     49 |     return 
 | 
|  |     50 | .end method
 | 
|  |     51 | 
 | 
|  |     52 | .method public static main([Ljava/lang/String;)V
 | 
|  |     53 |    .limit locals 200
 | 
|  |     54 |    .limit stack 200
 | 
|  |     55 | 
 | 
|  |     56 | """
 | 
|  |     57 | 
 | 
|  |     58 | val ending = """
 | 
|  |     59 | 
 | 
|  |     60 |    return
 | 
|  |     61 | 
 | 
|  |     62 | .end method
 | 
|  |     63 | """
 | 
|  |     64 | 
 | 
|  |     65 | println("Start compilation")
 | 
|  |     66 | 
 | 
|  |     67 | 
 | 
|  |     68 | // for generating new labels
 | 
|  |     69 | var counter = -1
 | 
|  |     70 | 
 | 
|  |     71 | def Fresh(x: String) = {
 | 
|  |     72 |   counter += 1
 | 
|  |     73 |   x ++ "_" ++ counter.toString()
 | 
|  |     74 | }
 | 
|  |     75 | 
 | 
|  |     76 | // environments and instructions
 | 
|  |     77 | type Env = Map[String, String]
 | 
|  |     78 | type Instrs = List[String]
 | 
|  |     79 | 
 | 
|  |     80 | // arithmetic expression compilation
 | 
|  |     81 | def compile_aexp(a: AExp, env : Env) : Instrs = a match {
 | 
|  |     82 |   case Num(i) => List("ldc " + i.toString + "\n")
 | 
|  |     83 |   case Var(s) => List("iload " + env(s) + "\n")
 | 
|  |     84 |   case Aop("+", a1, a2) => 
 | 
|  |     85 |     compile_aexp(a1, env) ++ 
 | 
|  |     86 |     compile_aexp(a2, env) ++ List("iadd\n")
 | 
|  |     87 |   case Aop("-", a1, a2) => 
 | 
|  |     88 |     compile_aexp(a1, env) ++ compile_aexp(a2, env) ++ List("isub\n")
 | 
|  |     89 |   case Aop("*", a1, a2) => 
 | 
|  |     90 |     compile_aexp(a1, env) ++ compile_aexp(a2, env) ++ List("imul\n")
 | 
|  |     91 | }
 | 
|  |     92 | 
 | 
|  |     93 | // boolean expression compilation
 | 
|  |     94 | def compile_bexp(b: BExp, env : Env, jmp: String) : Instrs = b match {
 | 
|  |     95 |   case True => Nil
 | 
|  |     96 |   case False => List("goto " + jmp + "\n")
 | 
|  |     97 |   case Bop("=", a1, a2) => 
 | 
|  |     98 |     compile_aexp(a1, env) ++ compile_aexp(a2, env) ++ 
 | 
|  |     99 |     List("if_icmpne " + jmp + "\n")
 | 
|  |    100 |   case Bop("!=", a1, a2) => 
 | 
|  |    101 |     compile_aexp(a1, env) ++ compile_aexp(a2, env) ++ 
 | 
|  |    102 |     List("if_icmpeq " + jmp + "\n")
 | 
|  |    103 |   case Bop("<", a1, a2) => 
 | 
|  |    104 |     compile_aexp(a1, env) ++ compile_aexp(a2, env) ++ 
 | 
|  |    105 |     List("if_icmpge " + jmp + "\n")
 | 
|  |    106 | }
 | 
|  |    107 | 
 | 
|  |    108 | // statement compilation
 | 
|  |    109 | def compile_stmt(s: Stmt, env: Env) : (Instrs, Env) = s match {
 | 
|  |    110 |   case Skip => (Nil, env)
 | 
|  |    111 |   case Assign(x, a) => {
 | 
|  |    112 |     val index = if (env.isDefinedAt(x)) env(x) else 
 | 
|  |    113 |                     env.keys.size.toString
 | 
|  |    114 |     (compile_aexp(a, env) ++ 
 | 
|  |    115 |      List("istore " + index + "\n"), env + (x -> index))
 | 
|  |    116 |   } 
 | 
|  |    117 |   case If(b, bl1, bl2) => {
 | 
|  |    118 |     val if_else = Fresh("If_else")
 | 
|  |    119 |     val if_end = Fresh("If_end")
 | 
|  |    120 |     val (instrs1, env1) = compile_block(bl1, env)
 | 
|  |    121 |     val (instrs2, env2) = compile_block(bl2, env1)
 | 
|  |    122 |     (compile_bexp(b, env, if_else) ++
 | 
|  |    123 |      instrs1 ++
 | 
|  |    124 |      List("goto " + if_end + "\n") ++
 | 
|  |    125 |      List("\n" + if_else + ":\n\n") ++
 | 
|  |    126 |      instrs2 ++
 | 
|  |    127 |      List("\n" + if_end + ":\n\n"), env2)
 | 
|  |    128 |   }
 | 
|  |    129 |   case While(b, bl) => {
 | 
|  |    130 |     val loop_begin = Fresh("Loop_begin")
 | 
|  |    131 |     val loop_end = Fresh("Loop_end")
 | 
|  |    132 |     val (instrs1, env1) = compile_block(bl, env)
 | 
|  |    133 |     (List("\n" + loop_begin + ":\n\n") ++
 | 
|  |    134 |      compile_bexp(b, env, loop_end) ++
 | 
|  |    135 |      instrs1 ++
 | 
|  |    136 |      List("goto " + loop_begin + "\n") ++
 | 
|  |    137 |      List("\n" + loop_end + ":\n\n"), env1)
 | 
|  |    138 |   }
 | 
|  |    139 |   case Write(x) => 
 | 
|  |    140 |     (List("iload " + env(x) + "\n" + 
 | 
|  |    141 |            "invokestatic XXX/XXX/write(I)V\n"), env)
 | 
| 612 |    142 |   case Array(s, n) => {
 | 
|  |    143 |     val index = if (env.isDefinedAt(s)) throw new Exception("Array already defined") else 
 | 
|  |    144 |                     env.keys.size.toString
 | 
|  |    145 |     (List("ldc " ++ n.toString ++ "\n",
 | 
|  |    146 |           "newarray int \n",
 | 
|  |    147 |           "astore " ++ index ++ "\n"), env + (s -> index))
 | 
|  |    148 |   } 
 | 
|  |    149 |   case AssignA(s, a1, a2) => {
 | 
|  |    150 |     val index = if (env.isDefinedAt(s)) env(s) else 
 | 
|  |    151 |                     throw new Exception("Array not yet defined")
 | 
|  |    152 |     (List("aload " + index) ++
 | 
|  |    153 |      compile_aexp(a1, env) ++
 | 
|  |    154 |      compile_aexp(a2, env) ++
 | 
|  |    155 |      List("iastore"), env)
 | 
|  |    156 |       
 | 
|  |    157 |       compile_aexp(a, env) ++ 
 | 
|  |    158 |      List("istore " + index + "\n"), env + (x -> index))
 | 
|  |    159 |   } 
 | 
| 609 |    160 | }
 | 
|  |    161 | 
 | 
|  |    162 | // compilation of a block (i.e. list of instructions)
 | 
|  |    163 | def compile_block(bl: Block, env: Env) : (Instrs, Env) = bl match {
 | 
|  |    164 |   case Nil => (Nil, env)
 | 
|  |    165 |   case s::bl => {
 | 
|  |    166 |     val (instrs1, env1) = compile_stmt(s, env)
 | 
|  |    167 |     val (instrs2, env2) = compile_block(bl, env1)
 | 
|  |    168 |     (instrs1 ++ instrs2, env2)
 | 
|  |    169 |   }
 | 
|  |    170 | }
 | 
|  |    171 | 
 | 
|  |    172 | // main compilation function for blocks
 | 
|  |    173 | def compile(bl: Block, class_name: String) : String = {
 | 
|  |    174 |   val instructions = compile_block(bl, Map.empty)._1
 | 
|  |    175 |   (beginning ++ instructions.mkString ++ ending).replaceAllLiterally("XXX", class_name)
 | 
|  |    176 | }
 | 
|  |    177 | 
 | 
|  |    178 | 
 | 
|  |    179 | // compiling and running files
 | 
|  |    180 | //
 | 
|  |    181 | // JVM files can be assembled with 
 | 
|  |    182 | //
 | 
|  |    183 | //    java -jar jvm/jasmin-2.4/jasmin.jar fib.j
 | 
|  |    184 | //
 | 
|  |    185 | // and started with
 | 
|  |    186 | //
 | 
|  |    187 | //    java fib/fib
 | 
|  |    188 | 
 | 
|  |    189 | 
 | 
|  |    190 | 
 | 
|  |    191 | import scala.util._
 | 
|  |    192 | import scala.sys.process._
 | 
|  |    193 | import scala.io
 | 
|  |    194 | 
 | 
|  |    195 | def compile_tofile(bl: Block, class_name: String) = {
 | 
|  |    196 |   val output = compile(bl, class_name)
 | 
|  |    197 |   val fw = new java.io.FileWriter(class_name + ".j") 
 | 
|  |    198 |   fw.write(output) 
 | 
|  |    199 |   fw.close()
 | 
|  |    200 | }
 | 
|  |    201 | 
 | 
|  |    202 | def compile_all(bl: Block, class_name: String) : Unit = {
 | 
|  |    203 |   compile_tofile(bl, class_name)
 | 
|  |    204 |   println("compiled ")
 | 
|  |    205 |   val test = ("java -jar jvm/jasmin-2.4/jasmin.jar " + class_name + ".j").!!
 | 
|  |    206 |   println("assembled ")
 | 
|  |    207 | }
 | 
|  |    208 | 
 | 
|  |    209 | def time_needed[T](i: Int, code: => T) = {
 | 
|  |    210 |   val start = System.nanoTime()
 | 
|  |    211 |   for (j <- 1 to i) code
 | 
|  |    212 |   val end = System.nanoTime()
 | 
|  |    213 |   (end - start)/(i * 1.0e9)
 | 
|  |    214 | }
 | 
|  |    215 | 
 | 
|  |    216 | 
 | 
|  |    217 | def compile_run(bl: Block, class_name: String) : Unit = {
 | 
|  |    218 |   println("Start compilation")
 | 
|  |    219 |   compile_all(bl, class_name)
 | 
|  |    220 |   println("Time: " + time_needed(1, ("java " + class_name + "/" + class_name).!))
 | 
|  |    221 | }
 | 
|  |    222 | 
 | 
|  |    223 | 
 | 
|  |    224 | // Fibonacci numbers as a test-case
 | 
|  |    225 | val fib_test = 
 | 
|  |    226 |   List(Assign("n", Num(10)),            //  n := 10;                     
 | 
|  |    227 |        Assign("minus1",Num(0)),         //  minus1 := 0;
 | 
|  |    228 |        Assign("minus2",Num(1)),         //  minus2 := 1;
 | 
|  |    229 |        Assign("temp",Num(0)),           //  temp := 0;
 | 
|  |    230 |        While(Bop("<",Num(0),Var("n")),  //  while n > 0 do  {
 | 
|  |    231 |           List(Assign("temp",Var("minus2")),    //  temp := minus2;
 | 
|  |    232 |                Assign("minus2",Aop("+",Var("minus1"),Var("minus2"))), 
 | 
|  |    233 |                                         //  minus2 := minus1 + minus2;
 | 
|  |    234 |                Assign("minus1",Var("temp")), //  minus1 := temp;
 | 
|  |    235 |                Assign("n",Aop("-",Var("n"),Num(1))))), //  n := n - 1 };
 | 
|  |    236 |        Write("minus1"))                 //  write minus1
 | 
|  |    237 | 
 | 
|  |    238 | 
 | 
|  |    239 | compile_run(fib_test, "fib")
 | 
|  |    240 | 
 | 
| 612 |    241 | val arr_test = 
 | 
|  |    242 |   List(Assign("x", Num(0)),
 | 
|  |    243 |        Array("a", 10))   
 | 
|  |    244 | 
 | 
|  |    245 | compile_block(arr_test, Map())._1.mkString
 | 
|  |    246 | compile_run(arr_test, "arr")
 | 
| 609 |    247 | 
 | 
| 611 |    248 | 
 | 
|  |    249 | val arr_test = 
 | 
|  |    250 |   List(Array("a", 10),
 | 
|  |    251 |        Array("b", 2),
 | 
|  |    252 |        AssignA("a", Num(0), Num(10)),
 | 
|  |    253 |        Assign("x", Ref("a", Num(0))),
 | 
|  |    254 |        Write("x"),
 | 
|  |    255 |        AssignA("b", Num(1), Num(5)),
 | 
|  |    256 |        Assign("x", Ref("b", Num(1))),
 | 
|  |    257 |        Write("x"))       
 | 
|  |    258 | 
 | 
|  |    259 | //compile_run(arr_test, "a") |