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