Commit Graph
100 Commits
Author SHA1 Message Date
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
Bob Nystrom 5f8794fdc2 refactor: rename list C API functions and remove Slot suffix for consistency
- Rename wrenGetSlotListSize to wrenGetListCount and wrenGetSlotListValue to wrenGetListElement
- Change wrenGetListElement to move element directly to another slot instead of returning WrenValue
- Update all test bindings and calls to match new API signatures
2016-07-28 15:06:36 +00:00
Bob Nystrom 21a0eef834 feat: add wrenGetSlotListSize and wrenGetSlotListValue API functions for list introspection
Add two new C API functions to the Wren VM that allow foreign methods to query the size of a list stored in a slot and retrieve individual values from it by index. The implementation validates the slot holds a list, extracts the internal ValueBuffer, and returns the count or a captured WrenValue respectively. Corresponding test bindings (getListSize, getListValue) and Wren test cases are included to verify the new functionality.
2016-07-28 14:53:19 +00:00
Bob Nystrom 4d1215697e feat: add MapEntry class and make Map a Sequence for direct iteration
Add MapEntry class to expose key-value pairs during map iteration, and make Map extend Sequence so maps can be directly iterated with `for` loops. Rename the internal `iterate_` primitive to `iterate` and update error messages for invalid map iterators.
2016-07-06 14:17:07 +00:00
Bob Nystrom a05f50ee24 feat: add VERBOSE=1 support to suppress @ prefix in Makefile targets
Introduce a V variable controlled by the VERBOSE environment flag across both the top-level Makefile and util/wren.mk. When VERBOSE=1 is set, V expands to empty, making all recipe lines echo their commands; otherwise V defaults to @, preserving silent builds. This replaces hardcoded @ prefixes on every recipe line with $(V), enabling developers to toggle verbosity without editing makefiles.
2016-07-06 13:51:12 +00:00
Bob Nystrom ff9764bc4d fix: return false instead of NULL in findEntry for empty map capacity check 2016-07-06 13:46:35 +00:00
Bob Nystrom d955842cf9 perf: add hashBits mixing function to fix integer hash collisions in map
The raw XOR of double's 32-bit halves causes small integers to have zero low bits,
mapping all small integer keys to entry zero in the hash map. This introduces a
bit-mixing function inspired by Java's HashMap that sloshes high bits downward,
eliminating the pathological collision pattern. The map_numeric benchmark improves
by ~18%, and a contrived benchmark with keys up to 1000 becomes 52x faster.
2016-06-27 15:13:45 +00:00
Bob Nystrom adad9f4b26 fix: prevent duplicate keys by reusing tombstones in map probe sequence
Previously, when inserting a key that already existed in the map but was
located after a tombstone in the probe sequence, the insertion would stop
at the first tombstone and add the key there, resulting in duplicate
entries for the same key. This fix introduces a `findEntry` function that
tracks the first encountered tombstone during probing and reuses it for
insertion only when the key is not found elsewhere in the sequence.
2016-06-27 14:14:52 +00:00
Bob Nystrom a44b210191 fix: allow optional module loading when host omits loadModuleFn
Previously, wrenImportModule unconditionally called vm->config.loadModuleFn,
causing a crash when the host did not set that function pointer. Now the
call is guarded by a NULL check, so hosts without a module loader can still
load built-in optional modules like "random" or "meta".
2016-06-27 14:08:08 +00:00
Bob Nystrom b7de67aa20 fix: move tty reset inside stdin stream guard to avoid resetting when stream not owned 2016-05-27 14:01:10 +00:00
Bob Nystrom 72a0d8cf51 fix: reset TTY mode before closing stdin stream in shutdownStdin
Move the uv_tty_reset_mode() call to execute before uv_close() on the stdinStream handle, ensuring the terminal is restored to normal mode prior to stream closure rather than after.
2016-05-27 13:59:43 +00:00
Bob Nystrom 15eb651d1f refactor: extract character handling into separate method and add ANSI fallback support
Extract the inline character processing logic from the REPL's main loop into a dedicated `handleChar()` method that returns a boolean to indicate whether the loop should exit. Add `_allowAnsi` flag and corresponding getter/setters for cursor and line to support a simpler fallback REPL when ANSI escape sequences are unavailable.
2016-05-24 02:59:01 +00:00
Bob Nystrom 69498a4893 feat: add tab-completion in REPL and Meta.getModuleVariables API
Add tab-completion support to the interactive REPL by introducing a new `Meta.getModuleVariables` foreign method that returns all top-level variable names from a given module. The REPL's `run()` method now handles the tab key to append completions, and the `refreshLine` method accepts a boolean parameter to control whether completion hints are shown. Also fix the Ctrl-D exit logic (inverted condition) and remove the unused `EscapeBracket` class.
2016-05-22 22:32:17 +00:00
Bob Nystrom 38462ba4ed feat: add ctrl-b/f/k/l/u/n/p shortcuts to repl line editor
Implement cursor movement (ctrl-b left, ctrl-f right), line clearing (ctrl-k kill after cursor, ctrl-u clear entire line, ctrl-l clear screen), and history navigation (ctrl-n next, ctrl-p previous) in the repl module, along with updated TODO comments for future shortcuts.
2016-05-21 17:33:36 +00:00
Bob Nystrom 5207686395 feat: add command history with up/down arrow navigation to REPL
Implement a history buffer in the REPL class that stores previously entered commands and allows cycling through them using the up and down arrow keys. The `_history` list and `_historyIndex` track the current position, with `previousHistory()` and `nextHistory()` methods restoring lines from the buffer or clearing the input when reaching the end. The `executeInput()` method now appends the current line to history before resetting, and the Ctrl-D exit condition is fixed to check `_line.isEmpty` instead of `_line == ""`.
2016-05-21 17:05:28 +00:00
Bob Nystrom c726845c42 feat: implement expression evaluation and statement detection in REPL with Meta.compileExpression
Add executeInput() method to REPL that lexes input, determines if it's a statement or expression based on the first token, and evaluates accordingly using Meta.eval for statements or the new Meta.compileExpression for expressions. Extend Meta.compile_ foreign method with isExpression and printErrors parameters, update wrenCompile signature to support expression compilation mode, and add newline handling after equals in variable definitions.
2016-05-21 06:03:05 +00:00
Bob Nystrom 33c211f7c2 feat: implement interactive REPL with line editing and syntax highlighting in Wren
Replace the simple fgets-based REPL loop with a full-featured interactive Wren REPL module. The new implementation supports cursor movement via arrow keys, Ctrl-A/E for line start/end, Ctrl-C/D for exit/delete, character insertion/deletion, and syntax highlighting of the current input line. The C side now imports the "repl" Wren module and runs the libuv event loop instead of blocking on stdin reads.
2016-05-21 03:30:09 +00:00
Bob Nystrom 1de17224e8 feat: add wrenAbortFiber() API to abort current fiber with runtime error object
Add a new public API function `wrenAbortFiber()` that allows foreign methods to abort the currently executing fiber with a custom runtime error object. The function validates the API slot, then sets the fiber's error field to the value in the specified slot. The interpreter loop is updated to check for a non-null fiber error after calling a foreign method, triggering a runtime error if set. New test files (error.c, error.h, error.wren) demonstrate usage via a static Error.runtimeError foreign method, verifying that the error is propagated through Fiber.try() and that the fiber's isDone and error properties are correctly set. Xcode project updated to include the new error.c source file.
2016-06-10 02:14:21 +00:00
Bob Nystrom 78fa150869 fix: correct broken range documentation link to point to values section 2016-05-27 14:23:41 +00:00
Bob Nystrom b845ff49c9 docs: fix relative link to iterator protocol in string.markdown
The link to the iterator protocol section in control-flow.html was incorrectly
pointing to `../control-flow.html` instead of `../../control-flow.html`, which
is the correct relative path from the `doc/site/modules/core/` directory.
2016-05-27 14:23:07 +00:00
Bob Nystrom 7768d1c9cd feat: add Platform.isWindows static method to check for Windows OS
Add a new `isWindows` static method to the `Platform` class that returns `true` when the host operating system name equals "Windows". This provides a less stringly-typed API compared to checking `Platform.name` directly. The implementation is a simple delegation to the existing `name` foreign method, comparing it against the "Windows" string. Includes a test that verifies `Platform.isWindows` is equivalent to `Platform.name == "Windows"`.
2016-05-21 19:53:21 +00:00
Bob Nystrom 67bf74777c feat: add Stdin.isTerminal method to detect TTY connection
Add a new `isTerminal` static method to the Stdin class that returns `true` when
stdin is connected to a TTY (interactive terminal) and `false` when input comes
from a pipe. Implementation uses libuv's `uv_guess_handle` to check the stdin
descriptor. Includes documentation, foreign method declaration, module
registration, and a test expecting `false` since tests run non-interactively.
2016-05-21 19:51:11 +00:00
Bob Nystrom 95ef1a2814 feat: rename process module to os and add Platform class with name and isPosix methods
Rename the "process" module to "os" across all source files, documentation, tests, and build configuration. Add a new Platform class to the os module with static methods `name` (returns OS string like "Windows", "Linux", "OS X", "iOS", "Unix", "POSIX", or "Unknown") and `isPosix` (returns bool indicating POSIX compliance). Update all import paths from "process" to "os" in test files and module registrations. Move process.c/h to os.c/h, rename processSetArguments to osSetArguments, and regenerate the os.wren.inc bytecode source. Add documentation pages for the os module and Platform class.
2016-05-21 19:44:17 +00:00
Bob Nystrom c5e1c2e57f feat: add versioning infrastructure and bump to 0.1.0
Define WREN_VERSION_MAJOR, WREN_VERSION_MINOR, WREN_VERSION_PATCH macros,
WREN_VERSION_STRING "0.1.0", and WREN_VERSION_NUMBER for monotonic checks.
Update REPL banner to use WREN_VERSION_STRING instead of hardcoded "v0.0.0".
Create CHANGELOG.md documenting the first declared version.
2016-05-21 17:53:05 +00:00
Bob Nystrom caee692c32 docs: rename WrenValue to WrenHandle across embedding docs and C API
Rename the `WrenValue` type to `WrenHandle` in the public C header, update all
function signatures (`wrenMakeCallHandle`, `wrenCall`, `wrenReleaseHandle`),
and rename the documentation page from "Slots and Values" to "Slots and Handles"
with corresponding link updates throughout the embedding guide and module source
files.
2016-05-21 03:55:28 +00:00
Bob Nystrom efa97cdccf feat: add Stdin.isRaw property to query and set terminal raw mode on stdin
Add foreign static getter `isRaw` and setter `isRaw=(value)` to the Stdin class, backed by a new `isStdinRaw` boolean flag and `uv_tty_set_mode` calls. The getter returns the current raw mode state, while the setter initializes the stdin stream if needed and applies raw or normal mode only when stdin is a TTY. Also includes a test file verifying default false, reading bytes in normal mode, enabling raw mode, and reading subsequent bytes.
2016-05-20 22:19:18 +00:00
Bob Nystrom 6394e1c486 feat: add Stdin.readByte() method for reading single byte from stdin
Implement a new `readByte()` static method on the `Stdin` class that reads one byte from standard input, blocking the current fiber until a byte is received. The method returns the byte value as a number or `null` if stdin is closed.

Refactor the internal buffering mechanism by introducing a shared `read_()` helper method that both `readByte()` and `readLine()` use, replacing the previous per-method buffering logic. The `readByte()` implementation peels off the first byte from the internal `__buffered` string using `bytes[0]` and slicing.

Add two test files: `read_byte.wren` verifying byte-by-byte reading of "first" and "second" input lines, and `read_byte_eof.wren` confirming that reading after stdin is closed returns the expected error message.
2016-05-20 18:50:14 +00:00
Bob Nystrom bdc8e1f409 docs: add subreddit link and wiki reference to contributing guide 2016-05-20 17:02:57 +00:00
Bob Nystrom e8d17172f4 docs: add comprehensive guide for calling Wren from C with wrenCall API
Replace placeholder TODO with full documentation covering method invocation via wrenCall(), including method signature lookup, receiver specification, and argument passing mechanics.
2016-05-19 23:01:54 +00:00
Bob Nystrom ad05bb2cde fix: apply white-space pre-wrap to pre blocks for Firefox line wrapping
The overflow:auto on pre elements caused horizontal scrollbars in Firefox
when code lines exceeded container width. Adding white-space:pre-wrap
enables natural line wrapping while preserving whitespace formatting,
eliminating the need for horizontal scrolling in narrow viewports.
2016-05-19 16:30:38 +00:00
Bob Nystrom 2bb999127a docs: restructure embedding API docs into multi-page section with slots, lifecycle, and C interop guides 2016-05-16 15:09:14 +00:00
Bob Nystrom 27f308a6ad fix: correct word order in error-handling documentation sentence
The phrase "most two common" was inverted to "two most common" in the
error-handling.markdown documentation file to fix a grammatical error
in the description of runtime error types.
2016-05-04 20:29:59 +00:00
Bob Nystrom d717f0f174 fix: count subscript parameters in wrenMakeCallHandle for bracket signatures
Add missing loop to count underscore parameters in subscript operator signatures
starting with '['. Previously only counted parameters in parenthesized signatures,
causing incorrect arity for methods like `[_,_]` and `[_,_]=(_)`. Also adds
validation assertions for null and empty signatures, and extends test coverage
with unary, binary, subscript, and subscript-set operator call handles.
2016-05-04 13:29:44 +00:00
Bob Nystrom 1c08148cc8 fix: correct typo and clarify gc heapGrowthPercentage documentation in wren.h 2016-05-03 19:27:16 +00:00
Bob Nystrom 34b0ab4e6c fix: correct typo "intpolations" to "interpolations" in values documentation
Fix a spelling error in the doc/site/values.markdown file where the word
"intpolations" was missing the letter 'e' in the section describing nested
string interpolation within interpolated expressions.
2016-05-03 19:26:39 +00:00
Bob Nystrom 143aaaf519 fix: correct spelling of "executable" in src/README.md documentation
Fix the typo "exectuable" to "executable" in the project structure description within the src/README.md file, specifically in the section documenting the cli directory's purpose.
2016-05-03 17:19:10 +00:00
Bob Nystrom c608f094ab docs: fix grammatical inversion in getting-started doc
Corrected "You can is use as a static" to "You can use it as a static"
in the virtual machine description paragraph of the getting-started
markdown file.
2016-05-03 04:54:42 +00:00
Bob Nystrom bd055a356b fix: correct argument order in list.insert example in method-calls docs
The example call `list.insert("item", 3)` was swapped to match the actual API signature where the index comes first, changing it to `list.insert(3, "item")` in the doc/site/method-calls.markdown file.
2016-05-02 23:23:56 +00:00
Bob Nystrom 07613f4eb0 style: align pointer asterisk to type name in MapEntry declarations across wren_value.c 2016-05-02 23:23:52 +00:00
Bob Nystrom 112bb5ca7c fix: correct C++ standardization year from 89 to 98 in embedding-api docs 2016-05-02 23:23:08 +00:00
Bob Nystrom 9bfdb6acd8 fix: correct argument order in list.insert example in method-calls documentation
The example code snippet for method call syntax previously showed `list.insert("item", 3)` which incorrectly placed the value before the index. Updated to `list.insert(3, "item")` to match Wren's actual List.insert method signature where the index parameter comes first.
2016-04-15 14:13:54 +00:00
Bob Nystrom 06748ba454 test: add test verifying closures of same code are unequal
Add a test case to equality.wren that creates two closures from the same
function literal inside a loop and asserts they are not equal, confirming
that each closure invocation produces a distinct object.
2016-03-26 21:22:38 +00:00
Bob Nystrom 19fc5e7534 feat: always wrap functions in closures to simplify VM and improve invocation performance
Simplify the VM by ensuring all called objects are closures, removing the need for runtime checks between bare functions and closures. This eliminates the `IS_FN`/`IS_CLOSURE` branching in `validateFn`, `checkArity`, `bindMethod`, and `wrenNewFiber`, and changes `CallFrame.fn` from `Obj*` to `ObjClosure*`. The compiler now emits `CODE_CLOSURE` for all function declarations, even those without upvalues, trading a small allocation cost at declaration time for faster and more uniform invocation. Benchmarks show performance is neutral to slightly improved across all tested workloads.
2016-03-26 21:00:17 +00:00
Bob Nystrom 82103a64f9 refactor: replace eager optional module loading with lazy source and foreign method hooks 2016-03-17 14:49:43 +00:00
Bob Nystrom 7e72462d90 feat: add WrenErrorType enum and route runtime errors through config errorFn callback
Replace direct fprintf(stderr) calls in wrenDebugPrintStackTrace with invocations of the host-provided errorFn callback, passing WREN_ERROR_RUNTIME for the error message and WREN_ERROR_STACK_TRACE for each stack frame. Introduce the WrenErrorType enum in wren.h with WREN_ERROR_COMPILE, WREN_ERROR_RUNTIME, and WREN_ERROR_STACK_TRACE values, update the WrenErrorFn typedef to accept a type parameter, and modify reportError in cli/vm.c to switch on the error type for formatted output. Adjust wrenDebugPrintStackTrace signature to take WrenVM* instead of ObjFiber* to access the config, and update all call sites accordingly.
2016-03-17 14:17:03 +00:00
Bob Nystrom 63e462bb84 chore: remove unused stdarg.h, stdio.h, and stdlib.h includes from wren_compiler.c and wren_value.c 2016-03-17 14:04:09 +00:00
Bob Nystrom d9ec3627cf feat: add WrenErrorFn callback to WrenConfiguration for custom error reporting
- Add `WrenErrorFn` typedef in wren.h accepting module, line, and message parameters
- Include `errorFn` slot in `WrenConfiguration` struct with documentation comment
- Initialize `errorFn` to NULL in `wrenInitConfiguration()` in wren_vm.c
- Replace direct `fprintf(stderr, ...)` in wren_compiler.c with call to `parser->vm->config.errorFn()`
- Add guard in wren_compiler.c to skip error reporting when `errorFn` is NULL
- Implement `reportError()` in cli/vm.c that writes formatted errors to stderr
- Wire `reportError` into config during `initVM()` in cli/vm.c
2016-03-16 15:04:03 +00:00
Bob Nystrom f16e5c775f feat: report undefined variable errors on the line where they are used
Store the line number of first use in implicitly declared variables as a numeric value, then synthesize a token at that line when reporting the error, ensuring bounded error message length even for pathologically long variable names.
2016-03-16 15:00:28 +00:00
Bob Nystrom 8fb291517d chore: add explanatory comments for Windows platform flag mappings and remove O_SYNC guard
Add inline comments clarifying the purpose of Windows-specific permission and mode flag
definitions in the platform compatibility block. Also remove the conditional `#ifdef O_SYNC`
guard around the O_SYNC flag assignment in `mapFileFlags`, since O_SYNC is now always
defined (as 0) on Windows.
2016-03-16 14:27:03 +00:00
Bob Nystrom 5ce4698605 feat: add Windows platform compatibility defines for file operations in io.c
Add conditional preprocessor definitions for Windows builds (WIN32/WIN64) to handle
platform-specific differences in file mode constants (S_IRUSR, S_IWUSR), sync flag
(O_SYNC), and stat macros (S_ISREG, S_ISDIR). Also fix a minor typo in the comment
describing file flag mapping logic.
2016-03-16 14:23:24 +00:00
Bob Nystrom f09b4f75d9 style: fix indentation and add comment for libuv library linking in wren.mk 2016-03-16 14:22:18 +00:00
Bob Nystrom 5d42ce9ad6 refactor: extract duplicate method detection into declareMethod helper and rename instanceMethods buffer to methods 2016-03-15 14:15:55 +00:00
Bob Nystrom 1d546cf840 feat: prevent duplicate method definitions in class compilation
Add tracking of static and instance method names during class compilation to detect and report duplicate method definitions. Introduce `hasMethod` helper function and `staticMethods`/`instanceMethods` buffers in the `ClassCompiler` struct, along with a `name` field for identification. Include a new test case `duplicate_methods.wren` verifying error generation for duplicate instance and static methods, while allowing same-named methods across static/instance boundaries.
2016-03-15 13:54:49 +00:00
Bob Nystrom c33dc205c3 chore: remove unused DUP opcode from compiler, debug, opcodes, and VM interpreter 2016-03-14 05:11:21 +00:00
Bob Nystrom c30ee8a297 refactor: consolidate compile error formatting into single printError helper
Replace multiple fprintf calls in lexError and compileError with a unified printError function that formats the entire error message into a fixed-size buffer before outputting it as a single fprintf call. This centralizes error formatting logic and prepares for future integration of a host-provided error callback by eliminating scattered fprintf invocations.
2016-03-12 05:30:54 +00:00
Bob Nystrom 51d1bb6b3a refactor: move shebang detection into default case and remove separate '#' branch 2016-03-12 01:23:31 +00:00
Bob Nystrom 78c4969cc4 feat: add Python 3 compatibility and formatted output to metrics script
Add `from __future__ import print_function` import for Python 2/3 compatibility and introduce `C_FORMAT_LINE` and `WREN_FORMAT_LINE` format strings to produce aligned columnar output for C source and Wren test file metrics respectively, replacing the previous unstructured print statements.
2016-03-07 15:56:44 +00:00
Bob Nystrom d9f608fa3f fix: correct variable naming and constructor syntax in FAQ code examples
- Rename `acc` to `account` in Lua and Wren examples for consistency
- Fix Wren constructor syntax from `this new` to `construct new`
- Remove hyphen from "one-byte" to match standard phrasing
2016-03-07 15:41:00 +00:00
Bob Nystrom 0f18db0097 refactor: move compiler function state directly into ObjFn to eliminate copying on completion 2016-03-04 15:49:34 +00:00
Bob Nystrom 53f4cb15c9 fix: remove wrenSetCompiler and fix compiler root not being popped on error 2016-03-04 01:48:47 +00:00
Bob Nystrom d4df37703d refactor: replace manual error assignment with RETURN_ERROR and RETURN_ERROR_FMT macros across validation and fiber functions
Consolidate repetitive `vm->fiber->error = wrenStringFormat(...)` and `return false` patterns into two new macros defined in wren_primitive.h, reducing code duplication and improving consistency in error reporting for fiber operations, number parsing, and type validation helpers.
2016-03-04 01:11:52 +00:00
Bob Nystrom db5223d14d feat: unify Fiber.try() error messages with call/transfer by adding verb parameter to runFiber
Add a `verb` string parameter to the `runFiber` helper function so that
`Fiber.try()` produces consistent error messages like "Cannot try a finished
fiber." instead of the previous generic fallback. Update all call sites
(`fiber_call`, `fiber_call1`, `fiber_transfer`, `fiber_transfer1`) to pass
the appropriate verb string, and add a new test case `try_error.wren`
verifying the error message for trying an aborted fiber.
2016-03-04 01:00:33 +00:00
Bob Nystrom 1ef9b77842 refactor: rename allowAssignment to canAssign and simplify parsePrecedence signature in wren_compiler.c 2016-03-04 00:30:48 +00:00
Bob Nystrom b2469990c0 test: add test for creating a VM with null config and fix wrenNewVM to handle NULL config 2016-03-03 22:31:47 +00:00
Bob Nystrom 443749b55d fix: correct typo 'wrenUpwrapClosure' to 'wrenUnwrapClosure' across multiple files
Fix the misspelled function name `wrenUpwrapClosure` to the correct `wrenUnwrapClosure` in wren_debug.c, wren_value.c, wren_value.h, and wren_vm.c. Also fix a minor grammar typo in wren_vm.c comment changing 'arguments' to 'argument'.
2016-02-28 00:23:48 +00:00
Bob Nystrom 06dad18184 docs: fix grammar and formatting in Wren VM comments and code 2016-02-28 00:05:50 +00:00
Bob Nystrom bbafbfd50a feat: add File.realPath() to resolve symlinks and normalize paths
Implement a new static method `File.realPath(path)` that resolves the given path by traversing symlinks and removing redundant `./` and `../` components, returning the canonical absolute path. The implementation uses libuv's `uv_fs_realpath` via an asynchronous callback pattern consistent with other File operations. Includes documentation, foreign method declarations, and two error-case tests for nonexistent paths and wrong argument types.
2016-02-27 23:53:02 +00:00
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