| 
     1 // A Small Compiler for the WHILE Language  | 
         | 
     2 //  | 
         | 
     3 // - this compiler contains support for "static" integer   | 
         | 
     4 //   arrays (they are mutable but cannot be re-sized)  | 
         | 
     5 //  | 
         | 
     6 // Call with   | 
         | 
     7 //  | 
         | 
     8 // amm compile_arrays.sc  | 
         | 
     9     | 
         | 
    10   | 
         | 
    11 // the abstract syntax trees for WHILE  | 
         | 
    12   | 
         | 
    13 abstract class Stmt  | 
         | 
    14 abstract class AExp  | 
         | 
    15 abstract class BExp   | 
         | 
    16 type Block = List[Stmt]  | 
         | 
    17   | 
         | 
    18 // statements  | 
         | 
    19 case object Skip extends Stmt  | 
         | 
    20 case class ArrayDef(s: String, n: Int) extends Stmt            // array definition  | 
         | 
    21 case class If(a: BExp, bl1: Block, bl2: Block) extends Stmt  | 
         | 
    22 case class While(b: BExp, bl: Block) extends Stmt  | 
         | 
    23 case class Assign(s: String, a: AExp) extends Stmt             // var := exp  | 
         | 
    24 case class AssignA(s: String, a1: AExp, a2: AExp) extends Stmt // arr[exp1] := exp2  | 
         | 
    25 case class Write(s: String) extends Stmt  | 
         | 
    26   | 
         | 
    27   | 
         | 
    28 // arithmetic expressions  | 
         | 
    29 case class Var(s: String) extends AExp  | 
         | 
    30 case class Num(i: Int) extends AExp  | 
         | 
    31 case class Aop(o: String, a1: AExp, a2: AExp) extends AExp  | 
         | 
    32 case class Ref(s: String, a: AExp) extends AExp  | 
         | 
    33   | 
         | 
    34 // boolean expressions  | 
         | 
    35 case object True extends BExp  | 
         | 
    36 case object False extends BExp  | 
         | 
    37 case class Bop(o: String, a1: AExp, a2: AExp) extends BExp  | 
         | 
    38   | 
         | 
    39   | 
         | 
    40 // compiler headers needed for the JVM  | 
         | 
    41 //  | 
         | 
    42 // - contains a main method and a method for writing out an integer  | 
         | 
    43 //  | 
         | 
    44 // - the stack and locals are hard-coded  | 
         | 
    45 //  | 
         | 
    46   | 
         | 
    47 val beginning = """  | 
         | 
    48 .class public XXX.XXX  | 
         | 
    49 .super java/lang/Object  | 
         | 
    50   | 
         | 
    51 .method public static write(I)V   | 
         | 
    52     .limit locals 1   | 
         | 
    53     .limit stack 2   | 
         | 
    54     getstatic java/lang/System/out Ljava/io/PrintStream;   | 
         | 
    55     iload 0  | 
         | 
    56     invokevirtual java/io/PrintStream/print(I)V  | 
         | 
    57     return   | 
         | 
    58 .end method  | 
         | 
    59   | 
         | 
    60 .method public static main([Ljava/lang/String;)V  | 
         | 
    61    .limit locals 200  | 
         | 
    62    .limit stack 200  | 
         | 
    63   | 
         | 
    64 ; COMPILED CODE STARTS     | 
         | 
    65   | 
         | 
    66 """  | 
         | 
    67   | 
         | 
    68 val ending = """  | 
         | 
    69 ; COMPILED CODE ENDS  | 
         | 
    70    return  | 
         | 
    71   | 
         | 
    72 .end method  | 
         | 
    73 """  | 
         | 
    74   | 
         | 
    75   | 
         | 
    76   | 
         | 
    77 // for generating new labels  | 
         | 
    78 var counter = -1  | 
         | 
    79   | 
         | 
    80 def Fresh(x: String) = { | 
         | 
    81   counter += 1  | 
         | 
    82   x ++ "_" ++ counter.toString()  | 
         | 
    83 }  | 
         | 
    84   | 
         | 
    85 // environments for variables and indices  | 
         | 
    86 type Env = Map[String, Int]  | 
         | 
    87   | 
         | 
    88 // convenient string interpolations   | 
         | 
    89 // for generating instructions and labels  | 
         | 
    90   | 
         | 
    91 implicit def sring_inters(sc: StringContext) = new { | 
         | 
    92     def i(args: Any*): String = "   " ++ sc.s(args:_*) ++ "\n"  | 
         | 
    93     def l(args: Any*): String = sc.s(args:_*) ++ ":\n"  | 
         | 
    94 }  | 
         | 
    95   | 
         | 
    96 def compile_op(op: String) = op match { | 
         | 
    97   case "+" => i"iadd"  | 
         | 
    98   case "-" => i"isub"  | 
         | 
    99   case "*" => i"imul"  | 
         | 
   100 }  | 
         | 
   101   | 
         | 
   102 // arithmetic expression compilation  | 
         | 
   103 def compile_aexp(a: AExp, env : Env) : String = a match { | 
         | 
   104   case Num(i) => i"ldc $i"  | 
         | 
   105   case Var(s) => i"iload ${env(s)}" | 
         | 
   106   case Aop(op, a1, a2) =>   | 
         | 
   107     compile_aexp(a1, env) ++ compile_aexp(a2, env) ++ compile_op(op)  | 
         | 
   108   case Ref(s, a) =>  | 
         | 
   109     i"aload ${env(s)}" ++ compile_aexp(a, env) ++  i"iaload" | 
         | 
   110 }  | 
         | 
   111   | 
         | 
   112 // boolean expression compilation  | 
         | 
   113 def compile_bexp(b: BExp, env : Env, jmp: String) : String = b match { | 
         | 
   114   case True => ""  | 
         | 
   115   case False => i"goto $jmp"  | 
         | 
   116   case Bop("==", a1, a2) =>  | 
         | 
   117     compile_aexp(a1, env) ++ compile_aexp(a2, env) ++ i"if_icmpne $jmp"  | 
         | 
   118   case Bop("!=", a1, a2) =>  | 
         | 
   119     compile_aexp(a1, env) ++ compile_aexp(a2, env) ++ i"if_icmpeq $jmp"  | 
         | 
   120   case Bop("<", a1, a2) =>  | 
         | 
   121     compile_aexp(a1, env) ++ compile_aexp(a2, env) ++ i"if_icmpge $jmp"  | 
         | 
   122 }  | 
         | 
   123   | 
         | 
   124 // statement compilation  | 
         | 
   125 def compile_stmt(s: Stmt, env: Env) : (String, Env) = s match { | 
         | 
   126   case Skip => ("", env) | 
         | 
   127   case Assign(x, a) => { | 
         | 
   128      val index = env.getOrElse(x, env.keys.size)  | 
         | 
   129     (compile_aexp(a, env) ++ i"istore $index \t\t; $x", env + (x -> index))   | 
         | 
   130   }   | 
         | 
   131   case If(b, bl1, bl2) => { | 
         | 
   132     val if_else = Fresh("If_else") | 
         | 
   133     val if_end = Fresh("If_end") | 
         | 
   134     val (instrs1, env1) = compile_block(bl1, env)  | 
         | 
   135     val (instrs2, env2) = compile_block(bl2, env1)  | 
         | 
   136     (compile_bexp(b, env, if_else) ++  | 
         | 
   137      instrs1 ++  | 
         | 
   138      i"goto $if_end" ++  | 
         | 
   139      l"$if_else" ++  | 
         | 
   140      instrs2 ++  | 
         | 
   141      l"$if_end", env2)  | 
         | 
   142   }  | 
         | 
   143   case While(b, bl) => { | 
         | 
   144     val loop_begin = Fresh("Loop_begin") | 
         | 
   145     val loop_end = Fresh("Loop_end") | 
         | 
   146     val (instrs1, env1) = compile_block(bl, env)  | 
         | 
   147     (l"$loop_begin" ++  | 
         | 
   148      compile_bexp(b, env, loop_end) ++  | 
         | 
   149      instrs1 ++  | 
         | 
   150      i"goto $loop_begin" ++  | 
         | 
   151      l"$loop_end", env1)  | 
         | 
   152   }  | 
         | 
   153   case Write(x) =>   | 
         | 
   154     (i"iload ${env(x)} \t\t; $x" ++  | 
         | 
   155      i"invokestatic XXX/XXX/write(I)V", env)  | 
         | 
   156   case ArrayDef(s: String, n: Int) => { | 
         | 
   157     val index = if (env.isDefinedAt(s)) throw new Exception("array def error") else  | 
         | 
   158                     env.keys.size  | 
         | 
   159     (i"ldc $n" ++  | 
         | 
   160      i"newarray int" ++  | 
         | 
   161      i"astore $index", env + (s -> index))  | 
         | 
   162   }  | 
         | 
   163   case AssignA(s, a1, a2) => { | 
         | 
   164     val index = if (env.isDefinedAt(s)) env(s) else   | 
         | 
   165                     throw new Exception("array not defined") | 
         | 
   166     (i"aload ${env(s)}" ++ | 
         | 
   167      compile_aexp(a1, env) ++  | 
         | 
   168      compile_aexp(a2, env) ++  | 
         | 
   169      i"iastore", env)  | 
         | 
   170   }   | 
         | 
   171 }  | 
         | 
   172   | 
         | 
   173 // compile a block (i.e. list of statements)  | 
         | 
   174 def compile_block(bl: Block, env: Env) : (String, Env) = bl match { | 
         | 
   175   case Nil => ("", env) | 
         | 
   176   case s::bl => { | 
         | 
   177     val (instrs1, env1) = compile_stmt(s, env)  | 
         | 
   178     val (instrs2, env2) = compile_block(bl, env1)  | 
         | 
   179     (instrs1 ++ instrs2, env2)  | 
         | 
   180   }  | 
         | 
   181 }  | 
         | 
   182   | 
         | 
   183   | 
         | 
   184 // main compile function for blocks (adds headers and proper JVM names)  | 
         | 
   185 def compile(bl: Block, class_name: String) : String = { | 
         | 
   186   val instructions = compile_block(bl, Map())._1  | 
         | 
   187   (beginning ++ instructions ++ ending).replace("XXX", class_name) | 
         | 
   188 }  | 
         | 
   189   | 
         | 
   190   | 
         | 
   191   | 
         | 
   192 // contrived example involving arrays  | 
         | 
   193 val array_test =   | 
         | 
   194   List(ArrayDef("a", 10),               // array a[10] | 
         | 
   195        ArrayDef("b", 2),                // array b[2] | 
         | 
   196        AssignA("a", Num(0), Num(10)),   // a[0] := 10 | 
         | 
   197        Assign("x", Ref("a", Num(0))),   // x := a[0] | 
         | 
   198        Write("x"),             | 
         | 
   199        AssignA("b", Num(1), Num(5)),    // b[1] := 5 | 
         | 
   200        Assign("x", Ref("b", Num(1))),   // x := b[1]  | 
         | 
   201        Write("x"))                      | 
         | 
   202   | 
         | 
   203   | 
         | 
   204 // prints out the JVM-assembly instructions for fib above  | 
         | 
   205 //  | 
         | 
   206 //    println(compile(array_test, "arr"))  | 
         | 
   207 //  | 
         | 
   208 // can be assembled by hand with   | 
         | 
   209 //  | 
         | 
   210 //    java -jar jasmin.jar arr.j  | 
         | 
   211 //  | 
         | 
   212 // and run with  | 
         | 
   213 //  | 
         | 
   214 //    java arr/arr  | 
         | 
   215   | 
         | 
   216 // automating the above  | 
         | 
   217 import ammonite.ops._  | 
         | 
   218   | 
         | 
   219 def compile_to_file(bl: Block, class_name: String) : Unit =   | 
         | 
   220   write.over(pwd / s"$class_name.j", compile(bl, class_name))    | 
         | 
   221   | 
         | 
   222 def compile_and_run(bl: Block, class_name: String) : Unit = { | 
         | 
   223   println(s"Start of compilation")  | 
         | 
   224   compile_to_file(bl, class_name)  | 
         | 
   225   println(s"generated $class_name.j file")  | 
         | 
   226   os.proc("java", "-jar", "jasmin.jar", s"$class_name.j").call() | 
         | 
   227   println(s"generated $class_name.class file ")  | 
         | 
   228   //println(os.proc("java", s"${class_name}/${class_name}").call().out.text()) | 
         | 
   229   os.proc("java", s"${class_name}/${class_name}").call(stdout = os.Inherit) | 
         | 
   230   println(s"done.")  | 
         | 
   231 }  | 
         | 
   232   | 
         | 
   233   | 
         | 
   234      | 
         | 
   235 @main def main() = { | 
         | 
   236   compile_and_run(array_test, "arr")  | 
         | 
   237 }  | 
         | 
   238   | 
         | 
   239   |