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