Bytecode VM

Overview

The bytecode VM is a stack-based virtual machine. Instructions operate on an implicit operand stack, pushing and popping values. This is the original execution backend for ƿit.

Compilation Pipeline

Source → Tokenize → Parse (AST) → Bytecode → Link → Execute

The compiler emits JSFunctionBytecode objects containing opcode sequences, constant pools, and debug information.

Instruction Categories

Value Loading

OpcodeDescription
push_i32Push a 32-bit immediate integer
push_constPush a value from the constant pool
nullPush null
push_falsePush false
push_truePush true

Stack Manipulation

OpcodeDescription
dropRemove top of stack
dupDuplicate top of stack
dup1 / dup2 / dup3Duplicate item at depth
swapSwap top two items
rot3l / rot3rRotate top three items
insert2 / insert3Insert top item deeper
nipRemove second item

Variable Access

OpcodeDescription
get_varLoad variable by name (pre-link)
put_varStore variable by name (pre-link)
get_loc / put_locAccess local variable by index
get_arg / put_argAccess function argument by index
get_env_slot / set_env_slotAccess closure variable (post-link)
get_global_slot / set_global_slotAccess global variable (post-link)

Variable access opcodes are patched during linking. get_var instructions are rewritten to get_loc, get_env_slot, or get_global_slot depending on where the variable is resolved.

Arithmetic

OpcodeDescription
add / sub / mul / divBasic arithmetic
mod / powModulo and power
neg / inc / decUnary operations
add_loc / inc_loc / dec_locOptimized local variable update

Comparison and Logic

OpcodeDescription
strict_eq / strict_neqEquality (ƿit uses strict only)
lt / lte / gt / gteOrdered comparison
not / lnotLogical / bitwise not
and / or / xorBitwise operations

Control Flow

OpcodeDescription
gotoUnconditional jump
if_true / if_falseConditional jump
goto8 / goto16Short jumps (size-optimized)
if_true8 / if_false8Short conditional jumps
catchSet exception handler

Function Calls

OpcodeDescription
callCall function with N arguments
tail_callTail-call optimization
call_methodCall method on object
returnReturn value from function
return_undefReturn null from function
throwThrow exception (disrupt)

Property Access

OpcodeDescription
get_fieldGet named property
put_fieldSet named property
get_array_elGet computed property
put_array_elSet computed property
define_fieldDefine property during object literal

Object Creation

OpcodeDescription
objectCreate new empty object
array_fromCreate array from stack values

Bytecode Patching

During the link/integrate phase, symbolic variable references are resolved to concrete access instructions. This is a critical optimization — the interpreter does not perform name lookups at runtime.

A get_var "x" instruction becomes:

  • get_loc 3 — if x is local variable at index 3
  • get_env_slot 1, 5 — if x is captured from outer scope (depth 1, slot 5)
  • get_global_slot 7 — if x is a global