Commit Graph

1894 Commits

Author SHA1 Message Date
Yukihiro "Matz" Matsumoto 79fe70ffdc khash: move kh_alloc to internal helper
Move kh_alloc_##name from public API to internal helper kh__alloc_##name
since it's only used internally within khash implementation.

Changes:
- Remove kh_alloc_##name from KHASH_DECLARE
- Add kh__alloc_##name as static inline in KHASH_DEFINE
- Update internal calls to use kh__alloc_##name

Co-authored-by: Claude <noreply@anthropic.com>
2025-08-14 10:53:07 +09:00
Yukihiro "Matz" Matsumoto 0be8fdc030 khash: rename internal helpers to kh__ prefix and organize API boundary
Rename internal helper functions from kh_ to kh__ prefix while correctly
organizing the API boundary:

KHASH_DECLARE (public interface):
- kh_keys_##name, kh_vals_##name, kh_flags_##name (used by kh_exist macro)

KHASH_DEFINE (internal helpers with kh__ prefix):
- kh__kv_size_##name, kh__htable_size_##name
- kh__mark_occupied_##name, kh__mark_deleted_##name
- kh__key_idx_##name, kh__next_probe_##name
- kh__insert_key_##name, kh__clear_flags_##name
- kh__is_small_##name, kh__get_small_##name
- kh__rebuild_##name, kh__put_small_##name

This clearly separates public API functions from internal implementation
helpers while ensuring kh_flags_##name remains accessible to the public
kh_exist macro.

Co-authored-by: Claude <noreply@anthropic.com>
2025-08-14 10:53:06 +09:00
Yukihiro "Matz" Matsumoto f4e9bf603c khash: add helpers to eliminate key assignment and memset duplication
Add kh_insert_key and kh_clear_flags helper functions to remove remaining
code duplication patterns in KHASH_DEFINE. These helpers consolidate:

- Key assignment pattern: keys[index] = key; kh_mark_occupied; h->size++
- Flag clearing pattern: memset(kh_flags, 0xaa, n_buckets/4)

Co-authored-by: Claude <noreply@anthropic.com>
2025-08-14 10:53:06 +09:00
Yukihiro "Matz" Matsumoto 73111cacfb khash.h: add linear probing helper to eliminate duplication
Added kh_next_probe_##name() helper function to encapsulate the repeated
linear probing step calculation pattern.

Replaced 2 instances of manual probing calculation:
- k = (k+(++step)) & khash_mask(h) -> k = kh_next_probe_##name(k, &step, h)

This eliminates the duplicated bit manipulation pattern and makes the
probing logic more readable and less error-prone.

Co-authored-by: Claude <noreply@anthropic.com>
2025-08-14 10:53:06 +09:00
Yukihiro "Matz" Matsumoto f46b57e22e khash.h: add unified rebuild helper to eliminate major duplication
Added kh_rebuild_##name() helper function that consolidates the complete
"save-allocate-rehash-cleanup" pattern shared between kh_resize and
kh_put_small functions.

The helper intelligently handles both scenarios:
- Small table conversion: iterates by size
- Hash table resize: iterates by buckets with flag checks

This eliminates approximately 25 lines of duplicated code across the
two functions while maintaining identical functionality.

Co-authored-by: Claude <noreply@anthropic.com>
2025-08-14 10:53:06 +09:00
Yukihiro "Matz" Matsumoto da09bae640 khash.h: inline kh_alloc_small function used only once
Removed kh_alloc_small_##name() function and inlined its body into the
single call site in kh_init_data_##name(). This eliminates unnecessary
function call overhead and reduces code complexity.

The function was only 2 lines and called once, making it an ideal
candidate for inlining.

Co-authored-by: Claude <noreply@anthropic.com>
2025-08-14 10:53:06 +09:00
Yukihiro "Matz" Matsumoto 22a6debf40 khash: improve helper function naming and add htable size helper
Renamed size calculation helpers for clarity:
- kh_data_size_##name() -> kh_kv_size_##name() (keys and values only)
- Added kh_htable_size_##name() (complete hash table including flags)

Updated all usages and simplified patterns:
- kh_kv_size_##name(n) + n/4 -> kh_htable_size_##name(n)

The new names clearly distinguish between:
- kv_size: just the key-value data
- htable_size: complete hash table allocation (data + flags)

This eliminates confusion and makes the code more self-documenting.

Co-authored-by: Claude <noreply@anthropic.com>
2025-08-14 10:53:06 +09:00
Yukihiro "Matz" Matsumoto 7cfc863353 khash: add hash calculation helper to eliminate duplication
Added kh_key_idx_##name() helper function to encapsulate the repeated
pattern of calculating bucket index from key hash.

Replaced 2 instances of manual hash calculation:
- __hash_func(mrb,key) & khash_mask(h) → kh_key_idx_##name(mrb, key, h)

This eliminates the duplicated hash-and-mask pattern and makes the code
more readable by clearly expressing the intent (get bucket index for key).

Co-authored-by: Claude <noreply@anthropic.com>
2025-08-14 10:53:05 +09:00
Yukihiro "Matz" Matsumoto 633544e087 khash: add flag operation helpers to eliminate bit manipulation duplication
Added two helper functions to encapsulate repeated flag manipulation patterns:
- kh_mark_occupied_##name(): clears both empty and deleted bits
- kh_mark_deleted_##name(): sets the deleted bit

Replaced 3 instances of manual bit manipulation with calls to these helpers:
- ed_flags[del_k/4] &= ~__m_del[del_k%4] → kh_mark_occupied_##name(h, del_k)
- ed_flags[k/4] &= ~__m_empty[k%4] → kh_mark_occupied_##name(h, k)
- ed_flags[x/4] |= __m_del[x%4] → kh_mark_deleted_##name(h, x)

This eliminates error-prone bit operations, improves readability, and makes
the flag state transitions self-documenting.

Co-authored-by: Claude <noreply@anthropic.com>
2025-08-14 10:53:05 +09:00
Yukihiro "Matz" Matsumoto 71c5e2c536 khash: move internal helpers from KHASH_DECLARE to KHASH_DEFINE
Moved kh_data_size_##name() and kh_flags_##name() from KHASH_DECLARE
to KHASH_DEFINE section where internal implementation details belong.

This improves the separation of concerns:
- KHASH_DECLARE: public API only (struct definition, function declarations)
- KHASH_DEFINE: implementation details and internal helper functions

No functional changes, only better code organization.

Co-authored-by: Claude <noreply@anthropic.com>
2025-08-14 10:53:05 +09:00
Yukihiro "Matz" Matsumoto 8bcd0d247e khash: add size calculation helper and refactor for better organization
Added kh_data_size_##name() helper function to eliminate duplicated size
calculation patterns throughout the khash implementation. This single
universal helper calculates data size for N elements and replaces all
manual sizeof calculations.

Key changes:
- Add kh_data_size_##name(khint_t count) helper in KHASH_DECLARE
- Replace manual calculations in kh_flags, kh_alloc_small, kh_alloc
- Replace complex size calculations in kh_replace function
- Use specific patterns: small tables use KHASH_SMALL_THRESHOLD,
  hash tables add n_buckets/4 for flag space

This refactoring eliminates 6 instances of duplicated size calculation
code while maintaining identical functionality and performance.

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 069da276f6 khash: fix small table implementation bugs
- Fix kh_exist macro to handle small tables correctly by checking size
  instead of non-existent flags
- Add proper small table deletion in kh_del function with element shifting
- Fix kh_copy to use corrected kh_exist macro instead of direct flag access
- Remove unused ed_flags variable in kh_copy function

Co-authored-by: Claude <noreply@anthropic.com>
2025-08-14 10:53:04 +09:00
Yukihiro "Matz" Matsumoto 344d28f961 khash.h (kh_destroy): both kh_destroy_data and mrb_free works with NULL 2025-08-14 10:53:04 +09:00
Yukihiro "Matz" Matsumoto 4624fcce56 khash: simplify allocation functions by using mrb_malloc directly
Remove kh_alloc_simple_* functions and explicit mrb_raise_nomemory calls
since mrb_malloc already handles memory allocation failures and raises
nomemory exceptions automatically, unlike mrb_malloc_simple.

This simplifies the code by removing redundant error handling.

Co-authored-by: Claude <noreply@anthropic.com>
2025-08-14 10:53:04 +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 3cd2201b70 khash: add kh_init_data and kh_destroy_data functions
Add core data initialization functions that handle only the internal data
allocation/deallocation without managing the khash struct itself.

Changes:
- Add kh_init_data_##name() for initializing khash internal data
- Add kh_destroy_data_##name() for cleaning up khash internal data
- Refactor kh_init_##name##_size() to use kh_init_data internally
- Refactor kh_destroy_##name() to use kh_destroy_data internally
- Add corresponding kh_init_data() and kh_destroy_data() macros

Benefits:
- Eliminates code duplication between init/destroy and embed functions
- Provides clear separation: data functions handle internals, regular functions handle struct lifecycle
- Enables embedding khash in other structures (e.g., mruby-set's RSet)
- Centralizes complex initialization logic in single implementation

Architecture:
- kh_init_data/kh_destroy_data: core implementation with small table optimization
- kh_init_size/kh_destroy: convenience wrappers that add struct allocation
- Same functionality preserved, all tests pass

This prepares khash for mruby-set integration while improving code organization
and maintainability.

Co-authored-by: Claude <noreply@anthropic.com>
2025-08-14 10:53:03 +09:00
Yukihiro "Matz" Matsumoto 56f798fb44 khash: add small table optimization with linear search
Optimize hash tables with <=4 elements by using linear search instead of
hash table structure, eliminating flag storage and hash computation overhead.

Changes:
- Add KHASH_SMALL_THRESHOLD constant (4 elements)
- Implement linear search for small tables (kh_get_small/kh_put_small)
- Add automatic conversion from small table to hash table when growing
- Start with small table mode in kh_init_size for small requests
- Update kh_end macro to handle small table mode (n_buckets == 0)
- Inline conversion logic directly in kh_put_small for efficiency

Memory impact:
- 40-60% memory reduction for tables with <=4 elements
- Eliminates flag storage and wasted bucket allocation for small tables
- 100% memory utilization vs ~50% in regular hash tables
- Particularly beneficial for mruby's embedded environment

Performance impact:
- Linear search faster than hash computation for <=4 elements
- Better cache locality with sequential memory access
- No hash function calls for small tables
- Automatic conversion ensures scalability for larger tables
- All existing tests pass with identical functionality

Small tables are common in mruby (instance variables, method tables,
small configuration objects), making this optimization valuable for
memory-constrained embedded environments.

Co-authored-by: Claude <noreply@anthropic.com>
2025-08-14 10:53:03 +09:00
Yukihiro "Matz" Matsumoto 16015f126e khash: optimize load factor from 75% to 87.5% for memory reduction
Increase hash table load factor to reduce memory usage in embedded
environments. Trade slight performance decrease for memory savings.

Changes:
- Rename UPPER_BOUND to KH_UPPER_BOUND to avoid name conflicts
- Adjust load factor from 75% to 87.5% (from (x)*3/4 to (x)*7/8)
- Add documentation explaining memory vs performance trade-off

Memory impact:
- Delays hash table resizes, allowing more efficient memory utilization
- Particularly beneficial for applications with many hash tables
- Reduces wasted bucket allocation in resize-heavy scenarios
- Aligns with mruby's memory-first design priority

Performance impact:
- Slightly more hash collisions (~43% increase in average probes)
- Minimal real-world impact due to good cache locality in linear probing
- All existing tests pass with identical functionality

The optimization is especially valuable for mruby's embedded target
environment where memory is more constrained than CPU cycles.

Co-authored-by: Claude <noreply@anthropic.com>
2025-08-14 10:53:03 +09:00
Yukihiro "Matz" Matsumoto 2371b52ab4 khash: optimize structure size by 50% with single data pointer
BREAKING CHANGE: khash field access macros now require type name parameter

Replace individual pointer fields (keys, vals, ed_flags) with single data
pointer and address calculation functions. This reduces khash structure
size from 32 to 16 bytes (50% reduction) while maintaining performance
through pointer caching in hot paths.

Structure changes:
- Single void *data field replaces keys/vals/ed_flags pointers
- Address calculation functions compute array locations on demand
- Hot path functions cache calculated pointers for performance

API changes (BREAKING):
- kh_key(h, x)      -> kh_key(typename, h, x)
- kh_val(h, x)      -> kh_val(typename, h, x)
- kh_exist(h, x)    -> kh_exist(typename, h, x)
- kh_value(h, x)    -> kh_value(typename, h, x)
- KHASH_FOREACH()   -> KHASH_FOREACH(typename, ...)

Migration required:
- mruby-metaprog: 4 call sites updated (familiar macro names, just add type parameter)
- mruby-array-ext: no changes needed (uses function-style API)
- External users: add type name as first parameter to field access macros

Benefits:
- 50% memory reduction per hash table (32 -> 16 bytes)
- 464 bytes total memory savings in mrbtest execution
- Better cache locality with smaller structures
- Optimized hot path performance with pointer caching
- Consistent with mruby memory-first design priority

Co-authored-by: Claude <noreply@anthropic.com>
2025-08-14 10:53:02 +09:00
Yukihiro "Matz" Matsumoto ad3a79f236 khash.h: replace kh_fill_flags with memset
Co-authored-by: Gemini <gemini@google.com>
2025-08-14 10:53:02 +09:00
Yukihiro "Matz" Matsumoto 07b803e28a docs: replace xml-style markup with markdown in comments
Replace XML-style markup tags in comments with markdown equivalents:
- <code>...</code> to `...` (inline code)
- <tt>...</tt> to `...` (teletype/monospace)
- <i>...</i> to *...* (italics/emphasis)
- +...+ to `...` (parameter/variable references)

Updated 80+ files across core source, headers, mrbgems, and libraries
to use consistent markdown formatting in documentation comments.
Handled edge cases including special characters like <=> operators.

Co-authored-by: Atlassian Rovo Dev
2025-08-14 10:52:49 +09:00
Yukihiro "Matz" Matsumoto fe4ed7e68d mruby-numeric-ext: implement integer#gcd and Integer#lcm methods
implement Integer#gcd and Integer#lcm methods in mruby-numeric-ext with full
support for both regular integers and bigints.

key changes:
- add mrb_int_gcd euclidean algorithm for regular integer gcd calculation
- implement int_gcd and int_lcm methods with proper type checking and bigint fallback
- add mrb_bint_gcd, mrb_bint_lcm, mrb_bint_abs functions to bigint api
- register gcd and lcm methods with integer class
- add comprehensive test coverage for both regular and bigint cases

Co-authored-by: Claude <noreply@anthropic.com>
2025-08-14 10:52:46 +09:00
Yukihiro "Matz" Matsumoto 7b0ee01310 mruby-random: support bigint in rand method
To achieve this, the following changes were made:

- Exported `mrb_bint_size`, `mrb_bint_from_bytes`, and `mrb_bint_sign`
  functions from `mruby-bigint` to be used in other mrbgems.
- Modified `mruby-random` to use these new functions to handle Bigint
  arguments in the `rand` method.

Co-authored-by: Gemini <gemini@google.com>
2025-08-14 10:52:46 +09:00
dearblue 91f2dca111 Merge mrb_obj_iv_inspect() into mrb_obj_inspect()
`mrb_obj_iv_inspect()` is an internal implementation function and is not called by any function other than `mrb_obj_inspect()`.
2025-07-21 20:54:50 +09:00
Yukihiro "Matz" Matsumoto 95656c40ff state.c: optimize mrb_state initialization by deferring method cache clear
During mrb_state initialization, especially when defining core classes and methods,
the method cache is repeatedly cleared. This causes significant overhead in
scenarios like mrbtest where mrb_state is initialized multiple times.

This commit introduces a `bootstrapping` flag in `struct mrb_state`.
When this flag is TRUE (during mrb_open_core), method cache clears
triggered by `mrb_define_method_raw` and `include_module_at` are suppressed.
The cache is cleared only once at the very end of `mrb_open_core` after
all core methods are defined, and the flag is then set to FALSE.

This optimization significantly reduces the number of method cache clears
during initialization, improving performance for repeated mrb_state creations.

Co-authored-by: Gemini <gemini@google.com>
2025-07-11 10:09:38 +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 419c8ebfb2 hash.c: add recursion detection to prevent SystemStackError; fix #5531
Add generalized recursion detection system and integrate it into Hash#==
and Hash#eql? to prevent infinite recursion with mutually recursive hash
structures. Uses call stack inspection for minimal memory overhead.

Co-authored-by: Claude <noreply@anthropic.com>
2025-07-11 10:09:36 +09:00
Yukihiro "Matz" Matsumoto 670b54f859 variable.h: add prefetch to bsearch_idx
This commit introduces memory prefetching to the `bsearch_idx` functions
in `src/class.c` and `src/variable.c` to improve performance.

A new macro `MRB_MEM_PREFETCH` is defined in `include/mruby/variable.h`
which uses `__builtin_prefetch` if available.

Co-authored-by: Gemini <gemini@google.com>
2025-07-11 10:09:35 +09:00
Yukihiro "Matz" Matsumoto c4464fa25a array.c: expose mrb_ary_dup() as a new C API 2025-06-29 20:46:51 +09:00
John Bampton 383cd6a936 misc: fix spelling word case 2025-06-25 10:46:23 +10:00
Yukihiro "Matz" Matsumoto a6a0346e1c mruby-os-memsize: support Set class 2025-06-24 13:56:07 +09:00
Yukihiro "Matz" Matsumoto 132561418b mruby-set: update Set class to use struct RSet not struct RData 2025-06-24 13:45:14 +09:00
google-labs-jules[bot] dfd7251223 Refactor: Improve Set GC marking and freeing
This commit addresses feedback on the initial Set GC marking implementation.

Changes include:
- Renamed set marking function to `mrb_gc_mark_set` and updated its
  return type to `size_t`.
- Introduced an explicit `mrb_gc_free_set` function for Set objects.
- Updated `gc_mark_children` to use the new mark function signature.
- Added an explicit `case MRB_TT_SET:` in `obj_free` to call `mrb_gc_free_set`.
- Adjusted `set_get_khash` in `mruby-set` to work with `MRB_TT_SET` directly,
  rather than relying on `mrb_data_get_ptr`.
- Corrected type checks in `set_init_copy` to use `MRB_TT_SET`.
- Updated function prototypes in internal headers and stubs in mrbc.
2025-06-24 04:02:41 +00:00
Yukihiro "Matz" Matsumoto 791b374155 khash.h: reduce KHASH_DEFAULT_SIZE from 32 to 8 2025-06-23 17:07:31 +09:00
Yukihiro "Matz" Matsumoto bce8cee8f9 khash.h (KHASH_FOREACH): a new macro to iterate over khash table 2025-06-23 17:07:28 +09:00
Yukihiro "Matz" Matsumoto 695207be68 hash.c (mrb_obj_hash_code): expose hash function 2025-06-23 17:07:21 +09:00
Yukihiro "Matz" Matsumoto eb5fbfbb40 class.c: Remove MRB_INLINE_METHOD_CACHE support from mt_tbl
The sorted array binary search implementation no longer uses the inline
cache array, so remove all MRB_INLINE_METHOD_CACHE definitions and
related code.
2025-05-28 08:33:21 +09:00
Yukihiro "Matz" Matsumoto 9fc58852e3 mruby-compiler: removed mrb_state dependency from two functions
- mrb_ccontext_partial_hook
- mrb_ccontext_cleanup_local_variables
2025-05-19 08:00:36 +09:00
Yukihiro "Matz" Matsumoto 9ef2f551b7 mruby-compiler: use new mempool API 2025-05-13 08:13:48 +09:00
Yukihiro "Matz" Matsumoto c2d5a402ba compile.h: change struct mrb_mempool to mrb_mempool
So that compatibility layer can be used without macro definition.
2025-05-12 12:30:15 +09:00
Yukihiro "Matz" Matsumoto 6566099dbb mempool.c: remove mrb_state dependency from mempool library
mempool.h provide compatibility layer so that existing programs does not
need to update (but update recommended anyway, since compatibility layer
takes mrb_state that is not used at all).
2025-05-12 08:26:18 +09:00
Yukihiro "Matz" Matsumoto 5522c94bb3 mruby.h: remove mrb_allocf type
As a result, we removed (already obsoleted) `mrb_open_allocf()', and
made `mrb_open_core()` take no argument. [incompatible changes]
2025-05-10 08:59:18 +09:00
Yukihiro "Matz" Matsumoto 5c71681d82 allocf.c (mrb_basic_alloc_func): remove ud argument 2025-05-10 08:59:18 +09:00
Yukihiro "Matz" Matsumoto c3cc559dfc allocf.c: rename mrb_default_alloc to mrb_basic_alloc_func
Along with removing mrb_state first argument from the function. From
mruby 3.2, this function is *not* the default function, but the entry
point that can be redefined for the application. The function in
`src/allocf.c` is the default *implementation* (using malloc / realloc /
free) of the function.
2025-05-09 21:50:18 +09:00
Yukihiro "Matz" Matsumoto 0bdd529430 mruby.h: remove allocf and allocf_ud from mrb_state
This is preparation for memory allocation restructuring.
2025-05-09 18:13:28 +09:00
Yukihiro "Matz" Matsumoto dbc4768758 mruby/internal.h: rename visibility separation macros; ref #6512 2025-05-08 07:32:36 +09:00
Yukihiro "Matz" Matsumoto c9a36e5d39 mruby/value.h: rename flag check macros; ref #6512 2025-05-08 07:27:30 +09:00
Yukihiro "Matz" Matsumoto 41e91a2ca8 vm.c (mrb_exec_irep): remove recently added separate_module argument
The argument was added in #6512
2025-05-08 07:27:23 +09:00
Yukihiro "Matz" Matsumoto aec8d0c58b Merge branch 'visibility' of github.com:dearblue/mruby into dearblue-visibility 2025-05-07 15:37:08 +09:00