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