Add a new primitive `string_indexOf_with_startIndex` that accepts a second integer argument to specify the starting position for the search. Modify the existing `wrenStringFind` function to accept a `startIndex` parameter, updating its Boyer-Moore-Horspool algorithm to begin scanning from the given offset. Update the `string_contains` primitive to pass `0` as the start index. Register the new overloaded method as `indexOf(_,_)` on the string class and add test cases covering boundary conditions and out-of-range start indices.
Add a new public API function `wrenAbortFiber()` that allows foreign methods to abort the currently executing fiber with a custom runtime error object. The function validates the API slot, then sets the fiber's error field to the value in the specified slot. The interpreter loop is updated to check for a non-null fiber error after calling a foreign method, triggering a runtime error if set. New test files (error.c, error.h, error.wren) demonstrate usage via a static Error.runtimeError foreign method, verifying that the error is propagated through Fiber.try() and that the fiber's isDone and error properties are correctly set. Xcode project updated to include the new error.c source file.
Simplify the VM by ensuring all called objects are closures, removing the need for runtime checks between bare functions and closures. This eliminates the `IS_FN`/`IS_CLOSURE` branching in `validateFn`, `checkArity`, `bindMethod`, and `wrenNewFiber`, and changes `CallFrame.fn` from `Obj*` to `ObjClosure*`. The compiler now emits `CODE_CLOSURE` for all function declarations, even those without upvalues, trading a small allocation cost at declaration time for faster and more uniform invocation. Benchmarks show performance is neutral to slightly improved across all tested workloads.
Fix the misspelled function name `wrenUpwrapClosure` to the correct `wrenUnwrapClosure` in wren_debug.c, wren_value.c, wren_value.h, and wren_vm.c. Also fix a minor grammar typo in wren_vm.c comment changing 'arguments' to 'argument'.
Replace the internal `foreignStackStart` pointer with a public `apiStack` field
that tracks the base of available C API slots. Extract the static
`ensureStack` helper into a non-static `wrenEnsureStack` function declared in
the header, enabling `wrenEnsureSlots()` to create a fiber and stack when
called outside a foreign method. Update `callForeign` to use `apiStack` and
adjust `metaCompile` to write results through the new pointer. Add a
`ensureOutsideForeign` test that allocates slots on a fresh VM, verifies
slot count grows from 0 to 20, and exercises all 20 slots with double values
to confirm the stack is correctly initialized and usable.
Migrate the foreign method argument access API from an argument-oriented naming
scheme to a slot-based one, renaming wrenGetArgumentCount to wrenGetSlotCount,
wrenGetArgumentBool to wrenGetSlotBool, and all other argument accessors
accordingly. Update every call site across the VM, modules (io, timer, meta,
random), and test files (benchmark, foreign_class) to use the new names. The
slot getters now assert the correct type at runtime rather than silently
returning defaults, shifting safety responsibility to the caller for
performance. Also add the IS_LIST type-checking macro to wren_value.h alongside
the existing IS_* macros.
The previous implementation allowed fibers as map keys by assigning each fiber a unique numeric ID for hashing and equality. This was originally added to support a misguided attempt at thread-local storage that was never used. This commit removes the fiber ID field from ObjFiber, the nextFiberId counter from WrenVM, the fiber hashing case in hashObject(), and the IS_FIBER check in validateKey(). The error message for invalid keys is updated from "Key must be a value type or fiber." to "Key must be a value type." and all affected test expectations are updated accordingly.
Add `numSlots` and `maxSlots` fields to `Compiler` struct to track current and maximum stack usage during compilation. Introduce `stackEffects` array mapping each opcode to its net stack delta, defined via updated `OPCODE` macro in `wren_opcodes.h` now taking a second argument. Modify `initCompiler` to initialize slot tracking from `numLocals`, update `emitByte` and related emit functions to adjust `numSlots` and update `maxSlots` when a new peak is reached. Extend `ObjFn` with `maxSlots` field, pass it through `wrenNewFunction` calls (including `makeCallStub`), and fix a null-check in `wrenDumpCode` for core module name.
Rename `wrenMarkValue` to `wrenGrayValue`, `wrenMarkBuffer` to `wrenGrayBuffer`, and `wrenDarkenObjs` to `wrenBlackenObjects` to make the tri-color garbage collection abstraction explicit. Introduce `wrenGrayObj` as a new helper that handles adding objects to the gray stack with cycle detection via the `isDark` flag. Update all call sites in the compiler, value, and VM modules to use the new names. Fix a typo in the VM header comment ("garbace" → "garbage").
The previous recursive `wrenMarkObj` approach could overflow the C stack when marking deeply nested object graphs. This commit introduces an iterative two-phase collector: objects are first "grayed" onto an explicit stack in the WrenVM struct, then `wrenDarkenObjs` iteratively processes the gray stack until all reachable objects are marked as "dark". The `marked` field is renamed to `isDark` to reflect the new semantics. A `gray` array with `grayDepth` and `maxGray` tracking is added to `WrenVM`, initialized in `initializeGC` and freed in `wrenFreeVM`. All internal mark calls (`markClass`, `markClosure`, `markFiber`, `wrenCollectGarbage`) are updated to use `wrenGrayObj` instead of `wrenMarkObj`. Two new test files (`deeply_nested_gc.wren` and `many_reallocations.wren`) verify that deeply nested object graphs and repeated GC cycles complete without stack overflow.
Add fallback empty UNREACHABLE() definition for GCC < 4.5 and non-MSVC compilers, and insert return/break statements after all UNREACHABLE() calls to prevent -Wreturn-type warnings when the macro expands to nothing. Also cast malloc result to char* in io.c to suppress C++ compilation warning.
The sourcePath field on ObjModule was redundant since it always matched the module name except for the main script. This change removes the parameter from wrenInterpret, wrenInterpretInModule, and wrenNewModule, and replaces all references to module->sourcePath with module->name in error reporting and debug output.
Remove the `sourcePath` field from `FnDebug` struct and the `Parser` struct, and instead store it directly in `ObjModule`. This eliminates duplication of the debug path across all functions in a module and simplifies the compiler interface by removing the `sourcePath` parameter from `wrenCompile()` and `wrenNewFunction()`. Update all call sites to reference `module->sourcePath` instead, including stack trace printing, code dumping, and the `meta_eval` primitive.
The PrimitiveResult enum (PRIM_VALUE/PRIM_FIBER) is removed and replaced with a simple bool return value where `true` indicates a normal value return and `false` signals a fiber switch or runtime error. This simplifies the interpreter dispatch in `runInterpreter` by converting the switch on enum cases into a single if/else branch, and reduces branching in the common value-returning path. All primitive function signatures, the `RETURN_VAL`/`RETURN_ERROR` macros, and the `runFiber` helper are updated accordingly.
Replace the special "call" primitive result type (PRIM_CALL) with a new METHOD_FN_CALL method type that marks function call methods. Add checkArity helper to validate argument count before invoking function closures, and update the interpreter dispatch to handle the new method type instead of relying on the removed PRIM_CALL result.
Replace the `ObjFiber* fiber` parameter in `DEF_PRIMITIVE` macro and `Primitive` typedef with direct access to `vm->fiber` inside each primitive implementation. Update all call sites in `fiber_current`, `fiber_try`, `fiber_yield`, `fiber_yield1`, `meta_eval`, and the interpreter dispatch to use `vm->fiber` or a local `current` variable instead of the passed-in `fiber` argument.
Replace separate PRIM_ERROR and PRIM_RUN_FIBER return codes with a unified PRIM_FIBER in PrimitiveResult enum, updating all primitive implementations and the interpreter switch case to use the new combined value.
Refactor runtime error handling to store errors directly in the fiber's error field instead of on the stack, enabling any object (except null) as an error value. Add Fiber.transferError(_) primitive for transferring errors between fibers. Update validation helpers to accept Value arguments directly and modify RETURN_ERROR macro to set fiber error. Adjust GC marking to use wrenMarkValue for the error field. Add tests for aborting with non-string errors and null abort behavior.
Add wrenNewStringFromRange function to wren_value.c that decodes UTF-8 code points from source string and re-encodes them into result, enabling correct range subscripts on multi-byte characters. Rename wrenUtf8NumBytes to wrenUtf8EncodeNumBytes and make wrenUtf8Encode return written byte count for use in range construction. Add wrenUtf8DecodeNumBytes utility to skip continuation bytes when iterating by byte index. Remove all skip directives from test files and add UTF-8 specific test cases verifying correct slicing across code point boundaries.
Implement the initial infrastructure for foreign classes in the Wren VM, including new opcodes (FOREIGN_CONSTRUCT, FOREIGN_CLASS), a WrenBindForeignClassFn callback type in the public API, and updated CLI vm.c to store and forward foreign binding callbacks via setForeignCallbacks(). The compiler now tracks whether a class is foreign via a new isForeign flag in ClassCompiler, emits CODE_FOREIGN_CONSTRUCT instead of CODE_CONSTRUCT for foreign class constructors, and errors on field definitions inside foreign classes. The debug dump and opcode header gain entries for the new opcodes, and wrenBindSuperclass handles the -1 numFields sentinel for foreign classes to prevent field inheritance from superclasses.
Replace three duplicated switch-on-type patterns (in wrenDebugPrintStackTrace, wrenAppendCallFrame, and runInterpreter) with a single static inline wrenGetFrameFunction that handles OBJ_FN and OBJ_CLOSURE cases with an UNREACHABLE default.
Replace the statically-sized CallFrame array in ObjFiber with a dynamically
allocated array that starts at INITIAL_CALL_FRAMES (4) and doubles when
capacity is exceeded. This reduces memory for new fibers and improves
fiber creation benchmark performance by ~45%.
The ASCII diagrams in the NaN tagging documentation had misaligned
brackets and inconsistent dash counts that made the bit layout
confusing. Updated the exponent/mantissa separator from parentheses
to brackets, fixed the NaN bits indicator alignment, and corrected
the highest mantissa bit marker position to match the actual bit
positions in the IEEE 754 double representation.
Add a unique numeric ID to each fiber allocation, enabling fibers to be used as map keys. This includes updating the hash function for OBJ_FIBER to return the fiber's ID, modifying key validation to accept fibers, updating documentation to describe the new capability, and adjusting all relevant test expectations and error messages.
Implement the `String.fromCodePoint(_)` primitive that creates a string from a Unicode code point, with validation for integer range 0–0x10ffff. Extract inline UTF-8 encoding logic from `readUnicodeEscape` in the compiler into new `wrenUtf8NumBytes` and `wrenUtf8Encode` utility functions in `wren_utils`, and add `wrenStringFromCodePoint` helper in `wren_value`. Update documentation for core classes to add "Methods" and "Static Methods" section headers, and include `String.fromCodePoint` docs with example. Add a test file `from_code_point.wren` covering various code points.
Implement the `WrenBindForeignMethodFn` callback type and `bindForeignMethodFn` configuration field to allow host applications to resolve foreign method declarations at class definition time. Refactor the IO library to use this new binding mechanism instead of the previous `wrenDefineStaticMethod` approach, adding `foreign` keyword support to the lexer and compiler. Introduce `freeCompiler` helper for cleanup, store module names in `ObjModule`, and update the VM to call the binder when processing `CODE_METHOD_INSTANCE` and `CODE_METHOD_STATIC` opcodes for foreign methods.
Rename the `Upvalue` struct and all related type references to `ObjUpvalue` across
wren_value.c, wren_value.h, and wren_vm.c. This aligns with the existing pattern
where Obj-derived types (like ObjModule, ObjClosure) use the Obj prefix even when
the type is not first-class in the language. The change touches function signatures,
variable declarations, pointer arithmetic in memory tracking, and the struct
definition itself.
Remove the `WrenVM* vm` parameter from `wrenValueBufferInit`, `wrenByteBufferInit`,
`wrenIntBufferInit`, `wrenStringBufferInit`, `wrenSymbolTableInit`,
`wrenMethodBufferInit`, `wrenStringFind`, and `wrenDebugPrintStackTrace`
functions across the compiler, core, debug, utils, value, and VM modules.
Update all call sites and macro definitions to match the simplified signatures,
eliminating dead parameters that were never used within the function bodies.
Replace the hand-rolled capacity/count/elements fields in ObjList with a
ValueBuffer struct, and update Compiler to use a ValueBuffer for its
constant pool instead of an ObjList. This eliminates the separate
ensureListCapacity and wrenListAdd functions, centralizing buffer growth
logic in wrenValueBufferWrite. Adjust all list primitives (add, clear,
count, iterate, iteratorValue) and the GC marking path to operate on the
embedded ValueBuffer. Add wrenMarkBuffer helper for marking buffer
contents during sweep.
Convert `validateIndexValue` and `validateIndex` return types to `uint32_t` with `UINT32_MAX` sentinel, update `wrenNewList`, `wrenListInsert`, `wrenListRemoveAt` signatures, and remove the TODO comment about type unification with `ObjMap`.
Cache the FNV-1a hash code in the ObjString struct at creation time, replacing the
on-the-fly sampling hash in hashObject() and enabling constant-time string equality
checks. Refactor string allocation into allocateString() and hashString() helpers,
remove the old wrenNewUninitializedString() declaration, and add a CONST_STRING
macro. Disable the unimplemented subscript range operator with a runtime error and
skip the related UTF-8 tests. Add a string_equals benchmark to measure the speedup.
The two validation functions in wren_core.c were calling wrenStringFormat with a format
string containing a "$" placeholder but were not passing the argName argument, causing
the placeholder to remain unsubstituted in error messages. This commit adds the missing
argName parameter to both calls.
Additionally, the CONST_STRING macro in wren_value.h was changed from using strlen(text)
to sizeof(text) - 1, which allows the compiler to compute the string length at compile
time rather than at runtime, improving performance for string literal creation.
The previous implementation used `sizeof(text) - 1` to determine string length at compile time, which required the argument to be a bare string literal. The new approach uses `strlen(text)` instead, which allows most compilers to evaluate the string length at compile time when a string literal is passed, while also supporting non-literal string arguments. This change trades compile-time guarantee for broader compatibility and compiler optimization potential.
Replace ad-hoc string construction using wrenNewString, wrenStringConcat, and sprintf with the new wrenStringFormat helper. This centralizes string formatting logic, reduces code duplication, and eliminates manual length calculations in wren_compiler.c, wren_core.c, wren_value.c, and wren_vm.c. Also introduces CONST_STRING macro for compile-time string literals and changes wrenNewUninitializedString return type from Value to ObjString* for consistency.
Separate Wren VM library sources from CLI tool sources by moving them into
src/vm/ and src/cli/ subdirectories respectively. Update the Makefile to use
separate wildcard patterns for each directory, generate distinct object file
paths under build/vm/ and build/cli/, and adjust include paths to src/include.
Also update the Xcode project file to reference the new file locations.
Change the `capacity` and `count` fields in `ObjList` from `int` to `uint32_t` to match the
types used in `ObjMap`, ensuring consistency between the two structures. Update all loop
variables and index calculations in `wren_core.c` and `wren_value.c` that interact with
these fields to use `uint32_t` instead of `int`, and remove the now-unnecessary negative
bounds check in `list_iterate` since unsigned types cannot be negative.