Bytecode VM

hard · compilers, virtual machine, bytecode

Bytecode VM

Implement a stack-based virtual machine that executes compiler bytecode.

Function signature

func Run(bc Bytecode) (Value, error)

Bytecode types

Use the provided types:

  • Bytecode with Main []Instr and Functions []Function
  • Function with Name, Params, and Code []Instr
  • Instr with Op, Int, and Str

Value types

Use the provided Value struct with kinds:

  • number
  • string
  • bool
  • nil

Runtime rules

Truthiness

  • false and nil are falsey
  • everything else is truthy

Arithmetic / comparison

  • + - * / work on numbers
  • + also supports string concatenation when both operands are strings
  • < <= > >= work on numbers
  • == / != compare by type and value

Type mismatches should return a non-nil error.

Variables and scopes

  • DEFINE_VAR / DEFINE_CONST create bindings in the current scope
  • STORE updates the nearest existing binding (error if const)
  • LOAD reads the nearest existing binding
  • ENTER_SCOPE / EXIT_SCOPE push and pop scope maps

Functions

  • Functions are stored in Bytecode.Functions and called by name (CALL).
  • Create a new local scope for each call, bind parameters, then execute the function body.
  • If a function returns without RETURN, its result is nil.
  • Functions can read global variables but we do not implement closures.

Program result

After executing Main, return the top of the stack if present; otherwise return nil.

Notes

  • Use absolute jump targets.
  • Keep the VM readable and straightforward.

Before implementation

Use the module’s worked reconstruction and independent debugging lab to predict an intermediate artifact first. Preserve one failing counterexample while implementing the stated API. The lesson’s transfer task uses a fresh case after the guided trace.

Run tests to see results
No issues detected
    Join Discord