LARA

Stack-Based Virtual Machine for Expression Evaluation

Check these instructions in JVM Spec: iadd, imul, iload, istore, bipush

abstract class Instruction 
case class Bipush(c : Int) extends Instruction
case class Iadd extends Instruction
case class Imul extends Instruction
case class Iload(slot : Int) extends Instruction
case class Istore(slot : Int) extends Instruction
 
class VM(var code    : Array[Instruction],
         var pc      : Int,        // program counter (current instruction)
         var local   : Array[Int], // local variables
         var operand : Array[Int], // operand stack
         var top     : Int         // top of operand stack
       ) 
{
  def step = {
    code(pc) match {
      case Bipush(c) => 
        operand(top + 1) = c
        top = top + 1
      case Iadd() =>
        operand(top - 1) = operand(top - 1) + operand(top)
        top = top - 1
      case Imul() => 
        operand(top - 1) = operand(top - 1) * operand(top)
        top = top - 1
      case Iload(n) => 
        operand(top + 1) = local(n)
        top = top + 1
      case Istore(n) => 
        local(n) = operand(top)
        top = top - 1
    }
    pc = pc + 1
  }
  def run = {
    while (pc < code.length)
      step
  }
}
 
object Test {
  def main(args : Array[String]) = {
    val code : Array[Instruction] = List(
      Iload(0),
      Iload(1),
      Imul(),
      Iload(1),
      Iload(2),
      Imul(),
      Iadd(),
      Iload(0),
      Iload(2),
      Imul(),
      Iadd(),
      Bipush(2),
      Imul()).toArray
    val local : Array[Int] = List(3,4,5).toArray
    val operand = new Array[Int](10)
    val vm = new VM(code,0,local,operand,0);
    vm.run
    println(vm.operand(vm.top))
  }
}