A virtual machine implements a computer in software.

Task[edit]
Write a virtual machine interpreter. This interpreter should be able to run virtual
assembly language programs created via the task. This is a
byte-coded, 32-bit word stack based virtual machine.

The program should read input from a file and/or stdin, and write output to a file and/or
stdout.

Input format:

Given the following program:

count = 1;
while (count < 10) {
    print("count is: ", count, "\n");
    count = count + 1;
}

The output from the Code generator is a virtual assembly code program:



 Output from gen, input to VM



Datasize: 1 Strings: 2
"count is: "
"\n"
    0 push  1
    5 store [0]
   10 fetch [0]
   15 push  10
   20 lt
   21 jz     (43) 65
   26 push  0
   31 prts
   32 fetch [0]
   37 prti
   38 push  1
   43 prts
   44 fetch [0]
   49 push  1
   54 add
   55 store [0]
   60 jmp    (-51) 10
   65 halt

The first line of the input specifies the datasize required and the number of constant
strings, in the order that they are reference via the code.

The data can be stored in a separate array, or the data can be stored at the beginning of
the stack. Data is addressed starting at 0. If there are 3 variables, the 3rd one if
referenced at address 2.

If there are one or more constant strings, they come next. The code refers to these
strings by their index. The index starts at 0. So if there are 3 strings, and the code
wants to reference the 3rd string, 2 will be used.

Next comes the actual virtual assembly code. The first number is the code address of that
instruction. After that is the instruction mnemonic, followed by optional operands,
depending on the instruction.

Registers:

sp:

   the stack pointer - points to the next top of stack.  The stack is a 32-bit integer
   array.

pc:

   the program counter - points to the current instruction to be performed.  The code is an
   array of bytes.

Data:

   data
   string pool

Instructions:

Each instruction is one byte. The following instructions also have a 32-bit integer
operand:

fetch [index]

where index is an index into the data array.

store [index]

where index is an index into the data array.

push n

where value is a 32-bit integer that will be pushed onto the stack.

jmp (n) addr

where (n) is a 32-bit integer specifying the distance between the current location and the
desired location. addr is an unsigned value of the actual code address.

jz (n) addr

where (n) is a 32-bit integer specifying the distance between the current location and the
desired location. addr is an unsigned value of the actual code address.

The following instructions do not have an operand. They perform their operation directly
against the stack:

For the following instructions, the operation is performed against the top two entries in
the stack:

add
sub
mul
div
mod
lt
gt
le
ge
eq
ne
and
or

For the following instructions, the operation is performed against the top entry in the
stack:

neg
not

Print the word at stack top as a character.

prtc

Print the word at stack top as an integer.

prti

Stack top points to an index into the string pool. Print that entry.

prts

Unconditional stop.

halt

 A simple example virtual machine

def run_vm(data_size)
    int stack[data_size + 1000]
    set stack[0..data_size - 1] to 0
    int pc = 0
    while True:
        op = code[pc]
        pc += 1
 
        if op == FETCH:
            stack.append(stack[bytes_to_int(code[pc:pc+word_size])[0]]);
            pc += word_size
        elif op == STORE:
            stack[bytes_to_int(code[pc:pc+word_size])[0]] = stack.pop();
            pc += word_size
        elif op == PUSH:
            stack.append(bytes_to_int(code[pc:pc+word_size])[0]);
            pc += word_size
        elif op == ADD:   stack[-2] += stack[-1]; stack.pop()
        elif op == SUB:   stack[-2] -= stack[-1]; stack.pop()
        elif op == MUL:   stack[-2] *= stack[-1]; stack.pop()
        elif op == DIV:   stack[-2] /= stack[-1]; stack.pop()
        elif op == MOD:   stack[-2] %= stack[-1]; stack.pop()
        elif op == LT:    stack[-2] = stack[-2] <  stack[-1]; stack.pop()
        elif op == GT:    stack[-2] = stack[-2] >  stack[-1]; stack.pop()
        elif op == LE:    stack[-2] = stack[-2] <= stack[-1]; stack.pop()
        elif op == GE:    stack[-2] = stack[-2] >= stack[-1]; stack.pop()
        elif op == EQ:    stack[-2] = stack[-2] == stack[-1]; stack.pop()
        elif op == NE:    stack[-2] = stack[-2] != stack[-1]; stack.pop()
        elif op == AND:   stack[-2] = stack[-2] and stack[-1]; stack.pop()
        elif op == OR:    stack[-2] = stack[-2] or  stack[-1]; stack.pop()
        elif op == NEG:   stack[-1] = -stack[-1]
        elif op == NOT:   stack[-1] = not stack[-1]
        elif op == JMP:   pc += bytes_to_int(code[pc:pc+word_size])[0]
        elif op == JZ:    if stack.pop() then pc += word_size else pc += bytes_to_int(code[pc:pc+word_size])[0]
        elif op == PRTC:  print stack[-1] as a character; stack.pop()
        elif op == PRTS:  print the constant string referred to by stack[-1]; stack.pop()
        elif op == PRTI:  print stack[-1] as an integer; stack.pop()
        elif op == HALT:  break
 Additional examples
Your solution should pass all the test cases above and the additional tests found Here.

Reference
The C and Python versions can be considered reference implementations.

Related Tasks
 Lexical Analyzer task
 Syntax Analyzer task
 Code Generator task
 AST Interpreter task

import "/dynamic" for Enum
import "/crypto" for Bytes
import "/fmt" for Conv
import "/ioutil" for FileUtil
 
var codes = [
    "fetch",
    "store",
    "push",
    "add",
    "sub",
    "mul",
    "div",
    "mod",
    "lt",
    "gt",
    "le",
    "ge",
    "eq",
    "ne",
    "and",
    "or",
    "neg",
    "not",
    "jmp",
    "jz",
    "prtc",
    "prts",
    "prti",
    "halt"
]
 
var Code = Enum.create("Code", codes)
 
var codeMap = {
    "fetch": Code.fetch,
    "store": Code.store,
    "push":  Code.push,
    "add":   Code.add,
    "sub":   Code.sub,
    "mul":   Code.mul,
    "div":   Code.div,
    "mod":   Code.mod,
    "lt":    Code.lt,
    "gt":    Code.gt,
    "le":    Code.le,
    "ge":    Code.ge,
    "eq":    Code.eq,
    "ne":    Code.ne,
    "and":   Code.and,
    "or":    Code.or,
    "neg":   Code.neg,
    "not":   Code.not,
    "jmp":   Code.jmp,
    "jz":    Code.jz,
    "prtc":  Code.prtc,
    "prts":  Code.prts,
    "prti":  Code.prti,
    "halt":  Code.halt
}
 
var object     = []
var stringPool = []
 
var reportError = Fn.new { |msg| Fiber.abort("error : %(msg)") }
 
var emitByte = Fn.new { |c| object.add(c) }
 
var emitWord = Fn.new { |n|
    var bs = Bytes.fromIntLE(n)
    for (b in bs) emitByte.call(b)
}
 
// Converts the 4 bytes starting at object[pc] to an unsigned 32 bit integer
// and thence to a signed 32 bit integer
var toInt32LE = Fn.new { |pc|
    var x = Bytes.toIntLE(object[pc...pc+4])
    if (x >= 2.pow(31)) x = x - 2.pow(32)
    return x
}
 
/* Virtual Machine interpreter */
 
var runVM = Fn.new { |dataSize|
    var stack = List.filled(dataSize + 1, 0)
    var pc = 0
    while (true) {
        var op = object[pc]
        pc = pc + 1
        if (op == Code.fetch) {
            var x = toInt32LE.call(pc)
            stack.add(stack[x])
            pc = pc + 4
        } else if (op == Code.store) {
            var x = toInt32LE.call(pc)
            var ln = stack.count
            stack[x] = stack[ln-1]
            stack = stack[0...ln-1]
            pc = pc + 4
        } else if (op == Code.push) {
            var x = toInt32LE.call(pc)
            stack.add(x)
            pc = pc + 4
        } else if (op == Code.add) {
            var ln = stack.count
            stack[ln-2] = stack[ln-2] + stack[ln-1]
            stack = stack[0...ln-1]
        } else if (op == Code.sub) {
            var ln = stack.count
            stack[ln-2] = stack[ln-2] - stack[ln-1]
            stack = stack[0...ln-1]
        } else if (op == Code.mul) {
            var ln = stack.count
            stack[ln-2] = stack[ln-2] * stack[ln-1]
            stack = stack[0...ln-1]
        } else if (op == Code.div) {
            var ln = stack.count
            stack[ln-2] = (stack[ln-2] / stack[ln-1]).truncate
            stack = stack[0...ln-1]
        } else if (op == Code.mod) {
            var ln = stack.count
            stack[ln-2] = stack[ln-2] % stack[ln-1]
            stack = stack[0...ln-1]
        } else if (op == Code.lt) {
            var ln = stack.count
            stack[ln-2] = Conv.btoi(stack[ln-2] < stack[ln-1])
            stack = stack[0...ln-1]
        } else if (op == Code.gt) {
            var ln = stack.count
            stack[ln-2] = Conv.btoi(stack[ln-2] > stack[ln-1])
            stack = stack[0...ln-1]
        } else if (op == Code.le) {
            var ln = stack.count
            stack[ln-2] = Conv.btoi(stack[ln-2] <= stack[ln-1])
            stack = stack[0...ln-1]
        } else if (op == Code.ge) {
            var ln = stack.count
            stack[ln-2] = Conv.btoi(stack[ln-2] >= stack[ln-1])
            stack = stack[0...ln-1]
        } else if (op == Code.eq) {
            var ln = stack.count
            stack[ln-2] = Conv.btoi(stack[ln-2] == stack[ln-1])
            stack = stack[0...ln-1]
        } else if (op == Code.ne) {
            var ln = stack.count
            stack[ln-2] = Conv.btoi(stack[ln-2] != stack[ln-1])
            stack = stack[0...ln-1]
        } else if (op == Code.and) {
            var ln = stack.count
            stack[ln-2] = Conv.btoi(Conv.itob(stack[ln-2]) && Conv.itob(stack[ln-1]))
            stack = stack[0...ln-1]
        } else if (op == Code.or) {
            var ln = stack.count
            stack[ln-2] = Conv.btoi(Conv.itob(stack[ln-2]) || Conv.itob(stack[ln-1]))
            stack = stack[0...ln-1]
        } else if (op == Code.neg) {
            var ln = stack.count
            stack[ln-1] = -stack[ln-1]
        } else if (op == Code.not) {
            var ln = stack.count
            stack[ln-1] = Conv.btoi(!Conv.itob(stack[ln-1]))
        } else if (op == Code.jmp) {
            var x = toInt32LE.call(pc)       
            pc = pc + x
        } else if (op == Code.jz) {
            var ln = stack.count
            var v = stack[ln-1]
            stack = stack[0...ln-1]
            if (v != 0) {
                pc = pc + 4
            } else {
                var x = toInt32LE.call(pc)
                pc = pc + x
            }
        } else if (op == Code.prtc) {
            var ln = stack.count
            System.write(String.fromByte(stack[ln-1]))
            stack = stack[0...ln-1]
        } else if (op == Code.prts) {
            var ln = stack.count
            System.write(stringPool[stack[ln-1]])
            stack = stack[0...ln-1]
        } else if (op == Code.prti) {
            var ln = stack.count
            System.write(stack[ln-1])
            stack = stack[0...ln-1]
        } else if (op == Code.halt) {
            return
        } else {
            reportError.call("Unknown opcode %(op)")
        }
    }
}
 
var translate = Fn.new { |s|
    var d = ""
    var i = 0
    while (i < s.count) {
        if (s[i] == "\\" && (i+1) < s.count) {
            if (s[i+1] == "n") {
                d = d + "\n"
                i = i + 1
            } else if (s[i+1] == "\\") {
                d = d + "\\"
                i = i + 1
            }
        } else {
            d = d + s[i]
        }
        i = i + 1
    }
    return d
}
 
var lines = []
var lineCount = 0
var lineNum = 0
 
var loadCode = Fn.new {
    var dataSize
    var firstLine = true
    while (lineNum < lineCount) {
        var line = lines[lineNum].trimEnd(" \t")
        lineNum = lineNum + 1
        if (line.count == 0) {
            if (firstLine) {
                reportError.call("empty line")
            } else {
                break
            }
        }
        var lineList = line.split(" ").where { |s| s != "" }.toList
        if (firstLine) {
            dataSize = Num.fromString(lineList[1])
            var nStrings = Num.fromString(lineList[3])
            for (i in 0...nStrings) {
                var s = lines[lineNum].trim("\"\n")
                lineNum = lineNum + 1
                stringPool.add(translate.call(s))
            }
            firstLine = false
            continue
        }
        var offset = Num.fromString(lineList[0])
        var instr = lineList[1]
        var opCode = codeMap[instr]
        if (!opCode) {
            reportError.call("Unknown instruction %(instr) at %(opCode)")
        }
        emitByte.call(opCode)
        if (opCode == Code.jmp || opCode == Code.jz) {
            var p = Num.fromString(lineList[3])
            emitWord.call(p - offset - 1)
        } else if (opCode == Code.push) {
            var value = Num.fromString(lineList[2])
            emitWord.call(value)
        } else if (opCode == Code.fetch || opCode == Code.store) {
            var value = Num.fromString(lineList[2].trim("[]"))
            emitWord.call(value)
        }
    }
    return dataSize
}
 
lines = FileUtil.readLines("codegen.txt")
lineCount = lines.count
runVM.call(loadCode.call())