Commit Graph

41 Commits

Author SHA1 Message Date
Evan Shaw
0dcd7bbffc refactor: embed string data as flexible array member in ObjString struct
Remove separate heap allocation for string text by storing it directly in the ObjString struct using a C99 flexible array member. This eliminates the need for an extra pointer indirection and a separate memory allocation call in wrenNewUninitializedString, while also simplifying the cleanup logic in wrenFreeObj by removing the explicit deallocation of the string's value buffer.
2015-01-05 02:03:50 +00:00
Bob Nystrom
1663d4d95c fix: name anonymous union in Method struct to comply with strict C99
The anonymous union inside the Method struct was previously unnamed, which is not allowed in strict C99 mode. This change names the union `fn` and updates all references to its members (`.primitive`, `.foreign`, `.obj`) to use the qualified syntax (`.fn.primitive`, `.fn.foreign`, `.fn.obj`). The NATIVE macro parameter was also renamed from `fn` to `function` to avoid shadowing the new union field name.
2015-01-03 04:17:10 +00:00
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
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
77bddf8f0a refactor: extract wrenNewUninitializedString to avoid passing NULL to wrenNewString for empty buffers 2014-12-06 18:04:46 +00:00
Bob Nystrom
d9a42f21ba fix: add missing -lm link flag and fix GCC warnings for getline and switch coverage
Add -lm flag to both debug and release linker commands in Makefile to resolve
undefined math library references. Define _GNU_SOURCE in main.c to make getline()
available under GCC. Add default cases to switch statements in runFile and
getNumArguments to suppress -Wswitch warnings. Fix u_int8_t to uint8_t type in
wrenNewFunction declaration and definition for POSIX compliance.
2014-11-26 22:03:05 +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
8d1e9750b8 feat: implement List instantiation via "new" and fix inline functions to static
Add `list_instantiate` native to create empty lists, bind it to List's metaclass for `new` support, and remove the related TODO. Also change three `inline` functions in `wren_value.h` to `static inline` to prevent linker errors. Include a new test `test/list/new.wren` verifying `new List` yields an empty list that supports `add`.
2014-04-08 14:31:23 +00:00
Bob Nystrom
8113e0bfc0 perf: inline wrenIsBool and wrenIsObjType into header, remove from source
Move the wrenIsBool and wrenIsObjType function definitions from wren_value.c
into wren_value.h as inline functions, eliminating function call overhead.
Also relocate OBJ_VAL macro definition to appear before its first use in the
header and add inline for wrenObjectToValue. This yields 3-13% speedup across
benchmarks (binary_trees, delta_blue, fib, for, method_call).
2014-04-08 14:17:25 +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
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
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
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
cf5a34025b feat: add isInclusive field to ObjRange and implement proper exclusive range iteration
Add isInclusive boolean to ObjRange struct to distinguish between inclusive (..) and exclusive (...) ranges. Update wrenNewRange signature to accept isInclusive parameter. Implement correct iteration logic for both ascending and descending ranges, handling empty exclusive ranges and floating-point iteration. Add type validation for range RHS operands. Update min/max/to properties to return raw endpoint values instead of adjusted ones. Add comprehensive test coverage for inclusive/exclusive ranges, negative ranges, empty ranges, floating-point iteration, isInclusive property, toString, and type error cases.
2014-01-20 21:20:22 +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
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
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
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
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
Bob Nystrom
e055360616 refactor: pass constants and bytecode directly to wrenNewFunction instead of post-assignment
Refactor ObjFn creation in endCompiler to pass all data (constants, bytecode, upvalues) directly to wrenNewFunction, eliminating the temporary post-construction assignment loop and memcpy. Update wrenNewFunction signature to accept these parameters, copy constants into a new owned array, and take ownership of the bytecode buffer. Adjust ObjFn struct to use dynamic bytecode pointer and bytecodeLength field instead of fixed-size array. Update memory tracking in markFn and cleanup in freeObj to handle the new dynamic bytecode allocation.
2013-12-27 01:28:33 +00:00
Bob Nystrom
ce60209fcc refactor: replace hardcoded ObjFn arrays with growable buffers in compiler
Restructure Compiler to use dynamic bytecode and constant buffers instead of
relying on ObjFn's fixed-size arrays. Move ObjFn creation to the end of
compilation, add wrenListAdd/Insert/RemoveAt helpers to wren_value, relocate
list capacity macros and ensureListCapacity into wren_value.c, and store a
Compiler pointer in WrenVM for GC safety during compilation.
2013-12-27 00:58:03 +00:00
Bob Nystrom
d972a6a696 refactor: replace unsigned char with uint8_t across debug, value, and vm modules
Migrate bytecode pointer types from `unsigned char*` to `uint8_t*` in `wren_debug.c`, `wren_value.h`, and `wren_vm.c` for consistent fixed-width integer usage. Also expand `ObjFn` bytecode array from 1024 to 2048 elements and update corresponding memory allocation in `markFn` to reflect the doubled capacity.
2013-12-26 00:31:30 +00:00
Bob Nystrom
dfe53d945c feat: inline bytecode array into ObjFn struct to eliminate separate heap allocation
Remove the dynamically allocated `bytecode` pointer from `ObjFn` and replace it with a fixed-size `unsigned char bytecode[1024]` array embedded directly in the struct. This eliminates the need for a separate `allocate` call in `wrenNewFunction`, the associated `deallocate` in `freeObj`, and the pointer indirection, simplifying memory management and improving cache locality for function bytecode access.
2013-12-26 00:19:35 +00:00
Bob Nystrom
d6e4d6bcf7 refactor: change CallFrame and Method fn fields from Value to Obj*
Replace the `fn` field in `CallFrame` and `Method` structs from `Value` to `Obj*`, since it always holds an ObjFn or ObjClosure. Update all callers to use `AS_OBJ` and `markObj` instead of `markValue`. Fix a bug in `freeObj` where `OBJ_CLOSURE` case incorrectly freed the upvalues flexible array instead of falling through to the no-op case.
2013-12-26 00:12:07 +00:00
Bob Nystrom
b081f2622d chore: remove resolved TODO comments and fix buffer size in num_toString
- Remove two TODO comments in wren_compiler.c about parameter length overflow check and assignment in named call
- Remove TODO about interning bool_toString and null_toString strings in wren_core.c
- Replace oversized 100-char temp buffer with precise 21-char buffer in num_toString, referencing Lua implementation
- Rename io_write native to io_writeString and remove TODO about calling toString on argument
2013-12-23 23:38:00 +00:00
Bob Nystrom
8c13258ef6 feat: promote Fiber from raw struct to heap-allocated ObjFiber with GC support
Refactor the VM's fiber representation from a stack-allocated `Fiber` struct embedded in `WrenVM` to a full `ObjFiber` object managed by the garbage collector. This includes adding the `OBJ_FIBER` object type enum, a `wrenNewFiber` allocation function, a `markFiber` traversal routine for GC marking, and updating all internal APIs (`DEF_FIBER_NATIVE`, `wrenDebugDumpStack`) to use `ObjFiber*` instead of `Fiber*`. The `Fiber` struct definition and its associated `CallFrame` type are moved from `wren_vm.h` into `wren_value.h`, and the `STACK_SIZE`/`MAX_CALL_FRAMES` constants are relocated accordingly. Additionally, the `vm->fiber` singleton pointer is removed, the `vm->unsupported` sentinel value is eliminated (replaced by returning `NULL_VAL` for invalid numeric operands), and the `wrenInterpret` function is temporarily removed. The `wrenNewClass` function's metaclass pinning order is also corrected to prevent premature GC collection.
2013-12-22 22:31:33 +00:00
Bob Nystrom
91873b3a90 refactor: split class creation into raw single-class and superclass binding phases
The bootstrapping of Object and Class now uses a two-phase approach: first creating a raw class with no metaclass or superclass via wrenNewSingleClass, then explicitly wiring superclass relationships with wrenBindSuperclass. This eliminates the need for special-case handling of null superclasses in the old newClass function and makes the metaclass chain setup explicit in wrenInitializeCore.
2013-12-22 04:44:37 +00:00
Bob Nystrom
7638dd2ee2 refactor: embed upvalue array directly in ObjClosure using flexible array member
Replace the separate heap-allocated `Upvalue** upvalues` pointer in `ObjClosure` with a C99 flexible array member `Upvalue* upvalues[]`. This eliminates an extra allocation per closure, reduces memory fragmentation, and simplifies the allocation logic in `wrenNewClosure` by computing the total size as `sizeof(ObjClosure) + sizeof(Upvalue*) * fn->numUpvalues`. The upvalue array is still zero-initialized to prevent GC issues during partial construction.
2013-12-16 06:02:22 +00:00
Bob Nystrom
55041f4640 feat: replace int-based booleans with stdbool.h bool type across core source files
Migrate all boolean-typed parameters, return values, struct fields, and local variables from `int` (with 0/1 convention) to C99 `bool` (`true`/`false`). Update corresponding comments, macro definitions, and documentation strings to use `true`/`false` terminology instead of "non-zero"/"zero". Add `#include <stdbool.h>` to `src/main.c`, `src/wren_compiler.c`, and `src/wren_value.h`. Remove the stale TODO comment in `src/wren_common.h` that originally proposed this change.
2013-12-15 07:41:23 +00:00
Bob Nystrom
34db2b2b9f chore: remove author attribution from TODO comments across multiple source files
Remove "(bob)" author prefix from all TODO comments in benchmark/method_call.wren, include/wren.h, src/main.c, src/wren_common.h, src/wren_compiler.c, src/wren_core.c, src/wren_value.c, src/wren_value.h, and src/wren_vm.c. Update the TODO_PATTERN regex in metrics script to match the new format without author parentheses. Also refactor test file counting in metrics to use os.walk with fnmatch for recursive directory traversal instead of glob.iglob.
2013-12-14 23:28:18 +00:00
Bob Nystrom
78f6e3b96d perf: inline wrenObjectToValue and switch Xcode project to C99 for speed bump 2013-12-14 19:34:49 +00:00
Bob Nystrom
fc3ebb924c refactor: replace raw #ifdef NAN_TAGGING with WREN_NAN_TAGGING flag and add WREN_COMPUTED_GOTO, WREN_DEBUG_GC_STRESS, WREN_TRACE_MEMORY configurable defines
Convert all conditional compilation guards from bare `#ifdef NAN_TAGGING` to `#if WREN_NAN_TAGGING` across wren_common.h, wren_value.c, wren_value.h, and wren_vm.c. Introduce new `#ifndef`-based defaults for WREN_NAN_TAGGING, WREN_COMPUTED_GOTO, WREN_DEBUG_GC_STRESS, and WREN_TRACE_MEMORY in wren_common.h, replacing the old TODO comments and commented-out debug flags. Update preprocessor indentation style for consistency.
2013-12-14 19:06:54 +00:00
Bob Nystrom
d7a0063f4b feat: replace constructor method special-casing with dedicated CODE_NEW instruction
Remove the METHOD_CTOR method type and CODE_METHOD_CTOR opcode, replacing them with a new CODE_NEW instruction that creates class instances directly in the bytecode. This simplifies the compiler by emitting CODE_NEW at the start of constructor bodies instead of relying on a separate method dispatch path, and eliminates the redundant METHOD_CTOR enum value from the method lookup logic.
2013-12-13 19:32:47 +00:00
Bob Nystrom
5e62b5856e perf: reorder MethodType enum and switch cases to improve branch prediction
Reorder the `MethodType` enum values so that `METHOD_NONE` is placed last instead of first,
and correspondingly move the `METHOD_NONE` case in the interpreter's dispatch switch to the
end of the case list. This places the most frequently executed method types (`METHOD_PRIMITIVE`,
`METHOD_FOREIGN`, `METHOD_BLOCK`, `METHOD_CTOR`) earlier in both the enum and the switch,
which can improve branch prediction and instruction cache locality in the hot dispatch loop.
2013-12-12 15:39:27 +00:00
Bob Nystrom
d8c31a4391 feat: add wrenBindMethod to patch field indices and superclass dispatch in inherited methods
When a class is defined, its superclass is not known until runtime since class definitions are imperative statements. This adds a new wrenBindMethod function that walks the bytecode of a method after it is bound to a class, adjusting LOAD_FIELD/STORE_FIELD indices to account for inherited fields and patching superclass dispatch targets. The newClass function now correctly accumulates numFields from the superclass chain, and the VM calls wrenBindMethod when binding methods to a class. Includes new test files for inherited field access and the is operator.
2013-12-11 00:13:25 +00:00
Bob Nystrom
5b05c477c6 feat: implement closures with upvalue support and statement/expression separation
Add closure objects that wrap functions with captured upvalues, enabling
first-class closures that close over local variables from enclosing scopes.
Introduce new bytecode instructions (CODE_CLOSURE, CODE_LOAD_UPVALUE,
CODE_STORE_UPVALUE, CODE_CLOSE_UPVALUE, CODE_RETURN) and a CompilerUpvalue
tracking system with a MAX_UPVALUES limit of 256. Refactor the grammar to
strictly separate statements from expressions, fixing a bug where block
expressions incorrectly popped locals while temporaries remained on the
stack. Rename internal functions (wrenCallFunction, wrenDebugDumpInstruction,
wrenDebugDumpStack) and add Upvalue allocation, closure creation, and
debug dump support for the new instructions.
2013-12-04 15:43:50 +00:00
Bob Nystrom
f9c534aef9 chore: rename source files to wren_ prefix and add module-level documentation headers 2013-11-28 16:11:50 +00:00