Commit Graph

85 Commits

Author SHA1 Message Date
Bob Nystrom
0fafa4bd07 refactor: replace integer stack index with pointer for stack top in fiber
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.
2014-12-31 18:34:27 +00:00
Bob Nystrom
d34cbd33ee perf: cache frame stack start pointer in local variable to reduce memory accesses
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.
2014-12-08 14:57:36 +00:00
Bob Nystrom
d224721f79 feat: store class reference directly in Obj struct and inline class lookup for method dispatch
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.
2014-12-07 22:29:50 +00:00
Bob Nystrom
520e841044 feat: add specialized LOAD_LOCAL_0..8 instructions to skip arg byte decode
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%.
2014-12-07 03:59:11 +00:00
Bob Nystrom
9b498b4638 fix: ensure all switch and unreachable paths return a value in release builds
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.
2014-12-02 05:36:06 +00:00
Bob Nystrom
306c33f01c fix: wrap ASSERT in do-while and add UNREACHABLE macro for GCC compatibility 2014-11-28 19:21:01 +00:00
Bob Nystrom
d60068db56 feat: add Fiber.try() method for catching errors across fiber boundaries
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.
2014-10-15 13:36:42 +00:00
Bob Nystrom
4d413f3473 fix: add null check when walking upvalue list in captureUpvalue
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.
2014-04-25 00:52:53 +00:00
Bob Nystrom
8abbc4197c feat: add MAX_VARIABLE_NAME limit and improve field overflow error message
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.
2014-04-22 14:06:26 +00:00
Bob Nystrom
c148fc307b fix: rename PinnedObj to WrenPinnedObj for public visibility in macros
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.
2014-04-07 14:47:58 +00:00
Bob Nystrom
2aaf6e5489 chore: rename debug and feature flags to consistent WREN_DEBUG_ and WREN_USE_ prefixes
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.
2014-04-07 14:45:09 +00:00
Bob Nystrom
e1cd942656 refactor: rename SymbolTable fields and flatten struct to StringBuffer alias
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.
2014-04-07 01:59:53 +00:00
Bob Nystrom
e7d2684d30 feat: replace fixed-size global array with growable ValueBuffer to support more than 256 globals
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.
2014-04-06 23:16:15 +00:00
Bob Nystrom
81f20caf33 feat: replace CODE_NEW instruction with instantiate method call for class and Fn
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`.
2014-04-03 00:42:30 +00:00
Bob Nystrom
39e275b09c refactor: remove methodNotFound and tooManyInheritedFields helpers, add RUNTIME_ERROR macro for unified runtime error handling in interpreter
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.
2014-03-30 15:39:28 +00:00
Bob Nystrom
f942da2723 fix: add runtime error when new is called on non-class argument
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.
2014-03-06 14:51:16 +00:00
Kyle Marek-Spartz
4cac6ce201 fix: remove redundant "Receiver" prefix from method-not-found error message
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.
2014-02-24 03:53:49 +00:00
Kyle Marek-Spartz
d5a121d7da feat: include receiver class name in methodNotFound error messages
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".
2014-02-22 07:20:53 +00:00
Bob Nystrom
04cb19c605 fix: close upvalues before fiber completion and add closure tests
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.
2014-02-14 15:16:56 +00:00
Bob Nystrom
a9519001bd fix: correct bounds check for method table lookup in wren_vm.c
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.
2014-02-09 04:25:33 +00:00
Bob Nystrom
01ff51191b feat: add wrenReturnNull and wrenReturnString functions for FFI string and null support
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.
2014-02-05 14:30:20 +00:00
Bob Nystrom
86015f4e48 feat: add numParams tracking and arity-checked fn.call variants for extra/missing args
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`.
2014-02-04 17:34:05 +00:00
Bob Nystrom
99eac12fd3 refactor: extract IO class into separate module with wrenLoadIOLibrary and wren_io.c
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.
2014-02-04 16:44:59 +00:00
Bob Nystrom
36aea2508c feat: define WrenInterpretResult enum and update wrenInterpret return type
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.
2014-02-03 14:51:44 +00:00
Bob Nystrom
2614bf3ab8 feat: add DROP() macro to discard stack top without returning value
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.
2014-02-01 18:44:47 +00:00
gaodayue
c5a07187b3 fix: suppress unused-value warnings from POP() macro by casting to void 2014-02-01 17:04:33 +00:00
Bob Nystrom
ea2ec33ce0 refactor: move class name from CODE_CLASS argument to stack in compiler and VM
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.
2014-01-29 15:47:09 +00:00
Bob Nystrom
e83296ea53 feat: add class name storage and expose via name method on class objects
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.
2014-01-28 23:31:11 +00:00
Bob Nystrom
74b67eae67 refactor: remove separate CODE_SUBCLASS instruction, unify class creation with null sentinel
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.
2014-01-27 01:25:38 +00:00
Bob Nystrom
f62ae5174e feat: restructure Makefile with debug/release builds and move scripts to subdirectory 2014-01-24 07:29:50 +00:00
Bob Nystrom
4536c82636 feat: move gc marking functions from wren_vm.c to wren_value.c and expose markValue/markObj as public API 2014-01-21 16:20:00 +00:00
Bob Nystrom
474e89c992 refactor: consolidate type-check helpers into generic wrenIsObjType and validate IS operand is class
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.
2014-01-21 15:52:03 +00:00
Bob Nystrom
f9371faf00 fix: store runtime error string in fiber and remove error parameter from stack trace printing 2014-01-21 06:55:11 +00:00
Bob Nystrom
a5c4918a75 feat: treat null as falsey in conditional and logical operator branches
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.
2014-01-21 02:12:55 +00:00
Bob Nystrom
a696c060fc chore: remove stale TODO comments for static fields and stack overflow in wren_value.c and wren_vm.c 2014-01-20 21:57:44 +00:00
Bob Nystrom
341147eaf4 refactor: extract duplicate marking logic into setMarkedFlag helper
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.
2014-01-20 21:54:14 +00:00
Bob Nystrom
ebb47d30e6 feat: replace Wren Range class with native C object for performance
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.
2014-01-20 16:45:15 +00:00
Bob Nystrom
7ad96755f4 feat: implement static methods as local variables in implicit class scope
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.
2014-01-19 21:01:51 +00:00
Bob Nystrom
7e196d9781 feat: add MAX_FIELDS constant and runtime overflow checks for class field limit of 255
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.
2014-01-15 15:59:10 +00:00
Bob Nystrom
8cee1f62bd fix: free GC objects in linked list when VM is freed
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.
2014-01-13 14:48:53 +00:00
Bob Nystrom
fc4880774e feat: implement fiber primitives with create, run, yield and caller tracking
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.
2014-01-12 19:02:07 +00:00
Bob Nystrom
33b0fae6f6 feat: extend jump offsets from 8-bit to 16-bit in compiler and VM
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.
2014-01-08 07:03:38 +00:00
Bob Nystrom
e23e0ce6a3 feat: remove hardcoded 256 symbol limit and switch to dynamic symbol table with 16-bit instruction arguments
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.
2014-01-04 19:08:31 +00:00
Bob Nystrom
64dab4db78 feat: add WREN_TRACE_GC flag and timing instrumentation to garbage collection
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.
2014-01-03 21:17:14 +00:00
Bob Nystrom
b93bd62623 refactor: extract SymbolTable into dedicated wren_utils module with prefixed API
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.
2014-01-02 04:57:58 +00:00
Bob Nystrom
1b605162ef refactor: move object freeing logic from wren_vm.c to wren_value.c alongside allocation code
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.
2014-01-01 21:31:19 +00:00
Bob Nystrom
547107a086 feat: add runtime error support with source paths, line info, and stack traces
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.
2014-01-01 21:25:24 +00:00
Bob Nystrom
4f215f6531 feat: allow empty blocks in parser and fix native call slot assertion
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.
2013-12-29 18:46:21 +00:00
Bob Nystrom
5570f7f46c refactor: rename nativeCallSlot and nativeCallNumArgs to foreignCallSlot and foreignCallNumArgs in WrenVM
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.
2013-12-29 18:14:38 +00:00
Bob Nystrom
b1e8d3f81e feat: add foreign method interface with native call support and argument passing
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.
2013-12-29 18:06:35 +00:00