progs/while/compile.sc
changeset 790 31a9f89776a3
parent 716 df7d47a507f8
child 809 2b9956d29038
equal deleted inserted replaced
789:f0696713177b 790:31a9f89776a3
       
     1 // A Small Compiler for the WHILE Language
       
     2 // (it does not use a parser nor lexer)
       
     3 //
       
     4 // cal with 
       
     5 //
       
     6 //   amm compile.sc test
       
     7 //   amm compile.sc test2
       
     8 
       
     9 
       
    10 // the abstract syntax trees
       
    11 abstract class Stmt
       
    12 abstract class AExp
       
    13 abstract class BExp 
       
    14 type Block = List[Stmt]
       
    15 
       
    16 // statements
       
    17 case object Skip extends Stmt
       
    18 case class If(a: BExp, bl1: Block, bl2: Block) extends Stmt
       
    19 case class While(b: BExp, bl: Block) extends Stmt
       
    20 case class Assign(s: String, a: AExp) extends Stmt
       
    21 case class Write(s: String) extends Stmt
       
    22 case class Read(s: String) extends Stmt
       
    23 
       
    24 // arithmetic expressions
       
    25 case class Var(s: String) extends AExp
       
    26 case class Num(i: Int) extends AExp
       
    27 case class Aop(o: String, a1: AExp, a2: AExp) extends AExp
       
    28 
       
    29 // boolean expressions
       
    30 case object True extends BExp
       
    31 case object False extends BExp
       
    32 case class Bop(o: String, a1: AExp, a2: AExp) extends BExp
       
    33 
       
    34 
       
    35 // compiler headers needed for the JVM
       
    36 // (contains methods for read and write)
       
    37 val beginning = """
       
    38 .class public XXX.XXX
       
    39 .super java/lang/Object
       
    40 
       
    41 .method public static write(I)V 
       
    42     .limit locals 1 
       
    43     .limit stack 2 
       
    44     getstatic java/lang/System/out Ljava/io/PrintStream; 
       
    45     iload 0
       
    46     invokevirtual java/io/PrintStream/println(I)V 
       
    47     return 
       
    48 .end method
       
    49 
       
    50 .method public static read()I 
       
    51     .limit locals 10 
       
    52     .limit stack 10
       
    53 
       
    54     ldc 0 
       
    55     istore 1  ; this will hold our final integer 
       
    56 Label1: 
       
    57     getstatic java/lang/System/in Ljava/io/InputStream; 
       
    58     invokevirtual java/io/InputStream/read()I 
       
    59     istore 2 
       
    60     iload 2 
       
    61     ldc 10   ; the newline delimiter 
       
    62     isub 
       
    63     ifeq Label2 
       
    64     iload 2 
       
    65     ldc 32   ; the space delimiter 
       
    66     isub 
       
    67     ifeq Label2
       
    68 
       
    69     iload 2 
       
    70     ldc 48   ; we have our digit in ASCII, have to subtract it from 48 
       
    71     isub 
       
    72     ldc 10 
       
    73     iload 1 
       
    74     imul 
       
    75     iadd 
       
    76     istore 1 
       
    77     goto Label1 
       
    78 Label2: 
       
    79     ;when we come here we have our integer computed in local variable 1 
       
    80     iload 1 
       
    81     ireturn 
       
    82 .end method
       
    83 
       
    84 .method public static main([Ljava/lang/String;)V
       
    85    .limit locals 200
       
    86    .limit stack 200
       
    87 
       
    88 ; COMPILED CODE STARTS
       
    89 
       
    90 """
       
    91 
       
    92 val ending = """
       
    93 ; COMPILED CODE ENDS
       
    94    return
       
    95 
       
    96 .end method
       
    97 """
       
    98 
       
    99 // Compiler functions
       
   100 
       
   101 
       
   102 // for generating new labels
       
   103 var counter = -1
       
   104 
       
   105 def Fresh(x: String) = {
       
   106   counter += 1
       
   107   x ++ "_" ++ counter.toString()
       
   108 }
       
   109 
       
   110 // convenient string interpolations 
       
   111 // for instructions and labels
       
   112 import scala.language.implicitConversions
       
   113 import scala.language.reflectiveCalls
       
   114 
       
   115 implicit def sring_inters(sc: StringContext) = new {
       
   116     def i(args: Any*): String = "   " ++ sc.s(args:_*) ++ "\n"
       
   117     def l(args: Any*): String = sc.s(args:_*) ++ ":\n"
       
   118 }
       
   119 
       
   120 // this allows us to write things like
       
   121 // i"add" and l"Label"
       
   122 
       
   123 
       
   124 // environments 
       
   125 type Env = Map[String, Int]
       
   126 
       
   127 
       
   128 def compile_op(op: String) = op match {
       
   129   case "+" => i"iadd"
       
   130   case "-" => i"isub"
       
   131   case "*" => i"imul"
       
   132 }
       
   133 
       
   134 // arithmetic expression compilation
       
   135 def compile_aexp(a: AExp, env : Env) : String = a match {
       
   136   case Num(i) => i"ldc $i"
       
   137   case Var(s) => i"iload ${env(s)} \t\t; $s"
       
   138   case Aop(op, a1, a2) => 
       
   139     compile_aexp(a1, env) ++ compile_aexp(a2, env) ++ compile_op(op)
       
   140 }
       
   141 
       
   142 // boolean expression compilation
       
   143 //  - the jump-label is for where to jump if the condition is not true
       
   144 def compile_bexp(b: BExp, env : Env, jmp: String) : String = b match {
       
   145   case True => ""
       
   146   case False => i"goto $jmp"
       
   147   case Bop("==", a1, a2) => 
       
   148     compile_aexp(a1, env) ++ compile_aexp(a2, env) ++ i"if_icmpne $jmp"
       
   149   case Bop("!=", a1, a2) => 
       
   150     compile_aexp(a1, env) ++ compile_aexp(a2, env) ++ i"if_icmpeq $jmp"
       
   151   case Bop("<", a1, a2) => 
       
   152     compile_aexp(a1, env) ++ compile_aexp(a2, env) ++ i"if_icmpge $jmp"
       
   153 }
       
   154 
       
   155 // statement compilation
       
   156 def compile_stmt(s: Stmt, env: Env) : (String, Env) = s match {
       
   157   case Skip => ("", env)
       
   158   case Assign(x, a) => {
       
   159     val index = env.getOrElse(x, env.keys.size)
       
   160     (compile_aexp(a, env) ++ i"istore $index \t\t; $x", env + (x -> index))
       
   161   } 
       
   162   case If(b, bl1, bl2) => {
       
   163     val if_else = Fresh("If_else")
       
   164     val if_end = Fresh("If_end")
       
   165     val (instrs1, env1) = compile_block(bl1, env)
       
   166     val (instrs2, env2) = compile_block(bl2, env1)
       
   167     (compile_bexp(b, env, if_else) ++
       
   168      instrs1 ++
       
   169      i"goto $if_end" ++
       
   170      l"$if_else" ++
       
   171      instrs2 ++
       
   172      l"$if_end", env2)
       
   173   }
       
   174   case While(b, bl) => {
       
   175     val loop_begin = Fresh("Loop_begin")
       
   176     val loop_end = Fresh("Loop_end")
       
   177     val (instrs1, env1) = compile_block(bl, env)
       
   178     (l"$loop_begin" ++
       
   179      compile_bexp(b, env, loop_end) ++
       
   180      instrs1 ++
       
   181      i"goto $loop_begin" ++
       
   182      l"$loop_end", env1)
       
   183   }
       
   184   case Write(x) => 
       
   185     (i"iload ${env(x)} \t\t; $x" ++ 
       
   186      i"invokestatic XXX/XXX/write(I)V", env)
       
   187   case Read(x) => {
       
   188     val index = env.getOrElse(x, env.keys.size) 
       
   189     (i"invokestatic XXX/XXX/read()I" ++ 
       
   190      i"istore $index \t\t; $x", env + (x -> index))
       
   191   }
       
   192 }
       
   193 
       
   194 // compilation of a block (i.e. list of instructions)
       
   195 def compile_block(bl: Block, env: Env) : (String, Env) = bl match {
       
   196   case Nil => ("", env)
       
   197   case s::bl => {
       
   198     val (instrs1, env1) = compile_stmt(s, env)
       
   199     val (instrs2, env2) = compile_block(bl, env1)
       
   200     (instrs1 ++ instrs2, env2)
       
   201   }
       
   202 }
       
   203 
       
   204 // main compilation function for blocks
       
   205 def compile(bl: Block, class_name: String) : String = {
       
   206   val instructions = compile_block(bl, Map.empty)._1
       
   207   (beginning ++ instructions ++ ending).replaceAllLiterally("XXX", class_name)
       
   208 }
       
   209 
       
   210 
       
   211 
       
   212 
       
   213 
       
   214 // Fibonacci numbers as a bare-bone test-case
       
   215 val fib_test = 
       
   216   List(Assign("n", Num(9)),            //  n := 10;                     
       
   217        Assign("minus1",Num(0)),         //  minus1 := 0;
       
   218        Assign("minus2",Num(1)),         //  minus2 := 1;
       
   219        Assign("temp",Num(0)),           //  temp := 0;
       
   220        While(Bop("<",Num(0),Var("n")),  //  while n > 0 do  {
       
   221           List(Assign("temp",Var("minus2")), //  temp := minus2;
       
   222                Assign("minus2",Aop("+",Var("minus1"),Var("minus2"))), 
       
   223                                         //  minus2 := minus1 + minus2;
       
   224                Assign("minus1",Var("temp")), //  minus1 := temp;
       
   225                Assign("n",Aop("-",Var("n"),Num(1))))), //  n := n - 1 };
       
   226        Write("minus1"))                 //  write minus1
       
   227 
       
   228 
       
   229 
       
   230 // prints out the JVM instructions
       
   231 @main
       
   232 def test() = 
       
   233   println(compile(fib_test, "fib"))
       
   234 
       
   235 
       
   236 
       
   237 
       
   238 // compiling and running .j-files
       
   239 //
       
   240 // JVM files can be assembled with 
       
   241 //
       
   242 //    java -jar jasmin.jar fib.j
       
   243 //
       
   244 // and started with
       
   245 //
       
   246 //    java fib/fib
       
   247 
       
   248 
       
   249 def run(bl: Block, class_name: String) = {
       
   250     val code = compile(bl, class_name)
       
   251     os.write.over(os.pwd / s"$class_name.j", code)
       
   252     os.proc("java", "-jar", "jasmin.jar", s"$class_name.j").call()
       
   253     print(os.proc("java", s"$class_name/$class_name").call().out.string)
       
   254 }
       
   255 
       
   256 @main
       
   257 def test2() =
       
   258   run(fib_test, "fib")