progs/while-arrays/compile_arrays.sc
changeset 974 0cb4bf2469d1
parent 958 fddf099a82f8
child 975 ae5c03560d4d
equal deleted inserted replaced
973:f25d338d16c9 974:0cb4bf2469d1
     5 //
     5 //
     6 // Call with 
     6 // Call with 
     7 //
     7 //
     8 // amm compile_arrays.sc
     8 // amm compile_arrays.sc
     9   
     9   
    10 //> using toolkit latest
    10 //> using toolkit 0.6.0
    11 
    11 
    12 
    12 
    13 // the abstract syntax trees for WHILE
    13 // the abstract syntax trees for WHILE
    14 
    14 
    15 abstract class Stmt
    15 abstract class Stmt
    88 type Env = Map[String, Int]
    88 type Env = Map[String, Int]
    89 
    89 
    90 // convenient string interpolations 
    90 // convenient string interpolations 
    91 // for generating instructions and labels
    91 // for generating instructions and labels
    92 
    92 
       
    93 
    93 extension (sc: StringContext) {
    94 extension (sc: StringContext) {
    94     def i(args: Any*): String = "   " ++ sc.s(args:_*) ++ "\n"
    95     def i(args: Any*): String = "   " ++ sc.s(args*) ++ "\n"
    95     def l(args: Any*): String = sc.s(args:_*) ++ ":\n"
    96     def l(args: Any*): String = sc.s(args*) ++ ":\n"
    96 }
    97 }
    97 
    98 
    98 
    99 
    99 def compile_op(op: String) = op match {
   100 def compile_op(op: String) = op match {
   100   case "+" => i"iadd"
   101   case "+" => i"iadd"
   126 
   127 
   127 // statement compilation
   128 // statement compilation
   128 def compile_stmt(s: Stmt, env: Env) : (String, Env) = s match {
   129 def compile_stmt(s: Stmt, env: Env) : (String, Env) = s match {
   129   case Skip => ("", env)
   130   case Skip => ("", env)
   130   case Assign(x, a) => {
   131   case Assign(x, a) => {
   131      val index = env.getOrElse(x, env.keys.size)
   132     val index = env.getOrElse(x, env.keys.size)
   132     (compile_aexp(a, env) ++ i"istore $index \t\t; $x", env + (x -> index)) 
   133     (compile_aexp(a, env) ++ i"istore $index \t\t; $x", env + (x -> index)) 
   133   } 
   134   } 
   134   case If(b, bl1, bl2) => {
   135   case If(b, bl1, bl2) => {
   135     val if_else = Fresh("If_else")
   136     val if_else = Fresh("If_else")
   136     val if_end = Fresh("If_end")
   137     val if_end = Fresh("If_end")
   216 //
   217 //
   217 //    java arr/arr
   218 //    java arr/arr
   218 
   219 
   219 // automating the above
   220 // automating the above
   220 
   221 
   221 import os._
   222 import os.*
   222 
   223 
   223 def compile_to_file(bl: Block, class_name: String) : Unit = 
   224 def compile_to_file(bl: Block, class_name: String) : Unit = 
   224   write.over(pwd / s"$class_name.j", compile(bl, class_name))  
   225   write.over(pwd / s"$class_name.j", compile(bl, class_name))  
   225 
   226 
   226 def compile_and_run(bl: Block, class_name: String) : Unit = {
   227 def compile_and_run(bl: Block, class_name: String) : Unit = {