Commit Graph
100 Commits
Author SHA1 Message Date
Bob Nystrom a02e359a40 feat: add String struct with length tracking and refactor symbol table to use it
Replace the char* based string buffer with a proper String struct that stores both the buffer pointer and length, eliminating strlen() calls in symbol table lookups. Update all symbol table consumers in debug printing, VM method resolution, and GC marking to access the .buffer field. Refactor Value union to use anonymous struct for num/obj fields, and change Obj flags to a bool marked field. Adjust ALLOCATE_FLEX macro to accept separate main type and array type parameters. Add regression test for map subscript on empty map returning null.
2015-02-02 05:47:43 +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 50e10efa89 refactor: change ALLOCATE_FLEX macro to accept element type and count instead of raw byte size
The macro now takes a main type, array element type, and element count, computing the total allocation as `sizeof(mainType) + sizeof(arrayType) * count`. This improves type safety and clarity at all call sites, which are updated to pass the element type (Upvalue*, Value, char) instead of manually computing byte sizes.
2015-02-01 23:12:37 +00:00
Bob Nystrom e6949ffd1b fix: cast length to int in wrenSymbolTableAdd to suppress implicit conversion warning 2015-01-31 18:54:27 +00:00
Bob Nystrom 3533a4b0bd fix: update symbol table to store String struct with length instead of raw char* 2015-01-31 18:49:41 +00:00
Bob Nystrom cdfad0a7eb fix: remove redundant OBJ_VAL wrapper in validateKey error string assignment 2015-01-30 04:44:46 +00:00
Bob Nystrom 6609bf2412 feat: add clang/OS X shared library support with dylib extension in Makefile
Introduce conditional detection of Darwin target to set appropriate shared library flags and extension (.dylib instead of .so). Refactor static and shared library build targets into combined `libwren` and `libwrend` phony targets that produce both .a and .dylib/.so files, and update .gitignore to exclude the new .dylib artifacts.
2015-01-29 03:50:53 +00:00
Bob Nystrom 6050ed75e1 refactor: replace bitfield ObjFlags with bool marked field in Obj struct
Remove the FLAG_MARKED enum and ObjFlags bitfield, replacing them with a dedicated bool `marked` member in the Obj struct. Update all references in wren_value.c and wren_vm.c to use direct boolean assignment and checks instead of bitwise flag operations. This simplifies the GC marking logic and eliminates the need for manual bit manipulation.
2015-01-29 03:19:19 +00:00
Bob Nystrom 7d333d2b82 fix: guard against null entry array in wrenMapFind for empty maps
Add early return of UINT32_MAX when map capacity is zero in wrenMapFind,
preventing a crash from modulo operation on zero during hash index calculation.
Includes regression test verifying subscript access on empty map returns null.
2015-01-29 03:19:04 +00:00
Bob Nystrom 494b1a360b refactor: replace bitfield flags with explicit bool marked field in Obj struct
Remove the FLAG_MARKED bitfield enum and replace the packed unsigned int flags field with a dedicated bool marked member in the Obj base struct. Update all references in wren_value.c and wren_vm.c to use direct boolean assignment and checks instead of bitwise operations, simplifying the garbage collection marking logic and eliminating the TODO about storing the flag off to the side.
2015-01-27 15:06:18 +00:00
Bob Nystrom ad6d777fe0 fix: fix ambiguous sequence point in dup macro by extracting peek to local variable 2015-01-27 05:23:54 +00:00
Bob Nystrom 55851d35ba feat: replace string-specific eqeq/bangeq with generic wrenValuesEqual for range equality support
Remove the dedicated string equality operators (string_eqeq, string_bangeq) and their NATIVE registrations, switching object_eqeq and object_bangeq to use the generic wrenValuesEqual instead of wrenValuesSame. Also fix wrenValuesEqual to use memcmp instead of strncmp for string comparison. Add a new test file test/range/equality.wren verifying inclusive and exclusive range equality and inequality.
2015-01-26 15:01:15 +00:00
Bob Nystrom bee26d2ab2 refactor: remove dedicated CODE_LIST bytecode in favor of new List instantiation with .add() calls
Eliminate the LIST opcode and its interpreter case, debug printing, and enum entry. Instead compile list literals by loading the List class, calling its constructor, then emitting DUP, element expression, CALL_1 for add(), and POP for each element. This removes interpreter loop code and lifts the previous 255-element limit on list literals.
2015-01-26 06:49:30 +00:00
Bob Nystrom a0fc04a2a9 docs: expand map documentation with hash code explanation and key constraints 2015-01-26 05:39:22 +00:00
Bob Nystrom f1d2f2f9c1 fix: add explicit readNumber call for numeric literal tokens in nextToken 2015-01-26 01:51:50 +00:00
Bob Nystrom 7fd1751499 feat: add hex literal parsing with readHexDigit and readHexNumber in wren_compiler.c
Implement hexadecimal number literal support in the Wren compiler by adding a `number` field to the Parser struct, a `readHexDigit` helper that returns -1 for invalid hex chars, and a `readHexNumber` function that skips the 'x' prefix, accumulates hex digits, converts via strtol, and emits a TOKEN_NUMBER. Update `readNumber` to remove the TODO placeholder for hex support. Include test cases for valid hex literals (0xFF, 0x09, negative -0xFF) and an invalid hex literal (2xFF) that triggers a lex error.
2015-01-26 01:49:05 +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 1d195f13ea docs: add core library overview, map class docs, and link value types to core classes 2015-01-25 19:08:13 +00:00
Bob Nystrom f093d0a42a feat: implement Map.keys, Map.values iterators and proper toString with key-value formatting
Add MapKeySequence and MapValueSequence classes in core.wren to expose iterable key and value views on Map instances. Implement native iterate_, keyIteratorValue_, and valueIteratorValue_ primitives in wren_core.c to support these sequences. Replace the stub Map.toString with a full implementation that iterates keys and formats each entry as "key: value", handling empty maps and nested maps correctly. Include comprehensive test suites for key iteration, value iteration, iterator type validation, and toString output across multiple orderings.
2015-01-25 18:27:38 +00:00
Bob Nystrom 56123c71e3 feat: implement map clear method to remove all entries
Add DEF_NATIVE(map_clear) that frees the underlying entries array and resets
capacity and count to zero, returning null. Register the "clear" method on
the Map class in wrenInitializeCore and include a test verifying the map is
emptied and the return value is null.
2015-01-25 16:39:44 +00:00
Bob Nystrom 2ec0a8aef9 feat: implement map literal syntax with curly braces and DUP bytecode
Add support for map literals using `{}` syntax in the compiler, replacing the previous `new Map` constructor pattern. This introduces a new `map()` grammar function that loads the Map class, instantiates it, and compiles key-value pairs using subscript setter calls. A new `CODE_DUP` bytecode is added to duplicate the map reference on the stack for each element insertion. The change includes updated test files to use literal syntax and new error tests for edge cases like EOF after colon, comma, key, or value.
2015-01-25 07:21:50 +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 3f0aceeffa chore: rename test files for user and auth modules to clarify scope 2015-01-24 22:42:25 +00:00
Bob Nystrom 239c65201b feat: add join method to Sequence and refactor List toString to use it 2015-01-24 22:39:45 +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 c65b03ac32 docs: update getting-started to reference project directories for XCode and MSVC2013 2015-01-23 18:41:11 +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 488fb27b91 feat: make String iterable over code points with iterate/iteratorValue primitives
Add String as a subclass of Sequence in core.wren and implement the iterator protocol for strings in wren_core.c. The string_iterate native advances through UTF-8 code point boundaries, while string_iteratorValue extracts the full code point at a given byte index. Includes comprehensive test coverage for iteration, edge cases (empty strings, mid-sequence positions), and error handling for invalid iterator types and out-of-bounds indices. Also updates documentation for String, List, and Sequence classes with iterator protocol details and usage examples.
2015-01-23 04:58:22 +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
Bob Nystrom 735268f620 test: add non-ASCII UTF-8 test cases for contains, endsWith, equality, indexOf, and startsWith string methods 2015-01-22 23:28:54 +00:00
Bob Nystrom 23c67c2e8b feat: remove UTF-8 encoding logic from addStringChar and accept raw bytes in string literals 2015-01-22 23:18:30 +00:00
Bob Nystrom 8d281434e4 docs: add type-checking guards to foreign argument getters and remove wrenReturnNull
Add runtime type validation to wrenGetArgumentBool, wrenGetArgumentDouble, and
wrenGetArgumentString in src/wren_vm.c, replacing TODO comments with actual
checks that return safe defaults (false, 0.0, NULL) on type mismatch.

Remove the unused wrenReturnNull function entirely from the VM implementation.

Update include/wren.h documentation for argument accessor functions to clarify
indexing semantics (including receiver at index 0) and document the new
type-checking behavior.
2015-01-22 15:05:55 +00:00
Bob Nystrom 6bd9da3a77 chore: reorder source file references in Xcode project.pbxproj children list
The diff reorders the `children` array of the `src` group in the Xcode project file,
moving `.c` files after their corresponding `.h` headers to match a consistent
header-before-source convention.
2015-01-22 15:05:32 +00:00
Bob Nystrom eed32946be fix: correct operator precedence of % from PREC_TERM to PREC_FACTOR
The modulo operator was incorrectly assigned PREC_TERM precedence, causing it to
bind less tightly than multiplication and division. This change promotes it to
PREC_FACTOR, matching the standard mathematical precedence where `%` has the
same binding strength as `*` and `/`.

A test case `IO.print(13 + 1 % 7)` is added to verify the fix, expecting `14`
(equivalent to `13 + (1 % 7)`) rather than the incorrect `(13 + 1) % 7 = 0`.
2015-01-21 21:50:09 +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
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 895f52c77b feat: add link to AUTHORS file in footer to credit contributors 2015-01-21 01:47:17 +00:00
Bob Nystrom f378af9c75 docs: add mailing list links and proposal reference to contributing and getting-started pages
- Insert "Getting acquainted" section in contributing guide with mailing list invitation
- Add proposal link for significant changes discussion before coding
- Promote mailing list as primary contact method in getting-started page
- Add link references for list, twitter, issue, and repo in getting-started
2015-01-21 01:46:52 +00:00
Bob Nystrom d11f24eb50 chore: move XCode project file from root to project/xcode/ directory
- Relocate wren.xcodeproj into project/xcode/ subdirectory
- Remove build_xcode/ from .gitignore as it is no longer at root level
- Update all internal PBXBuildFile references to use new file paths
2015-01-21 01:14:30 +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
Bob Nystrom 49bec173a6 feat: add wrenGetArgumentBool function to read boolean foreign call arguments
Add a new public API function `wrenGetArgumentBool` to the Wren VM that
allows foreign method implementations to retrieve boolean arguments from
the foreign call slot. The implementation includes assertions for null
slot, non-negative index, and bounds checking against the number of
arguments, and uses the existing AS_BOOL macro to extract the boolean
value from the slot.
2015-01-20 21:58:36 +00:00
Bob Nystrom 40e0ec5fa1 fix: suppress -fPIC on mingw32 and cygwin to avoid -Werror warnings 2015-01-20 21:42:46 +00:00
Bob Nystrom a74797f333 docs: split monolithic core-library.markdown into per-class docs under doc/site/core/ 2015-01-18 23:36:36 +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
Bob Nystrom 44a160e1f8 fix: add prep target to .PHONY list in Makefile
The prep target was missing from the .PHONY declaration, causing Make to skip
its execution when a file named 'prep' existed in the working directory. This
change ensures prep is always treated as a phony target and executed regardless
of file system state.
2015-01-18 18:03:13 +00:00
Bob Nystrom 20dbaa22e7 feat: add wrenReturnBool function for returning boolean values from foreign calls
Add a new public API function `wrenReturnBool` to the Wren C API, allowing
foreign method implementations to return boolean values. The function
includes the necessary `stdbool.h` include in the public header and
implements the return logic by storing a BOOL_VAL in the foreign call slot,
following the same pattern as existing return functions like
`wrenReturnNull` and `wrenReturnString`.
2015-01-17 16:45:45 +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
Bob Nystrom 222cddc751 fix: convert benchmark chart bars from scores to execution times
The benchmark HTML output previously displayed abstract "score" values and scaled bars by the highest score. This change replaces scores with the actual minimum execution time in seconds (e.g., "0.15s") and scales bar widths proportionally to the highest time, making the charts directly interpretable as performance comparisons. The `run_bench` script now computes `time` from `min(result["times"])` instead of `get_score()`, and the static performance documentation is updated to reflect the new time-based values.
2015-01-17 01:51:10 +00:00
Bob Nystrom 0c0f900cad fix: update benchmark numbers and bar widths in performance documentation
Update the Method Call and DeltaBlue benchmark tables with new Wren performance results (6748 and 7564 respectively), adjusting all other language scores and corresponding chart-bar width percentages to reflect the latest measurements.
2015-01-16 15:52:51 +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
Bob Nystrom 9a23d87900 docs: move all and reduce methods from List to new Sequence base class 2015-01-16 15:04:01 +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 4676e87ce9 chore: add Gavin Schulz to AUTHORS and rename forall to all in docs
- Add Gavin Schulz to the AUTHORS file
- Rename the `forall(predicate)` method to `all(predicate)` in the core library documentation
2015-01-16 05:17:45 +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 00dca683b7 docs: update README and site index to mention Wren compiles cleanly as C++98 or later 2015-01-16 05:15:21 +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 cf3bc7f07a fix: correct method name from forall to all in core library docs and add Gavin Schulz to AUTHORS 2015-01-16 04:38:00 +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 befee63a89 chore: rename test files to follow snake_case naming convention 2015-01-15 14:54:16 +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
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
Bob Nystrom 533644c1f6 refactor: rename global planner variable to ThePlanner in DeltaBlue benchmark
Replace the forward-declared `planner` variable with a capitalized `ThePlanner` name across all constraint methods and test functions, removing the TODO comment about forward declarations.
2015-01-15 07:02:12 +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
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
Bob Nystrom d031d0a77d fix: correct spelling of "brethren" and "invalid" in documentation files 2015-01-13 14:42:35 +00:00
Bob Nystrom 61abae46ec fix: correct spelling errors in documentation files
Fix three typos across documentation files: 'unvalid' to 'invalid' in
doc/error-handling.txt, and 'bretheren' to 'brethren' in both
doc/site/expressions.markdown and doc/site/getting-started.markdown
2015-01-13 00:58:05 +00:00
Bob Nystrom 289dd99c26 feat: add -g flag to DEBUG_CFLAGS in Makefile for debugging symbols
Add the -g compiler flag to DEBUG_CFLAGS in the Makefile to enable
generation of debugging symbols during debug builds, allowing better
debugging with tools like GDB.
2015-01-12 15:32:21 +00:00
Bob Nystrom d6b70a0af3 feat: add type validation for IO.read prompt and stdin support in test runner
Add string type check for IO.read() prompt argument with Fiber.abort on non-string input. Implement stdin piping in test runner via // stdin: comments, allowing tests to provide input lines. Update stack trace filtering to omit built-in library frames with empty source paths. Add io/read.wren and io/read_arg_not_string.wren test cases.
2015-01-12 05:47:29 +00:00
Bob Nystrom e12b36002e feat: add IO.read method with prompt and stdin input buffer
Implement a new static `IO.read(prompt)` method in the IO class that writes a prompt string to stdout and reads a line from stdin into a fixed 1024-byte buffer. The C implementation adds a `MAX_READ_LEN` constant, an `ioRead` function using `fgets`, and registers the method via `wrenDefineStaticMethod`. The builtin source string is updated to include the new Wren method definition.
2015-01-12 04:05:52 +00:00
Bob Nystrom a2c7499e0a fix: add tab character to whitespace skipping in nextToken parser
The nextToken function in wren_compiler.c previously only skipped spaces and carriage returns when advancing past whitespace, causing tab characters to be treated as non-whitespace tokens. This change adds '\t' to the whitespace check in both the initial case statement and the peekChar loop, ensuring tabs are properly skipped like other whitespace characters. A new test file test/whitespace.wren is added to verify correct handling of tabs in various indentation patterns and inline code positions.
2015-01-12 04:01:30 +00:00
Bob Nystrom 363486df33 feat: add test verifying carriage returns are treated as whitespace in parser
Add a new test file `test/ignore_carriage_returns.wren` that sprinkles carriage
return characters (`\r`) in various positions within source code to confirm the
parser correctly ignores them as whitespace. The test includes a deliberate
compile error to validate that line numbering remains accurate despite the
presence of carriage returns.
2015-01-12 03:58:30 +00:00
Bob Nystrom b8ad075a4f feat: add contains method to List and Set classes with example and documentation
Add a `contains(element)` method to the built-in `List` class in `builtin/core.wren` and its embedded source in `src/wren_core.c`, enabling linear search for an element. Introduce a new `Set` class example in `example/set.wren` implementing set operations (union, intersection, difference) using the new `contains` method. Update `doc/site/classes.markdown` with a warning against inheriting from built-in types due to internal bit representation constraints.
2015-01-12 03:53:17 +00:00
Bob Nystrom cd6d6c1f91 style: reformat while-loop body in nextToken to use braces 2015-01-12 03:52:59 +00:00
Bob Nystrom 34d3a8edb7 fix: open source files in binary mode and skip CR in whitespace
Change `fopen` mode from `"r"` to `"rb"` in `readFile()` to prevent CRLF-to-LF conversion on Windows, and add `'\r'` as a skipped whitespace character in `nextToken()` to handle carriage returns embedded in source files. This fixes parsing errors when Wren source files use Windows-style line endings.
2015-01-12 03:52:08 +00:00
Bob Nystrom acf02f1ebc docs: document restriction on inheriting from built-in types in classes guide
Add a note to the classes documentation page explaining that inheriting from built-in types (Bool, Num, String, Range, List) is not supported due to internal bit representation conflicts that cause errors when invoking inherited methods on derived types.
2015-01-12 03:50:39 +00:00
Bob Nystrom 887afc03be feat: add Set class example and List.contains method to core library
Add a complete Set class implementation in example/set.wren with union, intersection, and set minus operations. Implement List.contains method in builtin/core.wren and its C source to support element existence checks via iteration.
2015-01-12 03:50:07 +00:00
Bob Nystrom 4e461f0b0c chore: clarify comment for super outside method error handling path 2015-01-12 03:44:35 +00:00
Bob Nystrom 497e05c575 fix: guard against segfault when super is called at top level with no args
When `super` is invoked at the top level without an explicit method name, the compiler previously dereferenced a NULL `enclosingClass` pointer while trying to copy the enclosing method's signature. This change adds a NULL check for `enclosingClass` in the `super_` function, setting an empty method name and zero length when the pointer is NULL, preventing the segmentation fault. Also extends the test file `super_at_top_level.wren` with additional cases for bare `super`, `super.foo("bar")`, and `super("foo")` to verify error handling for these top-level super invocations.
2015-01-12 03:42:26 +00:00
Bob Nystrom 6928ba9935 chore: rename test files to snake_case and update string class docs
Rename indexOf.wren and startsWith.wren test files to index_of.wren and
starts_with.wren respectively, fix missing trailing newlines, update
string class documentation to clarify UTF-8 storage and move the
note about incorrect UTF-8 handling in the index operator, and
remove unnecessary parentheses in string_indexOf native return.
2015-01-12 03:13:15 +00:00
Bob Nystrom 7fd1e5eeaa fix: switch Google Fonts URL to protocol-relative to fix Firefox Mixed Content errors
The font stylesheet link in doc/site/template.html used an explicit http:// scheme,
causing Firefox to block the request on HTTPS pages due to Mixed Content warnings.
Changed to a protocol-relative URL (//fonts.googleapis.com/...) so the browser
automatically uses the same protocol as the parent page.
2015-01-09 17:34:35 +00:00
Bob Nystrom f010c8d79f fix: correct buffer size in string subscript operator to prevent off-by-one allocation
The `string_subscript` native was allocating a 2-byte buffer for single-character
results, causing a one-byte over-allocation. Changed to allocate exactly 1 byte
for the character plus the null terminator handled by `wrenNewUninitializedString`.

Also fixed `wrenNewUninitializedString` to properly cast the `length` parameter
to `int` when assigning to `ObjString->length`, resolving a potential
truncation warning on 64-bit systems.

Added a test case to verify that subscript access returns a properly formed
string that compares equal to the expected character.
2015-01-09 15:12:25 +00:00
Bob Nystrom 0572df823b fix: remove negative number literal parsing in lexer and update tests for unary minus precedence
The lexer previously treated a leading minus sign followed by a digit as a single negative number token, which caused incorrect parsing of expressions like `1-1` and broke method calls on negative numbers. This change removes that special case, making the minus sign always a separate token, and updates all test expectations to use explicit parentheses for negative number method calls.
2015-01-09 15:00:12 +00:00
Bob Nystrom 49e8b17056 refactor: move methodNotFound into runtimeError and allocate managed ObjString for GC safety 2015-01-09 06:29:37 +00:00
Bob Nystrom 5377a94a58 feat: add argument count to method-not-found error messages
Introduce a `methodNotFound` helper in `wren_vm.c` that parses the symbol name to determine the number of arguments and generates a detailed error message including the argument count. Update all runtime error calls and test expectations across fiber, inheritance, method, and super test files to reflect the new format, and add new test cases for method-not-found with 1, 2, and 11 arguments.
2015-01-09 05:49:20 +00:00
Bob Nystrom 0d318e9545 feat: add stack vs register-based VM design rationale to FAQ
Add a new FAQ entry explaining why Wren uses a stack-based bytecode VM
instead of a register-based one. The entry covers the trade-offs between
the two approaches, references Lua's switch to register-based VM, and
explains that Wren's operator-overloading design makes register-based
optimizations less beneficial.
2015-01-09 05:06:10 +00:00