Virtual Machine Design

I am working on the third rewrite of my virtual machine while I'm writing this. The papers and documentation around Lua programming language has been really helpful for studying the subject.

During the first rewrite, I concentrated on the value objects, then moved to implement an interpreter. It felt difficult to construct an object system over this.

During the second rewrite I concentrated on the object system. I had to create an operation for comparing strings, so I could have some method tables for the objects. It was nice thing, but programming new functions and objects were being harder all the time. I would have to return on rewriting all of it. The interpreter ended up missing completely, although I had nice lists.

During the third rewrite I started with the interpreter, like this:

#include <setjmp.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

typedef uint64_t vm_value;

typedef struct
{
    size_t argc;
    size_t valc;

    size_t   size;
    uint8_t* program;
} vm_descriptor;

typedef struct
{
    vm_descriptor* desc;
    uint8_t*  pc;
    vm_value* base;
    vm_value stack[4096];
} vm_context;

vm_descriptor* vm_new_descriptor(
        size_t argc,
        size_t valc,
        size_t size,
        uint8_t* program)
{
    vm_descriptor* desc;

    desc = malloc(sizeof(*desc));
    desc->argc = argc;
    desc->valc = valc;
    desc->size = size;
    desc->program = malloc(size);
    memcpy(desc->program, program, size);
    return desc;
}

void vm_loop(vm_context* ctx)
{
    uint8_t* pc = ctx->pc;
    vm_value* base = ctx->base;
    int op, a, b, c, d;

    const void* optable[] = {&&op_move};
    printf("interpreter\n");
next:
    op = pc[0];
    a  = pc[1];
    b  = pc[2];
    c  = pc[3];
    d  = b << 8 | c;
    pc += 4;
    goto *optable[op];
op_move:
    base[a] = base[b];
    goto next;
op_return:
    base[0] = base[a];
    return;
}

The point of an interpreter is to evaluate the programs you pass to it. Everything else that doesn't contribute to this goal is a distraction.

Although I will need everything I have written variations of this far, there needs to be an order in introducing it into an interpreter. Writing it won't be a struggle, and it will run well.

Similar posts