Commit Graph
100 Commits
Author SHA1 Message Date
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 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 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 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
Bob Nystrom c749d3a9a2 fix: correct grammar in module loader documentation sentence 2017-04-08 19:40:31 +00:00
Bob Nystrom 1f4c0975d0 fix: free dynamically allocated module source strings after compilation
When a module is loaded via the host's loadModuleFn callback, the source string is dynamically allocated and ownership is transferred to the VM. Previously, this memory was never freed after compilation, causing a leak. This change introduces an `allocatedSource` flag that tracks whether the source was dynamically allocated (host-provided) or a static constant (built-in modules like "random"). After `loadModule` completes, the source is freed if it was dynamically allocated, resolving the memory leak described in issue #430.
2017-04-08 19:38:36 +00:00
Bob Nystrom 560053aa0d fix: correct typos in documentation for foreign method binding and bitwise or description 2017-04-04 14:07:57 +00:00
Bob Nystrom 5803c8bb58 feat: add wren.hpp convenience header for C++ users linking to C Wren library 2017-03-25 17:05:33 +00:00
Bob Nystrom 479bf3b1a8 docs: add Blondie instance construction example to functions documentation
- Insert `var blondie = Blondie.new()` code snippet in functions.markdown
- Address issue #432 requesting explicit instance creation demonstration
2017-03-24 04:22:07 +00:00
Bob Nystrom 184126372c fix: set token type to TOKEN_ERROR after invalid character to prevent compiler loop
When the lexer encounters an invalid character, it now explicitly sets the
current token's type to TOKEN_ERROR and its length to 0. Previously, the
token retained the previous token's type, which could cause the compiler
to get stuck in an infinite loop in certain code paths.

Also improves the error message for non-ASCII invalid bytes by showing
the raw hex value instead of attempting to display the character, since
the lexer operates on raw bytes without UTF-8 decoding.

Adds regression test for issue #428 that was crashing the compiler with
an out-of-bounds memory access due to this loop.
2017-03-24 04:19:20 +00:00
Bob Nystrom 9b0d2aefb6 feat: add user_data API test and reorder WrenErrorFn vm parameter to first position
Add a new test suite for user data get/set operations on WrenVM, including
a Wren script that validates default NULL userData, retrieval after VM
creation, and mutation via wrenSetUserData. Also reorder the vm parameter
in WrenErrorFn callback signature and all its call sites to match the
convention used by other callback types, updating the typedef, the
reportError implementation, and all invocations in the compiler and
debug modules. Include the new source and header files in the Xcode
project build configuration.
2017-03-22 14:26:19 +00:00
Bob Nystrom 6c756c0c67 feat: add userData field and pass WrenVM* to error callback
Extend WrenConfiguration with a void* userData field for attaching arbitrary state to a VM instance. Add wrenGetUserData and wrenSetUserData accessor functions. Modify the WrenErrorFn typedef and all call sites (compiler, debug, VM) to pass the WrenVM pointer as the final argument, enabling error handlers to access VM context.
2017-03-22 14:12:26 +00:00
Bob Nystrom dad494093e feat: add validation to skip/take and rename split parameter for clarity
Add type and range checks to Sequence.skip() and Sequence.take() methods, aborting with "Count must be a non-negative integer." when count is not a non-negative integer. Rename split() parameter from 'delim' to 'delimiter' and update its error message from "Argument must be a non-empty string." to "Delimiter must be a non-empty string." for consistency. Remove old behavior allowing negative counts and add new test files for skip/take validation errors.
2017-03-15 14:22:44 +00:00
Bob Nystrom 38b92435bf feat: add lazy skip and take methods to Sequence with SkipSequence and TakeSequence classes
Implement `skip(count)` and `take(count)` on the Sequence class, backed by new SkipSequence and TakeSequence wrapper classes that lazily skip or limit iteration. Includes documentation in the sequence module markdown, core source definitions, and unit tests for edge cases (zero, negative, and overflow counts).
2017-03-15 14:15:00 +00:00
Bob Nystrom 10928fb5de chore: replace C++-style comments with C-style in callForeign function 2017-03-15 14:10:23 +00:00
Bob Nystrom cb2f45487b fix: restore apiStack after foreign method calls instead of setting to NULL 2017-03-15 14:09:31 +00:00
Bob Nystrom 996ba2b2cd fix: correct typo "seperator" to "separator" in string.markdown docs
Fix three occurrences of the misspelled word "seperator" in the string module
documentation, updating both the function signature header and the descriptive
text in the split() method section.
2017-03-15 14:06:07 +00:00
Bob Nystrom f96d2e3b8b feat: add split and replace methods to String class with tests and docs
Implement String.split(delim) and String.replace(from, to) methods in the core Wren VM. split returns a list of substrings separated by the given delimiter, while replace returns a new string with all occurrences of the old substring replaced by the new one. Both methods validate arguments (must be non-empty strings) and abort the fiber on invalid input. Include comprehensive test suites covering basic usage, multiple matches, non-ASCII characters, 8-bit clean data, and error cases. Update the string.markdown documentation with usage examples for both methods.
2017-03-15 14:04:56 +00:00
Bob Nystrom 414df30cdc test: add wrenSetSlotNull call and verify slot type in setSlots test 2017-03-03 15:57:50 +00:00
Bob Nystrom 8e926f12d8 docs: document libm linking requirement for Wren on BSD/Linux platforms 2017-03-02 15:17:03 +00:00
Bob Nystrom 4f9034fc8e docs: proofread configuring-the-vm guide for clarity and consistency
Reworded opening paragraph to improve flow and remove redundant phrasing.
Updated description of wrenInitConfiguration to emphasize prevention of uninitialized configuration.
Changed "the VM" to "Wren" in loadModuleFn description for consistent terminology.
2017-02-12 22:58:16 +00:00
Bob Nystrom ecf3b7081b docs: replace placeholder TODO with full VM configuration documentation and fix typo in wren.h
Replace the stub "TODO: Write these docs." in configuring-the-vm.markdown with comprehensive documentation covering all WrenConfiguration fields including binding callbacks, memory management, and error handling. Also fix the typo "phyisically" to "physically" in the wren.h header comment and remove trailing whitespace on several lines.
2017-02-12 19:04:38 +00:00
Bob Nystrom 63f46adf06 docs: revise embedding docs with foreign methods and tighten existing pages 2017-02-12 18:14:37 +00:00
Bob Nystrom 65d4481fae docs: add documentation for Num.log and Num.pow() methods in core module 2017-01-20 15:24:46 +00:00
Bob Nystrom be7682a656 feat: add log and pow methods to Num class with tests
Adds `log` method to Num class via DEF_NUM_FN macro, and `pow(_)` method via a new DEF_PRIMITIVE that calls C's `pow()`. Registers both primitives in wrenInitializeCore. Includes new test files `test/core/number/log.wren` and `test/core/number/pow.wren` covering basic cases and edge values (negative input for log, zero exponent for pow). Also adds Sven Bergström to AUTHORS.
2017-01-20 15:20:55 +00:00
Bob Nystrom 08a868ce3f fix: remove negative number bitwise not tests relying on undefined C behavior 2017-01-13 06:17:33 +00:00
Bob Nystrom b73b5e562a docs: add comment clarifying ci targets are used by Travis CI in Makefile 2017-01-13 05:55:35 +00:00
Bob Nystrom 1b635d029a fix: replace strtol with strtoll for 64-bit hex literal parsing on 32-bit platforms
The previous implementation used strtol() for parsing hex literals, which only supports up to 32-bit values on 32-bit architectures. This caused hex literals larger than 0x7FFFFFFF to overflow or fail. Changed to strtoll() which guarantees 64-bit parsing regardless of platform word size.

Also updated the error message to include the actual sizeof(long int) for debugging, uncommented the previously disabled 64-bit hex literal examples in syntax.wren, and added a test case for 0xdeadbeef to verify the fix works correctly.
2017-01-13 05:53:21 +00:00
Bob Nystrom cd6b97d341 chore: remove debug prints and add app path to test status line
Remove the two debug print statements for WREN_APP and TEST_APP paths that were cluttering test runner output. Update the status line format to include the relative path of the test application being run, making it clearer which binary's results are being reported when running multiple test suites.
2017-01-13 05:38:06 +00:00
Bob Nystrom 2620b34c8e fix: replace fpclassify with isnan/isinf for C++98 compatibility in wrenNumToString
The fpclassify() macro is not available in C++98, causing build failures on older compilers. This commit replaces the switch on fpclassify with explicit isnan() and isinf() checks, handling NaN and infinity edge cases directly. The logic for signed infinity is preserved by comparing value > 0.0 instead of using signbit(), which is also not guaranteed in C++98. This aligns with the existing usage of isnan/isinf elsewhere in the Wren codebase.
2017-01-13 05:34:11 +00:00
Bob Nystrom 54bc22efc0 fix: replace decimal u32 overflow test values with hex literals and remove undefined-behavior tests
The bitwise operator tests used decimal literals exceeding u32 range, causing undefined behavior when converting double to u32 on some compilers. This replaces those values with hex equivalents that fit within u32, removes tests for values past max u32, and adds TODO comments for future handling. Also simplifies the `num_bitwiseNot` primitive by removing the intermediate `wideVal` variable, and fixes minor formatting in `util/test.py`.
2017-01-13 05:32:50 +00:00
Bob Nystrom e9c337e2a5 feat: add multi-arch CI matrix with osx/linux, nan-tagging toggle, and 32/64-bit test targets 2017-01-13 04:19:52 +00:00
Bob Nystrom 8fa482c9ca fix: correct nextGC calculation to use additive heap growth instead of multiplicative
The previous formula `bytesAllocated * (100 + growthPercent) / 100` incorrectly
treated `heapGrowthPercent` as a multiplier on total heap size relative to
in-use memory, rather than as an additive percentage of current allocation.
The new formula `bytesAllocated + (bytesAllocated * growthPercent / 100)`
correctly computes the next GC threshold as the current allocation plus a
configured percentage of that allocation, matching the documented intent of
the configuration parameter.
2017-01-13 02:53:14 +00:00
Bob Nystrom 054fbd2f6c docs: clarify single-expression block restrictions and statement workaround
Add explanation that single-expression blocks cannot contain statements
(like class, for, if, import, return, var, while) since they don't
produce values, and show how to use a newline to create a block with
a single statement instead. Fixes #390.
2017-01-12 19:05:03 +00:00
Bob Nystrom 2294046b74 docs: improve clarity and flow in embedding documentation
Refine phrasing in the embedding guide for better readability: change "generate a runtime error" to "generate runtime errors", reword "What that gives you in return" to "What you get in return", and replace "get to the public header" with "find the public header" for more natural expression.
2017-01-12 15:11:01 +00:00
Bob Nystrom 25b1afcd2b docs: expand calling-c-from-wren with foreign method/class details and fix typo in slots-and-handles 2017-01-12 15:10:19 +00:00
Bob Nystrom 6e8a798959 fix: reset API stack to NULL when fiber is aborted in wrenCall to prevent broken state on reuse 2016-11-01 15:40:16 +00:00
Bob Nystrom 77f7f759ff fix: free libuv request data before resuming fiber on error in handleRequestError 2016-11-01 15:39:30 +00:00
Bob Nystrom d50275eae0 fix: correct variable reference in chained assignment test assertion
The test for chained assignment was incorrectly printing variable `a` twice instead of printing `b` for the second assertion. This fix changes the second `System.print(a)` to `System.print(b)` so the test correctly verifies that both `a` and `b` hold the value "chain" after the chained assignment `a = b = "chain"`.
2016-10-08 17:51:19 +00:00
Bob Nystrom 8d3a7eabb9 fix: reset apiStack to NULL after foreign constructor returns to prevent broken state on subsequent wrenCall 2016-08-28 15:23:27 +00:00
Bob Nystrom a82c4d7263 fix: parenthesize macro parameter in BOOL_VAL to prevent operator precedence bugs 2016-08-28 04:44:39 +00:00
Bob Nystrom 17777ef0ce feat: add --version flag to CLI main entry point printing WREN_VERSION_STRING
When invoked with exactly two arguments where the second is "--version", the
main function now prints the version string (e.g. "wren 0.4.0") and exits
successfully before any other initialization occurs.
2016-08-28 00:38:14 +00:00
Bob Nystrom c29f3e694f fix: replace DBL_EPSILON with DBL_MIN for Num.smallest in wren_core.c
Change the C implementation of `num_smallest` primitive to return `DBL_MIN` instead of `DBL_EPSILON`, correcting the value from the machine epsilon (difference between 1.0 and next representable value) to the smallest positive representable double. Update the documentation in `num.markdown` to describe `Num.smallest` as "the smallest positive representable numeric value" and `Num.largest` as "the largest representable numeric value". Add test files `largest.wren` and `smallest.wren` verifying the expected output values.
2016-08-28 00:25:32 +00:00
Bob Nystrom 5f6e06e1b5 feat: add Num.largest and Num.smallest static properties for float limits
Add two new static properties to the Num class: `Num.largest` returns `DBL_MAX`
and `Num.smallest` returns `DBL_EPSILON`. Include corresponding documentation
in the core module markdown and register the primitives in the VM core
initialization.
2016-08-28 00:18:21 +00:00
Bob Nystrom 879eac5d82 docs: reword embedding docs for clarity and consistency across slot, handle, and C-calling-Wren pages 2016-08-26 14:11:50 +00:00
Bob Nystrom 53b1120f90 fix: add const qualifier to SymbolTable parameter in wrenSymbolTableFind
The function signature in both the declaration (wren_utils.h) and definition
(wren_utils.c) is updated to accept a const SymbolTable* instead of a
non-const pointer, enabling callers to pass const-qualified symbol tables
without casting away constness.
2016-08-16 14:43:54 +00:00
Bob Nystrom 409873c382 perf: replace O(n) linear scan with O(1) map lookup for constant deduplication in compiler
Replace the linear scan of the function's constant table in `addConstant()` with a hash map lookup using a new `ObjMap* constants` field on the `Compiler` struct. This avoids O(n) performance degradation when compiling functions with many constants, such as large literal-heavy functions. The map stores constant values as keys and their index as numeric values, lazily initialized on first insertion. Also adds OBJ_FN hashing support in `hashObject()` to allow bare function objects as map keys internally, and includes a regression test with 65,550 constant entries to validate the fix.
2016-08-16 14:43:34 +00:00
Bob Nystrom 3ff11eb9f3 feat: deduplicate constants in addConstant to reuse existing values
Add linear scan in addConstant() to check for duplicate constant values before appending. This reduces memory usage for repeated constants and enables support for functions with large numbers of repeated entries. Includes TODO noting O(n) complexity for future optimization.
2016-08-16 14:24:04 +00:00
Bob Nystrom 5703a8dfa2 docs: add List.filled and List.new constructors to core module docs 2016-08-04 13:28:41 +00:00
Bob Nystrom bfb109473e feat: remove List.new(_) constructor and consolidate into List.filled(_,_)
Remove the List.new(_) primitive that initialized a list with null elements, merging its functionality into List.filled(_,_) which now accepts both size and default value. Add validation for negative size with a clear error message, and introduce comprehensive test coverage for filled list creation including edge cases for negative size, non-integer size, and non-numeric size arguments.
2016-08-04 05:42:31 +00:00
Bob Nystrom 85ab5d2aec feat: add List.new(_) and List.filled(_,_) constructors with size and default value
Add two new list constructors to the Wren VM: `List.new(size)` creates a list of given size with null elements, and `List.filled(size, value)` creates a list with all elements initialized to a specified default value. Includes corresponding C primitives `list_newWithSize` and `list_newWithSizeDefault`, registration in `wrenInitializeCore`, and a test file verifying both constructors produce correct counts and element values. Also adds Max Ferguson to AUTHORS.
2016-08-04 05:34:08 +00:00
Bob Nystrom 59a6fc1bcc feat: add negative start support and validate index in String.indexOf(_,_)
Simplify arithmetic in wrenStringFind by removing startIndex offset from loop range and using start directly as the initial index. Rename internal primitives to string_indexOf1 and string_indexOf2 for clarity. Add validateIndex helper to clamp negative start values and reject out-of-bounds indices. Update documentation to describe the new start parameter behavior. Add comprehensive test suite for indexOf with start, including negative offsets, edge cases, and error conditions.
2016-08-04 05:19:34 +00:00
Bob Nystrom 48b69a7c43 feat: add startIndex parameter to string indexOf and update internal find function
Add a new `indexOf(_,_)` primitive that accepts a start index for searching within strings, and modify the existing `wrenStringFind` function to accept and use a start index parameter. The existing `indexOf(_)` and `contains(_)` methods now pass 0 as the start index to maintain backward compatibility. The Boyer-Moore-Horspool search algorithm is updated to offset comparisons by the start index and return the absolute position in the original string. New test cases verify correct behavior with various start index values including edge cases where the start index exceeds string length.
2016-08-04 04:51:46 +00:00
Bob Nystrom 0e4503726e fix: correct bytecode offset calculation in debug dump macro
The `DEBUG_TRACE` macro was using `fn->bytecode` instead of `fn->code.data` to compute the instruction offset for `wrenDumpInstruction`. This caused incorrect offset values when dumping bytecode during interpreter tracing, as the bytecode pointer is stored in the `code.data` field of the function object.
2016-08-04 04:45:09 +00:00