72 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 b460554d33 vm.c: generalize pre-dispatch argument count check for C methods
Replace check_method_noarg() with check_argument_count() that validates
min <= argc <= max using the full aspec stored in mrb_method_t.flags.
This catches ArgumentError earlier at dispatch time, before entering
the C function.

The old check only handled the special case of aspec==0 (NOARG).
The new check extracts REQ, OPT, REST, POST, KEY, and KDICT from
the aspec and validates accordingly. Keyword hash is counted as
a positional arg only when the method doesn't accept keywords.

Remove MRB_METHOD_NOARG_P macro from proc.h (subsumed by aspec check).
Fix 15 incorrect aspec declarations across the codebase that were
exposed by the stricter enforcement.

Co-authored-by: Claude <noreply@anthropic.com>
2026-02-20 14:25:48 +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 20b9002214 class.c: merge conditional methods into ROM tables
Move conditional mrb_define_method_id() calls into ROM entry
arrays using #ifdef guards. With linear search, sizeof in
MRB_MT_ROM_TAB() adjusts automatically after preprocessing.

Cross-class ROM tables (methods a gem defines on a class it does
not own) are reverted to mrb_define_method_id(). Multiple gems
should not add ROM table layers to the same class; each layer
costs a 16-byte mrb_mt_tbl struct in RAM and deepens the lookup
chain. Use mrb_define_method_id() for cross-class methods.

Co-authored-by: Claude <noreply@anthropic.com>
2026-02-20 11:05:03 +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 067f123193 mruby-method: ROM method tables for Method/UnboundMethod classes
Co-authored-by: Claude <noreply@anthropic.com>
2026-02-19 09:39:28 +09:00
Yukihiro "Matz" Matsumoto eca051e022 mruby-method: add comprehensive documentation for all public methods
Added call-seq documentation for 16 key functions addressing critical 0%
documentation coverage. Includes method signatures, clear descriptions,
practical examples, and expected output for Method, UnboundMethod, Kernel,
and Module method introspection functionality.

Co-authored-by: Atlassian Rovo Dev
2025-07-09 13:49:59 +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
dearblue 3fd5e1c250 Fixed visibility at method definition
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
2025-04-11 21:36:26 +09:00
dearblue a981f5aed7 Add more const qualifier for RProc 2025-01-20 22:25:50 +09:00
Yukihiro "Matz" Matsumoto 8faf78f1b8 mruby-method: singleton_method() should search in superclasses
[ruby-bugs:20620](https://bugs.ruby-lang.org/issues/20620)
2024-10-04 21:37:49 +09:00
Yukihiro "Matz" Matsumoto d5fd3338a4 mruby-method: use presym for initialization 2024-06-14 01:46:22 +09:00
Yukihiro "Matz" Matsumoto ae6e5b7b5e mruby-method: adjust local variable declaration place 2024-05-13 23:37:21 +09:00
Yukihiro "Matz" Matsumoto 87b358a342 Including header files in include/* by <> 2024-03-26 13:59:59 +09:00
dearblue 8ecfacefca Prohibit Class#allocate in a different way
The method introduced by #5979 causes a fault by swapping classes.

```console
% bin/mruby -e 'Method = Proc; p Object.method(:inspect)'
zsh: segmentation fault (core dumped)  bin/mruby -e 'Method = Proc; p Object.method(:inspect)'
```

After applying this patch, a `TypeError` exception will be raised.

```console
% bin/mruby -e 'Method = Proc; p Object.method(:inspect)'
trace (most recent call last):
        [1] -e:1
-e:1:in method: allocation failure of Proc (TypeError)
```

However, if the `mrb_vtype` is the same object, the same care must still be taken as before.

```console
% bin/mruby -e 'Method = Binding; p method(:puts).eval("12345")'
trace (most recent call last):
        [1] -e:1
-e:1:in eval: wrong argument type nil (expected Proc) (TypeError)
```
2023-12-22 21:59:34 +09:00
Yukihiro "Matz" Matsumoto bef7eea468 mruby-method: small refactoring mostly regarding declarations 2023-12-06 22:20:38 +09:00
Yukihiro "Matz" Matsumoto 7f1ae1c344 mruby-method (method_to_s): avoid goto across declarations for C++ 2023-12-03 22:39:27 +09:00
Yukihiro "Matz" Matsumoto 9eae7df26e mruby-method (method_to_s): _proc may be nil; add check 2023-12-03 22:38:31 +09:00
Yukihiro "Matz" Matsumoto 02f189cebc mruby-method (method_to_s): add origin name in the string representation 2023-12-03 22:38:30 +09:00
Yukihiro "Matz" Matsumoto f5bc82f267 mruby-method (method_to_s): avoid origin class like Object(Object) 2023-12-03 22:38:30 +09:00
Yukihiro "Matz" Matsumoto b52870b4c6 mruby-method: add const modifier to struct RProc* 2023-12-03 22:38:29 +09:00
Yukihiro "Matz" Matsumoto 95e09c0c95 mruby-method: implement Kernel#singleton method in C
- Also fixes error message inconsistency
- Avoid unnecessary method object allocation if possible
2023-08-22 10:53:52 +09:00
Yukihiro "Matz" Matsumoto c32f7915fb reformat else clause indentation style 2023-05-20 00:21:01 +09:00
dearblue d3128ce58a Allow Class#allocate to be prohibited
Calling `Class#allocate` with `UnboundMethod#bind_call` usually succeeds without problems.
If this behavior does not make us happy, we can now prohibit it with `MRB_SET_INSTANCE_TT(klass, MRB_TT_UNDEF)`.

At the same time, it applies to the `Binding`, `Complex`, `Data`, `Float`, `Integer`, `Method`, `Rational` and `UnboundMethod` classes.
2023-04-09 21:14:07 +09:00
Yukihiro "Matz" Matsumoto eaaa474630 mruby-method/method.c: fix proc comparison for uncovered case 2023-04-01 10:37:16 +09:00
Yukihiro "Matz" Matsumoto 1f5a4d5386 mruby-method/method.c (method_eql): simplify the logic 2023-03-27 19:21:40 +09:00
Yukihiro "Matz" Matsumoto 553f9ba802 mruby-method/method.c (method_eql): use mrb_proc_eql 2023-03-27 19:15:03 +09:00
Yukihiro "Matz" Matsumoto 0f63551def mruby-method/method.c (method_p): stricter method type check 2023-03-27 11:32:15 +09:00
Yukihiro "Matz" Matsumoto 5617de0071 mruby-method/method.c (method_eql): do not check _klass for equality. 2022-11-03 23:38:27 +09:00
Yukihiro "Matz" Matsumoto e7e22ec6a8 mruby-method/method.c (method_to_s): add location information.
Test updated too.
2022-10-04 11:05:14 +09:00
Yukihiro "Matz" Matsumoto 3c16423c0a mruby-method/method.c (method_to_s): making it compatible with CRuby. 2022-09-29 11:00:49 +09:00
Yukihiro "Matz" Matsumoto 5e1c16653f mruby-method/method.c (method_super_method): fixed module related bug.
When the method is defined in module, super_method started method
searching from wrong point. We needed to find ICLASS corresponding to the
module, then start searching super_method from the next ancestor.
2022-09-27 23:03:38 +09:00
Yukihiro "Matz" Matsumoto 4107cc95a2 internal.c: move some functions to <mruby/internal.h>.
Ref #5776
2022-08-15 18:13:59 +09:00
Yukihiro "Matz" Matsumoto 37dc1be74b internal.c: move mrb_method_missing prototype to <mruby/internal.h>.
Ref #5776
2022-08-15 17:25:08 +09:00
Yukihiro "Matz" Matsumoto b99c389ec3 internal.h: aggregate internal functions.
Internal functions can only be called from within the library.
Functions listed in `mruby/internal.h` can be called from:

* core (src/*.c)
* gems (mrbgems/**/*.c)

But not from the application linked with `libmruby`.
2022-04-02 18:25:13 +09:00
dearblue 58a9621df7 Fix args_unshift() in mrbgems/mruby-method
Both keyword arguments and block arguments were being destroyed when there were no arguments.
The cause of this is #5585. I' m sorry.
2021-11-28 14:10:37 +09:00
dearblue 668b12e756 Check more MRB_ARGS_NONE()
The `__id__` method implemented in the C function has `MRB_ARGS_NONE()` specified, but it is also effective in the following cases.

```ruby
p nil.__id__ opts: 1 rescue p :a
p nil.method(:__id__).call 1 rescue p :b
p nil.method(:__id__).call opts: 1 rescue p :c
p nil.method(:__id__).to_proc.call 1 rescue p :d
p nil.method(:__id__).to_proc.call opts: 1 rescue p :e
p nil.method(:__id__).unbind.bind_call nil, 1 rescue p :f
p nil.method(:__id__).unbind.bind_call nil, opts: 1 rescue p :g
p nil.__send__ :__id__, 1 rescue p :h
p nil.__send__ :__id__, opts: 1 rescue p :i
```

After applying this patch, all items will output symbols in the same way as CRuby.

For this purpose, add `MRB_PROC_NOARG` to `struct RProc::flags`.
2021-11-26 12:18:41 +09:00
dearblue 16e388863a Fixed some methods where keyword arguments are not passed 2021-11-24 23:35:42 +09:00
dearblue b02bd63dc5 Fixed occurs SIGSEGV with mrbgems/mruby-method
Calling the `Method#{parameters,source_location}` method on a static `Proc` object resulted in `SIGSEGV`.
The trigger is https://github.com/mruby/mruby/pull/5402.

The original implementation of the `Method#{parameters,source_location}` method was to temporarily rewrite the object and then call the method of the same name in `Proc`.
Rewriting of objects placed in the ROM section by #5402 above is prohibited by hardware such as the CPU.
This caused a `SIGSEGV`.
2021-11-22 21:55:02 +09:00
Yukihiro "Matz" Matsumoto dccd66f9ef Support Ruby3.0 keyword arguments.
The Difference

Since Ruby1.9, the keyword arguments were emulated by Ruby using the hash
object at the bottom of the arguments. But we have gradually moved toward
keyword arguments separated from normal (positinal) arguments.

At the same time, we value compatibility, so that Ruby3.0 keyword
arguments are somewhat compromise. Basically, keyword arguments are
separated from positional arguments, except when the method does not
take any formal keyword arguments, given keyword arguments (packed
in the hash object) are considered as the last argument.

And we also allow non symbol keys in the keyword arguments. In that
case, those keys are just passed in the `**` hash (or raise
`ArgumentError` for unknown keys).

The Instruction Changes

We have changed `OP_SEND` instruction. `OP_SEND` instruction used to
take 3 operands, the register, the symbol, the number of (positional)
arguments. The meaning of the third operand has been changed. It is now
considered as `n|(nk<<4)`, where `n` is the number of positional
arguments, and `nk` is the number of keyword arguments, both occupies
4 bits in the operand.

The number `15` in both `n` and `nk` means variable sized arguments are
packed in the object. Positional arguments will be packed in the array,
and keyword arguments will be packed in the hash object. That means
arguments more than 14 values are always packed in the object.

Arguments information for other instructions (`OP_SENDB` and `OP_SUPER`)
are also changed. It works as the third operand of `OP_SEND`. the
difference between `OP_SEND` and `OP_SENDB` is just trivial. It assigns
`nil` to the block hidden arguments (right after arguments).

The instruction `OP_SENDV` and `OP_SENDVB` are removed. Those
instructions are replaced by `OP_SEND` and `OP_SENDB` respectively with
the `15` (variable sized) argument information.

Calling Convention

When calling a method, the stack elements shall be in the order of the
receiver of the method, positional arguments, keyword arguments and the
block argument. If the number of positional or keyword arugument (`n` or
`nk`) is zero, corresponding arguments will be empty. So when `n=0` and
`nk=0` the stack layout (from bottom to top) will be:

+-----------------------+
| recv | block (or nil) |
+-----------------------+

The last elements `block` should be explicitly filled before `OP_SEND`
or assigned to `nil` by `OP_SENDB` internally. In other words, the
following have exactly same behavior:

OP_SENDB clears `block` implicitly:

```
OP_SENDB reg sym 0
```

OP_SEND clears `block` implicitly:

```
OP_LOADNIL  R2
OP_SEND     R2 sym 0
```

When calling a method with only positional arguments (n=0..14) without
keyword arguments, the stack layout will be like following:

+--------------------------------------------+
| recv | arg1 | ... | arg_n | block (or nil) |
+--------------------------------------------+

When calling a method with arguments packed in the array (n=15) which
means argument splat (*) is used in the actual arguments, or more than
14 arguments are passed the stack layout will be like following:

+-------------------------------+
| recv | array | block (or nil) |
+-------------------------------+

The number of the actual arguments is determined by the length of the
argument array.

When keyword arguments are given (nk>0), keyword arguments are passed
between positional arguments and the block argument. For example, when
we pass one positional argument `1` and one keyword argument `a: 2`,
the stack layout will be like:

+------------------------------------+
| recv | 1 | :a | 2 | block (or nil) |
+------------------------------------+

Note that keyword arguments consume `2*nk` elements in the stack when
`nk=0..14` (unpacked).

When calling a method with keyword arguments packed in the hash object
(nk=15) which means keyword argument splat (**) is used or more than
14 keyword arguments in the actual arguments, the stack layout will
be like:

+------------------------------+
| recv | hash | block (or nil) |
+------------------------------+

Note for mruby/c

When mruby/c authors try to support new keyword arguments, they need
to handle the new meaning of the argument information operand. If they
choose not to support keyword arguments in mruby/c, it just raise
error when `nk` (taken by `(c>>4)&0xf`) is not zero. And combine
`OP_SENDV` behavior with `OP_SEND` when `n` is `15`.

If they want to support keyword arguments seriously, contact me at
<matz@ruby.or.jp> or `@yukihiro_matz`. I can help you.
2021-10-12 20:16:36 +09:00
dearblue c182903ea0 Fixed finding variables from proc in binding.eval failed
Previously the following code did not produce the expected results:
```ruby
bx = binding
block = bx.eval("a = 1; proc { a }")
bx.eval("a = 2")
p block.call  # Expect 2 but return 1 due to a bug
```

The previous implementation of `Binding#eval` evaluated the code and then merged the top layer variables.
This patch will parse and expand the variable space before making a call to `eval`.
This means that the call to `Binding#eval` will do the parsing twice.

In addition, the following changes will be made:
- Make `mrb_parser_foreach_top_variable()`, `mrb_binding_extract_proc()` and `mrb_binding_extract_env()` functions private global functions.
- Remove the `posthook` argument from `mrb_exec_irep()`.
  The `posthook` argument was introduced to implement the `binding` method.
  This patch is unnecessary because it uses a different implementation method.

ref #5362
fixed #5491
2021-06-26 13:43:36 +09:00
dearblue cc95e346fd Added MRB_OBJ_ALLOC() macro that does not require a cast
The `MRB_OBJ_ALLOC()` macro function returns a pointer of the type corresponding to the constant literal defined in `enum mrb_vtype`.
2021-06-20 11:08:28 +09:00
dearblue 4c196dcdaa Reorganize mcall() in mruby-method.
Use `mrb_exec_irep()`. If possible, re-entry into the VM will be suppressed.

Note that due to the effect of being a tail-call, the backtrace of `Method#call` will be lost, and it will look as if the target method was called directly.

This change fixes the problem of infinite loops when redefining methods that make block calls using `mruby-method`.

```console
% bin/mruby -e 'mm = method(:proc); define_method(:proc, ->(*a, &b) { mm.call(*a, &b) }); p proc { 1 }'
trace (most recent call last):
        [257] -e:1
        [256] -e:1:in proc
        [255] -e:1:in proc
        ...SNIP...
        [1] -e:1:in proc
-e:1:in proc: stack level too deep (SystemStackError)
```
2021-04-03 21:20:59 +09:00
Yukihiro "Matz" Matsumoto 5d37160455 Use MRB_SYM() more extensively. 2021-02-26 15:05:55 +09:00
Yukihiro "Matz" Matsumoto 17ecf14511 Revert "Minimize the changes in #5277"
This reverts commit dc51d89ac2.
2021-01-26 10:57:07 +09:00