// A Small Compiler for a simple functional language

// Abstract syntax trees
abstract class Exp
abstract class BExp 
abstract class Decl

// function declarations
case class Def(name: String, args: List[String], body: Exp) extends Decl
case class Main(e: Exp) extends Decl

// expressions
case class Call(name: String, args: List[Exp]) extends Exp
case class If(a: BExp, e1: Exp, e2: Exp) extends Exp
case class Write(e: Exp) extends Exp
case class Var(s: String) extends Exp
case class Num(i: Int) extends Exp
case class Aop(o: String, a1: Exp, a2: Exp) extends Exp
case class Sequ(e1: Exp, e2: Exp) extends Exp

// boolean expressions
case class Bop(o: String, a1: Exp, a2: Exp) extends BExp

// calculating the maximal needed stack size
def max_stack_exp(e: Exp): Int = e match {
  case Call(_, args) => args.map(max_stack_exp).sum
  case If(a, e1, e2) => max_stack_bexp(a) + (List(max_stack_exp(e1), max_stack_exp(e2)).max)
  case Write(e) => max_stack_exp(e) + 1
  case Var(_) => 1
  case Num(_) => 1
  case Aop(_, a1, a2) => max_stack_exp(a1) + max_stack_exp(a2)
  case Sequ(e1, e2) => List(max_stack_exp(e1), max_stack_exp(e2)).max
}
def max_stack_bexp(e: BExp): Int = e match {
  case Bop(_, a1, a2) => max_stack_exp(a1) + max_stack_exp(a2)
}

// compiler - built-in functions 
// copied from http://www.ceng.metu.edu.tr/courses/ceng444/link/jvm-cpm.html
//

val library = """
.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

"""

// for generating new labels
var counter = -1

def Fresh(x: String) = {
  counter += 1
  x ++ "_" ++ counter.toString()
}


type Env = Map[String, Int]
type Instrs = List[String]

// compile expressions
def compile_exp(a: Exp, env : Env) : Instrs = a match {
  case Num(i) => List("ldc " + i.toString + "\n")
  case Var(s) => List("iload " + env(s).toString + "\n")
  case Aop("+", a1, a2) => compile_exp(a1, env) ++ compile_exp(a2, env) ++ List("iadd\n")
  case Aop("-", a1, a2) => compile_exp(a1, env) ++ compile_exp(a2, env) ++ List("isub\n")
  case Aop("*", a1, a2) => compile_exp(a1, env) ++ compile_exp(a2, env) ++ List("imul\n")
  case Aop("/", a1, a2) => compile_exp(a1, env) ++ compile_exp(a2, env) ++ List("idiv\n")
  case Aop("%", a1, a2) => compile_exp(a1, env) ++ compile_exp(a2, env) ++ List("irem\n")
  case If(b, a1, a2) => {
    val if_else = Fresh("If_else")
    val if_end = Fresh("If_end")
    compile_bexp(b, env, if_else) ++
    compile_exp(a1, env) ++
    List("goto " + if_end + "\n") ++
    List("\n" + if_else + ":\n\n") ++
    compile_exp(a2, env) ++
    List("\n" + if_end + ":\n\n")
  }
  case Call(n, args) => {
    val is = "I" * args.length
    args.flatMap(a => compile_exp(a, env)) ++
    List ("invokestatic XXX/XXX/" + n + "(" + is + ")I\n")
  }
  case Sequ(a1, a2) => {
    compile_exp(a1, env) ++ List("pop\n") ++ compile_exp(a2, env)
  }
  case Write(a1) => {
    compile_exp(a1, env) ++
    List("dup\n",
         "invokestatic XXX/XXX/write(I)V\n")
  }
}

// compile boolean expressions
def compile_bexp(b: BExp, env : Env, jmp: String) : Instrs = b match {
  case Bop("==", a1, a2) => 
    compile_exp(a1, env) ++ compile_exp(a2, env) ++ List("if_icmpne " + jmp + "\n")
  case Bop("!=", a1, a2) => 
    compile_exp(a1, env) ++ compile_exp(a2, env) ++ List("if_icmpeq " + jmp + "\n")
  case Bop("<", a1, a2) => 
    compile_exp(a1, env) ++ compile_exp(a2, env) ++ List("if_icmpge " + jmp + "\n")
  case Bop("<=", a1, a2) => 
    compile_exp(a1, env) ++ compile_exp(a2, env) ++ List("if_icmpgt " + jmp + "\n")
}

// compile function for declarations and main
def compile_decl(d: Decl) : Instrs = d match {
  case Def(name, args, a) => { 
    val env = args.zipWithIndex.toMap
    val is = "I" * args.length
    List(".method public static " + name + "(" + is + ")I \n",
         ".limit locals " + args.length.toString + "\n",
         ".limit stack " + (1 + max_stack_exp(a)).toString + "\n",
         name + "_Start:\n") ++   
    compile_exp(a, env) ++
    List("ireturn\n",
         ".end method \n\n")
  }
  case Main(a) => {
    List(".method public static main([Ljava/lang/String;)V\n",
         ".limit locals 200\n",
         ".limit stack 200\n") ++
    compile_exp(a, Map()) ++
    List("invokestatic XXX/XXX/write(I)V\n",
         "return\n",
         ".end method\n")
  }
}

// main compilation function
def compile(prog: List[Decl], class_name: String) : String = {
  val instructions = prog.flatMap(compile_decl).mkString
  (library + instructions).replaceAllLiterally("XXX", class_name)
}




// example program (factorials)

val test_prog = 
  List(Def("fact", List("n"),
         If(Bop("==",Var("n"),Num(0)),
            Num(1),
            Aop("*",Var("n"),
                    Call("fact",List(Aop("-",Var("n"),Num(1))))))),

       Def("facT",List("n", "acc"),
         If(Bop("==",Var("n"),Num(0)),
            Var("acc"),
            Call("facT",List(Aop("-",Var("n"),Num(1)), 
                             Aop("*",Var("n"),Var("acc")))))),

       Main(Sequ(Write(Call("fact",List(Num(10)))),
                 Write(Call("facT",List(Num(10), Num(1)))))))

// prints out the JVM instructions
println(compile(test, "fact"))
