added comp
authorChristian Urban <christian dot urban at kcl dot ac dot uk>
Fri, 29 Nov 2013 09:01:21 +0000
changeset 212 1459e6e29621
parent 211 deece8c6cf3a
child 213 c41f193ffaf6
added comp
progs/compile-lexer.scala
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/progs/compile-lexer.scala	Fri Nov 29 09:01:21 2013 +0000
@@ -0,0 +1,672 @@
+import scala.language.implicitConversions    
+import scala.language.reflectiveCalls 
+import scala.util._
+import scala.annotation.tailrec
+import scala.sys.process._
+
+abstract class Rexp 
+case object NULL extends Rexp
+case object EMPTY extends Rexp
+case class CHAR(c: Char) extends Rexp
+case class ALT(r1: Rexp, r2: Rexp) extends Rexp 
+case class RANGE(cs: List[Char]) extends Rexp 
+case class SEQ(r1: Rexp, r2: Rexp) extends Rexp 
+case class PLUS(r: Rexp) extends Rexp 
+case class STAR(r: Rexp) extends Rexp 
+case class NTIMES(r: Rexp, n: Int) extends Rexp 
+case class NUPTOM(r: Rexp, n: Int, m: Int) extends Rexp
+
+object RANGE {
+  def apply(s: String) : RANGE = RANGE(s.toList)
+}
+def NMTIMES(r: Rexp, n: Int, m: Int) = {
+  if(m < n) throw new IllegalArgumentException("the number m cannot be smaller than n.")
+  else NUPTOM(r, n, m - n)
+}
+
+case class NOT(r: Rexp) extends Rexp 
+case class OPT(r: Rexp) extends Rexp 
+
+// some convenience for typing in regular expressions
+def charlist2rexp(s : List[Char]) : Rexp = s match {
+  case Nil => EMPTY
+  case c::Nil => CHAR(c)
+  case c::s => SEQ(CHAR(c), charlist2rexp(s))
+}
+implicit def string2rexp(s : String) : Rexp = charlist2rexp(s.toList)
+
+implicit def RexpOps (r: Rexp) = new {
+  def | (s: Rexp) = ALT(r, s)
+  def % = STAR(r)
+  def ~ (s: Rexp) = SEQ(r, s)
+}
+
+implicit def stringOps (s: String) = new {
+  def | (r: Rexp) = ALT(s, r)
+  def | (r: String) = ALT(s, r)
+  def % = STAR(s)
+  def ~ (r: Rexp) = SEQ(s, r)
+  def ~ (r: String) = SEQ(s, r)
+}
+
+
+// nullable function: tests whether the regular 
+// expression can recognise the empty string
+def nullable (r: Rexp) : Boolean = r match {
+  case NULL => false
+  case EMPTY => true
+  case CHAR(_) => false
+  case ALT(r1, r2) => nullable(r1) || nullable(r2)
+  case SEQ(r1, r2) => nullable(r1) && nullable(r2)
+  case STAR(_) => true
+  case PLUS(r) => nullable(r)
+  case NTIMES(r, i) => if (i == 0) true else nullable(r)
+  case NUPTOM(r, i, j) => if (i == 0) true else nullable(r)
+  case RANGE(_) => false
+  case NOT(r) => !(nullable(r))
+  case OPT(_) => true
+}
+
+// derivative of a regular expression w.r.t. a character
+def der (c: Char, r: Rexp) : Rexp = r match {
+  case NULL => NULL
+  case EMPTY => NULL
+  case CHAR(d) => if (c == d) EMPTY else NULL
+  case ALT(r1, r2) => ALT(der(c, r1), der(c, r2))
+  case SEQ(r1, r2) => 
+    if (nullable(r1)) ALT(SEQ(der(c, r1), r2), der(c, r2))
+    else SEQ(der(c, r1), r2)
+  case STAR(r) => SEQ(der(c, r), STAR(r))
+  case PLUS(r) => SEQ(der(c, r), STAR(r))
+  case NTIMES(r, i) => 
+    if (i == 0) NULL else der(c, SEQ(r, NTIMES(r, i - 1)))
+  case NUPTOM(r, i, j) =>
+    if (i == 0 && j == 0) NULL else 
+    if (i == 0) ALT(der(c, NTIMES(r, j)), der(c, NUPTOM(r, 0, j - 1)))
+    else der(c, SEQ(r, NUPTOM(r, i - 1, j)))
+  case RANGE(cs) => if (cs contains c) EMPTY else NULL
+  case NOT(r) => NOT(der (c, r))
+  case OPT(r) => der(c, r)
+}
+
+def zeroable (r: Rexp) : Boolean = r match {
+  case NULL => true
+  case EMPTY => false
+  case CHAR(_) => false
+  case ALT(r1, r2) => zeroable(r1) && zeroable(r2)
+  case SEQ(r1, r2) => zeroable(r1) || zeroable(r2)
+  case STAR(_) => false
+  case PLUS(r) => zeroable(r)
+  case NTIMES(r, i) => if (i == 0) false else zeroable(r)
+  case NUPTOM(r, i, j) => if (i == 0) false else zeroable(r)
+  case RANGE(_) => false
+  case NOT(r) => !(zeroable(r))     // bug: incorrect definition for NOT
+  case OPT(_) => false
+}
+
+// derivative w.r.t. a string (iterates der)
+def ders (s: List[Char], r: Rexp) : Rexp = s match {
+  case Nil => r
+  case c::s => ders(s, der(c, r))
+}
+
+
+// regular expressions for the While language
+val SYM = RANGE("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_")
+val DIGIT = RANGE("0123456789")
+val ID = SYM ~ (SYM | DIGIT).% 
+val NUM = PLUS(DIGIT)
+val KEYWORD : Rexp = "skip" | "while" | "do" | "if" | "then" | "else" | "read" | "write" | "true" | "false"
+val SEMI: Rexp = ";"
+val OP: Rexp = ":=" | "==" | "-" | "+" | "*" | "!=" | "<" | ">" | "%" | "/"
+val WHITESPACE = PLUS(" " | "\n" | "\t")
+val RPAREN: Rexp = ")"
+val LPAREN: Rexp = "("
+val BEGIN: Rexp = "{"
+val END: Rexp = "}"
+val ALL = SYM | DIGIT | " " | ":" | ";" | "\"" | "="
+val ALL2 = ALL | "\n"
+val COMMENT2 = ("/*" ~ NOT(ALL.% ~ "*/" ~ ALL.%) ~ "*/")
+val COMMENT = ("/*" ~ ALL2.% ~ "*/") | ("//" ~ ALL.% ~ "\n")
+val STRING = "\"" ~ ALL.% ~ "\""
+
+
+// token for While languag
+abstract class Token
+case object T_WHITESPACE extends Token
+case object T_SEMI extends Token
+case object T_LPAREN extends Token
+case object T_RPAREN extends Token
+case object T_BEGIN extends Token
+case object T_END extends Token
+case object T_COMMENT extends Token
+case class T_ID(s: String) extends Token
+case class T_OP(s: String) extends Token
+case class T_NUM(s: String) extends Token
+case class T_KWD(s: String) extends Token
+case class T_STRING(s: String) extends Token
+case class T_ERR(s: String) extends Token // special error token
+
+
+type TokenFun = String => Token
+type LexRules = List[(Rexp, TokenFun)]
+val While_lexing_rules: LexRules = 
+  List((KEYWORD, (s) => T_KWD(s)),
+       (ID, (s) => T_ID(s)),
+       (COMMENT, (s) => T_COMMENT),
+       (OP, (s) => T_OP(s)),
+       (NUM, (s) => T_NUM(s)),
+       (SEMI, (s) => T_SEMI),
+       (LPAREN, (s) => T_LPAREN),
+       (RPAREN, (s) => T_RPAREN),
+       (BEGIN, (s) => T_BEGIN),
+       (END, (s) => T_END),
+       (STRING, (s) => T_STRING(s.drop(1).dropRight(1))),
+       (WHITESPACE, (s) => T_WHITESPACE))
+
+
+// calculates derivatives until all of them are zeroable
+@tailrec
+def munch(s: List[Char], 
+          pos: Int, 
+          rs: LexRules, 
+          last: Option[(Int, TokenFun)]): Option[(Int, TokenFun)] = {
+  rs match {
+  case Nil => last
+  case rs if (s.length <= pos) => last
+  case rs => {
+    val ders = rs.map({case (r, tf) => (der(s(pos), r), tf)})
+    val rs_nzero = ders.filterNot({case (r, _) => zeroable(r)})
+    val rs_nulls = ders.filter({case (r, _) => nullable(r)})
+    val new_last = if (rs_nulls != Nil) Some((pos, rs_nulls.head._2)) else last
+    munch(s, 1 + pos, rs_nzero, new_last)
+  }
+}}
+
+// iterates the munching function and returns a Token list
+def tokenize(s: String, rs: LexRules) : List[Token] = munch(s.toList, 0, rs, None) match {
+  case None if (s == "") => Nil
+  case None => List(T_ERR(s"Lexing error: $s"))
+  case Some((n, tf)) => {
+    val (head, tail) = s.splitAt(n + 1)
+    tf(head)::tokenize(tail, rs)
+  }
+}
+
+def tokenizer(s:String) : List[Token] = 
+  tokenize(s, While_lexing_rules).filter {
+    case T_ERR(s) => { println(s); sys.exit(-1) }
+    case T_WHITESPACE => false
+    case T_COMMENT => false
+    case _ => true
+  } 
+
+def fromFile(name: String) : String = 
+  io.Source.fromFile(name).mkString
+
+// tokenizer tests
+//println(tokenizer(fromFile("loops.while")).mkString("\n"))
+//println(tokenizer(fromFile("fib.while")).mkString("\n"))
+//println(tokenizer(fromFile("collatz.while")).mkString("\n"))
+
+
+
+
+
+// Parser - Abstract syntax trees
+abstract class Stmt
+abstract class AExp
+abstract class BExp 
+type Block = List[Stmt]
+case object Skip extends Stmt
+case class If(a: BExp, bl1: Block, bl2: Block) extends Stmt
+case class While(b: BExp, bl: Block) extends Stmt
+case class Assign(s: String, a: AExp) extends Stmt
+case class Read(s: String) extends Stmt
+case class Write(s: String) extends Stmt
+case class WriteS(s: String) extends Stmt
+
+case class Var(s: String) extends AExp
+case class Num(i: Int) extends AExp
+case class Aop(o: String, a1: AExp, a2: AExp) extends AExp
+
+case object True extends BExp
+case object False extends BExp
+case class Bop(o: String, a1: AExp, a2: AExp) extends BExp
+
+// Parser combinators
+abstract class Parser[I <% Seq[_], T] {
+  def parse(ts: I): Set[(T, I)]
+
+  def parse_all(ts: I) : Set[T] =
+    for ((head, tail) <- parse(ts); if (tail.isEmpty)) yield head
+
+  def parse_single(ts: I) : T = parse_all(ts).toList match {
+    case List(t) => t
+    case _ => { println ("Parse Error") ; sys.exit(-1) }
+  }
+}
+
+class SeqParser[I <% Seq[_], T, S](p: => Parser[I, T], q: => Parser[I, S]) extends Parser[I, (T, S)] {
+  def parse(sb: I) = 
+    for ((head1, tail1) <- p.parse(sb); 
+         (head2, tail2) <- q.parse(tail1)) yield ((head1, head2), tail2)
+}
+
+class AltParser[I <% Seq[_], T](p: => Parser[I, T], q: => Parser[I, T]) extends Parser[I, T] {
+  def parse(sb: I) = p.parse(sb) ++ q.parse(sb)   
+}
+
+class FunParser[I <% Seq[_], T, S](p: => Parser[I, T], f: T => S) extends Parser[I, S] {
+  def parse(sb: I) = 
+    for ((head, tail) <- p.parse(sb)) yield (f(head), tail)
+}
+
+
+case class TokParser(tok: Token) extends Parser[List[Token], Token] {
+  def parse(ts: List[Token]) = ts match {
+    case t::ts if (t == tok) => Set((t, ts)) 
+    case _ => Set ()
+  }
+}
+implicit def token2tparser(t: Token) = TokParser(t)
+
+case object NumParser extends Parser[List[Token], Int] {
+  def parse(ts: List[Token]) = ts match {
+    case T_NUM(s)::ts => Set((s.toInt, ts)) 
+    case _ => Set ()
+  }
+}
+
+case object IdParser extends Parser[List[Token], String] {
+  def parse(ts: List[Token]) = ts match {
+    case T_ID(s)::ts => Set((s, ts)) 
+    case _ => Set ()
+  }
+}
+
+case object StringParser extends Parser[List[Token], String] {
+  def parse(ts: List[Token]) = ts match {
+    case T_STRING(s)::ts => Set((s, ts)) 
+    case _ => Set ()
+  }
+}
+
+implicit def ParserOps[I<% Seq[_], T](p: Parser[I, T]) = new {
+  def || (q : => Parser[I, T]) = new AltParser[I, T](p, q)
+  def ==>[S] (f: => T => S) = new FunParser[I, T, S](p, f)
+  def ~[S] (q : => Parser[I, S]) = new SeqParser[I, T, S](p, q)
+}
+implicit def TokOps(t: Token) = new {
+  def || (q : => Parser[List[Token], Token]) = new AltParser[List[Token], Token](t, q)
+  def ==>[S] (f: => Token => S) = new FunParser[List[Token], Token, S](t, f)
+  def ~[S](q : => Parser[List[Token], S]) = new SeqParser[List[Token], Token, S](t, q)
+}
+
+// arithmetic expressions
+lazy val AExp: Parser[List[Token], AExp] = 
+  (T ~ T_OP("+") ~ AExp) ==> { case ((x, y), z) => Aop("+", x, z): AExp } ||
+  (T ~ T_OP("-") ~ AExp) ==> { case ((x, y), z) => Aop("-", x, z): AExp } || T  
+lazy val T: Parser[List[Token], AExp] = 
+  (F ~ T_OP("*") ~ T) ==> { case ((x, y), z) => Aop("*", x, z): AExp } || 
+  (F ~ T_OP("/") ~ T) ==> { case ((x, y), z) => Aop("*", x, z): AExp } || 
+  (F ~ T_OP("%") ~ T) ==> { case ((x, y), z) => Aop("*", x, z): AExp } || F
+lazy val F: Parser[List[Token], AExp] = 
+  (T_LPAREN ~ AExp ~ T_RPAREN) ==> { case ((x, y), z) => y: AExp }|| 
+  IdParser ==> { case x => Var(x): AExp } || 
+  NumParser ==> { case x => Num(x): AExp }
+
+// boolean expressions
+lazy val BExp: Parser[List[Token], BExp] = 
+  (AExp ~ T_OP("==") ~ AExp) ==> { case ((x, y), z) => Bop("==", x, z): BExp } || 
+  (AExp ~ T_OP("!=") ~ AExp) ==> { case ((x, y), z) => Bop("!=", x, z): BExp } || 
+  (AExp ~ T_OP("<") ~ AExp) ==> { case ((x, y), z) => Bop("<", x, z): BExp } || 
+  (AExp ~ T_OP(">") ~ AExp) ==> { case ((x, y), z) => Bop("<", z, x): BExp } || 
+  (T_KWD("true") ==> ((_) => True)) || 
+  (T_KWD("false") ==> ((_) => False: BExp))
+
+lazy val Stmt: Parser[List[Token], Stmt] =
+  (T_KWD("skip") ==> ((_) => Skip: Stmt)) ||
+  (IdParser ~ T_OP(":=") ~ AExp) ==> { case ((x, y), z) => Assign(x, z): Stmt } ||
+  (T_KWD("if") ~ BExp ~ T_KWD("then") ~ Block ~ T_KWD("else") ~ Block) ==>
+    { case (((((x,y),z),u),v),w) => If(y, u, w): Stmt } ||
+  (T_KWD("while") ~ BExp ~ T_KWD("do") ~ Block) ==> { case (((x, y), z), w) => While(y, w) } ||
+  (T_KWD("read") ~ IdParser) ==> { case (x, y) => Read(y) } ||
+  (T_KWD("write") ~ IdParser) ==> { case (x, y) => Write(y) } ||
+  (T_KWD("write") ~ StringParser) ==> { case (x, y) => WriteS(y) }
+
+lazy val Stmts: Parser[List[Token], Block] =
+  (Stmt ~ T_SEMI ~ Stmts) ==> { case ((x, y), z) => x :: z : Block } ||
+  (Stmt ==> ((s) => List(s) : Block))
+
+lazy val Block: Parser[List[Token], Block] =
+  (T_BEGIN ~ Stmts ~ T_END) ==> { case ((x, y), z) => y : Block } || 
+  (Stmt ==> ((s) => List(s)))
+
+
+
+// parser examples
+val p1 = "x := 5"
+val p1_toks = tokenizer(p1) 
+val p1_ast = Block.parse_all(p1_toks)
+//println(p1_toks)
+//println(p1_ast)
+
+val p2 = "{ x := 5; y := 8}"
+val p2_toks = tokenizer(p2) 
+val p2_ast = Block.parse_all(p2_toks)
+//println(p2_ast)
+
+val p3 = "5 == 6"
+val p3_toks = tokenizer(p3) 
+val p3_ast = BExp.parse_all(p3_toks)
+//println(p3_ast)
+
+val p4 = "true"
+val p4_toks = tokenizer(p4) 
+val p4_ast = BExp.parse_all(p4_toks)
+//println(p4_ast)
+
+val p5 = "if true then skip else skip"
+val p5_toks = tokenizer(p5) 
+val p5_ast = Stmt.parse_all(p5_toks)
+//println(p5_ast)
+
+val p6 = "if true then x := 5 else x := 10"
+val p6_toks = tokenizer(p6) 
+val p6_ast = Stmt.parse_all(p6_toks)
+//println(p6_ast)
+
+val p7 = "if false then x := 5 else x := 10"
+val p7_toks = tokenizer(p7) 
+val p7_ast = Stmt.parse_all(p7_toks)
+//println(p7_ast)
+
+val p8 = "write x; write \"foo\"; read x "
+val p8_toks = tokenizer(p8) 
+val p8_ast = Stmts.parse_all(p8_toks)
+//println(p8_ast)
+
+// multiplication
+val p9 = """  x := 5;
+              y := 4;
+              r := 0;
+              while y > 0 do {
+                 r := r + x;
+                 y := y - 1
+              } 
+         """
+val p9_toks = tokenizer(p9) 
+val p9_ast = Stmts.parse_all(p9_toks)
+//println(p9_ast)
+
+// fibonacci numbers
+val p10 = """
+ write "Fib: ";
+ read n;
+ minus1 := 0;
+ minus2 := 1;
+ temp := 0;
+ while n > 0 do  {
+   temp := minus2;
+   minus2 := minus1 + minus2;
+   minus1 := temp;
+   n := n - 1
+ };
+ write "Result:";
+ write minus2
+"""
+val p10_toks = tokenizer(p10) 
+val p10_ast = Stmts.parse_all(p10_toks)
+//println(p10_ast)
+
+
+// an interpreter for the WHILE language
+type Env = Map[String, Int]
+
+def eval_aexp(a: AExp, env : Env) : Int = a match {
+  case Num(i) => i
+  case Var(s) => env(s)
+  case Aop("+", a1, a2) => eval_aexp(a1, env) + eval_aexp(a2, env)
+  case Aop("-", a1, a2) => eval_aexp(a1, env) - eval_aexp(a2, env)
+  case Aop("*", a1, a2) => eval_aexp(a1, env) * eval_aexp(a2, env)
+}
+
+def eval_bexp(b: BExp, env: Env) : Boolean = b match {
+  case True => true
+  case False => false
+  case Bop("==", a1, a2) => eval_aexp(a1, env) == eval_aexp(a2, env)
+  case Bop("!=", a1, a2) => !(eval_aexp(a1, env) == eval_aexp(a2, env))
+  case Bop("<", a1, a2) => eval_aexp(a1, env) < eval_aexp(a2, env)
+}
+
+def eval_stmt(s: Stmt, env: Env) : Env = s match {
+  case Skip => env
+  case Assign(x, a) => env + (x -> eval_aexp(a, env))
+  case If(b, bl1, bl2) => if (eval_bexp(b, env)) eval_bl(bl1, env) else eval_bl(bl2, env) 
+  case While(b, bl) => 
+    if (eval_bexp(b, env)) eval_stmt(While(b, bl), eval_bl(bl, env))
+    else env
+  case WriteS(s: String) => { println(s); env }
+  case Write(s: String) => { println(env(s)); env }
+  case Read(s: String) => tokenizer(Console.readLine) match {
+    case List(T_NUM(n)) => env + (s -> n.toInt)
+    case _ => { println("not a number"); eval_stmt(Read(s: String), env) }
+  }
+}
+
+def eval_bl(bl: Block, env: Env) : Env = bl match {
+  case Nil => env
+  case s::bl => eval_bl(bl, eval_stmt(s, env))
+}
+
+def eval(bl: Block) : Env = eval_bl(bl, Map())
+
+def interpret(s: String): Unit =
+  eval(Stmts.parse_all(tokenizer(s)).head)
+
+// interpreter example
+//interpret(p10)
+
+
+
+// compiler - built-in functions 
+// copied from http://www.ceng.metu.edu.tr/courses/ceng444/link/jvm-cpm.html
+//
+
+val beginning = """
+.class public XXX.XXX
+.super java/lang/Object
+
+.method public <init>()V
+        aload_0
+        invokenonvirtual java/lang/Object/<init>()V
+        return
+.end method
+
+.method public static write(I)V 
+        .limit locals 5 
+        .limit stack 5 
+        iload 0 
+        getstatic java/lang/System/out Ljava/io/PrintStream; 
+        swap 
+        invokevirtual java/io/PrintStream/println(I)V 
+        return 
+.end method
+
+.method public static writes(Ljava/lang/String;)V
+       .limit stack 2
+       .limit locals 2
+       getstatic java/lang/System/out Ljava/io/PrintStream;
+       aload 0
+       invokevirtual java/io/PrintStream/println(Ljava/lang/String;)V
+       return
+.end method
+
+.method public static read()I 
+      .limit locals 10 
+      .limit stack 10
+
+      ldc 0 
+      istore 1  ; this will hold our final integer 
+Label1: 
+      getstatic java/lang/System/in Ljava/io/InputStream; 
+      invokevirtual java/io/InputStream/read()I 
+      istore 2 
+      iload 2 
+      ldc 10   ; the newline delimiter 
+      isub 
+      ifeq Label2 
+      iload 2 
+      ldc 32   ; the space delimiter 
+      isub 
+      ifeq Label2
+
+      iload 2 
+      ldc 48   ; we have our digit in ASCII, have to subtract it from 48 
+      isub 
+      ldc 10 
+      iload 1 
+      imul 
+      iadd 
+      istore 1 
+      goto Label1 
+Label2: 
+      ;when we come here we have our integer computed in Local Variable 1 
+      iload 1 
+      ireturn 
+.end method
+
+.method public static main([Ljava/lang/String;)V
+      .limit locals 200
+      .limit stack 200
+
+"""
+
+val ending = """
+
+      return
+
+.end method
+"""
+
+// for generating new labels
+var counter = -1
+
+def Fresh(x: String) = {
+  counter += 1
+  x ++ "_" ++ counter.toString()
+}
+
+type Mem = Map[String, String]
+type Instrs = List[String]
+
+def compile_aexp(a: AExp, env : Mem) : Instrs = a match {
+  case Num(i) => List("ldc " + i.toString + "\n")
+  case Var(s) => List("iload " + env(s) + "\n")
+  case Aop("+", a1, a2) => compile_aexp(a1, env) ++ compile_aexp(a2, env) ++ List("iadd\n")
+  case Aop("-", a1, a2) => compile_aexp(a1, env) ++ compile_aexp(a2, env) ++ List("isub\n")
+  case Aop("*", a1, a2) => compile_aexp(a1, env) ++ compile_aexp(a2, env) ++ List("imul\n")
+}
+
+def compile_bexp(b: BExp, env : Mem, jmp: String) : Instrs = b match {
+  case True => Nil
+  case False => List("goto " + jmp + "\n")
+  case Bop("=", a1, a2) => 
+    compile_aexp(a1, env) ++ compile_aexp(a2, env) ++ List("if_icmpne " + jmp + "\n")
+  case Bop("!=", a1, a2) => 
+    compile_aexp(a1, env) ++ compile_aexp(a2, env) ++ List("if_icmpeq " + jmp + "\n")
+  case Bop("<", a1, a2) => 
+    compile_aexp(a1, env) ++ compile_aexp(a2, env) ++ List("if_icmpge " + jmp + "\n")
+}
+
+
+def compile_stmt(s: Stmt, env: Mem) : (Instrs, Mem) = s match {
+  case Skip => (Nil, env)
+  case Assign(x, a) => {
+    val index = if (env.isDefinedAt(x)) env(x) else env.keys.size.toString
+    (compile_aexp(a, env) ++ 
+     List("istore " + index + "\n"), env + (x -> index))
+  } 
+  case If(b, bl1, bl2) => {
+    val if_else = Fresh("If_else")
+    val if_end = Fresh("If_end")
+    val (instrs1, env1) = compile_bl(bl1, env)
+    val (instrs2, env2) = compile_bl(bl2, env1)
+    (compile_bexp(b, env, if_else) ++
+     instrs1 ++
+     List("goto " + if_end + "\n") ++
+     List("\n" + if_else + ":\n\n") ++
+     instrs2 ++
+     List("\n" + if_end + ":\n\n"), env2)
+  }
+  case While(b, bl) => {
+    val loop_begin = Fresh("Loop_begin")
+    val loop_end = Fresh("Loop_end")
+    val (instrs1, env1) = compile_bl(bl, env)
+    (List("\n" + loop_begin + ":\n\n") ++
+     compile_bexp(b, env, loop_end) ++
+     instrs1 ++
+     List("goto " + loop_begin + "\n") ++
+     List("\n" + loop_end + ":\n\n"), env1)
+  }
+  case Write(x) => 
+    (List("iload " + env(x) + "\n" + 
+          "invokestatic XXX/XXX/write(I)V\n"), env)
+  case WriteS(x) => 
+    (List("ldc \"" + x + "\"\n" + 
+          "invokestatic XXX/XXX/writes(Ljava/lang/String;)V\n"), env)
+  case Read(x) => {
+    val index = if (env.isDefinedAt(x)) env(x) else env.keys.size.toString
+    (List("invokestatic XXX/XXX/read()I\n" + 
+          "istore " + index + "\n"), env + (x -> index))
+  } 
+}
+
+
+def compile_bl(bl: Block, env: Mem) : (Instrs, Mem) = bl match {
+  case Nil => (Nil, env)
+  case s::bl => {
+    val (instrs1, env1) = compile_stmt(s, env)
+    val (instrs2, env2) = compile_bl(bl, env1)
+    (instrs1 ++ instrs2, env2)
+  }
+}
+
+def compile(class_name: String, input: String) : String = {
+  val tks = tokenizer(input)
+  val ast = Stmts.parse_single(tks)
+  val instructions = compile_bl(ast, Map.empty)._1
+  (beginning ++ instructions.mkString ++ ending).replaceAllLiterally("XXX", class_name)
+}
+
+
+def compile_file(file_name: String) = {
+  val class_name = file_name.split('.')(0)
+  val output = compile(class_name, fromFile(file_name))
+  val fw = new java.io.FileWriter(class_name + ".j") 
+  fw.write(output) 
+  fw.close()
+}
+
+def time_needed[T](i: Int, code: => T) = {
+  val start = System.nanoTime()
+  for (j <- 1 to i) code
+  val end = System.nanoTime()
+  (end - start)/(i * 1.0e9)
+}
+
+
+def compile_run(file_name: String) : Unit = {
+  val class_name = file_name.split('.')(0)
+  compile_file(file_name)
+  val test = ("java -jar jvm/jasmin-2.4/jasmin.jar " + class_name + ".j").!!
+  //("java " + class_name + "/" + class_name).!
+}
+
+
+//examples
+//println(compile("test", p9))
+//compile_run("loops.while")
+compile_run("fib.while")
+//compile_run("test.while")