Commit Graph

51 Commits

Author SHA1 Message Date
Bob Nystrom
e0984a5012 fix: require parentheses for zero-argument join() method on Sequence
The zero-argument overload of `join` on `Sequence` was previously defined as a
getter-style method without parentheses. This change makes it a regular method
that requires explicit parentheses, consistent with the one-argument `join(sep)`
variant and standard Wren method syntax. The implementation now reads
`join() { join("") }` instead of `join { join("") }`.

All call sites in tests and documentation are updated accordingly.
2015-09-16 14:15:48 +00:00
Bob Nystrom
aa72900a9e feat: replace IO class with System class and remove separate IO module
- Delete wren_io.c, wren_io.h, and io.wren source files
- Remove multi-arity print overloads and IO.read/IO.time methods
- Add System class with print, printAll, write, writeAll methods to core.wren
- Update all documentation examples and README to use System.print instead of IO.print
2015-09-15 14:46:09 +00:00
Bob Nystrom
85750ca338 feat: add StringCodePointSequence class and expose codePoints property on String
Extract codePointAt() logic into a dedicated StringCodePointSequence class that wraps a string and implements the Sequence interface, enabling iteration over code points. Add a `codePoints` getter to String that returns a new instance of this sequence. Refactor the underlying C implementation of `codePointAt_` to decode UTF-8 into actual code point integers (returning raw bytes for invalid sequences) and rename the primitive to use trailing underscore convention. Update all related tests to reflect the new behavior where mid-sequence byte indices return the raw byte string instead of an empty string, and add new test files for the code point sequence iteration.
2015-09-11 14:56:01 +00:00
Bob Nystrom
731e1f4b1d feat: replace public byteAt with private byteAt_ and add O(1) bytes.count
Remove the public `byteAt(_)` method from String and its ByteSequence wrapper, renaming it to the private `byteAt_(_)` to eliminate redundancy with `.bytes[_]`. Add a native `byteCount_` primitive on String and expose it as `count` on StringByteSequence, enabling O(1) byte length queries. Update all test files to use the new `.bytes` subscript API and add a dedicated `count.wren` test for the new functionality.
2015-09-11 06:52:18 +00:00
Bob Nystrom
7d9e45e906 feat: replace 'this' keyword with 'construct' for constructor definitions across core lib, compiler, docs, and tests
Add TOKEN_CONSTRUCT as a new reserved word in the Wren compiler lexer and parser, and update the grammar rule table so that 'construct' triggers a constructor signature instead of 'this'. Modify all built-in class definitions in core.wren, wren_core.c, benchmark files, and test fixtures to use 'construct new(...)' and 'construct named(...)' syntax. Update documentation in classes.markdown and syntax.markdown to reflect the new keyword, and remove the deprecated test files for 'new' and infix class expressions.
2015-07-21 14:24:53 +00:00
Bob Nystrom
e19ff59cce feat: replace new keyword with this constructor syntax and ClassName.new() calls across core library and docs
Replace all uses of the `new` reserved word with explicit `this new()` constructor definitions and `ClassName.new()` instantiation calls in builtin/core.wren. Update all documentation files (classes.markdown, fiber.markdown, fn.markdown, sequence.markdown, error-handling.markdown, expressions.markdown, fibers.markdown, functions.markdown) to reflect the new constructor syntax, removing `new` keyword examples and replacing them with `ClassName.new()` patterns and `this new()` definitions.
2015-07-10 16:18:22 +00:00
Bob Nystrom
1dc1c4e2bf feat: add isEmpty method to Sequence class with efficient early-termination check 2015-06-30 13:52:29 +00:00
Bob Nystrom
701cffbe69 revert: remove safeToString_ and recursive toString handling due to memory leak on runtime errors
The safeToString_ mechanism introduced in 40897f33 used per-fiber maps and lists to detect recursive toString calls, but leaked memory when runtime errors occurred before cleanup. This reverts to direct toString implementations for List and Map, removing the recursive detection logic and updating tests to mark self-referencing containers as TODO.
2015-05-19 13:50:17 +00:00
Bob Nystrom
898ac53f4f fix: prevent stack overflow on recursive toString for List and Map
Add `String.safeToString_` static method that tracks objects currently being
converted to string per fiber, returning "..." when recursion is detected.
Wrap List.toString and Map.toString with this guard to handle self-referential
and mutually recursive structures without crashing.
2015-05-03 18:13:05 +00:00
Bob Nystrom
446e8b2ca9 feat: rename Sequence.list method to toList and update all call sites
The `.list` method on Sequence was renamed to `.toList` to better reflect its
purpose of converting a sequence into a List object. This change updates the
method definition in `builtin/core.wren` and `src/vm/wren_core.c`, along with
all test files that called `.list` on sequences, maps, ranges, and custom
sequence implementations. The test file `test/core/sequence/list.wren` was also
renamed to `test/core/sequence/to_list.wren` to match the new method name.
2015-04-03 18:22:34 +00:00
Bob Nystrom
b6e2229b58 feat: move primitive class definitions from C into core.wren library source
Move the definitions of Bool, Fiber, Fn, Null, and Num classes from hardcoded C code in wren_core.c into the core.wren library source, allowing them to be parsed and created during library initialization. Simplify defineClass to always use wrenNewSingleClass, remove redundant root pushing in wrenNewClass, and adjust the class creation in the interpreter to use a Value instead of ObjClass*.
2015-04-03 15:00:55 +00:00
Bob Nystrom
7884d89165 docs: rename MapSequence and WhereSequence fields and parameters for clarity, expand map(_) and where(_) docs with lazy semantics and examples 2015-04-01 14:31:15 +00:00
Bob Nystrom
85a889e49f feat: replace eager map/where with lazy MapSequence and WhereSequence classes
Refactor Sequence.map and Sequence.where to return lazy MapSequence and WhereSequence wrappers instead of eagerly building a List. Add new MapSequence and WhereSequence classes that delegate iteration and apply the transformation or predicate on-the-fly. Update documentation to reflect lazy semantics and the need to call .list to materialize results. Adjust all existing tests to call .list on map/where results. Add new tests in test/core/sequence/ verifying lazy behavior with infinite Fibonacci iterators.
2015-04-01 14:22:02 +00:00
Bob Nystrom
7d7be7361e feat: add Sequence.each method to iterate over elements with a function
Add a new `each` method to the Sequence class in the Wren programming language,
allowing iteration over sequence elements by passing each element to a provided
function. This replaces the previous pattern of using `map` with `Fiber.yield`
in examples, providing a more direct and idiomatic way to perform side effects
per element. The implementation includes a core library method in `core.wren`,
a C source string in `wren_core.c`, documentation in the Sequence markdown file,
and three test cases covering normal iteration, empty sequences, and non-function
argument error handling.
2015-04-01 14:10:21 +00:00
Thorbjørn Lindeijer
5b71ac0c56 feat: replace eager list-based map/where with deferred MapSequence and WhereSequence classes
Introduce MapSequence and WhereSequence subclasses of Sequence that apply transformations lazily during iteration instead of building intermediate lists. Update Sequence.map and Sequence.where to return these deferred wrappers, modify all existing tests to call .list on results, and add new infinite-sequence tests verifying lazy behavior on Fibonacci iterators.
2015-03-28 21:51:50 +00:00
Thorbjørn Lindeijer
343bfa7a84 feat: add Sequence.each method for side-effect iteration without list creation
Add a new `each` method to the Sequence class that iterates over elements
calling a provided function for each, serving as a side-effect-only
alternative to `map` when the resulting list is not needed. This is
particularly important for the upcoming change where `map` will return a
new sequence instead of mutating in place, as demonstrated by updating
the README and index examples to use `each` with Fiber.yield. Includes
documentation in the Sequence API reference and three new test cases
covering normal iteration, empty sequences, and non-function argument
error handling.
2015-03-28 19:35:20 +00:00
Bob Nystrom
540a4a166a feat: make Sequence.all() and Sequence.any() return actual predicate values instead of booleans
Rewrite all() and any() to store and return the predicate's result directly, matching && and || semantics. Update documentation to describe the new behavior. Move tests from test/core/list/ to test/core/sequence/ and add cases verifying that the first falsey/truthy value is returned.
2015-03-28 17:18:45 +00:00
Bob Nystrom
cc5bf9fcfe feat: add Sequence.list method to collect elements into a new List
Implements a new `list` method on the Sequence class that iterates over all elements and returns them as a freshly created List object. Includes documentation with usage example and a test case using a custom TestSequence class to verify correct behavior.
2015-03-28 16:06:49 +00:00
Bob Nystrom
c3d0b66630 feat: add raw byte access methods and \x escape to String class
Add `byteAt(index)`, `codePointAt(index)`, and `bytes` sequence to String,
enabling direct byte-level manipulation of UTF-8 encoded strings. Introduce
`\x` hex escape sequence in string literals for specifying raw byte values.
Refactor Unicode escape parsing into a generic `readHexEscape` function
supporting variable digit counts. Implement `wrenUtf8Decode` utility for
decoding UTF-8 sequences from byte buffers. Add comprehensive tests for
`byteAt` including boundary conditions and error cases.
2015-03-28 03:44:07 +00:00
Thorbjørn Lindeijer
33d1217d6a feat: add Sequence.list method to convert any sequence into a List
Implements a new `list` method on the Sequence class that iterates over all elements and collects them into a new List instance. Includes documentation in the core sequence docs and a test case verifying correct behavior with a custom sequence implementation.
2015-03-27 21:59:58 +00:00
Thorbjørn Lindeijer
9dc939380c feat: add Sequence.count(predicate) method and update documentation
Implement a new `count(f)` method on the Sequence class that accepts a predicate function and returns the number of elements for which the predicate evaluates to true. The implementation iterates over the sequence, calling `f.call(element)` on each element and incrementing a counter when the result is truthy.

Also update the documentation for both Sequence and List classes: add full documentation for the new `count(predicate)` method on Sequence, and change the terminology in List docs from "items" to "elements" for consistency. Add three test files covering the basic predicate behavior, non-boolean return values from the predicate, and the error case when a non-function argument is passed.
2015-03-14 13:17:21 +00:00
Thorbjørn Lindeijer
b22040577e feat: move contains method from List to Sequence and add tests for List and Range
Add a generic `contains` implementation on the `Sequence` base class, removing the duplicate method from `List`. This allows all sequence types (including Range) to use the method without per-class redefinition. Include new test files for `List.contains` and `Range.contains` covering ordered, backwards, and exclusive ranges.
2015-03-15 14:43:10 +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
Thorbjørn Lindeijer
8f54dc5f76 feat: add Sequence.any method as complement to Sequence.all
Adds a new `any` method to the Sequence class that tests whether any element
in the sequence passes the given predicate function, returning true on the
first match or false if none match. Includes documentation, core library
source update, and three new test files covering basic functionality,
non-boolean return values, and non-function argument error handling.
2015-02-28 20:45:39 +00:00
Bob Nystrom
d5149f9a74 refactor: remove builtin import_ method from String class and inline module loading in compiler
The import_ method on String was a builtin that combined module loading and variable lookup. This change removes that method and instead emits separate bytecode instructions in the compiler: first calling loadModule_ on the module, then calling import_ on the module with the variable name. The native function string_lookUpVariable is renamed to string_import to match the new import_ method name on String's metaclass.
2015-02-16 18:21:29 +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
f2424f029e refactor: move module load failure handling from Wren to C with error string return
The loadModule_ primitive now returns NULL for already-loaded modules and an error string for missing modules, shifting the error handling from Wren's Fiber.abort to C's native string return. The Wren import_ method simplifies to only call the result when non-null, removing the false/true branching logic.
2015-02-16 18:12:41 +00:00
Bob Nystrom
70191aa022 feat: add module loading with String.import_ and embedder-provided loadModuleFn
Implement initial module system allowing Wren code to import other modules via a temporary `String.import_` method. The embedder must supply a `WrenLoadModuleFn` callback that returns source code for a given module name; the VM caches loaded modules and returns a fiber to execute the module body. Add `wrenImportModule` to the VM API, wire `loadModuleFn` into `WrenConfiguration`, and update the CLI interpreter to resolve imports relative to the entry script's directory. Include test cases for importing multiple variables, shared imports across modules, and verifying that variable bindings are independent across import sites.
2015-02-06 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
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
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
Gavin Schulz
9e20b3935a feat: abstract List's toString into generic join method on Sequence
Add `join` and `join(sep)` methods to the `Sequence` class, allowing any sequence to produce a concatenated string of its elements with an optional separator. Refactor `List.toString` to delegate to `join(", ")` with bracket wrapping, removing the manual iteration logic from List. Include new test files for List, Range, and String join behavior, plus runtime error tests for non-string separators.
2015-01-24 04:45:23 +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
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
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
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
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
Kyle Marek-Spartz
b949886707 feat: add contains method to List and update Set example to new operator syntax
Add a `contains(element)` method to the `List` class in the core library,
enabling linear search for an element across all list items. Update the
`example/set.wren` file to use the new Wren operator syntax for `|`, `+`,
`&`, and `-` methods, replacing old function-style parameter definitions
with block-style closures. Also fix trailing whitespace throughout the
Set example and embed the new `contains` method into the C source string
in `src/wren_core.c` for the built-in List class.
2015-01-09 22:02:40 +00:00
Bob Nystrom
fca506fdf1 feat: require parentheses around operator and setter method parameters in Wren
Enforce syntactic requirement for parentheses in operator method signatures (e.g., `+(other)` instead of `+ other`) and setter definitions (e.g., `bar=(value)` instead of `bar = value`). Update the compiler's `infixSignature`, `mixedSignature`, and `namedSignature` functions to consume explicit `(` and `)` tokens around parameter names. Migrate all built-in core library operator definitions and test fixtures to the new parenthesized syntax.
2014-04-09 00:54:37 +00:00
Bob Nystrom
be8c586d4b feat: implement List.addAll() method to append elements from iterable
Add `addAll(other)` method to the List class in both the Wren core library source and its embedded C string representation. The method iterates over the given `other` sequence, appends each element to the list using the existing `add()` method, and returns the original `other` argument to match the documented return behavior. Include a new test file `test/list/add_all.wren` covering basic appending, empty iterable, range input, and return value verification.
2014-04-06 15:37:37 +00:00
Kyle Marek-Spartz
e9391313b7 style: remove space before parentheses in map and where method definitions in core.wren and generated wren_core.c 2014-02-18 17:54:55 +00:00
Bob Nystrom
31ee167168 feat: extract map and where into Sequence base class for List and Range
Extract the common `map` and `where` methods from `List` into a new `Sequence` base class, making `List is Sequence` and `Range is Sequence`. Remove duplicate native method registrations for Range in wren_core.c and add new test files for Range map/where operations.
2014-02-16 17:20:31 +00:00
Bob Nystrom
d335116799 feat: add List.where method for filtering elements with a predicate function
Implement a `where` method on the List class that takes a function `f` and returns a new list containing only elements for which `f.call(element)` returns true. The implementation is added both in the builtin core.wren source and embedded in the C library source string in wren_core.c. Also includes a new test file `test/list/where.wren` verifying filtering with matching and non-matching predicates.
2014-02-15 19:21:24 +00:00
Kyle Marek-Spartz
35fbcc5b49 feat: add List.where method for filtering elements with predicate function
Implement a `where` method on the List class that takes a predicate function and returns a new list containing only elements for which the predicate returns true. The implementation iterates over the list, calls the predicate on each element, and collects matching elements into a new list. Includes test cases verifying filtering with both matching and non-matching predicates.
2014-02-15 06:42:14 +00:00
Kyle Marek-Spartz
48ef257973 feat: add List.map method with test for element transformation
Implement a `map` method on the List class that applies a given function `f` to each element, returning a new list with the transformed values. Includes a test case verifying incrementing each element by 1.
2014-02-15 05:06:29 +00:00
Bob Nystrom
08618abc5d fix: allow empty range subscripts [0..-1] and [0...0] on empty lists
Add special case in list_subscript native to return a new empty list when
the source list is empty and the requested range is [0..-1] (inclusive) or
[0...0] (exclusive). This enables using list[0..-1] as a universal copy
idiom that works even for empty lists. Update the List.+ operator to use
this idiom instead of manual iteration. Add test cases for both range
forms on empty lists.
2014-02-15 04:10:41 +00:00
Bob Nystrom
5f16a3a1cc fix: remove conditional guards in List.+ and handle empty list iteration in iterate native
The previous implementation of List.+ used conditional checks (`this.count > 0`, `that.count > 0`) before iterating, which caused the loop body to be skipped entirely for empty lists. This commit removes those guards, allowing the for-in loops to run unconditionally — the Wren VM's iterate/iterateValue protocol already handles the empty case correctly at the native level. Additionally, the `list_iterate` native in `wren_core.c` now returns `false` immediately when the list count is zero and the iterator argument is null, preventing an out-of-bounds index of 0 from being returned for empty lists. The test file `test/list/concat.wren` is renamed to `test/list/plus.wren` and extended with a check that the original list `a` remains unmodified after concatenation. A new test in `test/list/iterate.wren` verifies that iterating over an empty list returns `false`.
2014-02-15 01:24:06 +00:00
Kyle Marek-Spartz
e690a48e45 feat: implement List concat operator + supporting Range and empty lists
Add `+` method to List class in core.wren that creates a new list by concatenating elements from both operands. Supports concatenation with Range objects and handles empty lists on either side. Includes comprehensive test cases in test/list/concat.wren covering list-list, list-range, and empty list combinations.
2014-02-14 17:09:02 +00:00
Bob Nystrom
e3b3fef0fb feat: make this the implicit receiver for method calls inside class bodies
In the compiler, when a bare name is encountered inside a class definition and it does not resolve to a local variable or global, emit an implicit `this.` load before the call, enabling getter, setter, and method calls without explicit receiver. Update all benchmark, builtin, and test files to remove redundant `this.` qualifiers, and add comprehensive test suites for implicit receiver behavior across instance, inherited, static, nested, and shadowing scenarios.
2014-02-13 01:33:35 +00:00