Commit Graph

77 Commits

Author SHA1 Message Date
Bob Nystrom
ff420c816b feat: add wrenGetMethod, wrenCall, and wrenReleaseMethod for invoking Wren methods from C code 2015-02-28 21:31:15 +00:00
Bob Nystrom
c9f0dcde66 fix: convert signed integer types to unsigned in core and value modules to eliminate -Wsign-compare warnings
- Change `int` to `uint32_t` for iterator indices in `map_iterate` and `string_iterate` to match capacity/length types
- Update `String.length` field type from `int` to `uint32_t` in `wren_utils.h`
- Modify `wrenStringCodePointAt` parameter type from `int` to `uint32_t` and remove redundant negative index assertion
- Convert loop variable in `markMap` from `int` to `uint32_t` to match `map->capacity` type
- Add `-Wsign-compare`, `-Wtype-limits`, and `-Wuninitialized` compiler flags to catch future mismatches
2015-02-25 05:56:33 +00:00
Bob Nystrom
fca963cb48 fix: ensure UINT32_MAX is available in gcc C++ builds by defining __STDC_LIMIT_MACROS before including stdint.h in wren_common.h 2015-02-25 05:09:04 +00:00
Bob Nystrom
b3ea90f333 docs: correct comments in classDefinition, WREN_NAN_TAGGING define, and fix typo in collectGarbage 2015-02-21 08:09:55 +00:00
Bob Nystrom
d96fc0a381 feat: add map numeric/string benchmarks, IO.time, and refine Makefile clean targets
Add map_numeric and map_string benchmark scripts in Lua, Python, Ruby, and Wren to compare hash map insertion/lookup/deletion performance across languages. Register both new benchmarks in the benchmark runner script and fix its language executable paths to use WREN_DIR. Expose a new `IO.time` static method in the C IO module returning `time(NULL)` as a double. In the Makefile, split the monolithic `clean` target into separate removals for build artifacts, wren executables, and library variants to avoid accidental deletion of unrelated files. Remove hardcoded hash singleton constants from wren_value.c as they are no longer used.
2015-02-17 15:22:21 +00:00
Bob Nystrom
2082b64454 feat: move fiber execution of loaded modules from Wren to C runtime
The `loadModule_` primitive now returns a fiber when a module is loaded, and the C runtime handles calling it via `PRIM_RUN_FIBER` instead of the Wren code manually invoking the result. This removes the conditional `if (result != null) result.call` from the `import_` method in both the builtin source and the embedded libSource string, and adds `IS_FIBER` macro to `wren_value.h` for type checking in the native implementation.
2015-02-16 18:16:42 +00:00
Bob Nystrom
dc58f2aa06 feat: replace O(n) map deletion with tombstone-based open addressing
Replace the previous deletion strategy that required rehashing all entries after removal with a tombstone approach. When an entry is removed, its slot is marked with UNDEFINED_VAL key and TRUE_VAL value, allowing linear probing to continue past deleted slots during lookups. This prevents deletion from degrading to near-linear time in the presence of large clusters, matching the approach used by Python and Lua. Also refactor hashValue to hash raw bits of unboxed values under WREN_NAN_TAGGING, and update MapEntry documentation to clarify tombstone semantics.
2015-02-12 06:43:39 +00:00
Bob Nystrom
7cba07a322 feat: add shared library builds and fix string buffer type in symbol table
Add Makefile targets for building shared libraries (.so/.dylib) alongside existing static libraries, with platform-specific linker flags for macOS and Linux. Refactor the internal string representation from raw `char*` to a `String` struct that tracks both buffer and length, updating all symbol table operations, debug printing, and string concatenation calls to use the new type. Fix a null-termination bug in `copyName` and add support for the `\0` escape sequence in string literals.
2015-02-05 20:07:25 +00:00
Bob Nystrom
1fd8308f50 refactor: remove dedicated main module field from WrenVM struct
Instead of storing the main module directly in a dedicated field on WrenVM,
store it as a null-keyed entry in the new modules map. This eliminates the
redundant `vm->main` pointer and paves the way for supporting multiple named
modules. The change also adds `wrenFindVariable` as a public helper to look up
top-level variables in the main module, and updates `wrenNewFunction` to accept
an explicit module parameter instead of always using `vm->main`.
2015-02-05 20:03:19 +00:00
Bob Nystrom
9ed0bdac95 fix: cast index to uint32_t before comparing with string length in string_iterate 2015-02-05 04:28:27 +00:00
Bob Nystrom
8fa4f9c1bb refactor: change wrenStringFind to return UINT32_MAX instead of haystack->length for not-found
The wrenStringFind function previously returned the haystack length to indicate
a missing needle, which was ambiguous when the needle could legitimately appear
at the end of the string. This commit changes the sentinel value to UINT32_MAX,
updates all callers (string_contains, string_indexOf) to check against the new
sentinel, and adds explicit handling for empty needle and empty haystack edge
cases. The Boyer-Moore-Horspool implementation is also cleaned up with clearer
variable names and comments.
2015-02-05 04:23:50 +00:00
Bob Nystrom
84e1b78a7a feat: replace strstr with Boyer-Moore-Horspool string search in core string operations
Implement wrenStringFind function using Boyer-Moore-Horspool algorithm with 256-entry shift table for efficient substring matching. Update string_contains, string_indexOf, and string_count native methods to use the new implementation, fixing the empty string corner case to always return true when search string is empty.
2015-02-05 01:56:29 +00:00
Bob Nystrom
00226268c3 style: reformat string concat calls to 80 cols and fix comment typo
Break long wrenStringConcat calls across multiple lines in validateFn,
validateNum, validateIntValue, and validateString functions in
src/wren_core.c to stay within the 80-column limit. Also fix a comment
typo in src/wren_value.h: change "of" to "with" in the wrenStringConcat
documentation.
2015-02-04 16:15:35 +00:00
Marco Lizza
81a1a5a72f fix: add explicit length parameters to wrenStringConcat for null-containing string support
The function signature was changed from accepting null-terminated C strings to accepting explicit length parameters, with -1 indicating automatic strlen calculation. All call sites were updated to pass -1 for both lengths, and internal implementation switched from strcpy to memcpy to handle embedded null bytes correctly.
2015-02-04 12:44:39 +00:00
Marco Lizza
b43788a221 feat: replace strstr with wrenStringFind using Boyer-Moore-Horspool for 8-bit string support
Implement wrenStringFind function in wren_value.c that uses the Boyer-Moore-Horspool algorithm with a 256-entry shift table for full 8-bit character support. Update string_contains and string_indexOf native methods in wren_core.c to call the new function instead of strstr, fixing substring searches on strings containing null bytes or extended ASCII characters.
2015-02-04 12:38:15 +00:00
Marco Lizza
f5942f0123 fix: change ObjString length field type from int to uint32_t
The length field in ObjString struct is updated to use uint32_t instead of int,
ensuring consistent unsigned semantics for string size representation across
the codebase and preventing potential issues with negative length values.
2015-02-04 12:29:15 +00:00
Bob Nystrom
dcc4bf5487 fix: ensure NaN-tagged values are properly handled in hashValue and Value struct
The previous implementation of hashValue had UNREACHABLE() placed after the switch statement, which could be reached when using NaN-tagging mode. This fix moves UNREACHABLE() into default cases within each switch branch, ensuring it's only triggered for truly unreachable paths.

Additionally, the Value struct is refactored to use an anonymous union for num and obj fields, preventing undefined behavior from accessing inactive union members. All related macros and inline functions (AS_OBJ, wrenValuesSame, wrenObjectToValue, wrenValueToNum, wrenNumToValue, and singleton value definitions) are updated to use the new `as` union member access pattern.
2015-02-01 23:26:33 +00:00
Bob Nystrom
6858db260a fix: replace bitfield flags with bool marked and fix empty map lookup crash
Replace the ObjFlags bitfield approach with a simple bool `marked` field on Obj, removing the FLAG_MARKED constant and all bitwise operations. Also add a guard in wrenMapFind to return UINT32_MAX when map capacity is zero, preventing a crash on empty map subscript lookups. Fix the validateKey function to not wrap the error string in OBJ_VAL.
2015-01-30 15:21:41 +00:00
Bob Nystrom
7febf6cd57 refactor: convert Module struct to heap-allocated ObjModule with GC support
Replace the embedded `Module main` field in WrenVM with a pointer to a dynamically allocated `ObjModule`, adding a new OBJ_MODULE object type. Introduce `wrenNewModule()` constructor and `markModule()` GC tracer, update all references from `&vm->main` to `vm->main`, and remove the old `initModule`/`freeModule` static helpers.
2015-01-27 15:11:45 +00:00
Marco Lizza
ef9d17f641 refactor: replace bitwise ObjFlags with boolean marked field for GC tracking
Replace the single-bit FLAG_MARKED enum and ObjFlags bitfield with a direct bool 'marked' field on the Obj struct. This simplifies the garbage collector's mark-sweep logic by removing unnecessary bitwise operations (|, &, ~) and the associated enum definition, making the intent clearer and reducing cognitive overhead when reading GC-related code paths.
2015-01-27 13:13:26 +00:00
Marco Lizza
1acddac5e8 refactor: replace bitfield members with full-width ObjType and ObjFlags in Obj struct 2015-01-27 13:09:32 +00:00
Bob Nystrom
a794ce4ee1 refactor: move global variable storage from VM into Module struct
Functions now hold a reference to the module where they were defined and load module-level variables from there instead of from the VM's global table. This introduces a new Module struct with its own variable buffer and symbol table, replacing the VM-level globals and globalNames. The main module is stored directly in the VM as a temporary measure. Performance regresses slightly due to the indirection through the function's module pointer.
2015-01-26 15:45:21 +00:00
Bob Nystrom
f647680184 feat: add remove() method to Map class with native implementation and tests 2015-01-26 01:42:36 +00:00
Bob Nystrom
a83205ef89 feat: add containsKey method to Map and validate key types in subscript operations
Implement `containsKey()` native method on Map that returns a boolean indicating whether the given key exists in the map. Add `validateKey()` helper to reject non-value-type keys (objects, lists, fibers, etc.) with a clear runtime error. Refactor `wrenMapGet()` signature to return success/failure via bool and output the value through an out-parameter, enabling both `containsKey()` and the existing subscript operator to share the same key validation and lookup logic. Update `map_subscript` to return `null` instead of crashing when a key is not found. Add test cases for `containsKey` success/failure, and runtime error tests for invalid key types in subscript getter, setter, and containsKey.
2015-01-25 20:39:19 +00:00
Bob Nystrom
5c33ecc04f feat: add initial Map class with hash table, subscript, and count support
Implement the core Map data structure in Wren, including the ObjMap type with
hash table storage, native methods for instantiation, subscript get/set, and
count. Add Map class declaration to core.wren with a basic toString stub.
Introduce MapEntry struct and hash table growth logic with configurable load
factor. Add test files for map creation, count tracking, key type support
(including null, bool, num, string, range, and class keys), and growth
behavior. Refactor list capacity constants into shared MIN_CAPACITY and
GROW_FACTOR macros. Change object equality operators to use wrenValuesSame
instead of wrenValuesEqual.
2015-01-25 06:27:35 +00:00
Bob Nystrom
368d9a3052 feat: add arity getter to Fn class and rename numParams to arity
Add a public `arity` getter to the Fn class that returns the number of required arguments for a function. Internally rename the `numParams` field to `arity` across the codebase for consistency, update the C API parameter name from `numParams` to `arity` in `wrenDefineMethod` and `wrenDefineStaticMethod`, and adjust the error message in `callFunction` to use the new field name. Also update documentation to clarify that extra arguments are ignored rather than causing an error, and add a new test file `test/function/arity.wren` verifying arity values from 0 to 4.
2015-01-24 04:33:05 +00:00
Bob Nystrom
2fdb5cddd0 feat: add FLEXIBLE_ARRAY macro and update struct hack usage for C89/C99 portability 2015-01-23 18:38:12 +00:00
Bob Nystrom
2a123400b6 feat: add MSVC 2013 project files and fix C89 compatibility for Windows build
Add Visual Studio 2013 solution and project files under project/msvc2013/ directory, enabling native Windows builds without MinGW. Include Marco Lizza in AUTHORS for the contribution. Fix C89 compatibility issues for MSVC: disable computed goto via _MSC_VER check, define inline as _inline for non-C++ mode, change flexible array members from empty brackets to [0] syntax, and fix char to int type for readHexDigit return value. Refactor single-line if/while/for bodies in wren_compiler.c to use braces to satisfy MSVC stricter parsing.
2015-01-23 18:12:12 +00:00
Bob Nystrom
7e52e36a1c docs: clarify UTF-8 byte indexing in string subscript and add wrenStringCodePointAt helper 2015-01-23 00:38:03 +00:00
Marco Lizza
9b350e3e7d fix: replace zero-length flexible array members with zero-sized arrays to suppress non-standard warnings
In `src/wren_value.h`, change three flexible array members (`char value[]`, `Upvalue* upvalues[]`, `Value fields[]`) to explicit zero-sized arrays (`char value[0]`, `Upvalue* upvalues[0]`, `Value fields[0]`) to resolve compiler warnings about non-standard zero-sized array usage in structs `ObjString`, `ObjClosure`, and `ObjInstance`.
2015-01-21 09:21:04 +00:00
Bob Nystrom
1408294553 fix: add explicit uintptr_t cast in AS_OBJ macro for 32-bit MinGW compatibility
The AS_OBJ macro on NaN-tagged architectures was performing a direct cast from
uint64_t to Obj* which triggers a pointer-to-integer cast warning on 32-bit
MinGW where sizeof(Obj*) is 4 bytes. Adding an intermediate cast to uintptr_t
ensures the value is properly truncated before conversion to the pointer type.

Also replaces IS_SINGLETON macro usage with direct NULL_VAL/UNDEFINED_VAL
comparisons and removes the now-unused IS_SINGLETON definition.
2015-01-21 01:06:39 +00:00
Bob Nystrom
26fd4d2192 feat: refactor Value union to uint64_t and add C++98 compatibility for Wren VM
- Replace Value union with plain uint64_t typedef under WREN_NAN_TAGGING, removing num/bits field access
- Add wrenValueToNum and wrenNumToValue helper functions for double conversion
- Remove wrenValuesEqual function from wren_value.c as bitwise comparison is now direct
- Update Makefile with CPPFLAGS for C++98 compilation and add release-cpp build target
- Add wren-cpp and libwren-cpp.a to .gitignore for C++ build artifacts
2015-01-16 05:12:51 +00:00
Bob Nystrom
72291f8b74 feat: implicitly declare nonlocal names as globals for forward references
Add support for forward references to top-level variables by implicitly
declaring unresolved capitalized names as globals during compilation.
If a real definition is not found later, a compile-time error is raised.
This enables mutual recursion at the top level and fixes issues #101 and #106.

Introduce an `UNDEFINED` singleton value to mark implicitly declared globals
that have not yet been explicitly defined. Update `wrenDeclareGlobal` to add
such entries, and modify `wrenDefineGlobal` to check for and replace undefined
placeholders. Adjust the symbol table API to allow duplicate additions for
implicit declarations. Add test cases for mutual recursion, forward references
in functions and methods, and undefined variable errors.
2015-01-15 07:08:25 +00:00
Bob Nystrom
041e6213d5 refactor: change ObjString length field from size_t to int for consistency and reduced memory usage
The length field in ObjString struct now uses int instead of size_t, saving memory
and aligning with other string length storage conventions throughout the VM.
This eliminates signed/unsigned conversion warnings and matches the type used
elsewhere for string lengths.
2015-01-08 15:41:30 +00:00
Evan Shaw
38d93e9850 style: align continuation indentation and rephrase comment in ObjString length field 2015-01-08 06:34:58 +00:00
Evan Shaw
34670fa586 feat: store explicit string length in ObjString struct for wren values
Add a `length` field to the `ObjString` struct in `wren_value.h` and initialize it in `wrenNewUninitializedString()` in `wren_value.c`. This stores the string's byte count excluding the null terminator, enabling O(1) length retrieval while preserving null-terminated C string compatibility.
2015-01-07 20:53:32 +00:00
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