Commit Graph
100 Commits
Author SHA1 Message Date
Bob Nystrom 7265935df4 fix: correct operator precedence table in syntax docs to match actual implementation
The precedence table in doc/site/syntax.markdown had several operators listed at wrong priority levels. This commit reorders the table so that comparison operators (<, <=, >, >=) are at level 10, equality operators (==, !=) at level 12, and bitwise operators (&, ^, |) at levels 7-9, aligning with the true precedence hierarchy.
2016-02-27 18:14:09 +00:00
Bob Nystrom 030d8df612 chore: bump libuv version from v1.6.1 to v1.8.0 in util/libuv.py
Update the LIB_UV_VERSION constant in the build dependency script to point to the
newer v1.8.0 release tag, which includes bug fixes and performance improvements
for the event loop backend.
2016-02-27 17:19:56 +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 aca69b34e6 refactor: merge block() into statement() and remove redundant curly-block parsing
The block() function duplicated the curly-block parsing logic that statement() already handled for single-expression bodies. By removing block() and replacing its single call site in loopBody() with statement(), the compiler eliminates unnecessary indirection and simplifies the control flow parsing. The statement() comment is updated to clarify that it excludes variable binding statements like "var" and "class" which are not allowed in if-branch positions.
2016-02-25 15:04:48 +00:00
Bob Nystrom b301e9f119 feat: implement eager * operator for String and List to repeat content by integer count
Add `*(count)` method to both String and List classes in wren_core.wren, enabling eager repetition of string characters or list elements. The operator validates that count is a non-negative integer, aborting with a clear error message otherwise. For strings, concatenates the original string count times; for lists, builds a new list by adding all elements count times. Includes comprehensive test cases for normal, zero, and edge-case inputs, plus error tests for negative, non-integer, and non-numeric counts. Also refactors existing list plus tests to use inline expressions and adds a plus_not_iterable error test.
2016-02-24 15:48:03 +00:00
Bob Nystrom c9390c624b fix: add missing code block marker in list docs and simplify parens increment in compiler
- Add missing `:::wren` code block marker before the `removeAt` example in the list documentation to ensure proper syntax highlighting.
- Simplify the `parens` array increment in `readString` by combining the assignment and post-increment into a single expression.
2016-02-24 14:52:12 +00:00
Bob Nystrom 217763a51d fix: correct map doc to remove nonexistent iterate/iteratorValue and fix remove param formatting
- Remove erroneous iterate() and iteratorValue() method docs from map.markdown
  since Map does not expose those methods directly
- Fix remove(key) parameter formatting from [key] to `key` for consistency
- Correct File.read encoding description from "The encoding or decoding is done"
  to "No encoding or decoding is done" to accurately reflect behavior
2016-02-22 15:48:53 +00:00
Bob Nystrom 1973934fa2 feat: add Stat.isFile, Stat.isDirectory, File.exists, and Directory.exists methods
Add four new file system checking functions: Stat.isFile and Stat.isDirectory for querying entry type from a Stat object, and File.exists and Directory.exists static methods that return booleans by attempting to stat the path and checking the appropriate type. Also bump MAX_METHODS_PER_CLASS from 12 to 14 to accommodate the new Stat foreign methods, and clean up unused Scheduler imports in existing stat tests.
2016-02-21 20:23:33 +00:00
Bob Nystrom 7f744565fc feat: convert Stat from Wren class with list fields to foreign class with native C accessors
Replace the Wren-implemented Stat class that stored stat fields in a list with a foreign class backed by the raw uv_fs_stat struct, enabling direct C-level access to stat data for future methods like isDirectory() using S_ISDIR().
2016-02-21 19:34:10 +00:00
Bob Nystrom 42ba73b03b feat: add stat instance method to File class returning Stat object
Implement `File.stat` method that performs an asynchronous `fstat` call on the open file descriptor, returning a `Stat` object populated with file metadata (device, inode, mode, link count, user, group, size, block size, block count). Refactor the existing `statPathCallback` into a generic `statCallback` shared by both `statPath` and the new `fileStat` function. Bump `MAX_METHODS_PER_CLASS` from 11 to 12 to accommodate the new foreign method slot. Add comprehensive test coverage including successful stat retrieval and error handling when called on a closed file.
2016-02-21 18:18:45 +00:00
Bob Nystrom e87cd41c32 fix: replace hardcoded OS-specific file flags with portable bitmask mapping in io.c and io.wren 2016-02-21 01:25:41 +00:00
Bob Nystrom d53f9fa477 fix: include stdio.h for printf usage under debug trace flags in wren_vm.c 2016-02-20 21:36:22 +00:00
Bob Nystrom 60fc3ff59c feat: add file create, delete, writeBytes and FileFlags class to IO module
Implement File.create() and File.delete() static methods with async libuv operations, add writeBytes() instance method for writing at offsets, introduce FileFlags constants class mirroring POSIX open() flags, refactor File.open() to accept flag parameters via openWithFlags(), and update documentation and module registration accordingly.
2016-02-20 17:23:42 +00:00
Bob Nystrom 38f48fbce1 feat: add separate make targets for shared and static library builds
Introduce `shared` and `static` make targets to allow building only the shared library (`libwren.so`/`.dylib`) or only the static library (`libwren.a`), respectively. The existing `vm` target now depends on both new targets, preserving backward compatibility while enabling selective builds. This addresses issue #322 by providing finer-grained build control.
2016-02-19 15:22:10 +00:00
Bob Nystrom fe3997f825 feat: add wrenGetSlotType API to query low-level type of object in a slot
Introduce a new public C API function wrenGetSlotType() that returns the
underlying representation type (bool, num, foreign, list, null, string,
or unknown) of the object stored in a given VM slot. This allows C
extensions to inspect slot contents without needing to call individual
type-checking functions or handle errors from mismatched accessors.

The implementation in wren_vm.c uses the existing IS_* macros to
determine the type and returns the corresponding WrenType enum value.
A new WrenType enum is added to wren.h with WREN_TYPE_BOOL,
WREN_TYPE_NUM, WREN_TYPE_FOREIGN, WREN_TYPE_LIST, WREN_TYPE_NULL,
WREN_TYPE_STRING, and WREN_TYPE_UNKNOWN.

Test coverage is added in test/api/slots.c with a slotTypes() foreign
method that verifies all seven type values, and a ForeignType foreign
class is introduced in slots.wren to provide a foreign object for
testing WREN_TYPE_FOREIGN. The test harness in main.c is updated to
support binding foreign class allocate methods via slotsBindClass().
2016-02-19 15:18:00 +00:00
Bob Nystrom 5d04ed2aed fix: add overflow check for jump distance in patchJump and emit error on too much code
Add a MAX_JUMP constant set to 2^16 and validate jump distance in patchJump to prevent silent overflow when bytecode exceeds the maximum representable offset. Also remove the TODO comment in endLoop since the forward jump error will be caught by patchJump. Include test cases jump_too_far.wren and loop_too_far.wren to verify the compiler correctly reports "Too much code to jump over." for both conditional and loop constructs.
2016-02-19 14:57:38 +00:00
Bob Nystrom b1924d34d3 fix: skip skynet example in tests to prevent timeout on slow CI runners
Add early return for "skynet" path in run_example function to avoid
executing the skynet example during test runs, as it is too slow and
causes timeouts on Travis CI bots. Also reduce the kill timer from 5
to 2 seconds in the Test class to fail faster on hanging processes.
2016-02-15 06:28:14 +00:00
Bob Nystrom f3c68323bd fix: increase test timeout from 2 to 5 seconds and add skynet fiber benchmark example
The test runner's per-test timeout was raised to 5 seconds to prevent flaky
timeouts on slower systems. A new example file (example/skynet.wren) was added
demonstrating a million-fiber microbenchmark based on the skynet algorithm,
showcasing Wren's fiber concurrency model. Additionally, the shuffle test's
tolerance threshold was relaxed from 0.2 to 0.21 to reduce false positives
in the random distribution check.
2016-02-15 06:21:50 +00:00
Bob Nystrom dff44de30b fix: add explicit constructor to Foo class and fix abs example syntax in docs
- Add explicit `construct new() {}` to Foo class in error-handling doc to clarify method dispatch behavior
- Fix `(-123).abs` syntax in num.markdown to use parentheses for unary minus precedence
2016-02-15 06:18:53 +00:00
Bob Nystrom f33d85ca05 fix: correct two code samples in error-handling and num documentation
- Add missing construct new() {} to Foo class in error-handling.markdown
- Fix operator precedence for (-123).abs in num.markdown
2016-02-12 18:35:40 +00:00
Bob Nystrom cdf3b64ab2 refactor: replace classSlot int with Variable struct in defineMethod and method
Replace the integer `classSlot` parameter with a `Variable` struct in both `defineMethod()` and `method()` functions, removing duplicate code that handled top-level vs local class loading by delegating to the new `loadVariable()` helper.
2016-02-12 15:43:44 +00:00
Bob Nystrom 6367195722 perf: replace strncmp with memcmp in variable declaration and resolution
In both declareVariable and resolveLocal functions within wren_compiler.c,
the string comparison using strncmp is replaced with memcmp since the
length parameter is already known and null-termination checking is
unnecessary for these fixed-length identifier comparisons. This avoids
the overhead of scanning for null terminators when comparing local
variable names against token or parameter strings.
2016-02-12 15:27:42 +00:00
Bob Nystrom 18bedf45e1 feat: introduce Variable struct to replace raw index and load instruction pair
Replace the ad-hoc output parameter pattern in resolveNonmodule with a proper Variable struct that bundles the variable's index and scope (local, upvalue, or module). This makes variable references a first-class concept in the compiler, eliminating the need to pass around a separate Code pointer for load instructions and improving code clarity throughout the compilation pipeline.
2016-02-12 15:16:41 +00:00
Bob Nystrom c1bbd74416 docs: simplify wrenInterpret example by removing source path parameter 2016-02-09 15:24:55 +00:00
Bob Nystrom 19d7215412 feat: add sample(list) and sample(list, count) methods to Random class with two sampling algorithms 2016-02-09 15:24:45 +00:00
Bob Nystrom edf3717eb0 docs: remove source path parameter from wrenInterpret example in embedding-api docs 2016-02-09 01:43:05 +00:00
Bob Nystrom 813594b14c feat: add Random.shuffle() method using Fisher-Yates algorithm
Implement in-place shuffle for lists on the Random class, using the Fisher-Yates algorithm to ensure uniform permutation distribution. Includes documentation with usage examples, Wren source implementation, and a test suite covering empty lists, single-element lists, and verification that all 24 permutations of a 4-element list are reachable.
2016-02-07 18:38:39 +00:00
Bob Nystrom f1babe5ad4 feat: move File.stat to Stat.path and update all references across docs, source, and tests 2016-02-07 17:56:16 +00:00
Bob Nystrom c1d21ee099 docs: remove community page and redirect content to contributing page with wiki references
The community.markdown file is deleted entirely. Its content about mailing list, libraries, bindings, editor integrations, and tools is migrated into the contributing.markdown page, which now directs users to add such resources to the wiki instead of maintaining them inline. The site navigation template also removes the community link from both the sidebar and footer.
2016-01-24 23:39:35 +00:00
Bob Nystrom 87334da1df feat: replace wrenAllocateForeign with wrenSetSlotNewForeign supporting arbitrary slot and class selection
The old wrenAllocateForeign was limited to slot 0 and the class at the top of the API stack. The new wrenSetSlotNewForeign takes explicit slot and classSlot parameters, allowing foreign objects to be created in any slot from any class. All internal and test call sites updated to use the new API.
2016-01-24 17:25:04 +00:00
Bob Nystrom 885570f0b6 feat: add process module with arguments and allArguments static methods
- Introduce new 'process' module exposing a Process class with foreign static methods for accessing command-line arguments.
- Implement processSetArguments in main.c to store argc/argv, and processAllArguments in process.c to return them as a Wren list.
- Add --help flag support to CLI, printing usage with optional arguments.
- Include documentation for Process.arguments and Process.allArguments, plus module index and template updates.
- Register process module in modules.c and add Xcode project references for new source files.
- Add test scripts for allArguments and arguments, verifying list type, count, and expected values.
2016-01-22 15:57:26 +00:00
Bob Nystrom d8fef617ec fix: remove -fwhole-program flag from wren binary link step 2016-01-22 15:01:56 +00:00
Bob Nystrom 6b153f2a33 chore: update copyright year range in LICENSE from 2013-2015 to 2013-2016 2016-01-22 14:42:16 +00:00
Bob Nystrom 98efeb301d fix: disable -flto flag in wren.mk to avoid LLVM gold linker plugin error on clang builds 2016-01-22 14:42:01 +00:00
Bob Nystrom 58c7c735ed docs: add System.print calls to list examples, reword map docs, update method-calls and performance benchmarks
- Add System.print() wrapper to all list subscript and count examples in lists.markdown
- Reformat map literal alignment and reword description in maps.markdown
- Remove paragraph about fibers as map keys from maps.markdown
- Change method-calls example from "hello" to "Heyoo!" and reword VM execution description
- Update performance benchmark timings and bar widths across all test cases
2016-01-22 05:38:27 +00:00
Bob Nystrom 852eb9707e fix: update copyright year range in LICENSE from 2013-2015 to 2013-2016 2016-01-21 23:20:58 +00:00
Bob Nystrom 527d936c55 perf: enable link-time optimization and whole-program compilation in wren.mk for CLI builds
Add `-flto` to `C_OPTIONS` and replace the CLI linker invocation with `-fwhole-program`, yielding 5-45% performance improvements across benchmarks (e.g., api_call +30%, binary_trees +12%, fib +20%).
2016-01-20 15:47:00 +00:00
Bob Nystrom beaa1b7c73 fix: relax directory stat assertions to avoid filesystem-specific values
Replace hardcoded expected values for linkCount and size with range checks
(>=1 and >0 respectively) so the test passes across different filesystems
that may report varying directory metadata.
2016-01-05 15:32:51 +00:00
Bob Nystrom 7186b04bed feat: add File.stat static method and test for directory stat
Add a new `File.stat(path)` static method that returns a `Stat` object with low-level file system metadata for both files and directories. Include a test file `stat_static_directory.wren` that validates the returned `Stat` object's type and field types (device, inode, mode, linkCount, user, group, specialDevice, size, blockSize, blockCount) against a known test directory.
2016-01-01 18:05:31 +00:00
Bob Nystrom f112722d00 feat: add File.stat() method and Stat class for filesystem metadata queries
Implement asynchronous stat() on File class returning a new Stat object with device, inode, mode, linkCount, user, group, specialDevice, size, blockSize, and blockCount fields populated from libuv uv_fs_stat callback. Register foreign method statPath_ in module registry, bump MAX_METHODS_PER_CLASS to 10, add Stat class to io.wren with indexed field accessors, update documentation index with Stat page, and include test coverage for stat on existing file and nonexistent path.
2016-01-01 17:58:44 +00:00
Bob Nystrom 3746b56ed9 feat: add optional offset parameter to File.readBytes method
Extend File.readBytes with a second overload accepting an offset argument, allowing reads to start at any byte position from the beginning of the file. The existing single-argument variant now delegates to the new two-argument version with offset 0. Validation for the offset parameter mirrors the existing count checks, aborting on non-numeric, non-integer, or negative values. The underlying C implementation passes the offset directly to uv_fs_read, replacing the previous hardcoded zero. Documentation in the io module markdown is updated with usage examples for both signatures, and the old TODO comment about missing offset support is removed. New test files cover offset-based reads, edge cases (zero offset, past-end offset, zero count with offset), and error conditions for invalid offset arguments.
2015-12-30 16:13:19 +00:00
Bob Nystrom 00d4fca59a fix: replace square bracket parameter notation with backtick formatting in system docs
The documentation for `System.print` and `System.printAll` used square brackets
(e.g., `[object]`, `[sequence]`) to denote parameters, which is inconsistent
with the project's standard backtick formatting. This change updates both
descriptions to use backtick-wrapped parameter names (`object`, `sequence`).
2015-12-30 06:35:14 +00:00
Bob Nystrom 54d498ce5d fix: correct grammar and example errors in method-calls documentation
- Fix missing article "a" in "expose some stored or computed property"
- Fix missing relative pronoun "that" in "a method doesn't need any parameters"
- Replace incorrect example `list.clear` with `[1, 2, 3].clear` in getter/setter distinction section
- Simplify phrasing "without any collision" to "without a collision" in setters section
2015-12-30 06:29:13 +00:00
Bob Nystrom 0e1129bef3 docs: add full documentation for io module covering Directory, File, and Stdin classes 2015-12-30 05:56:44 +00:00
Bob Nystrom 9dd956dc10 fix: correct fileFinalizer declaration and use dedicated FINALIZER macro
The extern declaration for `fileFinalize` was changed from `(WrenVM* vm)` to `(void* data)` to match the actual Wren finalizer signature. A new `FINALIZER` macro was added that casts the function pointer to `WrenForeignMethodFn` and sets the signature to `"<finalize>"`. The `STATIC_METHOD("<finalize>", fileFinalize)` entry in the File class registry was replaced with `FINALIZER(fileFinalize)` to use this macro, ensuring the finalizer is correctly registered with the proper type and signature.
2015-12-30 05:07:26 +00:00
Bob Nystrom deb833b1d8 feat: replace manual byte-buffer parsing with native C list creation in Directory.list()
The C directoryListCallback now directly builds a Wren list using wrenSetSlotNewList and wrenInsertInList, eliminating the temporary byte buffer that required manual splitting in Wren. The Wren side is simplified to a single return of the scheduler result. Additionally, the wrenCall and wrenCaptureValue functions are hardened: wrenCall discards extra temporary slots and calls with arity 0, wrenCaptureValue properly roots/unroots object values during handle creation, and the debug stack trace printer skips stub functions with NULL module pointers. A new test case verifies that wrenCall correctly ignores extra temporary slots on the stack.
2015-12-29 16:37:47 +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 1797c6c977 refactor: replace finalizer fiber with raw data pointer callback
Remove the dedicated finalizer fiber from WrenVM and change finalizer functions to accept a void* data pointer instead of a full WrenVM reference. This prevents user code from interacting with the VM during garbage collection, simplifying the GC path and eliminating the need for pre-allocated fiber infrastructure. Update the WrenForeignClassMethods struct, all built-in finalizers (file, test), and the binding/calling logic accordingly.
2015-12-28 16:06:29 +00:00
Bob Nystrom 6abebbe906 feat: expose wrenEnsureSlots API and rename foreignStackStart to apiStack for slot access outside foreign methods
Replace the internal `foreignStackStart` pointer with a public `apiStack` field
that tracks the base of available C API slots. Extract the static
`ensureStack` helper into a non-static `wrenEnsureStack` function declared in
the header, enabling `wrenEnsureSlots()` to create a fiber and stack when
called outside a foreign method. Update `callForeign` to use `apiStack` and
adjust `metaCompile` to write results through the new pointer. Add a
`ensureOutsideForeign` test that allocates slots on a fresh VM, verifies
slot count grows from 0 to 20, and exercises all 20 slots with double values
to confirm the stack is correctly initialized and usable.
2015-12-28 15:43:17 +00:00
Bob Nystrom 278d66bdc1 feat: use dedicated fiber for foreign finalizer stack to avoid allocation during GC
The finalizer fiber is pre-allocated in the VM and reused for each finalizer call, replacing the previous approach that used a raw stack pointer. This ensures no memory allocation occurs during garbage collection when finalizers are invoked. The change also properly resets the fiber after each finalizer call and updates the GC rooting to include the new fiber.
2015-12-28 05:43:08 +00:00
Bob Nystrom 633dbfeed1 feat: add Directory.list() foreign method and async directory listing to io module 2015-12-27 04:42:53 +00:00
Bob Nystrom 195db501bf fix: rename shadowed variables in directoryListCallback to fix C++ compile error
Rename `result` and `resultLength` to `buffer` and `bufferLength` respectively, and rename `bufferSize` to `bufferCapacity` to avoid shadowing the `result` variable from the outer scope, which causes a C++ compilation error when compiling as C++.
2015-12-27 04:26:05 +00:00
Bob Nystrom 76dbeb39be fix: print object type enum value in unknown object error dump 2015-12-27 04:15:00 +00:00
Bob Nystrom a3bbc03afb chore: reorder OBJ_STRING case in wrenFreeObj switch to alphabetical order 2015-12-27 04:13:39 +00:00
Bob Nystrom a20ef8458b fix: correct spelling of 'upvalue' in comment for addUpvalue function 2015-12-27 04:12:35 +00:00
Bob Nystrom bdc2709234 chore: add build log output for wren_to_c_string invocations in makefile
Remove the print statement from wren_to_c_string.py that logged the input file path, and instead add printf commands to the three makefile rules that invoke the script, ensuring consistent logging format during builds.
2015-12-27 04:11:48 +00:00
Bob Nystrom 5e32d02778 fix: initialize match variable before loop in test.py stack trace parsing 2015-12-27 04:08:20 +00:00
Bob Nystrom 4d0b3f78a5 feat: add wrenGetVariable API to load top-level module variable into a slot
Implement wrenGetVariable function in wren_vm.c that looks up a top-level variable by name in a specified module and stores it in the given slot. Includes validation for non-null module/name parameters and slot bounds, module resolution via getModule, variable lookup through symbol table, and slot assignment. Adds corresponding declaration to wren.h public header. Introduces comprehensive test suite in test/api/get_variable.* covering scenarios: retrieving variable before definition (null), after definition, after reassignment, using a non-zero slot, and accessing a variable from another module. Registers the test bindings in test/api/main.c and updates Xcode project file to include the new source.
2015-12-26 18:53:14 +00:00
Bob Nystrom 9b2a03c48a feat: add Directory.list() method to io module for reading directory entries
Implement a new `Directory` class with a static `list(path)` method that returns an array of filenames from the specified directory. The implementation uses a foreign function `list_(path, fiber)` that performs the actual filesystem read via libuv, collects all directory entries into a zero-byte-terminated buffer, and then splits that buffer into individual strings on the Wren side. Includes test cases for normal directory listing, listing a file path (runtime error), listing a nonexistent path (runtime error), and passing a wrong argument type (runtime error). Also bumps `MAX_CLASSES_PER_MODULE` from 3 to 4 to accommodate the new class.
2015-12-24 18:12:12 +00:00
Bob Nystrom 51bc3a828c feat: add wrenGetValueDouble API and benchmark for wrenCall() performance
Add a new public API function wrenGetValueDouble() to extract numeric values from WrenValue handles, with proper assertions for NULL and type checking. Introduce a comprehensive benchmark test for wrenCall() that measures invocation overhead by calling a foreign method 1,000,000 times across a separate VM instance, validating result correctness and reporting elapsed time. Include the benchmark script api_call.wren and register it in the Python benchmarking harness. Also fix minor assertion message typos in wren_vm.c for consistency.
2015-12-24 01:29:53 +00:00
Bob Nystrom 5865f534fc fix: change map key parsing precedence from PRIMARY to UNARY
In wren_compiler.c, the map() function now parses map keys with PREC_UNARY
instead of PREC_PRIMARY, allowing unary operators like negation and bitwise
NOT in key expressions. Added test/language/map/bad_key_precedence.wren to
verify that binary operators (e.g., 1 + 2) still produce an error when used
as keys, and test/language/map/precedence.wren to validate correct parsing
of primary, call, and unary expressions in map keys.
2015-12-23 17:22:49 +00:00
Bob Nystrom dbd75f8905 feat: allow call and unary expressions as map keys in compiler
Change the map key parsing precedence from PREC_PRIMARY to PREC_UNARY in
wren_compiler.c, enabling method calls (e.g., name.count), subscript
access (name[0]), and unary operators (-1, ~3) as valid map keys.

Add two test files: precedence.wren verifying the new key types work
correctly, and bad_key_precedence.wren confirming that binary operators
like addition still produce a parse error.
2015-12-23 00:00:50 +00:00
Bob Nystrom c630715f4a fix: add one slot for implicit receiver in fiber stack capacity
The initial stack capacity calculation for new fibers was off by one because it did not account for the unused implicit receiver slot that the compiler assumes all functions have. This caused stack overflow when the function's maxSlots exactly matched the allocated capacity.

Additionally, add a missing return 0 statement in the hashValue function's default case under the UNREACHABLE() macro to suppress compiler warnings about non-void function not returning a value.
2015-12-17 04:55:18 +00:00
Bob Nystrom 001a9b7439 docs: add detailed slot-based API documentation for foreign method interface in wren.h 2015-12-17 00:39:27 +00:00
Bob Nystrom 23b6980dfd feat: add wrenEnsureSlots, wrenSetSlotNewList, and wrenInsertInList C API functions for list manipulation
Add three new public C API functions to the Wren embedding API that enable
foreign methods to create and populate lists. wrenEnsureSlots grows the
foreign slot stack to guarantee space for temporary work, wrenSetSlotNewList
stores a new empty list in a slot, and wrenInsertInList inserts a value from
one slot into a list at another slot at a given index (supporting negative
indices for relative positioning). The implementation includes a new internal
ensureStack helper that reallocates the fiber's stack and updates all
pointers (stack top, call frame starts, open upvalues, and foreign stack
start) when the reallocation moves the stack. New test files (lists.c,
lists.h, lists.wren) exercise creation, appending, insertion, and negative
index insertion, and the existing slots test is extended with an ensure test
that verifies slot count growth and slot usability.
2015-12-17 00:28:26 +00:00
Bob Nystrom 7535fed608 refactor: replace wrenReturn___() with wrenSetSlot___() for writing values to arbitrary slots
The old wrenReturn___() functions only wrote to slot 0 for return values. The new wrenSetSlot___() functions allow writing to any slot index, making them general-purpose for manipulating the foreign call stack. This change updates all call sites, removes the dedicated returns test suite in favor of slots tests, and adjusts the VM internals to treat slot 0 as the return position rather than using a separate return mechanism.
2015-12-16 21:00:13 +00:00
Bob Nystrom 234a98faef refactor: rename wrenGetArgument* to wrenGetSlot* and add IS_LIST macro for slot-based API
Migrate the foreign method argument access API from an argument-oriented naming
scheme to a slot-based one, renaming wrenGetArgumentCount to wrenGetSlotCount,
wrenGetArgumentBool to wrenGetSlotBool, and all other argument accessors
accordingly. Update every call site across the VM, modules (io, timer, meta,
random), and test files (benchmark, foreign_class) to use the new names. The
slot getters now assert the correct type at runtime rather than silently
returning defaults, shifting safety responsibility to the caller for
performance. Also add the IS_LIST type-checking macro to wren_value.h alongside
the existing IS_* macros.
2015-12-16 18:22:42 +00:00
Bob Nystrom e929c7c997 refactor: remove foreignCallNumArgs and rename foreignCallSlot to foreignStackStart
The number of arguments can be derived from the stack pointer difference, eliminating the need to store it separately. Rename the slot pointer to better reflect its purpose as the start of the foreign call's stack region.
2015-12-16 01:10:02 +00:00
Bob Nystrom 5d8ecad5a6 feat: add benchmark for Wren C API foreign method calls and refactor test class names
Add a new benchmark that measures the performance of calling foreign methods through the Wren C embedding API, specifically testing argument passing and return values with a tight loop of 10 million calls. Refactor test API classes from generic "Api" to specific names like "Call", "Returns", "Value", and "ForeignClass" to avoid naming conflicts with the new benchmark module. Update the benchmark runner to use the test_api executable for API-specific benchmarks and remove the special API test argument handling from the test runner.
2015-12-16 00:02:13 +00:00
Bob Nystrom ba0d308fba fix: remove fiber support as map keys and revert to value-only key validation
The previous implementation allowed fibers as map keys by assigning each fiber a unique numeric ID for hashing and equality. This was originally added to support a misguided attempt at thread-local storage that was never used. This commit removes the fiber ID field from ObjFiber, the nextFiberId counter from WrenVM, the fiber hashing case in hashObject(), and the IS_FIBER check in validateKey(). The error message for invalid keys is updated from "Key must be a value type or fiber." to "Key must be a value type." and all affected test expectations are updated accordingly.
2015-12-15 18:42:21 +00:00
Bob Nystrom 315e140a43 fix: correct fiber count in benchmark comment from 10000 to 100000 2015-12-15 18:37:53 +00:00
Bob Nystrom 6de3d6aa30 fix: correct debug instruction output and remove ClassCompiler parameter from method
- Fix debug dump to print human-readable instruction names instead of internal enum names (e.g., "RETURN" instead of "CODE_RETURN")
- Remove `ClassCompiler*` parameter from `method()` function, accessing class state through `compiler->enclosingClass` instead
- Change `ClassCompiler.fields` from pointer to embedded struct, updating field lookup to use address-of operator
2015-12-15 01:10:10 +00:00
Bob Nystrom 9aee7ee94e feat: grow fiber stack dynamically and replace fixed-size stack with heap-allocated array 2015-12-14 16:00:22 +00:00
Bob Nystrom 83254bbde3 feat: track max stack slots per function for dynamic stack growth
Add `numSlots` and `maxSlots` fields to `Compiler` struct to track current and maximum stack usage during compilation. Introduce `stackEffects` array mapping each opcode to its net stack delta, defined via updated `OPCODE` macro in `wren_opcodes.h` now taking a second argument. Modify `initCompiler` to initialize slot tracking from `numLocals`, update `emitByte` and related emit functions to adjust `numSlots` and update `maxSlots` when a new peak is reached. Extend `ObjFn` with `maxSlots` field, pass it through `wrenNewFunction` calls (including `makeCallStub`), and fix a null-check in `wrenDumpCode` for core module name.
2015-12-14 06:57:40 +00:00
Bob Nystrom 0f0d3f0c2d fix: propagate compile errors from imported modules and update test runner to skip them 2015-12-08 15:49:37 +00:00
Bob Nystrom 9dcba9f8b6 feat: ignore newlines in import statements and add test for multiline imports
Add calls to ignoreNewlines in the import compiler function to allow
newlines between the import keyword and the module string, and between
the module string and the for clause. Create a new test case
test/language/module/newlines/ that verifies multiline import syntax
works correctly with both bare imports and imports with variable
bindings.
2015-12-08 03:41:10 +00:00
Bob Nystrom 9d2b4af508 fix: allow empty ranges at the end of a sequence for lists and strings
Previously, empty ranges were only permitted at index zero on an empty sequence.
This change extends the `calculateRange` function to allow empty ranges at the
end of a non-empty sequence, enabling `list[3...3]` and `list[3..-1]` to return
an empty slice. Updated the range validation logic to check `range->from == *length`
instead of requiring a zero-length sequence, and added test cases for both lists
and strings to verify the new behavior.
2015-12-06 18:37:58 +00:00
Bob Nystrom 320c804ecf feat: add Dart benchmarks for binary_trees, delta_blue, fib, for, and method_call
Add five new Dart benchmark implementations (binary_trees, delta_blue, fib, for, method_call) under test/benchmark/ and register the Dart runner using the fletch runtime in util/benchmark.py. The benchmarks are ported from existing Wren and JavaScript versions, covering tree traversal, constraint solving, recursive Fibonacci, loop performance, and method call overhead.
2015-12-05 19:09:30 +00:00
Bob Nystrom a5d08effea fix: escape percent sign in string interpolation error message
The error message for a missing '(' after '%' in string interpolation
contained an unescaped '%' character, which could be misinterpreted
by format string functions. Changed the literal '%' to '%%' to ensure
proper display of the percent sign in the error output.
2015-12-05 18:15:18 +00:00
Bob Nystrom 93839b588a fix: add parentheses to method calls in delta_blue benchmark for idiomatic Wren syntax 2015-12-01 04:58:08 +00:00
Bob Nystrom 6a05397557 feat: add animals guessing game example with binary tree knowledge base 2015-11-29 17:43:47 +00:00
Bob Nystrom ce2028302a fix: correct .gitignore patterns to use leading slash and add missing pygments lexer file 2015-11-27 19:22:09 +00:00
Bob Nystrom e5da0ecddf fix: correct two typos in classes documentation for field naming and superclass method invocation 2015-11-25 16:59:16 +00:00
Bob Nystrom bbe21c48db fix: replace empty array initializers with named sentinel macros for VC++ compatibility 2015-11-25 16:36:42 +00:00
Bob Nystrom 58d4dfc2db refactor: eagerly evaluate interpolated expressions in string compilation
Remove the deferred function compilation for interpolation parts and instead evaluate them directly during string parsing. This simplifies the compiler by eliminating the need for String.interpolate_() and the associated closure creation, replacing it with a direct list construction and join() call.
2015-11-23 15:08:14 +00:00
Bob Nystrom 253707db17 docs: expand method scope documentation with this keyword and object scope explanation 2015-11-21 22:00:21 +00:00
Bob Nystrom fa1c1f5cda docs: document string interpolation syntax and update code examples across docs and site
Add a new "Interpolation" section to the values documentation explaining the `%(expr)` syntax with examples of complex expressions and nested interpolation. Update all code samples in README.md, getting-started.markdown, and index.markdown to use the new interpolation syntax instead of string concatenation. Adjust syntax highlighting in style.scss by adding a new `.si` class for interpolation spans with distinct background color, and tweak existing color values for strings, numbers, and keywords to improve visual distinction. Add the `\%` escape sequence to the list of supported escape characters in values.markdown.
2015-11-21 17:20:50 +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 a8961f817e feat: switch release build optimization from -Os to -O3 for performance
Change the C compiler optimization flag in util/wren.mk from -Os (size-optimized) to -O3 (aggressive speed optimization) for release builds. Benchmarks show consistent speed improvements across 10 of 11 tests, with gains ranging from 2.5% to 12.6% relative to baseline, and only method_call showing a minor 5.4% regression.
2015-11-10 15:33:15 +00:00
Bob Nystrom cf5b011be5 fix: remove trailing commas in END_MODULE and END_CLASS macros 2015-11-10 15:13:19 +00:00
Bob Nystrom 7fd90152ae docs: lowercase module names in sidebar and table, reword built-in module description for clarity 2015-11-09 15:42:48 +00:00
Bob Nystrom 60dd61be05 docs: replace placeholder TODO with full Random module docs and rename parameters from min/max to start/end 2015-11-09 15:37:06 +00:00
Bob Nystrom 909c242a03 chore: reorganize doc site structure by moving core docs under modules/ and removing category metadata
Restructure the documentation hierarchy to prepare for documenting additional built-in modules. Move all core library documentation from `doc/site/core/` to `doc/site/modules/core/`, rename `modules.markdown` to `modularity.markdown`, remove `^category` metadata lines from all affected pages, update cross-reference links to use relative paths under the new structure, and add a TODO placeholder to the Class class page.
2015-11-08 21:31:22 +00:00
Bob Nystrom 4562b2e497 docs: move precedence table from grammar page to syntax page with updated operator list and links 2015-11-08 18:59:23 +00:00
Bob Nystrom 1b2f11eec3 docs: remove outdated commented-out is operator documentation from method-calls page 2015-11-07 21:00:49 +00:00
Bob Nystrom f27fff9dd0 docs: document is operator as overridable infix method and add type-test examples 2015-11-07 21:00:24 +00:00
Bob Nystrom efcc4d07c7 docs: reorganize language guide into linear narrative with renamed sections and navigation links 2015-11-07 19:09:04 +00:00
Bob Nystrom 7fcd513b23 fix: add explicit casts to C++ compile errors in wren_value.c and wren_vm.c
Add explicit casts from void* to Obj** for reallocateFn calls in wrenNewVM and wrenFreeVM, and remove trailing whitespace on blank lines throughout wren_value.c to resolve C++ compilation errors.
2015-11-04 15:07:33 +00:00
Bob Nystrom 8afa5c3d68 fix: refactor GC gray set to use count/capacity and handle empty set edge cases
- Rename grayDepth to grayCount and maxGray to grayCapacity for clarity
- Fix gray stack growth condition to check capacity instead of depth
- Use config.reallocateFn directly instead of wrenReallocate wrapper
- Change blacken loop from do-while to while to handle empty gray set
- Remove separate initializeGC function and inline allocation in wrenNewVM
- Add explicit System.gc() calls in deeply_nested_gc and many_reallocations tests
- Normalize test output strings to lowercase "done"
2015-10-29 14:38:09 +00:00
Bob Nystrom 9fe0b2475e refactor: rename GC marking functions to tri-color terminology and add wrenGrayObj helper
Rename `wrenMarkValue` to `wrenGrayValue`, `wrenMarkBuffer` to `wrenGrayBuffer`, and `wrenDarkenObjs` to `wrenBlackenObjects` to make the tri-color garbage collection abstraction explicit. Introduce `wrenGrayObj` as a new helper that handles adding objects to the gray stack with cycle detection via the `isDark` flag. Update all call sites in the compiler, value, and VM modules to use the new names. Fix a typo in the VM header comment ("garbace" → "garbage").
2015-10-28 14:55:04 +00:00