Commit Graph

544 Commits

Author SHA1 Message Date
Bob Nystrom
550fd13565 chore: relocate AS_* and IS_* macros to top of wren_value.h for better organization 2015-03-19 14:28:53 +00:00
Bob Nystrom
1e842bbb2e feat: store precomputed hash in ObjString and use it for equality and hashing
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.
2015-03-18 14:09:03 +00:00
Bob Nystrom
a3418dc06a feat: swap list insert arguments to index-first order and update all call sites
Swap the parameter order of `List.insert()` from `(item, index)` to `(index, item)`,
matching the convention used by most standard libraries. Update the C implementation
in `wren_core.c`, all documentation examples, and every test file to reflect the new
signature. Also restructure MSVC project files to match the new `src/cli/` and
`src/vm/` directory layout, add Visual Studio cache files to `.gitignore`, and fix
a trailing whitespace issue in `class_supertype`.
2015-03-17 14:01:09 +00:00
Bob Nystrom
f6da4700f4 fix: guard string hash loop against zero-length strings causing division by zero 2015-03-17 14:00:54 +00:00
Bob Nystrom
0d42d87689 feat: reverse List.insert argument order to index-first, value-second
The `List.insert` method signature is changed from `insert(item, index)` to `insert(index, item)`, aligning with standard practice in most languages. All documentation, core implementation, and test files are updated to reflect the new parameter order. The `validateIndex` call now reads the index from slot 1 instead of slot 2, and the value is read from slot 2.
2015-03-16 16:18:59 +00:00
Bob Nystrom
76baf731db refactor: extract CLI VM creation and file execution into separate vm.c/vm.h
Move runFile() and VM configuration logic from main.c into new vm.c module,
exposing createVM() and runFile() functions. This decouples CLI script
execution from the REPL and main entry point, enabling reuse of the same
VM setup and file-running code for API tests.
2015-03-16 14:42:45 +00:00
Bob Nystrom
11a61b47ab feat: extract CLI file loading functions into separate io.c and io.h
Extract the static `readFile`, `readModule`, and `setRootDirectory` functions from main.c into a new io module, replacing the fixed-size `rootDirectory` array with a heap-allocated pointer and adding the corresponding header with public declarations.
2015-03-16 14:22:52 +00:00
Bob Nystrom
db365ae9fa fix: correct object type label in dumpObject for OBJ_RANGE case
The dumpObject function in wren_debug.c was incorrectly printing "[fn %p]" for
OBJ_RANGE objects instead of the correct "[range %p]" label. This fix ensures
that range objects are properly identified during debug output.
2015-03-16 14:05:40 +00:00
Bob Nystrom
a73ee9a8e7 fix: pass missing argName to wrenStringFormat in validateIntValue and validateIndexValue
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.
2015-03-16 06:17:08 +00:00
Bob Nystrom
e95b32188f refactor: replace sizeof-based string length with strlen in CONST_STRING macro
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.
2015-03-16 06:07:20 +00:00
Bob Nystrom
9314cbfd72 refactor: replace manual string concatenation with wrenStringFormat across VM core
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.
2015-03-16 05:32:20 +00:00
Thorbjørn Lindeijer
9a01d4b489 feat: reverse argument order of List.insert to index-first convention
The previous signature `insert(element, index)` was counter-intuitive and inconsistent with every major language's list API. This commit swaps the parameters to `insert(index, element)`, matching the convention used by Ruby, JavaScript, C++, Lua, C#, Java, and Python. All documentation, C implementation, and test files are updated to reflect the new order.
2015-03-15 21:51:24 +00:00
Bob Nystrom
d731e554e6 refactor: rename debug print functions to dump and move value printing to wren_debug.c 2015-03-15 17:09:43 +00:00
Bob Nystrom
cf3db93a06 refactor: remove failIf helper and return NULL on missing file in readFile 2015-03-15 17:09:22 +00:00
Bob Nystrom
18cf57d5f5 refactor: split source tree into vm/ and cli/ directories with updated build system
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.
2015-03-14 22:00:50 +00:00
Bob Nystrom
8436ead62e feat: add Class.supertype primitive and documentation for retrieving superclass
Implement a new `supertype` property on Class objects that returns the superclass of a given class. The primitive `class_supertype` checks if the class has a superclass (returning null for Object) and returns the superclass object. Includes documentation in the class reference and a test file verifying behavior for explicit superclasses, implicit Object inheritance, and Object's null supertype.
2015-03-14 16:48:45 +00:00
Bob Nystrom
3c44a3a001 refactor: replace manual zero-initialization with memset in wrenNewVM
Remove explicit NULL and zero assignments for vm fields (methodHandles, foreignCallSlot, foreignCallNumArgs, bytesAllocated, compiler, fiber, first, numTempRoots, modules) and consolidate them into a single memset(vm, 0, sizeof(WrenVM)) call, simplifying the initialization logic.
2015-03-14 16:36:27 +00:00
Bob Nystrom
f2693f57ad refactor: extract DEBUG_TRACE_INSTRUCTIONS macro and fix RUNTIME_ERROR brace style in runInterpreter
Moves the debug trace instruction printing logic from inline DISPATCH() macro into a dedicated DEBUG_TRACE_INSTRUCTIONS macro with proper WREN_DEBUG_TRACE_INSTRUCTIONS guard, and adjusts RUNTIME_ERROR macro to use Allman brace style for consistency with surrounding code.
2015-03-14 16:29:17 +00:00
Bob Nystrom
e52573c3f6 fix: change infinity string representation from "inf" to "infinity" in num_toString
Update the num_toString primitive in wren_core.c to return "infinity" and "-infinity"
instead of the platform-dependent "inf" and "-inf" for positive and negative infinity
values. This ensures consistent string output across different C compilers and
platforms that may format infinity differently. Update the corresponding test
expectations in test/number/divide.wren to match the new output format.
2015-03-13 14:35:10 +00:00
Bob Nystrom
9c56d90e1c fix: cast size_t arguments to unsigned long for consistent printf format across architectures 2015-03-13 14:27:11 +00:00
Bob Nystrom
e2555a0b96 chore: remove boilerplate comment block and fix include guard in wren_debug.h
Remove the Xcode-generated file header comment with copyright notice
and author attribution from wren_debug.h. Also correct the include guard
macro from `wren_wren_debug_h` to `wren_debug_h` to match the actual
file path and naming convention used by other headers in the project.
2015-03-13 14:26:42 +00:00
Bob Nystrom
eea7803aae fix: correct comment and fix typo in wren compiler and vm files
- Fix misleading comment in `new_` function in `wren_compiler.c` to accurately describe angle brackets instead of leading space
- Fix typo "Uknown" to "Unknown" in assertion message in `wrenCall` function in `wren_vm.c`
- Remove trailing whitespace in `wren_vm.c`
2015-03-12 14:26:29 +00:00
Bob Nystrom
101c94802b fix: pass char* buffer instead of ObjString to error() in wrenCompile
In the variable undefined check within wrenCompile, the error() call was
receiving an ObjString struct instead of its underlying char* buffer,
causing a type mismatch. Changed the argument to access the .buffer field
of the variable name string.
2015-03-11 14:31:18 +00:00
Gavin Schulz
a0e7e1fc67 fix: correct comment about name mangling in new_ function
The comment previously stated that a leading space prevents direct calls,
but the actual mechanism uses angle brackets in the method name "<instantiate>"
to make it inaccessible from user code.
2015-03-09 01:22:17 +00:00
Gavin Schulz
6c36816245 fix: correct spelling of "Unknown" in ASSERT message for argument type validation 2015-03-09 00:44:24 +00:00
Bob Nystrom
146995d54d chore: remove outdated TODO comments across compiler, core, value, and vm headers
- Delete TODO about nullary constructor handling in constructorSignature
- Remove TODO and commented-out code for making fibers iterable in wrenInitializeCore
- Eliminate TODO questioning elimination of OBJ_CLASS enum in favor of classObj pointers
- Drop TODO about moving WrenVM struct definition and using array for class fields
2015-03-07 22:10:34 +00:00
Bob Nystrom
250a855d82 fix: return null from IO.read on EOF instead of empty string
Previously, IO.read would return an empty string when stdin reached EOF because it always called wrenReturnString with the buffer, even when fgets returned NULL. Now it returns null by only calling wrenReturnString when fgets succeeds, and adds a test case verifying that IO.read returns null on EOF.
2015-03-07 21:47:07 +00:00
Bob Nystrom
3979a7dfff refactor: replace wrenMapFind with wrenMapGet returning Value instead of index
Refactor the internal Map API to replace the low-level `wrenMapFind` function
(which returned a raw entry index or UINT32_MAX) with a higher-level
`wrenMapGet` that directly returns the stored Value or UNDEFINED_VAL.

This change simplifies all call sites by eliminating manual index-based entry
lookups and direct access to the internal `entries` array. The old
`wrenMapFind` is made static and renamed to `findEntry`, returning a pointer
to the MapEntry struct instead of an index, which is used internally by
`wrenMapGet` and `wrenMapRemoveKey`.

Additionally, fix a bug in `loadModule` where a new module was always created
before checking if the module already existed; now the early return for
already-loaded modules correctly skips module creation and variable copying.
2015-03-07 20:41:18 +00:00
Bob Nystrom
f1fd125385 feat: allow yielding main fiber and expose current fiber reference
- Change Fiber.yield() to exit interpreter when no parent fiber exists instead of raising runtime error
- Add Fiber.current primitive to return the currently executing fiber object
- Update interpreter loop to stop execution when PRIM_RUN_FIBER receives null value
- Modify test expectations to reflect new yielding behavior from main fiber
2015-03-07 20:32:11 +00:00
Michel Martens
bdd0708a99 fix: return null from IO.read on EOF instead of empty string
Previously, IO.read would return an empty string when reading from stdin reached EOF. This changes the behavior to return null when fgets returns NULL, indicating end-of-file. The fix removes the unconditional wrenReturnString call and only returns the buffer when data was actually read. A new test case verifies that IO.read returns null on EOF.
2015-03-07 09:10:18 +00:00
Bob Nystrom
7dcd39f512 fix: remove deprecated num_deg and num_rad primitives, simplify num_fraction implementation 2015-03-07 06:52:42 +00:00
Bob Nystrom
92d72be158 feat: add deg, rad, fraction, sign, truncate primitives to num class
Add five new numeric methods to the Wren core library: deg (convert radians to degrees), rad (convert degrees to radians), fraction (extract fractional part), sign (return -1, 0, or 1), and truncate (discard fractional part). Register all new primitives in wrenInitializeCore and include corresponding test files for fraction, sign, and truncate operations.
2015-03-07 06:43:02 +00:00
Bob Nystrom
b712bb1929 feat: add count method to Sequence class with iteration-based element tally
Implement a `count` method on the `Sequence` class that iterates over all elements and returns the total number. The method uses a simple for-loop to increment a counter for each element, providing a generic way to determine sequence length without requiring a separate length property. Includes a test sequence that yields values 1 through 10 to verify the count returns 10.
2015-03-06 15:01:02 +00:00
Marco Lizza
ea20c2d086 fix: remove redundant integer division primitive from wren core
The `num_div` primitive performed integer division on two int32 values, but this
functionality is already covered by the existing `num_divide` primitive which
handles floating-point division. Removing this duplicate method eliminates
confusion and reduces code maintenance burden.
2015-03-05 08:48:52 +00:00
Marco Lizza
86ab538c21 style: reformat num_sign primitive to use early returns and consistent brace style 2015-03-04 23:47:54 +00:00
Marco Lizza
a4ebc39877 fix: replace int32_t cast with modf for correct truncate behavior
The previous implementation cast the number to int32_t, which incorrectly
truncated values outside the int32_t range and produced wrong results for
large doubles. The new implementation uses the standard C `modf` function
to correctly truncate the fractional part while preserving the full
double precision of the integer portion.
2015-03-04 23:46:45 +00:00
Marco Lizza
adca2b3aac feat: rename 'decimal' primitive to 'fraction' and reimplement using modf
Replace the num_decimal primitive with num_fraction, changing the implementation from a simple subtraction of integer part to using the standard C modf function for more robust fractional part extraction. Update the method registration in wrenInitializeCore to bind the new name and function.
2015-03-04 23:45:30 +00:00
Marco Lizza
5ffb2815ae feat: add integer division primitive 'div' to num class in wren_core.c
Implement DEF_PRIMITIVE(num_div) that casts both operands to int32_t
and performs integer division, returning the truncated quotient.
Register the new primitive as "div(_)" on the num class in
wrenInitializeCore, placed alphabetically between "deg" and "floor".
2015-03-04 15:10:37 +00:00
Bob Nystrom
6519dbf70e refactor: replace per-type mark helpers with unified wrenMarkObj in GC marking
Remove the dedicated `setMarkedFlag`, `markString`, `markFn`, and `markClass` helper functions, replacing their calls with the new generic `wrenMarkObj` entry point. This eliminates duplicated marking logic and ensures all object types go through a single marking path that handles cycle detection and memory tracking consistently.
2015-03-04 15:08:48 +00:00
Marco Lizza
610f98957f style: rename local variable num to value in num_decimal and num_sign primitives for consistency 2015-03-04 13:46:24 +00:00
Marco Lizza
2e36078d6e fix: extend num_sign primitive to return 0 for zero-valued numbers 2015-03-04 13:45:51 +00:00
Marco Lizza
1a60874e9c feat: add 'sign' primitive method to Number class returning 1 for non-negative and -1 for negative
Implement the num_sign primitive that checks if the numeric argument is >= 0.0
and returns 1.0 for non-negative values or -1.0 for negative values. Register
the new primitive on the Number class in wrenInitializeCore.
2015-03-04 13:42:50 +00:00
Marco Lizza
74943b558c fix: swap implementations of num_decimal and num_truncate primitives
The num_decimal primitive was incorrectly returning the integer part of a number
instead of the fractional part, while num_truncate was returning the fractional
part instead of truncating to the integer portion. This commit corrects both
functions by exchanging their logic bodies.
2015-03-04 13:42:34 +00:00
Marco Lizza
0a448e08d1 feat: add decimal and truncate number methods to wren core
Implement two new primitive methods for the Number class: `decimal` returns the integer part by casting to uint32_t, and `truncate` returns the fractional part by subtracting the integer portion from the original value. Register both primitives in the core initialization.
2015-03-03 23:29:19 +00:00
Marco Lizza
3c2c84e390 feat: add deg and rad number conversion primitives to Num class
Implement two new primitive methods on the Num class: `deg` converts radians to degrees by multiplying by 180/π (57.29578) and flooring, while `rad` converts degrees to radians by dividing by the same factor and flooring. Both are registered in `wrenInitializeCore` alongside existing trigonometric primitives.
2015-03-03 23:28:44 +00:00
Bob Nystrom
4781e77809 feat: add Sequence.any method and update docs, tests, and core source
Implement the `any` method on the Sequence class that returns true if any element passes the given predicate function. Update the core.wren library source, the C embedded source string in wren_core.c, and add comprehensive test files for normal usage, non-bool return values, and non-function argument error handling. Also fix a typo in the QA documentation and correct the initial account balance in the example.
2015-03-03 15:23:47 +00:00
Bob Nystrom
f809e4a1f1 refactor: extract shared makeNumber helper and fix OBJ_VAL wrapping in num_fromString
Extract the duplicated number parsing logic from readHexNumber and readNumber into a single makeNumber function that accepts an isHex flag. Also fix a missing OBJ_VAL wrapper in the num_fromString primitive's ERANGE error path and normalize trailing newlines in three test files.
2015-03-03 15:17:56 +00:00
Gavin Schulz
3dcffddbd5 feat: add ERANGE error handling for oversized number literals in lexer and Num.fromString
Replace TODO stubs with actual errno checks in readHexNumber, readNumber, and num_fromString to emit a "Number literal is too large." error when strtol/strtod overflow. Add three test files (literal_too_large.wren, hex_too_large.wren, from_string_too_large.wren) verifying compile-time and runtime error behavior for out-of-range numeric inputs.
2015-03-03 08:06:34 +00:00
Bob Nystrom
2eff9633ae fix: correct comment in DEALLOCATE macro to use "allocator" instead of "allocate"
The comment for the DEALLOCATE macro in wren_common.h previously read "Use the VM's allocate to free"
which was grammatically incorrect and misleading. Changed "allocate" to "allocator" to accurately
describe that the macro uses the VM's memory allocator function to free memory at the given pointer.
2015-03-02 15:32:09 +00:00
Bob Nystrom
09a7a126b0 feat: add DEALLOCATE macro and replace direct wrenReallocate calls for freeing memory
Introduce a DEALLOCATE macro that wraps wrenReallocate(vm, pointer, 0, 0) to provide a consistent, readable interface for freeing allocated memory. Replace all existing direct wrenReallocate calls used for deallocation across wren_core.c, wren_utils.c, wren_value.c, and wren_vm.c with the new macro. Also remove two stale TODO comments in wren_core.c related to testing and unimplemented map methods.
2015-03-02 15:31:46 +00:00