progs/fun/funt.scala
changeset 734 5d860ff01938
parent 695 484b74bc057e
equal deleted inserted replaced
733:022e2cb1668d 734:5d860ff01938
       
     1 // A Small Compiler for a Simple Functional Language
       
     2 // (includes a lexer and a parser)
       
     3 
       
     4 import scala.language.implicitConversions    
       
     5 import scala.language.reflectiveCalls 
       
     6 
       
     7 abstract class Rexp 
       
     8 case object ZERO extends Rexp
       
     9 case object ONE extends Rexp
       
    10 case class CHAR(c: Char) extends Rexp
       
    11 case class ALT(r1: Rexp, r2: Rexp) extends Rexp 
       
    12 case class SEQ(r1: Rexp, r2: Rexp) extends Rexp 
       
    13 case class STAR(r: Rexp) extends Rexp 
       
    14 case class RECD(x: String, r: Rexp) extends Rexp
       
    15   
       
    16 abstract class Val
       
    17 case object Empty extends Val
       
    18 case class Chr(c: Char) extends Val
       
    19 case class Sequ(v1: Val, v2: Val) extends Val
       
    20 case class Left(v: Val) extends Val
       
    21 case class Right(v: Val) extends Val
       
    22 case class Stars(vs: List[Val]) extends Val
       
    23 case class Rec(x: String, v: Val) extends Val
       
    24    
       
    25 // some convenience for typing in regular expressions
       
    26 def charlist2rexp(s : List[Char]): Rexp = s match {
       
    27   case Nil => ONE
       
    28   case c::Nil => CHAR(c)
       
    29   case c::s => SEQ(CHAR(c), charlist2rexp(s))
       
    30 }
       
    31 implicit def string2rexp(s : String) : Rexp = 
       
    32   charlist2rexp(s.toList)
       
    33 
       
    34 implicit def RexpOps(r: Rexp) = new {
       
    35   def | (s: Rexp) = ALT(r, s)
       
    36   def % = STAR(r)
       
    37   def ~ (s: Rexp) = SEQ(r, s)
       
    38 }
       
    39 
       
    40 implicit def stringOps(s: String) = new {
       
    41   def | (r: Rexp) = ALT(s, r)
       
    42   def | (r: String) = ALT(s, r)
       
    43   def % = STAR(s)
       
    44   def ~ (r: Rexp) = SEQ(s, r)
       
    45   def ~ (r: String) = SEQ(s, r)
       
    46   def $ (r: Rexp) = RECD(s, r)
       
    47 }
       
    48 
       
    49 def nullable (r: Rexp) : Boolean = r match {
       
    50   case ZERO => false
       
    51   case ONE => true
       
    52   case CHAR(_) => false
       
    53   case ALT(r1, r2) => nullable(r1) || nullable(r2)
       
    54   case SEQ(r1, r2) => nullable(r1) && nullable(r2)
       
    55   case STAR(_) => true
       
    56   case RECD(_, r1) => nullable(r1)
       
    57 }
       
    58 
       
    59 def der (c: Char, r: Rexp) : Rexp = r match {
       
    60   case ZERO => ZERO
       
    61   case ONE => ZERO
       
    62   case CHAR(d) => if (c == d) ONE else ZERO
       
    63   case ALT(r1, r2) => ALT(der(c, r1), der(c, r2))
       
    64   case SEQ(r1, r2) => 
       
    65     if (nullable(r1)) ALT(SEQ(der(c, r1), r2), der(c, r2))
       
    66     else SEQ(der(c, r1), r2)
       
    67   case STAR(r) => SEQ(der(c, r), STAR(r))
       
    68   case RECD(_, r1) => der(c, r1)
       
    69 }
       
    70 
       
    71 
       
    72 // extracts a string from value
       
    73 def flatten(v: Val) : String = v match {
       
    74   case Empty => ""
       
    75   case Chr(c) => c.toString
       
    76   case Left(v) => flatten(v)
       
    77   case Right(v) => flatten(v)
       
    78   case Sequ(v1, v2) => flatten(v1) + flatten(v2)
       
    79   case Stars(vs) => vs.map(flatten).mkString
       
    80   case Rec(_, v) => flatten(v)
       
    81 }
       
    82 
       
    83 // extracts an environment from a value;
       
    84 // used for tokenise a string
       
    85 def env(v: Val) : List[(String, String)] = v match {
       
    86   case Empty => Nil
       
    87   case Chr(c) => Nil
       
    88   case Left(v) => env(v)
       
    89   case Right(v) => env(v)
       
    90   case Sequ(v1, v2) => env(v1) ::: env(v2)
       
    91   case Stars(vs) => vs.flatMap(env)
       
    92   case Rec(x, v) => (x, flatten(v))::env(v)
       
    93 }
       
    94 
       
    95 // The Injection Part of the lexer
       
    96 
       
    97 def mkeps(r: Rexp) : Val = r match {
       
    98   case ONE => Empty
       
    99   case ALT(r1, r2) => 
       
   100     if (nullable(r1)) Left(mkeps(r1)) else Right(mkeps(r2))
       
   101   case SEQ(r1, r2) => Sequ(mkeps(r1), mkeps(r2))
       
   102   case STAR(r) => Stars(Nil)
       
   103   case RECD(x, r) => Rec(x, mkeps(r))
       
   104 }
       
   105 
       
   106 def inj(r: Rexp, c: Char, v: Val) : Val = (r, v) match {
       
   107   case (STAR(r), Sequ(v1, Stars(vs))) => Stars(inj(r, c, v1)::vs)
       
   108   case (SEQ(r1, r2), Sequ(v1, v2)) => Sequ(inj(r1, c, v1), v2)
       
   109   case (SEQ(r1, r2), Left(Sequ(v1, v2))) => Sequ(inj(r1, c, v1), v2)
       
   110   case (SEQ(r1, r2), Right(v2)) => Sequ(mkeps(r1), inj(r2, c, v2))
       
   111   case (ALT(r1, r2), Left(v1)) => Left(inj(r1, c, v1))
       
   112   case (ALT(r1, r2), Right(v2)) => Right(inj(r2, c, v2))
       
   113   case (CHAR(d), Empty) => Chr(c) 
       
   114   case (RECD(x, r1), _) => Rec(x, inj(r1, c, v))
       
   115   case _ => { println ("Injection error") ; sys.exit(-1) } 
       
   116 }
       
   117 
       
   118 // some "rectification" functions for simplification
       
   119 def F_ID(v: Val): Val = v
       
   120 def F_RIGHT(f: Val => Val) = (v:Val) => Right(f(v))
       
   121 def F_LEFT(f: Val => Val) = (v:Val) => Left(f(v))
       
   122 def F_ALT(f1: Val => Val, f2: Val => Val) = (v:Val) => v match {
       
   123   case Right(v) => Right(f2(v))
       
   124   case Left(v) => Left(f1(v))
       
   125 }
       
   126 def F_SEQ(f1: Val => Val, f2: Val => Val) = (v:Val) => v match {
       
   127   case Sequ(v1, v2) => Sequ(f1(v1), f2(v2))
       
   128 }
       
   129 def F_SEQ_Empty1(f1: Val => Val, f2: Val => Val) = 
       
   130   (v:Val) => Sequ(f1(Empty), f2(v))
       
   131 def F_SEQ_Empty2(f1: Val => Val, f2: Val => Val) = 
       
   132   (v:Val) => Sequ(f1(v), f2(Empty))
       
   133 def F_RECD(f: Val => Val) = (v:Val) => v match {
       
   134   case Rec(x, v) => Rec(x, f(v))
       
   135 }
       
   136 def F_ERROR(v: Val): Val = throw new Exception("error")
       
   137 
       
   138 def simp(r: Rexp): (Rexp, Val => Val) = r match {
       
   139   case ALT(r1, r2) => {
       
   140     val (r1s, f1s) = simp(r1)
       
   141     val (r2s, f2s) = simp(r2)
       
   142     (r1s, r2s) match {
       
   143       case (ZERO, _) => (r2s, F_RIGHT(f2s))
       
   144       case (_, ZERO) => (r1s, F_LEFT(f1s))
       
   145       case _ => if (r1s == r2s) (r1s, F_LEFT(f1s))
       
   146                 else (ALT (r1s, r2s), F_ALT(f1s, f2s)) 
       
   147     }
       
   148   }
       
   149   case SEQ(r1, r2) => {
       
   150     val (r1s, f1s) = simp(r1)
       
   151     val (r2s, f2s) = simp(r2)
       
   152     (r1s, r2s) match {
       
   153       case (ZERO, _) => (ZERO, F_ERROR)
       
   154       case (_, ZERO) => (ZERO, F_ERROR)
       
   155       case (ONE, _) => (r2s, F_SEQ_Empty1(f1s, f2s))
       
   156       case (_, ONE) => (r1s, F_SEQ_Empty2(f1s, f2s))
       
   157       case _ => (SEQ(r1s,r2s), F_SEQ(f1s, f2s))
       
   158     }
       
   159   }
       
   160   case RECD(x, r1) => {
       
   161     val (r1s, f1s) = simp(r1)
       
   162     (RECD(x, r1s), F_RECD(f1s))
       
   163   }
       
   164   case r => (r, F_ID)
       
   165 }
       
   166 
       
   167 // lexing functions including simplification
       
   168 def lex_simp(r: Rexp, s: List[Char]) : Val = s match {
       
   169   case Nil => if (nullable(r)) mkeps(r) else { println ("Lexing Error") ; sys.exit(-1) } 
       
   170   case c::cs => {
       
   171     val (r_simp, f_simp) = simp(der(c, r))
       
   172     inj(r, c, f_simp(lex_simp(r_simp, cs)))
       
   173   }
       
   174 }
       
   175 
       
   176 def lexing_simp(r: Rexp, s: String) = env(lex_simp(r, s.toList))
       
   177 
       
   178 
       
   179 // The Lexing Rules for the Fun Language
       
   180 
       
   181 def PLUS(r: Rexp) = r ~ r.%
       
   182 
       
   183 val SYM = "a" | "b" | "c" | "d" | "e" | "f" | "g" | "h" | "i" | "j" | "k" | 
       
   184           "l" | "m" | "n" | "o" | "p" | "q" | "r" | "s" | "t" | "u" | "v" | 
       
   185           "w" | "x" | "y" | "z" | "T" | "_"
       
   186 val DIGIT = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"
       
   187 val ID = SYM ~ (SYM | DIGIT).% 
       
   188 val NUM = PLUS(DIGIT)
       
   189 val KEYWORD : Rexp = "if" | "then" | "else" | "write" | "def"
       
   190 val SEMI: Rexp = ";"
       
   191 val OP: Rexp = "=" | "==" | "-" | "+" | "*" | "!=" | "<" | ">" | "<=" | ">=" | "%" | "/"
       
   192 val WHITESPACE = PLUS(" " | "\n" | "\t")
       
   193 val RPAREN: Rexp = ")"
       
   194 val LPAREN: Rexp = "("
       
   195 val COMMA: Rexp = ","
       
   196 val ALL = SYM | DIGIT | OP | " " | ":" | ";" | "\"" | "=" | "," | "(" | ")"
       
   197 val ALL2 = ALL | "\n"
       
   198 val COMMENT = ("/*" ~ ALL2.% ~ "*/") | ("//" ~ ALL.% ~ "\n")
       
   199 
       
   200 
       
   201 val WHILE_REGS = (("k" $ KEYWORD) | 
       
   202                   ("i" $ ID) | 
       
   203                   ("o" $ OP) | 
       
   204                   ("n" $ NUM) | 
       
   205                   ("s" $ SEMI) | 
       
   206                   ("c" $ COMMA) |
       
   207                   ("pl" $ LPAREN) |
       
   208                   ("pr" $ RPAREN) |
       
   209                   ("w" $ (WHITESPACE | COMMENT))).%
       
   210 
       
   211 
       
   212 
       
   213 // The tokens for the Fun language
       
   214 
       
   215 abstract class Token
       
   216 case object T_SEMI extends Token
       
   217 case object T_COMMA extends Token
       
   218 case object T_LPAREN extends Token
       
   219 case object T_RPAREN extends Token
       
   220 case class T_ID(s: String) extends Token
       
   221 case class T_OP(s: String) extends Token
       
   222 case class T_NUM(n: Int) extends Token
       
   223 case class T_KWD(s: String) extends Token
       
   224 
       
   225 val token : PartialFunction[(String, String), Token] = {
       
   226   case ("k", s) => T_KWD(s)
       
   227   case ("i", s) => T_ID(s)
       
   228   case ("o", s) => T_OP(s)
       
   229   case ("n", s) => T_NUM(s.toInt)
       
   230   case ("s", _) => T_SEMI
       
   231   case ("c", _) => T_COMMA
       
   232   case ("pl", _) => T_LPAREN
       
   233   case ("pr", _) => T_RPAREN
       
   234 }
       
   235 
       
   236 
       
   237 def tokenise(s: String) : List[Token] = 
       
   238   lexing_simp(WHILE_REGS, s).collect(token)
       
   239 
       
   240 
       
   241 
       
   242 // Parser combinators
       
   243 abstract class Parser[I, T](implicit ev: I => Seq[_]) {
       
   244   def parse(ts: I): Set[(T, I)]
       
   245 
       
   246   def parse_all(ts: I) : Set[T] =
       
   247     for ((head, tail) <- parse(ts); if (tail.isEmpty)) yield head
       
   248 
       
   249   def parse_single(ts: I) : T = parse_all(ts).toList match {
       
   250     case List(t) => t
       
   251     case _ => { println ("Parse Error\n") ; sys.exit(-1) }
       
   252   }
       
   253 }
       
   254 
       
   255 // convenience for matching later on
       
   256 case class ~[+A, +B](_1: A, _2: B)
       
   257 
       
   258 
       
   259 class SeqParser[I, T, S](p: => Parser[I, T], 
       
   260                          q: => Parser[I, S])(implicit ev: I => Seq[_]) extends Parser[I, ~[T, S]] {
       
   261   def parse(sb: I) = 
       
   262     for ((head1, tail1) <- p.parse(sb); 
       
   263          (head2, tail2) <- q.parse(tail1)) yield (new ~(head1, head2), tail2)
       
   264 }
       
   265 
       
   266 class AltParser[I, T](p: => Parser[I, T], 
       
   267                       q: => Parser[I, T])(implicit ev: I => Seq[_]) extends Parser[I, T] {
       
   268   def parse(sb: I) = p.parse(sb) ++ q.parse(sb)   
       
   269 }
       
   270 
       
   271 class FunParser[I, T, S](p: => Parser[I, T], 
       
   272                          f: T => S)(implicit ev: I => Seq[_]) extends Parser[I, S] {
       
   273   def parse(sb: I) = 
       
   274     for ((head, tail) <- p.parse(sb)) yield (f(head), tail)
       
   275 }
       
   276 
       
   277 implicit def ParserOps[I, T](p: Parser[I, T])(implicit ev: I => Seq[_]) = new {
       
   278   def || (q : => Parser[I, T]) = new AltParser[I, T](p, q)
       
   279   def ==>[S] (f: => T => S) = new FunParser[I, T, S](p, f)
       
   280   def ~[S] (q : => Parser[I, S]) = new SeqParser[I, T, S](p, q)
       
   281 }
       
   282 
       
   283 def ListParser[I, T, S](p: => Parser[I, T], 
       
   284                         q: => Parser[I, S])(implicit ev: I => Seq[_]): Parser[I, List[T]] = {
       
   285   (p ~ q ~ ListParser(p, q)) ==> { case x ~ _ ~ z => x :: z : List[T] } ||
       
   286   (p ==> ((s) => List(s)))
       
   287 }
       
   288 
       
   289 case class TokParser(tok: Token) extends Parser[List[Token], Token] {
       
   290   def parse(ts: List[Token]) = ts match {
       
   291     case t::ts if (t == tok) => Set((t, ts)) 
       
   292     case _ => Set ()
       
   293   }
       
   294 }
       
   295 
       
   296 implicit def token2tparser(t: Token) = TokParser(t)
       
   297 
       
   298 implicit def TokOps(t: Token) = new {
       
   299   def || (q : => Parser[List[Token], Token]) = new AltParser[List[Token], Token](t, q)
       
   300   def ==>[S] (f: => Token => S) = new FunParser[List[Token], Token, S](t, f)
       
   301   def ~[S](q : => Parser[List[Token], S]) = new SeqParser[List[Token], Token, S](t, q)
       
   302 }
       
   303 
       
   304 case object NumParser extends Parser[List[Token], Int] {
       
   305   def parse(ts: List[Token]) = ts match {
       
   306     case T_NUM(n)::ts => Set((n, ts)) 
       
   307     case _ => Set ()
       
   308   }
       
   309 }
       
   310 
       
   311 case object IdParser extends Parser[List[Token], String] {
       
   312   def parse(ts: List[Token]) = ts match {
       
   313     case T_ID(s)::ts => Set((s, ts)) 
       
   314     case _ => Set ()
       
   315   }
       
   316 }
       
   317 
       
   318 
       
   319 
       
   320 // Abstract syntax trees for Fun
       
   321 abstract class Exp
       
   322 abstract class BExp 
       
   323 abstract class Decl
       
   324 
       
   325 case class Def(name: String, args: List[String], body: Exp) extends Decl
       
   326 case class Main(e: Exp) extends Decl
       
   327 
       
   328 case class Call(name: String, args: List[Exp]) extends Exp
       
   329 case class If(a: BExp, e1: Exp, e2: Exp) extends Exp
       
   330 case class Write(e: Exp) extends Exp
       
   331 case class Var(s: String) extends Exp
       
   332 case class Num(i: Int) extends Exp
       
   333 case class Aop(o: String, a1: Exp, a2: Exp) extends Exp
       
   334 case class Sequence(e1: Exp, e2: Exp) extends Exp
       
   335 case class Bop(o: String, a1: Exp, a2: Exp) extends BExp
       
   336 
       
   337 
       
   338 
       
   339 // Grammar Rules for Fun
       
   340 
       
   341 // arithmetic expressions
       
   342 lazy val Exp: Parser[List[Token], Exp] = 
       
   343   (T_KWD("if") ~ BExp ~ T_KWD("then") ~ Exp ~ T_KWD("else") ~ Exp) ==>
       
   344     { case _ ~ y ~ _ ~ u ~ _ ~ w => If(y, u, w): Exp } ||
       
   345   (M ~ T_SEMI ~ Exp) ==> { case x ~ _ ~ z => Sequence(x, z): Exp } || M
       
   346 lazy val M: Parser[List[Token], Exp] =
       
   347   (T_KWD("write") ~ L) ==> { case _ ~ y => Write(y): Exp } || L
       
   348 lazy val L: Parser[List[Token], Exp] = 
       
   349   (T ~ T_OP("+") ~ Exp) ==> { case x ~ _ ~ z => Aop("+", x, z): Exp } ||
       
   350   (T ~ T_OP("-") ~ Exp) ==> { case x ~ _ ~ z => Aop("-", x, z): Exp } || T  
       
   351 lazy val T: Parser[List[Token], Exp] = 
       
   352   (F ~ T_OP("*") ~ T) ==> { case x ~ _ ~ z => Aop("*", x, z): Exp } || 
       
   353   (F ~ T_OP("/") ~ T) ==> { case x ~ _ ~ z => Aop("/", x, z): Exp } || 
       
   354   (F ~ T_OP("%") ~ T) ==> { case x ~ _ ~ z => Aop("%", x, z): Exp } || F
       
   355 lazy val F: Parser[List[Token], Exp] = 
       
   356   (IdParser ~ T_LPAREN ~ ListParser(Exp, T_COMMA) ~ T_RPAREN) ==> 
       
   357     { case x ~ _ ~ z ~ _ => Call(x, z): Exp } ||
       
   358   (T_LPAREN ~ Exp ~ T_RPAREN) ==> { case _ ~ y ~ _ => y: Exp } || 
       
   359   IdParser ==> { case x => Var(x): Exp } || 
       
   360   NumParser ==> { case x => Num(x): Exp }
       
   361 
       
   362 // boolean expressions
       
   363 lazy val BExp: Parser[List[Token], BExp] = 
       
   364   (Exp ~ T_OP("==") ~ Exp) ==> { case x ~ _ ~ z => Bop("==", x, z): BExp } || 
       
   365   (Exp ~ T_OP("!=") ~ Exp) ==> { case x ~ _ ~ z => Bop("!=", x, z): BExp } || 
       
   366   (Exp ~ T_OP("<") ~ Exp) ==> { case x ~ _ ~ z => Bop("<", x, z): BExp } || 
       
   367   (Exp ~ T_OP(">") ~ Exp) ==> { case x ~ _ ~ z => Bop("<", z, x): BExp } || 
       
   368   (Exp ~ T_OP("<=") ~ Exp) ==> { case x ~ _ ~ z => Bop("<=", x, z): BExp } || 
       
   369   (Exp ~ T_OP("=>") ~ Exp) ==> { case x ~ _ ~ z => Bop("<=", z, x): BExp }  
       
   370 
       
   371 lazy val Defn: Parser[List[Token], Decl] =
       
   372    (T_KWD("def") ~ IdParser ~ T_LPAREN ~ ListParser(IdParser, T_COMMA) ~ T_RPAREN ~ T_OP("=") ~ Exp) ==>
       
   373      { case x ~ y ~ z ~ w ~ u ~ v ~ r => Def(y, w, r): Decl }
       
   374 
       
   375 lazy val Prog: Parser[List[Token], List[Decl]] =
       
   376   (Defn ~ T_SEMI ~ Prog) ==> { case x ~ _ ~ z => x :: z : List[Decl] } ||
       
   377   (Exp ==> ((s) => List(Main(s)) : List[Decl]))
       
   378 
       
   379 
       
   380 // compiler - built-in functions 
       
   381 // copied from http://www.ceng.metu.edu.tr/courses/ceng444/link/jvm-cpm.html
       
   382 //
       
   383 
       
   384 val library = """
       
   385 .class public XXX.XXX
       
   386 .super java/lang/Object
       
   387 
       
   388 .method public static write(I)V 
       
   389         .limit locals 1 
       
   390         .limit stack 2 
       
   391         getstatic java/lang/System/out Ljava/io/PrintStream; 
       
   392         iload 0
       
   393         invokevirtual java/io/PrintStream/println(I)V 
       
   394         return 
       
   395 .end method
       
   396 
       
   397 """
       
   398 
       
   399 // calculating the maximal needed stack size
       
   400 def max_stack_exp(e: Exp): Int = e match {
       
   401   case Call(_, args) => args.map(max_stack_exp).sum
       
   402   case If(a, e1, e2) => max_stack_bexp(a) + (List(max_stack_exp(e1), max_stack_exp(e2)).max)
       
   403   case Write(e) => max_stack_exp(e) + 1
       
   404   case Var(_) => 1
       
   405   case Num(_) => 1
       
   406   case Aop(_, a1, a2) => max_stack_exp(a1) + max_stack_exp(a2)
       
   407   case Sequence(e1, e2) => List(max_stack_exp(e1), max_stack_exp(e2)).max
       
   408 }
       
   409 def max_stack_bexp(e: BExp): Int = e match {
       
   410   case Bop(_, a1, a2) => max_stack_exp(a1) + max_stack_exp(a2)
       
   411 }
       
   412 
       
   413 
       
   414 // for generating new labels
       
   415 var counter = -1
       
   416 
       
   417 def Fresh(x: String) = {
       
   418   counter += 1
       
   419   x ++ "_" ++ counter.toString()
       
   420 }
       
   421 
       
   422 // convenient string interpolations 
       
   423 // for instructions, labels and methods
       
   424 import scala.language.implicitConversions
       
   425 import scala.language.reflectiveCalls
       
   426 
       
   427 implicit def sring_inters(sc: StringContext) = new {
       
   428     def i(args: Any*): String = "   " ++ sc.s(args:_*) ++ "\n"
       
   429     def l(args: Any*): String = sc.s(args:_*) ++ ":\n"
       
   430     def m(args: Any*): String = sc.s(args:_*) ++ "\n"
       
   431 }
       
   432 
       
   433 
       
   434 type Env = Map[String, Int]
       
   435 
       
   436 
       
   437 def compile_expT(a: Exp, env : Env, name: String) : String = a match {
       
   438   case Num(i) => i"ldc $i"
       
   439   case Var(s) => i"iload ${env(s)}"
       
   440   case Aop("+", a1, a2) => compile_expT(a1, env, "") ++ compile_expT(a2, env, "") ++ i"iadd"
       
   441   case Aop("-", a1, a2) => compile_expT(a1, env, "") ++ compile_expT(a2, env, "") ++ i"isub"
       
   442   case Aop("*", a1, a2) => compile_expT(a1, env, "") ++ compile_expT(a2, env, "") ++ i"imul"
       
   443   case Aop("/", a1, a2) => compile_expT(a1, env, "") ++ compile_expT(a2, env, "") ++ i"idiv"
       
   444   case Aop("%", a1, a2) => compile_expT(a1, env, "") ++ compile_expT(a2, env, "") ++ i"irem"
       
   445   case If(b, a1, a2) => {
       
   446     val if_else = Fresh("If_else")
       
   447     val if_end = Fresh("If_end")
       
   448     compile_bexpT(b, env, if_else) ++
       
   449     compile_expT(a1, env, name) ++
       
   450     i"goto $if_end" ++
       
   451     l"$if_else" ++
       
   452     compile_expT(a2, env, name) ++
       
   453     l"$if_end"
       
   454   }
       
   455   case Call(n, args) => if (name == n) { 
       
   456     val stores = args.zipWithIndex.map { case (x, y) => i"istore $y" } 
       
   457     args.map(a => compile_expT(a, env, "")).mkString ++
       
   458     stores.reverse.mkString ++ 
       
   459     i"goto ${n}_Start" 
       
   460   } else {
       
   461     val is = "I" * args.length
       
   462     args.map(a => compile_expT(a, env, "")).mkString ++
       
   463     i"invokestatic XXX/XXX/${n}(${is})I"
       
   464   }
       
   465   case Sequence(a1, a2) => {
       
   466     compile_expT(a1, env, "") ++ i"pop" ++ compile_expT(a2, env, name)
       
   467   }
       
   468   case Write(a1) => {
       
   469     compile_expT(a1, env, "") ++
       
   470     i"dup" ++
       
   471     i"invokestatic XXX/XXX/write(I)V"
       
   472   }
       
   473 }
       
   474 
       
   475 def compile_bexpT(b: BExp, env : Env, jmp: String) : String = b match {
       
   476   case Bop("==", a1, a2) => 
       
   477     compile_expT(a1, env, "") ++ compile_expT(a2, env, "") ++ i"if_icmpne $jmp"
       
   478   case Bop("!=", a1, a2) => 
       
   479     compile_expT(a1, env, "") ++ compile_expT(a2, env, "") ++ i"if_icmpeq $jmp"
       
   480   case Bop("<", a1, a2) => 
       
   481     compile_expT(a1, env, "") ++ compile_expT(a2, env, "") ++ i"if_icmpge $jmp"
       
   482   case Bop("<=", a1, a2) => 
       
   483     compile_expT(a1, env, "") ++ compile_expT(a2, env, "") ++ i"if_icmpgt $jmp"
       
   484 }
       
   485 
       
   486 
       
   487 def compile_decl(d: Decl) : String = d match {
       
   488   case Def(name, args, a) => { 
       
   489     val env = args.zipWithIndex.toMap
       
   490     val is = "I" * args.length
       
   491     m".method public static $name($is)I" ++
       
   492     m".limit locals ${args.length}" ++
       
   493     m".limit stack ${1 + max_stack_exp(a)}" ++
       
   494     l"${name}_Start" ++   
       
   495     compile_expT(a, env, name) ++
       
   496     i"ireturn" ++ 
       
   497     m".end method\n"
       
   498   }
       
   499   case Main(a) => {
       
   500     m".method public static main([Ljava/lang/String;)V" ++
       
   501     m".limit locals 200" ++
       
   502     m".limit stack 200" ++
       
   503     compile_expT(a, Map(), "") ++
       
   504     i"invokestatic XXX/XXX/write(I)V" ++
       
   505     i"return\n" ++
       
   506     m".end method\n"
       
   507   }
       
   508 }
       
   509 
       
   510 // main compiler functions
       
   511 
       
   512 def time_needed[T](i: Int, code: => T) = {
       
   513   val start = System.nanoTime()
       
   514   for (j <- 1 to i) code
       
   515   val end = System.nanoTime()
       
   516   (end - start)/(i * 1.0e9)
       
   517 }
       
   518 
       
   519 def compile(class_name: String, input: String) : String = {
       
   520   val tks = tokenise(input)
       
   521   val ast = Prog.parse_single(tks)
       
   522   val instructions = ast.map(compile_decl).mkString
       
   523   (library + instructions).replaceAllLiterally("XXX", class_name)
       
   524 }
       
   525 
       
   526 def compile_file(class_name: String) = {
       
   527   val input = io.Source.fromFile(s"${class_name}.fun").mkString
       
   528   val output = compile(class_name, input)
       
   529   scala.tools.nsc.io.File(s"${class_name}.j").writeAll(output)
       
   530 }
       
   531 
       
   532 import scala.sys.process._
       
   533 
       
   534 def compile_run(class_name: String) : Unit = {
       
   535   compile_file(class_name)
       
   536   (s"java -jar jvm/jasmin-2.4/jasmin.jar ${class_name}.j").!!
       
   537   println("Time: " + time_needed(2, (s"java ${class_name}/${class_name}").!))
       
   538 }
       
   539 
       
   540 
       
   541 //examples
       
   542 compile_run("defs")
       
   543 compile_run("fact")