Commit Graph
100 Commits
Author SHA1 Message Date
Bob Nystrom 09a7a126b0 feat: add DEALLOCATE macro and replace direct wrenReallocate calls for freeing memory
Introduce a DEALLOCATE macro that wraps wrenReallocate(vm, pointer, 0, 0) to provide a consistent, readable interface for freeing allocated memory. Replace all existing direct wrenReallocate calls used for deallocation across wren_core.c, wren_utils.c, wren_value.c, and wren_vm.c with the new macro. Also remove two stale TODO comments in wren_core.c related to testing and unimplemented map methods.
2015-03-02 15:31:46 +00:00
Bob Nystrom 8897c6a0a5 refactor: rename NATIVE/DEF_NATIVE macros to PRIMITIVE/DEF_PRIMITIVE across wren_core
Rename the NATIVE macro to PRIMITIVE and DEF_NATIVE to DEF_PRIMITIVE, updating all
corresponding function prefixes from native_ to prim_ to maintain consistency with
the existing METHOD_PRIMITIVE type and terminology used throughout the codebase.
2015-03-02 15:24:04 +00:00
Bob Nystrom cb10020de5 chore: add Raymond Sohn to AUTHORS file and fix missing newline at EOF
The AUTHORS file was missing a trailing newline after Marco Lizza's entry.
This commit adds the missing newline and appends Raymond Sohn as a new
contributor to the project.
2015-03-01 16:40:17 +00:00
Bob Nystrom d6570cccce docs: expand static field documentation with instance access examples and null initialization note 2015-03-01 16:39:53 +00:00
Bob Nystrom 0b569194ef docs: add static field usage example to classes documentation 2015-03-01 16:34:11 +00:00
Bob Nystrom e00ea68927 chore: add Raymond Sohn to AUTHORS file with email address
The diff appends a new entry for Raymond Sohn with email raymondsohn@gmail.com
to the AUTHORS file, following the existing contributor list format.
2015-03-01 16:33:06 +00:00
Bob Nystrom f46b93976b fix: refactor fibonacci benchmark from closure to static class method 2015-03-01 16:20:55 +00:00
Bob Nystrom c11bb88105 perf: replace recursive closure with static method in fib benchmark for faster execution 2015-03-01 00:51:41 +00:00
Bob Nystrom aa5113ba77 fix: remove dead commented code and add null check for sourcePath in stack trace 2015-02-28 21:51:19 +00:00
Bob Nystrom ff420c816b feat: add wrenGetMethod, wrenCall, and wrenReleaseMethod for invoking Wren methods from C code 2015-02-28 21:31:15 +00:00
Bob Nystrom 091860b89d fix: add dedicated markRange function to correctly count ObjRange memory in GC 2015-02-28 17:09:57 +00:00
Bob Nystrom cf9d568469 fix: guard GC trigger to only fire on allocation, not deallocation 2015-02-28 05:41:59 +00:00
Bob Nystrom f77944a56c docs: add detailed documentation for benchmark runner script explaining trial methodology and baseline comparison 2015-02-28 05:34:07 +00:00
Bob Nystrom 3a8bc85674 refactor: extract validateSuperclass helper and move subclassing tests to inheritance directory 2015-02-27 16:08:27 +00:00
Bob Nystrom d7d067b960 feat: prevent subclassing of built-in types with runtime error
Add a check in the interpreter's class creation path that rejects attempts to subclass any of the seven core built-in types (Class, Fiber, Fn, List, Map, Range, String). When such a subclass is declared, a runtime error is raised with a message like "Class 'SubName' may not subclass a built-in". Also add corresponding test files for each forbidden subclass scenario.
2015-02-27 15:41:25 +00:00
Bob Nystrom fdcd1fdf03 docs: update ceil/floor examples with negative numbers and range docs to use non-integer values 2015-02-27 15:37:58 +00:00
Bob Nystrom ec9188ba96 docs: add ceil, floor, and range operator documentation to Num class doc page 2015-02-27 15:30:58 +00:00
Bob Nystrom 1dfdcb05a7 chore: encode stdin input as utf-8 bytes and remove extra newlines in test output 2015-02-27 15:22:27 +00:00
Bob Nystrom 08f40299f0 refactor: extract signature stringification into dedicated helper and update callers
The `signatureSymbol` function previously built a method name string as a side effect before hashing it. This change separates the stringification logic into a new `signatureToString` function that writes the full signature name into a provided buffer and updates its length. All callers now use the new helper, making the code clearer and allowing the stringified signature to be reused independently of symbol lookup.
2015-02-27 15:10:44 +00:00
Bob Nystrom 469f64fa9a refactor: remove endToken parameter and error handling from finishParameterList
The finishParameterList function no longer needs to consume the closing delimiter
or produce error messages, as that responsibility has been moved to the callers.
The parameterList wrapper function has been inlined into its single call site,
simplifying the parameter parsing flow.
2015-02-27 14:51:37 +00:00
Bob Nystrom 5382fa05d7 feat: allow empty argument list methods in calls, definitions, and docs
- Compile empty `()` as a valid method signature distinct from no parentheses
- Update `call()`, `clear()`, `run()`, `try()`, and `yield()` to use empty argument lists
- Revise documentation across multiple files to reflect new signature semantics
2015-02-27 07:08:36 +00:00
Bob Nystrom 94f34367f9 feat: switch method signatures to parenthesized parameter notation and update error messages
The method signature format has been changed from space-counted arity (e.g., "== ") to explicit parenthesized parameter lists (e.g., "==(_)"). This required updating the MAX_METHOD_SIGNATURE calculation to account for parentheses and parameter separators, replacing the old copyName helper with a new Signature struct and SignatureType enum, and rewriting the methodNotFound error message to display the full signature string instead of reconstructing arity from trailing spaces. All core method registrations in wren_core.c, wren_io.c, and corresponding test expectations have been updated to use the new signature format.
2015-02-27 05:56:15 +00:00
Bob Nystrom a24f51d4af feat: replace separate methodName/arity params with unified signature string in foreign method API
The wrenDefineMethod and wrenDefineStaticMethod functions now accept a single `signature` string parameter instead of separate `methodName` and `arity` arguments. This simplifies the API by letting callers specify the full method signature (including arity spaces) directly, removing the internal arity-to-spaces conversion logic in defineMethod. The change updates the header declaration, the internal defineMethod helper, and all call sites in wren_io.c to pass pre-formatted signatures.
2015-02-26 15:44:45 +00:00
Bob Nystrom a12b1695a7 docs: document NULL return behavior for wrenCompile on syntax errors 2015-02-26 15:37:10 +00:00
Bob Nystrom 8fb17b57f1 feat: split monolithic PREC_BITWISE into separate precedence levels for |, ^, &, and << >> in wren_compiler.c
Add new Precedence enum values (PREC_BITWISE_OR, PREC_BITWISE_XOR, PREC_BITWISE_AND, PREC_BITWISE_SHIFT) and a PREC_TERNARY level between assignment and logical operators. Update and_(), or_(), and conditional() to use the refined precedence constants. Include a test file verifying correct associativity and precedence ordering among bitwise operators (|, &, ^, <<) in expressions.
2015-02-25 15:14:31 +00:00
Bob Nystrom 3aa82e7960 fix: reject trailing non-number characters in Num.fromString parsing
Previously, `Num.fromString` accepted strings like `"1.2prefix"` and returned the
leading numeric portion (`1.2`). This change makes parsing stricter by requiring
that the entire string be consumed after `strtod`, skipping only trailing
whitespace. If any non-whitespace characters remain after the number, the
function now returns `null` instead of a partial result.

The fix also adds an explicit empty-string check and updates the test suite to
reflect the new behavior, replacing the old `"1.2prefix"` success test with a
`"1.2suffix"` null-return test.
2015-02-25 15:07:54 +00:00
Bob Nystrom f0a73b6ce2 feat: add Num.fromString static method to parse decimal strings into numbers
Implement a new `Num.fromString(value)` method that attempts to parse a string as a decimal literal and returns the corresponding `Num` instance, or `null` if parsing fails. The implementation uses `strtod` for conversion, validates the argument is a string at runtime, and includes tests for valid numbers, edge cases like leading/trailing whitespace and partial suffix parsing, non-number inputs returning null, and a runtime error when a non-string argument is passed. Also fixes a missing semicolon in the `toString` native registration and removes the hex literal TODO from the number literals test.
2015-02-25 14:53:12 +00:00
Bob Nystrom 766d9792a4 fix: correct missing closing parenthesis in removeAt example code 2015-02-25 14:49:42 +00:00
Bob Nystrom d57319e80a fix: use BENCHMARK_DIR constant for baseline file path in benchmark script 2015-02-25 06:08:57 +00:00
Bob Nystrom c9f0dcde66 fix: convert signed integer types to unsigned in core and value modules to eliminate -Wsign-compare warnings
- Change `int` to `uint32_t` for iterator indices in `map_iterate` and `string_iterate` to match capacity/length types
- Update `String.length` field type from `int` to `uint32_t` in `wren_utils.h`
- Modify `wrenStringCodePointAt` parameter type from `int` to `uint32_t` and remove redundant negative index assertion
- Convert loop variable in `markMap` from `int` to `uint32_t` to match `map->capacity` type
- Add `-Wsign-compare`, `-Wtype-limits`, and `-Wuninitialized` compiler flags to catch future mismatches
2015-02-25 05:56:33 +00:00
Bob Nystrom fca963cb48 fix: ensure UINT32_MAX is available in gcc C++ builds by defining __STDC_LIMIT_MACROS before including stdint.h in wren_common.h 2015-02-25 05:09:04 +00:00
Bob Nystrom 29e8708812 fix: add missing stdint.h include for UINT32_MAX in wren_core.c
The UINT32_MAX macro is defined in <stdint.h> but was not included, causing
compilation errors on platforms where it is not implicitly pulled in by other
headers. This commit adds the missing include to ensure the constant is
available for use in the source file.
2015-02-25 04:26:39 +00:00
Bob Nystrom 6396151732 fix: install gcc-multilib for 32-bit compilation support on 64-bit Travis CI VMs
Add before_install step to .travis.yml that updates apt packages and installs
gcc-multilib, enabling 32-bit C library headers and runtime for cross-compilation
in the CI environment.
2015-02-25 04:26:24 +00:00
Bob Nystrom f940f2d9d2 fix: use BENCHMARK_DIR constant for baseline file path in read and write operations
The baseline file path was hardcoded as "benchmark/baseline.txt" in both read_baseline() and generate_baseline() functions, ignoring the BENCHMARK_DIR constant. This caused the baseline file to be created in the wrong directory when BENCHMARK_DIR differed from the default "benchmark" path. Changed both functions to construct the path using os.path.join(BENCHMARK_DIR, "baseline.txt") for consistency and correctness.
2015-02-25 03:49:29 +00:00
Bob Nystrom 6596537e87 refactor: replace platform-specific getcwd with empty root directory for relative imports
Remove conditional getcwd logic for MSVC and POSIX, replacing it with a simple
empty root directory string. This simplifies the import path resolution by
always using relative paths from the current working directory instead of
attempting to resolve an absolute root path at startup.
2015-02-25 03:47:17 +00:00
Bob Nystrom 9d700df1cd fix: replace dynamic allocation with static buffer for rootDirectory in main.c
- Add platform-specific getcwd header includes for MSVC and POSIX
- Replace malloc-based rootDirectory assignment with a static 2048-byte buffer
- Initialize rootDirectory to point to the static buffer instead of an empty string
- Update runFile to use const char* for lastSlash and copy path directly into buffer
- Implement TODO in runRepl by calling getcwd to set rootDirectory to current working directory
2015-02-25 03:43:12 +00:00
Bob Nystrom 77148c2db6 chore: switch travis build script from make to make all for full configs 2015-02-25 03:32:46 +00:00
Bob Nystrom 8022c2b3c2 feat: allow multiple wrenInterpret calls to share module state for REPL
Initialize vm->modules to NULL in wrenNewVM and create a module registry map to track loaded modules. In loadModule, check if a module has already been loaded via wrenMapFind; if found, reuse the existing module object instead of creating a new one, enabling successive wrenInterpret calls to execute in the same module context and preserve variable bindings across REPL invocations.
2015-02-23 15:02:27 +00:00
Bob Nystrom 708b883e1f fix: correct typos in Fn class documentation for parameter name and grammar 2015-02-22 20:34:32 +00:00
Bob Nystrom f51847e9f4 refactor: extract call method helpers and clean up comment formatting in wren_compiler.c
Extract `callMethodInstruction` and `callMethod` helper functions from the
existing `methodCall` function to reduce code duplication and improve
readability. Also fix comment formatting for argument arity overloading
and block argument inclusion.
2015-02-22 19:04:43 +00:00
Bob Nystrom c1fc6adcb4 feat: extract argument list parsing into finishArgumentList helper
Extract the duplicated argument list parsing logic from methodCall and
subscript into a shared finishArgumentList function. This unifies the
comma-separated expression parsing, arity tracking, and newline handling
into a single location. Also add a new test case verifying that newlines
after commas and before closing delimiters are correctly handled in both
method calls and subscript expressions.
2015-02-22 18:42:49 +00:00
Bob Nystrom 609082b3ba fix: correct wrend binary path in test script from root to bin subdirectory 2015-02-22 18:42:21 +00:00
Bob Nystrom 9016d6e12d docs: document removeAt() return value and update list examples 2015-02-22 18:26:31 +00:00
Bob Nystrom ad7318d101 fix: guard against null pointer when script path lacks directory separator
When a script path contains no '/' character, strrchr returns NULL, causing a crash in the subsequent malloc and memcpy calls. This change adds a NULL check before attempting to extract the root directory, leaving rootDirectory as an empty string when no separator is present.
2015-02-22 18:22:21 +00:00
Bob Nystrom 2cdc57dda8 feat: restructure Makefile to delegate builds to script/wren.mk and output to bin/ and lib/ directories
The monolithic Makefile is replaced with a thin wrapper that invokes
script/wren.mk for each configuration. Build artifacts are now placed
in bin/ (executables) and lib/ (static/shared libraries) instead of
the project root. The .gitignore is updated accordingly, and the
getting-started documentation reflects the new output layout.
2015-02-22 18:19:23 +00:00
Bob Nystrom 42b4236b8d feat: move baseline file path from root to benchmark/ directory
Update read_baseline and generate_baseline functions to read from and write to
"benchmark/baseline.txt" instead of "baseline.txt" in the project root.
2015-02-21 21:49:02 +00:00
Bob Nystrom b3ea90f333 docs: correct comments in classDefinition, WREN_NAN_TAGGING define, and fix typo in collectGarbage 2015-02-21 08:09:55 +00:00
Bob Nystrom 325f39d7c4 fix: rewrap long lines in modules documentation to fix quote formatting 2015-02-20 14:54:03 +00:00
Bob Nystrom 7771a1a1cf docs: clarify cyclic import resolution with step-by-step execution trace in modules.markdown 2015-02-19 14:38:13 +00:00
Bob Nystrom 6187f7c3d8 style: convert Cthulu and Lovecraft class methods to single-line expression bodies 2015-02-19 14:32:46 +00:00
Bob Nystrom 7afbcd142d feat: add bitwise XOR, left shift, and right shift operators to Wren language
Add three new bitwise operators (^, <<, >>) to the Wren compiler and runtime,
including tokenization, parsing with correct precedence, and native method
implementations operating on 32-bit unsigned integers. New test files verify
correct behavior for edge cases including max u32 values and operand type errors.
2015-02-18 15:55:38 +00:00
Bob Nystrom e564621bd5 docs: add initial modules documentation and update error/variable terminology
Create new modules.markdown guide explaining Wren's module system, import syntax, and top-level scoping. Update error-handling.markdown to use "Top-level variable" instead of "Global variable" in error messages. Revise variables.markdown to clarify top-level variable visibility and link to the new modules page. Add "Modules" link to the site navigation template.
2015-02-18 15:55:09 +00:00
Bob Nystrom 00d18e5885 feat: add bitwise XOR, left shift, and right shift operators to compiler and runtime
Add token definitions for `<<`, `>>`, and `^` in the lexer with proper two-character parsing for shift operators. Register new infix operators at the BITWISE precedence level in the parser grammar. Implement native C functions for bitwise XOR, left shift, and right shift on 32-bit unsigned integers in the core runtime, and bind them as methods on the Num class. Include test files covering edge cases like max u32, overflow, and non-numeric operand errors.
2015-02-18 14:51:13 +00:00
Bob Nystrom 0d3eae5269 feat: allow zero or multiple imported names in import statement
Make the `for` clause in import statements optional, and support comma-separated lists of imported names when present. This removes the previous restriction of exactly one imported variable per import statement.

- Refactor `import()` in compiler to handle optional `for` clause with loop over comma-separated names
- Update existing tests to use comma-separated imports and omit `for` clause where appropriate
- Add new tests: `inside_block`, `name_collision`, `no_variable`
2015-02-17 15:32:33 +00:00
Bob Nystrom d96fc0a381 feat: add map numeric/string benchmarks, IO.time, and refine Makefile clean targets
Add map_numeric and map_string benchmark scripts in Lua, Python, Ruby, and Wren to compare hash map insertion/lookup/deletion performance across languages. Register both new benchmarks in the benchmark runner script and fix its language executable paths to use WREN_DIR. Expose a new `IO.time` static method in the C IO module returning `time(NULL)` as a double. In the Makefile, split the monolithic `clean` target into separate removals for build artifacts, wren executables, and library variants to avoid accidental deletion of unrelated files. Remove hardcoded hash singleton constants from wren_value.c as they are no longer used.
2015-02-17 15:22:21 +00:00
Bob Nystrom 4f471203fa feat: replace string import method with dedicated bytecode instruction for module variable loading
Replace the runtime string-based `import_` method call with a new `CODE_IMPORT_VARIABLE` bytecode instruction that directly loads variables from other modules. This eliminates the overhead of calling a native method and string-based module lookup during import, moving the logic into the VM interpreter loop with a dedicated `importVariable` helper function. The change includes adding the opcode to the compiler's `import` function, implementing the runtime lookup in `wren_vm.c`, updating the debug disassembler, and removing the now-unnecessary `string_import` native from `wren_core.c`.
2015-02-17 15:21:51 +00:00
Bob Nystrom e64e2c01e1 feat: replace string-based module loading with dedicated CODE_LOAD_MODULE bytecode instruction
Replace the previous approach of calling a native `loadModule_` method on string objects with a new `CODE_LOAD_MODULE` bytecode instruction. This eliminates the need for the `string_loadModule` native function and the indirect fiber invocation through `PRIM_RUN_FIBER`. The new implementation directly handles module loading in the VM by compiling the module source, creating a fiber, and switching execution contexts. The compiler now emits `CODE_LOAD_MODULE` followed by a `CODE_POP` to discard the unused fiber result, instead of the previous `CODE_CONSTANT` + `CODE_CALL_0` sequence.
2015-02-17 06:45:58 +00:00
Bob Nystrom d5149f9a74 refactor: remove builtin import_ method from String class and inline module loading in compiler
The import_ method on String was a builtin that combined module loading and variable lookup. This change removes that method and instead emits separate bytecode instructions in the compiler: first calling loadModule_ on the module, then calling import_ on the module with the variable name. The native function string_lookUpVariable is renamed to string_import to match the new import_ method name on String's metaclass.
2015-02-16 18:21:29 +00:00
Bob Nystrom 2082b64454 feat: move fiber execution of loaded modules from Wren to C runtime
The `loadModule_` primitive now returns a fiber when a module is loaded, and the C runtime handles calling it via `PRIM_RUN_FIBER` instead of the Wren code manually invoking the result. This removes the conditional `if (result != null) result.call` from the `import_` method in both the builtin source and the embedded libSource string, and adds `IS_FIBER` macro to `wren_value.h` for type checking in the native implementation.
2015-02-16 18:16:42 +00:00
Bob Nystrom f2424f029e refactor: move module load failure handling from Wren to C with error string return
The loadModule_ primitive now returns NULL for already-loaded modules and an error string for missing modules, shifting the error handling from Wren's Fiber.abort to C's native string return. The Wren import_ method simplifies to only call the result when non-null, removing the false/true branching logic.
2015-02-16 18:12:41 +00:00
Bob Nystrom 3845ed2c52 feat: add IO.time static method returning current Unix timestamp via time(NULL)
Implement a new `IO.time` static method in the Wren IO module that returns the current Unix timestamp as a double by calling `time(NULL)`. This provides a simple way for Wren scripts to obtain wall-clock time, complementing the existing `IO.clock` method which measures CPU time. The method is registered in `wrenLoadIOLibrary` alongside the other IO primitives.
2015-02-16 18:01:56 +00:00
Bob Nystrom 5db1f6778f refactor: remove HASH_* constants and inline singleton hash values in hashValue
Replace the named constants HASH_FALSE, HASH_NAN, HASH_NULL, and HASH_TRUE
with inline integer literals in the hashValue function, eliminating the
unused HASH_NAN constant and the associated TODO comment about tuning.
2015-02-16 17:33:07 +00:00
Bob Nystrom ea958deeef feat: add import keyword token and parser support with updated test syntax
Add TOKEN_IMPORT to the token enum and wire it into the keyword parser in readName(). Refactor string literal parsing by extracting stringConstant() helper that returns the constant index, allowing the new import parser to reuse it. Update all module test files to replace the old .import_() method calls with the new import "module" for Var syntax, and add new error test cases for missing string and missing for clause after import.
2015-02-15 00:46:00 +00:00
Bob Nystrom 53da84b870 chore: add cleanup of Mac .dylib files to Makefile clean target
Extend the clean target in the Makefile to remove libwren.dylib and libwrend.dylib
alongside the existing .a and .so artifacts, ensuring complete cleanup on macOS
builds.
2015-02-12 17:07:41 +00:00
Bob Nystrom da2002e7e1 fix: remove only build artifacts in clean target instead of all generated files 2015-02-12 17:06:37 +00:00
Bob Nystrom dc58f2aa06 feat: replace O(n) map deletion with tombstone-based open addressing
Replace the previous deletion strategy that required rehashing all entries after removal with a tombstone approach. When an entry is removed, its slot is marked with UNDEFINED_VAL key and TRUE_VAL value, allowing linear probing to continue past deleted slots during lookups. This prevents deletion from degrading to near-linear time in the presence of large clusters, matching the approach used by Python and Lua. Also refactor hashValue to hash raw bits of unboxed values under WREN_NAN_TAGGING, and update MapEntry documentation to clarify tombstone semantics.
2015-02-12 06:43:39 +00:00
Bob Nystrom aff3ce54db feat: add string-key map benchmark across lua, py, rb, wren with 1M entries
Add new benchmark files (map_string.lua, map_string.py, map_string.rb, map_string.wren) that test map performance using string keys generated from adverb-adjective combinations. Rename existing numeric map benchmarks from maps.* to map_numeric.* and increase their iteration count from 100k to 1M. Register both benchmarks in script/benchmark.py with their expected output values.
2015-02-12 06:41:59 +00:00
Bob Nystrom 25b9cbf9a1 refactor: rename HOME_DIR to WREN_DIR and script file from run_bench.py to benchmark.py
Rename the benchmark script file from `script/run_bench.py` to `script/benchmark.py` and update the internal variable `HOME_DIR` to `WREN_DIR` for clarity, reflecting that the directory points to the Wren project root rather than a generic home directory.
2015-02-12 03:48:39 +00:00
Bob Nystrom 91efd0d0cc feat: split core module from main and add implicit core imports for all modules
Extract core module loading into separate `loadIntoCore` function and `getCoreModule` helper, replacing the old `getMainModule`. Implement `loadModule` that automatically imports all core module variables into every newly loaded module, enabling implicit visibility of core types (Bool, Class, Fiber, etc.) across all user modules. Add `wrenImportModule` public API for module loading with circular import detection. Increase `WREN_MAX_TEMP_ROOTS` from 4 to 5 to accommodate additional GC roots during module loading. Add test cases for cyclic imports (a.wren/b.wren) and implicit core imports (implicitly_imports_core.wren/module.wren).
2015-02-11 18:06:45 +00:00
Bob Nystrom 6cce3433a5 feat: append ".wren" extension to module paths in readModule and update test imports
The readModule function now concatenates ".wren" to the module path when constructing the full file path, increasing the path buffer by 5 bytes. All test files have been updated to use bare module names (without ".wren") in import_ calls, and the expected error messages in unknown_module and unknown_variable tests are adjusted accordingly. A trailing blank line is also removed from wren_vm.c.
2015-02-06 19:52:05 +00:00
Bob Nystrom 70191aa022 feat: add module loading with String.import_ and embedder-provided loadModuleFn
Implement initial module system allowing Wren code to import other modules via a temporary `String.import_` method. The embedder must supply a `WrenLoadModuleFn` callback that returns source code for a given module name; the VM caches loaded modules and returns a fiber to execute the module body. Add `wrenImportModule` to the VM API, wire `loadModuleFn` into `WrenConfiguration`, and update the CLI interpreter to resolve imports relative to the entry script's directory. Include test cases for importing multiple variables, shared imports across modules, and verifying that variable bindings are independent across import sites.
2015-02-06 15:01:15 +00:00
Bob Nystrom 7cba07a322 feat: add shared library builds and fix string buffer type in symbol table
Add Makefile targets for building shared libraries (.so/.dylib) alongside existing static libraries, with platform-specific linker flags for macOS and Linux. Refactor the internal string representation from raw `char*` to a `String` struct that tracks both buffer and length, updating all symbol table operations, debug printing, and string concatenation calls to use the new type. Fix a null-termination bug in `copyName` and add support for the `\0` escape sequence in string literals.
2015-02-05 20:07:25 +00:00
Bob Nystrom 1fd8308f50 refactor: remove dedicated main module field from WrenVM struct
Instead of storing the main module directly in a dedicated field on WrenVM,
store it as a null-keyed entry in the new modules map. This eliminates the
redundant `vm->main` pointer and paves the way for supporting multiple named
modules. The change also adds `wrenFindVariable` as a public helper to look up
top-level variables in the main module, and updates `wrenNewFunction` to accept
an explicit module parameter instead of always using `vm->main`.
2015-02-05 20:03:19 +00:00
Bob Nystrom 9ed0bdac95 fix: cast index to uint32_t before comparing with string length in string_iterate 2015-02-05 04:28:27 +00:00
Bob Nystrom c6d8ad2844 chore: add trailing period to "8-bit clean" comments across string test files
Add a period at the end of the "// 8-bit clean" comment in 12 string test files
(concatenation, contains, count, ends_with, equality, index_of, iterate,
iterator_value, join, starts_with, subscript, to_string) to make the comment
grammatically consistent with other comments in the test suite.
2015-02-05 04:26:29 +00:00
Bob Nystrom 66c9c1ad4b feat: add length parameters to wrenStringConcat and implement Boyer-Moore-Horspool string search
Add explicit length parameters to wrenStringConcat to support binary-safe string concatenation, with -1 sentinel for automatic strlen calculation. Implement wrenStringFind using Boyer-Moore-Horspool algorithm for efficient substring search, returning UINT32_MAX when needle not found. Update all callers in wren_core.c validation functions and wren_value.c metaclass creation to pass length arguments. Extend string/index_of.wren tests with edge cases including empty needle, full match, and complex overlapping patterns.
2015-02-05 04:25:12 +00:00
Bob Nystrom 8fa4f9c1bb refactor: change wrenStringFind to return UINT32_MAX instead of haystack->length for not-found
The wrenStringFind function previously returned the haystack length to indicate
a missing needle, which was ambiguous when the needle could legitimately appear
at the end of the string. This commit changes the sentinel value to UINT32_MAX,
updates all callers (string_contains, string_indexOf) to check against the new
sentinel, and adds explicit handling for empty needle and empty haystack edge
cases. The Boyer-Moore-Horspool implementation is also cleaned up with clearer
variable names and comments.
2015-02-05 04:23:50 +00:00
Bob Nystrom 84e1b78a7a feat: replace strstr with Boyer-Moore-Horspool string search in core string operations
Implement wrenStringFind function using Boyer-Moore-Horspool algorithm with 256-entry shift table for efficient substring matching. Update string_contains, string_indexOf, and string_count native methods to use the new implementation, fixing the empty string corner case to always return true when search string is empty.
2015-02-05 01:56:29 +00:00
Bob Nystrom 00226268c3 style: reformat string concat calls to 80 cols and fix comment typo
Break long wrenStringConcat calls across multiple lines in validateFn,
validateNum, validateIntValue, and validateString functions in
src/wren_core.c to stay within the 80-column limit. Also fix a comment
typo in src/wren_value.h: change "of" to "with" in the wrenStringConcat
documentation.
2015-02-04 16:15:35 +00:00
Bob Nystrom 80815a279b fix: add explicit length parameters to wrenStringConcat calls in validation and class creation 2015-02-04 16:12:50 +00:00
Bob Nystrom daf0728b12 test: add 8-bit clean string tests for concatenation, contains, count, ends_with, equality, index_of, iterate, iterator_value, join, starts_with, subscript, and to_string 2015-02-04 14:59:57 +00:00
Bob Nystrom 8eecc5abe3 feat: add '\0' escape sequence support for null characters in string parsing
Add handling for the null character escape sequence '\0' in the readString function within wren_compiler.c. This extends the existing escape sequence handling to include the null character, allowing strings to contain embedded null bytes when explicitly escaped.
2015-02-04 14:57:42 +00:00
Bob Nystrom 69e10c11bc refactor: replace strcpy/strncpy with memcpy and explicit null-termination across compiler, core, utils, value, and vm modules
Replace all uses of strcpy() and strncpy() with memcpy() followed by explicit null-termination to avoid potential buffer over-reads and undefined behavior from non-null-terminated source strings. This change affects copyName() in wren_compiler.c, wrenSymbolTableAdd() in wren_utils.c, wrenNewFunction() and wrenNewString() in wren_value.c, and defineMethod() in wren_vm.c. Also converts the static "new" string initialization in new_() from strcpy to a C99 compound literal. Additionally fixes a minor whitespace alignment issue in string_endsWith() in wren_core.c.
2015-02-04 14:57:17 +00:00
Bob Nystrom 4f66bb2a84 fix: add unsigned suffix to FNV-1a hash constant for GCC C++ compilation
The constant 2166136261 triggers a warning under GCC when compiling as C++ because it exceeds the maximum value for a signed 32-bit integer. Adding the 'u' suffix explicitly marks it as unsigned, eliminating the compiler warning without changing the hash algorithm's behavior.
2015-02-04 14:55:44 +00:00
Bob Nystrom a02e359a40 feat: add String struct with length tracking and refactor symbol table to use it
Replace the char* based string buffer with a proper String struct that stores both the buffer pointer and length, eliminating strlen() calls in symbol table lookups. Update all symbol table consumers in debug printing, VM method resolution, and GC marking to access the .buffer field. Refactor Value union to use anonymous struct for num/obj fields, and change Obj flags to a bool marked field. Adjust ALLOCATE_FLEX macro to accept separate main type and array type parameters. Add regression test for map subscript on empty map returning null.
2015-02-02 05:47:43 +00:00
Bob Nystrom dcc4bf5487 fix: ensure NaN-tagged values are properly handled in hashValue and Value struct
The previous implementation of hashValue had UNREACHABLE() placed after the switch statement, which could be reached when using NaN-tagging mode. This fix moves UNREACHABLE() into default cases within each switch branch, ensuring it's only triggered for truly unreachable paths.

Additionally, the Value struct is refactored to use an anonymous union for num and obj fields, preventing undefined behavior from accessing inactive union members. All related macros and inline functions (AS_OBJ, wrenValuesSame, wrenObjectToValue, wrenValueToNum, wrenNumToValue, and singleton value definitions) are updated to use the new `as` union member access pattern.
2015-02-01 23:26:33 +00:00
Bob Nystrom 50e10efa89 refactor: change ALLOCATE_FLEX macro to accept element type and count instead of raw byte size
The macro now takes a main type, array element type, and element count, computing the total allocation as `sizeof(mainType) + sizeof(arrayType) * count`. This improves type safety and clarity at all call sites, which are updated to pass the element type (Upvalue*, Value, char) instead of manually computing byte sizes.
2015-02-01 23:12:37 +00:00
Bob Nystrom e6949ffd1b fix: cast length to int in wrenSymbolTableAdd to suppress implicit conversion warning 2015-01-31 18:54:27 +00:00
Bob Nystrom 3533a4b0bd fix: update symbol table to store String struct with length instead of raw char* 2015-01-31 18:49:41 +00:00
Bob Nystrom 6858db260a fix: replace bitfield flags with bool marked and fix empty map lookup crash
Replace the ObjFlags bitfield approach with a simple bool `marked` field on Obj, removing the FLAG_MARKED constant and all bitwise operations. Also add a guard in wrenMapFind to return UINT32_MAX when map capacity is zero, preventing a crash on empty map subscript lookups. Fix the validateKey function to not wrap the error string in OBJ_VAL.
2015-01-30 15:21:41 +00:00
Bob Nystrom cdfad0a7eb fix: remove redundant OBJ_VAL wrapper in validateKey error string assignment 2015-01-30 04:44:46 +00:00
Bob Nystrom 6609bf2412 feat: add clang/OS X shared library support with dylib extension in Makefile
Introduce conditional detection of Darwin target to set appropriate shared library flags and extension (.dylib instead of .so). Refactor static and shared library build targets into combined `libwren` and `libwrend` phony targets that produce both .a and .dylib/.so files, and update .gitignore to exclude the new .dylib artifacts.
2015-01-29 03:50:53 +00:00
Bob Nystrom 6050ed75e1 refactor: replace bitfield ObjFlags with bool marked field in Obj struct
Remove the FLAG_MARKED enum and ObjFlags bitfield, replacing them with a dedicated bool `marked` member in the Obj struct. Update all references in wren_value.c and wren_vm.c to use direct boolean assignment and checks instead of bitwise flag operations. This simplifies the GC marking logic and eliminates the need for manual bit manipulation.
2015-01-29 03:19:19 +00:00
Bob Nystrom 7d333d2b82 fix: guard against null entry array in wrenMapFind for empty maps
Add early return of UINT32_MAX when map capacity is zero in wrenMapFind,
preventing a crash from modulo operation on zero during hash index calculation.
Includes regression test verifying subscript access on empty map returns null.
2015-01-29 03:19:04 +00:00
Bob Nystrom 7febf6cd57 refactor: convert Module struct to heap-allocated ObjModule with GC support
Replace the embedded `Module main` field in WrenVM with a pointer to a dynamically allocated `ObjModule`, adding a new OBJ_MODULE object type. Introduce `wrenNewModule()` constructor and `markModule()` GC tracer, update all references from `&vm->main` to `vm->main`, and remove the old `initModule`/`freeModule` static helpers.
2015-01-27 15:11:45 +00:00
Bob Nystrom 494b1a360b refactor: replace bitfield flags with explicit bool marked field in Obj struct
Remove the FLAG_MARKED bitfield enum and replace the packed unsigned int flags field with a dedicated bool marked member in the Obj base struct. Update all references in wren_value.c and wren_vm.c to use direct boolean assignment and checks instead of bitwise operations, simplifying the garbage collection marking logic and eliminating the TODO about storing the flag off to the side.
2015-01-27 15:06:18 +00:00
Bob Nystrom a9f0b89df2 refactor: replace string-specific equality operators with generic wrenValuesEqual and add range equality tests
Remove dedicated string equality and inequality native methods (string_eqeq, string_bangeq) and their registration in wrenInitializeCore, since wrenValuesEqual now handles string comparison correctly using memcmp instead of strncmp. Also add a new test file for range equality and inequality checks.
2015-01-27 05:55:41 +00:00
Bob Nystrom ad6d777fe0 fix: fix ambiguous sequence point in dup macro by extracting peek to local variable 2015-01-27 05:23:54 +00:00
Bob Nystrom a794ce4ee1 refactor: move global variable storage from VM into Module struct
Functions now hold a reference to the module where they were defined and load module-level variables from there instead of from the VM's global table. This introduces a new Module struct with its own variable buffer and symbol table, replacing the VM-level globals and globalNames. The main module is stored directly in the VM as a temporary measure. Performance regresses slightly due to the indirection through the function's module pointer.
2015-01-26 15:45:21 +00:00
Bob Nystrom 55851d35ba feat: replace string-specific eqeq/bangeq with generic wrenValuesEqual for range equality support
Remove the dedicated string equality operators (string_eqeq, string_bangeq) and their NATIVE registrations, switching object_eqeq and object_bangeq to use the generic wrenValuesEqual instead of wrenValuesSame. Also fix wrenValuesEqual to use memcmp instead of strncmp for string comparison. Add a new test file test/range/equality.wren verifying inclusive and exclusive range equality and inequality.
2015-01-26 15:01:15 +00:00