变量版解释器

package com.moon.tina

/**
  * Created by lin on 2017/5/10.
  */
case class Instruction(name:String,pos:Int)

case class ExecuteInstructions(instructions:List[Instruction],numbers:List[Int],names:List[String])

case class TinaInterpreter() {
  var stack:List[Int]=List[Int]()
  var environment:Map[String,Int]=Map[String,Int]()
  var answer:Int= _

  def loadValue(num:Int): Unit ={
    stack=num +:stack
  }

  def printAnswer(): Unit ={
    answer=stack.head
  }

  def addTwoValues(): Unit ={
    val firstNum=stack.head
    stack=stack.drop(1)
    val secondNum=stack.head
    stack=stack.drop(1)
    val total=firstNum+secondNum
    stack=total+:stack
  }

  def storeName(name:String): Unit ={
    val value=stack.head
    stack=stack.drop(1)
    environment=environment+(name->value)
  }

  def loadName(name:String): Unit ={
    val value=environment(name)
    stack=value+:stack
  }

  def parseArgument(name:String,pos:Int,eInstructions:ExecuteInstructions):Any={
    if (name=="LOAD_VALUE"){
      pos
    }else if(name=="LOAD_NAME"||name=="STORE_NAME"){
      eInstructions.names(pos)
    }else None
  }

  def run(einstructions: ExecuteInstructions): Unit ={
    val instructions=einstructions.instructions
    val numbers=einstructions.numbers
    for(eachStep <- instructions){
      val argument=parseArgument(eachStep.name,eachStep.pos,einstructions)
      if(eachStep.name=="LOAD_VALUE"){
        val number=numbers(argument.asInstanceOf[Int])
        loadValue(number)
      }else if(eachStep.name=="ADD_TWO_VALUES"){
        addTwoValues()
      }else if(eachStep.name=="PRINT_ANSWER"){
        printAnswer()
      }else if(eachStep.name=="STORE_NAME"){
        storeName(argument.asInstanceOf[String])
      }else if(eachStep.name=="LOAD_NAME"){
        loadName(argument.asInstanceOf[String])
      }

    }
  }
}

object TinaInterpreter{
  def main(args: Array[String]) {
    val whatToExecute=ExecuteInstructions(List(
      Instruction("LOAD_VALUE",0),
      Instruction("STORE_NAME",0),
      Instruction("LOAD_VALUE",1),
      Instruction("STORE_NAME",1),
      Instruction("LOAD_NAME",0),
      Instruction("LOAD_NAME",1),
      Instruction("ADD_TWO_VALUES",-1),
      Instruction("LOAD_VALUE",2),
      Instruction("ADD_TWO_VALUES",-1),
      Instruction("PRINT_ANSWER",-1)
    ),
      List(7,13,21),
      List("a","b")
    )

    val interpreter=TinaInterpreter()
    interpreter.run(whatToExecute)
    println(interpreter.stack)
  }
}

你可能感兴趣的:(变量版解释器)