| 
     1 import scala.language.implicitConversions      | 
         | 
     2 import scala.language.reflectiveCalls   | 
         | 
     3 import scala.util._  | 
         | 
     4 import scala.annotation.tailrec  | 
         | 
     5 import scala.sys.process._  | 
         | 
     6   | 
         | 
     7 def fromFile(name: String) : String =   | 
         | 
     8   io.Source.fromFile(name).mkString  | 
         | 
     9   | 
         | 
    10 abstract class Rexp   | 
         | 
    11 case object NULL extends Rexp  | 
         | 
    12 case object EMPTY extends Rexp  | 
         | 
    13 case class CHAR(c: Char) extends Rexp  | 
         | 
    14 case class ALT(r1: Rexp, r2: Rexp) extends Rexp   | 
         | 
    15 case class RANGE(cs: List[Char]) extends Rexp   | 
         | 
    16 case class SEQ(r1: Rexp, r2: Rexp) extends Rexp   | 
         | 
    17 case class PLUS(r: Rexp) extends Rexp   | 
         | 
    18 case class STAR(r: Rexp) extends Rexp   | 
         | 
    19 case class NTIMES(r: Rexp, n: Int) extends Rexp   | 
         | 
    20 case class NUPTOM(r: Rexp, n: Int, m: Int) extends Rexp  | 
         | 
    21   | 
         | 
    22 object RANGE { | 
         | 
    23   def apply(s: String) : RANGE = RANGE(s.toList)  | 
         | 
    24 }  | 
         | 
    25 def NMTIMES(r: Rexp, n: Int, m: Int) = { | 
         | 
    26   if (m < n) throw new IllegalArgumentException("the number m cannot be smaller than n.") | 
         | 
    27   else NUPTOM(r, n, m - n)  | 
         | 
    28 }  | 
         | 
    29   | 
         | 
    30 case class NOT(r: Rexp) extends Rexp   | 
         | 
    31 case class OPT(r: Rexp) extends Rexp   | 
         | 
    32   | 
         | 
    33 // some convenience for typing in regular expressions  | 
         | 
    34 def charlist2rexp(s : List[Char]) : Rexp = s match { | 
         | 
    35   case Nil => EMPTY  | 
         | 
    36   case c::Nil => CHAR(c)  | 
         | 
    37   case c::s => SEQ(CHAR(c), charlist2rexp(s))  | 
         | 
    38 }  | 
         | 
    39 implicit def string2rexp(s : String) : Rexp = charlist2rexp(s.toList)  | 
         | 
    40   | 
         | 
    41 implicit def RexpOps (r: Rexp) = new { | 
         | 
    42   def | (s: Rexp) = ALT(r, s)  | 
         | 
    43   def % = STAR(r)  | 
         | 
    44   def ~ (s: Rexp) = SEQ(r, s)  | 
         | 
    45 }  | 
         | 
    46   | 
         | 
    47 implicit def stringOps (s: String) = new { | 
         | 
    48   def | (r: Rexp) = ALT(s, r)  | 
         | 
    49   def | (r: String) = ALT(s, r)  | 
         | 
    50   def % = STAR(s)  | 
         | 
    51   def ~ (r: Rexp) = SEQ(s, r)  | 
         | 
    52   def ~ (r: String) = SEQ(s, r)  | 
         | 
    53 }  | 
         | 
    54   | 
         | 
    55   | 
         | 
    56 // nullable function: tests whether the regular   | 
         | 
    57 // expression can recognise the empty string  | 
         | 
    58 def nullable (r: Rexp) : Boolean = r match { | 
         | 
    59   case NULL => false  | 
         | 
    60   case EMPTY => true  | 
         | 
    61   case CHAR(_) => false  | 
         | 
    62   case ALT(r1, r2) => nullable(r1) || nullable(r2)  | 
         | 
    63   case SEQ(r1, r2) => nullable(r1) && nullable(r2)  | 
         | 
    64   case STAR(_) => true  | 
         | 
    65   case PLUS(r) => nullable(r)  | 
         | 
    66   case NTIMES(r, i) => if (i == 0) true else nullable(r)  | 
         | 
    67   case NUPTOM(r, i, j) => if (i == 0) true else nullable(r)  | 
         | 
    68   case RANGE(_) => false  | 
         | 
    69   case NOT(r) => !(nullable(r))  | 
         | 
    70   case OPT(_) => true  | 
         | 
    71 }  | 
         | 
    72   | 
         | 
    73 // derivative of a regular expression w.r.t. a character  | 
         | 
    74 def der (c: Char, r: Rexp) : Rexp = r match { | 
         | 
    75   case NULL => NULL  | 
         | 
    76   case EMPTY => NULL  | 
         | 
    77   case CHAR(d) => if (c == d) EMPTY else NULL  | 
         | 
    78   case ALT(r1, r2) => ALT(der(c, r1), der(c, r2))  | 
         | 
    79   case SEQ(r1, r2) =>   | 
         | 
    80     if (nullable(r1)) ALT(SEQ(der(c, r1), r2), der(c, r2))  | 
         | 
    81     else SEQ(der(c, r1), r2)  | 
         | 
    82   case STAR(r) => SEQ(der(c, r), STAR(r))  | 
         | 
    83   case PLUS(r) => SEQ(der(c, r), STAR(r))  | 
         | 
    84   case NTIMES(r, i) =>   | 
         | 
    85     if (i == 0) NULL else der(c, SEQ(r, NTIMES(r, i - 1)))  | 
         | 
    86   case NUPTOM(r, i, j) =>  | 
         | 
    87     if (i == 0 && j == 0) NULL else   | 
         | 
    88     if (i == 0) ALT(der(c, NTIMES(r, j)), der(c, NUPTOM(r, 0, j - 1)))  | 
         | 
    89     else der(c, SEQ(r, NUPTOM(r, i - 1, j)))  | 
         | 
    90   case RANGE(cs) => if (cs contains c) EMPTY else NULL  | 
         | 
    91   case NOT(r) => NOT(der (c, r))  | 
         | 
    92   case OPT(r) => der(c, r)  | 
         | 
    93 }  | 
         | 
    94   | 
         | 
    95 def zeroable (r: Rexp) : Boolean = r match { | 
         | 
    96   case NULL => true  | 
         | 
    97   case EMPTY => false  | 
         | 
    98   case CHAR(_) => false  | 
         | 
    99   case ALT(r1, r2) => zeroable(r1) && zeroable(r2)  | 
         | 
   100   case SEQ(r1, r2) => zeroable(r1) || zeroable(r2)  | 
         | 
   101   case STAR(_) => false  | 
         | 
   102   case PLUS(r) => zeroable(r)  | 
         | 
   103   case NTIMES(r, i) => if (i == 0) false else zeroable(r)  | 
         | 
   104   case NUPTOM(r, i, j) => if (i == 0) false else zeroable(r)  | 
         | 
   105   case RANGE(_) => false  | 
         | 
   106   case NOT(r) => !(zeroable(r))     // bug: incorrect definition for NOT  | 
         | 
   107   case OPT(_) => false  | 
         | 
   108 }  | 
         | 
   109   | 
         | 
   110 // derivative w.r.t. a string (iterates der)  | 
         | 
   111 def ders (s: List[Char], r: Rexp) : Rexp = s match { | 
         | 
   112   case Nil => r  | 
         | 
   113   case c::s => ders(s, der(c, r))  | 
         | 
   114 }  | 
         | 
   115   | 
         | 
   116   | 
         | 
   117 // regular expressions for the While language  | 
         | 
   118 val SYM = RANGE("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_") | 
         | 
   119 val DIGIT = RANGE("0123456789") | 
         | 
   120 val ID = SYM ~ (SYM | DIGIT).%   | 
         | 
   121 val NUM = PLUS(DIGIT)  | 
         | 
   122 val KEYWORD : Rexp = "if" | "then" | "else" | "write" | "def"  | 
         | 
   123 val SEMI: Rexp = ";"  | 
         | 
   124 val COMMA: Rexp = ","  | 
         | 
   125 val OP: Rexp = ":=" | "==" | "-" | "+" | "*" | "!=" | "<=" | "=>" | "<" | ">" | "%" | "=" | "/"  | 
         | 
   126 val WHITESPACE = PLUS(" " | "\n" | "\t") | 
         | 
   127 val RPAREN: Rexp = ")"  | 
         | 
   128 val LPAREN: Rexp = "(" | 
         | 
   129 val ALL = SYM | DIGIT | OP | " " | ":" | ";" | "\"" | "=" | "," | "(" | ")" | 
         | 
   130 val ALL2 = ALL | "\n"  | 
         | 
   131 //val COMMENT2 = ("/*" ~ NOT(ALL.% ~ "*/" ~ ALL.%) ~ "*/") | 
         | 
   132 val COMMENT = ("/*" ~ ALL2.% ~ "*/") | ("//" ~ ALL.% ~ "\n") | 
         | 
   133   | 
         | 
   134   | 
         | 
   135 // token for While language  | 
         | 
   136 abstract class Token  | 
         | 
   137 case object T_WHITESPACE extends Token  | 
         | 
   138 case object T_SEMI extends Token  | 
         | 
   139 case object T_COMMA extends Token  | 
         | 
   140 case object T_LPAREN extends Token  | 
         | 
   141 case object T_RPAREN extends Token  | 
         | 
   142 case object T_COMMENT extends Token  | 
         | 
   143 case class T_ID(s: String) extends Token  | 
         | 
   144 case class T_OP(s: String) extends Token  | 
         | 
   145 case class T_NUM(s: String) extends Token  | 
         | 
   146 case class T_KWD(s: String) extends Token  | 
         | 
   147 case class T_ERR(s: String) extends Token // special error token  | 
         | 
   148   | 
         | 
   149   | 
         | 
   150 type TokenFun = String => Token  | 
         | 
   151 type LexRules = List[(Rexp, TokenFun)]  | 
         | 
   152 val While_lexing_rules: LexRules =   | 
         | 
   153   List((KEYWORD, (s) => T_KWD(s)),  | 
         | 
   154        (ID, (s) => T_ID(s)),  | 
         | 
   155        (COMMENT, (s) => T_COMMENT),  | 
         | 
   156        (OP, (s) => T_OP(s)),  | 
         | 
   157        (NUM, (s) => T_NUM(s)),  | 
         | 
   158        (SEMI, (s) => T_SEMI),  | 
         | 
   159        (COMMA, (s) => T_COMMA),  | 
         | 
   160        (LPAREN, (s) => T_LPAREN),  | 
         | 
   161        (RPAREN, (s) => T_RPAREN),  | 
         | 
   162        (WHITESPACE, (s) => T_WHITESPACE))  | 
         | 
   163   | 
         | 
   164   | 
         | 
   165 // calculates derivatives until all of them are zeroable  | 
         | 
   166 @tailrec  | 
         | 
   167 def munch(s: List[Char],   | 
         | 
   168           pos: Int,   | 
         | 
   169           rs: LexRules,   | 
         | 
   170           last: Option[(Int, TokenFun)]): Option[(Int, TokenFun)] = { | 
         | 
   171   rs match { | 
         | 
   172   case Nil => last  | 
         | 
   173   case rs if (s.length <= pos) => last  | 
         | 
   174   case rs => { | 
         | 
   175     val ders = rs.map({case (r, tf) => (der(s(pos), r), tf)}) | 
         | 
   176     val rs_nzero = ders.filterNot({case (r, _) => zeroable(r)}) | 
         | 
   177     val rs_nulls = ders.filter({case (r, _) => nullable(r)}) | 
         | 
   178     val new_last = if (rs_nulls != Nil) Some((pos, rs_nulls.head._2)) else last  | 
         | 
   179     munch(s, 1 + pos, rs_nzero, new_last)  | 
         | 
   180   }  | 
         | 
   181 }}  | 
         | 
   182   | 
         | 
   183 // iterates the munching function and returns a Token list  | 
         | 
   184 def tokenize(s: String, rs: LexRules) : List[Token] = munch(s.toList, 0, rs, None) match { | 
         | 
   185   case None if (s == "") => Nil  | 
         | 
   186   case None => List(T_ERR(s"Lexing error: $s"))  | 
         | 
   187   case Some((n, tf)) => { | 
         | 
   188     val (head, tail) = s.splitAt(n + 1)  | 
         | 
   189     tf(head)::tokenize(tail, rs)  | 
         | 
   190   }  | 
         | 
   191 }  | 
         | 
   192   | 
         | 
   193 def tokenizer(s:String) : List[Token] =   | 
         | 
   194   tokenize(s, While_lexing_rules).filter { | 
         | 
   195     case T_ERR(s) => { println(s); sys.exit(-1) } | 
         | 
   196     case T_WHITESPACE => false  | 
         | 
   197     case T_COMMENT => false  | 
         | 
   198     case _ => true  | 
         | 
   199   }   | 
         | 
   200   | 
         | 
   201   | 
         | 
   202   | 
         | 
   203 // Parser - Abstract syntax trees  | 
         | 
   204 abstract class Exp  | 
         | 
   205 abstract class BExp   | 
         | 
   206 abstract class Decl  | 
         | 
   207   | 
         | 
   208 case class Def(name: String, args: List[String], body: Exp) extends Decl  | 
         | 
   209 case class Main(e: Exp) extends Decl  | 
         | 
   210   | 
         | 
   211 case class Call(name: String, args: List[Exp]) extends Exp  | 
         | 
   212 case class If(a: BExp, e1: Exp, e2: Exp) extends Exp  | 
         | 
   213 case class Write(e: Exp) extends Exp  | 
         | 
   214 case class Var(s: String) extends Exp  | 
         | 
   215 case class Num(i: Int) extends Exp  | 
         | 
   216 case class Aop(o: String, a1: Exp, a2: Exp) extends Exp  | 
         | 
   217 case class Sequ(e1: Exp, e2: Exp) extends Exp  | 
         | 
   218   | 
         | 
   219 case class Bop(o: String, a1: Exp, a2: Exp) extends BExp  | 
         | 
   220   | 
         | 
   221 // calculating the maximal needed stack size  | 
         | 
   222 def max_stack_exp(e: Exp): Int = e match { | 
         | 
   223   case Call(_, args) => args.map(max_stack_exp).sum  | 
         | 
   224   case If(a, e1, e2) => max_stack_bexp(a) + (List(max_stack_exp(e1), max_stack_exp(e2)).max)  | 
         | 
   225   case Write(e) => max_stack_exp(e) + 1  | 
         | 
   226   case Var(_) => 1  | 
         | 
   227   case Num(_) => 1  | 
         | 
   228   case Aop(_, a1, a2) => max_stack_exp(a1) + max_stack_exp(a2)  | 
         | 
   229   case Sequ(e1, e2) => List(max_stack_exp(e1), max_stack_exp(e2)).max  | 
         | 
   230 }  | 
         | 
   231 def max_stack_bexp(e: BExp): Int = e match { | 
         | 
   232   case Bop(_, a1, a2) => max_stack_exp(a1) + max_stack_exp(a2)  | 
         | 
   233 }  | 
         | 
   234   | 
         | 
   235   | 
         | 
   236   | 
         | 
   237 // Parser combinators  | 
         | 
   238 abstract class Parser[I <% Seq[_], T] { | 
         | 
   239   def parse(ts: I): Set[(T, I)]  | 
         | 
   240   | 
         | 
   241   def parse_all(ts: I) : Set[T] =  | 
         | 
   242     for ((head, tail) <- parse(ts); if (tail.isEmpty)) yield head  | 
         | 
   243   | 
         | 
   244   def parse_single(ts: I) : T = parse_all(ts).toList match { | 
         | 
   245     case List(t) => t  | 
         | 
   246     case _ => { println ("Parse Error") ; sys.exit(-1) } | 
         | 
   247   }  | 
         | 
   248 }  | 
         | 
   249   | 
         | 
   250 class SeqParser[I <% Seq[_], T, S](p: => Parser[I, T], q: => Parser[I, S]) extends Parser[I, (T, S)] { | 
         | 
   251   def parse(sb: I) =   | 
         | 
   252     for ((head1, tail1) <- p.parse(sb);   | 
         | 
   253          (head2, tail2) <- q.parse(tail1)) yield ((head1, head2), tail2)  | 
         | 
   254 }  | 
         | 
   255   | 
         | 
   256 class AltParser[I <% Seq[_], T](p: => Parser[I, T], q: => Parser[I, T]) extends Parser[I, T] { | 
         | 
   257   def parse(sb: I) = p.parse(sb) ++ q.parse(sb)     | 
         | 
   258 }  | 
         | 
   259   | 
         | 
   260 class FunParser[I <% Seq[_], T, S](p: => Parser[I, T], f: T => S) extends Parser[I, S] { | 
         | 
   261   def parse(sb: I) =   | 
         | 
   262     for ((head, tail) <- p.parse(sb)) yield (f(head), tail)  | 
         | 
   263 }  | 
         | 
   264   | 
         | 
   265 case class TokParser(tok: Token) extends Parser[List[Token], Token] { | 
         | 
   266   def parse(ts: List[Token]) = ts match { | 
         | 
   267     case t::ts if (t == tok) => Set((t, ts))   | 
         | 
   268     case _ => Set ()  | 
         | 
   269   }  | 
         | 
   270 }  | 
         | 
   271   | 
         | 
   272 implicit def token2tparser(t: Token) = TokParser(t)  | 
         | 
   273   | 
         | 
   274 case object NumParser extends Parser[List[Token], Int] { | 
         | 
   275   def parse(ts: List[Token]) = ts match { | 
         | 
   276     case T_NUM(s)::ts => Set((s.toInt, ts))   | 
         | 
   277     case _ => Set ()  | 
         | 
   278   }  | 
         | 
   279 }  | 
         | 
   280   | 
         | 
   281 case object IdParser extends Parser[List[Token], String] { | 
         | 
   282   def parse(ts: List[Token]) = ts match { | 
         | 
   283     case T_ID(s)::ts => Set((s, ts))   | 
         | 
   284     case _ => Set ()  | 
         | 
   285   }  | 
         | 
   286 }  | 
         | 
   287   | 
         | 
   288   | 
         | 
   289 implicit def ParserOps[I<% Seq[_], T](p: Parser[I, T]) = new { | 
         | 
   290   def || (q : => Parser[I, T]) = new AltParser[I, T](p, q)  | 
         | 
   291   def ==>[S] (f: => T => S) = new FunParser[I, T, S](p, f)  | 
         | 
   292   def ~[S] (q : => Parser[I, S]) = new SeqParser[I, T, S](p, q)  | 
         | 
   293 }  | 
         | 
   294 implicit def TokOps(t: Token) = new { | 
         | 
   295   def || (q : => Parser[List[Token], Token]) = new AltParser[List[Token], Token](t, q)  | 
         | 
   296   def ==>[S] (f: => Token => S) = new FunParser[List[Token], Token, S](t, f)  | 
         | 
   297   def ~[S](q : => Parser[List[Token], S]) = new SeqParser[List[Token], Token, S](t, q)  | 
         | 
   298 }  | 
         | 
   299   | 
         | 
   300 def ListParser[I <% Seq[_], T, S](p: => Parser[I, T], q: => Parser[I, S]): Parser[I, List[T]] = { | 
         | 
   301   (p ~ q ~ ListParser(p, q)) ==> { case ((x, y), z) => x :: z : List[T] } || | 
         | 
   302   (p ==> ((s) => List(s)))  | 
         | 
   303 }  | 
         | 
   304   | 
         | 
   305   | 
         | 
   306 // expressions  | 
         | 
   307 lazy val Exp: Parser[List[Token], Exp] =   | 
         | 
   308   (T_KWD("if") ~ BExp ~ T_KWD("then") ~ Exp ~ T_KWD("else") ~ Exp) ==> | 
         | 
   309     { case (((((x, y), z), u), v), w) => If(y, u, w): Exp } || | 
         | 
   310   (M ~ T_SEMI ~ Exp) ==> { case ((x, y), z) => Sequ(x, z): Exp } || M | 
         | 
   311 lazy val M: Parser[List[Token], Exp] =  | 
         | 
   312   (T_KWD("write") ~ L) ==> { case (x, y) => Write(y): Exp } || L | 
         | 
   313 lazy val L: Parser[List[Token], Exp] =   | 
         | 
   314   (T ~ T_OP("+") ~ Exp) ==> { case ((x, y), z) => Aop("+", x, z): Exp } || | 
         | 
   315   (T ~ T_OP("-") ~ Exp) ==> { case ((x, y), z) => Aop("-", x, z): Exp } || T   | 
         | 
   316 lazy val T: Parser[List[Token], Exp] =   | 
         | 
   317   (F ~ T_OP("*") ~ T) ==> { case ((x, y), z) => Aop("*", x, z): Exp } ||  | 
         | 
   318   (F ~ T_OP("/") ~ T) ==> { case ((x, y), z) => Aop("/", x, z): Exp } ||  | 
         | 
   319   (F ~ T_OP("%") ~ T) ==> { case ((x, y), z) => Aop("%", x, z): Exp } || F | 
         | 
   320 lazy val F: Parser[List[Token], Exp] =   | 
         | 
   321   (IdParser ~ T_LPAREN ~ ListParser(Exp, T_COMMA) ~ T_RPAREN) ==>   | 
         | 
   322     { case (((x, y), z), w) => Call(x, z): Exp } || | 
         | 
   323   (T_LPAREN ~ Exp ~ T_RPAREN) ==> { case ((x, y), z) => y: Exp } ||  | 
         | 
   324   IdParser ==> { case x => Var(x): Exp } ||  | 
         | 
   325   NumParser ==> { case x => Num(x): Exp } | 
         | 
   326   | 
         | 
   327 // boolean expressions  | 
         | 
   328 lazy val BExp: Parser[List[Token], BExp] =   | 
         | 
   329   (Exp ~ T_OP("==") ~ Exp) ==> { case ((x, y), z) => Bop("==", x, z): BExp } ||  | 
         | 
   330   (Exp ~ T_OP("!=") ~ Exp) ==> { case ((x, y), z) => Bop("!=", x, z): BExp } ||  | 
         | 
   331   (Exp ~ T_OP("<") ~ Exp) ==> { case ((x, y), z) => Bop("<", x, z): BExp } ||  | 
         | 
   332   (Exp ~ T_OP(">") ~ Exp) ==> { case ((x, y), z) => Bop("<", z, x): BExp } ||  | 
         | 
   333   (Exp ~ T_OP("<=") ~ Exp) ==> { case ((x, y), z) => Bop("<=", x, z): BExp } ||  | 
         | 
   334   (Exp ~ T_OP("=>") ~ Exp) ==> { case ((x, y), z) => Bop("<=", z, x): BExp }   | 
         | 
   335   | 
         | 
   336 lazy val Defn: Parser[List[Token], Decl] =  | 
         | 
   337    (T_KWD("def") ~ IdParser ~ T_LPAREN ~ ListParser(IdParser, T_COMMA) ~ T_RPAREN ~ T_OP("=") ~ Exp) ==> | 
         | 
   338      { case ((((((x, y), z), w), u), v), r) => Def(y, w, r): Decl } | 
         | 
   339   | 
         | 
   340 lazy val Prog: Parser[List[Token], List[Decl]] =  | 
         | 
   341   (Defn ~ T_SEMI ~ Prog) ==> { case ((x, y), z) => x :: z : List[Decl] } || | 
         | 
   342   (Exp ==> ((s) => List(Main(s)) : List[Decl]))  | 
         | 
   343   | 
         | 
   344 // compiler - built-in functions   | 
         | 
   345 // copied from http://www.ceng.metu.edu.tr/courses/ceng444/link/jvm-cpm.html  | 
         | 
   346 //  | 
         | 
   347   | 
         | 
   348 val library = """  | 
         | 
   349 .class public XXX.XXX  | 
         | 
   350 .super java/lang/Object  | 
         | 
   351   | 
         | 
   352 .method public <init>()V  | 
         | 
   353         aload_0  | 
         | 
   354         invokenonvirtual java/lang/Object/<init>()V  | 
         | 
   355         return  | 
         | 
   356 .end method  | 
         | 
   357   | 
         | 
   358 .method public static write(I)V   | 
         | 
   359         .limit locals 5   | 
         | 
   360         .limit stack 5   | 
         | 
   361         iload 0   | 
         | 
   362         getstatic java/lang/System/out Ljava/io/PrintStream;   | 
         | 
   363         swap   | 
         | 
   364         invokevirtual java/io/PrintStream/println(I)V   | 
         | 
   365         return   | 
         | 
   366 .end method  | 
         | 
   367   | 
         | 
   368 """  | 
         | 
   369   | 
         | 
   370 // for generating new labels  | 
         | 
   371 var counter = -1  | 
         | 
   372   | 
         | 
   373 def Fresh(x: String) = { | 
         | 
   374   counter += 1  | 
         | 
   375   x ++ "_" ++ counter.toString()  | 
         | 
   376 }  | 
         | 
   377   | 
         | 
   378 type Mem = Map[String, Int]  | 
         | 
   379 type Instrs = List[String]  | 
         | 
   380   | 
         | 
   381 def compile_expT(a: Exp, env : Mem, name: String) : Instrs = a match { | 
         | 
   382   case Num(i) => List("ldc " + i.toString + "\n") | 
         | 
   383   case Var(s) => List("iload " + env(s).toString + "\n") | 
         | 
   384   case Aop("+", a1, a2) => compile_expT(a1, env, "") ++ compile_expT(a2, env, "") ++ List("iadd\n") | 
         | 
   385   case Aop("-", a1, a2) => compile_expT(a1, env, "") ++ compile_expT(a2, env, "") ++ List("isub\n") | 
         | 
   386   case Aop("*", a1, a2) => compile_expT(a1, env, "") ++ compile_expT(a2, env, "") ++ List("imul\n") | 
         | 
   387   case Aop("/", a1, a2) => compile_expT(a1, env, "") ++ compile_expT(a2, env, "") ++ List("idiv\n") | 
         | 
   388   case Aop("%", a1, a2) => compile_expT(a1, env, "") ++ compile_expT(a2, env, "") ++ List("irem\n") | 
         | 
   389   case If(b, a1, a2) => { | 
         | 
   390     val if_else = Fresh("If_else") | 
         | 
   391     val if_end = Fresh("If_end") | 
         | 
   392     compile_bexpT(b, env, if_else) ++  | 
         | 
   393     compile_expT(a1, env, name) ++  | 
         | 
   394     List("goto " + if_end + "\n") ++ | 
         | 
   395     List("\n" + if_else + ":\n\n") ++ | 
         | 
   396     compile_expT(a2, env, name) ++  | 
         | 
   397     List("\n" + if_end + ":\n\n") | 
         | 
   398   }  | 
         | 
   399   case Call(n, args) => if (name == n) {  | 
         | 
   400     val stores = args.zipWithIndex.map { case (x, y) => "istore " + y.toString + "\n" }  | 
         | 
   401     args.flatMap(a => compile_expT(a, env, "")) ++  | 
         | 
   402     stores.reverse ++   | 
         | 
   403     List ("goto " + n + "_Start\n")  | 
         | 
   404   } else { | 
         | 
   405     val is = "I" * args.length  | 
         | 
   406     args.flatMap(a => compile_expT(a, env, "")) ++  | 
         | 
   407     List ("invokestatic XXX/XXX/" + n + "(" + is + ")I\n") | 
         | 
   408   }  | 
         | 
   409   case Sequ(a1, a2) => { | 
         | 
   410     compile_expT(a1, env, "") ++ List("pop\n") ++ compile_expT(a2, env, name) | 
         | 
   411   }  | 
         | 
   412   case Write(a1) => { | 
         | 
   413     compile_expT(a1, env, "") ++  | 
         | 
   414     List("dup\n", | 
         | 
   415          "invokestatic XXX/XXX/write(I)V\n")  | 
         | 
   416   }  | 
         | 
   417 }  | 
         | 
   418   | 
         | 
   419 def compile_bexpT(b: BExp, env : Mem, jmp: String) : Instrs = b match { | 
         | 
   420   case Bop("==", a1, a2) =>  | 
         | 
   421     compile_expT(a1, env, "") ++ compile_expT(a2, env, "") ++ List("if_icmpne " + jmp + "\n") | 
         | 
   422   case Bop("!=", a1, a2) =>  | 
         | 
   423     compile_expT(a1, env, "") ++ compile_expT(a2, env, "") ++ List("if_icmpeq " + jmp + "\n") | 
         | 
   424   case Bop("<", a1, a2) =>  | 
         | 
   425     compile_expT(a1, env, "") ++ compile_expT(a2, env, "") ++ List("if_icmpge " + jmp + "\n") | 
         | 
   426   case Bop("<=", a1, a2) =>  | 
         | 
   427     compile_expT(a1, env, "") ++ compile_expT(a2, env, "") ++ List("if_icmpgt " + jmp + "\n") | 
         | 
   428 }  | 
         | 
   429   | 
         | 
   430   | 
         | 
   431 def compile_decl(d: Decl) : Instrs = d match { | 
         | 
   432   case Def(name, args, a) => {  | 
         | 
   433     val env = args.zipWithIndex.toMap  | 
         | 
   434     val is = "I" * args.length  | 
         | 
   435     List(".method public static " + name + "(" + is + ")I \n", | 
         | 
   436          ".limit locals " + args.length.toString + "\n",  | 
         | 
   437          ".limit stack " + (1 + max_stack_exp(a)).toString + "\n",  | 
         | 
   438          name + "_Start:\n") ++     | 
         | 
   439     compile_expT(a, env, name) ++  | 
         | 
   440     List("ireturn\n", | 
         | 
   441          ".end method \n\n")  | 
         | 
   442   }  | 
         | 
   443   case Main(a) => { | 
         | 
   444     List(".method public static main([Ljava/lang/String;)V\n", | 
         | 
   445          ".limit locals 200\n",  | 
         | 
   446          ".limit stack 200\n") ++  | 
         | 
   447     compile_expT(a, Map(), "") ++  | 
         | 
   448     List("invokestatic XXX/XXX/write(I)V\n", | 
         | 
   449          "return\n",  | 
         | 
   450          ".end method\n")  | 
         | 
   451   }  | 
         | 
   452 }  | 
         | 
   453   | 
         | 
   454 def compile(class_name: String, input: String) : String = { | 
         | 
   455   val tks = tokenizer(input)  | 
         | 
   456   //println(Prog.parse(tks))  | 
         | 
   457   val ast = Prog.parse_single(tks)  | 
         | 
   458   val instructions = ast.flatMap(compile_decl).mkString  | 
         | 
   459   (library + instructions).replaceAllLiterally("XXX", class_name) | 
         | 
   460 }  | 
         | 
   461   | 
         | 
   462   | 
         | 
   463 def compile_file(file_name: String) = { | 
         | 
   464   val class_name = file_name.split('.')(0) | 
         | 
   465   val output = compile(class_name, fromFile(file_name))  | 
         | 
   466   val fw = new java.io.FileWriter(class_name + ".j")   | 
         | 
   467   fw.write(output)   | 
         | 
   468   fw.close()  | 
         | 
   469 }  | 
         | 
   470   | 
         | 
   471 def time_needed[T](i: Int, code: => T) = { | 
         | 
   472   val start = System.nanoTime()  | 
         | 
   473   for (j <- 1 to i) code  | 
         | 
   474   val end = System.nanoTime()  | 
         | 
   475   (end - start)/(i * 1.0e9)  | 
         | 
   476 }  | 
         | 
   477   | 
         | 
   478 def compile_run(file_name: String) : Unit = { | 
         | 
   479   val class_name = file_name.split('.')(0) | 
         | 
   480   compile_file(file_name)  | 
         | 
   481   val test = ("java -jar jvm/jasmin-2.4/jasmin.jar " + class_name + ".j").!! | 
         | 
   482   println("Time: " + time_needed(2, ("java " + class_name + "/" + class_name).!)) | 
         | 
   483 }  | 
         | 
   484   | 
         | 
   485   | 
         | 
   486 //examples  | 
         | 
   487 compile_run("defs.rec") | 
         | 
   488 //compile_run("fact.rec") |