Ruby 4.1.0dev (2026-11-21 revision f2d62c677e2f3630665a556501e8ab3d5dccfa71)
proc.c (f2d62c677e2f3630665a556501e8ab3d5dccfa71)
1/**********************************************************************
2
3 proc.c - Proc, Binding, Env
4
5 $Author$
6 created at: Wed Jan 17 12:13:14 2007
7
8 Copyright (C) 2004-2007 Koichi Sasada
9
10**********************************************************************/
11
12#include "eval_intern.h"
13#include "internal.h"
14#include "internal/class.h"
15#include "internal/error.h"
16#include "internal/eval.h"
17#include "internal/gc.h"
18#include "internal/hash.h"
19#include "internal/object.h"
20#include "internal/proc.h"
21#include "internal/symbol.h"
22#include "internal/vm.h"
23#include "method.h"
24#include "iseq.h"
25#include "vm_core.h"
26#include "ractor_core.h"
27#include "yjit.h"
28
29const rb_cref_t *rb_vm_cref_in_context(VALUE self, VALUE cbase);
30
31struct METHOD {
32 const VALUE recv;
33 const VALUE klass;
34 /* needed for #super_method */
35 const VALUE iclass;
36 /* Different than me->owner only for ZSUPER methods.
37 This is error-prone but unavoidable unless ZSUPER methods are removed. */
38 const VALUE owner;
39 const rb_method_entry_t * const me;
40 /* for bound methods, `me' should be rb_callable_method_entry_t * */
41};
42
47static VALUE rb_cSourceRange;
48
49static rb_block_call_func bmcall;
50static int method_arity(VALUE);
51static int method_min_max_arity(VALUE, int *max);
52static VALUE proc_binding(VALUE self);
53
55 VALUE path;
56 VALUE absolute_path;
57 int start_line;
58 int start_column;
59 int end_line;
60 int end_column;
61};
62
63static size_t
64source_range_memsize(const void *ptr)
65{
66 return sizeof(struct source_range_data);
67}
68
69RUBY_REFERENCES(source_range_refs) = {
70 RUBY_REF_EDGE(struct source_range_data, path),
71 RUBY_REF_EDGE(struct source_range_data, absolute_path),
72 RUBY_REF_END
73};
74
75static const rb_data_type_t source_range_data_type = {
76 "source_range",
77 {
78 RUBY_REFS_LIST_PTR(source_range_refs),
80 source_range_memsize,
81 },
82 0, 0, RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_DECL_MARKING
83};
84
86rb_source_range_new(VALUE path, VALUE absolute_path, const rb_code_location_t *location)
87{
88 struct source_range_data *data;
90 rb_cSourceRange, struct source_range_data, &source_range_data_type, data);
91 RB_OBJ_WRITE(obj, &data->path, path);
92 RB_OBJ_WRITE(obj, &data->absolute_path, absolute_path);
93 data->start_line = location->beg_pos.lineno;
94 data->start_column = location->beg_pos.column;
95 data->end_line = location->end_pos.lineno;
96 data->end_column = location->end_pos.column;
97
98 return obj;
99}
100
101static VALUE
102source_range_new(const rb_iseq_t *iseq)
103{
104 if (!iseq) {
105 return Qnil;
106 }
107 rb_iseq_check(iseq);
108
109 VALUE path = rb_iseq_path(iseq);
110 VALUE absolute_path = rb_iseq_realpath(iseq);
111 if (NIL_P(path) && NIL_P(absolute_path)) {
112 return Qnil;
113 }
114
115 return rb_source_range_new(path, absolute_path, &ISEQ_BODY(iseq)->location.code_location);
116}
117
118static struct source_range_data *
119source_range_data_get(VALUE self)
120{
121 struct source_range_data *data;
122 TypedData_Get_Struct(self, struct source_range_data, &source_range_data_type, data);
123 return data;
124}
125
126/*
127 * call-seq:
128 * source_range.path -> String
129 *
130 * Returns the source path for the callable associated with this source range.
131 * This is the same path returned as the first element of #source_location.
132 */
133static VALUE
134source_range_path(VALUE self)
135{
136 return source_range_data_get(self)->path;
137}
138
139/*
140 * call-seq:
141 * source_range.absolute_path -> String or nil
142 *
143 * Returns the absolute source path for the callable associated with this source
144 * range, or +nil+ if the source has no absolute path, such as eval'd code.
145 */
146static VALUE
147source_range_absolute_path(VALUE self)
148{
149 return source_range_data_get(self)->absolute_path;
150}
151
152/*
153 * call-seq:
154 * source_range.start_line -> Integer
155 *
156 * Returns the 1-indexed line number where this source range starts.
157 */
158static VALUE
159source_range_start_line(VALUE self)
160{
161 return INT2NUM(source_range_data_get(self)->start_line);
162}
163
164/*
165 * call-seq:
166 * source_range.start_column -> Integer
167 *
168 * Returns the 0-indexed byte column where this source range starts.
169 *
170 * -> {}.source_range.start_column # => 0 # the '->'
171 * l = -> {}.source_range.start_column # => 4 # the '->'
172 * proc {}.source_range.start_column # => 5 # the '{'
173 * method(def m = 42).source_range.start_column # => 7 # the 'def'
174 */
175static VALUE
176source_range_start_column(VALUE self)
177{
178 return INT2NUM(source_range_data_get(self)->start_column);
179}
180
181/*
182 * call-seq:
183 * source_range.end_line -> Integer
184 *
185 * Returns the 1-indexed line number where this source range ends.
186 *
187 * Note that this does not include a potential heredoc that spans beyond the callable's end, for example:
188 *
189 * proc { <<~HEREDOC }.source_range.end_line # => 1
190 * heredoc
191 * contents
192 * HEREDOC
193 *
194 * To get the location of the final HEREDOC you can use +Prism.find(Proc|Method|UnboundMethod)+ and then compute the maximum end_line and end_column.
195 */
196static VALUE
197source_range_end_line(VALUE self)
198{
199 return INT2NUM(source_range_data_get(self)->end_line);
200}
201
202/*
203 * call-seq:
204 * source_range.end_column -> Integer
205 *
206 * Returns the 0-indexed byte column where this source range ends.
207 *
208 * Note that this does not include a potential heredoc that spans beyond the callable's end, for example:
209 *
210 * proc { <<~HEREDOC }.source_range.end_column # => 19
211 * heredoc
212 * contents
213 * HEREDOC
214 *
215 * To get the location of the final HEREDOC you can use +Prism.find(Proc|Method|UnboundMethod)+ and then compute the maximum end_line and end_column.
216 */
217static VALUE
218source_range_end_column(VALUE self)
219{
220 return INT2NUM(source_range_data_get(self)->end_column);
221}
222
223/*
224 * call-seq:
225 * source_range.inspect -> String
226 *
227 * Returns a human-readable string with the #absolute_path if available,
228 * otherwise the #path, and the start and end coordinates.
229 */
230static VALUE
231source_range_inspect(VALUE self)
232{
233 struct source_range_data *data = source_range_data_get(self);
234 VALUE str = rb_str_new_cstr("#<Ruby::SourceRange ");
235 VALUE path = NIL_P(data->absolute_path) ? data->path : data->absolute_path;
236
237 VM_ASSERT(!NIL_P(path));
238 rb_str_append(str, path);
239
240 rb_str_catf(str, ":(%d,%d)-(%d,%d)>",
241 data->start_line, data->start_column,
242 data->end_line, data->end_column);
243
244 return str;
245}
246
247/* Proc */
248
249#define IS_METHOD_PROC_IFUNC(ifunc) ((ifunc)->func == bmcall)
250
251static void
252block_mark_and_move(struct rb_block *block)
253{
254 switch (block->type) {
255 case block_type_iseq:
256 case block_type_ifunc:
257 {
258 struct rb_captured_block *captured = &block->as.captured;
259 rb_gc_mark_and_move(&captured->self);
260 rb_gc_mark_and_move(&captured->code.val);
261 if (captured->ep) {
262 rb_gc_mark_and_move((VALUE *)&captured->ep[VM_ENV_DATA_INDEX_ENV]);
263 }
264 }
265 break;
266 case block_type_symbol:
267 rb_gc_mark_and_move(&block->as.symbol);
268 break;
269 case block_type_proc:
270 rb_gc_mark_and_move(&block->as.proc);
271 break;
272 }
273}
274
275static ID id_refinements_recipe;
276
277static void
278proc_mark_and_move(void *ptr)
279{
280 rb_proc_t *proc = ptr;
281 block_mark_and_move((struct rb_block *)&proc->block);
282}
283
284enum refinement_recipe_index {
285 REFINEMENT_RECIPE_BASE_CREF, /* key: cref the modules are activated on */
286 REFINEMENT_RECIPE_CREF, /* value: cref with the refinements activated */
287 REFINEMENT_RECIPE_SRC_ISEQ, /* key: iseq of the block the Proc came from */
288 REFINEMENT_RECIPE_MODS /* key: modules, in the order given */
289};
290
291static bool
292refinement_recipe_eq(VALUE r1, VALUE r2)
293{
294 if (r1 == r2) return true;
295 rb_len_t len = RARRAY_LEN(r1);
296 if (RARRAY_LEN(r2) != len) return false;
297 if (RARRAY_AREF(r1, REFINEMENT_RECIPE_BASE_CREF) !=
298 RARRAY_AREF(r2, REFINEMENT_RECIPE_BASE_CREF)) return false;
299 if (RARRAY_AREF(r1, REFINEMENT_RECIPE_SRC_ISEQ) !=
300 RARRAY_AREF(r2, REFINEMENT_RECIPE_SRC_ISEQ)) return false;
301 for (rb_len_t i = REFINEMENT_RECIPE_MODS; i < len; i++) {
302 if (RARRAY_AREF(r1, i) != RARRAY_AREF(r2, i)) return false;
303 }
304 return true;
305}
306
307VALUE
308rb_proc_refinements_recipe(VALUE procval)
309{
310 rb_proc_t *proc;
311 GetProcPtr(procval, proc);
312 if (!proc->header.is_refined) return Qnil;
313 return rb_ivar_get(procval, id_refinements_recipe);
314}
315
316void
317rb_proc_set_refinements_recipe(VALUE procval, VALUE recipe)
318{
319 rb_proc_t *proc;
320 GetProcPtr(procval, proc);
321 rb_ivar_set(procval, id_refinements_recipe, recipe);
322 proc->header.is_refined = 1;
323}
324
325typedef struct {
326 rb_proc_t basic;
327 VALUE env[VM_ENV_DATA_SIZE + 1]; /* ..., envval */
329
330static inline bool
331cfunc_proc_inline_env_p(const rb_proc_t *proc)
332{
333 return proc->block.as.captured.ep == ((const cfunc_proc_t *)proc)->env + VM_ENV_DATA_SIZE - 1;
334}
335
336static size_t
337proc_memsize(const void *ptr)
338{
339 const rb_proc_t *proc = ptr;
340 switch (proc->block.type) {
341 case block_type_iseq:
342 case block_type_ifunc:
343 if (proc->block.as.captured.ep == ((const cfunc_proc_t *)ptr)->env+1)
344 return sizeof(cfunc_proc_t);
345 return sizeof(rb_proc_captured_t);
346 case block_type_symbol:
347 return sizeof(rb_proc_symbol_t);
348 case block_type_proc:
349 return sizeof(rb_proc_proc_t);
350 }
351 VM_UNREACHABLE(proc_memsize);
352 return 0;
353}
354
355const rb_data_type_t ruby_proc_data_type = {
356 "proc",
357 {
358 proc_mark_and_move,
360 proc_memsize,
361 proc_mark_and_move,
362 },
363 0, 0, RUBY_TYPED_THREAD_SAFE_FREE | RUBY_TYPED_WB_PROTECTED
364};
365
366#define proc_data_type ruby_proc_data_type
367
368VALUE
369rb_proc_alloc(VALUE klass, enum rb_block_type block_type)
370{
371 size_t size;
372 switch (block_type) {
373 case block_type_symbol:
374 size = sizeof(rb_proc_symbol_t);
375 break;
376 case block_type_proc:
377 size = sizeof(rb_proc_proc_t);
378 break;
379 case block_type_iseq:
380 case block_type_ifunc:
381 size = sizeof(rb_proc_captured_t);
382 break;
383 default:
384 VM_UNREACHABLE(rb_proc_alloc);
385 return Qundef;
386 }
387
388 return rb_data_typed_object_zalloc(klass, size, &proc_data_type);
389}
390
391VALUE
393{
394 return RBOOL(rb_typeddata_is_kind_of(proc, &proc_data_type));
395}
396
397/* :nodoc: */
398static VALUE
399proc_clone(VALUE self)
400{
401 VALUE procval = rb_proc_dup_0(self);
402 return rb_obj_clone_setup(self, procval, Qnil);
403}
404
405/* :nodoc: */
406static VALUE
407proc_dup(VALUE self)
408{
409 VALUE procval = rb_proc_dup_0(self);
410 return rb_obj_dup_setup(self, procval);
411}
412
413rb_cref_t *rb_vm_get_cref(const VALUE *ep);
414VALUE rb_proc_dup_with_iseq_and_recipe(VALUE self, const rb_iseq_t *iseq, VALUE recipe);
415
416/* Proc#refined memoizes the most recent recipe copied for a source iseq, with
417 * its copy. The memo lives in a hidden identity Hash:
418 *
419 * source iseq -> [recipe, copied_iseq]
420 *
421 * An entry is written when the copy is made, that is on the first call of a
422 * Proc built from the recipe, not when Proc#refined is called: a chain of
423 * calls then memoizes the chain as a whole, since the recipe of the last link
424 * carries all of the modules. It also means one entry per source iseq is
425 * enough for prc.refined(a).refined(b), which shares its entry with
426 * prc.refined(a, b).
427 *
428 * An entry is retained for the VM's lifetime, so a block that is itself a copy
429 * is never used as a key; such a Proc is copied by Proc#refined instead. */
430
431enum refinement_memo_index {
432 REFINEMENT_MEMO_RECIPE,
433 REFINEMENT_MEMO_COPIED_ISEQ
434};
435
436static VALUE refinement_memo_map; /* set once under the VM lock */
437
438static VALUE
439refinement_memo_get(const rb_iseq_t *src_iseq)
440{
441 VALUE memo = Qnil;
442 RB_VM_LOCKING() {
443 if (refinement_memo_map) {
444 memo = rb_hash_lookup(refinement_memo_map, (VALUE)src_iseq);
445 }
446 }
447 return memo;
448}
449
450static void
451refinement_memo_set(const rb_iseq_t *src_iseq, VALUE recipe, const rb_iseq_t *copied_iseq)
452{
453 VM_ASSERT(ISEQ_BODY(src_iseq)->type == ISEQ_TYPE_BLOCK);
454
455 VALUE memo = rb_ary_hidden_new(2);
456 rb_ary_push(memo, recipe);
457 rb_ary_push(memo, (VALUE)copied_iseq);
458 OBJ_FREEZE(memo);
459 /* Every element is shareable, so mark the memo array shareable too for
460 * reuse from any Ractor. */
462
463 /* create the map outside the lock; losing the race just discards it */
464 VALUE new_map = 0;
465 if (!refinement_memo_map) {
466 new_map = rb_obj_hide(rb_ident_hash_new());
467 }
468
469 RB_VM_LOCKING() {
470 if (!refinement_memo_map) {
471 rb_vm_register_global_object(new_map);
472 refinement_memo_map = new_map;
473 }
474 rb_hash_aset(refinement_memo_map, (VALUE)src_iseq, memo);
475 }
476}
477
478static rb_len_t
479refinement_recipe_modc(VALUE recipe)
480{
481 return NIL_P(recipe) ? 0 : RARRAY_LEN(recipe) - REFINEMENT_RECIPE_MODS;
482}
483
484static bool
485refinement_recipe_match(VALUE recipe, const rb_cref_t *base_cref, VALUE src_recipe,
486 long argc, const VALUE *mods)
487{
488 rb_len_t inherited = refinement_recipe_modc(src_recipe);
489 if (RARRAY_AREF(recipe, REFINEMENT_RECIPE_BASE_CREF) != (VALUE)base_cref) return false;
490 if (refinement_recipe_modc(recipe) != inherited + argc) return false;
491 for (rb_len_t i = 0; i < inherited; i++) {
492 if (RARRAY_AREF(recipe, REFINEMENT_RECIPE_MODS + i) !=
493 RARRAY_AREF(src_recipe, REFINEMENT_RECIPE_MODS + i)) return false;
494 }
495 for (long i = 0; i < argc; i++) {
496 if (RARRAY_AREF(recipe, REFINEMENT_RECIPE_MODS + inherited + i) != mods[i]) return false;
497 }
498 return true;
499}
500
501static VALUE
502refinement_recipe_new(const rb_cref_t *base_cref, const rb_cref_t *cref,
503 const rb_iseq_t *src_iseq, VALUE src_recipe,
504 long argc, const VALUE *mods)
505{
506 rb_len_t inherited = refinement_recipe_modc(src_recipe);
507 VALUE recipe = rb_ary_hidden_new(REFINEMENT_RECIPE_MODS + inherited + argc);
508 rb_ary_push(recipe, (VALUE)base_cref);
509 rb_ary_push(recipe, (VALUE)cref);
510 rb_ary_push(recipe, (VALUE)src_iseq);
511 for (rb_len_t i = 0; i < inherited; i++) {
512 rb_ary_push(recipe, RARRAY_AREF(src_recipe, REFINEMENT_RECIPE_MODS + i));
513 }
514 for (long i = 0; i < argc; i++) {
515 rb_ary_push(recipe, mods[i]);
516 }
517 OBJ_FREEZE(recipe);
518 RB_OBJ_SET_SHAREABLE(recipe);
519 return recipe;
520}
521
522static VALUE
523refinement_memo_lookup(const rb_iseq_t *src_iseq, const rb_cref_t *base_cref, VALUE src_recipe,
524 long argc, const VALUE *mods)
525{
526 VM_ASSERT(ISEQ_BODY(src_iseq)->type == ISEQ_TYPE_BLOCK);
527 VALUE memo = refinement_memo_get(src_iseq);
528 if (NIL_P(memo)) return Qnil;
529 VALUE recipe = RARRAY_AREF(memo, REFINEMENT_MEMO_RECIPE);
530 if (!refinement_recipe_match(recipe, base_cref, src_recipe, argc, mods)) return Qnil;
531 return recipe;
532}
533
534static const rb_iseq_t *
535refinement_iseq_copy(VALUE recipe)
536{
537 const rb_iseq_t *src_iseq =
538 (const rb_iseq_t *)RARRAY_AREF(recipe, REFINEMENT_RECIPE_SRC_ISEQ);
539 VALUE memo = refinement_memo_get(src_iseq);
540 if (!NIL_P(memo)) {
541 if (refinement_recipe_eq(RARRAY_AREF(memo, REFINEMENT_MEMO_RECIPE), recipe)) {
542 const rb_iseq_t *copied_iseq =
543 (const rb_iseq_t *)RARRAY_AREF(memo, REFINEMENT_MEMO_COPIED_ISEQ);
544 if (ISEQ_BODY(copied_iseq)->param.flags.ruby2_keywords ==
545 ISEQ_BODY(src_iseq)->param.flags.ruby2_keywords) {
546 return copied_iseq;
547 }
550 "Proc#refined re-copies the block because the ruby2_keywords flag changed after the copy was memoized"
551 );
552 }
553 else {
556 "Proc#refined called with different modules for the same block disables memoization"
557 );
558 }
559 }
560
561 /* copy outside the lock; losing a race just discards the extra copy */
562 const rb_iseq_t *copied_iseq = rb_iseq_dup_with_independent_caches(src_iseq);
563 refinement_memo_set(src_iseq, recipe, copied_iseq);
564 return copied_iseq;
565}
566
567NOINLINE(static void refinement_iseq_install(VALUE procval, rb_proc_t *proc));
568static void
569refinement_iseq_install(VALUE procval, rb_proc_t *proc)
570{
571 VALUE recipe = rb_ivar_get(procval, id_refinements_recipe);
572 const rb_iseq_t *copied_iseq = refinement_iseq_copy(recipe);
573
574 RB_VM_LOCKING() {
575 if (!FL_TEST_RAW((VALUE)proc->block.as.captured.code.iseq, ISEQ_REFINED_COPY)) {
576 RB_OBJ_WRITE(procval, &proc->block.as.captured.code.val, (VALUE)copied_iseq);
577 }
578 }
579}
580
581static inline void
582refinement_iseq_ensure(VALUE procval, rb_proc_t *proc)
583{
584 if (UNLIKELY(!FL_TEST_RAW((VALUE)proc->block.as.captured.code.iseq, ISEQ_REFINED_COPY))) {
585 refinement_iseq_install(procval, proc);
586 }
587}
588
589const rb_cref_t *
590rb_proc_refinements_cref_for_call(VALUE procval)
591{
592 rb_proc_t *proc;
593 GetProcPtr(procval, proc);
594 if (!proc->header.is_refined) return NULL;
595
596 refinement_iseq_ensure(procval, proc);
597 VALUE recipe = rb_ivar_get(procval, id_refinements_recipe);
598 return (const rb_cref_t *)RARRAY_AREF(recipe, REFINEMENT_RECIPE_CREF);
599}
600
601/*
602 * call-seq:
603 * prc.refined(*modules) -> a_proc
604 *
605 * Returns a new Proc that behaves like the receiver but with the refinements
606 * activated by the given modules in effect inside its body. The receiver is
607 * left unchanged.
608 *
609 * module StringRefinement
610 * refine String do
611 * def shout = upcase + "!"
612 * end
613 * end
614 *
615 * original = ->(s) { s.shout }
616 * refined_proc = original.refined(StringRefinement)
617 * refined_proc.call("hi") #=> "HI!"
618 * original.call("hi") #=> NoMethodError
619 *
620 * If no modules are given, returns the receiver.
621 * Otherwise, only Procs created from a Ruby block are supported; calling this
622 * on a Proc backed by a C function, a Symbol, or a method raises ArgumentError.
623 *
624 * When calls of this method are chained, all the given modules are activated
625 * in the order they are given, so refinements activated by a later call take
626 * precedence.
627 *
628 * The refinement set of the returned Proc is fixed when it is created:
629 * calling +using+ inside its body raises RuntimeError.
630 *
631 * The refinements are in effect throughout the body, including nested blocks
632 * and methods defined with +def+ inside it. As with a +def+ inside a +using+
633 * scope, such a method keeps the refinements even when it is called later:
634 *
635 * refined_proc = ->(s) {
636 * -> { s.shout }.call # nested block: "HI!"
637 * }.refined(StringRefinement)
638 *
639 * refined_proc = -> {
640 * obj = Object.new
641 * def obj.shout_hi = "hi".shout # the method sees the refinement
642 * obj.shout_hi #=> "HI!"
643 * }.refined(StringRefinement)
644 *
645 * Running the returned Proc requires a copy of the instruction sequence of the
646 * block and of all of its nested blocks, so that the copy can resolve methods
647 * through the refinements without affecting the original Proc. The copy is
648 * made when the Proc is first called, and is cached and reused for the same
649 * block and the same modules, whether they were given in one call or in a
650 * chain of calls; a Proc that is never called is never copied. Applying
651 * refinements therefore increases memory use roughly in proportion to the size
652 * of the block, once the Proc runs.
653 */
654static VALUE
655proc_refined(int argc, VALUE *argv, VALUE self)
656{
657 rb_proc_t *src;
658 GetProcPtr(self, src);
659
660 if (argc == 0) {
661 return self;
662 }
663
664 if (vm_block_type(&src->block) != block_type_iseq || src->header.is_from_method) {
665 rb_raise(rb_eArgError, "can't apply refinements to a Proc without a Ruby block");
666 }
667
668 for (int i = 0; i < argc; i++) {
669 Check_Type(argv[i], T_MODULE);
670 }
671
672 const rb_iseq_t *src_iseq = src->block.as.captured.code.iseq;
673 VALUE src_recipe = rb_proc_refinements_recipe(self);
674 const rb_cref_t *src_cref, *base_cref;
675 if (NIL_P(src_recipe)) {
676 src_cref = base_cref = rb_vm_get_cref(src->block.as.captured.ep);
677 }
678 else {
679 /* keep asking for the modules of the whole chain, so that a chained
680 * call ends up with the recipe of a single call of all of them */
681 src_cref = (const rb_cref_t *)RARRAY_AREF(src_recipe, REFINEMENT_RECIPE_CREF);
682 base_cref = (const rb_cref_t *)RARRAY_AREF(src_recipe, REFINEMENT_RECIPE_BASE_CREF);
683 }
684
685 /* A block that is itself a copy is short-lived, so it is not memoized, and
686 * it has to be copied here: ISEQ_REFINED_COPY has to keep meaning "the
687 * copy of this Proc". */
688 bool copied_src = FL_TEST_RAW((VALUE)src_iseq, ISEQ_REFINED_COPY);
689 if (copied_src) {
692 "Proc#refined on a Proc whose block was already copied by Proc#refined is not memoized"
693 );
694 }
695
696 VALUE recipe = copied_src ? Qnil :
697 refinement_memo_lookup(src_iseq, base_cref, src_recipe, argc, argv);
698 if (NIL_P(recipe)) {
699 rb_cref_t *cref = rb_vm_cref_dup(src_cref);
700 /* rb_using_module_recursive modifies shared subclass lists */
701 RB_VM_LOCKING() {
702 for (int i = 0; i < argc; i++) {
703 rb_using_module_recursive(cref, argv[i]);
704 }
705 }
706 /* Freeze the refinements table and mark it shareable so the memoized
707 * cref can be reused from any Ractor. */
708 VALUE refs = CREF_REFINEMENTS(cref);
709 if (!NIL_P(refs)) {
710 OBJ_FREEZE(refs);
712 }
713 CREF_OMOD_SHARED_SET(cref);
714 CREF_REFINED_PROC_SET(cref);
715 recipe = refinement_recipe_new(base_cref, cref, src_iseq, src_recipe, argc, argv);
716 }
717
718 const rb_iseq_t *new_iseq = copied_src ?
719 rb_iseq_dup_with_independent_caches(src_iseq) : src_iseq;
720
721 return rb_proc_dup_with_iseq_and_recipe(self, new_iseq, recipe);
722}
723
724/*
725 * call-seq:
726 * prc.lambda? -> true or false
727 *
728 * Returns +true+ if a Proc object is lambda.
729 * +false+ if non-lambda.
730 *
731 * The lambda-ness affects argument handling and the behavior of +return+ and +break+.
732 *
733 * A Proc object generated by +proc+ ignores extra arguments.
734 *
735 * proc {|a,b| [a,b] }.call(1,2,3) #=> [1,2]
736 *
737 * It provides +nil+ for missing arguments.
738 *
739 * proc {|a,b| [a,b] }.call(1) #=> [1,nil]
740 *
741 * It expands a single array argument.
742 *
743 * proc {|a,b| [a,b] }.call([1,2]) #=> [1,2]
744 *
745 * A Proc object generated by +lambda+ doesn't have such tricks.
746 *
747 * lambda {|a,b| [a,b] }.call(1,2,3) #=> ArgumentError
748 * lambda {|a,b| [a,b] }.call(1) #=> ArgumentError
749 * lambda {|a,b| [a,b] }.call([1,2]) #=> ArgumentError
750 *
751 * Proc#lambda? is a predicate for the tricks.
752 * It returns +true+ if no tricks apply.
753 *
754 * lambda {}.lambda? #=> true
755 * proc {}.lambda? #=> false
756 *
757 * Proc.new is the same as +proc+.
758 *
759 * Proc.new {}.lambda? #=> false
760 *
761 * +lambda+, +proc+ and Proc.new preserve the tricks of
762 * a Proc object given by <code>&</code> argument.
763 *
764 * lambda(&lambda {}).lambda? #=> true
765 * proc(&lambda {}).lambda? #=> true
766 * Proc.new(&lambda {}).lambda? #=> true
767 *
768 * lambda(&proc {}).lambda? #=> false
769 * proc(&proc {}).lambda? #=> false
770 * Proc.new(&proc {}).lambda? #=> false
771 *
772 * A Proc object generated by <code>&</code> argument has the tricks
773 *
774 * def n(&b) b.lambda? end
775 * n {} #=> false
776 *
777 * The <code>&</code> argument preserves the tricks if a Proc object
778 * is given by <code>&</code> argument.
779 *
780 * n(&lambda {}) #=> true
781 * n(&proc {}) #=> false
782 * n(&Proc.new {}) #=> false
783 *
784 * A Proc object converted from a method has no tricks.
785 *
786 * def m() end
787 * method(:m).to_proc.lambda? #=> true
788 *
789 * n(&method(:m)) #=> true
790 * n(&method(:m).to_proc) #=> true
791 *
792 * +define_method+ is treated the same as method definition.
793 * The defined method has no tricks.
794 *
795 * class C
796 * define_method(:d) {}
797 * end
798 * C.new.d(1,2) #=> ArgumentError
799 * C.new.method(:d).to_proc.lambda? #=> true
800 *
801 * +define_method+ always defines a method without the tricks,
802 * even if a non-lambda Proc object is given.
803 * This is the only exception for which the tricks are not preserved.
804 *
805 * class C
806 * define_method(:e, &proc {})
807 * end
808 * C.new.e(1,2) #=> ArgumentError
809 * C.new.method(:e).to_proc.lambda? #=> true
810 *
811 * This exception ensures that methods never have tricks
812 * and makes it easy to have wrappers to define methods that behave as usual.
813 *
814 * class C
815 * def self.def2(name, &body)
816 * define_method(name, &body)
817 * end
818 *
819 * def2(:f) {}
820 * end
821 * C.new.f(1,2) #=> ArgumentError
822 *
823 * The wrapper <i>def2</i> defines a method which has no tricks.
824 *
825 */
826
827VALUE
829{
830 rb_proc_t *proc;
831 GetProcPtr(procval, proc);
832
833 return RBOOL(proc->header.is_lambda);
834}
835
836/* Binding */
837
838static void
839binding_free(void *ptr)
840{
841 RUBY_FREE_ENTER("binding");
842 SIZED_FREE((rb_binding_t *)ptr);
843 RUBY_FREE_LEAVE("binding");
844}
845
846static void
847binding_mark_and_move(void *ptr)
848{
849 rb_binding_t *bind = ptr;
850
851 block_mark_and_move((struct rb_block *)&bind->block);
852 rb_gc_mark_and_move((VALUE *)&bind->pathobj);
853}
854
855static size_t
856binding_memsize(const void *ptr)
857{
858 return sizeof(rb_binding_t);
859}
860
861const rb_data_type_t ruby_binding_data_type = {
862 "binding",
863 {
864 binding_mark_and_move,
865 binding_free,
866 binding_memsize,
867 binding_mark_and_move,
868 },
869 0, 0, RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_THREAD_SAFE_FREE
870};
871
872VALUE
873rb_binding_alloc(VALUE klass)
874{
875 VALUE obj;
876 rb_binding_t *bind;
877 obj = TypedData_Make_Struct(klass, rb_binding_t, &ruby_binding_data_type, bind);
878#if YJIT_STATS
879 rb_yjit_collect_binding_alloc();
880#endif
881 return obj;
882}
883
884static VALUE
885binding_copy(VALUE self)
886{
887 VALUE bindval = rb_binding_alloc(rb_cBinding);
888 rb_binding_t *src, *dst;
889 GetBindingPtr(self, src);
890 GetBindingPtr(bindval, dst);
891 rb_vm_block_copy(bindval, &dst->block, &src->block);
892 RB_OBJ_WRITE(bindval, &dst->pathobj, src->pathobj);
893 dst->first_lineno = src->first_lineno;
894 return bindval;
895}
896
897/* :nodoc: */
898static VALUE
899binding_dup(VALUE self)
900{
901 return rb_obj_dup_setup(self, binding_copy(self));
902}
903
904/* :nodoc: */
905static VALUE
906binding_clone(VALUE self)
907{
908 return rb_obj_clone_setup(self, binding_copy(self), Qnil);
909}
910
911VALUE
913{
914 rb_execution_context_t *ec = GET_EC();
915 return rb_vm_make_binding(ec, ec->cfp);
916}
917
918/*
919 * call-seq:
920 * binding -> a_binding
921 *
922 * Returns a Binding object, describing the variable and
923 * method bindings at the point of call. This object can be used when
924 * calling Binding#eval to execute the evaluated command in this
925 * environment, or extracting its local variables.
926 *
927 * class User
928 * def initialize(name, position)
929 * @name = name
930 * @position = position
931 * end
932 *
933 * def get_binding
934 * binding
935 * end
936 * end
937 *
938 * user = User.new('Joan', 'manager')
939 * template = '{name: @name, position: @position}'
940 *
941 * # evaluate template in context of the object
942 * eval(template, user.get_binding)
943 * #=> {name: "Joan", position: "manager"}
944 *
945 * Binding#local_variable_get can be used to access the variables
946 * whose names are reserved Ruby keywords:
947 *
948 * # This is valid parameter declaration, but `if` parameter can't
949 * # be accessed by name, because it is a reserved word.
950 * def validate(field, validation, if: nil)
951 * condition = binding.local_variable_get('if')
952 * return unless condition
953 *
954 * # ...Some implementation ...
955 * end
956 *
957 * validate(:name, :empty?, if: false) # skips validation
958 * validate(:name, :empty?, if: true) # performs validation
959 *
960 */
961
962static VALUE
963rb_f_binding(VALUE self)
964{
965 return rb_binding_new();
966}
967
968/*
969 * call-seq:
970 * binding.eval(string, filename = default_filename, lineno = 1) -> obj
971 *
972 * Evaluates the Ruby expression(s) in +string+ in the context of
973 * +self+. Returns the result of the last expression:
974 *
975 * def get_binding(param) = binding
976 * b = get_binding("hello")
977 * b.eval("param") #=> "hello"
978 *
979 * If the optional +filename+ is given, it will be used as the
980 * filename of the evaluation (for <tt>__FILE__</tt> and errors).
981 * Otherwise, it will default to <tt>(eval at __FILE__:__LINE__)</tt>
982 * where <tt>__FILE__</tt> and <tt>__LINE__</tt> are the filename and
983 * line number of the caller, respectively:
984 *
985 * b.eval("puts __FILE__") # => "(eval at test.rb:4)"
986 * b.eval("puts __FILE__", "foobar.rb") # => "foobar.rb"
987 *
988 * If the optional +lineno+ is given, it will be used as the
989 * line number of the evaluation (for <tt>__LINE__</tt> and errors).
990 * Otherwise, it will default to 1:
991 *
992 * b.eval("puts __LINE__") # => 1
993 * b.eval("puts __LINE__", "foobar.rb", 10) # => 10
994 */
995
996static VALUE
997bind_eval(int argc, VALUE *argv, VALUE bindval)
998{
999 VALUE args[4];
1000
1001 rb_scan_args(argc, argv, "12", &args[0], &args[2], &args[3]);
1002 args[1] = bindval;
1003 return rb_f_eval(argc+1, args, Qnil /* self will be searched in eval */);
1004}
1005
1006static const VALUE *
1007get_local_variable_ptr(const rb_env_t **envp, ID lid, bool search_outer)
1008{
1009 const rb_env_t *env = *envp;
1010 do {
1011 if (!VM_ENV_FLAGS(env->ep, VM_FRAME_FLAG_CFRAME)) {
1012 if (VM_ENV_FLAGS(env->ep, VM_ENV_FLAG_ISOLATED)) {
1013 return NULL;
1014 }
1015
1016 const rb_iseq_t *iseq = env->iseq;
1017
1018 VM_ASSERT(rb_obj_is_iseq((VALUE)iseq));
1019
1020 const unsigned int local_table_size = ISEQ_BODY(iseq)->local_table_size;
1021 for (unsigned int i=0; i<local_table_size; i++) {
1022 if (ISEQ_BODY(iseq)->local_table[i] == lid) {
1023 if (ISEQ_BODY(iseq)->local_iseq == iseq &&
1024 ISEQ_BODY(iseq)->param.flags.has_block &&
1025 (unsigned int)ISEQ_BODY(iseq)->param.block_start == i) {
1026 const VALUE *ep = env->ep;
1027 if (!VM_ENV_FLAGS(ep, VM_FRAME_FLAG_MODIFIED_BLOCK_PARAM)) {
1028 RB_OBJ_WRITE(env, &env->env[i], rb_vm_bh_to_procval(GET_EC(), VM_ENV_BLOCK_HANDLER(ep)));
1029 VM_ENV_FLAGS_SET(ep, VM_FRAME_FLAG_MODIFIED_BLOCK_PARAM);
1030 }
1031 }
1032
1033 *envp = env;
1034 unsigned int last_lvar = env->env_size+VM_ENV_INDEX_LAST_LVAR
1035 - 1 /* errinfo */;
1036 return &env->env[last_lvar - (local_table_size - i)];
1037 }
1038 }
1039 }
1040 else {
1041 *envp = NULL;
1042 return NULL;
1043 }
1044 } while (search_outer && (env = rb_vm_env_prev_env(env)) != NULL);
1045
1046 *envp = NULL;
1047 return NULL;
1048}
1049
1050/*
1051 * check local variable name.
1052 * returns ID if it's an already interned symbol, or 0 with setting
1053 * local name in String to *namep.
1054 */
1055static ID
1056check_local_id(VALUE bindval, volatile VALUE *pname)
1057{
1058 ID lid = rb_check_id(pname);
1059 VALUE name = *pname;
1060
1061 if (lid) {
1062 if (!rb_is_local_id(lid)) {
1063 rb_name_err_raise("wrong local variable name '%1$s' for %2$s",
1064 bindval, ID2SYM(lid));
1065 }
1066 }
1067 else {
1068 if (!rb_is_local_name(name)) {
1069 rb_name_err_raise("wrong local variable name '%1$s' for %2$s",
1070 bindval, name);
1071 }
1072 return 0;
1073 }
1074 return lid;
1075}
1076
1077/*
1078 * call-seq:
1079 * binding.local_variables -> Array
1080 *
1081 * Returns the names of the binding's local variables as symbols.
1082 *
1083 * def foo
1084 * a = 1
1085 * 2.times do |n|
1086 * binding.local_variables #=> [:a, :n]
1087 * end
1088 * end
1089 *
1090 * This method is the short version of the following code:
1091 *
1092 * binding.eval("local_variables")
1093 *
1094 */
1095static VALUE
1096bind_local_variables(VALUE bindval)
1097{
1098 const rb_binding_t *bind;
1099 const rb_env_t *env;
1100
1101 GetBindingPtr(bindval, bind);
1102 env = VM_ENV_ENVVAL_PTR(vm_block_ep(&bind->block));
1103 return rb_vm_env_local_variables(env);
1104}
1105
1106int
1107rb_numparam_id_p(ID id)
1108{
1109 return (tNUMPARAM_1 << ID_SCOPE_SHIFT) <= id && id < ((tNUMPARAM_1 + 9) << ID_SCOPE_SHIFT);
1110}
1111
1112int
1113rb_implicit_param_p(ID id)
1114{
1115 return id == idItImplicit || rb_numparam_id_p(id);
1116}
1117
1118/*
1119 * call-seq:
1120 * binding.local_variable_get(symbol) -> obj
1121 *
1122 * Returns the value of the local variable +symbol+.
1123 *
1124 * def foo
1125 * a = 1
1126 * binding.local_variable_get(:a) #=> 1
1127 * binding.local_variable_get(:b) #=> NameError
1128 * end
1129 *
1130 * This method is the short version of the following code:
1131 *
1132 * binding.eval("#{symbol}")
1133 *
1134 */
1135static VALUE
1136bind_local_variable_get(VALUE bindval, VALUE sym)
1137{
1138 ID lid = check_local_id(bindval, &sym);
1139 const rb_binding_t *bind;
1140 const VALUE *ptr;
1141 const rb_env_t *env;
1142
1143 if (!lid) goto undefined;
1144 if (rb_numparam_id_p(lid)) {
1145 rb_name_err_raise("numbered parameter '%1$s' is not a local variable",
1146 bindval, ID2SYM(lid));
1147 }
1148
1149 GetBindingPtr(bindval, bind);
1150
1151 env = VM_ENV_ENVVAL_PTR(vm_block_ep(&bind->block));
1152 if ((ptr = get_local_variable_ptr(&env, lid, TRUE)) != NULL) {
1153 return *ptr;
1154 }
1155
1156 sym = ID2SYM(lid);
1157 undefined:
1158 rb_name_err_raise("local variable '%1$s' is not defined for %2$s",
1159 bindval, sym);
1161}
1162
1163/*
1164 * call-seq:
1165 * binding.local_variable_set(symbol, obj) -> obj
1166 *
1167 * Set local variable named +symbol+ as +obj+.
1168 *
1169 * def foo
1170 * a = 1
1171 * bind = binding
1172 * bind.local_variable_set(:a, 2) # set existing local variable `a'
1173 * bind.local_variable_set(:b, 3) # create new local variable `b'
1174 * # `b' exists only in binding
1175 *
1176 * p bind.local_variable_get(:a) #=> 2
1177 * p bind.local_variable_get(:b) #=> 3
1178 * p a #=> 2
1179 * p b #=> NameError
1180 * end
1181 *
1182 * This method behaves similarly to the following code:
1183 *
1184 * binding.eval("#{symbol} = #{obj}")
1185 *
1186 * if +obj+ can be dumped in Ruby code.
1187 */
1188static VALUE
1189bind_local_variable_set(VALUE bindval, VALUE sym, VALUE val)
1190{
1191 ID lid = check_local_id(bindval, &sym);
1192 rb_binding_t *bind;
1193 const VALUE *ptr;
1194 const rb_env_t *env;
1195
1196 if (!lid) lid = rb_intern_str(sym);
1197 if (rb_numparam_id_p(lid)) {
1198 rb_name_err_raise("numbered parameter '%1$s' is not a local variable",
1199 bindval, ID2SYM(lid));
1200 }
1201
1202 GetBindingPtr(bindval, bind);
1203 env = VM_ENV_ENVVAL_PTR(vm_block_ep(&bind->block));
1204 if ((ptr = get_local_variable_ptr(&env, lid, TRUE)) == NULL) {
1205 /* not found. create new env */
1206 ptr = rb_binding_add_dynavars(bindval, bind, 1, &lid);
1207 env = VM_ENV_ENVVAL_PTR(vm_block_ep(&bind->block));
1208 }
1209
1210#if YJIT_STATS
1211 rb_yjit_collect_binding_set();
1212#endif
1213
1214 RB_OBJ_WRITE(env, ptr, val);
1215
1216 return val;
1217}
1218
1219/*
1220 * call-seq:
1221 * binding.local_variable_defined?(symbol) -> obj
1222 *
1223 * Returns +true+ if a local variable +symbol+ exists.
1224 *
1225 * def foo
1226 * a = 1
1227 * binding.local_variable_defined?(:a) #=> true
1228 * binding.local_variable_defined?(:b) #=> false
1229 * end
1230 *
1231 * This method is the short version of the following code:
1232 *
1233 * binding.eval("defined?(#{symbol}) == 'local-variable'")
1234 *
1235 */
1236static VALUE
1237bind_local_variable_defined_p(VALUE bindval, VALUE sym)
1238{
1239 ID lid = check_local_id(bindval, &sym);
1240 const rb_binding_t *bind;
1241 const rb_env_t *env;
1242
1243 if (!lid) return Qfalse;
1244 if (rb_numparam_id_p(lid)) {
1245 rb_name_err_raise("numbered parameter '%1$s' is not a local variable",
1246 bindval, ID2SYM(lid));
1247 }
1248
1249 GetBindingPtr(bindval, bind);
1250 env = VM_ENV_ENVVAL_PTR(vm_block_ep(&bind->block));
1251 return RBOOL(get_local_variable_ptr(&env, lid, TRUE));
1252}
1253
1254/*
1255 * call-seq:
1256 * binding.implicit_parameters -> Array
1257 *
1258 * Returns the names of numbered parameters and "it" parameter
1259 * that are defined in the binding.
1260 *
1261 * def foo
1262 * [42].each do
1263 * it
1264 * binding.implicit_parameters #=> [:it]
1265 * end
1266 *
1267 * { k: 42 }.each do
1268 * _2
1269 * binding.implicit_parameters #=> [:_1, :_2]
1270 * end
1271 * end
1272 *
1273 */
1274static VALUE
1275bind_implicit_parameters(VALUE bindval)
1276{
1277 const rb_binding_t *bind;
1278 const rb_env_t *env;
1279
1280 GetBindingPtr(bindval, bind);
1281 env = VM_ENV_ENVVAL_PTR(vm_block_ep(&bind->block));
1282
1283 if (get_local_variable_ptr(&env, idItImplicit, FALSE)) {
1284 return rb_ary_new_from_args(1, ID2SYM(idIt));
1285 }
1286
1287 env = VM_ENV_ENVVAL_PTR(vm_block_ep(&bind->block));
1288 return rb_vm_env_numbered_parameters(env);
1289}
1290
1291/*
1292 * call-seq:
1293 * binding.implicit_parameter_get(symbol) -> obj
1294 *
1295 * Returns the value of the numbered parameter or "it" parameter.
1296 *
1297 * def foo
1298 * [42].each do
1299 * it
1300 * binding.implicit_parameter_get(:it) #=> 42
1301 * end
1302 *
1303 * { k: 42 }.each do
1304 * _2
1305 * binding.implicit_parameter_get(:_1) #=> :k
1306 * binding.implicit_parameter_get(:_2) #=> 42
1307 * end
1308 * end
1309 *
1310 */
1311static VALUE
1312bind_implicit_parameter_get(VALUE bindval, VALUE sym)
1313{
1314 ID lid = check_local_id(bindval, &sym);
1315 const rb_binding_t *bind;
1316 const VALUE *ptr;
1317 const rb_env_t *env;
1318
1319 if (lid == idIt) lid = idItImplicit;
1320
1321 if (!lid || !rb_implicit_param_p(lid)) {
1322 rb_name_err_raise("'%1$s' is not an implicit parameter",
1323 bindval, sym);
1324 }
1325
1326 GetBindingPtr(bindval, bind);
1327
1328 env = VM_ENV_ENVVAL_PTR(vm_block_ep(&bind->block));
1329 if ((ptr = get_local_variable_ptr(&env, lid, FALSE)) != NULL) {
1330 return *ptr;
1331 }
1332
1333 if (lid == idItImplicit) lid = idIt;
1334 rb_name_err_raise("implicit parameter '%1$s' is not defined for %2$s", bindval, ID2SYM(lid));
1336}
1337
1338/*
1339 * call-seq:
1340 * binding.implicit_parameter_defined?(symbol) -> obj
1341 *
1342 * Returns +true+ if the numbered parameter or "it" parameter exists.
1343 *
1344 * def foo
1345 * [42].each do
1346 * it
1347 * binding.implicit_parameter_defined?(:it) #=> true
1348 * binding.implicit_parameter_defined?(:_1) #=> false
1349 * end
1350 *
1351 * { k: 42 }.each do
1352 * _2
1353 * binding.implicit_parameter_defined?(:_1) #=> true
1354 * binding.implicit_parameter_defined?(:_2) #=> true
1355 * binding.implicit_parameter_defined?(:_3) #=> false
1356 * binding.implicit_parameter_defined?(:it) #=> false
1357 * end
1358 * end
1359 *
1360 */
1361static VALUE
1362bind_implicit_parameter_defined_p(VALUE bindval, VALUE sym)
1363{
1364 ID lid = check_local_id(bindval, &sym);
1365 const rb_binding_t *bind;
1366 const rb_env_t *env;
1367
1368 if (lid == idIt) lid = idItImplicit;
1369
1370 if (!lid || !rb_implicit_param_p(lid)) {
1371 rb_name_err_raise("'%1$s' is not an implicit parameter",
1372 bindval, sym);
1373 }
1374
1375 GetBindingPtr(bindval, bind);
1376 env = VM_ENV_ENVVAL_PTR(vm_block_ep(&bind->block));
1377 return RBOOL(get_local_variable_ptr(&env, lid, FALSE));
1378}
1379
1380/*
1381 * call-seq:
1382 * binding.receiver -> object
1383 *
1384 * Returns the bound receiver of the binding object.
1385 */
1386static VALUE
1387bind_receiver(VALUE bindval)
1388{
1389 const rb_binding_t *bind;
1390 GetBindingPtr(bindval, bind);
1391 return vm_block_self(&bind->block);
1392}
1393
1394/*
1395 * call-seq:
1396 * binding.source_location -> [String, Integer]
1397 *
1398 * Returns the Ruby source filename and line number of the binding object.
1399 */
1400static VALUE
1401bind_location(VALUE bindval)
1402{
1403 VALUE loc[2];
1404 const rb_binding_t *bind;
1405 GetBindingPtr(bindval, bind);
1406 loc[0] = pathobj_path(bind->pathobj);
1407 loc[1] = INT2FIX(bind->first_lineno);
1408
1409 return rb_ary_new4(2, loc);
1410}
1411
1412static VALUE
1413cfunc_proc_new(VALUE klass, VALUE ifunc)
1414{
1415 rb_proc_t *proc;
1416 cfunc_proc_t *sproc;
1417 VALUE procval = TypedData_Make_Struct(klass, cfunc_proc_t, &proc_data_type, sproc);
1418 VALUE *ep;
1419
1420 proc = &sproc->basic;
1421 vm_block_type_set(&proc->block, block_type_ifunc);
1422
1423 *(VALUE **)&proc->block.as.captured.ep = ep = sproc->env + VM_ENV_DATA_SIZE-1;
1424 ep[VM_ENV_DATA_INDEX_FLAGS] = VM_FRAME_MAGIC_IFUNC | VM_FRAME_FLAG_CFRAME | VM_ENV_FLAG_LOCAL | VM_ENV_FLAG_ESCAPED;
1425 ep[VM_ENV_DATA_INDEX_ME_CREF] = Qfalse;
1426 ep[VM_ENV_DATA_INDEX_SPECVAL] = VM_BLOCK_HANDLER_NONE;
1427 ep[VM_ENV_DATA_INDEX_ENV] = Qundef; /* envval */
1428
1429 /* self? */
1430 RB_OBJ_WRITE(procval, &proc->block.as.captured.code.ifunc, ifunc);
1431 proc->header.is_lambda = TRUE;
1432 return procval;
1433}
1434
1435VALUE
1436rb_func_proc_dup(VALUE src_obj)
1437{
1438 RUBY_ASSERT(rb_typeddata_is_instance_of(src_obj, &proc_data_type));
1439
1440 rb_proc_t *src_proc;
1441 GetProcPtr(src_obj, src_proc);
1442 RUBY_ASSERT(vm_block_type(&src_proc->block) == block_type_ifunc);
1443
1444 cfunc_proc_t *proc;
1445 VALUE proc_obj = TypedData_Make_Struct(rb_obj_class(src_obj), cfunc_proc_t, &proc_data_type, proc);
1446
1447 memcpy(&proc->basic, src_proc, sizeof(rb_proc_t));
1448 RB_OBJ_WRITTEN(proc_obj, Qundef, proc->basic.block.as.captured.self);
1449 RB_OBJ_WRITTEN(proc_obj, Qundef, proc->basic.block.as.captured.code.val);
1450
1451 const VALUE *src_ep = src_proc->block.as.captured.ep;
1452 if (cfunc_proc_inline_env_p(src_proc)) {
1453 VALUE *ep = *(VALUE **)&proc->basic.block.as.captured.ep = proc->env + VM_ENV_DATA_SIZE - 1;
1454 ep[VM_ENV_DATA_INDEX_FLAGS] = src_ep[VM_ENV_DATA_INDEX_FLAGS];
1455 ep[VM_ENV_DATA_INDEX_ME_CREF] = src_ep[VM_ENV_DATA_INDEX_ME_CREF];
1456 ep[VM_ENV_DATA_INDEX_SPECVAL] = src_ep[VM_ENV_DATA_INDEX_SPECVAL];
1457 RB_OBJ_WRITE(proc_obj, &ep[VM_ENV_DATA_INDEX_ENV], src_ep[VM_ENV_DATA_INDEX_ENV]);
1458 }
1459 else {
1460 rb_vm_block_ep_update(proc_obj, &proc->basic.block, src_ep);
1461 }
1462
1463 return proc_obj;
1464}
1465
1466static VALUE
1467sym_proc_new(VALUE klass, VALUE sym)
1468{
1469 VALUE procval = rb_proc_alloc(klass, block_type_symbol);
1470 rb_proc_t *proc;
1471 GetProcPtr(procval, proc);
1472
1473 vm_block_type_set(&proc->block, block_type_symbol);
1474 proc->header.is_lambda = TRUE;
1475 RB_OBJ_WRITE(procval, &proc->symbol.symbol, sym);
1476 return procval;
1477}
1478
1479struct vm_ifunc *
1480rb_vm_ifunc_new(rb_block_call_func_t func, const void *data, int min_argc, int max_argc)
1481{
1482 if (min_argc < UNLIMITED_ARGUMENTS ||
1483#if SIZEOF_INT * 2 > SIZEOF_VALUE
1484 min_argc >= (int)(1U << (SIZEOF_VALUE * CHAR_BIT) / 2) ||
1485#endif
1486 0) {
1487 rb_raise(rb_eRangeError, "minimum argument number out of range: %d",
1488 min_argc);
1489 }
1490 if (max_argc < UNLIMITED_ARGUMENTS ||
1491#if SIZEOF_INT * 2 > SIZEOF_VALUE
1492 max_argc >= (int)(1U << (SIZEOF_VALUE * CHAR_BIT) / 2) ||
1493#endif
1494 0) {
1495 rb_raise(rb_eRangeError, "maximum argument number out of range: %d",
1496 max_argc);
1497 }
1498 rb_execution_context_t *ec = GET_EC();
1499
1500 struct vm_ifunc *ifunc = IMEMO_NEW(struct vm_ifunc, imemo_ifunc, (VALUE)rb_vm_svar_lep(ec, ec->cfp));
1501
1502 rb_gc_register_pinning_obj((VALUE)ifunc);
1503
1504 ifunc->func = func;
1505 ifunc->data = data;
1506 ifunc->argc.min = min_argc;
1507 ifunc->argc.max = max_argc;
1508
1509 return ifunc;
1510}
1511
1512VALUE
1513rb_func_lambda_new(rb_block_call_func_t func, VALUE val, int min_argc, int max_argc)
1514{
1515 struct vm_ifunc *ifunc = rb_vm_ifunc_new(func, (void *)val, min_argc, max_argc);
1516 return cfunc_proc_new(rb_cProc, (VALUE)ifunc);
1517}
1518
1519static const char proc_without_block[] = "tried to create Proc object without a block";
1520
1521static VALUE
1522proc_new(VALUE klass, int8_t is_lambda)
1523{
1524 VALUE procval;
1525 const rb_execution_context_t *ec = GET_EC();
1526 rb_control_frame_t *cfp = ec->cfp;
1527 VALUE block_handler;
1528
1529 if ((block_handler = rb_vm_frame_block_handler(cfp)) == VM_BLOCK_HANDLER_NONE) {
1530 rb_raise(rb_eArgError, proc_without_block);
1531 }
1532
1533 /* block is in cf */
1534 switch (vm_block_handler_type(block_handler)) {
1535 case block_handler_type_proc:
1536 procval = VM_BH_TO_PROC(block_handler);
1537
1538 if (RBASIC_CLASS(procval) == klass) {
1539 return procval;
1540 }
1541 else {
1542 VALUE newprocval = rb_proc_dup(procval);
1543 RBASIC_SET_CLASS(newprocval, klass);
1544 return newprocval;
1545 }
1546 break;
1547
1548 case block_handler_type_symbol:
1549 return (klass != rb_cProc) ?
1550 sym_proc_new(klass, VM_BH_TO_SYMBOL(block_handler)) :
1551 rb_sym_to_proc(VM_BH_TO_SYMBOL(block_handler));
1552 break;
1553
1554 case block_handler_type_ifunc:
1555 case block_handler_type_iseq:
1556 return rb_vm_make_proc_lambda(ec, VM_BH_TO_CAPT_BLOCK(block_handler), klass, is_lambda);
1557 }
1558 VM_UNREACHABLE(proc_new);
1559 return Qnil;
1560}
1561
1562/*
1563 * call-seq:
1564 * Proc.new {|...| block } -> a_proc
1565 *
1566 * Creates a new Proc object, bound to the current context.
1567 *
1568 * proc = Proc.new { "hello" }
1569 * proc.call #=> "hello"
1570 *
1571 * Raises ArgumentError if called without a block.
1572 *
1573 * Proc.new #=> ArgumentError
1574 */
1575
1576static VALUE
1577rb_proc_s_new(int argc, VALUE *argv, VALUE klass)
1578{
1579 VALUE block = proc_new(klass, FALSE);
1580
1581 rb_obj_call_init_kw(block, argc, argv, RB_PASS_CALLED_KEYWORDS);
1582 return block;
1583}
1584
1585VALUE
1587{
1588 return proc_new(rb_cProc, FALSE);
1589}
1590
1591/*
1592 * call-seq:
1593 * proc { |...| block } -> a_proc
1594 *
1595 * Equivalent to Proc.new.
1596 */
1597
1598static VALUE
1599f_proc(VALUE _)
1600{
1601 return proc_new(rb_cProc, FALSE);
1602}
1603
1604VALUE
1606{
1607 return proc_new(rb_cProc, TRUE);
1608}
1609
1610static void
1611f_lambda_filter_non_literal(void)
1612{
1613 rb_control_frame_t *cfp = GET_EC()->cfp;
1614 VALUE block_handler = rb_vm_frame_block_handler(cfp);
1615
1616 if (block_handler == VM_BLOCK_HANDLER_NONE) {
1617 // no block error raised else where
1618 return;
1619 }
1620
1621 switch (vm_block_handler_type(block_handler)) {
1622 case block_handler_type_iseq:
1623 if (RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp)->ep == VM_BH_TO_ISEQ_BLOCK(block_handler)->ep) {
1624 return;
1625 }
1626 break;
1627 case block_handler_type_symbol:
1628 return;
1629 case block_handler_type_proc:
1630 if (rb_proc_lambda_p(VM_BH_TO_PROC(block_handler))) {
1631 return;
1632 }
1633 break;
1634 case block_handler_type_ifunc:
1635 break;
1636 }
1637
1638 rb_raise(rb_eArgError, "the lambda method requires a literal block");
1639}
1640
1641/*
1642 * call-seq:
1643 * lambda { |...| block } -> a_proc
1644 *
1645 * Equivalent to Proc.new, except the resulting Proc objects check the
1646 * number of parameters passed when called.
1647 */
1648
1649static VALUE
1650f_lambda(VALUE _)
1651{
1652 f_lambda_filter_non_literal();
1653 return rb_block_lambda();
1654}
1655
1656/* Document-method: Proc#===
1657 *
1658 * call-seq:
1659 * proc === obj -> result_of_proc
1660 *
1661 * Invokes the block with +obj+ as the proc's parameter like Proc#call.
1662 * This allows a proc object to be the target of a +when+ clause
1663 * in a case statement.
1664 */
1665
1666/* CHECKME: are the argument checking semantics correct? */
1667
1668/*
1669 * Document-method: Proc#[]
1670 * Document-method: Proc#call
1671 * Document-method: Proc#yield
1672 *
1673 * call-seq:
1674 * call(...) -> obj
1675 * self[...] -> obj
1676 * yield(...) -> obj
1677 *
1678 * Invokes the block, setting the block's parameters to the arguments
1679 * using something close to method calling semantics.
1680 * Returns the value of the last expression evaluated in the block.
1681 *
1682 * a_proc = Proc.new {|scalar, *values| values.map {|value| value*scalar } }
1683 * a_proc.call(9, 1, 2, 3) #=> [9, 18, 27]
1684 * a_proc[9, 1, 2, 3] #=> [9, 18, 27]
1685 * a_proc.(9, 1, 2, 3) #=> [9, 18, 27]
1686 * a_proc.yield(9, 1, 2, 3) #=> [9, 18, 27]
1687 *
1688 * Note that <code>prc.()</code> invokes <code>prc.call()</code> with
1689 * the parameters given. It's syntactic sugar to hide "call".
1690 *
1691 * For procs created using #lambda or <code>->()</code> an error is
1692 * generated if the wrong number of parameters are passed to the
1693 * proc. For procs created using Proc.new or Kernel.proc, extra
1694 * parameters are silently discarded and missing parameters are set
1695 * to +nil+.
1696 *
1697 * a_proc = proc {|a,b| [a,b] }
1698 * a_proc.call(1) #=> [1, nil]
1699 *
1700 * a_proc = lambda {|a,b| [a,b] }
1701 * a_proc.call(1) # ArgumentError: wrong number of arguments (given 1, expected 2)
1702 *
1703 * See also Proc#lambda?.
1704 */
1705#if 0
1706static VALUE
1707proc_call(int argc, VALUE *argv, VALUE procval)
1708{
1709 /* removed */
1710}
1711#endif
1712
1713#if SIZEOF_RB_LEN_T > SIZEOF_INT
1714static inline int
1715check_argc(rb_len_t argc)
1716{
1717 if (argc > INT_MAX || argc < 0) {
1718 rb_raise(rb_eArgError, "too many arguments (%"PRIuLEN")",
1719 (rb_ulen_t)argc);
1720 }
1721 return (int)argc;
1722}
1723#else
1724#define check_argc(argc) (argc)
1725#endif
1726
1727VALUE
1728rb_proc_call_kw(VALUE self, VALUE args, int kw_splat)
1729{
1730 VALUE vret;
1731 rb_proc_t *proc;
1732 int argc = check_argc(RARRAY_LEN(args));
1733
1734 // rb_vm_invoke_proc may end up modifying argv as part of calling and so we
1735 // must use RARRAY_PTR, which marks the array as WB_UNPROTECTED instead of
1736 // RARRAY_CONST_PTR. Unfortunately this is worse for GC.
1737 // See invoke_block_from_c_proc
1738 VALUE *argv = RARRAY_PTR(args);
1739 GetProcPtr(self, proc);
1740 vret = rb_vm_invoke_proc(GET_EC(), proc, argc, argv,
1741 kw_splat, VM_BLOCK_HANDLER_NONE,
1742 rb_proc_refinements_cref_for_call(self));
1743 RB_GC_GUARD(self);
1744 RB_GC_GUARD(args);
1745 return vret;
1746}
1747
1748VALUE
1750{
1751 return rb_proc_call_kw(self, args, RB_NO_KEYWORDS);
1752}
1753
1754static VALUE
1755proc_to_block_handler(VALUE procval)
1756{
1757 return NIL_P(procval) ? VM_BLOCK_HANDLER_NONE : procval;
1758}
1759
1760VALUE
1761rb_proc_call_with_block_kw(VALUE self, int argc, const VALUE *argv, VALUE passed_procval, int kw_splat)
1762{
1763 rb_execution_context_t *ec = GET_EC();
1764 VALUE vret;
1765 rb_proc_t *proc;
1766 GetProcPtr(self, proc);
1767 vret = rb_vm_invoke_proc(ec, proc, argc, argv, kw_splat, proc_to_block_handler(passed_procval),
1768 rb_proc_refinements_cref_for_call(self));
1769 RB_GC_GUARD(self);
1770 return vret;
1771}
1772
1773VALUE
1774rb_proc_call_with_block(VALUE self, int argc, const VALUE *argv, VALUE passed_procval)
1775{
1776 return rb_proc_call_with_block_kw(self, argc, argv, passed_procval, RB_NO_KEYWORDS);
1777}
1778
1779
1780/*
1781 * call-seq:
1782 * prc.arity -> integer
1783 *
1784 * Returns the number of mandatory arguments. If the block
1785 * is declared to take no arguments, returns 0. If the block is known
1786 * to take exactly n arguments, returns n.
1787 * If the block has optional arguments, returns -n-1, where n is the
1788 * number of mandatory arguments, with the exception for blocks that
1789 * are not lambdas and have only a finite number of optional arguments;
1790 * in this latter case, returns n.
1791 * Keyword arguments will be considered as a single additional argument,
1792 * that argument being mandatory if any keyword argument is mandatory.
1793 * A #proc with no argument declarations is the same as a block
1794 * declaring <code>||</code> as its arguments.
1795 *
1796 * proc {}.arity #=> 0
1797 * proc { || }.arity #=> 0
1798 * proc { |a| }.arity #=> 1
1799 * proc { |a, b| }.arity #=> 2
1800 * proc { |a, b, c| }.arity #=> 3
1801 * proc { |*a| }.arity #=> -1
1802 * proc { |a, *b| }.arity #=> -2
1803 * proc { |a, *b, c| }.arity #=> -3
1804 * proc { |x:, y:, z:0| }.arity #=> 1
1805 * proc { |*a, x:, y:0| }.arity #=> -2
1806 *
1807 * proc { |a=0| }.arity #=> 0
1808 * lambda { |a=0| }.arity #=> -1
1809 * proc { |a=0, b| }.arity #=> 1
1810 * lambda { |a=0, b| }.arity #=> -2
1811 * proc { |a=0, b=0| }.arity #=> 0
1812 * lambda { |a=0, b=0| }.arity #=> -1
1813 * proc { |a, b=0| }.arity #=> 1
1814 * lambda { |a, b=0| }.arity #=> -2
1815 * proc { |(a, b), c=0| }.arity #=> 1
1816 * lambda { |(a, b), c=0| }.arity #=> -2
1817 * proc { |a, x:0, y:0| }.arity #=> 1
1818 * lambda { |a, x:0, y:0| }.arity #=> -2
1819 */
1820
1821static VALUE
1822proc_arity(VALUE self)
1823{
1824 int arity = rb_proc_arity(self);
1825 return INT2FIX(arity);
1826}
1827
1828static inline int
1829rb_iseq_min_max_arity(const rb_iseq_t *iseq, int *max)
1830{
1831 *max = ISEQ_BODY(iseq)->param.flags.has_rest == FALSE ?
1832 ISEQ_BODY(iseq)->param.lead_num + ISEQ_BODY(iseq)->param.opt_num + ISEQ_BODY(iseq)->param.post_num +
1833 (ISEQ_BODY(iseq)->param.flags.has_kw == TRUE || ISEQ_BODY(iseq)->param.flags.has_kwrest == TRUE || ISEQ_BODY(iseq)->param.flags.forwardable == TRUE)
1835 return ISEQ_BODY(iseq)->param.lead_num + ISEQ_BODY(iseq)->param.post_num + (ISEQ_BODY(iseq)->param.flags.has_kw && ISEQ_BODY(iseq)->param.keyword->required_num > 0);
1836}
1837
1838static int
1839rb_vm_block_min_max_arity(const struct rb_block *block, int *max)
1840{
1841 again:
1842 switch (vm_block_type(block)) {
1843 case block_type_iseq:
1844 return rb_iseq_min_max_arity(rb_iseq_check(block->as.captured.code.iseq), max);
1845 case block_type_proc:
1846 block = vm_proc_block(block->as.proc);
1847 goto again;
1848 case block_type_ifunc:
1849 {
1850 const struct vm_ifunc *ifunc = block->as.captured.code.ifunc;
1851 if (IS_METHOD_PROC_IFUNC(ifunc)) {
1852 /* e.g. method(:foo).to_proc.arity */
1853 return method_min_max_arity((VALUE)ifunc->data, max);
1854 }
1855 *max = ifunc->argc.max;
1856 return ifunc->argc.min;
1857 }
1858 case block_type_symbol:
1859 *max = UNLIMITED_ARGUMENTS;
1860 return 1;
1861 }
1862 *max = UNLIMITED_ARGUMENTS;
1863 return 0;
1864}
1865
1866/*
1867 * Returns the number of required parameters and stores the maximum
1868 * number of parameters in max, or UNLIMITED_ARGUMENTS if no max.
1869 * For non-lambda procs, the maximum is the number of non-ignored
1870 * parameters even though there is no actual limit to the number of parameters
1871 */
1872static int
1873rb_proc_min_max_arity(VALUE self, int *max)
1874{
1875 rb_proc_t *proc;
1876 GetProcPtr(self, proc);
1877 return rb_vm_block_min_max_arity(&proc->block, max);
1878}
1879
1880int
1882{
1883 rb_proc_t *proc;
1884 int max, min;
1885 GetProcPtr(self, proc);
1886 min = rb_vm_block_min_max_arity(&proc->block, &max);
1887 return (proc->header.is_lambda ? min == max : max != UNLIMITED_ARGUMENTS) ? min : -min-1;
1888}
1889
1890static void
1891block_setup(struct rb_block *block, VALUE block_handler)
1892{
1893 switch (vm_block_handler_type(block_handler)) {
1894 case block_handler_type_iseq:
1895 block->type = block_type_iseq;
1896 block->as.captured = *VM_BH_TO_ISEQ_BLOCK(block_handler);
1897 break;
1898 case block_handler_type_ifunc:
1899 block->type = block_type_ifunc;
1900 block->as.captured = *VM_BH_TO_IFUNC_BLOCK(block_handler);
1901 break;
1902 case block_handler_type_symbol:
1903 block->type = block_type_symbol;
1904 block->as.symbol = VM_BH_TO_SYMBOL(block_handler);
1905 break;
1906 case block_handler_type_proc:
1907 block->type = block_type_proc;
1908 block->as.proc = VM_BH_TO_PROC(block_handler);
1909 }
1910}
1911
1912int
1913rb_block_pair_yield_optimizable(void)
1914{
1915 int min, max;
1916 const rb_execution_context_t *ec = GET_EC();
1917 rb_control_frame_t *cfp = ec->cfp;
1918 VALUE block_handler = rb_vm_frame_block_handler(cfp);
1919 struct rb_block block;
1920
1921 if (block_handler == VM_BLOCK_HANDLER_NONE) {
1922 rb_raise(rb_eArgError, "no block given");
1923 }
1924
1925 block_setup(&block, block_handler);
1926 min = rb_vm_block_min_max_arity(&block, &max);
1927
1928 switch (vm_block_type(&block)) {
1929 case block_type_symbol:
1930 return 0;
1931
1932 case block_type_proc:
1933 {
1934 VALUE procval = block_handler;
1935 rb_proc_t *proc;
1936 GetProcPtr(procval, proc);
1937 if (proc->header.is_lambda) return 0;
1938 if (min != max) return 0;
1939 return min > 1;
1940 }
1941
1942 case block_type_ifunc:
1943 {
1944 const struct vm_ifunc *ifunc = block.as.captured.code.ifunc;
1945 if (ifunc->flags & IFUNC_YIELD_OPTIMIZABLE) return 1;
1946 }
1947
1948 default:
1949 return min > 1;
1950 }
1951}
1952
1953int
1954rb_block_arity(void)
1955{
1956 int min, max;
1957 const rb_execution_context_t *ec = GET_EC();
1958 rb_control_frame_t *cfp = ec->cfp;
1959 VALUE block_handler = rb_vm_frame_block_handler(cfp);
1960 struct rb_block block;
1961
1962 if (block_handler == VM_BLOCK_HANDLER_NONE) {
1963 rb_raise(rb_eArgError, "no block given");
1964 }
1965
1966 block_setup(&block, block_handler);
1967
1968 switch (vm_block_type(&block)) {
1969 case block_type_symbol:
1970 return -1;
1971
1972 case block_type_proc:
1973 return rb_proc_arity(block_handler);
1974
1975 default:
1976 min = rb_vm_block_min_max_arity(&block, &max);
1977 return max != UNLIMITED_ARGUMENTS ? min : -min-1;
1978 }
1979}
1980
1981int
1982rb_block_min_max_arity(int *max)
1983{
1984 const rb_execution_context_t *ec = GET_EC();
1985 rb_control_frame_t *cfp = ec->cfp;
1986 VALUE block_handler = rb_vm_frame_block_handler(cfp);
1987 struct rb_block block;
1988
1989 if (block_handler == VM_BLOCK_HANDLER_NONE) {
1990 rb_raise(rb_eArgError, "no block given");
1991 }
1992
1993 block_setup(&block, block_handler);
1994 return rb_vm_block_min_max_arity(&block, max);
1995}
1996
1997const rb_iseq_t *
1998rb_proc_get_iseq(VALUE self, int *is_proc)
1999{
2000 const rb_proc_t *proc;
2001 const struct rb_block *block;
2002
2003 GetProcPtr(self, proc);
2004 block = &proc->block;
2005 if (is_proc) *is_proc = !proc->header.is_lambda;
2006
2007 switch (vm_block_type(block)) {
2008 case block_type_iseq:
2009 return rb_iseq_check(block->as.captured.code.iseq);
2010 case block_type_proc:
2011 return rb_proc_get_iseq(block->as.proc, is_proc);
2012 case block_type_ifunc:
2013 {
2014 const struct vm_ifunc *ifunc = block->as.captured.code.ifunc;
2015 if (IS_METHOD_PROC_IFUNC(ifunc)) {
2016 /* method(:foo).to_proc */
2017 if (is_proc) *is_proc = 0;
2018 return rb_method_iseq((VALUE)ifunc->data);
2019 }
2020 else {
2021 return NULL;
2022 }
2023 }
2024 case block_type_symbol:
2025 return NULL;
2026 }
2027
2028 VM_UNREACHABLE(rb_proc_get_iseq);
2029 return NULL;
2030}
2031
2032/* call-seq:
2033 * self == other -> true or false
2034 * eql?(other) -> true or false
2035 *
2036 * Returns whether +self+ and +other+ were created from the same code
2037 * block and the same binding:
2038 *
2039 * def return_block(&block)
2040 * block
2041 * end
2042 *
2043 * def pass_block_twice(&block)
2044 * [return_block(&block), return_block(&block)]
2045 * end
2046 *
2047 * block1, block2 = pass_block_twice { puts 'test' }
2048 * # Blocks might be instantiated into Proc's lazily, so they may, or may not,
2049 * # be the same object.
2050 * # But they are produced from the same code block, so they are equal
2051 * block1 == block2
2052 * #=> true
2053 *
2054 * # Another Proc will never be equal, even if the code is the "same"
2055 * block1 == proc { puts 'test' }
2056 * #=> false
2057 *
2058 * # Proc with the same code block but different binding is not equal:
2059 * def new_proc = proc { 1 }
2060 * new_proc == new_proc
2061 * #=> false
2062 *
2063 */
2064VALUE
2065rb_proc_eq(VALUE self, VALUE other)
2066{
2067 const rb_proc_t *self_proc, *other_proc;
2068 const struct rb_block *self_block, *other_block;
2069
2070 if (rb_obj_class(self) != rb_obj_class(other)) {
2071 return Qfalse;
2072 }
2073
2074 GetProcPtr(self, self_proc);
2075 GetProcPtr(other, other_proc);
2076
2077 if (self_proc->header.is_from_method != other_proc->header.is_from_method ||
2078 self_proc->header.is_lambda != other_proc->header.is_lambda ||
2079 self_proc->header.is_refined != other_proc->header.is_refined) {
2080 return Qfalse;
2081 }
2082
2083 self_block = &self_proc->block;
2084 other_block = &other_proc->block;
2085
2086 if (vm_block_type(self_block) != vm_block_type(other_block)) {
2087 return Qfalse;
2088 }
2089
2090 switch (vm_block_type(self_block)) {
2091 case block_type_iseq:
2092 if (self_block->as.captured.ep != \
2093 other_block->as.captured.ep) {
2094 return Qfalse;
2095 }
2096 /* a refined Proc's block iseq flips from the source to the copy on
2097 * the first call; compare what the Procs were built from instead */
2098 if (self_proc->header.is_refined) {
2099 if (!refinement_recipe_eq(rb_proc_refinements_recipe(self),
2100 rb_proc_refinements_recipe(other))) {
2101 return Qfalse;
2102 }
2103 }
2104 else if (self_block->as.captured.code.iseq != \
2105 other_block->as.captured.code.iseq) {
2106 return Qfalse;
2107 }
2108 break;
2109 case block_type_ifunc:
2110 if (self_block->as.captured.code.ifunc != \
2111 other_block->as.captured.code.ifunc) {
2112 return Qfalse;
2113 }
2114
2115 if (self_block->as.captured.ep != other_block->as.captured.ep) {
2116 if (!cfunc_proc_inline_env_p(self_proc) ||
2117 !cfunc_proc_inline_env_p(other_proc) ||
2118 memcmp(
2119 ((const cfunc_proc_t *)self_proc)->env,
2120 ((const cfunc_proc_t *)other_proc)->env,
2121 sizeof(((const cfunc_proc_t *)self_proc)->env))) {
2122 return Qfalse;
2123 }
2124 }
2125 break;
2126 case block_type_proc:
2127 if (self_block->as.proc != other_block->as.proc) {
2128 return Qfalse;
2129 }
2130 break;
2131 case block_type_symbol:
2132 if (self_block->as.symbol != other_block->as.symbol) {
2133 return Qfalse;
2134 }
2135 break;
2136 }
2137
2138 return Qtrue;
2139}
2140
2141static VALUE
2142iseq_location(const rb_iseq_t *iseq)
2143{
2144 VALUE loc[2];
2145
2146 if (!iseq) return Qnil;
2147 rb_iseq_check(iseq);
2148 loc[0] = rb_iseq_path(iseq);
2149 loc[1] = RB_INT2NUM(ISEQ_BODY(iseq)->location.first_lineno);
2150
2151 return rb_ary_new4(2, loc);
2152}
2153
2154VALUE
2155rb_iseq_location(const rb_iseq_t *iseq)
2156{
2157 return iseq_location(iseq);
2158}
2159
2160/*
2161 * call-seq:
2162 * prc.source_location -> [String, Integer]
2163 *
2164 * Returns the Ruby source filename and line number containing this proc
2165 * or +nil+ if this proc was not defined in Ruby (i.e. native).
2166 */
2167
2168VALUE
2169rb_proc_location(VALUE self)
2170{
2171 return iseq_location(rb_proc_get_iseq(self, 0));
2172}
2173
2174/*
2175 * call-seq:
2176 * prc.source_range -> Ruby::SourceRange or nil
2177 *
2178 * Returns a Ruby::SourceRange for this proc, or +nil+ if this proc was
2179 * not defined in Ruby (i.e. native) or has no source path.
2180 *
2181 * The returned Ruby::SourceRange includes the source path, absolute path when
2182 * available, and the start and end line and byte-column coordinates.
2183 *
2184 * See https://github.com/ruby/spec/blob/master/core/proc/source_range_spec.rb
2185 * for the location of start/end line/column in various cases.
2186 */
2187static VALUE
2188rb_proc_source_range(VALUE self)
2189{
2190 return source_range_new(rb_proc_get_iseq(self, 0));
2191}
2192
2193VALUE
2194rb_unnamed_parameters(int arity)
2195{
2196 VALUE a, param = rb_ary_new2((arity < 0) ? -arity : arity);
2197 int n = (arity < 0) ? ~arity : arity;
2198 ID req, rest;
2199 CONST_ID(req, "req");
2200 a = rb_ary_new3(1, ID2SYM(req));
2201 OBJ_FREEZE(a);
2202 for (; n; --n) {
2203 rb_ary_push(param, a);
2204 }
2205 if (arity < 0) {
2206 CONST_ID(rest, "rest");
2207 rb_ary_store(param, ~arity, rb_ary_new3(1, ID2SYM(rest)));
2208 }
2209 return param;
2210}
2211
2212/*
2213 * call-seq:
2214 * prc.parameters(lambda: nil) -> array
2215 *
2216 * Returns the parameter information of this proc. If the lambda
2217 * keyword is provided and not nil, treats the proc as a lambda if
2218 * true and as a non-lambda if false.
2219 *
2220 * prc = proc{|x, y=42, *other|}
2221 * prc.parameters #=> [[:opt, :x], [:opt, :y], [:rest, :other]]
2222 * prc = lambda{|x, y=42, *other|}
2223 * prc.parameters #=> [[:req, :x], [:opt, :y], [:rest, :other]]
2224 * prc = proc{|x, y=42, *other|}
2225 * prc.parameters(lambda: true) #=> [[:req, :x], [:opt, :y], [:rest, :other]]
2226 * prc = lambda{|x, y=42, *other|}
2227 * prc.parameters(lambda: false) #=> [[:opt, :x], [:opt, :y], [:rest, :other]]
2228 */
2229
2230static VALUE
2231rb_proc_parameters(int argc, VALUE *argv, VALUE self)
2232{
2233 static ID keyword_ids[1];
2234 VALUE opt, lambda;
2235 VALUE kwargs[1];
2236 int is_proc ;
2237 const rb_iseq_t *iseq;
2238
2239 iseq = rb_proc_get_iseq(self, &is_proc);
2240
2241 if (!keyword_ids[0]) {
2242 CONST_ID(keyword_ids[0], "lambda");
2243 }
2244
2245 rb_scan_args(argc, argv, "0:", &opt);
2246 if (!NIL_P(opt)) {
2247 rb_get_kwargs(opt, keyword_ids, 0, 1, kwargs);
2248 lambda = kwargs[0];
2249 if (!NIL_P(lambda)) {
2250 is_proc = !RTEST(lambda);
2251 }
2252 }
2253
2254 if (!iseq) {
2255 return rb_unnamed_parameters(rb_proc_arity(self));
2256 }
2257 return rb_iseq_parameters(iseq, is_proc);
2258}
2259
2260static st_index_t
2261iseq_location_hash(st_index_t hash, const rb_iseq_t *iseq)
2262{
2263 const struct rb_iseq_constant_body *body = ISEQ_BODY(iseq);
2264 if (body) {
2265 const rb_iseq_location_t *loc = &body->location;
2266 hash = rb_st_hash_uint(hash, (st_index_t)loc->code_location.beg_pos.lineno);
2267 hash = rb_st_hash_uint(hash, (st_index_t)loc->code_location.beg_pos.column);
2268 hash = rb_st_hash_uint(hash, (st_index_t)loc->code_location.end_pos.lineno);
2269 hash = rb_st_hash_uint(hash, (st_index_t)loc->code_location.end_pos.column);
2270 }
2271 return hash;
2272}
2273
2274st_index_t
2275rb_hash_proc(st_index_t hash, VALUE prc)
2276{
2277 rb_proc_t *proc;
2278 GetProcPtr(prc, proc);
2279
2280 switch (vm_block_type(&proc->block)) {
2281 case block_type_iseq:
2282 if (proc->header.is_refined) {
2283 /* from the recipe, not the block iseq: the latter flips from the
2284 * source to the copy on the first call, and the hash must not */
2285 VALUE recipe = rb_proc_refinements_recipe(prc);
2286 rb_len_t len = RARRAY_LEN(recipe);
2287 hash = rb_st_hash_uint(hash, (st_index_t)RARRAY_AREF(recipe, REFINEMENT_RECIPE_BASE_CREF));
2288 hash = iseq_location_hash(hash, (const rb_iseq_t *)RARRAY_AREF(recipe, REFINEMENT_RECIPE_SRC_ISEQ));
2289 for (rb_len_t i = REFINEMENT_RECIPE_MODS; i < len; i++) {
2290 hash = rb_st_hash_uint(hash, (st_index_t)RARRAY_AREF(recipe, i));
2291 }
2292 }
2293 else {
2294 hash = iseq_location_hash(hash, proc->block.as.captured.code.iseq);
2295 }
2296 break;
2297 case block_type_ifunc:
2298 hash = rb_st_hash_uint(hash, (st_index_t)proc->block.as.captured.code.ifunc->func);
2299 hash = rb_st_hash_uint(hash, (st_index_t)proc->block.as.captured.code.ifunc->data);
2300 break;
2301 case block_type_symbol:
2302 hash = rb_st_hash_uint(hash, rb_any_hash(proc->block.as.symbol));
2303 break;
2304 case block_type_proc:
2305 hash = rb_st_hash_uint(hash, rb_any_hash(proc->block.as.proc));
2306 break;
2307 default:
2308 rb_bug("rb_hash_proc: unknown block type %d", vm_block_type(&proc->block));
2309 }
2310
2311 /* ifunc procs have their own allocated ep. If an ifunc is duplicated, they
2312 * will point to different ep but they should return the same hash code, so
2313 * we cannot include the ep in the hash. Symbol and proc type blocks are
2314 * smaller and do not have an ep at all. */
2315 if (vm_block_type(&proc->block) == block_type_iseq) {
2316 hash = rb_hash_uint(hash, (st_index_t)proc->block.as.captured.ep);
2317 }
2318
2319 return hash;
2320}
2321
2322static VALUE sym_proc_cache = Qfalse;
2323
2324/*
2325 * call-seq:
2326 * to_proc
2327 *
2328 * Returns a Proc object which calls the method with name of +self+
2329 * on the first parameter and passes the remaining parameters to the method.
2330 *
2331 * proc = :to_s.to_proc # => #<Proc:0x000001afe0e48680(&:to_s) (lambda)>
2332 * proc.call(1000) # => "1000"
2333 * proc.call(1000, 16) # => "3e8"
2334 * (1..3).collect(&:to_s) # => ["1", "2", "3"]
2335 *
2336 */
2337
2338VALUE
2339rb_sym_to_proc(VALUE sym)
2340{
2341 enum {SYM_PROC_CACHE_SIZE = 67};
2342
2343 if (rb_ractor_main_p()) {
2344 if (!sym_proc_cache) {
2345 sym_proc_cache = rb_ary_hidden_new(SYM_PROC_CACHE_SIZE);
2346 rb_ary_store(sym_proc_cache, SYM_PROC_CACHE_SIZE - 1, Qnil);
2347 }
2348
2349 ID id = SYM2ID(sym);
2350 rb_len_t index = (id % SYM_PROC_CACHE_SIZE);
2351 VALUE procval = RARRAY_AREF(sym_proc_cache, index);
2352 if (RTEST(procval)) {
2353 rb_proc_t *proc;
2354 GetProcPtr(procval, proc);
2355
2356 if (proc->block.as.symbol == sym) {
2357 return procval;
2358 }
2359 }
2360
2361 procval = sym_proc_new(rb_cProc, sym);
2362 RARRAY_ASET(sym_proc_cache, index, procval);
2363
2364 return RB_GC_GUARD(procval);
2365 }
2366 else {
2367 return sym_proc_new(rb_cProc, sym);
2368 }
2369}
2370
2371/*
2372 * call-seq:
2373 * prc.hash -> integer
2374 *
2375 * Returns a hash value corresponding to proc body.
2376 *
2377 * See also Object#hash.
2378 */
2379
2380static VALUE
2381proc_hash(VALUE self)
2382{
2383 st_index_t hash;
2384 hash = rb_hash_start(0);
2385 hash = rb_hash_proc(hash, self);
2386 hash = rb_hash_end(hash);
2387 return ST2FIX(hash);
2388}
2389
2390VALUE
2391rb_block_to_s(VALUE self, const struct rb_block *block, const char *additional_info)
2392{
2393 VALUE cname = rb_obj_class(self);
2394 VALUE str = rb_sprintf("#<%"PRIsVALUE":", cname);
2395
2396 again:
2397 switch (vm_block_type(block)) {
2398 case block_type_proc:
2399 block = vm_proc_block(block->as.proc);
2400 goto again;
2401 case block_type_iseq:
2402 {
2403 const rb_iseq_t *iseq = rb_iseq_check(block->as.captured.code.iseq);
2404 rb_str_catf(str, "%p %"PRIsVALUE":%d", (void *)self,
2405 rb_iseq_path(iseq),
2406 ISEQ_BODY(iseq)->location.first_lineno);
2407 }
2408 break;
2409 case block_type_symbol:
2410 rb_str_catf(str, "%p(&%+"PRIsVALUE")", (void *)self, block->as.symbol);
2411 break;
2412 case block_type_ifunc:
2413 rb_str_catf(str, "%p", (void *)block->as.captured.code.ifunc);
2414 break;
2415 }
2416
2417 if (additional_info) rb_str_cat_cstr(str, additional_info);
2418 rb_str_cat_cstr(str, ">");
2419 return str;
2420}
2421
2422/*
2423 * call-seq:
2424 * prc.to_s -> string
2425 *
2426 * Returns the unique identifier for this proc, along with
2427 * an indication of where the proc was defined.
2428 */
2429
2430static VALUE
2431proc_to_s(VALUE self)
2432{
2433 const rb_proc_t *proc;
2434 GetProcPtr(self, proc);
2435 return rb_block_to_s(self, &proc->block, proc->header.is_lambda ? " (lambda)" : NULL);
2436}
2437
2438/*
2439 * call-seq:
2440 * prc.to_proc -> proc
2441 *
2442 * Part of the protocol for converting objects to Proc objects.
2443 * Instances of class Proc simply return themselves.
2444 */
2445
2446static VALUE
2447proc_to_proc(VALUE self)
2448{
2449 return self;
2450}
2451
2452static void
2453bm_mark_and_move(void *ptr)
2454{
2455 struct METHOD *data = ptr;
2456 rb_gc_mark_and_move((VALUE *)&data->recv);
2457 rb_gc_mark_and_move((VALUE *)&data->klass);
2458 rb_gc_mark_and_move((VALUE *)&data->iclass);
2459 rb_gc_mark_and_move((VALUE *)&data->owner);
2460 rb_gc_mark_and_move_ptr((rb_method_entry_t **)&data->me);
2461}
2462
2463static const rb_data_type_t method_data_type = {
2464 "method",
2465 {
2466 bm_mark_and_move,
2468 NULL, // No external memory to report,
2469 bm_mark_and_move,
2470 },
2471 0, 0, RUBY_TYPED_THREAD_SAFE_FREE | RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_EMBEDDABLE | RUBY_TYPED_FROZEN_SHAREABLE_NO_REC
2472};
2473
2474VALUE
2476{
2477 return RBOOL(rb_typeddata_is_kind_of(m, &method_data_type));
2478}
2479
2480static int
2481respond_to_missing_p(VALUE klass, VALUE obj, VALUE sym, int scope)
2482{
2483 /* TODO: merge with obj_respond_to() */
2484 ID rmiss = idRespond_to_missing;
2485
2486 if (UNDEF_P(obj)) return 0;
2487 if (rb_method_basic_definition_p(klass, rmiss)) return 0;
2488 return RTEST(rb_funcall(obj, rmiss, 2, sym, RBOOL(!scope)));
2489}
2490
2491
2492static VALUE
2493mnew_missing(VALUE klass, VALUE obj, ID id, VALUE mclass)
2494{
2495 struct METHOD *data;
2496 VALUE method = TypedData_Make_Struct(mclass, struct METHOD, &method_data_type, data);
2497 rb_method_entry_t *me;
2498 rb_method_definition_t *def;
2499
2500 RB_OBJ_WRITE(method, &data->recv, obj);
2501 RB_OBJ_WRITE(method, &data->klass, klass);
2502 RB_OBJ_WRITE(method, &data->owner, klass);
2503
2504 def = ZALLOC(rb_method_definition_t);
2505 def->type = VM_METHOD_TYPE_MISSING;
2506 def->original_id = id;
2507
2508 me = rb_method_entry_create(id, klass, METHOD_VISI_UNDEF, def);
2509
2510 RB_OBJ_WRITE(method, &data->me, me);
2511
2512 return method;
2513}
2514
2515static VALUE
2516mnew_missing_by_name(VALUE klass, VALUE obj, VALUE *name, int scope, VALUE mclass)
2517{
2518 VALUE vid = rb_str_intern(*name);
2519 *name = vid;
2520 if (!respond_to_missing_p(klass, obj, vid, scope)) return Qfalse;
2521 return mnew_missing(klass, obj, SYM2ID(vid), mclass);
2522}
2523
2524VALUE rb_zsuper_to_super(int argc, VALUE *argv, VALUE self);
2525
2526static inline bool
2527refinement_module_p(VALUE mod)
2528{
2529 return RB_TYPE_P(mod, T_MODULE) && FL_TEST_RAW(mod, RMODULE_IS_REFINEMENT);
2530}
2531
2532VALUE rb_vm_module_refinement_iclass(VALUE refinement_iclass, VALUE defined_class);
2533VALUE rb_vm_refinement_iclass_for_cme(VALUE refinement, const rb_callable_method_entry_t *cme);
2534
2535static VALUE
2536find_refined_target_ancestor(VALUE start, VALUE refined_target)
2537{
2538 VALUE klass;
2539 for (klass = start; klass; klass = RCLASS_SUPER(klass)) {
2540 if (RB_TYPE_P(klass, T_ICLASS) && RBASIC(klass)->klass == refined_target) {
2541 return klass;
2542 }
2543 }
2544 return 0;
2545}
2546
2547static VALUE
2548find_ancestor(VALUE start, VALUE ancestor)
2549{
2550 VALUE klass;
2551 for (klass = start; klass; klass = RCLASS_SUPER(klass)) {
2552 if (klass == ancestor) return klass;
2553 }
2554 return 0;
2555}
2556
2557static VALUE
2558find_refinement_iclass(VALUE owner, VALUE klass, VALUE iclass)
2559{
2560 VALUE refined_target = rb_refinement_module_get_refined_class(owner);
2561
2562 if (RB_TYPE_P(refined_target, T_MODULE)) {
2563 /* If the iclass given is already the refinement iclass we want,
2564 * return it instead of generating a new refinement iclass, so that
2565 * Method/UnboundMethod equality works as expected.
2566 */
2567 VALUE refinement_iclass = RCLASS_SUPER(iclass);
2568 while (RICLASS_FOR_REFINEMENT_P(refinement_iclass)) {
2569 refinement_iclass = RCLASS_SUPER(refinement_iclass);
2570 }
2571 if (RB_TYPE_P(refinement_iclass, T_ICLASS) &&
2572 RBASIC(refinement_iclass)->klass == refined_target &&
2573 find_ancestor(klass, refinement_iclass)) {
2574 return iclass;
2575 }
2576
2577 VALUE refined_ancestor = find_refined_target_ancestor(klass, refined_target);
2578 if (!refined_ancestor) {
2579 refined_ancestor = rb_include_class_new(refined_target, klass);
2580 }
2581 iclass = rb_vm_module_refinement_iclass(iclass, refined_ancestor);
2582 }
2583
2584 return iclass;
2585}
2586
2587static VALUE
2588mnew_internal(const rb_method_entry_t *me, VALUE klass, VALUE iclass,
2589 VALUE obj, ID id, VALUE mclass, int scope, int error)
2590{
2591 struct METHOD *data;
2592 VALUE method;
2593 const rb_method_entry_t *original_me = me;
2594 rb_method_visibility_t visi = METHOD_VISI_UNDEF;
2595
2596 again:
2597 if (UNDEFINED_METHOD_ENTRY_P(me)) {
2598 if (respond_to_missing_p(klass, obj, ID2SYM(id), scope)) {
2599 return mnew_missing(klass, obj, id, mclass);
2600 }
2601 if (!error) return Qnil;
2602 rb_print_undef(klass, id, METHOD_VISI_UNDEF);
2603 }
2604 if (visi == METHOD_VISI_UNDEF) {
2605 visi = METHOD_ENTRY_VISI(me);
2606 RUBY_ASSERT(visi != METHOD_VISI_UNDEF); /* !UNDEFINED_METHOD_ENTRY_P(me) */
2607 if (scope && (visi != METHOD_VISI_PUBLIC)) {
2608 if (!error) return Qnil;
2609 rb_print_inaccessible(klass, id, visi);
2610 }
2611 }
2612 if (me->def->type == VM_METHOD_TYPE_ZSUPER ||
2613 (me->def->type == VM_METHOD_TYPE_CFUNC && me->def->body.cfunc.func == (rb_cfunc_t)rb_zsuper_to_super)) {
2614 if (me->def->type == VM_METHOD_TYPE_ZSUPER && me->defined_class) {
2615 VALUE klass = RCLASS_SUPER(RCLASS_ORIGIN(me->defined_class));
2616 id = me->def->original_id;
2617 me = (rb_method_entry_t *)rb_callable_method_entry_with_refinements(klass, id, &iclass);
2618 }
2619 else {
2620 VALUE klass = RCLASS_SUPER(RCLASS_ORIGIN(me->owner));
2621 id = me->def->original_id;
2622 me = rb_method_entry_without_refinements(klass, id, &iclass);
2623 }
2624 goto again;
2625 }
2626
2627 method = TypedData_Make_Struct(mclass, struct METHOD, &method_data_type, data);
2628
2629 if (UNDEF_P(obj)) {
2630 RB_OBJ_WRITE(method, &data->recv, Qundef);
2631 RB_OBJ_WRITE(method, &data->klass, Qundef);
2632 }
2633 else {
2634 RB_OBJ_WRITE(method, &data->recv, obj);
2635 RB_OBJ_WRITE(method, &data->klass, klass);
2636 }
2637 RB_OBJ_WRITE(method, &data->iclass, iclass);
2638 RB_OBJ_WRITE(method, &data->owner, original_me->owner);
2639 RB_OBJ_WRITE(method, &data->me, me);
2640
2641 return method;
2642}
2643
2644static VALUE
2645mnew_from_me(const rb_method_entry_t *me, VALUE klass, VALUE iclass,
2646 VALUE obj, ID id, VALUE mclass, int scope)
2647{
2648 if (me && refinement_module_p(me->owner) && !RICLASS_FOR_REFINEMENT_P(iclass)) {
2649 iclass = klass;
2650 }
2651
2652 return mnew_internal(me, klass, iclass, obj, id, mclass, scope, TRUE);
2653}
2654
2655static VALUE
2656mnew_callable(VALUE klass, VALUE obj, ID id, VALUE mclass, int scope)
2657{
2658 const rb_method_entry_t *me;
2659 VALUE iclass = Qnil;
2660
2661 ASSUME(!UNDEF_P(obj));
2662 me = (rb_method_entry_t *)rb_callable_method_entry_with_refinements(klass, id, &iclass);
2663 return mnew_from_me(me, klass, iclass, obj, id, mclass, scope);
2664}
2665
2666static VALUE
2667mnew_unbound(VALUE klass, ID id, VALUE mclass, int scope)
2668{
2669 const rb_method_entry_t *me;
2670 VALUE iclass = Qnil;
2671
2672 me = rb_method_entry_with_refinements(klass, id, &iclass);
2673 return mnew_from_me(me, klass, iclass, Qundef, id, mclass, scope);
2674}
2675
2676static inline VALUE
2677method_entry_defined_class(const rb_method_entry_t *me)
2678{
2679 VALUE defined_class = me->defined_class;
2680 return defined_class ? defined_class : me->owner;
2681}
2682
2683/**********************************************************************
2684 *
2685 * Document-class: Method
2686 *
2687 * +Method+ objects are created by Object#method, and are associated
2688 * with a particular object (not just with a class). They may be
2689 * used to invoke the method within the object, and as a block
2690 * associated with an iterator. They may also be unbound from one
2691 * object (creating an UnboundMethod) and bound to another.
2692 *
2693 * class Thing
2694 * def square(n)
2695 * n*n
2696 * end
2697 * end
2698 * thing = Thing.new
2699 * meth = thing.method(:square)
2700 *
2701 * meth.call(9) #=> 81
2702 * [ 1, 2, 3 ].collect(&meth) #=> [1, 4, 9]
2703 *
2704 * [ 1, 2, 3 ].each(&method(:puts)) #=> prints 1, 2, 3
2705 *
2706 * require 'date'
2707 * %w[2017-03-01 2017-03-02].collect(&Date.method(:parse))
2708 * #=> [#<Date: 2017-03-01 ((2457814j,0s,0n),+0s,2299161j)>, #<Date: 2017-03-02 ((2457815j,0s,0n),+0s,2299161j)>]
2709 */
2710
2711/*
2712 * call-seq:
2713 * self == other -> true or false
2714 *
2715 * Returns whether +self+ and +other+ are bound to the same
2716 * object and refer to the same method definition and the classes
2717 * defining the methods are the same class or module.
2718 */
2719
2720static VALUE
2721method_eq(VALUE method, VALUE other)
2722{
2723 struct METHOD *m1, *m2;
2724 VALUE klass1, klass2;
2725
2726 if (!rb_obj_is_method(other))
2727 return Qfalse;
2728 if (CLASS_OF(method) != CLASS_OF(other))
2729 return Qfalse;
2730
2731 Check_TypedStruct(method, &method_data_type);
2732 m1 = (struct METHOD *)RTYPEDDATA_GET_DATA(method);
2733 m2 = (struct METHOD *)RTYPEDDATA_GET_DATA(other);
2734
2735 klass1 = method_entry_defined_class(m1->me);
2736 klass2 = method_entry_defined_class(m2->me);
2737 if (RB_TYPE_P(klass1, T_ICLASS)) klass1 = RBASIC_CLASS(klass1);
2738 if (RB_TYPE_P(klass2, T_ICLASS)) klass2 = RBASIC_CLASS(klass2);
2739
2740 if (!rb_method_entry_eq(m1->me, m2->me) ||
2741 klass1 != klass2 ||
2742 m1->klass != m2->klass ||
2743 m1->recv != m2->recv) {
2744 return Qfalse;
2745 }
2746
2747 return Qtrue;
2748}
2749
2750/*
2751 * call-seq:
2752 * meth.eql?(other_meth) -> true or false
2753 * meth == other_meth -> true or false
2754 *
2755 * Two unbound method objects are equal if they refer to the same
2756 * method definition.
2757 *
2758 * Array.instance_method(:each_slice) == Enumerable.instance_method(:each_slice)
2759 * #=> true
2760 *
2761 * Array.instance_method(:sum) == Enumerable.instance_method(:sum)
2762 * #=> false, Array redefines the method for efficiency
2763 */
2764#define unbound_method_eq method_eq
2765
2766/*
2767 * call-seq:
2768 * meth.hash -> integer
2769 *
2770 * Returns a hash value corresponding to the method object.
2771 *
2772 * See also Object#hash.
2773 */
2774
2775static VALUE
2776method_hash(VALUE method)
2777{
2778 struct METHOD *m;
2779 st_index_t hash;
2780
2781 TypedData_Get_Struct(method, struct METHOD, &method_data_type, m);
2782 hash = rb_hash_start((st_index_t)m->recv);
2783 hash = rb_hash_method_entry(hash, m->me);
2784 hash = rb_hash_end(hash);
2785
2786 return ST2FIX(hash);
2787}
2788
2789/*
2790 * call-seq:
2791 * meth.unbind -> unbound_method
2792 *
2793 * Dissociates <i>meth</i> from its current receiver. The resulting
2794 * UnboundMethod can subsequently be bound to a new object of the
2795 * same class (see UnboundMethod).
2796 */
2797
2798static VALUE
2799method_unbind(VALUE obj)
2800{
2801 VALUE method;
2802 struct METHOD *orig, *data;
2803
2804 TypedData_Get_Struct(obj, struct METHOD, &method_data_type, orig);
2806 &method_data_type, data);
2807 RB_OBJ_WRITE(method, &data->recv, Qundef);
2808 RB_OBJ_WRITE(method, &data->klass, Qundef);
2809 RB_OBJ_WRITE(method, &data->iclass, orig->iclass);
2810 RB_OBJ_WRITE(method, &data->owner, orig->me->owner);
2811 RB_OBJ_WRITE(method, &data->me, rb_method_entry_clone(orig->me));
2812
2813 return method;
2814}
2815
2816/*
2817 * call-seq:
2818 * meth.receiver -> object
2819 *
2820 * Returns the bound receiver of the method object.
2821 *
2822 * (1..3).method(:map).receiver # => 1..3
2823 */
2824
2825static VALUE
2826method_receiver(VALUE obj)
2827{
2828 struct METHOD *data;
2829
2830 TypedData_Get_Struct(obj, struct METHOD, &method_data_type, data);
2831 return data->recv;
2832}
2833
2834/*
2835 * call-seq:
2836 * meth.name -> symbol
2837 *
2838 * Returns the name of the method.
2839 */
2840
2841static VALUE
2842method_name(VALUE obj)
2843{
2844 struct METHOD *data;
2845
2846 TypedData_Get_Struct(obj, struct METHOD, &method_data_type, data);
2847 return ID2SYM(data->me->called_id);
2848}
2849
2850/*
2851 * call-seq:
2852 * meth.original_name -> symbol
2853 *
2854 * Returns the original name of the method.
2855 *
2856 * class C
2857 * def foo; end
2858 * alias bar foo
2859 * end
2860 * C.instance_method(:bar).original_name # => :foo
2861 */
2862
2863static VALUE
2864method_original_name(VALUE obj)
2865{
2866 struct METHOD *data;
2867
2868 TypedData_Get_Struct(obj, struct METHOD, &method_data_type, data);
2869 return ID2SYM(data->me->def->original_id);
2870}
2871
2872/*
2873 * call-seq:
2874 * meth.owner -> class_or_module
2875 *
2876 * Returns the class or module on which this method is defined.
2877 * In other words,
2878 *
2879 * meth.owner.instance_methods(false).include?(meth.name) # => true
2880 *
2881 * holds as long as the method is not removed/undefined/replaced,
2882 * (with private_instance_methods instead of instance_methods if the method
2883 * is private).
2884 *
2885 * See also Method#receiver.
2886 *
2887 * (1..3).method(:map).owner #=> Enumerable
2888 */
2889
2890static VALUE
2891method_owner(VALUE obj)
2892{
2893 struct METHOD *data;
2894 TypedData_Get_Struct(obj, struct METHOD, &method_data_type, data);
2895 return data->owner;
2896}
2897
2898/*
2899 * call-seq:
2900 * meth.box -> box or nil
2901 *
2902 * Returns the Ruby::Box where +meth+ is defined in.
2903 */
2904static VALUE
2905method_box(VALUE obj)
2906{
2907 struct METHOD *data;
2908 const rb_box_t *box;
2909
2910 TypedData_Get_Struct(obj, struct METHOD, &method_data_type, data);
2911 box = data->me->def->box;
2912 if (!box) return Qnil;
2913 if (box->box_object) return box->box_object;
2914 rb_bug("Unexpected box on the method definition: %p", (void*) box);
2916}
2917
2918void
2919rb_method_name_error(VALUE klass, VALUE str)
2920{
2921#define MSG(s) rb_fstring_lit("undefined method '%1$s' for"s" '%2$s'")
2922 VALUE c = klass;
2923 VALUE s = Qundef;
2924
2925 if (RCLASS_SINGLETON_P(c)) {
2926 VALUE obj = RCLASS_ATTACHED_OBJECT(klass);
2927
2928 switch (BUILTIN_TYPE(obj)) {
2929 case T_MODULE:
2930 case T_CLASS:
2931 c = obj;
2932 break;
2933 default:
2934 break;
2935 }
2936 }
2937 else if (RB_TYPE_P(c, T_MODULE)) {
2938 s = MSG(" module");
2939 }
2940 if (UNDEF_P(s)) {
2941 s = MSG(" class");
2942 }
2943 rb_name_err_raise_str(s, c, str);
2944#undef MSG
2945}
2946
2947static VALUE
2948obj_method(VALUE obj, VALUE vid, int scope)
2949{
2950 ID id = rb_check_id(&vid);
2951 const VALUE klass = CLASS_OF(obj);
2952 const VALUE mclass = rb_cMethod;
2953
2954 if (!id) {
2955 VALUE m = mnew_missing_by_name(klass, obj, &vid, scope, mclass);
2956 if (m) return m;
2957 rb_method_name_error(klass, vid);
2958 }
2959 return mnew_callable(klass, obj, id, mclass, scope);
2960}
2961
2962/*
2963 * call-seq:
2964 * obj.method(sym) -> method
2965 *
2966 * Looks up the named method as a receiver in <i>obj</i>, returning a
2967 * +Method+ object (or raising NameError). The +Method+ object acts as a
2968 * closure in <i>obj</i>'s object instance, so instance variables and
2969 * the value of <code>self</code> remain available.
2970 *
2971 * class Demo
2972 * def initialize(n)
2973 * @iv = n
2974 * end
2975 * def hello()
2976 * "Hello, @iv = #{@iv}"
2977 * end
2978 * end
2979 *
2980 * k = Demo.new(99)
2981 * m = k.method(:hello)
2982 * m.call #=> "Hello, @iv = 99"
2983 *
2984 * l = Demo.new('Fred')
2985 * m = l.method("hello")
2986 * m.call #=> "Hello, @iv = Fred"
2987 *
2988 * Note that +Method+ implements <code>to_proc</code> method, which
2989 * means it can be used with iterators.
2990 *
2991 * [ 1, 2, 3 ].each(&method(:puts)) # => prints 3 lines to stdout
2992 *
2993 * out = File.open('test.txt', 'w')
2994 * [ 1, 2, 3 ].each(&out.method(:puts)) # => prints 3 lines to file
2995 *
2996 * require 'date'
2997 * %w[2017-03-01 2017-03-02].collect(&Date.method(:parse))
2998 * #=> [#<Date: 2017-03-01 ((2457814j,0s,0n),+0s,2299161j)>, #<Date: 2017-03-02 ((2457815j,0s,0n),+0s,2299161j)>]
2999 */
3000
3001VALUE
3003{
3004 return obj_method(obj, vid, FALSE);
3005}
3006
3007/*
3008 * call-seq:
3009 * obj.public_method(sym) -> method
3010 *
3011 * Similar to _method_, searches public method only.
3012 */
3013
3014VALUE
3015rb_obj_public_method(VALUE obj, VALUE vid)
3016{
3017 return obj_method(obj, vid, TRUE);
3018}
3019
3020static VALUE
3021rb_obj_singleton_method_lookup(VALUE arg)
3022{
3023 VALUE *args = (VALUE *)arg;
3024 return rb_obj_method(args[0], args[1]);
3025}
3026
3027static VALUE
3028rb_obj_singleton_method_lookup_fail(VALUE arg1, VALUE arg2)
3029{
3030 return Qfalse;
3031}
3032
3033/*
3034 * call-seq:
3035 * obj.singleton_method(sym) -> method
3036 *
3037 * Similar to _method_, searches singleton method only.
3038 *
3039 * class Demo
3040 * def initialize(n)
3041 * @iv = n
3042 * end
3043 * def hello()
3044 * "Hello, @iv = #{@iv}"
3045 * end
3046 * end
3047 *
3048 * k = Demo.new(99)
3049 * def k.hi
3050 * "Hi, @iv = #{@iv}"
3051 * end
3052 * m = k.singleton_method(:hi)
3053 * m.call #=> "Hi, @iv = 99"
3054 * m = k.singleton_method(:hello) #=> NameError
3055 */
3056
3057VALUE
3058rb_obj_singleton_method(VALUE obj, VALUE vid)
3059{
3060 VALUE sc = rb_singleton_class_get(obj);
3061 VALUE klass;
3062 ID id = rb_check_id(&vid);
3063
3064 if (NIL_P(sc) ||
3065 NIL_P(klass = RCLASS_ORIGIN(sc)) ||
3066 !NIL_P(rb_special_singleton_class(obj))) {
3067 /* goto undef; */
3068 }
3069 else if (! id) {
3070 VALUE m = mnew_missing_by_name(klass, obj, &vid, FALSE, rb_cMethod);
3071 if (m) return m;
3072 /* else goto undef; */
3073 }
3074 else {
3075 VALUE args[2] = {obj, vid};
3076 VALUE ruby_method = rb_rescue(rb_obj_singleton_method_lookup, (VALUE)args, rb_obj_singleton_method_lookup_fail, Qfalse);
3077 if (ruby_method) {
3078 struct METHOD *method = (struct METHOD *)RTYPEDDATA_GET_DATA(ruby_method);
3079 VALUE lookup_class = RBASIC_CLASS(obj);
3080 VALUE stop_class = rb_class_superclass(sc);
3081 VALUE method_class = method->iclass;
3082
3083 /* Determine if method is in singleton class, or module included in or prepended to it */
3084 do {
3085 if (lookup_class == method_class) {
3086 return ruby_method;
3087 }
3088 lookup_class = RCLASS_SUPER(lookup_class);
3089 } while (lookup_class && lookup_class != stop_class);
3090 }
3091 }
3092
3093 /* undef: */
3094 if (id) vid = ID2SYM(id);
3095 rb_name_err_raise("undefined singleton method '%1$s' for '%2$s'",
3096 obj, vid);
3098}
3099
3100/*
3101 * call-seq:
3102 * mod.instance_method(symbol) -> unbound_method
3103 *
3104 * Returns an +UnboundMethod+ representing the given
3105 * instance method in _mod_.
3106 * See +UnboundMethod+ about how to utilize it
3107 *
3108 * class Person
3109 * def initialize(name)
3110 * @name = name
3111 * end
3112 *
3113 * def hi
3114 * puts "Hi, I'm #{@name}!"
3115 * end
3116 * end
3117 *
3118 * dave = Person.new('Dave')
3119 * thomas = Person.new('Thomas')
3120 *
3121 * hi = Person.instance_method(:hi)
3122 * hi.bind_call(dave)
3123 * hi.bind_call(thomas)
3124 *
3125 * <em>produces:</em>
3126 *
3127 * Hi, I'm Dave!
3128 * Hi, I'm Thomas!
3129 */
3130
3131static VALUE
3132rb_mod_instance_method(VALUE mod, VALUE vid)
3133{
3134 ID id = rb_check_id(&vid);
3135 if (!id) {
3136 rb_method_name_error(mod, vid);
3137 }
3138 return mnew_unbound(mod, id, rb_cUnboundMethod, FALSE);
3139}
3140
3141/*
3142 * call-seq:
3143 * mod.public_instance_method(symbol) -> unbound_method
3144 *
3145 * Similar to _instance_method_, searches public method only.
3146 */
3147
3148static VALUE
3149rb_mod_public_instance_method(VALUE mod, VALUE vid)
3150{
3151 ID id = rb_check_id(&vid);
3152 if (!id) {
3153 rb_method_name_error(mod, vid);
3154 }
3155 return mnew_unbound(mod, id, rb_cUnboundMethod, TRUE);
3156}
3157
3158static VALUE
3159rb_mod_define_method_with_visibility(int argc, VALUE *argv, VALUE mod, const struct rb_scope_visi_struct* scope_visi)
3160{
3161 ID id;
3162 VALUE body;
3163 VALUE name;
3164 int is_method = FALSE;
3165
3166 rb_check_arity(argc, 1, 2);
3167 name = argv[0];
3168 id = rb_check_id(&name);
3169 if (argc == 1) {
3170 body = rb_block_lambda();
3171 }
3172 else {
3173 body = argv[1];
3174
3175 if (rb_obj_is_method(body)) {
3176 is_method = TRUE;
3177 }
3178 else if (rb_obj_is_proc(body)) {
3179 is_method = FALSE;
3180 }
3181 else {
3182 rb_raise(rb_eTypeError,
3183 "wrong argument type %s (expected Proc/Method/UnboundMethod)",
3184 rb_obj_classname(body));
3185 }
3186 }
3187 if (!id) id = rb_to_id(name);
3188
3189 if (is_method) {
3190 struct METHOD *method = (struct METHOD *)RTYPEDDATA_GET_DATA(body);
3191 if (method->me->owner != mod && !RB_TYPE_P(method->me->owner, T_MODULE) &&
3192 !RTEST(rb_class_inherited_p(mod, method->me->owner))) {
3193 if (RCLASS_SINGLETON_P(method->me->owner)) {
3194 rb_raise(rb_eTypeError,
3195 "can't bind singleton method to a different class");
3196 }
3197 else {
3198 rb_raise(rb_eTypeError,
3199 "bind argument must be a subclass of % "PRIsVALUE,
3200 method->me->owner);
3201 }
3202 }
3203 rb_method_entry_set(mod, id, method->me, scope_visi->method_visi);
3204 if (scope_visi->module_func) {
3205 rb_method_entry_set(rb_singleton_class(mod), id, method->me, METHOD_VISI_PUBLIC);
3206 }
3207 RB_GC_GUARD(body);
3208 }
3209 else {
3210 rb_proc_t *body_proc;
3211 GetProcPtr(body, body_proc);
3212 /* A bmethod never reads the refinement cref carried on the proc;
3213 * reject rather than silently drop the refinements. */
3214 if (body_proc->header.is_refined) {
3215 rb_raise(rb_eArgError,
3216 "can't define a method from a Proc with refinements");
3217 }
3218 VALUE procval = rb_proc_dup(body);
3219 if (vm_proc_iseq(procval) != NULL) {
3220 rb_proc_t *proc;
3221 GetProcPtr(procval, proc);
3222 proc->header.is_lambda = TRUE;
3223 proc->header.is_from_method = TRUE;
3224 }
3225 rb_add_method(mod, id, VM_METHOD_TYPE_BMETHOD, (void *)procval, scope_visi->method_visi);
3226 if (scope_visi->module_func) {
3227 rb_add_method(rb_singleton_class(mod), id, VM_METHOD_TYPE_BMETHOD, (void *)body, METHOD_VISI_PUBLIC);
3228 }
3229 }
3230
3231 return ID2SYM(id);
3232}
3233
3234/*
3235 * call-seq:
3236 * define_method(symbol, method) -> symbol
3237 * define_method(symbol) { block } -> symbol
3238 *
3239 * Defines an instance method in the receiver. The _method_
3240 * parameter can be a +Proc+, a +Method+ or an +UnboundMethod+ object.
3241 * If a block is specified, it is used as the method body.
3242 * If a block or the _method_ parameter has parameters,
3243 * they're used as method parameters.
3244 * This block is evaluated using #instance_eval.
3245 *
3246 * class A
3247 * def fred
3248 * puts "In Fred"
3249 * end
3250 * def create_method(name, &block)
3251 * self.class.define_method(name, &block)
3252 * end
3253 * define_method(:wilma) { puts "Charge it!" }
3254 * define_method(:flint) {|name| puts "I'm #{name}!"}
3255 * end
3256 * class B < A
3257 * define_method(:barney, instance_method(:fred))
3258 * end
3259 * a = B.new
3260 * a.barney
3261 * a.wilma
3262 * a.flint('Dino')
3263 * a.create_method(:betty) { p self }
3264 * a.betty
3265 *
3266 * <em>produces:</em>
3267 *
3268 * In Fred
3269 * Charge it!
3270 * I'm Dino!
3271 * #<B:0x401b39e8>
3272 */
3273
3274static VALUE
3275rb_mod_define_method(int argc, VALUE *argv, VALUE mod)
3276{
3277 const rb_cref_t *cref = rb_vm_cref_in_context(mod, mod);
3278 const rb_scope_visibility_t default_scope_visi = {METHOD_VISI_PUBLIC, FALSE};
3279 const rb_scope_visibility_t *scope_visi = &default_scope_visi;
3280
3281 if (cref) {
3282 scope_visi = CREF_SCOPE_VISI(cref);
3283 }
3284
3285 return rb_mod_define_method_with_visibility(argc, argv, mod, scope_visi);
3286}
3287
3288/*
3289 * call-seq:
3290 * define_singleton_method(symbol, method) -> symbol
3291 * define_singleton_method(symbol) { block } -> symbol
3292 *
3293 * Defines a public singleton method in the receiver. The _method_
3294 * parameter can be a +Proc+, a +Method+ or an +UnboundMethod+ object.
3295 * If a block is specified, it is used as the method body.
3296 * If a block or a method has parameters, they're used as method parameters.
3297 *
3298 * class A
3299 * class << self
3300 * def class_name
3301 * to_s
3302 * end
3303 * end
3304 * end
3305 * A.define_singleton_method(:who_am_i) do
3306 * "I am: #{class_name}"
3307 * end
3308 * A.who_am_i # ==> "I am: A"
3309 *
3310 * guy = "Bob"
3311 * guy.define_singleton_method(:hello) { "#{self}: Hello there!" }
3312 * guy.hello #=> "Bob: Hello there!"
3313 *
3314 * chris = "Chris"
3315 * chris.define_singleton_method(:greet) {|greeting| "#{greeting}, I'm Chris!" }
3316 * chris.greet("Hi") #=> "Hi, I'm Chris!"
3317 */
3318
3319static VALUE
3320rb_obj_define_method(int argc, VALUE *argv, VALUE obj)
3321{
3322 VALUE klass = rb_singleton_class(obj);
3323 const rb_scope_visibility_t scope_visi = {METHOD_VISI_PUBLIC, FALSE};
3324
3325 return rb_mod_define_method_with_visibility(argc, argv, klass, &scope_visi);
3326}
3327
3328/*
3329 * define_method(symbol, method) -> symbol
3330 * define_method(symbol) { block } -> symbol
3331 *
3332 * Defines a global function by _method_ or the block.
3333 */
3334
3335static VALUE
3336top_define_method(int argc, VALUE *argv, VALUE obj)
3337{
3338 return rb_mod_define_method(argc, argv, rb_top_main_class("define_method"));
3339}
3340
3341/*
3342 * call-seq:
3343 * method.clone -> new_method
3344 *
3345 * Returns a clone of this method.
3346 *
3347 * class A
3348 * def foo
3349 * return "bar"
3350 * end
3351 * end
3352 *
3353 * m = A.new.method(:foo)
3354 * m.call # => "bar"
3355 * n = m.clone.call # => "bar"
3356 */
3357
3358static VALUE
3359method_clone(VALUE self)
3360{
3361 VALUE clone;
3362 struct METHOD *orig, *data;
3363
3364 TypedData_Get_Struct(self, struct METHOD, &method_data_type, orig);
3365 clone = TypedData_Make_Struct(rb_obj_class(self), struct METHOD, &method_data_type, data);
3366 rb_obj_clone_setup(self, clone, Qnil);
3367 RB_OBJ_WRITE(clone, &data->recv, orig->recv);
3368 RB_OBJ_WRITE(clone, &data->klass, orig->klass);
3369 RB_OBJ_WRITE(clone, &data->iclass, orig->iclass);
3370 RB_OBJ_WRITE(clone, &data->owner, orig->owner);
3371 RB_OBJ_WRITE(clone, &data->me, rb_method_entry_clone(orig->me));
3372 return clone;
3373}
3374
3375/* :nodoc: */
3376static VALUE
3377method_dup(VALUE self)
3378{
3379 VALUE clone;
3380 struct METHOD *orig, *data;
3381
3382 TypedData_Get_Struct(self, struct METHOD, &method_data_type, orig);
3383 clone = TypedData_Make_Struct(rb_obj_class(self), struct METHOD, &method_data_type, data);
3384 rb_obj_dup_setup(self, clone);
3385 RB_OBJ_WRITE(clone, &data->recv, orig->recv);
3386 RB_OBJ_WRITE(clone, &data->klass, orig->klass);
3387 RB_OBJ_WRITE(clone, &data->iclass, orig->iclass);
3388 RB_OBJ_WRITE(clone, &data->owner, orig->owner);
3389 RB_OBJ_WRITE(clone, &data->me, rb_method_entry_clone(orig->me));
3390 return clone;
3391}
3392
3393/*
3394 * call-seq:
3395 * call(...) -> obj
3396 * self[...] -> obj
3397 * self === obj -> result_of_method
3398 *
3399 * Invokes +self+ with the specified arguments, returning the
3400 * method's return value.
3401 *
3402 * m = 12.method("+")
3403 * m.call(3) #=> 15
3404 * m.call(20) #=> 32
3405 *
3406 * Using Method#=== allows a method object to be the target of a +when+ clause
3407 * in a case statement.
3408 *
3409 * require 'prime'
3410 *
3411 * case 1373
3412 * when Prime.method(:prime?)
3413 * # ...
3414 * end
3415 */
3416
3417static VALUE
3418rb_method_call_pass_called_kw(int argc, const VALUE *argv, VALUE method)
3419{
3420 return rb_method_call_kw(argc, argv, method, RB_PASS_CALLED_KEYWORDS);
3421}
3422
3423VALUE
3424rb_method_call_kw(int argc, const VALUE *argv, VALUE method, int kw_splat)
3425{
3426 VALUE procval = rb_block_given_p() ? rb_block_proc() : Qnil;
3427 return rb_method_call_with_block_kw(argc, argv, method, procval, kw_splat);
3428}
3429
3430VALUE
3431rb_method_call(int argc, const VALUE *argv, VALUE method)
3432{
3433 VALUE procval = rb_block_given_p() ? rb_block_proc() : Qnil;
3434 return rb_method_call_with_block(argc, argv, method, procval);
3435}
3436
3437static const rb_callable_method_entry_t *
3438method_callable_method_entry(const struct METHOD *data)
3439{
3440 if (data->me->defined_class == 0) rb_bug("method_callable_method_entry: not callable.");
3441 return (const rb_callable_method_entry_t *)data->me;
3442}
3443
3444static inline VALUE
3445call_method_data(rb_execution_context_t *ec, const struct METHOD *data,
3446 int argc, const VALUE *argv, VALUE passed_procval, int kw_splat)
3447{
3448 vm_passed_block_handler_set(ec, proc_to_block_handler(passed_procval));
3449 return rb_vm_call_kw(ec, data->recv, data->me->called_id, argc, argv,
3450 method_callable_method_entry(data), kw_splat);
3451}
3452
3453VALUE
3454rb_method_call_with_block_kw(int argc, const VALUE *argv, VALUE method, VALUE passed_procval, int kw_splat)
3455{
3456 const struct METHOD *data;
3457 rb_execution_context_t *ec = GET_EC();
3458
3459 TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
3460 if (UNDEF_P(data->recv)) {
3461 rb_raise(rb_eTypeError, "can't call unbound method; bind first");
3462 }
3463 return call_method_data(ec, data, argc, argv, passed_procval, kw_splat);
3464}
3465
3466VALUE
3467rb_method_call_with_block(int argc, const VALUE *argv, VALUE method, VALUE passed_procval)
3468{
3469 return rb_method_call_with_block_kw(argc, argv, method, passed_procval, RB_NO_KEYWORDS);
3470}
3471
3472/**********************************************************************
3473 *
3474 * Document-class: UnboundMethod
3475 *
3476 * Ruby supports two forms of objectified methods. Class +Method+ is
3477 * used to represent methods that are associated with a particular
3478 * object: these method objects are bound to that object. Bound
3479 * method objects for an object can be created using Object#method.
3480 *
3481 * Ruby also supports unbound methods; methods objects that are not
3482 * associated with a particular object. These can be created either
3483 * by calling Module#instance_method or by calling #unbind on a bound
3484 * method object. The result of both of these is an UnboundMethod
3485 * object.
3486 *
3487 * Unbound methods can only be called after they are bound to an
3488 * object. That object must be a kind_of? the method's original
3489 * class.
3490 *
3491 * class Square
3492 * def area
3493 * @side * @side
3494 * end
3495 * def initialize(side)
3496 * @side = side
3497 * end
3498 * end
3499 *
3500 * area_un = Square.instance_method(:area)
3501 *
3502 * s = Square.new(12)
3503 * area = area_un.bind(s)
3504 * area.call #=> 144
3505 *
3506 * Unbound methods are a reference to the method at the time it was
3507 * objectified: subsequent changes to the underlying class will not
3508 * affect the unbound method.
3509 *
3510 * class Test
3511 * def test
3512 * :original
3513 * end
3514 * end
3515 * um = Test.instance_method(:test)
3516 * class Test
3517 * def test
3518 * :modified
3519 * end
3520 * end
3521 * t = Test.new
3522 * t.test #=> :modified
3523 * um.bind(t).call #=> :original
3524 *
3525 */
3526
3527static void
3528convert_umethod_to_method_components(const struct METHOD *data, VALUE recv, VALUE *methclass_out, VALUE *klass_out, VALUE *iclass_out, const rb_method_entry_t **me_out, const bool clone)
3529{
3530 VALUE methclass = data->owner;
3531 VALUE iclass = data->iclass;
3532 VALUE klass = CLASS_OF(recv);
3533
3534 if (RB_TYPE_P(methclass, T_MODULE)) {
3535 VALUE refined_class = rb_refinement_module_get_refined_class(methclass);
3536 if (!NIL_P(refined_class)) methclass = refined_class;
3537 }
3538 if (!RB_TYPE_P(methclass, T_MODULE) && !RTEST(rb_obj_is_kind_of(recv, methclass))) {
3539 if (RCLASS_SINGLETON_P(methclass)) {
3540 rb_raise(rb_eTypeError,
3541 "singleton method called for a different object");
3542 }
3543 else {
3544 rb_raise(rb_eTypeError, "bind argument must be an instance of % "PRIsVALUE,
3545 methclass);
3546 }
3547 }
3548
3549 const rb_method_entry_t *me;
3550 if (clone) {
3551 me = rb_method_entry_clone(data->me);
3552 }
3553 else {
3554 me = data->me;
3555 }
3556
3557 if (RB_TYPE_P(me->owner, T_MODULE)) {
3558 if (!clone) {
3559 // if we didn't previously clone the method entry, then we need to clone it now
3560 // because this branch manipulates it in rb_method_entry_complement_defined_class
3561 me = rb_method_entry_clone(me);
3562 }
3563 if (refinement_module_p(me->owner) && RICLASS_FOR_REFINEMENT_P(iclass)) {
3564 iclass = find_refinement_iclass(me->owner, klass, iclass);
3565 klass = iclass;
3566 }
3567 else {
3568 VALUE ic = RB_TYPE_P(iclass, T_ICLASS) ? find_ancestor(klass, iclass) : 0;
3569 if (!ic) ic = rb_class_search_ancestor(klass, me->owner);
3570 if (ic) {
3571 klass = ic;
3572 iclass = ic;
3573 }
3574 else {
3575 klass = rb_include_class_new(methclass, klass);
3576 iclass = klass;
3577 }
3578 }
3579 me = (const rb_method_entry_t *) rb_method_entry_complement_defined_class(me, me->called_id, klass);
3580 }
3581
3582 *methclass_out = methclass;
3583 *klass_out = klass;
3584 *iclass_out = iclass;
3585 *me_out = me;
3586}
3587
3588/*
3589 * call-seq:
3590 * umeth.bind(obj) -> method
3591 *
3592 * Bind <i>umeth</i> to <i>obj</i>. If Klass was the class from which
3593 * <i>umeth</i> was obtained, <code>obj.kind_of?(Klass)</code> must
3594 * be true.
3595 *
3596 * class A
3597 * def test
3598 * puts "In test, class = #{self.class}"
3599 * end
3600 * end
3601 * class B < A
3602 * end
3603 * class C < B
3604 * end
3605 *
3606 *
3607 * um = B.instance_method(:test)
3608 * bm = um.bind(C.new)
3609 * bm.call
3610 * bm = um.bind(B.new)
3611 * bm.call
3612 * bm = um.bind(A.new)
3613 * bm.call
3614 *
3615 * <em>produces:</em>
3616 *
3617 * In test, class = C
3618 * In test, class = B
3619 * prog.rb:16:in `bind': bind argument must be an instance of B (TypeError)
3620 * from prog.rb:16
3621 */
3622
3623static VALUE
3624umethod_bind(VALUE method, VALUE recv)
3625{
3626 VALUE methclass, klass, iclass;
3627 const rb_method_entry_t *me;
3628 const struct METHOD *data;
3629 TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
3630 convert_umethod_to_method_components(data, recv, &methclass, &klass, &iclass, &me, true);
3631
3632 struct METHOD *bound;
3633 method = TypedData_Make_Struct(rb_cMethod, struct METHOD, &method_data_type, bound);
3634 RB_OBJ_WRITE(method, &bound->recv, recv);
3635 RB_OBJ_WRITE(method, &bound->klass, klass);
3636 RB_OBJ_WRITE(method, &bound->iclass, iclass);
3637 RB_OBJ_WRITE(method, &bound->owner, methclass);
3638 RB_OBJ_WRITE(method, &bound->me, me);
3639
3640 return method;
3641}
3642
3643/*
3644 * call-seq:
3645 * umeth.bind_call(recv, args, ...) -> obj
3646 *
3647 * Bind <i>umeth</i> to <i>recv</i> and then invokes the method with the
3648 * specified arguments.
3649 * This is semantically equivalent to <code>umeth.bind(recv).call(args, ...)</code>.
3650 */
3651static VALUE
3652umethod_bind_call(int argc, VALUE *argv, VALUE method)
3653{
3655 VALUE recv = argv[0];
3656 argc--;
3657 argv++;
3658
3659 VALUE passed_procval = rb_block_given_p() ? rb_block_proc() : Qnil;
3660 rb_execution_context_t *ec = GET_EC();
3661
3662 const struct METHOD *data;
3663 TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
3664
3665 const rb_callable_method_entry_t *cme = rb_callable_method_entry(CLASS_OF(recv), data->me->called_id);
3666 if (data->me == (const rb_method_entry_t *)cme) {
3667 vm_passed_block_handler_set(ec, proc_to_block_handler(passed_procval));
3668 return rb_vm_call_kw(ec, recv, cme->called_id, argc, argv, cme, RB_PASS_CALLED_KEYWORDS);
3669 }
3670 else {
3671 VALUE methclass, klass, iclass;
3672 const rb_method_entry_t *me;
3673 convert_umethod_to_method_components(data, recv, &methclass, &klass, &iclass, &me, false);
3674 struct METHOD bound = { recv, klass, 0, methclass, me };
3675
3676 return call_method_data(ec, &bound, argc, argv, passed_procval, RB_PASS_CALLED_KEYWORDS);
3677 }
3678}
3679
3680/*
3681 * Returns the number of required parameters and stores the maximum
3682 * number of parameters in max, or UNLIMITED_ARGUMENTS
3683 * if there is no maximum.
3684 */
3685static int
3686method_def_min_max_arity(const rb_method_definition_t *def, int *max)
3687{
3688 again:
3689 if (!def) return *max = 0;
3690 switch (def->type) {
3691 case VM_METHOD_TYPE_CFUNC:
3692 if (def->body.cfunc.argc < 0) {
3693 *max = UNLIMITED_ARGUMENTS;
3694 return 0;
3695 }
3696 return *max = check_argc(def->body.cfunc.argc);
3697 case VM_METHOD_TYPE_ZSUPER:
3698 *max = UNLIMITED_ARGUMENTS;
3699 return 0;
3700 case VM_METHOD_TYPE_ATTRSET:
3701 return *max = 1;
3702 case VM_METHOD_TYPE_IVAR:
3703 return *max = 0;
3704 case VM_METHOD_TYPE_ALIAS:
3705 def = rb_method_entry_def_acquire(rb_method_alias_original_me(def));
3706 goto again;
3707 case VM_METHOD_TYPE_BMETHOD:
3708 return rb_proc_min_max_arity(def->body.bmethod.proc, max);
3709 case VM_METHOD_TYPE_ISEQ:
3710 return rb_iseq_min_max_arity(rb_iseq_check(def->body.iseq.iseqptr), max);
3711 case VM_METHOD_TYPE_UNDEF:
3712 case VM_METHOD_TYPE_NOTIMPLEMENTED:
3713 return *max = 0;
3714 case VM_METHOD_TYPE_MISSING:
3715 *max = UNLIMITED_ARGUMENTS;
3716 return 0;
3717 case VM_METHOD_TYPE_OPTIMIZED: {
3718 switch (def->body.optimized.type) {
3719 case OPTIMIZED_METHOD_TYPE_SEND:
3720 *max = UNLIMITED_ARGUMENTS;
3721 return 0;
3722 case OPTIMIZED_METHOD_TYPE_CALL:
3723 *max = UNLIMITED_ARGUMENTS;
3724 return 0;
3725 case OPTIMIZED_METHOD_TYPE_BLOCK_CALL:
3726 *max = UNLIMITED_ARGUMENTS;
3727 return 0;
3728 case OPTIMIZED_METHOD_TYPE_STRUCT_AREF:
3729 *max = 0;
3730 return 0;
3731 case OPTIMIZED_METHOD_TYPE_STRUCT_ASET:
3732 *max = 1;
3733 return 1;
3734 default:
3735 break;
3736 }
3737 break;
3738 }
3739 case VM_METHOD_TYPE_REFINED:
3740 *max = UNLIMITED_ARGUMENTS;
3741 return 0;
3742 }
3743 rb_bug("method_def_min_max_arity: invalid method entry type (%d)", def->type);
3745}
3746
3747static int
3748method_def_arity(const rb_method_definition_t *def)
3749{
3750 int max, min = method_def_min_max_arity(def, &max);
3751 return min == max ? min : -min-1;
3752}
3753
3754int
3755rb_method_entry_arity(const rb_method_entry_t *me)
3756{
3757 return method_def_arity(rb_method_entry_def_acquire(me));
3758}
3759
3760/*
3761 * call-seq:
3762 * meth.arity -> integer
3763 *
3764 * Returns an indication of the number of arguments accepted by a
3765 * method. Returns a nonnegative integer for methods that take a fixed
3766 * number of arguments. For Ruby methods that take a variable number of
3767 * arguments, returns -n-1, where n is the number of required arguments.
3768 * Keyword arguments will be considered as a single additional argument,
3769 * that argument being mandatory if any keyword argument is mandatory.
3770 * For methods written in C, returns -1 if the call takes a
3771 * variable number of arguments.
3772 *
3773 * class C
3774 * def one; end
3775 * def two(a); end
3776 * def three(*a); end
3777 * def four(a, b); end
3778 * def five(a, b, *c); end
3779 * def six(a, b, *c, &d); end
3780 * def seven(a, b, x:0); end
3781 * def eight(x:, y:); end
3782 * def nine(x:, y:, **z); end
3783 * def ten(*a, x:, y:); end
3784 * end
3785 * c = C.new
3786 * c.method(:one).arity #=> 0
3787 * c.method(:two).arity #=> 1
3788 * c.method(:three).arity #=> -1
3789 * c.method(:four).arity #=> 2
3790 * c.method(:five).arity #=> -3
3791 * c.method(:six).arity #=> -3
3792 * c.method(:seven).arity #=> -3
3793 * c.method(:eight).arity #=> 1
3794 * c.method(:nine).arity #=> 1
3795 * c.method(:ten).arity #=> -2
3796 *
3797 * "cat".method(:size).arity #=> 0
3798 * "cat".method(:replace).arity #=> 1
3799 * "cat".method(:squeeze).arity #=> -1
3800 * "cat".method(:count).arity #=> -1
3801 */
3802
3803static VALUE
3804method_arity_m(VALUE method)
3805{
3806 int n = method_arity(method);
3807 return INT2FIX(n);
3808}
3809
3810static int
3811method_arity(VALUE method)
3812{
3813 struct METHOD *data;
3814
3815 TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
3816 return rb_method_entry_arity(data->me);
3817}
3818
3819static const rb_method_entry_t *
3820original_method_entry(VALUE mod, ID id)
3821{
3822 const rb_method_entry_t *me;
3823
3824 while ((me = rb_method_entry(mod, id)) != 0) {
3825 const rb_method_definition_t *def = me->def;
3826
3827 if (def->type != VM_METHOD_TYPE_ZSUPER &&
3828 (def->type != VM_METHOD_TYPE_CFUNC ||
3829 def->body.cfunc.func != (rb_cfunc_t)rb_zsuper_to_super)) break;
3830
3831 mod = RCLASS_SUPER(me->owner);
3832 id = def->original_id;
3833 }
3834 return me;
3835}
3836
3837static int
3838method_min_max_arity(VALUE method, int *max)
3839{
3840 const struct METHOD *data;
3841
3842 TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
3843 return method_def_min_max_arity(rb_method_entry_def_acquire(data->me), max);
3844}
3845
3846int
3848{
3849 const rb_method_entry_t *me = original_method_entry(mod, id);
3850 if (!me) return 0; /* should raise? */
3851 return rb_method_entry_arity(me);
3852}
3853
3854int
3856{
3857 return rb_mod_method_arity(CLASS_OF(obj), id);
3858}
3859
3860VALUE
3861rb_callable_receiver(VALUE callable)
3862{
3863 if (rb_obj_is_proc(callable)) {
3864 VALUE binding = proc_binding(callable);
3865 return rb_funcall(binding, rb_intern("receiver"), 0);
3866 }
3867 else if (rb_obj_is_method(callable)) {
3868 return method_receiver(callable);
3869 }
3870 else {
3871 return Qundef;
3872 }
3873}
3874
3875const rb_method_definition_t *
3876rb_method_def(VALUE method)
3877{
3878 const struct METHOD *data;
3879
3880 TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
3881 return rb_method_entry_def_acquire(data->me);
3882}
3883
3884static const rb_iseq_t *
3885method_def_iseq(const rb_method_definition_t *def)
3886{
3887 switch (def->type) {
3888 case VM_METHOD_TYPE_ISEQ:
3889 return rb_iseq_check(def->body.iseq.iseqptr);
3890 case VM_METHOD_TYPE_BMETHOD:
3891 return rb_proc_get_iseq(def->body.bmethod.proc, 0);
3892 case VM_METHOD_TYPE_ALIAS:
3893 return method_def_iseq(rb_method_entry_def_acquire(rb_method_alias_original_me(def)));
3894 case VM_METHOD_TYPE_CFUNC:
3895 case VM_METHOD_TYPE_ATTRSET:
3896 case VM_METHOD_TYPE_IVAR:
3897 case VM_METHOD_TYPE_ZSUPER:
3898 case VM_METHOD_TYPE_UNDEF:
3899 case VM_METHOD_TYPE_NOTIMPLEMENTED:
3900 case VM_METHOD_TYPE_OPTIMIZED:
3901 case VM_METHOD_TYPE_MISSING:
3902 case VM_METHOD_TYPE_REFINED:
3903 break;
3904 }
3905 return NULL;
3906}
3907
3908const rb_iseq_t *
3909rb_method_iseq(VALUE method)
3910{
3911 return method_def_iseq(rb_method_def(method));
3912}
3913
3914static const rb_cref_t *
3915method_cref(VALUE method)
3916{
3917 const rb_method_definition_t *def = rb_method_def(method);
3918
3919 again:
3920 switch (def->type) {
3921 case VM_METHOD_TYPE_ISEQ:
3922 return def->body.iseq.cref;
3923 case VM_METHOD_TYPE_ALIAS:
3924 def = rb_method_entry_def_acquire(rb_method_alias_original_me(def));
3925 goto again;
3926 default:
3927 return NULL;
3928 }
3929}
3930
3931static VALUE
3932method_def_location(const rb_method_definition_t *def)
3933{
3934 if (def->type == VM_METHOD_TYPE_ATTRSET || def->type == VM_METHOD_TYPE_IVAR) {
3935 if (!def->body.attr.location)
3936 return Qnil;
3937 return rb_ary_dup(def->body.attr.location);
3938 }
3939 return iseq_location(method_def_iseq(def));
3940}
3941
3942VALUE
3943rb_method_entry_location(const rb_method_entry_t *me)
3944{
3945 if (!me) return Qnil;
3946 return method_def_location(rb_method_entry_def_acquire(me));
3947}
3948
3949/*
3950 * call-seq:
3951 * source_location -> location
3952 *
3953 * Returns a two-element array containing the Ruby source filename
3954 * as a string and the line number integer where +self+ is defined:
3955 *
3956 * def greeting = "hello"
3957 * method(:greeting).source_location # => ["test.rb", 1]
3958 *
3959 * Returns nil if +self+ is not a method defined in Ruby (i.e. defined
3960 * using native code):
3961 *
3962 * Kernel.method(:puts).source_location # => nil
3963 */
3964
3965VALUE
3966rb_method_location(VALUE method)
3967{
3968 return method_def_location(rb_method_def(method));
3969}
3970
3971static VALUE
3972method_def_source_range(const rb_method_definition_t *def)
3973{
3974 return source_range_new(method_def_iseq(def));
3975}
3976
3977/*
3978 * call-seq:
3979 * meth.source_range -> Ruby::SourceRange or nil
3980 *
3981 * Returns a Ruby::SourceRange for this method, or +nil+ if this method
3982 * was not defined in Ruby (i.e. native) or has no source path.
3983 *
3984 * The returned Ruby::SourceRange includes the source path, absolute path when
3985 * available, and the start and end line and byte-column coordinates.
3986 *
3987 * See https://github.com/ruby/spec/blob/master/core/method/shared/source_range.rb
3988 * for the location of start/end line/column in various cases.
3989 */
3990static VALUE
3991rb_method_source_range(VALUE method)
3992{
3993 return method_def_source_range(rb_method_def(method));
3994}
3995
3996static const rb_method_definition_t *
3997vm_proc_method_def(VALUE procval)
3998{
3999 const rb_proc_t *proc;
4000 const struct rb_block *block;
4001 const struct vm_ifunc *ifunc;
4002
4003 GetProcPtr(procval, proc);
4004 block = &proc->block;
4005
4006 if (vm_block_type(block) == block_type_ifunc &&
4007 IS_METHOD_PROC_IFUNC(ifunc = block->as.captured.code.ifunc)) {
4008 return rb_method_def((VALUE)ifunc->data);
4009 }
4010 else {
4011 return NULL;
4012 }
4013}
4014
4015static VALUE
4016method_def_parameters(const rb_method_definition_t *def)
4017{
4018 const rb_iseq_t *iseq;
4019 const rb_method_definition_t *bmethod_def;
4020
4021 switch (def->type) {
4022 case VM_METHOD_TYPE_ISEQ:
4023 iseq = method_def_iseq(def);
4024 return rb_iseq_parameters(iseq, 0);
4025 case VM_METHOD_TYPE_BMETHOD:
4026 if ((iseq = method_def_iseq(def)) != NULL) {
4027 return rb_iseq_parameters(iseq, 0);
4028 }
4029 else if ((bmethod_def = vm_proc_method_def(def->body.bmethod.proc)) != NULL) {
4030 return method_def_parameters(bmethod_def);
4031 }
4032 break;
4033
4034 case VM_METHOD_TYPE_ALIAS:
4035 return method_def_parameters(rb_method_entry_def_acquire(rb_method_alias_original_me(def)));
4036
4037 case VM_METHOD_TYPE_OPTIMIZED:
4038 if (def->body.optimized.type == OPTIMIZED_METHOD_TYPE_STRUCT_ASET) {
4039 VALUE param = rb_ary_new_from_args(2, ID2SYM(rb_intern("req")), ID2SYM(rb_intern("_")));
4040 return rb_ary_new_from_args(1, param);
4041 }
4042 break;
4043
4044 case VM_METHOD_TYPE_CFUNC:
4045 case VM_METHOD_TYPE_ATTRSET:
4046 case VM_METHOD_TYPE_IVAR:
4047 case VM_METHOD_TYPE_ZSUPER:
4048 case VM_METHOD_TYPE_UNDEF:
4049 case VM_METHOD_TYPE_NOTIMPLEMENTED:
4050 case VM_METHOD_TYPE_MISSING:
4051 case VM_METHOD_TYPE_REFINED:
4052 break;
4053 }
4054
4055 return rb_unnamed_parameters(method_def_arity(def));
4056
4057}
4058
4059/*
4060 * call-seq:
4061 * meth.parameters -> array
4062 *
4063 * Returns the parameter information of this method.
4064 *
4065 * def foo(bar); end
4066 * method(:foo).parameters #=> [[:req, :bar]]
4067 *
4068 * def foo(bar, baz, bat, &blk); end
4069 * method(:foo).parameters #=> [[:req, :bar], [:req, :baz], [:req, :bat], [:block, :blk]]
4070 *
4071 * def foo(bar, *args); end
4072 * method(:foo).parameters #=> [[:req, :bar], [:rest, :args]]
4073 *
4074 * def foo(bar, baz, *args, &blk); end
4075 * method(:foo).parameters #=> [[:req, :bar], [:req, :baz], [:rest, :args], [:block, :blk]]
4076 */
4077
4078static VALUE
4079rb_method_parameters(VALUE method)
4080{
4081 return method_def_parameters(rb_method_def(method));
4082}
4083
4084static inline VALUE
4085append_param_name(VALUE str, VALUE name, const char *unnamed)
4086{
4087 if (!NIL_P(name)) {
4088 rb_str_append(str, rb_sym2str(name));
4089 }
4090 else if (unnamed) {
4091 rb_str_cat_cstr(str, unnamed);
4092 }
4093 return str;
4094}
4095
4096/*
4097 * call-seq:
4098 * meth.to_s -> string
4099 * meth.inspect -> string
4100 *
4101 * Returns a human-readable description of the underlying method.
4102 *
4103 * "cat".method(:count).inspect #=> "#<Method: String#count(*)>"
4104 * (1..3).method(:map).inspect #=> "#<Method: Range(Enumerable)#map()>"
4105 *
4106 * In the latter case, the method description includes the "owner" of the
4107 * original method (+Enumerable+ module, which is included into +Range+).
4108 *
4109 * +inspect+ also provides, when possible, method argument names (call
4110 * sequence) and source location.
4111 *
4112 * require 'net/http'
4113 * Net::HTTP.method(:get).inspect
4114 * #=> "#<Method: Net::HTTP.get(uri_or_host, path=..., port=...) <skip>/lib/ruby/2.7.0/net/http.rb:457>"
4115 *
4116 * <code>...</code> in argument definition means argument is optional (has
4117 * some default value).
4118 *
4119 * For methods defined in C (language core and extensions), location and
4120 * argument names can't be extracted, and only generic information is provided
4121 * in form of <code>*</code> (any number of arguments) or <code>_</code> (some
4122 * positional argument).
4123 *
4124 * "cat".method(:count).inspect #=> "#<Method: String#count(*)>"
4125 * "cat".method(:+).inspect #=> "#<Method: String#+(_)>""
4126
4127 */
4128
4129static VALUE
4130method_inspect(VALUE method)
4131{
4132 struct METHOD *data;
4133 VALUE str;
4134 const char *sharp = "#";
4135 VALUE mklass;
4136 VALUE defined_class;
4137
4138 TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
4139 str = rb_sprintf("#<% "PRIsVALUE": ", rb_obj_class(method));
4140
4141 mklass = data->iclass;
4142 if (!mklass) mklass = data->klass;
4143
4144 if (RB_TYPE_P(mklass, T_ICLASS)) {
4145 /* TODO: I'm not sure why mklass is T_ICLASS.
4146 * UnboundMethod#bind() can set it as T_ICLASS at convert_umethod_to_method_components()
4147 * but not sure it is needed.
4148 */
4149 mklass = RBASIC_CLASS(mklass);
4150 }
4151
4152 const rb_method_definition_t *def = rb_method_entry_def_acquire(data->me);
4153 if (def->type == VM_METHOD_TYPE_ALIAS) {
4154 defined_class = rb_method_alias_original_me(def)->owner;
4155 }
4156 else {
4157 defined_class = method_entry_defined_class(data->me);
4158 }
4159
4160 if (RB_TYPE_P(defined_class, T_ICLASS)) {
4161 defined_class = RBASIC_CLASS(defined_class);
4162 }
4163
4164 if (UNDEF_P(data->recv)) {
4165 // UnboundMethod
4166 rb_str_buf_append(str, rb_inspect(defined_class));
4167 }
4168 else if (RCLASS_SINGLETON_P(mklass)) {
4169 VALUE v = RCLASS_ATTACHED_OBJECT(mklass);
4170
4171 if (UNDEF_P(data->recv)) {
4172 rb_str_buf_append(str, rb_inspect(mklass));
4173 }
4174 else if (data->recv == v) {
4176 sharp = ".";
4177 }
4178 else {
4179 rb_str_buf_append(str, rb_inspect(data->recv));
4180 rb_str_buf_cat2(str, "(");
4182 rb_str_buf_cat2(str, ")");
4183 sharp = ".";
4184 }
4185 }
4186 else {
4187 mklass = data->klass;
4188 if (RB_TYPE_P(mklass, T_ICLASS)) {
4189 mklass = RBASIC_CLASS(mklass);
4190 }
4191 if (RCLASS_SINGLETON_P(mklass)) {
4192 VALUE v = RCLASS_ATTACHED_OBJECT(mklass);
4193 if (!(RB_TYPE_P(v, T_CLASS) || RB_TYPE_P(v, T_MODULE))) {
4194 do {
4195 mklass = RCLASS_SUPER(mklass);
4196 } while (RB_TYPE_P(mklass, T_ICLASS));
4197 }
4198 }
4199 rb_str_buf_append(str, rb_inspect(mklass));
4200 if (defined_class != mklass) {
4201 rb_str_catf(str, "(% "PRIsVALUE")", defined_class);
4202 }
4203 }
4204 rb_str_buf_cat2(str, sharp);
4205 rb_str_append(str, rb_id2str(data->me->called_id));
4206 if (data->me->called_id != def->original_id) {
4207 rb_str_catf(str, "(%"PRIsVALUE")",
4208 rb_id2str(def->original_id));
4209 }
4210 if (def->type == VM_METHOD_TYPE_NOTIMPLEMENTED) {
4211 rb_str_buf_cat2(str, " (not-implemented)");
4212 }
4213
4214 // parameter information
4215 {
4216 VALUE params = rb_method_parameters(method);
4217 VALUE pair, name, kind;
4218 const VALUE req = ID2SYM(rb_intern("req"));
4219 const VALUE opt = ID2SYM(rb_intern("opt"));
4220 const VALUE keyreq = ID2SYM(rb_intern("keyreq"));
4221 const VALUE key = ID2SYM(rb_intern("key"));
4222 const VALUE rest = ID2SYM(rb_intern("rest"));
4223 const VALUE keyrest = ID2SYM(rb_intern("keyrest"));
4224 const VALUE block = ID2SYM(rb_intern("block"));
4225 const VALUE nokey = ID2SYM(rb_intern("nokey"));
4226 const VALUE noblock = ID2SYM(rb_intern("noblock"));
4227 int forwarding = 0;
4228
4229 rb_str_buf_cat2(str, "(");
4230
4231 if (RARRAY_LEN(params) == 3 &&
4232 RARRAY_AREF(RARRAY_AREF(params, 0), 0) == rest &&
4233 RARRAY_AREF(RARRAY_AREF(params, 0), 1) == ID2SYM('*') &&
4234 RARRAY_AREF(RARRAY_AREF(params, 1), 0) == keyrest &&
4235 RARRAY_AREF(RARRAY_AREF(params, 1), 1) == ID2SYM(idPow) &&
4236 RARRAY_AREF(RARRAY_AREF(params, 2), 0) == block &&
4237 RARRAY_AREF(RARRAY_AREF(params, 2), 1) == ID2SYM('&')) {
4238 forwarding = 1;
4239 }
4240
4241 for (int i = 0; i < RARRAY_LEN(params); i++) {
4242 pair = RARRAY_AREF(params, i);
4243 kind = RARRAY_AREF(pair, 0);
4244 if (RARRAY_LEN(pair) > 1) {
4245 name = RARRAY_AREF(pair, 1);
4246 }
4247 else {
4248 name = Qnil;
4249 }
4250
4251 if (kind == req) {
4252 append_param_name(str, name, "_");
4253 }
4254 else if (kind == opt) {
4255 rb_str_cat_cstr(append_param_name(str, name, "_"), "=...");
4256 }
4257 else if (kind == keyreq) {
4258 rb_str_cat_cstr(append_param_name(str, name, NULL), ":");
4259 }
4260 else if (kind == key) {
4261 rb_str_cat_cstr(append_param_name(str, name, NULL), ": ...");
4262 }
4263 else if (kind == rest) {
4264 rb_str_cat_cstr(str, forwarding ? "..." : "*");
4265 if (name != ID2SYM('*')) {
4266 append_param_name(str, name, NULL);
4267 }
4268 }
4269 else if (kind == keyrest) {
4270 if (name != ID2SYM(idPow)) {
4271 append_param_name(rb_str_cat_cstr(str, "**"), name, NULL);
4272 }
4273 else if (i > 0) {
4274 rb_str_set_len(str, RSTRING_LEN(str) - 2);
4275 }
4276 else {
4277 rb_str_cat_cstr(str, "**");
4278 }
4279 }
4280 else if (kind == block) {
4281 if (name == ID2SYM('&')) {
4282 if (forwarding) {
4283 rb_str_set_len(str, RSTRING_LEN(str) - 2);
4284 }
4285 else {
4286 rb_str_cat_cstr(str, "...");
4287 }
4288 }
4289 else {
4290 append_param_name(rb_str_cat_cstr(str, "&"), name, NULL);
4291 }
4292 }
4293 else if (kind == nokey) {
4294 rb_str_buf_cat2(str, "**nil");
4295 }
4296 else if (kind == noblock) {
4297 rb_str_buf_cat2(str, "&nil");
4298 }
4299
4300 if (i < RARRAY_LEN(params) - 1) {
4301 rb_str_buf_cat2(str, ", ");
4302 }
4303 }
4304 rb_str_buf_cat2(str, ")");
4305 }
4306
4307 { // source location
4308 VALUE loc = rb_method_location(method);
4309 if (!NIL_P(loc)) {
4310 rb_str_catf(str, " %"PRIsVALUE":%"PRIsVALUE,
4311 RARRAY_AREF(loc, 0), RARRAY_AREF(loc, 1));
4312 }
4313 }
4314
4315 rb_str_buf_cat2(str, ">");
4316
4317 return str;
4318}
4319
4320static VALUE
4321bmcall(RB_BLOCK_CALL_FUNC_ARGLIST(args, method))
4322{
4323 return rb_method_call_with_block_kw(argc, argv, method, blockarg, RB_PASS_CALLED_KEYWORDS);
4324}
4325
4326VALUE
4329 VALUE val)
4330{
4331 VALUE procval = rb_block_call(rb_mRubyVMFrozenCore, idProc, 0, 0, func, val);
4332 return procval;
4333}
4334
4335/*
4336 * call-seq:
4337 * meth.to_proc -> proc
4338 *
4339 * Returns a Proc object corresponding to this method.
4340 */
4341
4342static VALUE
4343method_to_proc(VALUE method)
4344{
4345 VALUE procval;
4346 rb_proc_t *proc;
4347
4348 /*
4349 * class Method
4350 * def to_proc
4351 * lambda{|*args|
4352 * self.call(*args)
4353 * }
4354 * end
4355 * end
4356 */
4357 procval = rb_block_call(rb_mRubyVMFrozenCore, idLambda, 0, 0, bmcall, method);
4358 GetProcPtr(procval, proc);
4359 proc->header.is_from_method = 1;
4360 return procval;
4361}
4362
4363extern VALUE rb_find_defined_class_by_owner(VALUE current_class, VALUE target_owner);
4364extern int rb_method_definition_eq(const rb_method_definition_t *d1, const rb_method_definition_t *d2);
4365rb_cref_t * rb_vm_get_cref(const VALUE *ep);
4366
4367/*
4368 * call-seq:
4369 * meth.super_method -> method
4370 *
4371 * Returns a +Method+ of superclass which would be called when super is used
4372 * or nil if there is no method on superclass.
4373 */
4374
4375static VALUE
4376method_super_method(VALUE method)
4377{
4378 const struct METHOD *data;
4379 VALUE super_class, iclass;
4380 ID mid;
4381 const rb_method_entry_t *me;
4382
4383 TypedData_Get_Struct(method, struct METHOD, &method_data_type, data);
4384 iclass = data->iclass;
4385 if (!iclass) return Qnil;
4386 bool is_refinement_method = refinement_module_p(data->me->owner);
4387 const rb_method_definition_t *def = rb_method_entry_def_acquire(data->me);
4388 if (def->type == VM_METHOD_TYPE_ALIAS && data->me->defined_class) {
4389 const rb_method_entry_t *orig_me = rb_method_alias_original_me(def);
4390 super_class = RCLASS_SUPER(rb_find_defined_class_by_owner(data->me->defined_class,
4391 orig_me->owner));
4392 mid = rb_method_entry_def_acquire(orig_me)->original_id;
4393 }
4394 else if (is_refinement_method) {
4395 if (RICLASS_FOR_REFINEMENT_P(iclass)) {
4396 do {
4397 super_class = RCLASS_SUPER(iclass);
4398 iclass = super_class;
4399 } while (RICLASS_FOR_REFINEMENT_P(super_class));
4400 }
4401 else {
4402 super_class = find_refined_target_ancestor(iclass, rb_refinement_module_get_refined_class(data->me->owner));
4403 if (!super_class) {
4404 super_class = RCLASS_SUPER(data->me->owner);
4405 }
4406 }
4407 mid = def->original_id;
4408 }
4409 else {
4410 VALUE klass = iclass;
4411 if (RICLASS_FOR_REFINEMENT_P(klass)) {
4412 // Refined methods need this check before superclass determination
4413 klass = RBASIC(klass)->klass;
4414 }
4415 super_class = RCLASS_SUPER(RCLASS_ORIGIN(klass));
4416 mid = def->original_id;
4417 }
4418 if (!super_class) return Qnil;
4419
4420 // For refined methods, skip refinements for the same definition, but consider
4421 // refinements for superclass methods
4422 const rb_method_definition_t *skip_def = is_refinement_method ? def : NULL;
4423
4424 // Use the CREF of the Method/UnboundMethod, not the CREF of the caller of super_method.
4425 // We must avoid the use of rb_callable_method_entry_with_refinements, as that will
4426 // implicitly use the refinements activated in of the caller of super_method.
4427 const rb_cref_t *cref = NULL;
4428 switch (def->type) {
4429 case VM_METHOD_TYPE_ISEQ:
4430 cref = def->body.iseq.cref;
4431 break;
4432 case VM_METHOD_TYPE_BMETHOD: {
4433 const rb_proc_t *proc;
4434 GetProcPtr(def->body.bmethod.proc, proc);
4435 const struct rb_block *block = &proc->block;
4436 if (vm_block_type(block) == block_type_iseq)
4437 cref = rb_vm_get_cref(block->as.captured.ep);
4438 break;
4439 }
4440 default:
4441 break;
4442 }
4443 VALUE klass = super_class;
4444 me = NULL;
4445 while (klass) {
4446 const rb_callable_method_entry_t *cme = rb_callable_method_entry(klass, mid);
4447 if (!cme) break;
4448 if (cme->def->type != VM_METHOD_TYPE_REFINED) {
4449 me = (rb_method_entry_t *)cme;
4450 iclass = cme->defined_class;
4451 break;
4452 }
4453 // Look through all CREF scopes for a refinement for cme->owner, mirroring
4454 // the loop in search_refined_method.
4455 const rb_cref_t *c;
4456 for (c = cref; c; c = CREF_NEXT(c)) {
4457 VALUE refs = CREF_REFINEMENTS(c);
4458 if (NIL_P(refs)) continue;
4459 VALUE r = rb_hash_lookup(refs, cme->owner);
4460 if (NIL_P(r)) continue;
4461 r = rb_vm_refinement_iclass_for_cme(r, cme);
4462 const rb_callable_method_entry_t *ref_cme = rb_callable_method_entry(r, mid);
4463 if (!ref_cme) break;
4464 if (ref_cme->def->type == VM_METHOD_TYPE_REFINED) continue;
4465 if (skip_def && rb_method_definition_eq(ref_cme->def, skip_def)) continue;
4466 me = (rb_method_entry_t *)ref_cme;
4467 iclass = ref_cme->defined_class;
4468 break;
4469 }
4470 if (me) break;
4471 // No refined method found. Use orig_me if available, or normal method lookup
4472 // in superclass otherwise.
4473 const rb_method_entry_t *orig_me = cme->def->body.refined.orig_me;
4474 if (orig_me) {
4475 me = (rb_method_entry_t *)orig_me;
4476 iclass = cme->defined_class;
4477 break;
4478 }
4479 klass = RCLASS_SUPER(cme->defined_class);
4480 }
4481 if (!me) return Qnil;
4482 VALUE mklass = (RB_TYPE_P(me->owner, T_MODULE) || UNDEF_P(data->recv)) ? iclass : CLASS_OF(data->recv);
4483 return mnew_internal(me, mklass, iclass, data->recv, mid, rb_obj_class(method), FALSE, FALSE);
4484}
4485
4486/*
4487 * call-seq:
4488 * local_jump_error.exit_value -> obj
4489 *
4490 * Returns the exit value associated with this +LocalJumpError+.
4491 */
4492static VALUE
4493localjump_xvalue(VALUE exc)
4494{
4495 return rb_iv_get(exc, "@exit_value");
4496}
4497
4498/*
4499 * call-seq:
4500 * local_jump_error.reason -> symbol
4501 *
4502 * The reason this block was terminated:
4503 * :break, :redo, :retry, :next, :return, or :noreason.
4504 */
4505
4506static VALUE
4507localjump_reason(VALUE exc)
4508{
4509 return rb_iv_get(exc, "@reason");
4510}
4511
4512rb_cref_t *rb_vm_cref_new_toplevel(void); /* vm.c */
4513
4514static const rb_env_t *
4515env_clone(const rb_env_t *env, const rb_cref_t *cref)
4516{
4517 VALUE *new_ep;
4518 VALUE *new_body;
4519 const rb_env_t *new_env;
4520
4521 VM_ASSERT(env->ep > env->env);
4522 VM_ASSERT(VM_ENV_ESCAPED_P(env->ep));
4523
4524 if (cref == NULL) {
4525 cref = rb_vm_cref_new_toplevel();
4526 }
4527
4528 new_body = ALLOC_N(VALUE, env->env_size);
4529 new_ep = &new_body[env->ep - env->env];
4530 new_env = vm_env_new(new_ep, new_body, env->env_size, env->iseq);
4531
4532 /* The memcpy has to happen after the vm_env_new because it can trigger a
4533 * GC compaction which can move the objects in the env. */
4534 MEMCPY(new_body, env->env, VALUE, env->env_size);
4535 /* VM_ENV_DATA_INDEX_ENV is set in vm_env_new but will get overwritten
4536 * by the memcpy above. */
4537 new_ep[VM_ENV_DATA_INDEX_ENV] = (VALUE)new_env;
4538 RB_OBJ_WRITE(new_env, &new_ep[VM_ENV_DATA_INDEX_ME_CREF], (VALUE)cref);
4539 VM_ASSERT(VM_ENV_ESCAPED_P(new_ep));
4540 return new_env;
4541}
4542
4543/*
4544 * call-seq:
4545 * prc.binding -> binding
4546 *
4547 * Returns the binding associated with <i>prc</i>.
4548 *
4549 * def fred(param)
4550 * proc {}
4551 * end
4552 *
4553 * b = fred(99)
4554 * eval("param", b.binding) #=> 99
4555 */
4556static VALUE
4557proc_binding(VALUE self)
4558{
4559 VALUE bindval, binding_self = Qundef;
4560 rb_binding_t *bind;
4561 const rb_proc_t *proc;
4562 const rb_iseq_t *iseq = NULL;
4563 const struct rb_block *block;
4564 const rb_env_t *env = NULL;
4565
4566 GetProcPtr(self, proc);
4567 block = &proc->block;
4568
4569 if (proc->header.is_isolated) rb_raise(rb_eArgError, "Can't create Binding from isolated Proc");
4570
4571 again:
4572 switch (vm_block_type(block)) {
4573 case block_type_iseq:
4574 iseq = block->as.captured.code.iseq;
4575 binding_self = block->as.captured.self;
4576 env = VM_ENV_ENVVAL_PTR(block->as.captured.ep);
4577 break;
4578 case block_type_proc:
4579 GetProcPtr(block->as.proc, proc);
4580 block = &proc->block;
4581 goto again;
4582 case block_type_ifunc:
4583 {
4584 const struct vm_ifunc *ifunc = block->as.captured.code.ifunc;
4585 if (IS_METHOD_PROC_IFUNC(ifunc)) {
4586 VALUE method = (VALUE)ifunc->data;
4587 VALUE name = rb_fstring_lit("<empty_iseq>");
4588 rb_iseq_t *empty;
4589 binding_self = method_receiver(method);
4590 iseq = rb_method_iseq(method);
4591 env = VM_ENV_ENVVAL_PTR(block->as.captured.ep);
4592 env = env_clone(env, method_cref(method));
4593 /* set empty iseq */
4594 empty = rb_iseq_new(Qnil, name, name, Qnil, 0, ISEQ_TYPE_TOP);
4595 RB_OBJ_WRITE(env, &env->iseq, empty);
4596 break;
4597 }
4598 }
4599 /* FALLTHROUGH */
4600 case block_type_symbol:
4601 rb_raise(rb_eArgError, "Can't create Binding from C level Proc");
4603 }
4604
4605 bindval = rb_binding_alloc(rb_cBinding);
4606 GetBindingPtr(bindval, bind);
4607 RB_OBJ_WRITE(bindval, &bind->block.as.captured.self, binding_self);
4608 RB_OBJ_WRITE(bindval, &bind->block.as.captured.code.iseq, env->iseq);
4609 rb_vm_block_ep_update(bindval, &bind->block, env->ep);
4610 RB_OBJ_WRITTEN(bindval, Qundef, VM_ENV_ENVVAL(env->ep));
4611
4612 if (iseq) {
4613 rb_iseq_check(iseq);
4614 RB_OBJ_WRITE(bindval, &bind->pathobj, ISEQ_BODY(iseq)->location.pathobj);
4615 bind->no_realpath = ISEQ_BODY(iseq)->no_realpath;
4616 bind->first_lineno = ISEQ_BODY(iseq)->location.first_lineno;
4617 }
4618 else {
4619 bool no_realpath;
4620 RB_OBJ_WRITE(bindval, &bind->pathobj,
4621 rb_iseq_pathobj_new(rb_fstring_lit("(binding)"), Qnil, &no_realpath));
4622 bind->no_realpath = no_realpath;
4623 bind->first_lineno = 1;
4624 }
4625
4626 return bindval;
4627}
4628
4629static rb_block_call_func curry;
4630
4631static VALUE
4632make_curry_proc(VALUE proc, VALUE passed, VALUE arity)
4633{
4634 VALUE args = rb_ary_new3(3, proc, passed, arity);
4635 rb_proc_t *procp;
4636 int is_lambda;
4637
4638 GetProcPtr(proc, procp);
4639 is_lambda = procp->header.is_lambda;
4640 rb_ary_freeze(passed);
4641 rb_ary_freeze(args);
4642 proc = rb_proc_new(curry, args);
4643 GetProcPtr(proc, procp);
4644 procp->header.is_lambda = is_lambda;
4645 return proc;
4646}
4647
4648static VALUE
4649curry(RB_BLOCK_CALL_FUNC_ARGLIST(_, args))
4650{
4651 VALUE proc, passed, arity;
4652 proc = RARRAY_AREF(args, 0);
4653 passed = RARRAY_AREF(args, 1);
4654 arity = RARRAY_AREF(args, 2);
4655
4656 passed = rb_ary_plus(passed, rb_ary_new4(argc, argv));
4657 rb_ary_freeze(passed);
4658
4659 if (RARRAY_LEN(passed) < FIX2INT(arity)) {
4660 if (!NIL_P(blockarg)) {
4661 rb_warn("given block not used");
4662 }
4663 arity = make_curry_proc(proc, passed, arity);
4664 return arity;
4665 }
4666 else {
4667 // `passed` is the only reference keeping this array (and thus the
4668 // buffer that RARRAY_CONST_PTR points into) alive, but it is otherwise
4669 // unused after this point. Without RB_GC_GUARD the compiler may drop it
4670 // before the call returns, so conservative stack marking misses it and
4671 // GC can reclaim the array while it is still being read as argv,
4672 // crashing with "try to mark T_NONE object".
4673 VALUE result = rb_proc_call_with_block(proc, check_argc(RARRAY_LEN(passed)), RARRAY_CONST_PTR(passed), blockarg);
4674 RB_GC_GUARD(passed);
4675 return result;
4676 }
4677}
4678
4679 /*
4680 * call-seq:
4681 * prc.curry -> a_proc
4682 * prc.curry(arity) -> a_proc
4683 *
4684 * Returns a curried proc. If the optional <i>arity</i> argument is given,
4685 * it determines the number of arguments.
4686 * A curried proc receives some arguments. If a sufficient number of
4687 * arguments are supplied, it passes the supplied arguments to the original
4688 * proc and returns the result. Otherwise, returns another curried proc that
4689 * takes the rest of arguments.
4690 *
4691 * The optional <i>arity</i> argument should be supplied when currying procs with
4692 * variable arguments to determine how many arguments are needed before the proc is
4693 * called.
4694 *
4695 * b = proc {|x, y, z| (x||0) + (y||0) + (z||0) }
4696 * p b.curry[1][2][3] #=> 6
4697 * p b.curry[1, 2][3, 4] #=> 6
4698 * p b.curry(5)[1][2][3][4][5] #=> 6
4699 * p b.curry(5)[1, 2][3, 4][5] #=> 6
4700 * p b.curry(1)[1] #=> 1
4701 *
4702 * b = proc {|x, y, z, *w| (x||0) + (y||0) + (z||0) + w.inject(0, &:+) }
4703 * p b.curry[1][2][3] #=> 6
4704 * p b.curry[1, 2][3, 4] #=> 10
4705 * p b.curry(5)[1][2][3][4][5] #=> 15
4706 * p b.curry(5)[1, 2][3, 4][5] #=> 15
4707 * p b.curry(1)[1] #=> 1
4708 *
4709 * b = lambda {|x, y, z| (x||0) + (y||0) + (z||0) }
4710 * p b.curry[1][2][3] #=> 6
4711 * p b.curry[1, 2][3, 4] #=> wrong number of arguments (given 4, expected 3)
4712 * p b.curry(5) #=> wrong number of arguments (given 5, expected 3)
4713 * p b.curry(1) #=> wrong number of arguments (given 1, expected 3)
4714 *
4715 * b = lambda {|x, y, z, *w| (x||0) + (y||0) + (z||0) + w.inject(0, &:+) }
4716 * p b.curry[1][2][3] #=> 6
4717 * p b.curry[1, 2][3, 4] #=> 10
4718 * p b.curry(5)[1][2][3][4][5] #=> 15
4719 * p b.curry(5)[1, 2][3, 4][5] #=> 15
4720 * p b.curry(1) #=> wrong number of arguments (given 1, expected 3)
4721 *
4722 * b = proc { :foo }
4723 * p b.curry[] #=> :foo
4724 */
4725static VALUE
4726proc_curry(int argc, const VALUE *argv, VALUE self)
4727{
4728 int sarity, max_arity, min_arity = rb_proc_min_max_arity(self, &max_arity);
4729 VALUE arity;
4730
4731 if (rb_check_arity(argc, 0, 1) == 0 || NIL_P(arity = argv[0])) {
4732 arity = INT2FIX(min_arity);
4733 }
4734 else {
4735 sarity = NUM2INT(arity);
4736 if (rb_proc_lambda_p(self)) {
4737 rb_check_arity(sarity, min_arity, max_arity);
4738 }
4739 arity = INT2FIX(sarity);
4740 }
4741
4742 return make_curry_proc(self, rb_ary_new(), arity);
4743}
4744
4745/*
4746 * call-seq:
4747 * meth.curry -> proc
4748 * meth.curry(arity) -> proc
4749 *
4750 * Returns a curried proc based on the method. When the proc is called with a number of
4751 * arguments that is lower than the method's arity, then another curried proc is returned.
4752 * Only when enough arguments have been supplied to satisfy the method signature, will the
4753 * method actually be called.
4754 *
4755 * The optional <i>arity</i> argument should be supplied when currying methods with
4756 * variable arguments to determine how many arguments are needed before the method is
4757 * called.
4758 *
4759 * def foo(a,b,c)
4760 * [a, b, c]
4761 * end
4762 *
4763 * proc = self.method(:foo).curry
4764 * proc2 = proc.call(1, 2) #=> #<Proc>
4765 * proc2.call(3) #=> [1,2,3]
4766 *
4767 * def vararg(*args)
4768 * args
4769 * end
4770 *
4771 * proc = self.method(:vararg).curry(4)
4772 * proc2 = proc.call(:x) #=> #<Proc>
4773 * proc3 = proc2.call(:y, :z) #=> #<Proc>
4774 * proc3.call(:a) #=> [:x, :y, :z, :a]
4775 */
4776
4777static VALUE
4778rb_method_curry(int argc, const VALUE *argv, VALUE self)
4779{
4780 VALUE proc = method_to_proc(self);
4781 return proc_curry(argc, argv, proc);
4782}
4783
4784static VALUE
4785compose(RB_BLOCK_CALL_FUNC_ARGLIST(_, args))
4786{
4787 VALUE f, g, fargs;
4788 f = RARRAY_AREF(args, 0);
4789 g = RARRAY_AREF(args, 1);
4790
4791 if (rb_obj_is_proc(g))
4792 fargs = rb_proc_call_with_block_kw(g, argc, argv, blockarg, RB_PASS_CALLED_KEYWORDS);
4793 else
4794 fargs = rb_funcall_with_block_kw(g, idCall, argc, argv, blockarg, RB_PASS_CALLED_KEYWORDS);
4795
4796 if (rb_obj_is_proc(f))
4797 return rb_proc_call(f, rb_ary_new3(1, fargs));
4798 else
4799 return rb_funcallv(f, idCall, 1, &fargs);
4800}
4801
4802static VALUE
4803to_callable(VALUE f)
4804{
4805 VALUE mesg;
4806
4807 if (rb_obj_is_proc(f)) return f;
4808 if (rb_obj_is_method(f)) return f;
4809 if (rb_obj_respond_to(f, idCall, TRUE)) return f;
4810 mesg = rb_fstring_lit("callable object is expected");
4812}
4813
4814static VALUE rb_proc_compose_to_left(VALUE self, VALUE g);
4815static VALUE rb_proc_compose_to_right(VALUE self, VALUE g);
4816
4817/*
4818 * call-seq:
4819 * prc << g -> a_proc
4820 *
4821 * Returns a proc that is the composition of this proc and the given <i>g</i>.
4822 * The returned proc takes a variable number of arguments, calls <i>g</i> with them
4823 * then calls this proc with the result.
4824 *
4825 * f = proc {|x| x * x }
4826 * g = proc {|x| x + x }
4827 * p (f << g).call(2) #=> 16
4828 *
4829 * See Proc#>> for detailed explanations.
4830 */
4831static VALUE
4832proc_compose_to_left(VALUE self, VALUE g)
4833{
4834 return rb_proc_compose_to_left(self, to_callable(g));
4835}
4836
4837static VALUE
4838rb_proc_compose_to_left(VALUE self, VALUE g)
4839{
4840 VALUE proc, args, procs[2];
4841 rb_proc_t *procp;
4842 int is_lambda;
4843
4844 procs[0] = self;
4845 procs[1] = g;
4846 args = rb_ary_tmp_new_from_values(0, 2, procs);
4847
4848 if (rb_obj_is_proc(g)) {
4849 GetProcPtr(g, procp);
4850 is_lambda = procp->header.is_lambda;
4851 }
4852 else {
4853 VM_ASSERT(rb_obj_is_method(g) || rb_obj_respond_to(g, idCall, TRUE));
4854 is_lambda = 1;
4855 }
4856
4857 proc = rb_proc_new(compose, args);
4858 GetProcPtr(proc, procp);
4859 procp->header.is_lambda = is_lambda;
4860
4861 return proc;
4862}
4863
4864/*
4865 * call-seq:
4866 * prc >> g -> a_proc
4867 *
4868 * Returns a proc that is the composition of this proc and the given <i>g</i>.
4869 * The returned proc takes a variable number of arguments, calls this proc with them
4870 * then calls <i>g</i> with the result.
4871 *
4872 * f = proc {|x| x * x }
4873 * g = proc {|x| x + x }
4874 * p (f >> g).call(2) #=> 8
4875 *
4876 * <i>g</i> could be other Proc, or Method, or any other object responding to
4877 * +call+ method:
4878 *
4879 * class Parser
4880 * def self.call(text)
4881 * # ...some complicated parsing logic...
4882 * end
4883 * end
4884 *
4885 * pipeline = File.method(:read) >> Parser >> proc { |data| puts "data size: #{data.count}" }
4886 * pipeline.call('data.json')
4887 *
4888 * See also Method#>> and Method#<<.
4889 */
4890static VALUE
4891proc_compose_to_right(VALUE self, VALUE g)
4892{
4893 return rb_proc_compose_to_right(self, to_callable(g));
4894}
4895
4896static VALUE
4897rb_proc_compose_to_right(VALUE self, VALUE g)
4898{
4899 VALUE proc, args, procs[2];
4900 rb_proc_t *procp;
4901 int is_lambda;
4902
4903 procs[0] = g;
4904 procs[1] = self;
4905 args = rb_ary_tmp_new_from_values(0, 2, procs);
4906
4907 GetProcPtr(self, procp);
4908 is_lambda = procp->header.is_lambda;
4909
4910 proc = rb_proc_new(compose, args);
4911 GetProcPtr(proc, procp);
4912 procp->header.is_lambda = is_lambda;
4913
4914 return proc;
4915}
4916
4917/*
4918 * call-seq:
4919 * self << g -> a_proc
4920 *
4921 * Returns a proc that is the composition of the given +g+ and this method.
4922 *
4923 * The returned proc takes a variable number of arguments. It first calls +g+
4924 * with the arguments, then calls +self+ with the return value of +g+.
4925 *
4926 * def f(ary) = ary << 'in f'
4927 *
4928 * f = self.method(:f)
4929 * g = proc { |ary| ary << 'in proc' }
4930 * (f << g).call([]) # => ["in proc", "in f"]
4931 */
4932static VALUE
4933rb_method_compose_to_left(VALUE self, VALUE g)
4934{
4935 g = to_callable(g);
4936 self = method_to_proc(self);
4937 return proc_compose_to_left(self, g);
4938}
4939
4940/*
4941 * call-seq:
4942 * self >> g -> a_proc
4943 *
4944 * Returns a proc that is the composition of this method and the given +g+.
4945 *
4946 * The returned proc takes a variable number of arguments. It first calls +self+
4947 * with the arguments, then calls +g+ with the return value of +self+.
4948 *
4949 * def f(ary) = ary << 'in f'
4950 *
4951 * f = self.method(:f)
4952 * g = proc { |ary| ary << 'in proc' }
4953 * (f >> g).call([]) # => ["in f", "in proc"]
4954 */
4955static VALUE
4956rb_method_compose_to_right(VALUE self, VALUE g)
4957{
4958 g = to_callable(g);
4959 self = method_to_proc(self);
4960 return proc_compose_to_right(self, g);
4961}
4962
4963/*
4964 * call-seq:
4965 * proc.ruby2_keywords -> proc
4966 *
4967 * Deprecated: will be removed in Ruby 4.4. Use explicit delegation
4968 * (<tt>*args, **kwargs</tt>) instead; it works correctly on Ruby 3.0
4969 * and later. See https://bugs.ruby-lang.org/issues/22205 for the
4970 * schedule.
4971 *
4972 * Marks the proc as passing keywords through a normal argument splat.
4973 * This should only be called on procs that accept an argument splat
4974 * (<tt>*args</tt>) but not explicit keywords or a keyword splat. It
4975 * marks the proc such that if the proc is called with keyword arguments,
4976 * the final hash argument is marked with a special flag such that if it
4977 * is the final element of a normal argument splat to another method call,
4978 * and that method call does not include explicit keywords or a keyword
4979 * splat, the final element is interpreted as keywords. In other words,
4980 * keywords will be passed through the proc to other methods.
4981 *
4982 * This should only be used for procs that delegate keywords to another
4983 * method, and only for backwards compatibility with Ruby versions before
4984 * 2.7.
4985 */
4986
4987static VALUE
4988proc_ruby2_keywords(VALUE procval)
4989{
4990 rb_proc_t *proc;
4991 GetProcPtr(procval, proc);
4992
4993 rb_check_frozen(procval);
4994
4995 if (proc->header.is_from_method) {
4996 rb_warn("Skipping set of ruby2_keywords flag for proc (proc created from method)");
4997 return procval;
4998 }
4999
5000 switch (proc->block.type) {
5001 case block_type_iseq:
5002 if (ISEQ_BODY(proc->block.as.captured.code.iseq)->param.flags.has_rest &&
5003 !ISEQ_BODY(proc->block.as.captured.code.iseq)->param.flags.has_post &&
5004 !ISEQ_BODY(proc->block.as.captured.code.iseq)->param.flags.has_kw &&
5005 !ISEQ_BODY(proc->block.as.captured.code.iseq)->param.flags.has_kwrest) {
5006 if (proc->header.is_refined) {
5007 /* on a copy of this Proc's own: the block is shared with the
5008 * source Proc until the first call, and the copy installed by
5009 * it may be memoized and shared with sibling Procs */
5010 const rb_iseq_t *copy =
5011 rb_iseq_dup_with_independent_caches(proc->block.as.captured.code.iseq);
5012 ISEQ_BODY(copy)->param.flags.ruby2_keywords = 1;
5013 RB_VM_LOCKING() {
5014 RB_OBJ_WRITE(procval, &proc->block.as.captured.code.val, (VALUE)copy);
5015 }
5016 }
5017 else {
5018 ISEQ_BODY(proc->block.as.captured.code.iseq)->param.flags.ruby2_keywords = 1;
5019 }
5020 }
5021 else {
5022 rb_warn("Skipping set of ruby2_keywords flag for proc (proc accepts keywords or post arguments or proc does not accept argument splat)");
5023 }
5024 break;
5025 default:
5026 rb_warn("Skipping set of ruby2_keywords flag for proc (proc not defined in Ruby)");
5027 break;
5028 }
5029
5030 return procval;
5031}
5032
5033/*
5034 * Document-class: LocalJumpError
5035 *
5036 * Raised when Ruby can't yield as requested.
5037 *
5038 * A typical scenario is attempting to yield when no block is given:
5039 *
5040 * def call_block
5041 * yield 42
5042 * end
5043 * call_block
5044 *
5045 * <em>raises the exception:</em>
5046 *
5047 * LocalJumpError: no block given (yield)
5048 *
5049 * A more subtle example:
5050 *
5051 * def get_me_a_return
5052 * Proc.new { return 42 }
5053 * end
5054 * get_me_a_return.call
5055 *
5056 * <em>raises the exception:</em>
5057 *
5058 * LocalJumpError: unexpected return
5059 */
5060
5061/*
5062 * Document-class: SystemStackError
5063 *
5064 * Raised in case of a stack overflow.
5065 *
5066 * def me_myself_and_i
5067 * me_myself_and_i
5068 * end
5069 * me_myself_and_i
5070 *
5071 * <em>raises the exception:</em>
5072 *
5073 * SystemStackError: stack level too deep
5074 */
5075
5076/*
5077 * Document-class: Ruby::SourceRange
5078 *
5079 * An object representing a range of Ruby source code.
5080 *
5081 * Source ranges are returned by Proc#source_range, Method#source_range, and
5082 * UnboundMethod#source_range, as well as Thread::Backtrace::Location#source_range.
5083 * They include the source path, absolute path when available,
5084 * start line, start byte column, end line, and end byte column.
5085 *
5086 * The primary purpose of this class is to implement `Prism.find` precisely and cleanly on all Ruby implementations,
5087 * in a way which does not depend on implementation details like `node_id`.
5088 * For that we need the start/end line/column and the absolute_path, which is exactly what this class provides.
5089 *
5090 * The user of `Prism.find` can then tweak the result as desired to, for example,
5091 * include heredocs as mentioned in Ruby::SourceRange#end_line.
5092 * Or for Proc#source_range to include the method to which the block is passed.
5093 *
5094 * Note that the returned source range is not always an evaluable fragment by itself,
5095 * notably because heredocs can go beyond the `end` of the method and
5096 * for blocks because the range starts at `{`/`do`.
5097 */
5098
5099/*
5100 * Document-class: Proc
5101 *
5102 * A +Proc+ object is an encapsulation of a block of code, which can be stored
5103 * in a local variable, passed to a method or another Proc, and can be called.
5104 * Proc is an essential concept in Ruby and a core of its functional
5105 * programming features.
5106 *
5107 * square = Proc.new {|x| x**2 }
5108 *
5109 * square.call(3) #=> 9
5110 * # shorthands:
5111 * square.(3) #=> 9
5112 * square[3] #=> 9
5113 *
5114 * Proc objects are _closures_, meaning they remember and can use the entire
5115 * context in which they were created.
5116 *
5117 * def gen_times(factor)
5118 * Proc.new {|n| n*factor } # remembers the value of factor at the moment of creation
5119 * end
5120 *
5121 * times3 = gen_times(3)
5122 * times5 = gen_times(5)
5123 *
5124 * times3.call(12) #=> 36
5125 * times5.call(5) #=> 25
5126 * times3.call(times5.call(4)) #=> 60
5127 *
5128 * == Creation
5129 *
5130 * There are several methods to create a Proc
5131 *
5132 * * Use the Proc class constructor:
5133 *
5134 * proc1 = Proc.new {|x| x**2 }
5135 *
5136 * * Use the Kernel#proc method as a shorthand of Proc.new:
5137 *
5138 * proc2 = proc {|x| x**2 }
5139 *
5140 * * Receiving a block of code into proc argument (note the <code>&</code>):
5141 *
5142 * def make_proc(&block)
5143 * block
5144 * end
5145 *
5146 * proc3 = make_proc {|x| x**2 }
5147 *
5148 * * Construct a proc with lambda semantics using the Kernel#lambda method
5149 * (see below for explanations about lambdas):
5150 *
5151 * lambda1 = lambda {|x| x**2 }
5152 *
5153 * * Use the {Lambda proc literal}[rdoc-ref:syntax/literals.rdoc@Lambda+Proc+Literals] syntax
5154 * (also constructs a proc with lambda semantics):
5155 *
5156 * lambda2 = ->(x) { x**2 }
5157 *
5158 * == Lambda and non-lambda semantics
5159 *
5160 * Procs are coming in two flavors: lambda and non-lambda (regular procs).
5161 * Differences are:
5162 *
5163 * * In lambdas, +return+ and +break+ means exit from this lambda;
5164 * * In non-lambda procs, +return+ means exit from embracing method
5165 * (and will throw +LocalJumpError+ if invoked outside the method);
5166 * * In non-lambda procs, +break+ means exit from the method which the block given for.
5167 * (and will throw +LocalJumpError+ if invoked after the method returns);
5168 * * In lambdas, arguments are treated in the same way as in methods: strict,
5169 * with +ArgumentError+ for mismatching argument number,
5170 * and no additional argument processing;
5171 * * Regular procs accept arguments more generously: missing arguments
5172 * are filled with +nil+, single Array arguments are deconstructed if the
5173 * proc has multiple arguments, and there is no error raised on extra
5174 * arguments.
5175 *
5176 * Examples:
5177 *
5178 * # +return+ in non-lambda proc, +b+, exits +m2+.
5179 * # (The block +{ return }+ is given for +m1+ and embraced by +m2+.)
5180 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1 { return }; $a << :m2 end; m2; p $a
5181 * #=> []
5182 *
5183 * # +break+ in non-lambda proc, +b+, exits +m1+.
5184 * # (The block +{ break }+ is given for +m1+ and embraced by +m2+.)
5185 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1 { break }; $a << :m2 end; m2; p $a
5186 * #=> [:m2]
5187 *
5188 * # +next+ in non-lambda proc, +b+, exits the block.
5189 * # (The block +{ next }+ is given for +m1+ and embraced by +m2+.)
5190 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1 { next }; $a << :m2 end; m2; p $a
5191 * #=> [:m1, :m2]
5192 *
5193 * # Using +proc+ method changes the behavior as follows because
5194 * # The block is given for +proc+ method and embraced by +m2+.
5195 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1(&proc { return }); $a << :m2 end; m2; p $a
5196 * #=> []
5197 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1(&proc { break }); $a << :m2 end; m2; p $a
5198 * # break from proc-closure (LocalJumpError)
5199 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1(&proc { next }); $a << :m2 end; m2; p $a
5200 * #=> [:m1, :m2]
5201 *
5202 * # +return+, +break+ and +next+ in the stubby lambda exits the block.
5203 * # (+lambda+ method behaves same.)
5204 * # (The block is given for stubby lambda syntax and embraced by +m2+.)
5205 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1(&-> { return }); $a << :m2 end; m2; p $a
5206 * #=> [:m1, :m2]
5207 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1(&-> { break }); $a << :m2 end; m2; p $a
5208 * #=> [:m1, :m2]
5209 * $a = []; def m1(&b) b.call; $a << :m1 end; def m2() m1(&-> { next }); $a << :m2 end; m2; p $a
5210 * #=> [:m1, :m2]
5211 *
5212 * p = proc {|x, y| "x=#{x}, y=#{y}" }
5213 * p.call(1, 2) #=> "x=1, y=2"
5214 * p.call([1, 2]) #=> "x=1, y=2", array deconstructed
5215 * p.call(1, 2, 8) #=> "x=1, y=2", extra argument discarded
5216 * p.call(1) #=> "x=1, y=", nil substituted instead of error
5217 *
5218 * l = lambda {|x, y| "x=#{x}, y=#{y}" }
5219 * l.call(1, 2) #=> "x=1, y=2"
5220 * l.call([1, 2]) # ArgumentError: wrong number of arguments (given 1, expected 2)
5221 * l.call(1, 2, 8) # ArgumentError: wrong number of arguments (given 3, expected 2)
5222 * l.call(1) # ArgumentError: wrong number of arguments (given 1, expected 2)
5223 *
5224 * def test_return
5225 * -> { return 3 }.call # just returns from lambda into method body
5226 * proc { return 4 }.call # returns from method
5227 * return 5
5228 * end
5229 *
5230 * test_return # => 4, return from proc
5231 *
5232 * Lambdas are useful as self-sufficient functions, in particular useful as
5233 * arguments to higher-order functions, behaving exactly like Ruby methods.
5234 *
5235 * Procs are useful for implementing iterators:
5236 *
5237 * def test
5238 * [[1, 2], [3, 4], [5, 6]].map {|a, b| return a if a + b > 10 }
5239 * # ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
5240 * end
5241 *
5242 * Inside +map+, the block of code is treated as a regular (non-lambda) proc,
5243 * which means that the internal arrays will be deconstructed to pairs of
5244 * arguments, and +return+ will exit from the method +test+. That would
5245 * not be possible with a stricter lambda.
5246 *
5247 * You can tell a lambda from a regular proc by using the #lambda? instance method.
5248 *
5249 * Lambda semantics is typically preserved during the proc lifetime, including
5250 * <code>&</code>-deconstruction to a block of code:
5251 *
5252 * p = proc {|x, y| x }
5253 * l = lambda {|x, y| x }
5254 * [[1, 2], [3, 4]].map(&p) #=> [1, 3]
5255 * [[1, 2], [3, 4]].map(&l) # ArgumentError: wrong number of arguments (given 1, expected 2)
5256 *
5257 * The only exception is dynamic method definition: even if defined by
5258 * passing a non-lambda proc, methods still have normal semantics of argument
5259 * checking.
5260 *
5261 * class C
5262 * define_method(:e, &proc {})
5263 * end
5264 * C.new.e(1,2) #=> ArgumentError
5265 * C.new.method(:e).to_proc.lambda? #=> true
5266 *
5267 * This exception ensures that methods never have unusual argument passing
5268 * conventions, and makes it easy to have wrappers defining methods that
5269 * behave as usual.
5270 *
5271 * class C
5272 * def self.def2(name, &body)
5273 * define_method(name, &body)
5274 * end
5275 *
5276 * def2(:f) {}
5277 * end
5278 * C.new.f(1,2) #=> ArgumentError
5279 *
5280 * The wrapper <code>def2</code> receives _body_ as a non-lambda proc,
5281 * yet defines a method which has normal semantics.
5282 *
5283 * == Conversion of other objects to procs
5284 *
5285 * Any object that implements the +to_proc+ method can be converted into
5286 * a proc by the <code>&</code> operator, and therefore can be
5287 * consumed by iterators.
5288 *
5289 * class Greeter
5290 * def initialize(greeting)
5291 * @greeting = greeting
5292 * end
5293 *
5294 * def to_proc
5295 * proc {|name| "#{@greeting}, #{name}!" }
5296 * end
5297 * end
5298 *
5299 * hi = Greeter.new("Hi")
5300 * hey = Greeter.new("Hey")
5301 * ["Bob", "Jane"].map(&hi) #=> ["Hi, Bob!", "Hi, Jane!"]
5302 * ["Bob", "Jane"].map(&hey) #=> ["Hey, Bob!", "Hey, Jane!"]
5303 *
5304 * Of the Ruby core classes, this method is implemented by +Symbol+,
5305 * +Method+, and +Hash+.
5306 *
5307 * :to_s.to_proc.call(1) #=> "1"
5308 * [1, 2].map(&:to_s) #=> ["1", "2"]
5309 *
5310 * method(:puts).to_proc.call(1) # prints 1
5311 * [1, 2].each(&method(:puts)) # prints 1, 2
5312 *
5313 * {test: 1}.to_proc.call(:test) #=> 1
5314 * %i[test many keys].map(&{test: 1}) #=> [1, nil, nil]
5315 *
5316 * == Orphaned Proc
5317 *
5318 * +return+ and +break+ in a block exit a method.
5319 * If a Proc object is generated from the block and the Proc object
5320 * survives until the method is returned, +return+ and +break+ cannot work.
5321 * In such case, +return+ and +break+ raises LocalJumpError.
5322 * A Proc object in such situation is called as orphaned Proc object.
5323 *
5324 * Note that the method to exit is different for +return+ and +break+.
5325 * There is a situation that orphaned for +break+ but not orphaned for +return+.
5326 *
5327 * def m1(&b) b.call end; def m2(); m1 { return } end; m2 # ok
5328 * def m1(&b) b.call end; def m2(); m1 { break } end; m2 # ok
5329 *
5330 * def m1(&b) b end; def m2(); m1 { return }.call end; m2 # ok
5331 * def m1(&b) b end; def m2(); m1 { break }.call end; m2 # LocalJumpError
5332 *
5333 * def m1(&b) b end; def m2(); m1 { return } end; m2.call # LocalJumpError
5334 * def m1(&b) b end; def m2(); m1 { break } end; m2.call # LocalJumpError
5335 *
5336 * Since +return+ and +break+ exits the block itself in lambdas,
5337 * lambdas cannot be orphaned.
5338 *
5339 * == Anonymous block parameters
5340 *
5341 * To simplify writing short blocks, Ruby provides two different types of
5342 * anonymous parameters: +it+ (single parameter) and numbered ones: <tt>_1</tt>,
5343 * <tt>_2</tt> and so on.
5344 *
5345 * # Explicit parameter:
5346 * %w[test me please].each { |str| puts str.upcase } # prints TEST, ME, PLEASE
5347 * (1..5).map { |i| i**2 } # => [1, 4, 9, 16, 25]
5348 *
5349 * # it:
5350 * %w[test me please].each { puts it.upcase } # prints TEST, ME, PLEASE
5351 * (1..5).map { it**2 } # => [1, 4, 9, 16, 25]
5352 *
5353 * # Numbered parameter:
5354 * %w[test me please].each { puts _1.upcase } # prints TEST, ME, PLEASE
5355 * (1..5).map { _1**2 } # => [1, 4, 9, 16, 25]
5356 *
5357 * === +it+
5358 *
5359 * +it+ is a name that is available inside a block when no explicit parameters
5360 * defined, as shown above.
5361 *
5362 * %w[test me please].each { puts it.upcase } # prints TEST, ME, PLEASE
5363 * (1..5).map { it**2 } # => [1, 4, 9, 16, 25]
5364 *
5365 * +it+ is a "soft keyword": it is not a reserved name, and can be used as
5366 * a name for methods and local variables:
5367 *
5368 * it = 5 # no warnings
5369 * def it(&block) # RSpec-like API, no warnings
5370 * # ...
5371 * end
5372 *
5373 * +it+ can be used as a local variable even in blocks that use it as an
5374 * implicit parameter (though this style is obviously confusing):
5375 *
5376 * [1, 2, 3].each {
5377 * # takes a value of implicit parameter "it" and uses it to
5378 * # define a local variable with the same name
5379 * it = it**2
5380 * p it
5381 * }
5382 *
5383 * In a block with explicit parameters defined +it+ usage raises an exception:
5384 *
5385 * [1, 2, 3].each { |x| p it }
5386 * # syntax error found (SyntaxError)
5387 * # [1, 2, 3].each { |x| p it }
5388 * # ^~ 'it' is not allowed when an ordinary parameter is defined
5389 *
5390 * But if a local name (variable or method) is available, it would be used:
5391 *
5392 * it = 5
5393 * [1, 2, 3].each { |x| p it }
5394 * # Prints 5, 5, 5
5395 *
5396 * Blocks using +it+ can be nested:
5397 *
5398 * %w[test me].each { it.each_char { p it } }
5399 * # Prints "t", "e", "s", "t", "m", "e"
5400 *
5401 * Blocks using +it+ are considered to have one parameter:
5402 *
5403 * p = proc { it**2 }
5404 * l = lambda { it**2 }
5405 * p.parameters # => [[:opt]]
5406 * p.arity # => 1
5407 * l.parameters # => [[:req]]
5408 * l.arity # => 1
5409 *
5410 * === Numbered parameters
5411 *
5412 * Numbered parameters are another way to name block parameters implicitly.
5413 * Unlike +it+, numbered parameters allow to refer to several parameters
5414 * in one block.
5415 *
5416 * %w[test me please].each { puts _1.upcase } # prints TEST, ME, PLEASE
5417 * {a: 100, b: 200}.map { "#{_1} = #{_2}" } # => "a = 100", "b = 200"
5418 *
5419 * Parameter names from +_1+ to +_9+ are supported:
5420 *
5421 * [10, 20, 30].zip([40, 50, 60], [70, 80, 90]).map { _1 + _2 + _3 }
5422 * # => [120, 150, 180]
5423 *
5424 * Though, it is advised to resort to them wisely, probably limiting
5425 * yourself to +_1+ and +_2+, and to one-line blocks.
5426 *
5427 * Numbered parameters can't be used together with explicitly named
5428 * ones:
5429 *
5430 * [10, 20, 30].map { |x| _1**2 }
5431 * # SyntaxError (ordinary parameter is defined)
5432 *
5433 * Numbered parameters can't be mixed with +it+ either:
5434 *
5435 * [10, 20, 30].map { _1 + it }
5436 * # SyntaxError: 'it' is not allowed when a numbered parameter is already used
5437 *
5438 * To avoid conflicts, naming local variables or method
5439 * arguments +_1+, +_2+ and so on, causes an error.
5440 *
5441 * _1 = 'test'
5442 * # ^~ _1 is reserved for numbered parameters (SyntaxError)
5443 *
5444 * Using implicit numbered parameters affects block's arity:
5445 *
5446 * p = proc { _1 + _2 }
5447 * l = lambda { _1 + _2 }
5448 * p.parameters # => [[:opt, :_1], [:opt, :_2]]
5449 * p.arity # => 2
5450 * l.parameters # => [[:req, :_1], [:req, :_2]]
5451 * l.arity # => 2
5452 *
5453 * Blocks with numbered parameters can't be nested:
5454 *
5455 * %w[test me].each { _1.each_char { p _1 } }
5456 * # numbered parameter is already used in outer block (SyntaxError)
5457 * # %w[test me].each { _1.each_char { p _1 } }
5458 * # ^~
5459 *
5460 */
5461
5462void
5463Init_Proc(void)
5464{
5465#undef rb_intern
5466 id_refinements_recipe = rb_make_internal_id();
5467
5468 VALUE mRuby = rb_define_module("Ruby");
5469
5470 /* Ruby::SourceRange */
5471 rb_cSourceRange = rb_define_class_under(mRuby, "SourceRange", rb_cObject);
5472 rb_undef_alloc_func(rb_cSourceRange);
5473 rb_undef_method(CLASS_OF(rb_cSourceRange), "new");
5474 rb_define_method(rb_cSourceRange, "path", source_range_path, 0);
5475 rb_define_method(rb_cSourceRange, "absolute_path", source_range_absolute_path, 0);
5476 rb_define_method(rb_cSourceRange, "start_line", source_range_start_line, 0);
5477 rb_define_method(rb_cSourceRange, "start_column", source_range_start_column, 0);
5478 rb_define_method(rb_cSourceRange, "end_line", source_range_end_line, 0);
5479 rb_define_method(rb_cSourceRange, "end_column", source_range_end_column, 0);
5480 rb_define_method(rb_cSourceRange, "inspect", source_range_inspect, 0);
5481
5482 /* Proc */
5483 rb_cProc = rb_define_class("Proc", rb_cObject);
5485 rb_define_singleton_method(rb_cProc, "new", rb_proc_s_new, -1);
5486
5487 rb_add_method_optimized(rb_cProc, idCall, OPTIMIZED_METHOD_TYPE_CALL, 0, METHOD_VISI_PUBLIC);
5488 rb_add_method_optimized(rb_cProc, rb_intern("[]"), OPTIMIZED_METHOD_TYPE_CALL, 0, METHOD_VISI_PUBLIC);
5489 rb_add_method_optimized(rb_cProc, rb_intern("==="), OPTIMIZED_METHOD_TYPE_CALL, 0, METHOD_VISI_PUBLIC);
5490 rb_add_method_optimized(rb_cProc, rb_intern("yield"), OPTIMIZED_METHOD_TYPE_CALL, 0, METHOD_VISI_PUBLIC);
5491
5492#if 0 /* for RDoc */
5493 rb_define_method(rb_cProc, "call", proc_call, -1);
5494 rb_define_method(rb_cProc, "[]", proc_call, -1);
5495 rb_define_method(rb_cProc, "===", proc_call, -1);
5496 rb_define_method(rb_cProc, "yield", proc_call, -1);
5497#endif
5498
5499 rb_define_method(rb_cProc, "to_proc", proc_to_proc, 0);
5500 rb_define_method(rb_cProc, "arity", proc_arity, 0);
5501 rb_define_method(rb_cProc, "clone", proc_clone, 0);
5502 rb_define_method(rb_cProc, "dup", proc_dup, 0);
5503 rb_define_method(rb_cProc, "refined", proc_refined, -1);
5504 rb_define_method(rb_cProc, "hash", proc_hash, 0);
5505 rb_define_method(rb_cProc, "to_s", proc_to_s, 0);
5506 rb_define_alias(rb_cProc, "inspect", "to_s");
5508 rb_define_method(rb_cProc, "binding", proc_binding, 0);
5509 rb_define_method(rb_cProc, "curry", proc_curry, -1);
5510 rb_define_method(rb_cProc, "<<", proc_compose_to_left, 1);
5511 rb_define_method(rb_cProc, ">>", proc_compose_to_right, 1);
5512 rb_define_method(rb_cProc, "==", rb_proc_eq, 1);
5513 rb_define_method(rb_cProc, "eql?", rb_proc_eq, 1);
5514 rb_define_method(rb_cProc, "source_location", rb_proc_location, 0);
5515 rb_define_method(rb_cProc, "source_range", rb_proc_source_range, 0);
5516 rb_define_method(rb_cProc, "parameters", rb_proc_parameters, -1);
5517 rb_define_method(rb_cProc, "ruby2_keywords", proc_ruby2_keywords, 0);
5518
5519 /* Exceptions */
5520 rb_eLocalJumpError = rb_define_class("LocalJumpError", rb_eStandardError);
5521 rb_define_method(rb_eLocalJumpError, "exit_value", localjump_xvalue, 0);
5522 rb_define_method(rb_eLocalJumpError, "reason", localjump_reason, 0);
5523
5524 rb_eSysStackError = rb_define_class("SystemStackError", rb_eException);
5525 rb_vm_register_special_exception(ruby_error_sysstack, rb_eSysStackError, "stack level too deep");
5526
5527 /* utility functions */
5528 rb_define_global_function("proc", f_proc, 0);
5529 rb_define_global_function("lambda", f_lambda, 0);
5530
5531 /* Method */
5532 rb_cMethod = rb_define_class("Method", rb_cObject);
5535 rb_define_method(rb_cMethod, "==", method_eq, 1);
5536 rb_define_method(rb_cMethod, "eql?", method_eq, 1);
5537 rb_define_method(rb_cMethod, "hash", method_hash, 0);
5538 rb_define_method(rb_cMethod, "clone", method_clone, 0);
5539 rb_define_method(rb_cMethod, "dup", method_dup, 0);
5540 rb_define_method(rb_cMethod, "call", rb_method_call_pass_called_kw, -1);
5541 rb_define_method(rb_cMethod, "===", rb_method_call_pass_called_kw, -1);
5542 rb_define_method(rb_cMethod, "curry", rb_method_curry, -1);
5543 rb_define_method(rb_cMethod, "<<", rb_method_compose_to_left, 1);
5544 rb_define_method(rb_cMethod, ">>", rb_method_compose_to_right, 1);
5545 rb_define_method(rb_cMethod, "[]", rb_method_call_pass_called_kw, -1);
5546 rb_define_method(rb_cMethod, "arity", method_arity_m, 0);
5547 rb_define_method(rb_cMethod, "inspect", method_inspect, 0);
5548 rb_define_method(rb_cMethod, "to_s", method_inspect, 0);
5549 rb_define_method(rb_cMethod, "to_proc", method_to_proc, 0);
5550 rb_define_method(rb_cMethod, "receiver", method_receiver, 0);
5551 rb_define_method(rb_cMethod, "name", method_name, 0);
5552 rb_define_method(rb_cMethod, "original_name", method_original_name, 0);
5553 rb_define_method(rb_cMethod, "owner", method_owner, 0);
5554 rb_define_method(rb_cMethod, "unbind", method_unbind, 0);
5555 rb_define_method(rb_cMethod, "source_location", rb_method_location, 0);
5556 rb_define_method(rb_cMethod, "source_range", rb_method_source_range, 0);
5557 rb_define_method(rb_cMethod, "parameters", rb_method_parameters, 0);
5558 rb_define_method(rb_cMethod, "super_method", method_super_method, 0);
5560 rb_define_method(rb_mKernel, "public_method", rb_obj_public_method, 1);
5561 rb_define_method(rb_mKernel, "singleton_method", rb_obj_singleton_method, 1);
5562
5563 rb_define_method(rb_cMethod, "box", method_box, 0);
5564
5565 /* UnboundMethod */
5566 rb_cUnboundMethod = rb_define_class("UnboundMethod", rb_cObject);
5569 rb_define_method(rb_cUnboundMethod, "==", unbound_method_eq, 1);
5570 rb_define_method(rb_cUnboundMethod, "eql?", unbound_method_eq, 1);
5571 rb_define_method(rb_cUnboundMethod, "hash", method_hash, 0);
5572 rb_define_method(rb_cUnboundMethod, "clone", method_clone, 0);
5573 rb_define_method(rb_cUnboundMethod, "dup", method_dup, 0);
5574 rb_define_method(rb_cUnboundMethod, "arity", method_arity_m, 0);
5575 rb_define_method(rb_cUnboundMethod, "inspect", method_inspect, 0);
5576 rb_define_method(rb_cUnboundMethod, "to_s", method_inspect, 0);
5577 rb_define_method(rb_cUnboundMethod, "name", method_name, 0);
5578 rb_define_method(rb_cUnboundMethod, "original_name", method_original_name, 0);
5579 rb_define_method(rb_cUnboundMethod, "owner", method_owner, 0);
5580 rb_define_method(rb_cUnboundMethod, "bind", umethod_bind, 1);
5581 rb_define_method(rb_cUnboundMethod, "bind_call", umethod_bind_call, -1);
5582 rb_define_method(rb_cUnboundMethod, "source_location", rb_method_location, 0);
5583 rb_define_method(rb_cUnboundMethod, "source_range", rb_method_source_range, 0);
5584 rb_define_method(rb_cUnboundMethod, "parameters", rb_method_parameters, 0);
5585 rb_define_method(rb_cUnboundMethod, "super_method", method_super_method, 0);
5586
5587 /* Module#*_method */
5588 rb_define_method(rb_cModule, "instance_method", rb_mod_instance_method, 1);
5589 rb_define_method(rb_cModule, "public_instance_method", rb_mod_public_instance_method, 1);
5590 rb_define_method(rb_cModule, "define_method", rb_mod_define_method, -1);
5591
5592 /* Kernel */
5593 rb_define_method(rb_mKernel, "define_singleton_method", rb_obj_define_method, -1);
5594
5596 "define_method", top_define_method, -1);
5597}
5598
5599/*
5600 * Objects of class Binding encapsulate the execution context at some
5601 * particular place in the code and retain this context for future
5602 * use. The variables, methods, value of <code>self</code>, and
5603 * possibly an iterator block that can be accessed in this context
5604 * are all retained. Binding objects can be created using
5605 * Kernel#binding, and are made available to the callback of
5606 * Kernel#set_trace_func and instances of TracePoint.
5607 *
5608 * These binding objects can be passed as the second argument of the
5609 * Kernel#eval method, establishing an environment for the
5610 * evaluation.
5611 *
5612 * class Demo
5613 * def initialize(n)
5614 * @secret = n
5615 * end
5616 * def get_binding
5617 * binding
5618 * end
5619 * end
5620 *
5621 * k1 = Demo.new(99)
5622 * b1 = k1.get_binding
5623 * k2 = Demo.new(-3)
5624 * b2 = k2.get_binding
5625 *
5626 * eval("@secret", b1) #=> 99
5627 * eval("@secret", b2) #=> -3
5628 * eval("@secret") #=> nil
5629 *
5630 * Binding objects have no class-specific methods.
5631 *
5632 */
5633
5634void
5635Init_Binding(void)
5636{
5637 rb_gc_register_address(&sym_proc_cache);
5638
5639 rb_cBinding = rb_define_class("Binding", rb_cObject);
5642 rb_define_method(rb_cBinding, "clone", binding_clone, 0);
5643 rb_define_method(rb_cBinding, "dup", binding_dup, 0);
5644 rb_define_method(rb_cBinding, "eval", bind_eval, -1);
5645 rb_define_method(rb_cBinding, "local_variables", bind_local_variables, 0);
5646 rb_define_method(rb_cBinding, "local_variable_get", bind_local_variable_get, 1);
5647 rb_define_method(rb_cBinding, "local_variable_set", bind_local_variable_set, 2);
5648 rb_define_method(rb_cBinding, "local_variable_defined?", bind_local_variable_defined_p, 1);
5649 rb_define_method(rb_cBinding, "implicit_parameters", bind_implicit_parameters, 0);
5650 rb_define_method(rb_cBinding, "implicit_parameter_get", bind_implicit_parameter_get, 1);
5651 rb_define_method(rb_cBinding, "implicit_parameter_defined?", bind_implicit_parameter_defined_p, 1);
5652 rb_define_method(rb_cBinding, "receiver", bind_receiver, 0);
5653 rb_define_method(rb_cBinding, "source_location", bind_location, 0);
5654 rb_define_global_function("binding", rb_f_binding, 0);
5655}
#define rb_define_method(klass, mid, func, arity)
Defines klass#mid.
#define rb_define_singleton_method(klass, mid, func, arity)
Defines klass.mid.
#define rb_define_private_method(klass, mid, func, arity)
Defines klass#mid and makes it private.
#define rb_define_global_function(mid, func, arity)
Defines rb_mKernel #mid.
VALUE rb_singleton_class(VALUE obj)
Finds or creates the singleton class of the passed object.
Definition class.c:3025
VALUE rb_singleton_class_get(VALUE obj)
Returns the singleton class of obj, or nil if obj is not a singleton object.
Definition class.c:3011
void rb_define_alias(VALUE klass, const char *name1, const char *name2)
Defines an alias of a method.
Definition class.c:3068
void rb_undef_method(VALUE klass, const char *name)
Defines an undef of a method.
Definition class.c:2871
int rb_scan_args(int argc, const VALUE *argv, const char *fmt,...)
Retrieves argument from argc and argv to given VALUE references according to the format string.
Definition class.c:3358
int rb_block_given_p(void)
Determines if the current method is given a block.
Definition eval.c:1041
int rb_get_kwargs(VALUE keyword_hash, const ID *table, int required, int optional, VALUE *values)
Keyword argument deconstructor.
Definition class.c:3147
#define rb_str_buf_cat2
Old name of rb_usascii_str_new_cstr.
Definition string.h:1707
#define Qundef
Old name of RUBY_Qundef.
#define INT2FIX
Old name of RB_INT2FIX.
Definition long.h:48
#define ID2SYM
Old name of RB_ID2SYM.
Definition symbol.h:44
#define OBJ_FREEZE
Old name of RB_OBJ_FREEZE.
Definition fl_type.h:131
#define UNREACHABLE_RETURN
Old name of RBIMPL_UNREACHABLE_RETURN.
Definition assume.h:29
#define SYM2ID
Old name of RB_SYM2ID.
Definition symbol.h:45
#define ZALLOC
Old name of RB_ZALLOC.
Definition memory.h:405
#define CLASS_OF
Old name of rb_class_of.
Definition globals.h:205
#define rb_ary_new4
Old name of rb_ary_new_from_values.
Definition array.h:659
#define FIX2INT
Old name of RB_FIX2INT.
Definition int.h:41
#define T_MODULE
Old name of RUBY_T_MODULE.
Definition value_type.h:70
#define ASSUME
Old name of RBIMPL_ASSUME.
Definition assume.h:27
#define T_ICLASS
Old name of RUBY_T_ICLASS.
Definition value_type.h:66
#define ALLOC_N
Old name of RB_ALLOC_N.
Definition memory.h:402
#define FL_TEST_RAW
Old name of RB_FL_TEST_RAW.
Definition fl_type.h:128
#define rb_ary_new3
Old name of rb_ary_new_from_args.
Definition array.h:658
#define Qtrue
Old name of RUBY_Qtrue.
#define ST2FIX
Old name of RB_ST2FIX.
Definition st_data_t.h:33
#define NUM2INT
Old name of RB_NUM2INT.
Definition int.h:44
#define INT2NUM
Old name of RB_INT2NUM.
Definition int.h:43
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define NIL_P
Old name of RB_NIL_P.
#define T_CLASS
Old name of RUBY_T_CLASS.
Definition value_type.h:58
#define BUILTIN_TYPE
Old name of RB_BUILTIN_TYPE.
Definition value_type.h:85
#define Check_TypedStruct(v, t)
Old name of rb_check_typeddata.
Definition rtypeddata.h:109
#define CONST_ID
Old name of RUBY_CONST_ID.
Definition symbol.h:47
#define rb_ary_new2
Old name of rb_ary_new_capa.
Definition array.h:657
VALUE rb_eLocalJumpError
LocalJumpError exception.
Definition eval.c:50
void rb_category_warn(rb_warning_category_t category, const char *fmt,...)
Identical to rb_category_warning(), except it reports unless $VERBOSE is nil.
Definition error.c:474
void rb_exc_raise(VALUE mesg)
Raises an exception in the current thread.
Definition eval.c:678
VALUE rb_eStandardError
StandardError exception.
Definition error.c:1454
VALUE rb_eRangeError
RangeError exception.
Definition error.c:1461
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1457
void rb_warn(const char *fmt,...)
Identical to rb_warning(), except it reports unless $VERBOSE is nil.
Definition error.c:464
VALUE rb_exc_new_str(VALUE etype, VALUE str)
Identical to rb_exc_new_cstr(), except it takes a Ruby's string instead of C's.
Definition error.c:1508
VALUE rb_eException
Mother of all exceptions.
Definition error.c:1449
VALUE rb_eSysStackError
SystemStackError exception.
Definition eval.c:51
@ RB_WARN_CATEGORY_PERFORMANCE
Warning is for performance issues (not enabled by -w).
Definition error.h:54
VALUE rb_class_superclass(VALUE klass)
Queries the parent of the given class.
Definition object.c:2320
VALUE rb_cUnboundMethod
UnboundMethod class.
Definition proc.c:43
VALUE rb_mKernel
Kernel module.
Definition object.c:59
VALUE rb_cObject
Object class.
Definition object.c:60
VALUE rb_obj_hide(VALUE obj)
Make the object invisible from Ruby code.
Definition object.c:94
VALUE rb_cBinding
Binding class.
Definition proc.c:45
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
Definition object.c:230
VALUE rb_inspect(VALUE obj)
Generates a human-readable textual representation of the given object.
Definition object.c:665
VALUE rb_cModule
Module class.
Definition object.c:61
VALUE rb_class_inherited_p(VALUE scion, VALUE ascendant)
Determines if the given two modules are relatives.
Definition object.c:1839
VALUE rb_obj_is_kind_of(VALUE obj, VALUE klass)
Queries if the given object is an instance (of possibly descendants) of the given class.
Definition object.c:902
VALUE rb_cProc
Proc class.
Definition proc.c:46
VALUE rb_cMethod
Method class.
Definition proc.c:44
#define RB_OBJ_WRITTEN(old, oldv, young)
Identical to RB_OBJ_WRITE(), except it doesn't write any values, but only a WB declaration.
Definition gc.h:504
#define RB_OBJ_WRITE(old, slot, young)
Declaration of a "back" pointer.
Definition gc.h:492
#define RUBY_ASSERT(...)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
Definition assert.h:219
VALUE rb_funcall(VALUE recv, ID mid, int n,...)
Calls a method.
Definition vm_eval.c:1149
VALUE rb_funcallv(VALUE recv, ID mid, int argc, const VALUE *argv)
Identical to rb_funcall(), except it takes the method arguments as a C array.
Definition vm_eval.c:1107
VALUE rb_funcall_with_block_kw(VALUE recv, ID mid, int argc, const VALUE *argv, VALUE procval, int kw_splat)
Identical to rb_funcallv_with_block(), except you can specify how to handle the last element of the g...
Definition vm_eval.c:1236
VALUE rb_ary_dup(VALUE ary)
Duplicates an array.
void rb_ary_store(VALUE ary, rb_len_t key, VALUE val)
Destructively stores the passed value to the passed array's passed index.
VALUE rb_ary_plus(VALUE lhs, VALUE rhs)
Creates a new array, concatenating the former to the latter.
VALUE rb_ary_new(void)
Allocates a new, empty array.
VALUE rb_ary_hidden_new(rb_len_t capa)
Allocates a hidden (no class) empty array.
VALUE rb_ary_push(VALUE ary, VALUE elem)
Special case of rb_ary_cat() that it adds only one element.
VALUE rb_ary_freeze(VALUE obj)
Freeze an array, preventing further modifications.
#define UNLIMITED_ARGUMENTS
This macro is used in conjunction with rb_check_arity().
Definition error.h:35
static int rb_check_arity(int argc, int min, int max)
Ensures that the passed integer is in the passed range.
Definition error.h:284
int rb_is_local_id(ID id)
Classifies the given ID, then sees if it is a local variable.
Definition symbol.c:1272
VALUE rb_method_call_with_block(int argc, const VALUE *argv, VALUE recv, VALUE proc)
Identical to rb_proc_call(), except you can additionally pass a proc as a block.
Definition proc.c:3467
int rb_obj_method_arity(VALUE obj, ID mid)
Identical to rb_mod_method_arity(), except it searches for singleton methods rather than instance met...
Definition proc.c:3855
VALUE rb_proc_call(VALUE recv, VALUE args)
Evaluates the passed proc with the passed arguments.
Definition proc.c:1749
VALUE rb_proc_call_with_block_kw(VALUE recv, int argc, const VALUE *argv, VALUE proc, int kw_splat)
Identical to rb_proc_call_with_block(), except you can specify how to handle the last element of the ...
Definition proc.c:1761
VALUE rb_method_call_kw(int argc, const VALUE *argv, VALUE recv, int kw_splat)
Identical to rb_method_call(), except you can specify how to handle the last element of the given arr...
Definition proc.c:3424
VALUE rb_obj_method(VALUE recv, VALUE mid)
Creates a method object.
Definition proc.c:3002
VALUE rb_proc_lambda_p(VALUE recv)
Queries if the given object is a lambda.
Definition proc.c:828
VALUE rb_block_proc(void)
Constructs a Proc object from implicitly passed components.
Definition proc.c:1586
VALUE rb_proc_call_with_block(VALUE recv, int argc, const VALUE *argv, VALUE proc)
Identical to rb_proc_call(), except you can additionally pass another proc object,...
Definition proc.c:1774
int rb_mod_method_arity(VALUE mod, ID mid)
Queries the number of mandatory arguments of the method defined in the given module.
Definition proc.c:3847
VALUE rb_method_call_with_block_kw(int argc, const VALUE *argv, VALUE recv, VALUE proc, int kw_splat)
Identical to rb_method_call_with_block(), except you can specify how to handle the last element of th...
Definition proc.c:3454
VALUE rb_obj_is_method(VALUE recv)
Queries if the given object is a method.
Definition proc.c:2475
VALUE rb_block_lambda(void)
Identical to rb_proc_new(), except it returns a lambda.
Definition proc.c:1605
VALUE rb_proc_call_kw(VALUE recv, VALUE args, int kw_splat)
Identical to rb_proc_call(), except you can specify how to handle the last element of the given array...
Definition proc.c:1728
VALUE rb_binding_new(void)
Snapshots the current execution context and turn it into an instance of rb_cBinding.
Definition proc.c:912
int rb_proc_arity(VALUE recv)
Queries the number of mandatory arguments of the given Proc.
Definition proc.c:1881
VALUE rb_method_call(int argc, const VALUE *argv, VALUE recv)
Evaluates the passed method with the passed arguments.
Definition proc.c:3431
VALUE rb_obj_is_proc(VALUE recv)
Queries if the given object is a proc.
Definition proc.c:392
#define rb_hash_uint(h, i)
Just another name of st_hash_uint.
Definition string.h:967
#define rb_hash_end(h)
Just another name of st_hash_end.
Definition string.h:970
VALUE rb_str_append(VALUE dst, VALUE src)
Identical to rb_str_buf_append(), except it converts the right hand side before concatenating.
Definition string.c:3947
void rb_str_set_len(VALUE str, rb_len_t len)
Overwrites the length of the string.
Definition string.c:3529
VALUE rb_str_buf_append(VALUE dst, VALUE src)
Identical to rb_str_cat_cstr(), except it takes Ruby's string instead of C's.
Definition string.c:3911
st_index_t rb_hash_start(st_index_t i)
Starts a series of hashing.
Definition random.c:1714
#define rb_str_cat_cstr(buf, str)
Identical to rb_str_cat(), except it assumes the passed pointer is a pointer to a C string.
Definition string.h:1681
#define rb_str_new_cstr(str)
Identical to rb_str_new, except it assumes the passed pointer is a pointer to a C string.
Definition string.h:1539
VALUE rb_str_intern(VALUE str)
Identical to rb_to_symbol(), except it assumes the receiver being an instance of RString.
Definition symbol.c:1091
VALUE rb_ivar_set(VALUE obj, ID name, VALUE val)
Identical to rb_iv_set(), except it accepts the name as an ID instead of a C string.
Definition variable.c:2168
VALUE rb_ivar_get(VALUE obj, ID name)
Identical to rb_iv_get(), except it accepts the name as an ID instead of a C string.
Definition variable.c:1651
void rb_undef_alloc_func(VALUE klass)
Deletes the allocator function of a class.
Definition vm_method.c:1892
int rb_method_basic_definition_p(VALUE klass, ID mid)
Well... Let us hesitate from describing what a "basic definition" is.
Definition vm_method.c:3629
int rb_obj_respond_to(VALUE obj, ID mid, int private_p)
Identical to rb_respond_to(), except it additionally takes the visibility parameter.
Definition vm_method.c:3735
ID rb_check_id(volatile VALUE *namep)
Detects if the given name is already interned or not.
Definition symbol.c:1296
VALUE rb_sym2str(VALUE symbol)
Obtain a frozen string representation of a symbol (not including the leading colon).
Definition symbol.c:1155
ID rb_to_id(VALUE str)
Identical to rb_intern_str(), except it tries to convert the parameter object to an instance of rb_cS...
Definition string.c:16272
VALUE rb_iv_get(VALUE obj, const char *name)
Obtains an instance variable.
Definition variable.c:4597
int len
Length of the buffer.
Definition io.h:8
#define RB_OBJ_SET_SHAREABLE(obj)
Wrapper of rb_obj_set_shareable().
Definition ractor.h:290
#define RB_INT2NUM
Just another name of rb_int2num_inline.
Definition int.h:37
#define RB_BLOCK_CALL_FUNC_ARGLIST(yielded_arg, callback_arg)
Shim for block function parameters.
Definition iterator.h:58
rb_block_call_func * rb_block_call_func_t
Shorthand type that represents an iterator-written-in-C function pointer.
Definition iterator.h:88
VALUE rb_block_call_func(RB_BLOCK_CALL_FUNC_ARGLIST(yielded_arg, callback_arg))
This is the type of a function that the interpreter expect for C-backended blocks.
Definition iterator.h:83
#define MEMCPY(p1, p2, type, n)
Handy macro to call memcpy.
Definition memory.h:375
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
Definition memory.h:170
VALUE rb_block_call(VALUE q, ID w, int e, const VALUE *r, type *t, VALUE y)
Call a method with a block.
VALUE rb_proc_new(type *q, VALUE w)
Creates a rb_cProc instance.
VALUE type(ANYARGS)
ANYARGS-ed function type.
VALUE rb_rescue(type *q, VALUE w, type *e, VALUE r)
An equivalent of rescue clause.
#define RARRAY_LEN
Just another name of rb_array_len.
Definition rarray.h:50
static VALUE * RARRAY_PTR(VALUE ary)
Wild use of a C pointer.
Definition rarray.h:365
#define RARRAY_AREF(a, i)
References an object in an array.
Definition rarray.h:422
static void RARRAY_ASET(VALUE ary, rb_len_t i, VALUE v)
Assigns an object in an array.
Definition rarray.h:386
#define RARRAY_CONST_PTR
Just another name of rb_array_const_ptr.
Definition rarray.h:51
static VALUE RBASIC_CLASS(VALUE obj)
Queries the class of an object.
Definition rbasic.h:166
#define RBASIC(obj)
Convenient casting macro.
Definition rbasic.h:40
#define RCLASS_SUPER
Just another name of rb_class_get_superclass.
Definition rclass.h:44
#define RUBY_TYPED_DEFAULT_FREE
This is a value you can set to rb_data_type_struct::dfree.
Definition rtypeddata.h:81
#define RUBY_TYPED_FREE_IMMEDIATELY
Macros to see if each corresponding flag is defined.
Definition rtypeddata.h:122
#define TypedData_Get_Struct(obj, type, data_type, sval)
Obtains a C struct from inside of a wrapper Ruby object.
Definition rtypeddata.h:773
struct rb_data_type_struct rb_data_type_t
This is the struct that holds necessary info for a struct.
Definition rtypeddata.h:239
#define TypedData_Make_Struct(klass, type, data_type, sval)
Identical to TypedData_Wrap_Struct, except it allocates a new data region internally instead of takin...
Definition rtypeddata.h:604
const char * rb_obj_classname(VALUE obj)
Queries the name of the class of the passed object.
Definition variable.c:532
#define RB_PASS_CALLED_KEYWORDS
Pass keywords if current method is called with keywords, useful for argument delegation.
Definition scan_args.h:78
#define RB_NO_KEYWORDS
Do not pass keywords.
Definition scan_args.h:69
#define RTEST
This is an old name of RB_TEST.
#define _(args)
This was a transition path from K&R to ANSI.
Definition stdarg.h:35
Definition proc.c:31
rb_cref_t * cref
class reference, should be marked
Definition method.h:144
const rb_iseq_t * iseqptr
iseq pointer, should be separated from iseqval
Definition method.h:143
IFUNC (Internal FUNCtion).
Definition imemo.h:89
long rb_len_t
A signed integer type for lengths and indices of objects such as String and Array.
Definition value.h:142
unsigned long rb_ulen_t
An unsigned integer type that has the same width with rb_len_t.
Definition value.h:145
uintptr_t ID
Type that represents a Ruby identifier such as a variable name.
Definition value.h:52
#define SIZEOF_VALUE
Identical to sizeof(VALUE), except it is a macro that can also be used inside of preprocessor directi...
Definition value.h:69
uintptr_t VALUE
Type that represents a Ruby object.
Definition value.h:40
static void Check_Type(VALUE v, enum ruby_value_type t)
Identical to RB_TYPE_P(), except it raises exceptions on predication failure.
Definition value_type.h:425
static bool RB_TYPE_P(VALUE obj, enum ruby_value_type t)
Queries if the given object is of given type.
Definition value_type.h:376