Ruby  3.4.0dev (2024-11-22 revision 801e66352e698eb533c535f600d958bc1e07e75e)
eval.c (801e66352e698eb533c535f600d958bc1e07e75e)
1 /**********************************************************************
2 
3  eval.c -
4 
5  $Author$
6  created at: Thu Jun 10 14:22:17 JST 1993
7 
8  Copyright (C) 1993-2007 Yukihiro Matsumoto
9  Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
10  Copyright (C) 2000 Information-technology Promotion Agency, Japan
11 
12 **********************************************************************/
13 
14 #include "ruby/internal/config.h"
15 
16 #ifdef HAVE_SYS_PRCTL_H
17 #include <sys/prctl.h>
18 #endif
19 
20 #include "eval_intern.h"
21 #include "internal.h"
22 #include "internal/class.h"
23 #include "internal/cont.h"
24 #include "internal/error.h"
25 #include "internal/eval.h"
26 #include "internal/gc.h"
27 #include "internal/hash.h"
28 #include "internal/inits.h"
29 #include "internal/io.h"
30 #include "internal/object.h"
31 #include "internal/thread.h"
32 #include "internal/variable.h"
33 #include "ruby/fiber/scheduler.h"
34 #include "iseq.h"
35 #include "rjit.h"
36 #include "probes.h"
37 #include "probes_helper.h"
38 #include "ruby/vm.h"
39 #include "vm_core.h"
40 #include "ractor_core.h"
41 
42 NORETURN(static void rb_raise_jump(VALUE, VALUE));
43 void rb_ec_clear_current_thread_trace_func(const rb_execution_context_t *ec);
44 void rb_ec_clear_all_trace_func(const rb_execution_context_t *ec);
45 
46 static int rb_ec_cleanup(rb_execution_context_t *ec, enum ruby_tag_type ex);
47 static int rb_ec_exec_node(rb_execution_context_t *ec, void *n);
48 
51 
52 ID ruby_static_id_signo, ruby_static_id_status;
53 extern ID ruby_static_id_cause;
54 #define id_cause ruby_static_id_cause
55 
56 #define exception_error GET_VM()->special_exceptions[ruby_error_reenter]
57 
58 #include "eval_error.c"
59 #include "eval_jump.c"
60 
61 #define CLASS_OR_MODULE_P(obj) \
62  (!SPECIAL_CONST_P(obj) && \
63  (BUILTIN_TYPE(obj) == T_CLASS || BUILTIN_TYPE(obj) == T_MODULE))
64 
65 int
67 {
68  enum ruby_tag_type state;
69 
70  if (GET_VM())
71  return 0;
72 
73  /*
74  * Disable THP early before mallocs happen because we want this to
75  * affect as many future pages as possible for CoW-friendliness
76  */
77 #if defined(__linux__) && defined(PR_SET_THP_DISABLE)
78  prctl(PR_SET_THP_DISABLE, 1, 0, 0, 0);
79 #endif
80  Init_BareVM();
81  rb_vm_encoded_insn_data_table_init();
82  Init_vm_objects();
83 
84  EC_PUSH_TAG(GET_EC());
85  if ((state = EC_EXEC_TAG()) == TAG_NONE) {
86  rb_call_inits();
88  GET_VM()->running = 1;
89  }
90  EC_POP_TAG();
91 
92  return state;
93 }
94 
95 void
96 ruby_init(void)
97 {
98  int state = ruby_setup();
99  if (state) {
100  if (RTEST(ruby_debug)) {
101  rb_execution_context_t *ec = GET_EC();
102  rb_ec_error_print(ec, ec->errinfo);
103  }
104  exit(EXIT_FAILURE);
105  }
106 }
107 
108 void *
109 ruby_options(int argc, char **argv)
110 {
111  rb_execution_context_t *ec = GET_EC();
112  enum ruby_tag_type state;
113  void *volatile iseq = 0;
114 
115  EC_PUSH_TAG(ec);
116  if ((state = EC_EXEC_TAG()) == TAG_NONE) {
117  iseq = ruby_process_options(argc, argv);
118  }
119  else {
120  rb_ec_clear_current_thread_trace_func(ec);
121  int exitcode = error_handle(ec, ec->errinfo, state);
122  ec->errinfo = Qnil; /* just been handled */
123  iseq = (void *)INT2FIX(exitcode);
124  }
125  EC_POP_TAG();
126  return iseq;
127 }
128 
129 static void
130 rb_ec_fiber_scheduler_finalize(rb_execution_context_t *ec)
131 {
132  enum ruby_tag_type state;
133 
134  EC_PUSH_TAG(ec);
135  if ((state = EC_EXEC_TAG()) == TAG_NONE) {
137  }
138  else {
139  state = error_handle(ec, ec->errinfo, state);
140  }
141  EC_POP_TAG();
142 }
143 
144 static void
145 rb_ec_teardown(rb_execution_context_t *ec)
146 {
147  // If the user code defined a scheduler for the top level thread, run it:
148  rb_ec_fiber_scheduler_finalize(ec);
149 
150  EC_PUSH_TAG(ec);
151  if (EC_EXEC_TAG() == TAG_NONE) {
152  rb_vm_trap_exit(rb_ec_vm_ptr(ec));
153  }
154  EC_POP_TAG();
155  rb_ec_exec_end_proc(ec);
156  rb_ec_clear_all_trace_func(ec);
157 }
158 
159 static void
160 rb_ec_finalize(rb_execution_context_t *ec)
161 {
163  ec->errinfo = Qnil;
164  rb_objspace_call_finalizer();
165 }
166 
167 void
169 {
170  rb_execution_context_t *ec = GET_EC();
171  rb_ec_teardown(ec);
172  rb_ec_finalize(ec);
173 }
174 
175 int
177 {
178  return rb_ec_cleanup(GET_EC(), (enum ruby_tag_type)ex);
179 }
180 
181 static int
182 rb_ec_cleanup(rb_execution_context_t *ec, enum ruby_tag_type ex)
183 {
184  int state;
185  volatile VALUE save_error = Qundef;
186  volatile int sysex = EXIT_SUCCESS;
187  volatile int signaled = 0;
188  rb_thread_t *th = rb_ec_thread_ptr(ec);
189  rb_thread_t *const volatile th0 = th;
190  volatile int step = 0;
191  volatile VALUE message = Qnil;
192  VALUE buf;
193 
194  rb_threadptr_interrupt(th);
195  rb_threadptr_check_signal(th);
196 
197  EC_PUSH_TAG(ec);
198  if ((state = EC_EXEC_TAG()) == TAG_NONE) {
199  RUBY_VM_CHECK_INTS(ec);
200 
201  step_0: step++;
202  save_error = ec->errinfo;
203  if (THROW_DATA_P(ec->errinfo)) ec->errinfo = Qnil;
204 
205  /* exits with failure but silently when an exception raised
206  * here */
207  rb_ec_teardown(ec);
208 
209  step_1: step++;
210  VALUE err = ec->errinfo;
211  volatile int mode0 = 0, mode1 = 0;
212  if (err != save_error && !NIL_P(err)) {
213  mode0 = exiting_split(err, &sysex, &signaled);
214  }
215 
216  /* exceptions after here will be ignored */
217 
218  /* build error message including causes */
219  err = ATOMIC_VALUE_EXCHANGE(save_error, Qnil);
220 
221  if (!NIL_P(err) && !THROW_DATA_P(err)) {
222  mode1 = exiting_split(err, (mode0 & EXITING_WITH_STATUS) ? NULL : &sysex, &signaled);
223  if (mode1 & EXITING_WITH_MESSAGE) {
224  buf = rb_str_new(NULL, 0);
225  rb_ec_error_print_detailed(ec, err, buf, Qundef);
226  message = buf;
227  }
228  }
229 
230  step_2: step++;
231  /* protect from Thread#raise */
232  th->status = THREAD_KILLED;
233 
234  rb_ractor_terminate_all();
235 
236  step_3: step++;
237  if (!NIL_P(buf = message)) {
238  warn_print_str(buf);
239  }
240  else if (!NIL_OR_UNDEF_P(err = save_error) ||
241  (ex != TAG_NONE && !((mode0|mode1) & EXITING_WITH_STATUS))) {
242  sysex = error_handle(ec, err, ex);
243  }
244  }
245  else {
246  th = th0;
247  switch (step) {
248  case 0: goto step_0;
249  case 1: goto step_1;
250  case 2: goto step_2;
251  case 3: goto step_3;
252  }
253  }
254 
255  rb_ec_finalize(ec);
256 
257  /* unlock again if finalizer took mutexes. */
258  rb_threadptr_unlock_all_locking_mutexes(th);
259  th = th0;
260  EC_POP_TAG();
261  th = th0;
262  rb_thread_stop_timer_thread();
263  ruby_vm_destruct(th->vm);
264  // For YJIT, call this after ruby_vm_destruct() frees jit_cont for the root fiber.
265  rb_jit_cont_finish();
266 
267  if (signaled) ruby_default_signal(signaled);
268 
269  return sysex;
270 }
271 
272 static int
273 rb_ec_exec_node(rb_execution_context_t *ec, void *n)
274 {
275  volatile int state;
276  rb_iseq_t *iseq = (rb_iseq_t *)n;
277  if (!n) return 0;
278 
279  EC_PUSH_TAG(ec);
280  if ((state = EC_EXEC_TAG()) == TAG_NONE) {
281  rb_iseq_eval_main(iseq);
282  }
283  EC_POP_TAG();
284  return state;
285 }
286 
287 void
288 ruby_stop(int ex)
289 {
290  exit(ruby_cleanup(ex));
291 }
292 
293 int
294 ruby_executable_node(void *n, int *status)
295 {
296  VALUE v = (VALUE)n;
297  int s;
298 
299  switch (v) {
300  case Qtrue: s = EXIT_SUCCESS; break;
301  case Qfalse: s = EXIT_FAILURE; break;
302  default:
303  if (!FIXNUM_P(v)) return TRUE;
304  s = FIX2INT(v);
305  }
306  if (status) *status = s;
307  return FALSE;
308 }
309 
310 int
312 {
313  rb_execution_context_t *ec = GET_EC();
314  int status;
315  if (!ruby_executable_node(n, &status)) {
316  rb_ec_cleanup(ec, (NIL_P(ec->errinfo) ? TAG_NONE : TAG_RAISE));
317  return status;
318  }
319  return rb_ec_cleanup(ec, rb_ec_exec_node(ec, n));
320 }
321 
322 int
324 {
325  return rb_ec_exec_node(GET_EC(), n);
326 }
327 
328 /*
329  * call-seq:
330  * Module.nesting -> array
331  *
332  * Returns the list of +Modules+ nested at the point of call.
333  *
334  * module M1
335  * module M2
336  * $a = Module.nesting
337  * end
338  * end
339  * $a #=> [M1::M2, M1]
340  * $a[0].name #=> "M1::M2"
341  */
342 
343 static VALUE
344 rb_mod_nesting(VALUE _)
345 {
346  VALUE ary = rb_ary_new();
347  const rb_cref_t *cref = rb_vm_cref();
348 
349  while (cref && CREF_NEXT(cref)) {
350  VALUE klass = CREF_CLASS(cref);
351  if (!CREF_PUSHED_BY_EVAL(cref) &&
352  !NIL_P(klass)) {
353  rb_ary_push(ary, klass);
354  }
355  cref = CREF_NEXT(cref);
356  }
357  return ary;
358 }
359 
360 /*
361  * call-seq:
362  * Module.constants -> array
363  * Module.constants(inherited) -> array
364  *
365  * In the first form, returns an array of the names of all
366  * constants accessible from the point of call.
367  * This list includes the names of all modules and classes
368  * defined in the global scope.
369  *
370  * Module.constants.first(4)
371  * # => [:ARGF, :ARGV, :ArgumentError, :Array]
372  *
373  * Module.constants.include?(:SEEK_SET) # => false
374  *
375  * class IO
376  * Module.constants.include?(:SEEK_SET) # => true
377  * end
378  *
379  * The second form calls the instance method +constants+.
380  */
381 
382 static VALUE
383 rb_mod_s_constants(int argc, VALUE *argv, VALUE mod)
384 {
385  const rb_cref_t *cref = rb_vm_cref();
386  VALUE klass;
387  VALUE cbase = 0;
388  void *data = 0;
389 
390  if (argc > 0 || mod != rb_cModule) {
391  return rb_mod_constants(argc, argv, mod);
392  }
393 
394  while (cref) {
395  klass = CREF_CLASS(cref);
396  if (!CREF_PUSHED_BY_EVAL(cref) &&
397  !NIL_P(klass)) {
398  data = rb_mod_const_at(CREF_CLASS(cref), data);
399  if (!cbase) {
400  cbase = klass;
401  }
402  }
403  cref = CREF_NEXT(cref);
404  }
405 
406  if (cbase) {
407  data = rb_mod_const_of(cbase, data);
408  }
409  return rb_const_list(data);
410 }
411 
418 void
420 {
421  if (SPECIAL_CONST_P(klass)) {
422  Check_Type(klass, T_CLASS);
423  }
424  if (RB_TYPE_P(klass, T_MODULE)) {
425  rb_module_set_initialized(klass);
426  }
427  if (OBJ_FROZEN(klass)) {
428  const char *desc;
429 
430  if (RCLASS_SINGLETON_P(klass)) {
431  desc = "object";
432  klass = RCLASS_ATTACHED_OBJECT(klass);
433  if (!SPECIAL_CONST_P(klass)) {
434  switch (BUILTIN_TYPE(klass)) {
435  case T_MODULE:
436  case T_ICLASS:
437  desc = "Module";
438  break;
439  case T_CLASS:
440  desc = "Class";
441  break;
442  default:
443  break;
444  }
445  }
446  }
447  else {
448  switch (BUILTIN_TYPE(klass)) {
449  case T_MODULE:
450  case T_ICLASS:
451  desc = "module";
452  break;
453  case T_CLASS:
454  desc = "class";
455  break;
456  default:
457  Check_Type(klass, T_CLASS);
458  UNREACHABLE;
459  }
460  }
461  rb_frozen_error_raise(klass, "can't modify frozen %s: %"PRIsVALUE, desc, klass);
462  }
463 }
464 
465 NORETURN(static void rb_longjmp(rb_execution_context_t *, enum ruby_tag_type, volatile VALUE, VALUE));
466 static VALUE get_errinfo(void);
467 #define get_ec_errinfo(ec) rb_ec_get_errinfo(ec)
468 
469 static VALUE
470 exc_setup_cause(VALUE exc, VALUE cause)
471 {
472 #if OPT_SUPPORT_JOKE
473  if (NIL_P(cause)) {
474  ID id_true_cause;
475  CONST_ID(id_true_cause, "true_cause");
476 
477  cause = rb_attr_get(rb_eFatal, id_true_cause);
478  if (NIL_P(cause)) {
479  cause = rb_exc_new_cstr(rb_eFatal, "because using such Ruby");
480  rb_ivar_set(cause, id_cause, INT2FIX(42)); /* the answer */
481  OBJ_FREEZE(cause);
482  rb_ivar_set(rb_eFatal, id_true_cause, cause);
483  }
484  }
485 #endif
486  if (!NIL_P(cause) && cause != exc) {
487  rb_ivar_set(exc, id_cause, cause);
488  if (!rb_ivar_defined(cause, id_cause)) {
489  rb_ivar_set(cause, id_cause, Qnil);
490  }
491  }
492  return exc;
493 }
494 
495 static inline VALUE
496 exc_setup_message(const rb_execution_context_t *ec, VALUE mesg, VALUE *cause)
497 {
498  int nocause = 0;
499  int nocircular = 0;
500 
501  if (NIL_P(mesg)) {
502  mesg = ec->errinfo;
503  if (INTERNAL_EXCEPTION_P(mesg)) EC_JUMP_TAG(ec, TAG_FATAL);
504  nocause = 1;
505  }
506  if (NIL_P(mesg)) {
507  mesg = rb_exc_new(rb_eRuntimeError, 0, 0);
508  nocause = 0;
509  nocircular = 1;
510  }
511  if (UNDEF_P(*cause)) {
512  if (nocause) {
513  *cause = Qnil;
514  nocircular = 1;
515  }
516  else if (!rb_ivar_defined(mesg, id_cause)) {
517  *cause = get_ec_errinfo(ec);
518  }
519  else {
520  nocircular = 1;
521  }
522  }
523  else if (!NIL_P(*cause) && !rb_obj_is_kind_of(*cause, rb_eException)) {
524  rb_raise(rb_eTypeError, "exception object expected");
525  }
526 
527  if (!nocircular && !NIL_P(*cause) && !UNDEF_P(*cause) && *cause != mesg) {
528 #if 0 /* maybe critical for some cases */
529  rb_exc_check_circular_cause(*cause);
530 #else
531  VALUE c = *cause;
532  while (!NIL_P(c = rb_attr_get(c, id_cause))) {
533  if (c == mesg) {
534  rb_raise(rb_eArgError, "circular causes");
535  }
536  }
537 #endif
538  }
539  return mesg;
540 }
541 
542 static void
543 setup_exception(rb_execution_context_t *ec, enum ruby_tag_type tag, volatile VALUE mesg, VALUE cause)
544 {
545  VALUE e;
546  int line;
547  const char *file = rb_source_location_cstr(&line);
548  const char *const volatile file0 = file;
549 
550  if ((file && !NIL_P(mesg)) || !UNDEF_P(cause)) {
551  volatile int state = 0;
552 
553  EC_PUSH_TAG(ec);
554  if (EC_EXEC_TAG() == TAG_NONE && !(state = rb_ec_set_raised(ec))) {
555  VALUE bt = rb_get_backtrace(mesg);
556  if (!NIL_P(bt) || UNDEF_P(cause)) {
557  if (OBJ_FROZEN(mesg)) {
558  mesg = rb_obj_dup(mesg);
559  }
560  }
561  if (!UNDEF_P(cause) && !THROW_DATA_P(cause)) {
562  exc_setup_cause(mesg, cause);
563  }
564  if (NIL_P(bt)) {
565  VALUE at = rb_ec_backtrace_object(ec);
566  rb_ivar_set(mesg, idBt_locations, at);
567  set_backtrace(mesg, at);
568  }
569  rb_ec_reset_raised(ec);
570  }
571  EC_POP_TAG();
572  file = file0;
573  if (state) goto fatal;
574  }
575 
576  if (!NIL_P(mesg)) {
577  ec->errinfo = mesg;
578  }
579 
580  if (RTEST(ruby_debug) && !NIL_P(e = ec->errinfo) &&
582  enum ruby_tag_type state;
583 
584  mesg = e;
585  EC_PUSH_TAG(ec);
586  if ((state = EC_EXEC_TAG()) == TAG_NONE) {
587  ec->errinfo = Qnil;
588  e = rb_obj_as_string(mesg);
589  ec->errinfo = mesg;
590  if (file && line) {
591  e = rb_sprintf("Exception '%"PRIsVALUE"' at %s:%d - %"PRIsVALUE"\n",
592  rb_obj_class(mesg), file, line, e);
593  }
594  else if (file) {
595  e = rb_sprintf("Exception '%"PRIsVALUE"' at %s - %"PRIsVALUE"\n",
596  rb_obj_class(mesg), file, e);
597  }
598  else {
599  e = rb_sprintf("Exception '%"PRIsVALUE"' - %"PRIsVALUE"\n",
600  rb_obj_class(mesg), e);
601  }
602  warn_print_str(e);
603  }
604  EC_POP_TAG();
605  if (state == TAG_FATAL && ec->errinfo == exception_error) {
606  ec->errinfo = mesg;
607  }
608  else if (state) {
609  rb_ec_reset_raised(ec);
610  EC_JUMP_TAG(ec, state);
611  }
612  }
613 
614  if (rb_ec_set_raised(ec)) {
615  goto fatal;
616  }
617 
618  if (tag != TAG_FATAL) {
619  RUBY_DTRACE_HOOK(RAISE, rb_obj_classname(ec->errinfo));
620  EXEC_EVENT_HOOK(ec, RUBY_EVENT_RAISE, ec->cfp->self, 0, 0, 0, mesg);
621  }
622  return;
623 
624  fatal:
625  ec->errinfo = exception_error;
626  rb_ec_reset_raised(ec);
627  EC_JUMP_TAG(ec, TAG_FATAL);
628 }
629 
631 void
632 rb_ec_setup_exception(const rb_execution_context_t *ec, VALUE mesg, VALUE cause)
633 {
634  if (UNDEF_P(cause)) {
635  cause = get_ec_errinfo(ec);
636  }
637  if (cause != mesg) {
638  if (THROW_DATA_P(cause)) {
639  cause = Qnil;
640  }
641 
642  rb_ivar_set(mesg, id_cause, cause);
643  }
644 }
645 
646 static void
647 rb_longjmp(rb_execution_context_t *ec, enum ruby_tag_type tag, volatile VALUE mesg, VALUE cause)
648 {
649  mesg = exc_setup_message(ec, mesg, &cause);
650  setup_exception(ec, tag, mesg, cause);
651  rb_ec_raised_clear(ec);
652  EC_JUMP_TAG(ec, tag);
653 }
654 
655 static VALUE make_exception(int argc, const VALUE *argv, int isstr);
656 
657 NORETURN(static void rb_exc_exception(VALUE mesg, enum ruby_tag_type tag, VALUE cause));
658 
659 static void
660 rb_exc_exception(VALUE mesg, enum ruby_tag_type tag, VALUE cause)
661 {
662  if (!NIL_P(mesg)) {
663  mesg = make_exception(1, &mesg, FALSE);
664  }
665  rb_longjmp(GET_EC(), tag, mesg, cause);
666 }
667 
675 void
677 {
678  rb_exc_exception(mesg, TAG_RAISE, Qundef);
679 }
680 
688 void
690 {
691  rb_exc_exception(mesg, TAG_FATAL, Qnil);
692 }
693 
694 void
696 {
698 }
699 
700 enum {raise_opt_cause, raise_max_opt}; /*< \private */
701 
702 static int
703 extract_raise_opts(int argc, VALUE *argv, VALUE *opts)
704 {
705  int i;
706  if (argc > 0) {
707  VALUE opt;
708  argc = rb_scan_args(argc, argv, "*:", NULL, &opt);
709  if (!NIL_P(opt)) {
710  if (!RHASH_EMPTY_P(opt)) {
711  ID keywords[1];
712  CONST_ID(keywords[0], "cause");
713  rb_get_kwargs(opt, keywords, 0, -1-raise_max_opt, opts);
714  if (!RHASH_EMPTY_P(opt)) argv[argc++] = opt;
715  return argc;
716  }
717  }
718  }
719  for (i = 0; i < raise_max_opt; ++i) {
720  opts[i] = Qundef;
721  }
722  return argc;
723 }
724 
725 VALUE
726 rb_f_raise(int argc, VALUE *argv)
727 {
728  VALUE err;
729  VALUE opts[raise_max_opt], *const cause = &opts[raise_opt_cause];
730 
731  argc = extract_raise_opts(argc, argv, opts);
732  if (argc == 0) {
733  if (!UNDEF_P(*cause)) {
734  rb_raise(rb_eArgError, "only cause is given with no arguments");
735  }
736  err = get_errinfo();
737  if (!NIL_P(err)) {
738  argc = 1;
739  argv = &err;
740  }
741  }
742  rb_raise_jump(rb_make_exception(argc, argv), *cause);
743 
745 }
746 
747 /*
748  * call-seq:
749  * raise(exception, message = exception.to_s, backtrace = nil, cause: $!)
750  * raise(message = nil, cause: $!)
751  *
752  * Raises an exception;
753  * see {Exceptions}[rdoc-ref:exceptions.md].
754  *
755  * Argument +exception+ sets the class of the new exception;
756  * it should be class Exception or one of its subclasses
757  * (most commonly, RuntimeError or StandardError),
758  * or an instance of one of those classes:
759  *
760  * begin
761  * raise(StandardError)
762  * rescue => x
763  * p x.class
764  * end
765  * # => StandardError
766  *
767  * Argument +message+ sets the stored message in the new exception,
768  * which may be retrieved by method Exception#message;
769  * the message must be
770  * a {string-convertible object}[rdoc-ref:implicit_conversion.rdoc@String-Convertible+Objects]
771  * or +nil+:
772  *
773  * begin
774  * raise(StandardError, 'Boom')
775  * rescue => x
776  * p x.message
777  * end
778  * # => "Boom"
779  *
780  * If argument +message+ is not given,
781  * the message is the exception class name.
782  *
783  * See {Messages}[rdoc-ref:exceptions.md@Messages].
784  *
785  * Argument +backtrace+ sets the stored backtrace in the new exception,
786  * which may be retrieved by method Exception#backtrace;
787  * the backtrace must be an array of strings or +nil+:
788  *
789  * begin
790  * raise(StandardError, 'Boom', %w[foo bar baz])
791  * rescue => x
792  * p x.backtrace
793  * end
794  * # => ["foo", "bar", "baz"]
795  *
796  * If argument +backtrace+ is not given,
797  * the backtrace is set according to an array of Thread::Backtrace::Location objects,
798  * as derived from the call stack.
799  *
800  * See {Backtraces}[rdoc-ref:exceptions.md@Backtraces].
801  *
802  * Keyword argument +cause+ sets the stored cause in the new exception,
803  * which may be retrieved by method Exception#cause;
804  * the cause must be an exception object (Exception or one of its subclasses),
805  * or +nil+:
806  *
807  * begin
808  * raise(StandardError, cause: RuntimeError.new)
809  * rescue => x
810  * p x.cause
811  * end
812  * # => #<RuntimeError: RuntimeError>
813  *
814  * If keyword argument +cause+ is not given,
815  * the cause is the value of <tt>$!</tt>.
816  *
817  * See {Cause}[rdoc-ref:exceptions.md@Cause].
818  *
819  * In the alternate calling sequence,
820  * where argument +exception+ _not_ given,
821  * raises a new exception of the class given by <tt>$!</tt>,
822  * or of class RuntimeError if <tt>$!</tt> is +nil+:
823  *
824  * begin
825  * raise
826  * rescue => x
827  * p x
828  * end
829  * # => RuntimeError
830  *
831  * With argument +exception+ not given,
832  * argument +message+ and keyword argument +cause+ may be given,
833  * but argument +backtrace+ may not be given.
834  */
835 
836 static VALUE
837 f_raise(int c, VALUE *v, VALUE _)
838 {
839  return rb_f_raise(c, v);
840 }
841 
842 static VALUE
843 make_exception(int argc, const VALUE *argv, int isstr)
844 {
845  VALUE mesg, exc;
846 
847  mesg = Qnil;
848  switch (argc) {
849  case 0:
850  return Qnil;
851  case 1:
852  exc = argv[0];
853  if (isstr &&! NIL_P(exc)) {
854  mesg = rb_check_string_type(exc);
855  if (!NIL_P(mesg)) {
856  return rb_exc_new3(rb_eRuntimeError, mesg);
857  }
858  }
859 
860  case 2:
861  case 3:
862  break;
863  default:
864  rb_error_arity(argc, 0, 3);
865  }
866  if (NIL_P(mesg)) {
867  mesg = rb_check_funcall(argv[0], idException, argc != 1, &argv[1]);
868  }
869  if (UNDEF_P(mesg)) {
870  rb_raise(rb_eTypeError, "exception class/object expected");
871  }
872  if (!rb_obj_is_kind_of(mesg, rb_eException)) {
873  rb_raise(rb_eTypeError, "exception object expected");
874  }
875  if (argc == 3) {
876  set_backtrace(mesg, argv[2]);
877  }
878 
879  return mesg;
880 }
881 
882 VALUE
883 rb_make_exception(int argc, const VALUE *argv)
884 {
885  return make_exception(argc, argv, TRUE);
886 }
887 
890 static void
891 rb_raise_jump(VALUE mesg, VALUE cause)
892 {
893  rb_execution_context_t *ec = GET_EC();
894  const rb_control_frame_t *cfp = ec->cfp;
895  const rb_callable_method_entry_t *me = rb_vm_frame_method_entry(cfp);
896  VALUE klass = me->owner;
897  VALUE self = cfp->self;
898  ID mid = me->called_id;
899 
900  rb_vm_pop_frame(ec);
901  EXEC_EVENT_HOOK(ec, RUBY_EVENT_C_RETURN, self, me->def->original_id, mid, klass, Qnil);
902 
903  rb_longjmp(ec, TAG_RAISE, mesg, cause);
904 }
905 
906 void
907 rb_jump_tag(int tag)
908 {
909  if (UNLIKELY(tag < TAG_RETURN || tag > TAG_FATAL)) {
910  unknown_longjmp_status(tag);
911  }
912  EC_JUMP_TAG(GET_EC(), tag);
913 }
914 
915 int
917 {
918  if (rb_vm_frame_block_handler(GET_EC()->cfp) == VM_BLOCK_HANDLER_NONE) {
919  return FALSE;
920  }
921  else {
922  return TRUE;
923  }
924 }
925 
926 int rb_vm_cframe_keyword_p(const rb_control_frame_t *cfp);
927 
928 int
930 {
931  return rb_vm_cframe_keyword_p(GET_EC()->cfp);
932 }
933 
935 
936 void
938 {
939  if (!rb_block_given_p()) {
940  rb_vm_localjump_error("no block given", Qnil, 0);
941  }
942 }
943 
944 VALUE
945 rb_rescue2(VALUE (* b_proc) (VALUE), VALUE data1,
946  VALUE (* r_proc) (VALUE, VALUE), VALUE data2, ...)
947 {
948  va_list ap;
949  va_start(ap, data2);
950  VALUE ret = rb_vrescue2(b_proc, data1, r_proc, data2, ap);
951  va_end(ap);
952  return ret;
953 }
954 
955 VALUE
956 rb_vrescue2(VALUE (* b_proc) (VALUE), VALUE data1,
957  VALUE (* r_proc) (VALUE, VALUE), VALUE data2,
958  va_list args)
959 {
960  enum ruby_tag_type state;
961  rb_execution_context_t * volatile ec = GET_EC();
962  rb_control_frame_t *volatile cfp = ec->cfp;
963  volatile VALUE result = Qfalse;
964  volatile VALUE e_info = ec->errinfo;
965 
966  EC_PUSH_TAG(ec);
967  if ((state = EC_EXEC_TAG()) == TAG_NONE) {
968  retry_entry:
969  result = (*b_proc) (data1);
970  }
971  else if (result) {
972  /* escape from r_proc */
973  if (state == TAG_RETRY) {
974  state = TAG_NONE;
975  ec->errinfo = Qnil;
976  result = Qfalse;
977  goto retry_entry;
978  }
979  }
980  else {
981  rb_vm_rewind_cfp(ec, cfp);
982 
983  if (state == TAG_RAISE) {
984  int handle = FALSE;
985  VALUE eclass;
986  va_list ap;
987 
988  result = Qnil;
989  /* reuses args when raised again after retrying in r_proc */
990  va_copy(ap, args);
991  while ((eclass = va_arg(ap, VALUE)) != 0) {
992  if (rb_obj_is_kind_of(ec->errinfo, eclass)) {
993  handle = TRUE;
994  break;
995  }
996  }
997  va_end(ap);
998 
999  if (handle) {
1000  state = TAG_NONE;
1001  if (r_proc) {
1002  result = (*r_proc) (data2, ec->errinfo);
1003  }
1004  ec->errinfo = e_info;
1005  }
1006  }
1007  }
1008  EC_POP_TAG();
1009  if (state)
1010  EC_JUMP_TAG(ec, state);
1011 
1012  return result;
1013 }
1014 
1015 VALUE
1016 rb_rescue(VALUE (* b_proc)(VALUE), VALUE data1,
1017  VALUE (* r_proc)(VALUE, VALUE), VALUE data2)
1018 {
1019  return rb_rescue2(b_proc, data1, r_proc, data2, rb_eStandardError,
1020  (VALUE)0);
1021 }
1022 
1023 VALUE
1024 rb_protect(VALUE (* proc) (VALUE), VALUE data, int *pstate)
1025 {
1026  volatile VALUE result = Qnil;
1027  volatile enum ruby_tag_type state;
1028  rb_execution_context_t * volatile ec = GET_EC();
1029  rb_control_frame_t *volatile cfp = ec->cfp;
1030 
1031  EC_PUSH_TAG(ec);
1032  if ((state = EC_EXEC_TAG()) == TAG_NONE) {
1033  result = (*proc)(data);
1034  }
1035  else {
1036  rb_vm_rewind_cfp(ec, cfp);
1037  }
1038  EC_POP_TAG();
1039 
1040  if (pstate != NULL) *pstate = state;
1041  return result;
1042 }
1043 
1044 VALUE
1045 rb_ensure(VALUE (*b_proc)(VALUE), VALUE data1, VALUE (*e_proc)(VALUE), VALUE data2)
1046 {
1047  enum ruby_tag_type state;
1048  volatile VALUE result = Qnil;
1049  VALUE errinfo;
1050  rb_execution_context_t * volatile ec = GET_EC();
1051  EC_PUSH_TAG(ec);
1052  if ((state = EC_EXEC_TAG()) == TAG_NONE) {
1053  result = (*b_proc) (data1);
1054  }
1055  EC_POP_TAG();
1056  errinfo = ec->errinfo;
1057  if (!NIL_P(errinfo) && !RB_TYPE_P(errinfo, T_OBJECT)) {
1058  ec->errinfo = Qnil;
1059  }
1060  (*e_proc)(data2);
1061  ec->errinfo = errinfo;
1062  if (state)
1063  EC_JUMP_TAG(ec, state);
1064  return result;
1065 }
1066 
1067 static ID
1068 frame_func_id(const rb_control_frame_t *cfp)
1069 {
1070  const rb_callable_method_entry_t *me = rb_vm_frame_method_entry(cfp);
1071 
1072  if (me) {
1073  return me->def->original_id;
1074  }
1075  else {
1076  return 0;
1077  }
1078 }
1079 
1080 static ID
1081 frame_called_id(rb_control_frame_t *cfp)
1082 {
1083  const rb_callable_method_entry_t *me = rb_vm_frame_method_entry(cfp);
1084 
1085  if (me) {
1086  return me->called_id;
1087  }
1088  else {
1089  return 0;
1090  }
1091 }
1092 
1093 ID
1095 {
1096  return frame_func_id(GET_EC()->cfp);
1097 }
1098 
1099 ID
1101 {
1102  return frame_called_id(GET_EC()->cfp);
1103 }
1104 
1105 static rb_control_frame_t *
1106 previous_frame(const rb_execution_context_t *ec)
1107 {
1108  rb_control_frame_t *prev_cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(ec->cfp);
1109  /* check if prev_cfp can be accessible */
1110  if ((void *)(ec->vm_stack + ec->vm_stack_size) == (void *)(prev_cfp)) {
1111  return 0;
1112  }
1113  return prev_cfp;
1114 }
1115 
1116 static ID
1117 prev_frame_callee(void)
1118 {
1119  rb_control_frame_t *prev_cfp = previous_frame(GET_EC());
1120  if (!prev_cfp) return 0;
1121  return frame_called_id(prev_cfp);
1122 }
1123 
1124 static ID
1125 prev_frame_func(void)
1126 {
1127  rb_control_frame_t *prev_cfp = previous_frame(GET_EC());
1128  if (!prev_cfp) return 0;
1129  return frame_func_id(prev_cfp);
1130 }
1131 
1138 ID
1140 {
1141  const rb_execution_context_t *ec = GET_EC();
1142  const rb_control_frame_t *cfp = ec->cfp;
1143  ID mid;
1144 
1145  while (!(mid = frame_func_id(cfp)) &&
1146  (cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp),
1147  !RUBY_VM_CONTROL_FRAME_STACK_OVERFLOW_P(ec, cfp)));
1148  return mid;
1149 }
1150 
1151 /*
1152  * call-seq:
1153  * append_features(mod) -> mod
1154  *
1155  * When this module is included in another, Ruby calls
1156  * #append_features in this module, passing it the receiving module
1157  * in _mod_. Ruby's default implementation is to add the constants,
1158  * methods, and module variables of this module to _mod_ if this
1159  * module has not already been added to _mod_ or one of its
1160  * ancestors. See also Module#include.
1161  */
1162 
1163 static VALUE
1164 rb_mod_append_features(VALUE module, VALUE include)
1165 {
1166  if (!CLASS_OR_MODULE_P(include)) {
1167  Check_Type(include, T_CLASS);
1168  }
1169  rb_include_module(include, module);
1170 
1171  return module;
1172 }
1173 
1174 /*
1175  * call-seq:
1176  * include(module, ...) -> self
1177  *
1178  * Invokes Module.append_features on each parameter in reverse order.
1179  */
1180 
1181 static VALUE
1182 rb_mod_include(int argc, VALUE *argv, VALUE module)
1183 {
1184  int i;
1185  ID id_append_features, id_included;
1186 
1187  CONST_ID(id_append_features, "append_features");
1188  CONST_ID(id_included, "included");
1189 
1190  if (BUILTIN_TYPE(module) == T_MODULE && FL_TEST(module, RMODULE_IS_REFINEMENT)) {
1191  rb_raise(rb_eTypeError, "Refinement#include has been removed");
1192  }
1193 
1195  for (i = 0; i < argc; i++) {
1196  Check_Type(argv[i], T_MODULE);
1197  if (FL_TEST(argv[i], RMODULE_IS_REFINEMENT)) {
1198  rb_raise(rb_eTypeError, "Cannot include refinement");
1199  }
1200  }
1201  while (argc--) {
1202  rb_funcall(argv[argc], id_append_features, 1, module);
1203  rb_funcall(argv[argc], id_included, 1, module);
1204  }
1205  return module;
1206 }
1207 
1208 /*
1209  * call-seq:
1210  * prepend_features(mod) -> mod
1211  *
1212  * When this module is prepended in another, Ruby calls
1213  * #prepend_features in this module, passing it the receiving module
1214  * in _mod_. Ruby's default implementation is to overlay the
1215  * constants, methods, and module variables of this module to _mod_
1216  * if this module has not already been added to _mod_ or one of its
1217  * ancestors. See also Module#prepend.
1218  */
1219 
1220 static VALUE
1221 rb_mod_prepend_features(VALUE module, VALUE prepend)
1222 {
1223  if (!CLASS_OR_MODULE_P(prepend)) {
1224  Check_Type(prepend, T_CLASS);
1225  }
1226  rb_prepend_module(prepend, module);
1227 
1228  return module;
1229 }
1230 
1231 /*
1232  * call-seq:
1233  * prepend(module, ...) -> self
1234  *
1235  * Invokes Module.prepend_features on each parameter in reverse order.
1236  */
1237 
1238 static VALUE
1239 rb_mod_prepend(int argc, VALUE *argv, VALUE module)
1240 {
1241  int i;
1242  ID id_prepend_features, id_prepended;
1243 
1244  if (BUILTIN_TYPE(module) == T_MODULE && FL_TEST(module, RMODULE_IS_REFINEMENT)) {
1245  rb_raise(rb_eTypeError, "Refinement#prepend has been removed");
1246  }
1247 
1248  CONST_ID(id_prepend_features, "prepend_features");
1249  CONST_ID(id_prepended, "prepended");
1250 
1252  for (i = 0; i < argc; i++) {
1253  Check_Type(argv[i], T_MODULE);
1254  if (FL_TEST(argv[i], RMODULE_IS_REFINEMENT)) {
1255  rb_raise(rb_eTypeError, "Cannot prepend refinement");
1256  }
1257  }
1258  while (argc--) {
1259  rb_funcall(argv[argc], id_prepend_features, 1, module);
1260  rb_funcall(argv[argc], id_prepended, 1, module);
1261  }
1262  return module;
1263 }
1264 
1265 static void
1266 ensure_class_or_module(VALUE obj)
1267 {
1268  if (!RB_TYPE_P(obj, T_CLASS) && !RB_TYPE_P(obj, T_MODULE)) {
1270  "wrong argument type %"PRIsVALUE" (expected Class or Module)",
1271  rb_obj_class(obj));
1272  }
1273 }
1274 
1275 static VALUE
1276 hidden_identity_hash_new(void)
1277 {
1278  VALUE hash = rb_ident_hash_new();
1279 
1280  RBASIC_CLEAR_CLASS(hash); /* hide from ObjectSpace */
1281  return hash;
1282 }
1283 
1284 static VALUE
1285 refinement_superclass(VALUE superclass)
1286 {
1287  if (RB_TYPE_P(superclass, T_MODULE)) {
1288  /* FIXME: Should ancestors of superclass be used here? */
1289  return rb_include_class_new(RCLASS_ORIGIN(superclass), rb_cBasicObject);
1290  }
1291  else {
1292  return superclass;
1293  }
1294 }
1295 
1299 static void
1300 rb_using_refinement(rb_cref_t *cref, VALUE klass, VALUE module)
1301 {
1302  VALUE iclass, c, superclass = klass;
1303 
1304  ensure_class_or_module(klass);
1305  Check_Type(module, T_MODULE);
1306  if (NIL_P(CREF_REFINEMENTS(cref))) {
1307  CREF_REFINEMENTS_SET(cref, hidden_identity_hash_new());
1308  }
1309  else {
1310  if (CREF_OMOD_SHARED(cref)) {
1311  CREF_REFINEMENTS_SET(cref, rb_hash_dup(CREF_REFINEMENTS(cref)));
1312  CREF_OMOD_SHARED_UNSET(cref);
1313  }
1314  if (!NIL_P(c = rb_hash_lookup(CREF_REFINEMENTS(cref), klass))) {
1315  superclass = c;
1316  while (c && RB_TYPE_P(c, T_ICLASS)) {
1317  if (RBASIC(c)->klass == module) {
1318  /* already used refinement */
1319  return;
1320  }
1321  c = RCLASS_SUPER(c);
1322  }
1323  }
1324  }
1325  superclass = refinement_superclass(superclass);
1326  c = iclass = rb_include_class_new(module, superclass);
1327  RB_OBJ_WRITE(c, &RCLASS_REFINED_CLASS(c), klass);
1328 
1329  RCLASS_M_TBL(c) = RCLASS_M_TBL(module);
1330 
1331  rb_hash_aset(CREF_REFINEMENTS(cref), klass, iclass);
1332 }
1333 
1334 static int
1335 using_refinement(VALUE klass, VALUE module, VALUE arg)
1336 {
1337  rb_cref_t *cref = (rb_cref_t *) arg;
1338 
1339  rb_using_refinement(cref, klass, module);
1340  return ST_CONTINUE;
1341 }
1342 
1343 static void
1344 using_module_recursive(const rb_cref_t *cref, VALUE klass)
1345 {
1346  ID id_refinements;
1347  VALUE super, module, refinements;
1348 
1349  super = RCLASS_SUPER(klass);
1350  if (super) {
1351  using_module_recursive(cref, super);
1352  }
1353  switch (BUILTIN_TYPE(klass)) {
1354  case T_MODULE:
1355  module = klass;
1356  break;
1357 
1358  case T_ICLASS:
1359  module = RBASIC(klass)->klass;
1360  break;
1361 
1362  default:
1363  rb_raise(rb_eTypeError, "wrong argument type %s (expected Module)",
1364  rb_obj_classname(klass));
1365  break;
1366  }
1367  CONST_ID(id_refinements, "__refinements__");
1368  refinements = rb_attr_get(module, id_refinements);
1369  if (NIL_P(refinements)) return;
1370  rb_hash_foreach(refinements, using_refinement, (VALUE) cref);
1371 }
1372 
1376 static void
1377 rb_using_module(const rb_cref_t *cref, VALUE module)
1378 {
1379  Check_Type(module, T_MODULE);
1380  using_module_recursive(cref, module);
1381  rb_clear_all_refinement_method_cache();
1382 }
1383 
1384 /*
1385  * call-seq:
1386  * target -> class_or_module
1387  *
1388  * Return the class or module refined by the receiver.
1389  *
1390  * module M
1391  * refine String do
1392  * end
1393  * end
1394  *
1395  * M.refinements[0].target # => String
1396  */
1397 VALUE
1398 rb_refinement_module_get_refined_class(VALUE module)
1399 {
1400  ID id_refined_class;
1401 
1402  CONST_ID(id_refined_class, "__refined_class__");
1403  return rb_attr_get(module, id_refined_class);
1404 }
1405 
1406 static void
1407 add_activated_refinement(VALUE activated_refinements,
1408  VALUE klass, VALUE refinement)
1409 {
1410  VALUE iclass, c, superclass = klass;
1411 
1412  if (!NIL_P(c = rb_hash_lookup(activated_refinements, klass))) {
1413  superclass = c;
1414  while (c && RB_TYPE_P(c, T_ICLASS)) {
1415  if (RBASIC(c)->klass == refinement) {
1416  /* already used refinement */
1417  return;
1418  }
1419  c = RCLASS_SUPER(c);
1420  }
1421  }
1422  superclass = refinement_superclass(superclass);
1423  c = iclass = rb_include_class_new(refinement, superclass);
1424  RB_OBJ_WRITE(c, &RCLASS_REFINED_CLASS(c), klass);
1425  refinement = RCLASS_SUPER(refinement);
1426  while (refinement && refinement != klass) {
1427  c = RCLASS_SET_SUPER(c, rb_include_class_new(refinement, RCLASS_SUPER(c)));
1428  RB_OBJ_WRITE(c, &RCLASS_REFINED_CLASS(c), klass);
1429  refinement = RCLASS_SUPER(refinement);
1430  }
1431  rb_hash_aset(activated_refinements, klass, iclass);
1432 }
1433 
1434 /*
1435  * call-seq:
1436  * refine(mod) { block } -> module
1437  *
1438  * Refine <i>mod</i> in the receiver.
1439  *
1440  * Returns a module, where refined methods are defined.
1441  */
1442 
1443 static VALUE
1444 rb_mod_refine(VALUE module, VALUE klass)
1445 {
1446  VALUE refinement;
1447  ID id_refinements, id_activated_refinements,
1448  id_refined_class, id_defined_at;
1449  VALUE refinements, activated_refinements;
1450  rb_thread_t *th = GET_THREAD();
1451  VALUE block_handler = rb_vm_frame_block_handler(th->ec->cfp);
1452 
1453  if (block_handler == VM_BLOCK_HANDLER_NONE) {
1454  rb_raise(rb_eArgError, "no block given");
1455  }
1456  if (vm_block_handler_type(block_handler) != block_handler_type_iseq) {
1457  rb_raise(rb_eArgError, "can't pass a Proc as a block to Module#refine");
1458  }
1459 
1460  ensure_class_or_module(klass);
1461  CONST_ID(id_refinements, "__refinements__");
1462  refinements = rb_attr_get(module, id_refinements);
1463  if (NIL_P(refinements)) {
1464  refinements = hidden_identity_hash_new();
1465  rb_ivar_set(module, id_refinements, refinements);
1466  }
1467  CONST_ID(id_activated_refinements, "__activated_refinements__");
1468  activated_refinements = rb_attr_get(module, id_activated_refinements);
1469  if (NIL_P(activated_refinements)) {
1470  activated_refinements = hidden_identity_hash_new();
1471  rb_ivar_set(module, id_activated_refinements,
1472  activated_refinements);
1473  }
1474  refinement = rb_hash_lookup(refinements, klass);
1475  if (NIL_P(refinement)) {
1476  VALUE superclass = refinement_superclass(klass);
1477  refinement = rb_refinement_new();
1478  RCLASS_SET_SUPER(refinement, superclass);
1479  RUBY_ASSERT(BUILTIN_TYPE(refinement) == T_MODULE);
1480  FL_SET(refinement, RMODULE_IS_REFINEMENT);
1481  CONST_ID(id_refined_class, "__refined_class__");
1482  rb_ivar_set(refinement, id_refined_class, klass);
1483  CONST_ID(id_defined_at, "__defined_at__");
1484  rb_ivar_set(refinement, id_defined_at, module);
1485  rb_hash_aset(refinements, klass, refinement);
1486  add_activated_refinement(activated_refinements, klass, refinement);
1487  }
1488  rb_yield_refine_block(refinement, activated_refinements);
1489  return refinement;
1490 }
1491 
1492 static void
1493 ignored_block(VALUE module, const char *klass)
1494 {
1495  const char *anon = "";
1496  Check_Type(module, T_MODULE);
1497  if (!RTEST(rb_search_class_path(module))) {
1498  anon = ", maybe for Module.new";
1499  }
1500  rb_warn("%s""using doesn't call the given block""%s.", klass, anon);
1501 }
1502 
1503 /*
1504  * call-seq:
1505  * using(module) -> self
1506  *
1507  * Import class refinements from <i>module</i> into the current class or
1508  * module definition.
1509  */
1510 
1511 static VALUE
1512 mod_using(VALUE self, VALUE module)
1513 {
1514  rb_control_frame_t *prev_cfp = previous_frame(GET_EC());
1515 
1516  if (prev_frame_func()) {
1518  "Module#using is not permitted in methods");
1519  }
1520  if (prev_cfp && prev_cfp->self != self) {
1521  rb_raise(rb_eRuntimeError, "Module#using is not called on self");
1522  }
1523  if (rb_block_given_p()) {
1524  ignored_block(module, "Module#");
1525  }
1526  rb_using_module(rb_vm_cref_replace_with_duplicated_cref(), module);
1527  return self;
1528 }
1529 
1530 
1531 /*
1532  * call-seq:
1533  * refinements -> array
1534  *
1535  * Returns an array of +Refinement+ defined within the receiver.
1536  *
1537  * module A
1538  * refine Integer do
1539  * end
1540  *
1541  * refine String do
1542  * end
1543  * end
1544  *
1545  * p A.refinements
1546  *
1547  * <em>produces:</em>
1548  *
1549  * [#<refinement:Integer@A>, #<refinement:String@A>]
1550  */
1551 static VALUE
1552 mod_refinements(VALUE self)
1553 {
1554  ID id_refinements;
1555  VALUE refinements;
1556 
1557  CONST_ID(id_refinements, "__refinements__");
1558  refinements = rb_attr_get(self, id_refinements);
1559  if (NIL_P(refinements)) {
1560  return rb_ary_new();
1561  }
1562  return rb_hash_values(refinements);
1563 }
1564 
1565 static int
1566 used_modules_i(VALUE _, VALUE mod, VALUE ary)
1567 {
1568  ID id_defined_at;
1569  CONST_ID(id_defined_at, "__defined_at__");
1570  while (BUILTIN_TYPE(rb_class_of(mod)) == T_MODULE && FL_TEST(rb_class_of(mod), RMODULE_IS_REFINEMENT)) {
1571  rb_ary_push(ary, rb_attr_get(rb_class_of(mod), id_defined_at));
1572  mod = RCLASS_SUPER(mod);
1573  }
1574  return ST_CONTINUE;
1575 }
1576 
1577 /*
1578  * call-seq:
1579  * used_modules -> array
1580  *
1581  * Returns an array of all modules used in the current scope. The ordering
1582  * of modules in the resulting array is not defined.
1583  *
1584  * module A
1585  * refine Object do
1586  * end
1587  * end
1588  *
1589  * module B
1590  * refine Object do
1591  * end
1592  * end
1593  *
1594  * using A
1595  * using B
1596  * p Module.used_modules
1597  *
1598  * <em>produces:</em>
1599  *
1600  * [B, A]
1601  */
1602 static VALUE
1603 rb_mod_s_used_modules(VALUE _)
1604 {
1605  const rb_cref_t *cref = rb_vm_cref();
1606  VALUE ary = rb_ary_new();
1607 
1608  while (cref) {
1609  if (!NIL_P(CREF_REFINEMENTS(cref))) {
1610  rb_hash_foreach(CREF_REFINEMENTS(cref), used_modules_i, ary);
1611  }
1612  cref = CREF_NEXT(cref);
1613  }
1614 
1615  return rb_funcall(ary, rb_intern("uniq"), 0);
1616 }
1617 
1618 static int
1619 used_refinements_i(VALUE _, VALUE mod, VALUE ary)
1620 {
1621  while (BUILTIN_TYPE(rb_class_of(mod)) == T_MODULE && FL_TEST(rb_class_of(mod), RMODULE_IS_REFINEMENT)) {
1622  rb_ary_push(ary, rb_class_of(mod));
1623  mod = RCLASS_SUPER(mod);
1624  }
1625  return ST_CONTINUE;
1626 }
1627 
1628 /*
1629  * call-seq:
1630  * used_refinements -> array
1631  *
1632  * Returns an array of all modules used in the current scope. The ordering
1633  * of modules in the resulting array is not defined.
1634  *
1635  * module A
1636  * refine Object do
1637  * end
1638  * end
1639  *
1640  * module B
1641  * refine Object do
1642  * end
1643  * end
1644  *
1645  * using A
1646  * using B
1647  * p Module.used_refinements
1648  *
1649  * <em>produces:</em>
1650  *
1651  * [#<refinement:Object@B>, #<refinement:Object@A>]
1652  */
1653 static VALUE
1654 rb_mod_s_used_refinements(VALUE _)
1655 {
1656  const rb_cref_t *cref = rb_vm_cref();
1657  VALUE ary = rb_ary_new();
1658 
1659  while (cref) {
1660  if (!NIL_P(CREF_REFINEMENTS(cref))) {
1661  rb_hash_foreach(CREF_REFINEMENTS(cref), used_refinements_i, ary);
1662  }
1663  cref = CREF_NEXT(cref);
1664  }
1665 
1666  return ary;
1667 }
1668 
1670  rb_cref_t *cref;
1671  VALUE refinement;
1672  VALUE module;
1673 };
1674 
1675 /* vm.c */
1676 rb_cref_t *rb_vm_cref_dup_without_refinements(const rb_cref_t *cref);
1677 
1678 static enum rb_id_table_iterator_result
1679 refinement_import_methods_i(ID key, VALUE value, void *data)
1680 {
1681  const rb_method_entry_t *me = (const rb_method_entry_t *)value;
1682  struct refinement_import_methods_arg *arg = (struct refinement_import_methods_arg *)data;
1683 
1684  if (me->def->type != VM_METHOD_TYPE_ISEQ) {
1685  rb_raise(rb_eArgError, "Can't import method which is not defined with Ruby code: %"PRIsVALUE"#%"PRIsVALUE, rb_class_path(arg->module), rb_id2str(key));
1686  }
1687  rb_cref_t *new_cref = rb_vm_cref_dup_without_refinements(me->def->body.iseq.cref);
1688  CREF_REFINEMENTS_SET(new_cref, CREF_REFINEMENTS(arg->cref));
1689  rb_add_method_iseq(arg->refinement, key, me->def->body.iseq.iseqptr, new_cref, METHOD_ENTRY_VISI(me));
1690  return ID_TABLE_CONTINUE;
1691 }
1692 
1693 /*
1694  * Note: docs for the method are in class.c
1695  */
1696 
1697 static VALUE
1698 refinement_import_methods(int argc, VALUE *argv, VALUE refinement)
1699 {
1700  int i;
1701  struct refinement_import_methods_arg arg;
1702 
1704  for (i = 0; i < argc; i++) {
1705  Check_Type(argv[i], T_MODULE);
1706  if (RCLASS_SUPER(argv[i])) {
1707  rb_warn("%"PRIsVALUE" has ancestors, but Refinement#import_methods doesn't import their methods", rb_class_path(argv[i]));
1708  }
1709  }
1710  arg.cref = rb_vm_cref_replace_with_duplicated_cref();
1711  arg.refinement = refinement;
1712  for (i = 0; i < argc; i++) {
1713  arg.module = argv[i];
1714  struct rb_id_table *m_tbl = RCLASS_M_TBL(argv[i]);
1715  if (!m_tbl) continue;
1716  rb_id_table_foreach(m_tbl, refinement_import_methods_i, &arg);
1717  }
1718  return refinement;
1719 }
1720 
1721 void
1722 rb_obj_call_init(VALUE obj, int argc, const VALUE *argv)
1723 {
1724  rb_obj_call_init_kw(obj, argc, argv, RB_NO_KEYWORDS);
1725 }
1726 
1727 void
1728 rb_obj_call_init_kw(VALUE obj, int argc, const VALUE *argv, int kw_splat)
1729 {
1730  PASS_PASSED_BLOCK_HANDLER();
1731  rb_funcallv_kw(obj, idInitialize, argc, argv, kw_splat);
1732 }
1733 
1734 void
1736 {
1737  rb_include_module(rb_singleton_class(obj), module);
1738 }
1739 
1740 /*
1741  * call-seq:
1742  * extend_object(obj) -> obj
1743  *
1744  * Extends the specified object by adding this module's constants and
1745  * methods (which are added as singleton methods). This is the callback
1746  * method used by Object#extend.
1747  *
1748  * module Picky
1749  * def Picky.extend_object(o)
1750  * if String === o
1751  * puts "Can't add Picky to a String"
1752  * else
1753  * puts "Picky added to #{o.class}"
1754  * super
1755  * end
1756  * end
1757  * end
1758  * (s = Array.new).extend Picky # Call Object.extend
1759  * (s = "quick brown fox").extend Picky
1760  *
1761  * <em>produces:</em>
1762  *
1763  * Picky added to Array
1764  * Can't add Picky to a String
1765  */
1766 
1767 static VALUE
1768 rb_mod_extend_object(VALUE mod, VALUE obj)
1769 {
1770  rb_extend_object(obj, mod);
1771  return obj;
1772 }
1773 
1774 /*
1775  * call-seq:
1776  * obj.extend(module, ...) -> obj
1777  *
1778  * Adds to _obj_ the instance methods from each module given as a
1779  * parameter.
1780  *
1781  * module Mod
1782  * def hello
1783  * "Hello from Mod.\n"
1784  * end
1785  * end
1786  *
1787  * class Klass
1788  * def hello
1789  * "Hello from Klass.\n"
1790  * end
1791  * end
1792  *
1793  * k = Klass.new
1794  * k.hello #=> "Hello from Klass.\n"
1795  * k.extend(Mod) #=> #<Klass:0x401b3bc8>
1796  * k.hello #=> "Hello from Mod.\n"
1797  */
1798 
1799 static VALUE
1800 rb_obj_extend(int argc, VALUE *argv, VALUE obj)
1801 {
1802  int i;
1803  ID id_extend_object, id_extended;
1804 
1805  CONST_ID(id_extend_object, "extend_object");
1806  CONST_ID(id_extended, "extended");
1807 
1809  for (i = 0; i < argc; i++) {
1810  Check_Type(argv[i], T_MODULE);
1811  if (FL_TEST(argv[i], RMODULE_IS_REFINEMENT)) {
1812  rb_raise(rb_eTypeError, "Cannot extend object with refinement");
1813  }
1814  }
1815  while (argc--) {
1816  rb_funcall(argv[argc], id_extend_object, 1, obj);
1817  rb_funcall(argv[argc], id_extended, 1, obj);
1818  }
1819  return obj;
1820 }
1821 
1822 VALUE
1823 rb_top_main_class(const char *method)
1824 {
1825  VALUE klass = GET_THREAD()->top_wrapper;
1826 
1827  if (!klass) return rb_cObject;
1828  rb_warning("main.%s in the wrapped load is effective only in wrapper module", method);
1829  return klass;
1830 }
1831 
1832 /*
1833  * call-seq:
1834  * include(module, ...) -> self
1835  *
1836  * Invokes Module.append_features on each parameter in turn.
1837  * Effectively adds the methods and constants in each module to the
1838  * receiver.
1839  */
1840 
1841 static VALUE
1842 top_include(int argc, VALUE *argv, VALUE self)
1843 {
1844  return rb_mod_include(argc, argv, rb_top_main_class("include"));
1845 }
1846 
1847 /*
1848  * call-seq:
1849  * using(module) -> self
1850  *
1851  * Import class refinements from <i>module</i> into the scope where
1852  * #using is called.
1853  */
1854 
1855 static VALUE
1856 top_using(VALUE self, VALUE module)
1857 {
1858  const rb_cref_t *cref = CREF_NEXT(rb_vm_cref());
1859  rb_control_frame_t *prev_cfp = previous_frame(GET_EC());
1860  rb_thread_t *th = GET_THREAD();
1861 
1862  if ((th->top_wrapper ? CREF_NEXT(cref) : cref) ||
1863  (prev_cfp && rb_vm_frame_method_entry(prev_cfp))) {
1864  rb_raise(rb_eRuntimeError, "main.using is permitted only at toplevel");
1865  }
1866  if (rb_block_given_p()) {
1867  ignored_block(module, "main.");
1868  }
1869  rb_using_module(rb_vm_cref_replace_with_duplicated_cref(), module);
1870  return self;
1871 }
1872 
1873 static const VALUE *
1874 errinfo_place(const rb_execution_context_t *ec)
1875 {
1876  const rb_control_frame_t *cfp = ec->cfp;
1877  const rb_control_frame_t *end_cfp = RUBY_VM_END_CONTROL_FRAME(ec);
1878 
1879  while (RUBY_VM_VALID_CONTROL_FRAME_P(cfp, end_cfp)) {
1880  if (VM_FRAME_RUBYFRAME_P(cfp)) {
1881  if (ISEQ_BODY(cfp->iseq)->type == ISEQ_TYPE_RESCUE) {
1882  return &cfp->ep[VM_ENV_INDEX_LAST_LVAR];
1883  }
1884  else if (ISEQ_BODY(cfp->iseq)->type == ISEQ_TYPE_ENSURE &&
1885  !THROW_DATA_P(cfp->ep[VM_ENV_INDEX_LAST_LVAR]) &&
1886  !FIXNUM_P(cfp->ep[VM_ENV_INDEX_LAST_LVAR])) {
1887  return &cfp->ep[VM_ENV_INDEX_LAST_LVAR];
1888  }
1889  }
1890  cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp);
1891  }
1892  return 0;
1893 }
1894 
1895 VALUE
1896 rb_ec_get_errinfo(const rb_execution_context_t *ec)
1897 {
1898  const VALUE *ptr = errinfo_place(ec);
1899  if (ptr) {
1900  return *ptr;
1901  }
1902  else {
1903  return ec->errinfo;
1904  }
1905 }
1906 
1907 static VALUE
1908 get_errinfo(void)
1909 {
1910  return get_ec_errinfo(GET_EC());
1911 }
1912 
1913 static VALUE
1914 errinfo_getter(ID id, VALUE *_)
1915 {
1916  return get_errinfo();
1917 }
1918 
1919 VALUE
1921 {
1922  return GET_EC()->errinfo;
1923 }
1924 
1925 void
1927 {
1928  if (!NIL_P(err) && !rb_obj_is_kind_of(err, rb_eException)) {
1929  rb_raise(rb_eTypeError, "assigning non-exception to $!");
1930  }
1931  GET_EC()->errinfo = err;
1932 }
1933 
1934 static VALUE
1935 errat_getter(ID id, VALUE *_)
1936 {
1937  VALUE err = get_errinfo();
1938  if (!NIL_P(err)) {
1939  return rb_get_backtrace(err);
1940  }
1941  else {
1942  return Qnil;
1943  }
1944 }
1945 
1946 static void
1947 errat_setter(VALUE val, ID id, VALUE *var)
1948 {
1949  VALUE err = get_errinfo();
1950  if (NIL_P(err)) {
1951  rb_raise(rb_eArgError, "$! not set");
1952  }
1953  set_backtrace(err, val);
1954 }
1955 
1956 /*
1957  * call-seq:
1958  * __method__ -> symbol
1959  *
1960  * Returns the name at the definition of the current method as a
1961  * Symbol.
1962  * If called outside of a method, it returns <code>nil</code>.
1963  *
1964  */
1965 
1966 static VALUE
1967 rb_f_method_name(VALUE _)
1968 {
1969  ID fname = prev_frame_func(); /* need *method* ID */
1970 
1971  if (fname) {
1972  return ID2SYM(fname);
1973  }
1974  else {
1975  return Qnil;
1976  }
1977 }
1978 
1979 /*
1980  * call-seq:
1981  * __callee__ -> symbol
1982  *
1983  * Returns the called name of the current method as a Symbol.
1984  * If called outside of a method, it returns <code>nil</code>.
1985  *
1986  */
1987 
1988 static VALUE
1989 rb_f_callee_name(VALUE _)
1990 {
1991  ID fname = prev_frame_callee(); /* need *callee* ID */
1992 
1993  if (fname) {
1994  return ID2SYM(fname);
1995  }
1996  else {
1997  return Qnil;
1998  }
1999 }
2000 
2001 /*
2002  * call-seq:
2003  * __dir__ -> string
2004  *
2005  * Returns the canonicalized absolute path of the directory of the file from
2006  * which this method is called. It means symlinks in the path is resolved.
2007  * If <code>__FILE__</code> is <code>nil</code>, it returns <code>nil</code>.
2008  * The return value equals to <code>File.dirname(File.realpath(__FILE__))</code>.
2009  *
2010  */
2011 static VALUE
2012 f_current_dirname(VALUE _)
2013 {
2014  VALUE base = rb_current_realfilepath();
2015  if (NIL_P(base)) {
2016  return Qnil;
2017  }
2018  base = rb_file_dirname(base);
2019  return base;
2020 }
2021 
2022 /*
2023  * call-seq:
2024  * global_variables -> array
2025  *
2026  * Returns an array of the names of global variables. This includes
2027  * special regexp global variables such as <tt>$~</tt> and <tt>$+</tt>,
2028  * but does not include the numbered regexp global variables (<tt>$1</tt>,
2029  * <tt>$2</tt>, etc.).
2030  *
2031  * global_variables.grep /std/ #=> [:$stdin, :$stdout, :$stderr]
2032  */
2033 
2034 static VALUE
2035 f_global_variables(VALUE _)
2036 {
2037  return rb_f_global_variables();
2038 }
2039 
2040 /*
2041  * call-seq:
2042  * trace_var(symbol, cmd ) -> nil
2043  * trace_var(symbol) {|val| block } -> nil
2044  *
2045  * Controls tracing of assignments to global variables. The parameter
2046  * +symbol+ identifies the variable (as either a string name or a
2047  * symbol identifier). _cmd_ (which may be a string or a
2048  * +Proc+ object) or block is executed whenever the variable
2049  * is assigned. The block or +Proc+ object receives the
2050  * variable's new value as a parameter. Also see
2051  * #untrace_var.
2052  *
2053  * trace_var :$_, proc {|v| puts "$_ is now '#{v}'" }
2054  * $_ = "hello"
2055  * $_ = ' there'
2056  *
2057  * <em>produces:</em>
2058  *
2059  * $_ is now 'hello'
2060  * $_ is now ' there'
2061  */
2062 
2063 static VALUE
2064 f_trace_var(int c, const VALUE *a, VALUE _)
2065 {
2066  return rb_f_trace_var(c, a);
2067 }
2068 
2069 /*
2070  * call-seq:
2071  * untrace_var(symbol [, cmd] ) -> array or nil
2072  *
2073  * Removes tracing for the specified command on the given global
2074  * variable and returns +nil+. If no command is specified,
2075  * removes all tracing for that variable and returns an array
2076  * containing the commands actually removed.
2077  */
2078 
2079 static VALUE
2080 f_untrace_var(int c, const VALUE *a, VALUE _)
2081 {
2082  return rb_f_untrace_var(c, a);
2083 }
2084 
2085 void
2086 Init_eval(void)
2087 {
2088  rb_define_virtual_variable("$@", errat_getter, errat_setter);
2089  rb_define_virtual_variable("$!", errinfo_getter, 0);
2090 
2091  rb_gvar_ractor_local("$@");
2092  rb_gvar_ractor_local("$!");
2093 
2094  rb_define_global_function("raise", f_raise, -1);
2095  rb_define_global_function("fail", f_raise, -1);
2096 
2097  rb_define_global_function("global_variables", f_global_variables, 0);
2098 
2099  rb_define_global_function("__method__", rb_f_method_name, 0);
2100  rb_define_global_function("__callee__", rb_f_callee_name, 0);
2101  rb_define_global_function("__dir__", f_current_dirname, 0);
2102 
2103  rb_define_method(rb_cModule, "include", rb_mod_include, -1);
2104  rb_define_method(rb_cModule, "prepend", rb_mod_prepend, -1);
2105 
2106  rb_define_private_method(rb_cModule, "append_features", rb_mod_append_features, 1);
2107  rb_define_private_method(rb_cModule, "extend_object", rb_mod_extend_object, 1);
2108  rb_define_private_method(rb_cModule, "prepend_features", rb_mod_prepend_features, 1);
2109  rb_define_private_method(rb_cModule, "refine", rb_mod_refine, 1);
2110  rb_define_private_method(rb_cModule, "using", mod_using, 1);
2111  rb_define_method(rb_cModule, "refinements", mod_refinements, 0);
2112  rb_define_singleton_method(rb_cModule, "used_modules",
2113  rb_mod_s_used_modules, 0);
2114  rb_define_singleton_method(rb_cModule, "used_refinements",
2115  rb_mod_s_used_refinements, 0);
2116  rb_undef_method(rb_cClass, "refine");
2117  rb_define_private_method(rb_cRefinement, "import_methods", refinement_import_methods, -1);
2118  rb_define_method(rb_cRefinement, "target", rb_refinement_module_get_refined_class, 0);
2119  rb_undef_method(rb_cRefinement, "append_features");
2120  rb_undef_method(rb_cRefinement, "prepend_features");
2121  rb_undef_method(rb_cRefinement, "extend_object");
2122 
2123  rb_undef_method(rb_cClass, "module_function");
2124 
2125  Init_vm_eval();
2126  Init_eval_method();
2127 
2128  rb_define_singleton_method(rb_cModule, "nesting", rb_mod_nesting, 0);
2129  rb_define_singleton_method(rb_cModule, "constants", rb_mod_s_constants, -1);
2130 
2131  rb_define_private_method(rb_singleton_class(rb_vm_top_self()),
2132  "include", top_include, -1);
2133  rb_define_private_method(rb_singleton_class(rb_vm_top_self()),
2134  "using", top_using, 1);
2135 
2136  rb_define_method(rb_mKernel, "extend", rb_obj_extend, -1);
2137 
2138  rb_define_global_function("trace_var", f_trace_var, -1);
2139  rb_define_global_function("untrace_var", f_untrace_var, -1);
2140 
2141  rb_vm_register_special_exception(ruby_error_reenter, rb_eFatal, "exception reentered");
2142  rb_vm_register_special_exception(ruby_error_stackfatal, rb_eFatal, "machine stack overflow in critical region");
2143 
2144  id_signo = rb_intern_const("signo");
2145  id_status = rb_intern_const("status");
2146 }
2147 
2148 int
2150 {
2151  return *rb_orig_errno_ptr();
2152 }
2153 
2154 void
2156 {
2157  *rb_orig_errno_ptr() = e;
2158 }
2159 
2160 int *
2162 {
2163  return rb_orig_errno_ptr();
2164 }
#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_singleton_method(klass, mid, func, arity)
Defines klass.mid.
Definition: cxxanyargs.hpp:685
#define rb_define_private_method(klass, mid, func, arity)
Defines klass#mid and makes it private.
Definition: cxxanyargs.hpp:677
#define RUBY_EVENT_RAISE
Encountered a raise statement.
Definition: event.h:45
#define RUBY_EVENT_C_RETURN
Return from a method, written in C.
Definition: event.h:44
void rb_include_module(VALUE klass, VALUE module)
Includes a module to a class.
Definition: class.c:1187
VALUE rb_refinement_new(void)
Creates a new, anonymous refinement.
Definition: class.c:1082
void rb_extend_object(VALUE obj, VALUE module)
Extend the object with the module.
Definition: eval.c:1735
void rb_prepend_module(VALUE klass, VALUE module)
Identical to rb_include_module(), except it "prepends" the passed module to the klass,...
Definition: class.c:1438
VALUE rb_singleton_class(VALUE obj)
Finds or creates the singleton class of the passed object.
Definition: class.c:2297
void rb_class_modify_check(VALUE klass)
Asserts that klass is not a frozen class.
Definition: eval.c:419
void rb_need_block(void)
Declares that the current method needs a block.
Definition: eval.c:937
ID rb_frame_last_func(void)
Returns the ID of the last method in the call stack.
Definition: eval.c:1139
void rb_undef_method(VALUE klass, const char *name)
Defines an undef of a method.
Definition: class.c:2166
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:2635
void rb_define_method(VALUE klass, const char *name, VALUE(*func)(ANYARGS), int argc)
Defines a method.
Definition: class.c:2142
int rb_keyword_given_p(void)
Determines if the current method is given a keyword argument.
Definition: eval.c:929
int rb_block_given_p(void)
Determines if the current method is given a block.
Definition: eval.c:916
int rb_get_kwargs(VALUE keyword_hash, const ID *table, int required, int optional, VALUE *values)
Keyword argument deconstructor.
Definition: class.c:2424
void rb_define_global_function(const char *name, VALUE(*func)(ANYARGS), int argc)
Defines a global function.
Definition: class.c:2339
#define Qundef
Old name of RUBY_Qundef.
#define INT2FIX
Old name of RB_INT2FIX.
Definition: long.h:48
#define OBJ_FROZEN
Old name of RB_OBJ_FROZEN.
Definition: fl_type.h:137
#define UNREACHABLE
Old name of RBIMPL_UNREACHABLE.
Definition: assume.h:28
#define ID2SYM
Old name of RB_ID2SYM.
Definition: symbol.h:44
#define SPECIAL_CONST_P
Old name of RB_SPECIAL_CONST_P.
#define OBJ_FREEZE
Old name of RB_OBJ_FREEZE.
Definition: fl_type.h:135
#define UNREACHABLE_RETURN
Old name of RBIMPL_UNREACHABLE_RETURN.
Definition: assume.h:29
#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 T_ICLASS
Old name of RUBY_T_ICLASS.
Definition: value_type.h:66
#define FL_SET
Old name of RB_FL_SET.
Definition: fl_type.h:129
#define rb_exc_new3
Old name of rb_exc_new_str.
Definition: error.h:38
#define Qtrue
Old name of RUBY_Qtrue.
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define T_OBJECT
Old name of RUBY_T_OBJECT.
Definition: value_type.h:75
#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 FL_TEST
Old name of RB_FL_TEST.
Definition: fl_type.h:131
#define FIXNUM_P
Old name of RB_FIXNUM_P.
#define CONST_ID
Old name of RUBY_CONST_ID.
Definition: symbol.h:47
void ruby_stop(int ex)
Calls ruby_cleanup() and exits the process.
Definition: eval.c:288
int ruby_exec_node(void *n)
Identical to ruby_run_node(), except it returns an opaque execution status.
Definition: eval.c:323
int ruby_setup(void)
Initializes the VM and builtin libraries.
Definition: eval.c:66
void ruby_finalize(void)
Runs the VM finalization processes.
Definition: eval.c:168
int ruby_cleanup(int ex)
Destructs the VM.
Definition: eval.c:176
void * ruby_process_options(int argc, char **argv)
Identical to ruby_options(), except it raises ruby-level exceptions on failure.
Definition: ruby.c:3148
void ruby_prog_init(void)
Defines built-in variables.
Definition: ruby.c:3101
void ruby_sig_finalize(void)
Clear signal handlers.
Definition: signal.c:1437
#define ruby_debug
This variable controls whether the interpreter is in debug mode.
Definition: error.h:486
VALUE rb_eLocalJumpError
LocalJumpError exception.
Definition: eval.c:49
void rb_raise(VALUE exc, const char *fmt,...)
Exception entry point.
Definition: error.c:3635
VALUE rb_rescue2(VALUE(*b_proc)(VALUE), VALUE data1, VALUE(*r_proc)(VALUE, VALUE), VALUE data2,...)
An equivalent of rescue clause.
Definition: eval.c:945
void rb_exc_raise(VALUE mesg)
Raises an exception in the current thread.
Definition: eval.c:676
VALUE rb_eSystemExit
SystemExit exception.
Definition: error.c:1401
VALUE rb_eStandardError
StandardError exception.
Definition: error.c:1405
void rb_set_errinfo(VALUE err)
Sets the current exception ($!) to the given value.
Definition: eval.c:1926
VALUE rb_eTypeError
TypeError exception.
Definition: error.c:1408
VALUE rb_vrescue2(VALUE(*b_proc)(VALUE), VALUE data1, VALUE(*r_proc)(VALUE, VALUE), VALUE data2, va_list args)
Identical to rb_rescue2(), except it takes va_list instead of variadic number of arguments.
Definition: eval.c:956
void rb_frozen_error_raise(VALUE frozen_obj, const char *fmt,...)
Raises an instance of rb_eFrozenError.
Definition: error.c:3959
VALUE rb_eFatal
fatal exception.
Definition: error.c:1404
VALUE rb_eInterrupt
Interrupt exception.
Definition: error.c:1402
void rb_exc_fatal(VALUE mesg)
Raises a fatal error in the current thread.
Definition: eval.c:689
VALUE rb_eRuntimeError
RuntimeError exception.
Definition: error.c:1406
void rb_warn(const char *fmt,...)
Identical to rb_warning(), except it reports unless $VERBOSE is nil.
Definition: error.c:466
VALUE rb_exc_new(VALUE etype, const char *ptr, long len)
Creates an instance of the passed exception class.
Definition: error.c:1446
VALUE rb_eArgError
ArgumentError exception.
Definition: error.c:1409
VALUE rb_eException
Mother of all exceptions.
Definition: error.c:1400
VALUE rb_rescue(VALUE(*b_proc)(VALUE), VALUE data1, VALUE(*r_proc)(VALUE, VALUE), VALUE data2)
Identical to rb_rescue2(), except it does not take a list of exception classes.
Definition: eval.c:1016
VALUE rb_ensure(VALUE(*b_proc)(VALUE), VALUE data1, VALUE(*e_proc)(VALUE), VALUE data2)
An equivalent to ensure clause.
Definition: eval.c:1045
VALUE rb_errinfo(void)
This is the same as $! in Ruby.
Definition: eval.c:1920
VALUE rb_eSysStackError
SystemStackError exception.
Definition: eval.c:50
VALUE rb_eThreadError
ThreadError exception.
Definition: eval.c:934
void rb_warning(const char *fmt,...)
Issues a warning.
Definition: error.c:497
VALUE rb_cClass
Class class.
Definition: object.c:68
VALUE rb_mKernel
Kernel module.
Definition: object.c:65
VALUE rb_cRefinement
Refinement class.
Definition: object.c:69
static VALUE rb_class_of(VALUE obj)
Object to class mapping function.
Definition: globals.h:172
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
Definition: object.c:247
VALUE rb_obj_dup(VALUE obj)
Duplicates the given object.
Definition: object.c:576
VALUE rb_cBasicObject
BasicObject class.
Definition: object.c:64
VALUE rb_cModule
Module class.
Definition: object.c:67
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:865
#define RB_OBJ_WRITE(old, slot, young)
Declaration of a "back" pointer.
Definition: gc.h:603
int ruby_run_node(void *n)
Runs the given compiled source and exits this process.
Definition: eval.c:311
void ruby_init(void)
Calls ruby_setup() and check error.
Definition: eval.c:96
void * ruby_options(int argc, char **argv)
Processes command line arguments and compiles the Ruby source to execute.
Definition: eval.c:109
int ruby_executable_node(void *n, int *status)
Checks the return value of ruby_options().
Definition: eval.c:294
VALUE rb_funcall(VALUE recv, ID mid, int n,...)
Calls a method.
Definition: vm_eval.c:1099
VALUE rb_funcallv_kw(VALUE recv, ID mid, int argc, const VALUE *argv, int kw_splat)
Identical to rb_funcallv(), except you can specify how to handle the last element of the given array.
Definition: vm_eval.c:1066
VALUE rb_ary_new(void)
Allocates a new, empty array.
Definition: array.c:747
VALUE rb_ary_push(VALUE ary, VALUE elem)
Special case of rb_ary_cat() that it adds only one element.
Definition: array.c:1384
#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
ID rb_frame_callee(void)
Identical to rb_frame_this_func(), except it returns the named used to call the method.
Definition: eval.c:1100
ID rb_frame_this_func(void)
Queries the name of the Ruby level method that is calling this function.
Definition: eval.c:1094
void rb_obj_call_init(VALUE obj, int argc, const VALUE *argv)
Calls initialize method of the passed object with the passed arguments.
Definition: eval.c:1722
void rb_interrupt(void)
Raises an instance of rb_eInterrupt.
Definition: eval.c:695
VALUE rb_make_exception(int argc, const VALUE *argv)
Constructs an exception object from the list of arguments, in a manner similar to Ruby's raise.
Definition: eval.c:883
void rb_jump_tag(int state)
This function is to re-throw global escapes.
Definition: eval.c:907
void rb_obj_call_init_kw(VALUE, int, const VALUE *, int)
Identical to rb_obj_call_init(), except you can specify how to handle the last element of the given a...
Definition: eval.c:1728
VALUE rb_file_dirname(VALUE fname)
Strips a file path's last component (and trailing separators if any).
Definition: file.c:4890
void rb_hash_foreach(VALUE hash, int(*func)(VALUE key, VALUE val, VALUE arg), VALUE arg)
Iterates over a hash.
VALUE rb_hash_aset(VALUE hash, VALUE key, VALUE val)
Inserts or replaces ("upsert"s) the objects into the given hash table.
Definition: hash.c:2893
VALUE rb_hash_lookup(VALUE hash, VALUE key)
Identical to rb_hash_aref(), except it always returns RUBY_Qnil for misshits.
Definition: hash.c:2099
VALUE rb_hash_dup(VALUE hash)
Duplicates a hash.
Definition: hash.c:1563
VALUE rb_protect(VALUE(*func)(VALUE args), VALUE args, int *state)
Protects a function call from potential global escapes from the function.
void ruby_default_signal(int sig)
Pretends as if there was no custom signal handler.
Definition: signal.c:411
#define rb_exc_new_cstr(exc, str)
Identical to rb_exc_new(), except it assumes the passed pointer is a pointer to a C string.
Definition: string.h:1670
VALUE rb_str_new(const char *ptr, long len)
Allocates an instance of rb_cString.
Definition: string.c:1050
VALUE rb_check_string_type(VALUE obj)
Try converting an object to its stringised representation using its to_str method,...
Definition: string.c:2854
VALUE rb_obj_as_string(VALUE obj)
Try converting an object to its stringised representation using its to_s method, if any.
Definition: string.c:1786
VALUE rb_f_untrace_var(int argc, const VALUE *argv)
Deletes the passed tracer from the passed global variable, or if omitted, deletes everything.
Definition: variable.c:801
VALUE rb_const_list(void *)
This is another mysterious API that comes with no documents at all.
Definition: variable.c:3385
VALUE rb_attr_get(VALUE obj, ID name)
Identical to rb_ivar_get()
Definition: variable.c:1358
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:1859
VALUE rb_f_trace_var(int argc, const VALUE *argv)
Traces a global variable.
Definition: variable.c:755
void * rb_mod_const_at(VALUE, void *)
This API is mysterious.
Definition: variable.c:3346
VALUE rb_mod_constants(int argc, const VALUE *argv, VALUE recv)
Resembles Module#constants.
Definition: variable.c:3417
VALUE rb_ivar_defined(VALUE obj, ID name)
Queries if the instance variable is defined at the object.
Definition: variable.c:1876
VALUE rb_f_global_variables(void)
Queries the list of global variables.
Definition: variable.c:955
VALUE rb_class_path(VALUE mod)
Identical to rb_mod_name(), except it returns #<Class: ...> style inspection for anonymous modules.
Definition: variable.c:293
void * rb_mod_const_of(VALUE, void *)
This is a variant of rb_mod_const_at().
Definition: variable.c:3363
VALUE rb_check_funcall(VALUE recv, ID mid, int argc, const VALUE *argv)
Identical to rb_funcallv(), except it returns RUBY_Qundef instead of raising rb_eNoMethodError.
Definition: vm_eval.c:668
static ID rb_intern_const(const char *str)
This is a "tiny optimisation" over rb_intern().
Definition: symbol.h:276
ID rb_intern(const char *name)
Finds or creates a symbol of the given name.
Definition: symbol.c:823
VALUE rb_id2str(ID id)
Identical to rb_id2name(), except it returns a Ruby's String instead of C's.
Definition: symbol.c:986
void rb_define_virtual_variable(const char *name, rb_gvar_getter_t *getter, rb_gvar_setter_t *setter)
Defines a global variable that is purely function-backended.
Definition: variable.c:738
char * ptr
Pointer to the underlying memory region, of at least capa bytes.
Definition: io.h:2
int ruby_vm_destruct(ruby_vm_t *vm)
Destructs the passed VM.
Definition: vm.c:3063
VALUE rb_sprintf(const char *fmt,...)
Ruby's extended sprintf(3).
Definition: sprintf.c:1217
#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 RHASH_EMPTY_P(h)
Checks if the hash is empty.
Definition: rhash.h:79
static int * rb_orig_errno_ptr(void)
Not sure if it is necessary for extension libraries but this is where the "bare" errno is located.
Definition: ruby.h:381
int * rb_errno_ptr(void)
The location of errno
Definition: eval.c:2161
const char * rb_obj_classname(VALUE obj)
Queries the name of the class of the passed object.
Definition: variable.c:427
int rb_errno(void)
Identical to system errno.
Definition: eval.c:2149
void rb_errno_set(int err)
Set the errno.
Definition: eval.c:2155
#define RB_NO_KEYWORDS
Do not pass keywords.
Definition: scan_args.h:69
Scheduler APIs.
VALUE rb_fiber_scheduler_set(VALUE scheduler)
Destructively assigns the passed scheduler to that of the current thread that is calling this functio...
Definition: scheduler.c:187
#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: method.h:62
CREF (Class REFerence)
Definition: method.h:44
Definition: method.h:54
rb_cref_t * cref
class reference, should be marked
Definition: method.h:136
const rb_iseq_t * iseqptr
iseq pointer, should be separated from iseqval
Definition: method.h:135
uintptr_t ID
Type that represents a Ruby identifier such as a variable name.
Definition: value.h:52
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:433
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