100 Commits
Author SHA1 Message Date
Bob Nystrom c3a6b7f29c fix: replace hashBits with Wang integer hash to fix catastrophic collision in numeric map keys
The old hashBits function XORed the two 32-bit halves of a double and applied a weak mixing from Java's HashMap, which produced severe clustering for small integers (e.g., all values 1..N mapped to entry zero). This caused O(N²) insertion/lookup in maps with numeric keys. The new implementation uses Thomas Wang's integer hash (via V8's ComputeLongHash), which distributes bits uniformly across the 30-bit hash space. Also doubles the iteration count in map_numeric benchmarks (from 1M to 2M) to better stress the hash function, and updates the expected benchmark output accordingly.
2019-07-28 04:00:02 +00:00
Robert Nystrom 5f0d1f909b fix: replace hashBits with V8's integer hash to fix catastrophic collision for numeric keys
The old hashBits function XORed the two 32-bit halves of a double and applied
Java HashMap-style mixing, but for small integers the low bits of the double
representation are mostly zero, causing nearly all keys to map to entry zero.
This replaces it with Thomas Wang's integer hash (as used by V8's
ComputeLongHash), which properly scatters bits across the 32-bit key space.
Also updates the map_numeric benchmark to iterate 2,000,000 entries (up from
1,000,000) and adjusts the expected output in util/benchmark.py accordingly.
2019-07-27 20:34:07 +00:00
Bob Nystrom 6700a1e766 feat: add String.fromByte primitive with validation and unit tests
Implement a new String.fromByte(byte) class method that creates a single-byte string from an integer 0-255. Includes C primitive in wren_core.c with bounds checking, the wrenStringFromByte helper in wren_value.c, header declaration, documentation in the core string markdown, and five test files covering valid values (65, 0, 255) and error cases (non-integer, non-number, too large, negative).
2019-03-01 03:31:26 +00:00
Bob Nystrom 92e5fc7cf5 fix: correct pointer dereference in absolutePrefixLength for Windows drive letter check
The fix changes `path->chars[2]` to `path[2]` in the drive letter absolute path detection logic, resolving a compilation error on Windows where `path` is a `const char*` pointer, not a struct with a `chars` member.
2019-02-20 17:00:22 +00:00
Bob Nystrom 460d0d2855 fix: rename include guard in wren_compiler.h from wren_parser_h to wren_compiler_h
The include guard macro in src/vm/wren_compiler.h was incorrectly named
wren_parser_h, likely a copy-paste artifact from the parser header.
This change corrects it to wren_compiler_h to match the actual filename
and prevent potential ODR violations when both headers are included.
2019-02-15 15:30:46 +00:00
Bob Nystrom 609d90493e fix: remove unused wrenInterpretInModule prototype from wren_vm.h 2019-02-15 15:30:16 +00:00
Bob Nystrom 38b70b4648 fix: correct null-check assert in insertEntry to guard against empty entries array 2019-02-14 15:51:57 +00:00
Bob Nystrom 8e5ad18146 fix: prevent buffer overflow in error label for long tokens in wren_compiler.c
Replace fixed-size ERROR_MESSAGE_SIZE buffer with dynamically sized array based on MAX_VARIABLE_NAME to avoid stack overflow when formatting error messages for tokens exceeding the original buffer capacity.
2019-02-14 15:42:12 +00:00
Bob Nystrom 2c60f0b07b feat: add ctrl+w word-delete and escape-bracket home/end/delete keys to repl input handling
Implement Ctrl+w keybinding to delete the word left of cursor by first removing trailing spaces then deleting non-space characters. Add EscapeBracket.delete handler that calls deleteRight() and consumes the extra 126 byte. Support EscapeBracket.end and EscapeBracket.home to jump cursor to line end and start respectively. Define corresponding constants ctrlW (0x17), delete (0x33), end (0x46), and home (0x48) in the Chars and EscapeBracket classes.
2019-02-14 15:33:30 +00:00
Bob Nystrom f3a1c71c49 feat: add ctrl+w word-delete, delete key, home/end keys to repl input handling
Add Ctrl+w keybinding to delete the word left of cursor by removing trailing spaces then characters until next space. Implement EscapeBracket.delete handling to delete character right of cursor and consume the trailing 126 byte. Support EscapeBracket.end and EscapeBracket.home to jump cursor to end or start of line. Register new ctrlW constant (0x17) and EscapeBracket constants for delete (0x33), end (0x46), home (0x48). Add Taylor Hoff to AUTHORS.
2019-02-14 15:31:22 +00:00
Bob Nystrom 673d5c57cd feat: add wrenHasError helper and replace raw IS_NULL checks on fiber->error
Introduce a static inline `wrenHasError` function in `wren_value.h` that encapsulates the `!IS_NULL(fiber->error)` pattern, improving code readability and maintainability. Replace all direct `IS_NULL(fiber->error)` checks across `wren_core.c`, `wren_vm.c`, and the interpreter loop with calls to this new helper. Additionally, clean up commented-out debug print statements and extraneous blank lines in the `trim` methods within the embedded core module source string, and add Michel Hermier to the AUTHORS file.
2019-02-11 15:52:38 +00:00
Bob Nystrom a1ab679539 feat: add limited re-entrant foreign call support with apiStack management
Introduce a limited form of re-entrant calls by enforcing that apiStack is NULL before entering a foreign call and resetting it to NULL after completion, replacing the previous save/restore pattern. Add a regression test (call_calls_foreign) that exercises re-entrant wrenCall invocations where a foreign method triggers another API call, verifying slot counts and correct parameter passing. Fix a typo in reset_stack_after_call_abort test (afterConstruct -> afterAbort) and update Makefile to build api_test target separately.
2019-02-11 15:38:09 +00:00
Bob Nystrom 523e157c6a feat: allow re-entrant wrenCall from foreign methods by resetting apiStack to NULL
The core change in wren_vm.c replaces the save/restore pattern for vm->apiStack with a simple NULL assignment after foreign calls, enabling nested wrenCall invocations from within foreign method handlers. This is accompanied by new test files (call_calls_foreign.c/.h/.wren) that verify the re-entrant call path works correctly, along with Makefile and Xcode project updates to build and run the new tests. A minor typo fix in reset_stack_after_call_abort.c renames a handle variable from 'afterConstruct' to 'afterAbort' for consistency.
2019-02-09 01:09:39 +00:00
Bob Nystrom 8e2f9a6a15 fix: flush stdout before reading input in promptString method of animals example 2018-08-01 14:28:48 +00:00
Bob Nystrom 5f79c48f2b fix: add explicit C-style casts for malloc calls in resolution test helpers 2018-07-24 14:27:18 +00:00
Bob Nystrom b753039ee3 fix: add explicit char* cast for string literal assignment in runRepl
The assignment of a string literal to a non-const char* pointer triggers a C++
compiler warning about deprecated conversion. Adding the explicit cast silences
the warning while preserving the existing behavior, since the pointer is never
passed to free() or otherwise modified.
2018-07-24 14:21:41 +00:00
Bob Nystrom 3da64b9f8c feat: add placeholder file to force Git tracking of empty modules directory
Add an empty.txt file under test/language/module/use_nearest_modules_dir/a/wren_modules/ to ensure Git creates and tracks the directory structure, which would otherwise be omitted due to containing no files.
2018-07-24 14:15:04 +00:00
Bob Nystrom 4b160f017b feat: prevent calling root fiber and refactor fiber state tracking
Add explicit check in `runFiber()` to reject calls to the root fiber, preventing VM crashes when a completed fiber's caller tries to resume it. Replace the boolean `callerIsTrying` field with a `FiberState` enum (`FIBER_TRY`, `FIBER_ROOT`, `FIBER_OTHER`) to track fiber invocation mode, updating all relevant primitives and initialization. Include new test cases (`call_root.wren`, `call_wren_call_root.*`) and re-entrancy documentation notes.
2018-07-21 17:02:29 +00:00
Bob Nystrom daeff98b83 refactor: replace special METHOD_FN_CALL type with regular primitives for Fn.call() overloads
Remove the dedicated METHOD_FN_CALL method type and its associated arity-checking dispatch logic in the VM. Instead, define a shared `call()` helper that validates argument count and invokes `wrenCallFunction`, then generate individual `fn_call0` through `fn_call16` primitives via a macro. This eliminates the special-case method type while preserving identical behavior for all 17 call overloads.

Also rename the `fn` union member to `as` in the `Method` struct, update all references accordingly, and add a `benchmark_baseline` Makefile target for generating performance baselines.
2018-07-18 15:20:11 +00:00
Bob Nystrom 37147366f9 chore: add path.c and resolution.c to api_test target in XCode project
Add two new source files (path.c and resolution.c) to the PBXSourcesBuildPhase
of the api_test target in the wren XCode project file, ensuring they are
compiled as part of the test suite build.
2018-07-18 14:30:18 +00:00
Bob Nystrom 20a6571dc4 feat: add RFC-0001 proposal for smarter imports with relative and package resolution
Introduce a detailed RFC document outlining improvements to Wren's module import system, including relative import paths, package-based resolution, and ecosystem support. The proposal addresses current limitations where imports are always relative to the working directory, making code reuse across directories difficult. Key changes include supporting relative imports from the importing file's location and defining a package root mechanism for third-party dependencies.
2018-07-16 14:03:00 +00:00
Bob Nystrom 4ffd409e21 docs: add implementation status note to smarter-imports RFC
The note clarifies that the proposal is now mostly implemented, though
the actual implementation diverges from the original design described
in the document.
2018-07-16 14:02:53 +00:00
Bob Nystrom ab10e3248c feat: switch CI targets from test to api_test and add path resolution for relative imports
Replace the `test` make target with `api_test` in all CI build configurations (32/64-bit, debug/release, C/C++). Introduce a new `Path` abstraction with normalization, directory detection, and realpath resolution to support relative module imports (e.g., `"./cthulu"`). Update `runFile` and `runRepl` to return `WrenInterpretResult` instead of void, enabling proper exit codes on compile/runtime errors. Add `stat.h` for cross-platform file mode macros and a `wrenModulesDirectory` path for future package imports.
2018-07-16 14:00:08 +00:00
Bob Nystrom a8005feb21 chore: add Travis CI docs deployment job and update build dependencies
- Add automatic docs deployment stage for master branch pushes in .travis.yml
- Include python3-markdown, python3-pygments, python3-setuptools, and ruby-sass as build dependencies
- Switch from container-based to sudo-required builds with trusty dist for custom Pygments lexer installation
- Ensure build directory exists before generating docs in Makefile
2018-07-16 04:01:14 +00:00
Bob Nystrom 45368f1038 feat: add logical import support with wren_modules directory resolution and path type classification
Introduce a path type classification system (absolute, relative, simple) to distinguish logical imports from relative ones. Implement automatic discovery of a "wren_modules" directory by walking up from the root directory. Refactor the CLI to return interpret results and exit codes instead of exiting directly. Extract cross-platform stat macros into a shared header. Update test API calls to use explicit relative paths.
2018-07-16 03:09:41 +00:00
Bob Nystrom 305f43659d fix: replace deprecated libuv.py with update_deps.py and build_libuv.py in vs2017 PreBuildEvents
Update all four PreBuildEvent configurations (Debug Win32, Debug x64, Release Win32, Release x64) in the vs2017 wren.vcxproj to call the new update_deps.py and build_libuv.py scripts instead of the removed libuv.py download and build commands. Also append "vs2017" argument to the vcbuild.bat call in build_libuv_windows function to ensure correct toolchain selection.
2018-07-15 18:08:21 +00:00
Bob Nystrom ffc9ec950c feat: add trim, trimEnd, trimStart methods with optional chars argument to String class
Implement six new trimming methods on String: trim(), trim(chars), trimEnd(), trimEnd(chars), trimStart(), trimStart(chars). The core logic uses a private trim_ helper that accepts a chars string, converts it to code points, and iterates from the start and/or end of the string to remove matching characters. Default whitespace set is tab, carriage return, newline, and space. Includes comprehensive test coverage for default and custom character trimming, edge cases (empty strings, all-trimmed strings, 8-bit clean data), and runtime error when chars argument is not a string.
2018-07-15 17:48:56 +00:00
Bob Nystrom e6b216e1b0 feat: enable auto-deployment of docs to gh-pages branch from Travis CI 2018-07-15 04:35:33 +00:00
Bob Nystrom f4238a38e8 fix: replace smartypants package with python-smartypants in Travis config
The smartypants package name was incorrect for the Ubuntu distribution used in CI; switching to python-smartypants ensures the correct Debian/Ubuntu package is installed for text processing dependencies.
2018-07-15 04:00:59 +00:00
Bob Nystrom 7f598b72af fix: replace python3-smartypants with smartypants in travis addons
The previous package name python3-smartypants was incorrect for the Travis CI
build environment, causing package installation failures. This commit corrects
the package name to smartypants, which is the proper apt package for the
SmartyPants text processing library used in documentation generation.
2018-07-15 03:51:48 +00:00
Bob Nystrom b6d2ed4bb3 chore: add python3-smartypants to Travis CI addons apt packages 2018-07-15 03:44:22 +00:00
Bob Nystrom a3e64a59cc chore: add IDEWorkspaceChecks.plist for Xcode shared workspace data 2018-07-14 19:12:37 +00:00
Bob Nystrom 4a9e06bbed fix: install python3-pygments dependency for docs build on Travis CI 2018-07-14 19:12:07 +00:00
Bob Nystrom 41546e3bab fix: add python3-setuptools dependency for docs build in travis config 2018-07-14 18:57:11 +00:00
Bob Nystrom 9103d3d4ed fix: switch python commands to python3 in docs and deploy scripts
Update all references from `python` to `python3` in contributing guide and Travis deployment script to ensure compatibility with systems where `python` is not linked to Python 3. Also add missing `Description-Content-Type` metadata field to the Wren Pygments lexer egg-info.
2018-07-14 18:44:53 +00:00
Bob Nystrom d12ef41482 fix: correct python/sudo command order in deploy_docs_from_travis.sh
The previous commit mistakenly placed 'sudo' after 'python' in the
pygments lexer setup command, causing a permission error. This fix
reverses the order to 'sudo python setup.py develop', ensuring the
package installs with proper system privileges.
2018-07-14 18:17:36 +00:00
Bob Nystrom e93159ca5b fix: disable container-based Travis builds and switch to sudo-required trusty dist
The container-based infrastructure does not support sudo, which is needed to install the custom Pygments lexer for documentation generation. This change replaces the `sudo: false` directive with `sudo: required` and explicitly sets the distribution to `trusty`. Additionally, the deploy script is corrected to invoke `sudo python` instead of plain `python` when installing the lexer, ensuring the system-wide installation succeeds.
2018-07-14 18:05:41 +00:00
Bob Nystrom c7423bbcd9 feat: enable doc deployment on master pushes and install pygments lexer before build 2018-07-14 17:35:45 +00:00
Bob Nystrom d12463b82e chore: disable doc deployment job in Travis CI and add TODOs for known issues 2018-07-13 16:15:26 +00:00
Bob Nystrom bf5b66264f chore: rename deploy script and simplify travis condition to push-only
- Rename util/deployGHP.sh to util/deploy_docs_from_travis.sh for consistency
- Change deploy condition from excluding pull requests to explicitly requiring push events on master branch
2018-07-13 15:02:37 +00:00
Bob Nystrom 0ae4fd93d4 feat: add Travis CI auto-deploy script for GitHub Pages documentation 2018-07-13 14:46:46 +00:00
Bob Nystrom 6ed29286b3 fix: set correct soname to libwren.so for Linux shared library builds 2018-07-13 14:19:06 +00:00
Bob Nystrom 2c023eb8f1 docs: fix incorrect statement about file read/write after close in file.markdown
The documentation for the `close()` method on the File module incorrectly stated that reading or writing is still possible after closing the file. This commit corrects the description to accurately reflect that the file cannot be read from or written to after it has been closed.
2018-07-13 14:02:49 +00:00
Bob Nystrom d1d676b6f5 chore: add Charlotte Koch to AUTHORS and undefine FINALIZER macro in modules.c
Resolve merge conflict in AUTHORS by adding missing contributor entry.
Prevent macro leak by adding #undef FINALIZER after the module registry
definition in src/cli/modules.c, consistent with other macro cleanup.
2018-07-13 14:01:57 +00:00
Bob Nystrom a3ef71cd70 chore: add Michal Kozakiewicz to AUTHORS and guard Windows permission macros with ifndef 2018-07-13 13:53:34 +00:00
Bob Nystrom 52d65d48df fix: ensure expression compilation consumes all input by checking for EOF token
When compiling a single expression, the parser now explicitly consumes the TOKEN_EOF token after parsing the expression. This ensures that any trailing garbage or unexpected tokens after the expression are caught and reported as errors, rather than being silently ignored. The comment for the non-expression path is also updated to clarify that it checks for end of file rather than end of block.
2018-04-28 23:54:33 +00:00
Bob Nystrom be6c17558d fix: replace strncpy with memcpy and increase error message buffer size
Replace strncpy with memcpy in readBuiltInModule to avoid potential string termination issues
when copying module source code, and increase ERROR_MESSAGE_SIZE from 60 to 80 to provide
more room for compiler error messages with long variable names.
2018-04-28 23:38:09 +00:00
Bob Nystrom c3aad8049e fix: mark field symbol tables during class compilation to prevent GC from freeing field strings 2018-04-28 19:13:03 +00:00
Bob Nystrom 2b165f9649 refactor: replace raw String struct with ObjString* in symbol tables and GC handling
Migrate the internal `String` struct to use the heap-allocated `ObjString*` throughout the compiler, debugger, VM, and value system. This unifies string representation, enables proper garbage collection of symbol table entries via new `wrenBlackenSymbolTable` function, and removes manual memory management for symbol names.
2018-04-28 17:22:42 +00:00
Bob Nystrom 883754094a fix: remove redundant braces and update comment for UTF-8 BOM skip in wrenCompile 2018-04-28 17:07:04 +00:00
Bob Nystrom 91ddcea168 feat: skip UTF-8 BOM in source input and add regression test
Add handling for UTF-8 byte order mark (BOM) at the start of source code
in wrenCompile function by checking for the three-byte sequence \xEF\xBB\xBF
and advancing the source pointer past it. Include a regression test file
(test/regression/520.wren) that contains a BOM to verify the fix works
correctly.
2018-04-28 17:00:59 +00:00
Bob Nystrom 5c3d883204 fix: guard signature string overflow when too many parameters are passed
Add a MAX_PARAMETERS bound to the loop in signatureParameterList to prevent
buffer overflow when a method signature has an excessive number of parameters.
A compile error is already reported in such cases, but the unbounded loop could
still write past the end of the name buffer. Also add regression test 494.wren
to cover this scenario.
2018-04-27 16:13:40 +00:00
Bob Nystrom 248e3a69f0 fix: pre-allocate slot zero in every compiled chunk to fix REPL local variable declarations
The compiler now always reserves slot zero for either the closure or method
receiver, eliminating a corner case where top-level REPL code lacked the
pre-allocated slot that function/method bodies expect. This ensures local
variables declared in REPL loops (e.g. `for (i in 1..2)`) get correct slot
indexes.

Additionally, inlines `wrenResetFiber` into `wrenNewFiber` and stores the
imported module's closure on the stack before invoking it, preventing a GC
from collecting the closure during import.
2018-04-27 15:20:49 +00:00
Bob Nystrom 7bb024eccc docs: correct code examples in classes and concurrency docs
Fix two documentation errors: change `Foo.bar.printFromStatic()` to
`Foo.printFromStatic()` in classes.markdown, and replace `map` with `each`
in concurrency.markdown to match the actual Wren API.
2018-04-26 04:09:48 +00:00
Bob Nystrom 398fe71099 fix: reformat LICENSE text to match MIT template from choosealicense.com
The previous file used a non-standard preamble ("Wren uses the MIT License:")
and included an extra parenthetical clarification about binary distributions.
This commit rewrites the license body to exactly follow the standard MIT
License template published at https://choosealicense.com/licenses/mit/,
removes the custom header, and normalizes line wrapping so that GitHub and
other license detection tools correctly identify the project as MIT-licensed.
2018-04-23 23:48:47 +00:00
Bob Nystrom bc045f5492 fix: correct parameter cast in fileFinalize example to use 'data' instead of 'file' 2018-04-07 06:49:55 +00:00
Bob Nystrom ee7d881e19 fix: correct bindForeignMethod() example to check isStatic flag
The example code in the embedding documentation for bindForeignMethod() incorrectly used `!isStatic` when checking for a static method `Math.add(_,_)`. Changed the condition to `isStatic` so the example correctly demonstrates how to dispatch static foreign methods.
2018-03-26 14:52:26 +00:00
Bob Nystrom 5d0814f85d fix: correct argument count for import opcodes and fix field offset in bind method code 2018-03-26 14:50:49 +00:00
Bob Nystrom 5b9640909c fix: correct assertion check in wrenGetVariable to validate name instead of module
The assertion for the `name` parameter in `wrenGetVariable` was incorrectly checking `module != NULL` instead of `name != NULL`. This fix ensures the variable name parameter is properly validated, preventing potential null pointer dereferences when retrieving variables.

Additionally, adds Marshall Bowers to the AUTHORS file.
2018-03-26 14:50:16 +00:00
Bob Nystrom d11c0b0d4b fix: correct opcode argument counts and field offset in wrenBindMethodCode
The getNumArguments function had CODE_IMPORT_MODULE incorrectly returning 1 instead of 2, and CODE_IMPORT_VARIABLE returning 2 instead of 4. Additionally, wrenBindMethodCode had two bugs: it was incrementing ip before reading the instruction, causing incorrect opcode dispatch, and it was using ip++ instead of ip+1 for field offset adjustment, corrupting subsequent bytecode. The super instruction handling also incorrectly skipped over the symbol bytes before reading the constant index.
2018-03-26 14:49:54 +00:00
Bob Nystrom 80bb3ebad7 feat: implement relative import resolution with normalized paths and update all test modules
Replace the flat module name-to-path mapping with a proper relative import resolver that handles "./" and "../" prefixes relative to the importer's directory. This is a breaking change: existing imports in user code that assume paths are relative to the entrypoint file will now fail. Stack trace output and host API calls now use the resolved module string instead of the short import name. Update all test fixtures to use "./" relative imports and adjust C test files to pass the full resolved module path to wrenGetVariable.
2018-03-24 18:10:36 +00:00
Bob Nystrom c4532102e8 feat: add minimal path manipulation C module for internal VM use
Introduce a new `Path` struct and associated functions in `src/cli/path.c` and `src/cli/path.h` for resolving relative imports within the VM. The module provides operations such as normalization, directory extraction, extension removal, joining, and absolute path detection. Additionally, add a lightweight unit test framework under `test/unit/` with a `test.h`/`test.c` harness and `path_test.c` covering normalization cases. Update the build system (`Makefile`, `util/wren.mk`) to separate API tests from unit tests, rename the test executables to `api_wren` and `unit_wren`, and adjust CI targets and Python test scripts accordingly.
2018-03-24 17:52:16 +00:00
Bob Nystrom 761032c0fc feat: add WrenResolveModuleFn callback and module name parameter to wrenInterpret for relative import resolution
This breaking API change introduces a new `WrenResolveModuleFn` callback in the configuration that allows the host to canonicalize import module names, enabling relative imports. The `wrenInterpret()` function now requires a `module` parameter to specify the module name for the code being interpreted. The `wrenInterpretInModule()` function is removed in favor of the updated `wrenInterpret()`. The `metaCompile` function now dynamically looks up the caller's module name instead of hardcoding "main". New test files `resolution.c`, `resolution.h`, and `resolution.wren` are added to verify resolver behavior including null default, NULL return error, string rewriting, shared module deduplication, and importer propagation.
2018-03-23 14:54:09 +00:00
Bob Nystrom 9a8e46bd2d fix: add missing WrenVM* parameter to errorFn signature in documentation
The error callback function signature in the embedding documentation was missing the required WrenVM* first parameter, which would cause compilation errors for users following the example. The fix adds the vm parameter to the error function declaration in the configuring-the-vm markdown file.
2018-03-22 17:31:01 +00:00
Bob Nystrom 88ad0fc138 feat: replace module import string operand with direct ObjModule reference in IMPORT_VARIABLE
Add CODE_END_MODULE opcode to store the current ObjModule in vm->lastModule after module body execution. Modify IMPORT_VARIABLE to load variables from vm->lastModule instead of using a constant string operand for the module name. Update opcode definitions, debug dump, compiler import logic, and interpreter dispatch accordingly. Refactor variable lookup into getModuleVariable helper. Adjust formatting in wren_primitive.c and wren_opt_meta.c.
2018-03-20 13:54:51 +00:00
Bob Nystrom b4c20e8d7c fix: wrap Meta.compile result in Fiber.new to restore REPL execution 2018-03-19 21:08:04 +00:00
Bob Nystrom cf05cd7c8c refactor: change wrenCompileSource to return ObjClosure instead of ObjFiber and inline import execution
The compileInModule function now returns a closure directly instead of wrapping it in a fiber, simplifying the compilation pipeline and removing unnecessary fiber overhead for module imports. The wrenImportModule function is moved into wren_vm.c and rewritten to execute the imported module's closure immediately rather than returning a fiber for deferred execution. This change also adds a test for yielding from an imported module to verify correct behavior with the new execution model.
2018-03-17 16:33:33 +00:00
Bob Nystrom 2bbd385f69 refactor: consolidate duplicate wrenPopRoot calls in wrenCompileSource
Remove redundant NULL-check branches for module parameter by merging the
wrenPopRoot call into a single conditional after compileInModule, eliminating
the early return path and simplifying control flow in the compilation entry point.
2018-03-17 16:13:51 +00:00
Bob Nystrom 43a9501f7b feat: update vendored GYP to latest upstream with z/OS and MSVC SDK improvements
Replace the bundled GYP build system with a newer upstream version that adds z/OS platform support, improves MSVC SDK version detection with compatible SDK fallback, fixes host LDFLAGS handling in ninja generator, and includes various bug fixes and maintainer updates across multiple generator backends.
2018-03-14 15:06:06 +00:00
Bob Nystrom 3a1d93e2a8 fix: add unreachable return after switch in getNumArguments to fix compiler warning
The switch statement in getNumArguments covers all opcode cases, but the compiler
cannot prove exhaustiveness. Adding UNREACHABLE() followed by return 0 eliminates
the "control reaches end of non-void function" warning on strict compiler settings.
2017-11-01 05:07:07 +00:00
Bob Nystrom de5faf5108 fix: correct method examples in Range docs to use from/to/max instead of min
The documentation examples for the `from`, `to`, and `max` properties of the Range class were incorrectly using `.min` in their code samples. Updated the examples in `doc/site/modules/core/range.markdown` to call the correct methods: `.from` for the `from` property, `.to` for the `to` property, and `.max` for the `max` property, ensuring the printed output values match the documented behavior.
2017-10-31 23:24:58 +00:00
Bob Nystrom 981ea50407 feat: replace core library import calls with dedicated bytecode instructions
Replace the previous approach of desugaring import statements into calls to System.importModule() and System.getModuleVariable() with two new bytecode instructions: CODE_IMPORT_MODULE and CODE_IMPORT_VARIABLE. This eliminates the need for the corresponding primitive methods in the core library, adds proper debug dump support for the new opcodes, and updates the compiler to emit these instructions directly. The getNumArguments function is also updated to handle the new opcodes and the unreachable default case is removed.
2017-10-31 22:58:59 +00:00
Bob Nystrom 534551e604 fix: correct broken relative link for embedding API reference in getting-started doc
The link target for the embedded API reference was pointing to
`embedding-api.html` but the actual generated page uses the path
`embedding` without the `.html` extension. This change fixes the
link so it resolves correctly on the documentation site.
2017-10-31 21:04:37 +00:00
Bob Nystrom 7db8c32982 feat: add RFC proposal for smarter imports with relative and package resolution 2017-10-31 14:49:40 +00:00
Bob Nystrom aad58ab908 fix: add missing language specifier and variable declaration in C code example 2017-10-20 05:12:25 +00:00
Bob Nystrom 1be81bde81 feat: allow passing initial value to fiber function parameter on first call
When a fiber is started for the first time via call() or transfer(), the value argument is now bound to the fiber's function parameter if it takes one. Previously, the first value was always ignored. Also adds runtime error for fibers created with functions taking more than one parameter, and updates documentation and tests accordingly.
2017-10-20 03:45:13 +00:00
Bob Nystrom 3452b70666 docs: update Wren documentation examples to use string interpolation and clarify fiber and method call semantics
- Replace string concatenation with interpolation in class method examples
- Remove backticks from Fiber class references in concurrency docs
- Add guidelines for choosing between getters and empty-parentheses methods
- Clarify block syntax for single-expression functions and chaining
2017-10-20 02:52:05 +00:00
Bob Nystrom 7ea381d001 docs: clarify embedding API docs with precise wording and cross-references 2017-10-19 14:02:18 +00:00
Bob Nystrom 4018d42c39 docs: remove placeholder application-lifecycle page and complete first draft of embedding docs
- Delete the empty "Application Lifecycle" page (was just a TODO placeholder)
- Expand "Storing C Data" from stub to full documentation covering foreign classes, initialization, access, and finalization
- Add note that VM is not re-entrant; warn against calling wrenCall/wrenInterpret from foreign methods
- Fix broken cross-reference links (configuring-the-vm.html, wren.hpp include)
- Clarify slot API usage: remove confusing sentence about implicit return of receiver
- Fix grammar: "each VM them differently" → "each VM differently", "is only be called" → "is only called"
- Improve phrasing throughout for clarity and consistency
2017-10-17 15:26:06 +00:00
Bob Nystrom 8bd5b85df5 fix: switch REPL eval to use fiber execution and add explicit stdout flush
Replace `Meta.eval()` to compile source into a fiber instead of a function, fixing issue #456 where top-level variable declarations failed in the REPL. Add `Stdout` import and flush stdout before reading stdin since `System.print()` no longer auto-flushes. Refactor token detection to use `lexFirst()` instead of full `lex()`, and add new `Meta.compile()` method returning a fiber. Internally rename `wrenNewString` to `wrenNewStringLength` with explicit length parameter, updating all call sites across compiler, core, and meta modules.
2017-10-13 14:58:57 +00:00
Bob Nystrom 1d1e5d68ad feat: add servedocs make target and HTTP server to generate_docs.py
Add a new `servedocs` Makefile target that runs `generate_docs.py --serve`, enabling continuous doc generation and local web serving. Extend the Python script with `RootedHTTPServer` and `RootedHTTPRequestHandler` classes to serve generated HTML files from the output directory, refreshing content on each request via `format_files(True)`. Also update the shebang to `python3` and change the conversion print message from "converted" to "Built".
2017-10-12 13:38:34 +00:00
Bob Nystrom 5ab44d7203 fix: correct function name in comment for foreign allocate callback
The comment in the WrenForeignClassMethods struct incorrectly referenced
`wrenAllocateForeign` instead of the actual function `wrenSetSlotNewForeign()`.
This fixes the documentation to match the correct API function name that must
be called exactly once inside the allocate callback body.
2017-10-12 13:37:49 +00:00
Bob Nystrom 5098c37491 feat: add explicit Stdout.flush() and remove automatic flush on System.write()
Remove the automatic fflush(stdout) call from the write() function in vm.c, which was causing gratuitous performance overhead on every System.write() invocation. Introduce a new Stdout class with a foreign static flush() method that delegates to fflush(stdout), giving users explicit control over when output is flushed. Update the io module registration in modules.c to include the Stdout class and bump MAX_CLASSES_PER_MODULE from 5 to 6. Add documentation for Stdout in doc/site/modules/io/stdout.markdown, update the io index and template to list the new class, and add flush() usage notes to the Stdin readByte() and readLine() docs. Implement the stdoutFlush() foreign function in io.c.
2017-10-09 14:16:05 +00:00
Bob Nystrom 8b2994b6e4 fix: rename ClassCompiler typedef to ClassInfo across compiler source
Rename the internal `ClassCompiler` struct typedef to `ClassInfo` to better reflect its purpose as a descriptor for the enclosing class context during compilation. Update all variable declarations, function signatures, and references throughout `wren_compiler.c` to use the new type name, including in `getEnclosingClass`, `field`, `super_`, and `declareMethod` functions. This resolves issue #469 by eliminating the misleading "Compiler" suffix from a type that tracks class metadata rather than compilation state.
2017-10-09 13:47:42 +00:00
Bob Nystrom ffb15081f0 refactor: extract if-statement compilation into dedicated ifStatement helper 2017-10-08 17:47:31 +00:00
Bob Nystrom 2dd7578130 feat: add 17 non-crashing regression tests from wren-fuzz for issue #442
These test cases cover malformed class declarations, invalid string literals,
corrupted identifiers, and various edge cases that previously caused crashes
but now produce expected parse errors.
2017-10-08 17:15:15 +00:00
Bob Nystrom bd31425b5f fix: detect missing closing brace in block parsing to prevent crash
The compiler previously relied on `match(TOKEN_RIGHT_BRACE)` in the while loop condition, which consumed the brace and made it impossible to detect a missing one. Changed to peek-based loop termination and added explicit `consume` call for the closing brace, ensuring proper error reporting when '}' is absent. Added regression test for issue #429.
2017-10-08 17:03:42 +00:00
Bob Nystrom 623cc454e5 fix: parenthesize count argument in ALLOCATE_FLEX and ALLOCATE_ARRAY macros
Add parentheses around the `count` parameter in both `ALLOCATE_FLEX` and
`ALLOCATE_ARRAY` macro definitions to prevent operator precedence bugs when
the argument is an expression. Without this fix, expressions like
`sizeof(type) * n + 1` would be evaluated incorrectly due to `*` having
higher precedence than `+`.
2017-10-08 16:45:06 +00:00
Bob Nystrom 381ef53e84 fix: avoid undefined pointer difference behavior in wrenEnsureStack
When the fiber's stack is reallocated, pointer subtraction between old and new stack
addresses is undefined behavior. Instead of computing an offset and adding it to each
pointer, recalculate each pointer relative to the new stack base using well-defined
arithmetic within the single array. This affects the apiStack, call frame stackStart
pointers, open upvalue values, and the stackTop pointer.
2017-10-08 16:42:35 +00:00
Bob Nystrom 168d6d75b5 feat: add Num.round method for rounding numbers to nearest integer
Implement the `round` method on the Num class in the Wren VM, which rounds a number to the nearest integer using standard rounding rules (away from zero for .5). The implementation adds a new `DEF_NUM_FN(round, round)` macro invocation in `wren_core.c`, registers the corresponding primitive `num_round`, and includes comprehensive documentation in the core module reference. A new test file `test/core/number/round.wren` validates behavior for positive, negative, zero, and fractional values. Also adds Kyle Charters to the AUTHORS file.
2017-10-06 14:51:55 +00:00
Bob Nystrom eecc18244f fix: abort all fibers along call chain when one fiber errors
In runtimeError, walk the entire fiber call chain and set each fiber's error field to the same error value, unhooking callers as we go. Previously only the immediate caller was considered, leaving intermediate fibers in an inconsistent state. This ensures that when a fiber aborts, every fiber in the chain up to (but not including) the one that catches the error via try() is properly marked as errored.

Also remove the old nested fiber tests from try.wren and add a new comprehensive test (try_through_call.wren) that verifies the percolation behavior through multiple levels of fiber calls and confirms that intermediate fibers carry the error while the catching fiber and its callers remain clean.
2017-10-06 14:39:00 +00:00
Bob Nystrom 85c4e9aa57 fix: propagate aborted fiber error check before call and unwind caller chain in runtimeError
Move the aborted fiber check in runFiber to execute before the "already called" check, ensuring a clear error message for aborted fibers. In runtimeError, replace the single caller unhook with a loop that walks the fiber chain, preserving the callerIsTrying flag and only unhooking fibers until a try-catch boundary is found, enabling proper error propagation through nested fiber calls. Add test cases for one and two levels of nested fiber try calls.
2017-10-06 13:58:27 +00:00
Bob Nystrom 42ac5a33a5 docs: remove obsolete comment block about foreign method return value constraints in wren.h 2017-10-05 13:51:48 +00:00
Bob Nystrom 39983d6246 docs: clarify Fiber.abort and error behavior with null handling and updated examples 2017-10-05 13:50:45 +00:00
Bob Nystrom 72e6bca610 fix: restrict libuv build to library target on Linux skipping tests 2017-04-09 16:58:00 +00:00
Bob Nystrom 82bba89a3b fix: correct index from 2 to 1 when accessing arch argument in main function
The off-by-one error caused the arch argument to be read from args[2] instead of args[1], which would either read an out-of-bounds index or pick the wrong argument when exactly two arguments were provided. This fix ensures the optional architecture parameter is correctly retrieved from the second command-line argument.
2017-04-09 16:37:27 +00:00
Bob Nystrom f25778d874 feat: vendor GYP and libuv dependencies directly into repository for offline builds
Remove dynamic dependency download during build by checking in libuv source and GYP build tooling. Update .gitignore to exclude intermediate build artifacts from the vendored deps directory, adjust Makefile to remove the now-unnecessary cleanall target and deps folder cleanup, and add the full libuv project tree including its own .gitignore, .mailmap, AUTHORS, CONTRIBUTING.md, ChangeLog, and LICENSE files.
2017-04-09 16:31:44 +00:00
Bob Nystrom 5916a401de fix: correct broken embedding link in README to point to new URL path
The embedding API reference link was pointing to the old `embedding-api.html` path, which would result in a 404. Updated it to the correct `embedding/` path to ensure users can access the documentation.
2018-02-20 22:23:39 +00:00
Bob Nystrom c332ca35fd fix: remove duplicate floating_point.wren test file that was identical to integer range tests
The deleted test file `test/core/range/floating_point.wren` was a direct copy of the integer range test file, testing `.from` on integer ranges rather than actual floating-point ranges. This removal resolves issue #438 by eliminating the redundant test that provided no coverage for floating-point range behavior.
2017-04-08 19:53:33 +00:00
Bob Nystrom 3f148df007 chore: remove msvc2013 projects and add vs2017 solution with x64 support
Delete the entire util/msvc2013 directory containing Visual Studio 2013 solution and project files. Add new util/vs2017 directory with updated solution targeting Visual Studio 2017 (v141 toolset) and supporting both Win32 and x64 platforms. Update .gitignore to ignore .vs/ and obj/ directories. Modify build_libuv_windows in util/libuv.py to accept an arch parameter and pass x86 or x64 to vcbuild.bat.
2017-04-08 19:48:47 +00:00