Commit Graph

379 Commits

Author SHA1 Message Date
Marco Lizza
915f403bc7 chore: restore standard header include order and move CRT secure warning to MSVC project
The diff reorders includes across multiple source files to place standard library headers before project headers, removes the `_CRT_SECURE_NO_WARNINGS` define from `wren_common.h`, and adds it as a preprocessor definition in both Debug and Release configurations of the MSVC 2013 project file.
2015-01-23 09:05:10 +00:00
Marco Lizza
88d7c318ef feat: add Math library source and integrate into MSVC project and VM initialization
Add wren_math.c and wren_math.h to the MSVC 2013 project files, including both the .vcxproj and .vcxproj.filters. Also fix the indentation of the WREN_COMPUTED_GOTO comment in wren_common.h and correct a conditional guard bug in wren_vm.c where wrenLoadMathLibrary was guarded by WREN_USE_LIB_IO instead of WREN_USE_LIB_MATH.
2015-01-22 16:46:09 +00:00
Marco Lizza
a34eb52d6c feat: add Math library with abs, ceil, floor, int, frac, trig, and xorshift RNG
Implement the Math standard library module for Wren, including absolute value, ceiling, floor, integer/fractional decomposition, trigonometric functions (sin, cos, tan), degree/radian conversion, and a seeded xorshift random number generator. Add WREN_USE_LIB_MATH compile-time flag to wren_common.h and provide comprehensive test suite under test/math/.
2015-01-22 15:42:40 +00:00
Marco Lizza
9a50b5f318 feat: add Math library with abs, ceil, floor, trig, and xorshift RNG
Implement a new optional Math module for the Wren standard library, gated behind the WREN_USE_LIB_MATH flag (default on). The module provides double-precision math functions (abs, ceil, floor, int, frac, sin, cos, tan, deg, rad) and a xorshift-based pseudo-random number generator with srand/rand methods. Includes comprehensive test files for each function and an all_tests runner.
2015-01-22 15:41:19 +00:00
Marco Lizza
c2f1a962d6 fix: replace WREN_PIN/WREN_UNPIN macros with wrenPushRoot/wrenPopRoot and fix modulo operator precedence 2015-01-22 09:13:16 +00:00
Evan Shaw
ffcdd8ae9e fix: correct operator precedence for % token from PREC_TERM to PREC_FACTOR
The modulo operator was incorrectly assigned PREC_TERM precedence, making it
evaluate at the same level as + and -. This caused expressions like "13 + 1 % 7"
to parse as "(13 + 1) % 7" instead of the correct "13 + (1 % 7)".

Changed the grammar rule for TOKEN_PERCENT to use PREC_FACTOR, matching the
precedence of * and / operators. Added a precedence test case in mod.wren to
verify the fix.
2015-01-21 20:49:43 +00:00
Bob Nystrom
fccdf60ce8 refactor: rename "pinned" terminology to "tempRoots" across VM and common header
Rename all instances of "pinned" objects to "temporary roots" in wren_vm.c, wren_vm.h, and wren_common.h to better describe their stack-based lifecycle. Update the WREN_MAX_PINNED constant to WREN_MAX_TEMP_ROOTS, rename the vm->pinned array to vm->tempRoots, and rename vm->numPinned to vm->numTempRoots. Adjust all related comments and assertions to reflect the new terminology, including the GC stress test comment in wren_common.h.
2015-01-21 16:02:18 +00:00
Bob Nystrom
6223bb2342 fix: replace broken WREN_PIN macro with proper wrenPushRoot/wrenPopRoot GC root stack 2015-01-21 15:56:06 +00:00
Marco Lizza
3cdc3dde84 fix: work around MSVC 2013 optimizer bug causing memory access violation in wrenPinObj and wrenUnpinObj
Disable optimization for wrenPinObj and wrenUnpinObj functions under Microsoft Visual Studio 2013 to prevent the compiler from incorrectly inlining them, which triggers a memory access violation. The pragma directives bracket only these two functions to minimize the impact on the rest of the compilation unit.
2015-01-21 10:01:09 +00:00
Marco Lizza
ff9625a80d chore: reorder include directives to place wren_common.h first across all source files
Enforce a consistent include ordering convention across the codebase: wren_common.h (as configuration header) first, followed by the module's own header, then other wren_*.h headers in lexicographic order, and finally standard library includes. Also add missing wren_common.h include to main.c and wren_io.c, and add _CRT_SECURE_NO_WARNINGS define for MSVC in wren_common.h.
2015-01-21 09:30:37 +00:00
Marco Lizza
80620957b3 fix: disable computed goto for MSVC due to lack of compiler support
The WREN_COMPUTED_GOTO macro is now conditionally set to 0 when
compiling with _MSC_VER, as Microsoft's compiler does not support
the computed-goto extension used by the VM dispatch loop.
2015-01-21 09:27:27 +00:00
Marco Lizza
a70a23e03d fix: avoid returning void function result in for/while/class/var statements 2015-01-21 09:23:46 +00:00
Marco Lizza
19862a2959 fix: change readHexDigit return type from char to int to prevent sign extension bugs 2015-01-21 09:22:56 +00:00
Marco Lizza
25b6a37b2c fix: add _inline fallback for MSVC plain-C compilation in wren_common.h 2015-01-21 09:22:18 +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
a4baa42d6f feat: add user-defined subscript operators with bracket parameter lists
Refactor parameter list parsing to support bracket-delimited parameters for
subscript operators. Extract finishParameterList from parameterList to handle
the common closing logic, and add TOKEN_RIGHT_BRACKET case for error messages.
Add comprehensive test suite for subscript getters and setters with 1-3
parameters in test/method/subscript_operators.wren.
2015-01-21 02:25:54 +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
f0f03ec763 refactor: replace CalculatedRange struct with output parameters in calculateRange
The CalculatedRange struct is removed from the header and calculateRange now returns the start index directly while using pointer parameters for length and step, simplifying the API and reducing struct overhead.
2015-01-20 23:33:21 +00:00
Bob Nystrom
f5017a3963 feat: add string range subscript support with CalculatedRange helper
Extract range validation logic into a reusable `calculateRange` function that handles inclusive/exclusive bounds, negative indices, and direction stepping. Add `CalculatedRange` struct to `wren_core.h` and implement string subscript tests covering forward, backward, negative, and half-negative ranges along with comprehensive error cases for out-of-bounds and non-integer range endpoints.
2015-01-20 23:01:14 +00:00
Bob Nystrom
9f8cc364b8 perf: tighten field and jump offset types from int to uint8_t/uint16_t in interpreter
Replace signed `int` with unsigned `uint8_t` for field indices in LOAD_FIELD_THIS, STORE_FIELD_THIS, LOAD_FIELD, and STORE_FIELD opcodes, and with `uint16_t` for jump offsets in JUMP, LOOP, and JUMP_IF opcodes. This eliminates sign-extension overhead and enables better code generation, yielding 1-7% performance gains across binary_trees, delta_blue, fib, for, and method_call benchmarks.
2015-01-20 22:41:09 +00:00
Bob Nystrom
f99f61376d refactor: remove unused return values from consume() and consumeLine() in wren_compiler.c
The consume() function previously returned a pointer to the consumed token,
and consumeLine() returned a boolean indicating success. Both return values
were never used by any callers. This change converts both functions to void,
eliminating dead code and simplifying the interface.
2015-01-20 22:40:34 +00:00
Bob Nystrom
b173b4e385 feat: add wrenGetArgumentBool and wrenReturnBool, reorder foreign API declarations in header and implementation 2015-01-20 22:00:03 +00:00
Harry Lawrence
672fdb51f1 feat: add wrenGetArgumentBool function to retrieve boolean foreign call arguments
Implement the wrenGetArgumentBool function in wren_vm.c, which retrieves a boolean value from the foreign call argument slot at the given index. The function includes assertions for valid call context, non-negative index, and argument bounds. Also add the corresponding declaration to the public wren.h header to expose the new API for foreign method implementations.
2015-01-19 14:40:37 +00:00
Bob Nystrom
25dfc4f5fa feat: add wrenReturnBool API for boolean return from foreign calls
Add a new public API function `wrenReturnBool` to the Wren C API, enabling
foreign method implementations to return boolean values. The implementation
stores the boolean as a Wren BOOL_VAL in the foreign call slot and clears
the slot pointer, following the same pattern as existing `wrenReturnString`.

Also add the missing `prep` target to the .PHONY list in the Makefile and
include `<stdbool.h>` in the public header to support the `bool` type used
in the new function signature.
2015-01-18 18:20:29 +00:00
Bob Nystrom
850d6d1b5d fix: raise precedence of is above equality operators in parser
The `is` operator was placed at `PREC_IS` which had lower precedence than `PREC_EQUALITY`, causing expressions like `true == 10 is Num` to parse incorrectly. Moved `PREC_IS` above `PREC_EQUALITY` in the precedence enum to give `is` higher binding power than `==` and `!=`. Added precedence tests in new `test/precedence.wren` file and removed TODO comments about precedence from `test/is/is.wren`.
2015-01-18 18:20:13 +00:00
Harry Lawrence
7fed1ef294 feat: add wrenReturnBool function to return boolean values from foreign calls
Add a new public API function `wrenReturnBool` that allows foreign function
implementations to return boolean values to Wren. The function validates
that it is called within a foreign call context using an assertion, then
writes the boolean value into the foreign call slot and clears the slot
pointer. This completes the set of return value helpers alongside the
existing `wrenReturnNull` and `wrenReturnString` functions.
2015-01-17 11:48:27 +00:00
Bob Nystrom
48c3f540df fix: replace getline with fgets and remove _GNU_SOURCE for cross-platform compatibility
Remove the Linux-specific `_GNU_SOURCE` macro and `getline()` usage in the REPL loop, replacing them with a fixed-size `fgets()` buffer of 1024 bytes. Also switch `snprintf` to `sprintf` in `wren_vm.c` for the field limit error message, eliminating the need for `_GNU_SOURCE` entirely.
2015-01-17 07:32:20 +00:00
Gavin Schulz
2799fa6b58 feat: add range subscripting support for strings with CalculatedRange helper
Extract range validation logic from list_subscript into a reusable calculateRange function that handles inclusive/exclusive bounds, negative indices, and direction stepping. Add CalculatedRange struct to wren_core.h and implement string subscripting via the new helper, including comprehensive test coverage for forward, backward, negative, and half-negative ranges with proper error messages for out-of-bounds and non-integer values.
2015-01-17 07:20:56 +00:00
Bob Nystrom
151978710d perf: inline callFunction and optimize method dispatch in interpreter loop 2015-01-16 15:45:42 +00:00
Bob Nystrom
f76cde35a5 fix: replace designated initializer with field assignments in main.c
Replace the C99 designated initializer syntax for `WrenConfiguration config` with explicit field assignments to avoid potential compiler compatibility issues. The change preserves the same configuration values: `reallocateFn` set to NULL, `heapGrowthPercent` and `minHeapSize` set to 0, and `initialHeapSize` set to 100 MB.
2015-01-16 15:10:33 +00:00
Luchs
fb14301967 feat: implement single-argument reduce with manual iteration and empty-sequence abort
Replace the previous slice-based single-argument reduce implementation with an explicit iterator loop that seeds from the first element. This avoids the out-of-bounds range error on single-element lists and adds a Fiber.abort for empty sequences. Update the test to verify correct behavior for single-element and empty sequences.
2015-01-16 08:24:18 +00:00
Luchs
afa0a0a8e9 feat: add reduce method to Sequence with two overloads and tests
Implement `reduce` on the `Sequence` class in core.wren with two overloads: one taking an initial accumulator and a function, and another using the first element as the initial accumulator. Add three test files covering normal reduction, single-element edge case, and wrong arity error.
2015-01-15 15:29:49 +00:00
Bob Nystrom
d3ea153a31 feat: implement ! operator for all core types with proper truthiness semantics
Add native `!` methods to Null, Object, Num, String, and List classes so that `!` works reliably on any value. Null returns `true`, all other types return `false` since they are considered truthy. Update documentation to describe the operator as returning the logical complement and add comprehensive tests for each type. Also fix the `all` method test to use a truthy string instead of expecting a runtime error.
2015-01-16 05:50:01 +00:00
Bob Nystrom
e71e85f42c feat: add C++98 compilation support and refactor Value type to uint64_t for nan tagging
Add C++98 compatibility by introducing explicit casts, replacing C99-specific constructs with macros, and updating the build system to produce C++ object files. Refactor the Value union to a plain uint64_t when WREN_NAN_TAGGING is enabled, adding helper functions for num-to-value and value-to-num conversions. Update the compiler to split emit into emit and emitShort for cleaner bytecode emission, and rename emitByte/emitShort to emitByteArg/emitShortArg.
2015-01-16 05:17:08 +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
7f92bc7a49 fix: replace switch-based interpreter loop with goto dispatch for computed gotos disabled path 2015-01-16 00:22:55 +00:00
Bob Nystrom
e8121af372 refactor: replace static allocate function with ALLOCATE, ALLOCATE_FLEX, and ALLOCATE_ARRAY macros in wren_value.c
Remove the single-purpose `allocate` helper and introduce three type-safe allocation macros (`ALLOCATE`, `ALLOCATE_FLEX`, `ALLOCATE_ARRAY`) that directly invoke `wrenReallocate`. Update all call sites in `wren_value.c` — including `wrenNewSingleClass`, `wrenNewClosure`, `wrenNewFiber`, and `wrenNewFunction` — to use the appropriate macro, eliminating the need for manual sizeof calculations and improving compile-time type checking when compiling as C++.
2015-01-16 00:21:14 +00:00
Bob Nystrom
45414b192c fix: add explicit casts for C++ compatibility in wren_vm.c and wren_vm.h 2015-01-16 00:02:38 +00:00
Bob Nystrom
2cbce0b2e8 fix: add explicit C-style casts for implicit conversions in wren_debug and wren_utils
Add explicit casts to `(Code)` in `debugPrintInstruction` for bytecode indexing, to `(char*)` in `wrenSymbolTableAdd` for heap string allocation, and to `(type*)` in the `DEFINE_BUFFER` macro's reallocation call to ensure C++ compilation compatibility without implicit conversion errors.
2015-01-16 00:00:51 +00:00
Bob Nystrom
ba81988800 fix: cast malloc result and adjust compiler emit functions for C++ compatibility
- Cast malloc return to char* in src/main.c to avoid C++ implicit void* conversion
- Rename emit to emitByteArg and emitShort to emitShortArg in src/wren_compiler.c to avoid conflict with new emit and emitShort helpers
- Add new emit function taking uint8_t byte and emitShort helper for 16-bit big-endian emission
- Remove stray semicolon in script/test.py
2015-01-15 23:59:14 +00:00
Bob Nystrom
4acdc503e4 feat: add Sequence.all method and forall documentation with tests
Implement `all(f)` method on Sequence class that returns true if all elements pass the predicate function. Add corresponding documentation entry for `forall(predicate)` in core-library.markdown. Include three test files covering basic functionality, non-boolean return handling, and non-function argument error cases.
2015-01-15 14:52:43 +00:00
Gavin Schulz
adee8ac482 refactor: rename Sequence method forall to all across core lib, C source, and test files 2015-01-15 07:19:31 +00:00
Bob Nystrom
ee239f2bb6 feat: add undefined sentinel value and implicit global declaration for forward references
Add a new singleton value `VAL_UNDEFINED` to represent globals that have been implicitly declared via forward reference but not yet explicitly defined. Introduce `wrenDeclareGlobal()` to create such entries in the global table, and modify `wrenDefineGlobal()` to check for and resolve undefined slots. Update the compiler's `findUpvalue()` to stop closure capture at method boundaries, preventing methods from closing over local variables. Refactor `wrenSymbolTableAdd()` to always add symbols without duplicate checking, moving that logic to callers. Adjust error messages in the compiler to handle EOF tokens and improve newline formatting. Fix the delta_blue benchmark by renaming the global `planner` variable to `ThePlanner` to avoid shadowing the forward-declared function.
2015-01-15 07:08:34 +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
Gavin Schulz
cb1703409c test: add forall test for empty list and non-bool/non-function args
Add test case verifying that `forall` returns true for an empty list regardless of predicate, and add two new test files covering runtime errors when `forall` receives a non-boolean-returning function or a non-function argument. Also refactor the `forall` implementation to use logical negation (`!`) instead of explicit `!= true` comparison.
2015-01-15 06:42:15 +00:00
Bob Nystrom
82ef82cdb9 fix: prevent redundant keyword checks after first match in readName
Replace sequential `if` statements with `else if` chains in `readName` so that once a keyword matches (e.g. "break"), the remaining keyword checks are skipped, fixing issue #110 where later keywords could incorrectly override an already-matched token type.
2015-01-14 14:46:02 +00:00
Gavin Schulz
580ca8cf27 feat: add forall method to Sequence class for testing all elements pass predicate
Implement a `forall` method on the Sequence class that takes a predicate function and returns true only if every element in the sequence satisfies the predicate. The method iterates through all elements, returning false immediately upon encountering any element where the predicate does not return exactly true. Includes core library documentation and a test file verifying behavior with numeric comparisons and non-boolean predicate returns.
2015-01-14 07:47:01 +00:00
Bob Nystrom
54ef9bbc73 feat: stop closure upvalue search at method boundaries and treat capitalized names as globals
Modify `findUpvalue` in the compiler to return -1 when the enclosing function is a method, preventing closures from capturing outer local variables. Add a new `nonlocal` variable resolution path that treats capitalized identifiers as global variables rather than method receivers. Update existing test files to use capitalized global names and add new test cases for nonlocal assignment, duplicate nonlocal declarations, block scoping, and method-local variable shadowing.
2015-01-14 05:36:42 +00:00
Kyle Marek-Spartz
d2cbb7a04b fix: remove trailing semicolon from DECLARE_BUFFER macro template
The DECLARE_BUFFER macro in src/wren_utils.h had an extraneous semicolon at the end of the wren##name##BufferWrite function declaration. This caused a double-semicolon issue when the macro was expanded in source files, as the macro invocation sites already added their own semicolons. Removing the trailing semicolon from the macro template ensures consistent and correct C syntax across all buffer type declarations.
2015-01-13 02:16:06 +00:00
Kyle Marek-Spartz
c0d04de818 fix: add missing semicolons to DEFINE_BUFFER invocations and macro definition
The commit adds missing semicolons to three DEFINE_BUFFER calls in wren_utils.c and wren_value.c, and also adds a semicolon to the DECLARE_BUFFER macro definition in wren_utils.h to ensure proper syntax termination. Additionally, it removes trailing whitespace on two blank lines in wren_value.c.
2015-01-12 23:23:37 +00:00