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