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>
Introduce "object shapes" (hidden classes) that share IV key
layouts across objects with the same instance variable assignment
order. This eliminates per-object key storage overhead.
Memory savings: ~22% heap reduction for object-heavy workloads
(e.g., 150k objects with 2-6 IVs). Per-object: 40->24 bytes
for 2 IVs. Objects exceeding 16 IVs or using
remove_instance_variable fall back to traditional iv_tbl.
Co-authored-by: Claude <noreply@anthropic.com>
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>
Add a dedicated uint32_t flags field to mrb_mt_entry instead of
packing flags into the lower bits of mrb_sym via MRB_MT_KEY().
The key field now stores the pure symbol ID with no shift.
On 64-bit, the flags field fills the alignment gap after mrb_sym,
so entry size remains 16 bytes (zero overhead). On 32-bit, entry
size grows from 8 to 12 bytes.
This eliminates the risk of symbol ID overflow from the 4-bit
shift, and the flags field can later store aspec (MRB_ARGS_*)
information that was previously discarded.
Co-authored-by: Claude <noreply@anthropic.com>
`&nil` is recently introduced in CRuby to explicitly declare that
a method does not accept a block. When a block is passed,
ArgumentError "no block accepted" is raised. This is analogous to
`**nil` for keyword arguments.
The noblock flag is encoded in bit 23 of OP_ENTER's aspec operand
(24=n1:m5:o5:r1:m5:k5:d1:b1), avoiding the need for a new opcode.
Co-authored-by: Claude <noreply@anthropic.com>
Replace per-symbol mrb_malloc() with a chunk-based string pool that
batches allocations into 4KB chunks. This reduces malloc call count
by ~12x (e.g. 909 vs 10,887 for 10k dynamic symbols) and eliminates
per-allocation malloc metadata overhead (~16 bytes/symbol).
Pool allocations are rounded up to even size to preserve LSB pointer
tagging used for literal detection.
Co-authored-by: Claude <noreply@anthropic.com>
With this PR, I can remove the original task.c in picoruby/picoruby and future development will be much easier.
## Add
### General
- C API functions exported with MRB_API for external integration:
- mrb_execute_proc_synchronously() for synchronous proc execution
- Task control APIs (mrb_create_task, mrb_suspend_task, mrb_resume_task, mrb_terminate_task, mrb_stop_task, mrb_task_value, mrb_task_status)
- Task context management APIs for picoruby-sandbox (mrb_task_init_context, mrb_task_reset_context, mrb_task_proc_set)
- Task.tick class method to get current tick count
- Comprehensive C API documentation with WASM integration examples
### For PicoRuby.wasm
- WASM/Emscripten support: Disable SIGALRM timer when __EMSCRIPTEN__ is defined, as JavaScript handles tick calls via setInterval
- Scheduler lock mechanism to prevent asynchronous task operations during synchronous execution (scheduler_lock counter in mrb_task_state)
- mrb_task_run_once() for single-step execution (event loop integration)
## Fix
### task.c
- Replace MRB_FIBER_TERMINATED with MRB_TASK_STOPPED just for clarity
- Allow suspending DORMANT and WAITING tasks in mrb_task_suspend (See comment in the source)
- Task context initialization by removing dummy callinfo push/pop
*NOTE*
With the dummy callinfo code that I deleted, IRB in PicoRuby ended SEGV.
If that code is mandatory, we need to discuss how to solve my problem.
### vm.c
- Handle MRB_TASK_CREATED status in VM's NORMAL_RETURN phase to properly stop tasks
----
These changes are necessary to make PicoRuby work.
Nevertheless, even with this patch, MicroRuby for Raspberry Pi Pico 2 is still unstable.
I would like to merge this PR anyway to make development easier by involving the PicoRuby community.
rename mrb_alloca() to mrb_temp_alloc() for clearer naming - the new name
better describes its purpose as GC-managed temporary allocation. keep
mrb_alloca() as a macro alias for backward compatibility.
apply mrb_temp_alloc() to fix potential memory leaks in:
- mruby-strftime: if mrb_str_cat() raises, allocated buffers now cleaned by GC
- mruby-io File.readlink: if mrb_str_new() raises, buffer now cleaned by GC
Co-authored-by: Claude <noreply@anthropic.com>
mrb_method_cache_clear() was called unconditionally from class.c and
state.c, but the function definition was guarded by MRB_NO_METHOD_CACHE.
This caused linker errors when building with MRB_NO_METHOD_CACHE defined.
Add empty macro definition when MRB_NO_METHOD_CACHE is defined, matching
the existing pattern used for mrb_mc_clear_by_class().
Co-authored-by: Claude <noreply@anthropic.com>
since all current uses check for failure (!MRB_OPEN_SUCCESS), add
MRB_OPEN_FAILURE() as the primary macro for better readability. define
MRB_OPEN_SUCCESS() in terms of MRB_OPEN_FAILURE() to avoid duplication
and optimize the common case. update all usage sites to use the clearer
MRB_OPEN_FAILURE() form.
Co-authored-by: Claude <noreply@anthropic.com>
changed mrb_open() and mrb_open_core() to return mrb_state with mrb->exc
set (instead of NULL) when initialization fails. this allows callers to
programmatically inspect error details, which is essential for embedded
systems without stderr. return NULL only for true allocation failure.
added MRB_OPEN_SUCCESS(mrb) macro to check initialization success, since
mrb != NULL no longer guarantees success. updated all binary tools
(mruby, mirb, mrdb, mrbtest) to use new pattern: check MRB_OPEN_SUCCESS,
print exception details via mrb_print_error if available, then mrb_close.
mrb_core_init_protect now preserves exception in mrb->exc instead of
printing and clearing it, giving caller control over error handling.
breaking change: callers must use MRB_OPEN_SUCCESS(mrb) or check both
mrb != NULL && mrb->exc == NULL. old NULL-only checks will miss
initialization failures.
Co-authored-by: Claude <noreply@anthropic.com>
when overriding struct#==, array#==, or hash#== with super, the recursion
detection incorrectly treated the super call as a circular reference. this
was caused by commit 5ca2d442 which added recursion detection.
the fix introduces mrb_recursive_func_p that starts from ci[-2] instead of
ci[-1], skipping the immediate parent frame which may be a ruby override
calling super. equality methods (==, eql?) now use this function, while
inspect methods keep using mrb_recursive_method_p for immediate circular
reference detection.
Co-authored-by: Claude <noreply@anthropic.com>
remove MRB_TASK_CREATED and MRB_TASK_STOPPED from mrb_fiber_state enum
and define them as aliases to MRB_FIBER_CREATED and MRB_FIBER_TERMINATED.
this makes the relationship between tasks and fibers clearer and avoids
artificially extending the enum with semantically equivalent values.
Co-authored-by: Claude <noreply@anthropic.com>
Implement main task wrapper following Fiber's pattern, where root context
is represented by a special task object. This matches PicoRuby behavior
where Task.current always returns a task object, even from root context.
The main task is lazy-allocated on first Task.current call from root,
stored in mrb->task.main_task, and has name "main", status RUNNING,
priority 0. It wraps the root context without allocating a separate
execution context.
Co-authored-by: Claude <noreply@anthropic.com>
replace confusing "tcb" (task control block) terminology with clearer
"mrb_task" naming:
- struct mrb_tcb -> struct mrb_task
- update mrb_task_state to use mrb_task pointers
- rename internal functions to avoid naming conflicts:
- mrb_task_new -> task_alloc
- mrb_task_free (lifecycle) -> task_free
- update field names for clarity:
- tcb_join -> join
- task (ruby object) -> self
- value (return value) -> result
this makes the code more readable and follows mruby naming conventions
like mrb_context, mrb_irep, etc.
Co-authored-by: Claude <noreply@anthropic.com>
extend mrb_fiber_state enum with task-specific states:
- MRB_TASK_CREATED: task context initialized
- MRB_TASK_STOPPED: task execution finished
add mrb_task_state structure to mrb_state:
- task queues array (dormant, ready, waiting, suspended)
- tick counter for scheduling
- wakeup_tick for sleep timing
- switching flag for context switches
remove duplicate mrb_task_state definition from task.h since it is
now defined in include/mruby.h. all changes guarded by
MRB_USE_TASK_SCHEDULER for zero overhead when disabled.
Co-authored-by: Claude <noreply@anthropic.com>
Replace fixed 256-element hash array in mrb_state with adaptive approach:
- Linear search for <=255 symbols (typical embedded use case)
- Hash table allocated on-demand when symbols exceed threshold
- Reduces mrb_state size by 1KB per instance (1068->36 bytes in symbol fields)
- Configurable threshold via MRB_SYMBOL_LINEAR_THRESHOLD in mrbconf.h
Co-authored-by: Claude <noreply@anthropic.com>
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
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>
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>
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.
There was a problem with visibility state from proc that straddles a fiber or is independent.
Therefore, it has been changed to give priority to env objects, if any.
Also, added "separate module" flag to block traversal to a higher level env object.
Note that the "separate module" flag is now set when calling blocks with the `mrb_yield_with_class()` function.
fixed https://github.com/mruby/mruby/issues/6494
To avoid confusion with pools in irep, we renamed region-based memory
manager from pool to mempool.
- rename pool.c to mempool.c
- separate mempool.h
- rename all mrb_pool to mrb_mempool
So if someone is using pool.c functions (I suppose no one does though),
they need to rename all `mrb_pool` to `mrb_mempool` and include
`mruby/mempool.h` header at the top.
This reverts commit ad2e626e7a.
Because of the changes made by #6282, the following code caused a problem.
```ruby
b = proc { break "BAD!" }
p self.tap { b.call }
# (expected) => break from proc-closure (LocalJumpError)
# (after #6282) => "BAD!"
```
I revived the `mrb_callinfo::blk` field to fix this, but it did not overcome the following problem.
```ruby
def m(&b); b = b.clone; GC.start; b.call; end
p m { break "OK!" }
# (expected) => "OK!"
# (revived blk) => break from proc-closure (LocalJumpError)
```
The purpose is to remove the `mid` field from the `mrb_cache_entry` structure.
The resulting RAM requirement for the method cache is reduced from 5 words per entry to 4 words per entry for 32-bit CPUs.
The relevant changes are as follows:
- Removed `MRB_USE_METHOD_T_STRUCT`.
The `mrb_method_t` type is now always defined as a structure.
- Include method IDs in `mrb_method_t`
Change the `flags` member to `uint32_t`.
The bitstring structure should be the same as the keys of the `mt` table in `class.c`.
I believe the impact on API compatibility with previous versions is minimal.