119 Commits

Author SHA1 Message Date
Yukihiro "Matz" Matsumoto 8956c5abb5 mruby.h: include mruby/presym.h for all source files
Since presym is now mandatory, mruby.h includes presym.h so that
MRB_SYM() macros are available everywhere without explicit include.
Remove redundant #include <mruby/presym.h> from all source files.

Co-authored-by: Claude <noreply@anthropic.com>
2026-03-09 16:50:58 +09:00
Yukihiro "Matz" Matsumoto 71cb3c2e3a class.c: allocate ROM table wrappers per mrb_state
ROM method tables used static mrb_mt_tbl variables shared
across the process. The next pointer in each wrapper was
mutated by mrb_mt_init_rom(), causing cross-state
contamination when multiple mrb_state instances existed.

Allocate mrb_mt_tbl wrappers per-state via mrb_malloc().
The const mrb_mt_entry[] arrays remain static and shared.
Wrappers are tracked in mrb->rom_mt and freed at mrb_close().

Remove MRB_MT_ROM_TAB macro; add MRB_MT_INIT_ROM macro that
auto-computes size and calls the new mrb_mt_init_rom().

Co-authored-by: Claude <noreply@anthropic.com>
2026-02-20 22:24:31 +09:00
Yukihiro "Matz" Matsumoto 483c155a41 class.c: store aspec in ROM method table entries
Restore MRB_ARGS_* argument specs and ISO section comments to all
709 ROM method table entries. The aspec is encoded in bits 4-27 of
the flags field; MRB_MT_NOARG is now auto-derived from aspec==0.

Add MRB_MT_ENTRY_PRIVATE() macro for private methods (53 entries)
and MRB_MT_ASPEC() accessor for extracting aspec from flags.

Co-authored-by: Claude <noreply@anthropic.com>
2026-02-20 11:44:28 +09:00
Yukihiro "Matz" Matsumoto 8adba34bd9 class.c: auto-set MRB_MT_FUNC in MRB_MT_ENTRY macro
Since ROM table entries are always C functions, have the
MRB_MT_ENTRY() macro set MRB_MT_FUNC automatically. This
simplifies entry definitions across all 32 source files.

Co-authored-by: Claude <noreply@anthropic.com>
2026-02-20 10:37:06 +09:00
Yukihiro "Matz" Matsumoto 0fab703028 class.c: use linear search for method tables; make ROM entries const
Replace binary search with linear scan in mt_get(), mt_put(),
mt_del(), mt_chain_has(), and mrb_mt_foreach(). The method cache
makes repeated lookups O(1), so linear scan on cache misses is
acceptable.

This removes the sorting requirement, allowing ROM entry arrays
to be declared const. On embedded systems, const static data
resides in flash/ROM instead of RAM, saving ~8.4KB for ~700
method entries on 32-bit MCUs.

Co-authored-by: Claude <noreply@anthropic.com>
2026-02-20 08:26:05 +09:00
Yukihiro "Matz" Matsumoto bde2202100 class.c: refactor ROM method tables to array-of-structs layout
Replace the parallel-arrays (struct-of-arrays) ROM method table
layout with an array-of-structs layout where each mrb_mt_entry
bundles its function pointer and symbol key together.

New MRB_MT_ENTRY() and MRB_MT_ROM_TAB() macros simplify ROM table
definitions from a 3-part pattern (SIZE define + anonymous struct +
mrb_mt_tbl) to a 2-part pattern (entries array + mrb_mt_tbl).

Internal mt_* functions in class.c are simplified: single memmove/
memcpy operations replace paired key+value operations.

Co-authored-by: Claude <noreply@anthropic.com>
2026-02-19 23:59:30 +09:00
Yukihiro "Matz" Matsumoto 0ed26f8352 class.c: rename mt_/MT_ to mrb_mt_/MRB_MT_ for non-static identifiers
Follow mruby's naming convention: non-static types, macros, and
functions use the mrb_/MRB_ prefix. Renamed:
- union mt_ptr -> union mrb_mt_ptr
- mt_tbl -> mrb_mt_tbl
- MT_KEY(), MT_FUNC, MT_NOARG, MT_PUBLIC, MT_PRIVATE -> MRB_MT_*
- MT_KEY_SHIFT, MT_READONLY_BIT, MT_REMOVED_P -> MRB_MT_*
- mt_init_rom() -> mrb_mt_init_rom()
File-local static functions and macros in class.c are unchanged.

Co-authored-by: Claude <noreply@anthropic.com>
2026-02-19 15:22:55 +09:00
Yukihiro "Matz" Matsumoto 52c71f5b99 mrbgems: remove MRB_NO_PRESYM guards from additional gems
Co-authored-by: Claude <noreply@anthropic.com>
2026-02-19 12:17:43 +09:00
Yukihiro "Matz" Matsumoto ae41bb332a mruby-set: ROM method table for Set class (43 methods)
Co-authored-by: Claude <noreply@anthropic.com>
2026-02-19 09:39:23 +09:00
Yukihiro "Matz" Matsumoto 0ba48a2a5b mruby-set: fix memory leak in khash rebuild using mrb_protect_error()
wrap hash and eql callbacks with mrb_protect_error() to catch exceptions
during khash table rebuild. when an exception occurs (e.g., SystemStackError
from infinite recursion), return a safe default value and store the exception
in mrb->exc for later processing. this prevents memory leaks from orphaned
allocations when exceptions propagate through khash rebuild.

Co-authored-by: Claude <noreply@anthropic.com>
2026-01-17 13:00:45 +09:00
Yukihiro "Matz" Matsumoto 27c9356f99 Revert "mruby-set: fix memory leak caused by recursive hash computation"
This reverts commit c9e3af60e1.
2026-01-17 12:55:50 +09:00
Yukihiro "Matz" Matsumoto c9e3af60e1 mruby-set: fix memory leak caused by recursive hash computation
when a Set contains itself (directly or indirectly), computing its hash
would cause infinite recursion leading to SystemStackError. the exception
during khash rebuild leaked memory.

add recursion detection flag to Set#hash that returns 0 for recursive
references, similar to Ruby's behavior.

Co-authored-by: Claude <noreply@anthropic.com>
2026-01-08 08:23:43 +09:00
Yukihiro "Matz" Matsumoto 97d4d8f45b mruby-set: standardize block parameter spacing
changed block spacing from { | to {| for consistency.

Co-authored-by: Claude <noreply@anthropic.com>
2025-12-11 18:09:10 +09:00
Yukihiro "Matz" Matsumoto 29644b0365 mruby-set: add parentheses to to_enum calls
added parentheses to all to_enum calls where the return value is used.

Co-authored-by: Claude <noreply@anthropic.com>
2025-12-11 18:09:07 +09:00
Yukihiro "Matz" Matsumoto a6b55e741e mruby-set: fix use-after-free by adding write barriers
young objects stored in old Set instances were being freed during GC
because write barriers were missing. added mrb_field_write_barrier_value()
calls after all kset_put() operations. introduced kset_to_rset() macro
using container-of pattern to obtain RSet pointer from embedded kset_t
without adding function parameters.

Co-authored-by: Claude <noreply@anthropic.com>
2025-11-17 20:08:57 +09:00
Yukihiro "Matz" Matsumoto 153f915d5f mruby-set: fix memory leak in flatten when exceptions raised; fix #6664
set_do_flatten allocated temporary kset_t* via kset_init(). when
exceptions were raised during flattening (e.g., from hash function),
temporary kset was never freed. refactored to pass result set directly
and fill in-place. result set object is GC-protected, so exceptions
are handled cleanly without leaks.

Co-authored-by: Claude <noreply@anthropic.com>
2025-11-13 15:43:19 +09:00
Yukihiro "Matz" Matsumoto 9207af8ede mruby-set: use kh_is_end() for safe iteration; ref #6664
kh_is_end() safely checks if an iterator is at the end position,
preventing issues when the hash table is modified during iteration.
replaced direct kset_end() comparisons with kset_is_end() calls
throughout set operations.

Co-authored-by: Claude <noreply@anthropic.com>
2025-11-13 15:43:12 +09:00
dearblue 0e653eb4c2 Fixed use-after-free with Set#join
The `mrb_obj_as_string()` function can call the `#to_s` method.
String addresses and string lengths obtained outside the `KSET_FOREACH()` loop may become invalid.
2025-11-04 22:09:08 +09:00
Yukihiro "Matz" Matsumoto a3797173c2 mruby-set: fix memory leak from double initialization; fix #6645
set_init was overwriting set->set without freeing the existing khash
table, causing a memory leak when initialize is called multiple times.

Prevent double initialization by raising an exception in set_init,
while allowing replace/dup semantics in set_init_copy by properly
freeing old data before reinitializing.

Co-authored-by: Claude <noreply@anthropic.com>
2025-10-22 12:06:47 +09:00
Yukihiro "Matz" Matsumoto b6179bb0b4 mruby-set: add spec.summary
Co-authored-by: Claude <noreply@anthropic.com>
2025-10-08 23:55:22 +09:00
Piotr Usewicz f5e7ea63bf Extract golden ration prime into constant
This removes the magic number that also gets repeated in the code.
Adding a constant adds extra context without having to add comments.
2025-08-19 11:11:26 +02:00
Yukihiro "Matz" Matsumoto 7dc870c022 mruby-set: reduce KSET_INITIAL_SIZE to 4
This change optimizes memory consumption by reducing the initial size of
the set's internal hash table.

Co-authored-by: Gemini <gemini@google.com>
2025-08-14 10:53:05 +09:00
Yukihiro "Matz" Matsumoto 8a7c758bbd mruby-set: rename KSET_DEFAULT_SIZE to KSET_INITIAL_SIZE
Rename the constant to better reflect its semantic meaning as an initial
size hint for new Set allocations rather than a hard default value.

Co-authored-by: Claude <noreply@anthropic.com>
2025-08-14 10:53:05 +09:00
Yukihiro "Matz" Matsumoto 7368be7568 khash: add kh_replace optimization for efficient copying
Add kh_replace function that uses direct memory copying instead of
element-by-element rehashing for improved performance.

- Add kh_replace_name function with smart handling of different table types
- Optimize kh_copy to use kh_replace instead of element iteration
- Update Set operations to use kh_replace for copying
- Remove redundant kset_copy_replace function

The optimization provides O(1) memory copy vs O(n) hash operations,
handles small tables and hash tables correctly, and avoids infinite
recursion issues with self-referential data structures.

Co-authored-by: Claude <noreply@anthropic.com>
2025-08-14 10:53:05 +09:00
Yukihiro "Matz" Matsumoto ccdfc9a6bd mruby-set: make hash algorithm order-independent
Replace FNV-1a with XOR-based hash algorithm to ensure sets with identical
contents produce the same hash value regardless of insertion order.

The original FNV-1a algorithm was order-dependent, causing Set[1,2,3] and
Set[3,1,2] to have different hash values despite being equal sets. This
became problematic with small table optimization where iteration order
differs from hash table order.

The new algorithm uses commutative XOR operations with golden ratio mixing
to maintain good distribution properties while ensuring hash consistency.

Co-authored-by: Claude <noreply@anthropic.com>
2025-08-14 10:53:04 +09:00
Yukihiro "Matz" Matsumoto 378b4858fd mruby-set: refactor flatten functions to eliminate code duplication
Extract common logic from set_flatten and set_flatten_bang into helper
functions set_has_nested_sets() and set_do_flatten(). This eliminates
~40 lines of duplicated code while maintaining identical functionality
and performance.

Co-authored-by: Claude <noreply@anthropic.com>
2025-08-14 10:53:04 +09:00
Yukihiro "Matz" Matsumoto 8f7bfa4f68 mruby-set: convert kset_copy_* macros to functions
Convert kset_copy_merge and kset_copy_replace from macros to static
functions for better maintainability and debugging.

Benefits:
- Better debugging: can set breakpoints and step through code
- Improved type safety: proper function parameter checking
- Cleaner code: no macro expansion bloat at call sites
- Better error messages: meaningful function names in stack traces
- Easier maintenance: functions are simpler to modify than complex macros

The operations are substantial enough (memory allocation, loops with GC
management) that function call overhead is negligible compared to the
actual work performed.

Co-authored-by: Claude <noreply@anthropic.com>
2025-08-14 10:53:03 +09:00
Yukihiro "Matz" Matsumoto 76188b46ef khash: remove unused mrb parameter from KHASH_FOREACH macro
Remove the unused mrb_state parameter from KHASH_FOREACH macro to clean
up the API. The parameter was never used in the macro implementation and
only cluttered the call sites.

Changes:
- Update KHASH_FOREACH macro signature: (name, mrb, kh, k) -> (name, kh, k)
- Update documentation and usage examples in khash.h
- Update KSET_FOREACH wrapper macro in mruby-set
- Update 2 direct call sites in mruby-metaprog
- All mruby-set call sites automatically updated via wrapper macro

This is a breaking change but follows the recent API cleanup where we
already modified KHASH_FOREACH signature. The macro now has a cleaner
interface without the unused parameter.

Co-authored-by: Claude <noreply@anthropic.com>
2025-08-14 10:53:03 +09:00
Yukihiro "Matz" Matsumoto b22a8da598 mruby-set: integrate with unified khash.h implementation
Replace custom kset hash table implementation with unified khash.h to
reduce code redundancy and improve maintainability. This change removes
over 300 lines of duplicate hash table code while preserving all Set
functionality.

Key changes:
- Use khash.h DECLARE/DEFINE macros instead of custom kset functions
- Add helper macros for set state checking (empty/uninitialized)
- Implement separate merge and replace operations for set copying
- Update memory size calculation for new khash structure layout
- Fix iterator usage to match new khash API requirements

Benefits:
- 50% memory reduction from optimized khash structure
- Small table optimization with linear search for <= 4 elements
- Improved load factor (87.5% vs 75%) for better memory utilization
- Single unified hash implementation across mruby codebase

All existing Set functionality and APIs are preserved. Tests pass with
no regressions.

Co-authored-by: Claude <noreply@anthropic.com>
2025-08-14 10:53:03 +09:00
Yukihiro "Matz" Matsumoto e907995dcd mruby-set: replace custom kset implementation with khash.h
Replace the custom kset hash table implementation with the optimized
khash.h while maintaining identical functionality and memory footprint.

Changes:
- Replace custom kset_t struct with kh_set_val_t typedef
- Use KHASH_DECLARE/DEFINE macros for type-safe hash operations
- Add compatibility layer to preserve existing kset API
- Embed khash struct directly in RSet (same 16-byte footprint)
- Remove duplicate string.h include (provided by khash.h)

Benefits:
- Unified hash implementation across mruby core
- Eliminated ~200 lines of duplicate hash table code
- Automatic benefits from future khash optimizations
- Reduced maintenance burden with single hash implementation
- Identical performance and memory characteristics

The RSet structure maintains the same size through embedded khash
struct, and all Set class functionality remains unchanged.

Co-authored-by: Claude <noreply@anthropic.com>
2025-08-14 10:53:03 +09:00
Yukihiro "Matz" Matsumoto 9fe7d6af6a mruby-set: improve Set#hash tests; ref #6587 2025-08-14 10:52:56 +09:00
Yukihiro "Matz" Matsumoto 8ebe0d3a15 test(set): ensure hash consistency 2025-07-25 18:12:48 +09:00
Yukihiro "Matz" Matsumoto 479711700e mruby-set: add comprehensive call-seq documentation for all Ruby methods
Added complete call-seq documentation for all 17 Ruby methods in mrblib/set.rb:

- initialize: Added examples showing set creation with and without blocks
- merge: Added examples showing element merging and self-modification
- replace: Added examples showing complete set replacement
- subtract: Added examples showing element removal from enumerable
- intersection (&): Added examples showing common elements between sets
- union (|, +): Added examples showing set combination operations
- difference (-): Added examples showing set subtraction operations
- ^ (exclusive or): Added examples showing symmetric difference
- each: Added examples showing iteration with blocks and enumerators
- delete_if: Added examples showing conditional element deletion
- keep_if: Added examples showing conditional element retention
- collect!/map!: Added examples showing in-place element transformation
- reject!: Added examples showing conditional deletion with nil return
- select!/filter!: Added examples showing conditional retention with nil return
- classify: Added examples showing element classification into hash
- divide: Added examples showing set division into subsets

Co-authored-by: Atlassian Rovo Dev
2025-07-17 14:46:41 +09:00
Yukihiro "Matz" Matsumoto 2735340702 kernel.c: remove mrb_inspect_recursive_p(); #5531
And use mrb_recursive_method_p() and its helper methods.

Co-authored-by: Claude <noreply@anthropic.com>
2025-07-11 10:09:37 +09:00
Yukihiro "Matz" Matsumoto 9b6bc8a3d8 set: use mrb_define_method_id and MRB_SYM()
Updated method definitions in mrbgems/mruby-set/src/set.c to use
mrb_define_method_id and MRB_SYM() for consistency and to leverage
presyms. This includes handling '?' and '!' in method names
with MRB_SYM_Q() and MRB_SYM_B() respectively, and using string
literals for mrb_define_alias.

Co-authored-by: Gemini <gemini@google.com>
2025-06-27 10:28:49 +09:00
Yukihiro "Matz" Matsumoto 2008d1733b mruby-set: use || operator in merge and subtract methods 2025-06-27 09:01:19 +09:00
Yukihiro "Matz" Matsumoto 62affa290f mruby-set: simplify initialize method return flow 2025-06-27 09:01:19 +09:00
Yukihiro "Matz" Matsumoto 6db72e01fe mruby-set: simplify optimized method pattern with || operator 2025-06-27 09:01:19 +09:00
Yukihiro "Matz" Matsumoto 192880c1e7 mruby-set: refactor internal methods for cleaner enumerable logic
Internal C functions now return a status, allowing Ruby methods
to avoid `is_a?(Set)` checks and simplify the logic for handling
different enumerable types.

Co-authored-by: Gemini <gemini@google.com>
2025-06-27 09:01:19 +09:00
Yukihiro "Matz" Matsumoto 456c8c97e8 mruby-set: optimize and refactor set_is_set()
- Use a direct type check instead of `mrb_obj_is_kind_of()` for efficiency.
- Remove the unused `mrb_state*` argument from the function signature.
2025-06-26 08:11:38 +09:00
Yukihiro "Matz" Matsumoto 3b2e2e0901 mruby-set: refactor kset_resize to prevent GC memory leak
Refactored `kset_resize` and `kset_put2` in `mrbgems/mruby-set/src/set.c`
to address a potential memory leak.

The previous implementation of `kset_resize` could lead to objects
referenced only by `old_keys` being garbage collected if a GC cycle
was triggered during calls to `mrb_obj_hash_code()` or `mrb_eql()`
while rehashing. This was because `s->data` was updated to the new,
empty data block before `old_keys` were fully processed.

Changes:
- Introduced a `kset_raw_put` function to encapsulate the common logic
  for inserting an element into a set's underlying arrays (keys/flags).
- Modified `kset_resize` to:
  - Keep the `old_data` pointer (and thus `old_keys`) valid and reachable
    throughout the rehashing process.
  - Allocate `new_data` and populate it using `kset_raw_put` for each
    element from `old_data`.
  - Free `old_data` only after all elements are successfully copied.
  - Update the main set structure (`s->data`, `s->n_buckets`, `s->size`)
    after the new data is fully prepared.
- Refactored `kset_put2` to use the `kset_raw_put` function, reducing
  code duplication.

This ensures that all mrb_value objects remain reachable during GC
cycles that might occur within the rehashing logic, preventing the
memory leak.
2025-06-26 07:56:49 +09:00
Yukihiro "Matz" Matsumoto c6801740a0 mruby-set (kset_resize): n_bucket inconsistency when GC happens 2025-06-25 17:47:49 +09:00
Yukihiro "Matz" Matsumoto c7bbd8e10f mruby-set: add mrb_static_assert_object_size
The C struct that implements Ruby object should fit in RVALUE.
2025-06-25 17:47:48 +09:00
Yukihiro "Matz" Matsumoto 5963fbb56b mruby-set: refactor set_reset
- implement kset_rehash()
- use kset_rehash() in set_reset()
- remove no longer used kset_copy()
2025-06-25 17:47:48 +09:00
Yukihiro "Matz" Matsumoto 4be57dd807 mruby-set: reduce forward declarations 2025-06-25 17:47:48 +09:00
Yukihiro "Matz" Matsumoto ea913f62be mruby-set (set_flatten_recursive): rename argument names 2025-06-25 17:47:48 +09:00
Yukihiro "Matz" Matsumoto 3f06d8e5ae mruby-set: adjust mrb_gc_arena_restore() places
- not before `return` statement (VM will do)
- at the bottom of KSET_FOREACH loop body
2025-06-25 17:47:47 +09:00
Yukihiro "Matz" Matsumoto 2644086977 mruby-set: remove names with kh that remain from last change 2025-06-25 17:47:47 +09:00
Yukihiro "Matz" Matsumoto 0edd0aec73 mruby-set: use KSET_FOREACH macro extensively
Implemented by: Rovo Dev
2025-06-25 13:33:39 +09:00
Yukihiro "Matz" Matsumoto fc6d7cc424 mruby-set: new helper function set_ensure_initialized 2025-06-25 13:23:21 +09:00