Migrate fiber stack management from an integer `stackSize` counter to a direct `Value* stackTop` pointer, eliminating repeated `stack[stackSize - 1]` calculations. Update all stack slot accesses, iteration loops, and the `CallFrame::stackStart` field to use pointer arithmetic, simplifying the code and reducing index arithmetic overhead.
Store the start of the current frame's stack in a local `stackStart` variable
during LOAD_FRAME() macro execution, replacing repeated calculations of
`fiber->stack[frame->stackStart + offset]` with `stackStart[offset]` across
LOAD_LOCAL and LOAD_FIELD opcodes. Also remove unused `upvalues` register
variable and its assignments from closure handling paths.
Move the class pointer from ObjInstance into the base Obj struct and remove the separate metaclass field from ObjClass, allowing all heap objects to directly reference their class. Add an inlined wrenGetClassInline function in the header to eliminate function call overhead during method dispatch, yielding 10-43% performance gains across benchmarks.
Introduce nine new bytecode instructions (CODE_LOAD_LOCAL_0 through CODE_LOAD_LOCAL_8) that directly encode the local slot number in the opcode itself, eliminating the need to read and decode a separate argument byte for the most frequently accessed local variables. This optimization targets the hottest path in the interpreter, as LOAD_LOCAL is the most executed instruction across benchmarks (e.g., 3.75M times in delta_blue). The compiler's `loadLocal` helper emits the specialized opcode when the slot index is ≤8, falling back to the generic `CODE_LOAD_LOCAL` with an argument byte otherwise. The VM dispatch table and debug printer are updated accordingly. Benchmarks show consistent speedups: fib +7.3%, method_call +5.9%, binary_trees +1.9%, for +2.8%, delta_blue +1.0%.
In `getNumArguments`, add a `return 0` after the `UNREACHABLE()` default case to prevent
undefined behavior when assertions are disabled. In `wrenGetClass`, reorder the
`UNREACHABLE()` macro before the `return NULL` so the unreachable annotation is
always emitted. In `runInterpreter`, replace the `ASSERT(0, ...)` with an explicit
`UNREACHABLE()` and `return false` to guarantee a return value on all control paths
when the interpreter exits unexpectedly.
Implement a new `Fiber.try()` method that allows a calling fiber to catch runtime errors from a called fiber. When a fiber is invoked with `try()` instead of `call()`, any runtime error that occurs in the called fiber is returned as a string to the caller rather than terminating the program with a stack trace. The `callerIsTrying` flag on `ObjFiber` tracks this state, and the `runtimeError` function now checks this flag to redirect the error to the caller's stack. Also adds `Fiber.error` getter to retrieve the error string from a failed fiber, changes `Fiber.isDone` to return `true` for errored fibers, and migrates the fiber error field from a raw `char*` to an `ObjString*` for proper memory management. Includes comprehensive test cases for try behavior, re-entry prevention, and error state queries.
The crash occurred in captureUpvalue() when an upvalue for an earlier local
variable was captured after a later one. The function walked to the end of the
open upvalue list but then dereferenced a NULL pointer when comparing
upvalue->value against the target local slot.
Added a NULL guard before the equality check so that if no existing upvalue
is found, the function correctly proceeds to create a new one instead of
dereferencing a null pointer.
Also fixed a typo in the comment ("existsing" -> "existing").
Added regression test close_over_later_variable.wren that exercises the
scenario of capturing upvalues for locals in reverse declaration order.
Add a 64-character maximum identifier length with compile-time error reporting, and enhance the runtime field overflow error to include the class name and remove the TODO comment. Update test expectations for both limit scenarios.
The internal PinnedObj type was renamed to WrenPinnedObj across the codebase to make it publicly accessible, as the WREN_PIN macro expands to stack allocations of this type that must be visible to external consumers. Updated all typedefs, function signatures, and variable declarations in wren_vm.c and wren_vm.h to use the new prefixed name, and removed the TODO comment about moving the struct into wren_vm.c.
Rename boolean defines from `true`/`false` to `1`/`0` for consistency, prefix debug flags with `WREN_DEBUG_`, add `WREN_USE_LIB_IO` flag to guard IO library loading, and wrap IO module includes and function declarations in conditional compilation blocks.
Replace the nested `SymbolTable` struct (containing a `StringBuffer names` field) with a direct `typedef StringBuffer SymbolTable`, updating all internal accesses from `symbols->names.data` to `symbols->data` and `symbols->names.count` to `symbols->count`. Rename `vm->methods` to `vm->methodNames` and `vm->globalSymbols` to `vm->globalNames` across the codebase, including debug printing, compiler symbol resolution, core initialization, and VM interpreter error messages. Remove the stale TODO comment about error codes in `wren.h` and adjust the `instantiate` method name to include a leading space to prevent direct user invocation.
Replace the static `Value globals[MAX_GLOBALS]` array in WrenVM with a dynamic `ValueBuffer` that grows on demand, removing the 256-global limit. Introduce `wrenDefineGlobal()` helper that adds a named global to the symbol table and stores its value in the buffer, returning -2 when the 65536 limit is reached. Update all global access sites (compiler emit, runtime interpreter, GC marking, debug disassembly, core class definition) to use the buffer's data pointer and short (16-bit) opcode arguments instead of byte-sized ones. Add a regression test `many_globals.wren` that defines 8200 globals to verify the new capacity.
Refactor the 'new' operator compilation to emit a method call to 'instantiate' on the class instead of using a dedicated bytecode instruction. This allows built-in types like Fn to override instantiation behavior, enabling `new Fn { ... }` to return the block argument directly. Remove the CODE_NEW opcode from the VM, compiler, and debug printer, and add native methods `class_instantiate`, `fn_instantiate`, `fn_new`, and `object_instantiate` to handle the new dispatch. Update test files to reflect the renamed `Function` class to `Fn`.
Replace two static error-reporting functions with a single RUNTIME_ERROR macro that stores the fiber frame before calling runtimeError and returning false. This consolidates error handling logic and prepares for catching runtime errors from other fibers by ensuring consistent frame preservation.
In the interpreter's NEW opcode handler, check if the top-of-stack value is a class before attempting construction. If not, raise a runtime error with a descriptive message instead of silently failing or crashing.
Also add a test case (test/new_on_nonclass.wren) that verifies the error is correctly triggered when calling new on a non-class value like an integer.
The error message for unimplemented methods previously included the word "Receiver"
before the class name, which was redundant and inconsistent with other error messages.
Updated the format string in `methodNotFound()` to drop "Receiver" and use the class
name directly. Added a new test case for static method not found errors and updated
existing test expectations to match the new message format.
Add ObjClass* parameter to methodNotFound and pass classObj from all call sites in runInterpreter, so the error message displays the receiver's class name instead of a generic "Receiver does not implement method".
Move upvalue closing logic from the else branch to before the fiber completion check
to ensure upvalues are properly closed when a fiber finishes. Add test cases for
closure behavior across fiber yields and for Fiber.create argument type validation.
The previous comparison `classObj->methods.count < symbol` incorrectly allowed
access when `symbol` equals `count`, which is out of bounds for zero-indexed
arrays. Changed both occurrences in `runInterpreter` to use `symbol >= count`
to properly guard against out-of-bounds access.
Add two new public API functions to the Wren VM for foreign function interface
(FFI) return values. wrenReturnNull sets the foreign call slot to a null value,
while wrenReturnString copies the provided text into a new Wren heap string,
supporting both explicit length and strlen-based length calculation. Both
functions include assertions to ensure they are called within a valid foreign
call context.
Add `numParams` field to `ObjFn` and `Compiler` structs to track expected parameter count. Refactor `parameterList` to return count and store it in compiler. Modify `endCompiler` to pass `numParams` to `wrenNewFunction`. Replace single `fn_call` native with 17 arity-specific `fn_call0` through `fn_call16` natives that validate argument count against `fn->numParams` via `callFunction` helper, returning error on missing args. Remove stale TODO comment in VM interpreter. Add test files `call_extra_arguments.wren` and `call_missing_arguments.wren`.
Replace monolithic corelib.wren with per-class builtin/*.wren files and generate_builtins.py script. Move IO class definition and its native writeString_ method from wren_core.c to new wren_io.c, adding wrenGetArgumentString and wrenDefineStaticMethod to the public API. Update Makefile target from corelib to builtin and remove generate_corelib.py.
Replace the TODO placeholder for error codes with a proper WrenInterpretResult enum
containing WREN_RESULT_SUCCESS, WREN_RESULT_COMPILE_ERROR, and
WREN_RESULT_RUNTIME_ERROR. Update wrenInterpret signature to return the new type
and refactor callers in main.c and wren_vm.c to use the enum values instead of
magic exit codes. Also add a startup banner to the REPL.
Replace all (void) POP() calls with a dedicated DROP() macro that decrements
fiber->stackSize directly, eliminating unused-value compiler warnings and
making the intent of discarding the stack top explicit throughout the
interpreter loop, logical operators, upvalue closing, and object construction.
In the compiler's classDefinition function, the class name constant is now emitted as a separate CODE_CONSTANT instruction before CODE_CLASS, instead of being passed as a short argument to CODE_CLASS. The VM's CLASS case handler is updated to pop the class name string from the stack using PEEK2() instead of reading it from the constant table via READ_SHORT(). The comment in wren_vm.h is revised to document that the class name is now on the stack below the superclass.
Store the class name string in `ObjClass` during compilation and class creation, and expose it through a new `class_name` native method. Also update `object_toString` to return the class name for class instances and "instance of <name>" for regular instances.
Eliminate the dedicated CODE_SUBCLASS opcode and instead push a null value to indicate implicit inheritance from Object. This simplifies the bytecode interpreter by using a single CODE_CLASS instruction that checks the top of stack for a null sentinel to determine whether to use the implicit Object superclass or a user-provided superclass. The change also consolidates argument counting and debug printing logic, removing the now-unnecessary case branches for CODE_SUBCLASS across the compiler, VM, and debug modules.
Replace six separate type-check functions (wrenIsClosure, wrenIsFiber, wrenIsFn, wrenIsInstance, wrenIsRange, wrenIsString) with a single wrenIsObjType that takes an ObjType parameter. Add IS_CLASS macro and runtime validation in the IS bytecode handler to ensure the right operand is a class, producing a clear error message when it is not. Add test case for non-class right operand.
Update the VM interpreter to treat null as falsey alongside false in if, while, for, and logical AND/OR operations. Remove the TODO comment and adjust short-circuit logic in OP_JUMP_IF and OP_JUMP_IF_NOT branches. Refactor existing test files into subdirectories (if/, logical_operator/, while/) and add dedicated truthiness tests for each construct. Remove old test/if.wren and update and/or tests to exclude null/0/"" truthiness checks now that null is falsey.
Extract the common pattern of checking and setting the FLAG_MARKED bit on an object into a dedicated static helper function. This eliminates repeated inline code across markInstance, markList, markUpvalue, markFiber, and other marking functions, improving maintainability and reducing the risk of inconsistencies in cycle detection.
Remove the Range class definition from corelib.wren and implement it as a native C type with ObjRange struct, adding native methods for from, to, min, max, iterate, and iteratorValue. Move range operator handling from Num class to native num_dotDot and num_dotDotDot functions. Update VM to support OBJ_RANGE type in marking, printing, and type checking. Add comprehensive test suite for range operations including ordered, backwards, and exclusive ranges.
Refactor the compiler to treat static methods as local variables defined in an implicit scope surrounding the class, eliminating the need for VM-level static method support. This changes `declareVariable` to use the previously consumed token, adds `declareNamedVariable` for explicit token consumption, and updates `parameterList` to use the new function. Adjusts VM bytecode ordering for `CODE_METHOD_INSTANCE` and `CODE_METHOD_STATIC` to pop the class before the function body. Adds comprehensive test coverage for static fields including closures, nested classes, default null values, instance method access, and error cases for field usage outside classes or in static methods.
Add a MAX_FIELDS constant (255) to wren_common.h and implement field overflow
validation in the compiler and VM. The compiler now emits an error when a class
declares more than 255 fields, and the VM checks for inherited field overflow
at class creation time, producing a descriptive runtime error. Also add four
test files (many_fields, many_inherited_fields, too_many_fields,
too_many_inherited_fields) to verify both valid and invalid field counts.
Add iteration over the VM's object linked list in wrenFreeVM to properly
deallocate all allocated GC objects before freeing the VM memory,
replacing the previous TODO placeholder comment.
Add core fiber functionality including Fiber.create, Fiber.run, Fiber.yield
primitives with value passing between fibers. Introduce PRIM_RUN_FIBER result
type for interpreter loop, add caller field to ObjFiber struct for yield
resumption, and update GC marking to traverse fiber caller chains. Modify
wrenNewFiber to accept a function/closure argument and initialize the first
call frame. Add debug stack printing with fiber pointer. Include test suite
covering fiber creation, run, yield, value passing, type checking, and
caller resumption.
Replace single-byte jump offset emission and reading with two-byte (uint16) handling across all jump instructions (JUMP, LOOP, JUMP_IF, AND, OR). Add new emitJump helper that reserves a 16-bit placeholder, update patchJump to write the offset as big-endian short, and change VM opcode handlers to use READ_SHORT instead of READ_BYTE for jump offsets. This increases maximum jump distance from 255 to 65535 bytes, supporting larger generated bytecode.
Replace the fixed-size MAX_SYMBOLS array with a dynamically growing StringBuffer for symbol names, update all instruction encodings to use 16-bit operands for constants and method symbols, and refactor method binding to use a dynamic MethodBuffer per class. Remove the constant deduplication logic in addConstant and the commented-out struct fields in initCompiler.
Introduce a new `WREN_TRACE_GC` compile-time flag in `wren_common.h` to enable
dedicated GC tracing independently from general memory tracing. When either
`WREN_TRACE_MEMORY` or `WREN_TRACE_GC` is set, include `<time.h>` and modify
`collectGarbage()` to measure elapsed wall-clock time using `clock()`. The GC
trace now reports bytes before and after collection, bytes collected, the next
GC threshold, and the duration in seconds. Also move the `-- gc --` header
print and the `nextGC` calculation inside the tracing guard to avoid
side-effects when tracing is disabled.
Move SymbolTable struct and its associated functions (initSymbolTable, clearSymbolTable, addSymbol, findSymbol, ensureSymbol, getSymbolName) from wren_vm.c and wren_value.h into new wren_utils.c and wren_utils.h files. Rename all functions with wrenSymbolTable prefix for consistent naming convention, update all call sites across compiler, core, debug, and VM files, and relocate MAX_SYMBOLS constant to wren_common.h.
Consolidate memory management by relocating the static freeObj function into wren_value.c as the public wrenFreeObj API, keeping allocation and deallocation co-located for better code organization.
Introduce primitive error signaling, runtime error handling with callstack printing, and fiber termination on error. Add source file path and method name tracking to functions, along with debug line number information. Update arithmetic operators to error on non-numeric operands and implement proper "method not found" runtime errors. Refactor the test runner to expect runtime errors with exit code 70 (EX_SOFTWARE) and update the C API to accept source paths in wrenInterpret and wrenCompile. Rename WrenNativeMethodFn to WrenForeignMethodFn and adjust related typedefs. Add debug source line arrays to compilers and functions, and replace the old debug dump functions with new print-based variants that display line numbers.
Add support for empty block bodies in the Wren compiler by early-returning
from `finishBlock` when a right brace is immediately matched. This permits
syntactically valid constructs like `{}`, `if (true) {}`, and empty function
or method bodies.
Fix a copy-paste error in `wrenGetArgumentDouble` where the assertion
checked `nativeCallSlot` and `nativeCallNumArgs` instead of the correct
`foreignCallSlot` and `foreignCallNumArgs` fields.
Add test cases covering standalone empty blocks, empty blocks in if/else
statements, and empty function and method bodies returning null.
Rename the fields `nativeCallSlot` and `nativeCallNumArgs` to `foreignCallSlot` and
`foreignCallNumArgs` across `wren_vm.c` and `wren_vm.h` to accurately reflect that
these fields are used exclusively during foreign function calls, not native method
invocations. Update all references in `callForeign`, `wrenGetArgumentDouble`, and
`wrenReturnDouble` accordingly.
Introduce the `WrenNativeMethodFn` callback type and `METHOD_FOREIGN` enum value to allow host applications to define C-implemented methods on Wren classes. Add `wrenDefineMethod`, `wrenGetArgumentDouble`, and `wrenReturnDouble` API functions, along with `nativeCallSlot` and `nativeCallNumArgs` VM fields to manage foreign call state. Implement `callForeign` in the interpreter loop to invoke native methods and handle stack cleanup. Move `MAX_PARAMETERS`, `MAX_METHOD_NAME`, and `MAX_METHOD_SIGNATURE` constants from `wren_compiler.c` to `wren_common.h` for shared use across the VM.