Bytecode VM
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:
BytecodewithMain []InstrandFunctions []FunctionFunctionwithName,Params, andCode []InstrInstrwithOp,Int, andStr
Value types
Use the provided Value struct with kinds:
- number
- string
- bool
- nil
Runtime rules
Truthiness
falseandnilare 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_CONSTcreate bindings in the current scopeSTOREupdates the nearest existing binding (error if const)LOADreads the nearest existing bindingENTER_SCOPE/EXIT_SCOPEpush and pop scope maps
Functions
- Functions are stored in
Bytecode.Functionsand 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 isnil. - 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.
Run tests to see results
No issues detected