Commit Graph

80 Commits

Author SHA1 Message Date
Bob Nystrom
19fc5e7534 feat: always wrap functions in closures to simplify VM and improve invocation performance
Simplify the VM by ensuring all called objects are closures, removing the need for runtime checks between bare functions and closures. This eliminates the `IS_FN`/`IS_CLOSURE` branching in `validateFn`, `checkArity`, `bindMethod`, and `wrenNewFiber`, and changes `CallFrame.fn` from `Obj*` to `ObjClosure*`. The compiler now emits `CODE_CLOSURE` for all function declarations, even those without upvalues, trading a small allocation cost at declaration time for faster and more uniform invocation. Benchmarks show performance is neutral to slightly improved across all tested workloads.
2016-03-26 21:00:17 +00:00
Bob Nystrom
82103a64f9 refactor: replace eager optional module loading with lazy source and foreign method hooks 2016-03-17 14:49:43 +00:00
Bob Nystrom
d4df37703d refactor: replace manual error assignment with RETURN_ERROR and RETURN_ERROR_FMT macros across validation and fiber functions
Consolidate repetitive `vm->fiber->error = wrenStringFormat(...)` and `return false` patterns into two new macros defined in wren_primitive.h, reducing code duplication and improving consistency in error reporting for fiber operations, number parsing, and type validation helpers.
2016-03-04 01:11:52 +00:00
Bob Nystrom
db5223d14d feat: unify Fiber.try() error messages with call/transfer by adding verb parameter to runFiber
Add a `verb` string parameter to the `runFiber` helper function so that
`Fiber.try()` produces consistent error messages like "Cannot try a finished
fiber." instead of the previous generic fallback. Update all call sites
(`fiber_call`, `fiber_call1`, `fiber_transfer`, `fiber_transfer1`) to pass
the appropriate verb string, and add a new test case `try_error.wren`
verifying the error message for trying an aborted fiber.
2016-03-04 01:00:33 +00:00
Bob Nystrom
0fde331974 refactor: replace import opcodes with core method calls for module loading
Remove CODE_LOAD_MODULE and CODE_IMPORT_VARIABLE opcodes, replacing them with calls to System.importModule(_) and System.getModuleVariable(_,_) primitives. This simplifies the interpreter loop, improves performance by reducing bytecode dispatch, and prepares for moving module loading logic into Wren source code for embedder flexibility.
2016-02-27 06:43:54 +00:00
Bob Nystrom
9f48ac681c feat: replace wrenGetMethod with slot-based wrenCall API using wrenMakeCallHandle and wrenEnsureSlots
Refactor the C API for invoking Wren methods from C code. Remove the old
wrenGetMethod and wrenCallVarArgs functions that used a type-string-based
argument marshalling system. Introduce a new slot-based approach where
callers first call wrenEnsureSlots to reserve space, then use wrenSetSlot___
functions to place the receiver and arguments on the stack, and finally call
wrenCall with a handle created by wrenMakeCallHandle. Results are retrieved
via wrenGetSlot___. This change simplifies the VM internals, eliminates
varargs parsing overhead, and yields a 185% speed improvement in the call
benchmark. Update all internal modules (scheduler, io, timer) and test files
to use the new API. Also fix fiber suspension to clear the API stack pointer
and adjust the interpreter to store the final fiber result at stack[0] for
C API access.
2015-12-29 15:58:47 +00:00
Bob Nystrom
920b3e2a32 feat: implement string interpolation with %(expr) syntax in compiler and core library
Add lexer support for `TOKEN_INTERPOLATION` to split string literals at interpolation points, introduce `MAX_INTERPOLATION_NESTING` limit of 8, and compile interpolated strings by emitting calls to `String.interpolate_()`. Optimize list and map literal construction with new `addCore_` primitives to reduce stack churn. Update `String`, `List`, and `Map` `toString` methods in core library to use interpolation syntax, and migrate all benchmark and test files from explicit concatenation to interpolated strings.
2015-11-11 15:55:48 +00:00
Bob Nystrom
498d1af8d0 feat: add System.gc() method and replace test's Api.gc() with it
Add a new `System.gc()` primitive that calls `wrenCollectGarbage` to allow
scripts to trigger garbage collection. Document the method in the core
System page. Remove the test-only `Api.gc()` foreign method and update
the foreign_class test to use `System.gc()` instead.
2015-10-24 17:56:27 +00:00
Bob Nystrom
6f67fda56a chore: rename "core library" to "core module" in comments across wren_core.c and wren_core.h
Update three inline comments in wren_core.c (defineClass docstring and wrenInitializeCore bootstrap note) and one in wren_core.h (module-level description) to consistently refer to the "core module" instead of "core library", aligning terminology with the actual module-based architecture.
2015-10-16 02:38:25 +00:00
Bob Nystrom
8b70246acd refactor: remove sourcePath parameter from wrenInterpret and related module functions
The sourcePath field on ObjModule was redundant since it always matched the module name except for the main script. This change removes the parameter from wrenInterpret, wrenInterpretInModule, and wrenNewModule, and replaces all references to module->sourcePath with module->name in error reporting and debug output.
2015-10-16 01:17:42 +00:00
Bob Nystrom
c65fdb2f94 refactor: extract Meta class into separate module and add eval method with compile support 2015-10-16 01:08:56 +00:00
Bob Nystrom
640779a81c refactor: replace PrimitiveResult enum with boolean return type for primitive functions
The PrimitiveResult enum (PRIM_VALUE/PRIM_FIBER) is removed and replaced with a simple bool return value where `true` indicates a normal value return and `false` signals a fiber switch or runtime error. This simplifies the interpreter dispatch in `runInterpreter` by converting the switch on enum cases into a single if/else branch, and reduces branching in the common value-returning path. All primitive function signatures, the `RETURN_VAL`/`RETURN_ERROR` macros, and the `runFiber` helper are updated accordingly.
2015-10-04 03:43:12 +00:00
Bob Nystrom
4d1d6d03f4 feat: remove PRIM_CALL result type and add METHOD_FN_CALL for function call special-casing
Replace the special "call" primitive result type (PRIM_CALL) with a new METHOD_FN_CALL method type that marks function call methods. Add checkArity helper to validate argument count before invoking function closures, and update the interpreter dispatch to handle the new method type instead of relying on the removed PRIM_CALL result.
2015-10-04 02:04:11 +00:00
Bob Nystrom
1ebb7f2507 refactor: remove explicit ObjFiber parameter from all primitive function signatures
Replace the `ObjFiber* fiber` parameter in `DEF_PRIMITIVE` macro and `Primitive` typedef with direct access to `vm->fiber` inside each primitive implementation. Update all call sites in `fiber_current`, `fiber_try`, `fiber_yield`, `fiber_yield1`, `meta_eval`, and the interpreter dispatch to use `vm->fiber` or a local `current` variable instead of the passed-in `fiber` argument.
2015-10-02 14:51:12 +00:00
Bob Nystrom
af90291f6f feat: add isInfinity and isInteger methods to Num class
Implements two new methods on the Num class: isInfinity checks if a number is positive or negative infinity using isinf(), and isInteger checks if a number has no fractional component, returning false for NaN and infinity. Includes C primitives, documentation, and test files.
2015-09-30 15:41:43 +00:00
Bob Nystrom
b3086333f0 refactor: unify PRIM_ERROR and PRIM_RUN_FIBER into single PRIM_FIBER enum value
Replace separate PRIM_ERROR and PRIM_RUN_FIBER return codes with a unified PRIM_FIBER in PrimitiveResult enum, updating all primitive implementations and the interpreter switch case to use the new combined value.
2015-09-30 14:32:39 +00:00
Bob Nystrom
2dcb3660b5 feat: add Fiber.transferError and allow non-string error objects in fiber abort
Refactor runtime error handling to store errors directly in the fiber's error field instead of on the stack, enabling any object (except null) as an error value. Add Fiber.transferError(_) primitive for transferring errors between fibers. Update validation helpers to accept Value arguments directly and modify RETURN_ERROR macro to set fiber error. Adjust GC marking to use wrenMarkValue for the error field. Add tests for aborting with non-string errors and null abort behavior.
2015-09-30 05:57:03 +00:00
Bob Nystrom
ffe87c271d feat: add configurable write callback for System.print output delegation
Add a `WrenWriteFn` callback to `WrenConfiguration` that allows host applications to control how text from `System.print()` and related functions is displayed. When set, the VM invokes this callback instead of directly calling `printf`. If the callback is NULL, printed text is silently discarded. The CLI's `initVM()` now registers a simple `write` function that prints to stdout, while the core `system_writeString` primitive checks for the callback before outputting. This change also refactors `wrenInitConfiguration` to set `defaultReallocate` as the default reallocation function and consolidates configuration fields into a single `WrenConfiguration` struct stored directly in `WrenVM`, removing separate member fields for reallocate, bindForeignMethod, bindForeignClass, loadModule, minNextGC, and heapScalePercent.
2015-09-16 06:01:43 +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
95626bb136 feat: replace inline C string literals with auto-generated .wren.inc includes
Replace the manually embedded C string constants for builtin Wren modules with
a new build system that automatically generates `.wren.inc` header files from
`.wren` source files. The old `script/generate_builtins.py` is removed and
replaced by `script/wren_to_c_string.py`, which produces standalone include
files with a `PREAMBLE` containing the module name and source path. The Makefile
gains pattern rules to rebuild these `.wren.inc` files whenever the
corresponding `.wren` source changes, and the `builtin` phony target is removed
since the generation is now automatic. The `wren.mk` wildcard lists are updated
to include the new `.wren.inc` files as dependencies. The `timer.c` and
`wren_core.c` source files now `#include` their respective `.wren.inc` headers
instead of defining the string literals inline, and the `timer.wren` trailing
newline is removed.
2015-09-13 17:03:02 +00:00
Bob Nystrom
c5cea469e3 docs: clarify string is byte array, move .count to codePoints.count, remove O(n) primitive
The string class is now documented as an immutable byte array rather than a
sequence of Unicode code points. The .count getter is removed from the string
primitive and replaced by .codePoints.count on the code point sequence
interface, making the O(n) cost explicit. Updated the doc site and test files
accordingly.
2015-09-12 04:33:26 +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
a619851cf2 feat: implement UTF-8 aware string subscript ranges with new wrenNewStringFromRange helper
Add wrenNewStringFromRange function to wren_value.c that decodes UTF-8 code points from source string and re-encodes them into result, enabling correct range subscripts on multi-byte characters. Rename wrenUtf8NumBytes to wrenUtf8EncodeNumBytes and make wrenUtf8Encode return written byte count for use in range construction. Add wrenUtf8DecodeNumBytes utility to skip continuation bytes when iterating by byte index. Remove all skip directives from test files and add UTF-8 specific test cases verifying correct slicing across code point boundaries.
2015-09-02 05:14:55 +00:00
Bob Nystrom
ef93496fd4 fix: remove default constructors and require explicit construct new() for all user classes
The compiler no longer auto-generates a default `new()` constructor for classes. All classes must now explicitly define `construct new() {}` to be instantiable. This change removes the `createDefaultConstructor` function from the compiler, eliminates the `return_this` primitive used by Object's default initializer, and adds explicit constructors to all test and example classes. Core metaclasses (Bool, Class, Null, Num, Object, Range, Sequence) now correctly reject `new()` calls with runtime errors.
2015-09-01 15:16:04 +00:00
Bob Nystrom
7e111d19da feat: replace fiber run() with transfer() and suspend() for scheduler-friendly semantics
Remove the run() method from fibers and introduce transfer() for non-stack-based fiber switching, along with suspend() to pause the interpreter and return control to the host application. Update Timer.sleep() to use runNextScheduled_() instead of Fiber.yield(), and add Timer.schedule() for creating independently scheduled fibers. Refactor the core fiber runtime to support transfer semantics, including proper error handling for aborted fibers and self-transfer edge cases. Fix a missing quote in test.py's runtime error validation string.
2015-08-31 05:15:37 +00:00
Bob Nystrom
16613c678b fix: rename constructor initializer keyword from "this" to "init" across compiler, core, and documentation
Rename the constructor initializer signature prefix from "this " to "init " in
wren_common.h's MAX_METHOD_SIGNATURE calculation, wren_compiler.c's
signatureToString and createDefaultConstructor functions, and wren_core.c's
default Object constructor primitive registration. This changes the syntactic
keyword used to define initializer methods in the Wren language.
2015-08-21 05:30:44 +00:00
Bob Nystrom
45c717b11b feat: add module parameter to wrenFindVariable and expose wrenGetCoreModule
Refactor wrenFindVariable to accept an explicit ObjModule* parameter instead of
implicitly using the main module. Promote the internal getCoreModule helper to
a public wrenGetCoreModule function declared in wren_vm.h. Update all call sites
in wren_core.c and wren_meta.c to pass the core module when looking up core
variables, and replace inline getCoreModule calls in wren_vm.c with the new
public function. Remove the NULL-module fallback documentation from
wrenDeclareVariable and wrenDefineVariable.
2015-08-06 14:13:11 +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
8ae42156d8 feat: add return_this primitive to replace duplicated identity-returning implementations
Extract the common pattern of returning the receiver argument into a single
DEF_PRIMITIVE(return_this) function, and refactor fiber_instantiate,
fn_instantiate, and the default Object constructor to use it instead of
inline RETURN_VAL(args[0]) calls. Also fix trailing whitespace on isEmpty
and class_toString lines in the core library source string.
2015-06-30 14:39:43 +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
d04e6a61a6 feat: add dedicated toString primitive for Class and simplify object_toString
Extract class name retrieval from object_toString into a new class_toString primitive, registered on the Class metaclass. This removes the IS_CLASS branch from object_toString, which now only handles instances and falls back to "<object>". The change ensures Class objects return their own name directly via toString rather than relying on the generic object handler.
2015-06-28 22:33:37 +00:00
Bob Nystrom
a4f5ee0280 refactor: replace dedicated CODE_IS opcode with infix operator method call for "is" 2015-06-19 14:58:07 +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
332f570a1a feat: add Object.same static method for reliable built-in equality
Introduce a new static method `Object.same(obj1, obj2)` that exposes the VM's
built-in equality semantics (`wrenValuesEqual`) directly, bypassing any
user-defined `==` overrides. This required creating a dedicated metaclass for
Object (subclass of Class) to host the static method without polluting every
class with a `same` method. The implementation wires up a new `Object metaclass`
in the core initialization sequence, adjusts the class hierarchy setup order,
and adds comprehensive tests covering value types, identity comparison, and
verification that `Object.same` ignores custom `==` operators.
2015-05-01 14:55:28 +00:00
Luchs
1cd91a52b4 fix: rename builtin static variables to avoid linker ambiguity across modules 2015-04-16 11:07:14 +00:00
Luchs
205bf6d596 refactor: rename static callFunction helper to callFn to avoid name collision with public API
The static helper `callFunction` in wren_core.c was renamed to `callFn` to prevent symbol conflicts with the public `wrenCallFunction` API, ensuring unique linkage and clearer separation between internal and external call paths.
2015-03-26 19:42:20 +00:00
Bob Nystrom
d92a8f1c93 fix: replace foreign Meta.eval with primitive and suppress compile errors in wrenCompile 2015-04-04 04:22:58 +00:00
Bob Nystrom
734a415999 fix: cast subtraction result to int before abs to suppress clang -Wabsolute-value warning 2015-04-04 01:38:10 +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
17c6f277b2 refactor: merge patriciomacadden's refactoring branch into mainline
Consolidate the refactoring branch changes from patriciomacadden's fork into the main repository, incorporating the updated class definition logic in wren_core.c that replaces the separate defineSingleClass function with a unified defineClass function capable of handling both raw and subclassed class creation.
2015-04-03 14:19:17 +00:00
Luchs
3373ae0296 fix: cast subtraction to int before abs to suppress clang 3.5 -Wabsolute-value warning 2015-04-01 15:42:20 +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
Bob Nystrom
07de6fca9e fix: remove extraneous space inside isspace cast in num_fromString 2015-04-01 13:43:44 +00:00
ComFreek
57919022b8 fix: cast char to unsigned char before isspace to fix char-subscripts warning 2015-03-31 16:27:44 +00:00