Ruby  3.4.0dev (2024-11-22 revision 37a72b0150ec36b4ea27175039afc28c62207b0c)
error.c (37a72b0150ec36b4ea27175039afc28c62207b0c)
1 /**********************************************************************
2 
3  error.c -
4 
5  $Author$
6  created at: Mon Aug 9 16:11:34 JST 1993
7 
8  Copyright (C) 1993-2007 Yukihiro Matsumoto
9 
10 **********************************************************************/
11 
12 #include "ruby/internal/config.h"
13 
14 #include <errno.h>
15 #include <stdarg.h>
16 #include <stdio.h>
17 
18 #ifdef HAVE_STDLIB_H
19 # include <stdlib.h>
20 #endif
21 
22 #ifdef HAVE_UNISTD_H
23 # include <unistd.h>
24 #endif
25 
26 #ifdef HAVE_SYS_WAIT_H
27 # include <sys/wait.h>
28 #endif
29 
30 #if defined __APPLE__
31 # include <AvailabilityMacros.h>
32 #endif
33 
34 #include "internal.h"
35 #include "internal/class.h"
36 #include "internal/error.h"
37 #include "internal/eval.h"
38 #include "internal/hash.h"
39 #include "internal/io.h"
40 #include "internal/load.h"
41 #include "internal/object.h"
42 #include "internal/process.h"
43 #include "internal/string.h"
44 #include "internal/symbol.h"
45 #include "internal/thread.h"
46 #include "internal/variable.h"
47 #include "ruby/encoding.h"
48 #include "ruby/st.h"
49 #include "ruby/util.h"
50 #include "ruby_assert.h"
51 #include "vm_core.h"
52 #include "yjit.h"
53 
54 #include "builtin.h"
55 
61 #ifndef EXIT_SUCCESS
62 #define EXIT_SUCCESS 0
63 #endif
64 
65 #ifndef WIFEXITED
66 #define WIFEXITED(status) 1
67 #endif
68 
69 #ifndef WEXITSTATUS
70 #define WEXITSTATUS(status) (status)
71 #endif
72 
73 VALUE rb_iseqw_local_variables(VALUE iseqval);
74 VALUE rb_iseqw_new(const rb_iseq_t *);
75 int rb_str_end_with_asciichar(VALUE str, int c);
76 
77 long rb_backtrace_length_limit = -1;
78 VALUE rb_eEAGAIN;
79 VALUE rb_eEWOULDBLOCK;
80 VALUE rb_eEINPROGRESS;
81 static VALUE rb_mWarning;
82 static VALUE rb_cWarningBuffer;
83 
84 static ID id_warn;
85 static ID id_category;
86 static ID id_deprecated;
87 static ID id_experimental;
88 static ID id_performance;
89 static ID id_strict_unused_block;
90 static VALUE sym_category;
91 static VALUE sym_highlight;
92 static struct {
93  st_table *id2enum, *enum2id;
94 } warning_categories;
95 
96 extern const char *rb_dynamic_description;
97 
98 static const char *
99 rb_strerrno(int err)
100 {
101 #define defined_error(name, num) if (err == (num)) return (name);
102 #define undefined_error(name)
103 #include "known_errors.inc"
104 #undef defined_error
105 #undef undefined_error
106  return NULL;
107 }
108 
109 static int
110 err_position_0(char *buf, long len, const char *file, int line)
111 {
112  if (!file) {
113  return 0;
114  }
115  else if (line == 0) {
116  return snprintf(buf, len, "%s: ", file);
117  }
118  else {
119  return snprintf(buf, len, "%s:%d: ", file, line);
120  }
121 }
122 
123 RBIMPL_ATTR_FORMAT(RBIMPL_PRINTF_FORMAT, 5, 0)
124 static VALUE
125 err_vcatf(VALUE str, const char *pre, const char *file, int line,
126  const char *fmt, va_list args)
127 {
128  if (file) {
129  rb_str_cat2(str, file);
130  if (line) rb_str_catf(str, ":%d", line);
131  rb_str_cat2(str, ": ");
132  }
133  if (pre) rb_str_cat2(str, pre);
134  rb_str_vcatf(str, fmt, args);
135  return str;
136 }
137 
138 static VALUE syntax_error_with_path(VALUE, VALUE, VALUE*, rb_encoding*);
139 
140 VALUE
141 rb_syntax_error_append(VALUE exc, VALUE file, int line, int column,
142  rb_encoding *enc, const char *fmt, va_list args)
143 {
144  const char *fn = NIL_P(file) ? NULL : RSTRING_PTR(file);
145  if (!exc) {
146  VALUE mesg = rb_enc_str_new(0, 0, enc);
147  err_vcatf(mesg, NULL, fn, line, fmt, args);
148  rb_str_cat2(mesg, "\n");
149  rb_write_error_str(mesg);
150  }
151  else {
152  VALUE mesg;
153  exc = syntax_error_with_path(exc, file, &mesg, enc);
154  err_vcatf(mesg, NULL, fn, line, fmt, args);
155  }
156 
157  return exc;
158 }
159 
160 static unsigned int warning_disabled_categories = (
162  ~RB_WARN_CATEGORY_DEFAULT_BITS);
163 
164 static unsigned int
165 rb_warning_category_mask(VALUE category)
166 {
167  return 1U << rb_warning_category_from_name(category);
168 }
169 
171 rb_warning_category_from_name(VALUE category)
172 {
173  st_data_t cat_value;
174  ID cat_id;
175  Check_Type(category, T_SYMBOL);
176  if (!(cat_id = rb_check_id(&category)) ||
177  !st_lookup(warning_categories.id2enum, cat_id, &cat_value)) {
178  rb_raise(rb_eArgError, "unknown category: %"PRIsVALUE, category);
179  }
180  return (rb_warning_category_t)cat_value;
181 }
182 
183 static VALUE
184 rb_warning_category_to_name(rb_warning_category_t category)
185 {
186  st_data_t id;
187  if (!st_lookup(warning_categories.enum2id, category, &id)) {
188  rb_raise(rb_eArgError, "invalid category: %d", (int)category);
189  }
190  return id ? ID2SYM(id) : Qnil;
191 }
192 
193 void
194 rb_warning_category_update(unsigned int mask, unsigned int bits)
195 {
196  warning_disabled_categories &= ~mask;
197  warning_disabled_categories |= mask & ~bits;
198 }
199 
200 bool
201 rb_warning_category_enabled_p(rb_warning_category_t category)
202 {
203  return !(warning_disabled_categories & (1U << category));
204 }
205 
206 /*
207  * call-seq:
208  * Warning[category] -> true or false
209  *
210  * Returns the flag to show the warning messages for +category+.
211  * Supported categories are:
212  *
213  * +:deprecated+ ::
214  * deprecation warnings
215  * * assignment of non-nil value to <code>$,</code> and <code>$;</code>
216  * * keyword arguments
217  * etc.
218  *
219  * +:experimental+ ::
220  * experimental features
221  *
222  * +:performance+ ::
223  * performance hints
224  * * Shape variation limit
225  */
226 
227 static VALUE
228 rb_warning_s_aref(VALUE mod, VALUE category)
229 {
230  rb_warning_category_t cat = rb_warning_category_from_name(category);
231  return RBOOL(rb_warning_category_enabled_p(cat));
232 }
233 
234 /*
235  * call-seq:
236  * Warning[category] = flag -> flag
237  *
238  * Sets the warning flags for +category+.
239  * See Warning.[] for the categories.
240  */
241 
242 static VALUE
243 rb_warning_s_aset(VALUE mod, VALUE category, VALUE flag)
244 {
245  unsigned int mask = rb_warning_category_mask(category);
246  unsigned int disabled = warning_disabled_categories;
247  if (!RTEST(flag))
248  disabled |= mask;
249  else
250  disabled &= ~mask;
251  warning_disabled_categories = disabled;
252  return flag;
253 }
254 
255 /*
256  * call-seq:
257  * categories -> array
258  *
259  * Returns a list of the supported category symbols.
260  */
261 
262 static VALUE
263 rb_warning_s_categories(VALUE mod)
264 {
265  st_index_t num = warning_categories.id2enum->num_entries;
266  ID *ids = ALLOCA_N(ID, num);
267  num = st_keys(warning_categories.id2enum, ids, num);
268  VALUE ary = rb_ary_new_capa(num);
269  for (st_index_t i = 0; i < num; ++i) {
270  rb_ary_push(ary, ID2SYM(ids[i]));
271  }
272  return rb_ary_freeze(ary);
273 }
274 
275 /*
276  * call-seq:
277  * warn(msg, category: nil) -> nil
278  *
279  * Writes warning message +msg+ to $stderr. This method is called by
280  * Ruby for all emitted warnings. A +category+ may be included with
281  * the warning.
282  *
283  * See the documentation of the Warning module for how to customize this.
284  */
285 
286 static VALUE
287 rb_warning_s_warn(int argc, VALUE *argv, VALUE mod)
288 {
289  VALUE str;
290  VALUE opt;
291  VALUE category = Qnil;
292 
293  rb_scan_args(argc, argv, "1:", &str, &opt);
294  if (!NIL_P(opt)) rb_get_kwargs(opt, &id_category, 0, 1, &category);
295 
296  Check_Type(str, T_STRING);
297  rb_must_asciicompat(str);
298  if (!NIL_P(category)) {
299  rb_warning_category_t cat = rb_warning_category_from_name(category);
300  if (!rb_warning_category_enabled_p(cat)) return Qnil;
301  }
302  rb_write_error_str(str);
303  return Qnil;
304 }
305 
306 /*
307  * Document-module: Warning
308  *
309  * The Warning module contains a single method named #warn, and the
310  * module extends itself, making Warning.warn available.
311  * Warning.warn is called for all warnings issued by Ruby.
312  * By default, warnings are printed to $stderr.
313  *
314  * Changing the behavior of Warning.warn is useful to customize how warnings are
315  * handled by Ruby, for instance by filtering some warnings, and/or outputting
316  * warnings somewhere other than <tt>$stderr</tt>.
317  *
318  * If you want to change the behavior of Warning.warn you should use
319  * <tt>Warning.extend(MyNewModuleWithWarnMethod)</tt> and you can use +super+
320  * to get the default behavior of printing the warning to <tt>$stderr</tt>.
321  *
322  * Example:
323  * module MyWarningFilter
324  * def warn(message, category: nil, **kwargs)
325  * if /some warning I want to ignore/.match?(message)
326  * # ignore
327  * else
328  * super
329  * end
330  * end
331  * end
332  * Warning.extend MyWarningFilter
333  *
334  * You should never redefine Warning#warn (the instance method), as that will
335  * then no longer provide a way to use the default behavior.
336  *
337  * The warning[https://rubygems.org/gems/warning] gem provides convenient ways to customize Warning.warn.
338  */
339 
340 static VALUE
341 rb_warning_warn(VALUE mod, VALUE str)
342 {
343  return rb_funcallv(mod, id_warn, 1, &str);
344 }
345 
346 
347 static int
348 rb_warning_warn_arity(void)
349 {
350  const rb_method_entry_t *me = rb_method_entry(rb_singleton_class(rb_mWarning), id_warn);
351  return me ? rb_method_entry_arity(me) : 1;
352 }
353 
354 static VALUE
355 rb_warn_category(VALUE str, VALUE category)
356 {
357  if (RUBY_DEBUG && !NIL_P(category)) {
358  rb_warning_category_from_name(category);
359  }
360 
361  if (rb_warning_warn_arity() == 1) {
362  return rb_warning_warn(rb_mWarning, str);
363  }
364  else {
365  VALUE args[2];
366  args[0] = str;
367  args[1] = rb_hash_new();
368  rb_hash_aset(args[1], sym_category, category);
369  return rb_funcallv_kw(rb_mWarning, id_warn, 2, args, RB_PASS_KEYWORDS);
370  }
371 }
372 
373 static void
374 rb_write_warning_str(VALUE str)
375 {
376  rb_warning_warn(rb_mWarning, str);
377 }
378 
379 RBIMPL_ATTR_FORMAT(RBIMPL_PRINTF_FORMAT, 4, 0)
380 static VALUE
381 warn_vsprintf(rb_encoding *enc, const char *file, int line, const char *fmt, va_list args)
382 {
383  VALUE str = rb_enc_str_new(0, 0, enc);
384 
385  err_vcatf(str, "warning: ", file, line, fmt, args);
386  return rb_str_cat2(str, "\n");
387 }
388 
389 #define with_warn_vsprintf(enc, file, line, fmt) \
390  VALUE str; \
391  va_list args; \
392  va_start(args, fmt); \
393  str = warn_vsprintf(enc, file, line, fmt, args); \
394  va_end(args);
395 
396 void
397 rb_compile_warn(const char *file, int line, const char *fmt, ...)
398 {
399  if (!NIL_P(ruby_verbose)) {
400  with_warn_vsprintf(NULL, file, line, fmt) {
401  rb_write_warning_str(str);
402  }
403  }
404 }
405 
406 void
407 rb_enc_compile_warn(rb_encoding *enc, const char *file, int line, const char *fmt, ...)
408 {
409  if (!NIL_P(ruby_verbose)) {
410  with_warn_vsprintf(enc, file, line, fmt) {
411  rb_write_warning_str(str);
412  }
413  }
414 }
415 
416 /* rb_compile_warning() reports only in verbose mode */
417 void
418 rb_compile_warning(const char *file, int line, const char *fmt, ...)
419 {
420  if (RTEST(ruby_verbose)) {
421  with_warn_vsprintf(NULL, file, line, fmt) {
422  rb_write_warning_str(str);
423  }
424  }
425 }
426 
427 /* rb_enc_compile_warning() reports only in verbose mode */
428 void
429 rb_enc_compile_warning(rb_encoding *enc, const char *file, int line, const char *fmt, ...)
430 {
431  if (RTEST(ruby_verbose)) {
432  with_warn_vsprintf(enc, file, line, fmt) {
433  rb_write_warning_str(str);
434  }
435  }
436 }
437 
438 void
439 rb_category_compile_warn(rb_warning_category_t category, const char *file, int line, const char *fmt, ...)
440 {
441  if (!NIL_P(ruby_verbose)) {
442  with_warn_vsprintf(NULL, file, line, fmt) {
443  rb_warn_category(str, rb_warning_category_to_name(category));
444  }
445  }
446 }
447 
448 RBIMPL_ATTR_FORMAT(RBIMPL_PRINTF_FORMAT, 2, 0)
449 static VALUE
450 warning_string(rb_encoding *enc, const char *fmt, va_list args)
451 {
452  int line;
453  const char *file = rb_source_location_cstr(&line);
454  return warn_vsprintf(enc, file, line, fmt, args);
455 }
456 
457 #define with_warning_string(mesg, enc, fmt) \
458  with_warning_string_from(mesg, enc, fmt, fmt)
459 #define with_warning_string_from(mesg, enc, fmt, last_arg) \
460  VALUE mesg; \
461  va_list args; va_start(args, last_arg); \
462  mesg = warning_string(enc, fmt, args); \
463  va_end(args);
464 
465 void
466 rb_warn(const char *fmt, ...)
467 {
468  if (!NIL_P(ruby_verbose)) {
469  with_warning_string(mesg, 0, fmt) {
470  rb_write_warning_str(mesg);
471  }
472  }
473 }
474 
475 void
476 rb_category_warn(rb_warning_category_t category, const char *fmt, ...)
477 {
478  if (!NIL_P(ruby_verbose) && rb_warning_category_enabled_p(category)) {
479  with_warning_string(mesg, 0, fmt) {
480  rb_warn_category(mesg, rb_warning_category_to_name(category));
481  }
482  }
483 }
484 
485 void
486 rb_enc_warn(rb_encoding *enc, const char *fmt, ...)
487 {
488  if (!NIL_P(ruby_verbose)) {
489  with_warning_string(mesg, enc, fmt) {
490  rb_write_warning_str(mesg);
491  }
492  }
493 }
494 
495 /* rb_warning() reports only in verbose mode */
496 void
497 rb_warning(const char *fmt, ...)
498 {
499  if (RTEST(ruby_verbose)) {
500  with_warning_string(mesg, 0, fmt) {
501  rb_write_warning_str(mesg);
502  }
503  }
504 }
505 
506 /* rb_category_warning() reports only in verbose mode */
507 void
508 rb_category_warning(rb_warning_category_t category, const char *fmt, ...)
509 {
510  if (RTEST(ruby_verbose) && rb_warning_category_enabled_p(category)) {
511  with_warning_string(mesg, 0, fmt) {
512  rb_warn_category(mesg, rb_warning_category_to_name(category));
513  }
514  }
515 }
516 
517 VALUE
518 rb_warning_string(const char *fmt, ...)
519 {
520  with_warning_string(mesg, 0, fmt) {
521  }
522  return mesg;
523 }
524 
525 #if 0
526 void
527 rb_enc_warning(rb_encoding *enc, const char *fmt, ...)
528 {
529  if (RTEST(ruby_verbose)) {
530  with_warning_string(mesg, enc, fmt) {
531  rb_write_warning_str(mesg);
532  }
533  }
534 }
535 #endif
536 
537 static bool
538 deprecation_warning_enabled(void)
539 {
540  if (NIL_P(ruby_verbose)) return false;
541  if (!rb_warning_category_enabled_p(RB_WARN_CATEGORY_DEPRECATED)) return false;
542  return true;
543 }
544 
545 static void
546 warn_deprecated(VALUE mesg, const char *removal, const char *suggest)
547 {
548  rb_str_set_len(mesg, RSTRING_LEN(mesg) - 1);
549  rb_str_cat_cstr(mesg, " is deprecated");
550  if (removal) {
551  rb_str_catf(mesg, " and will be removed in Ruby %s", removal);
552  }
553  if (suggest) rb_str_catf(mesg, "; use %s instead", suggest);
554  rb_str_cat_cstr(mesg, "\n");
555  rb_warn_category(mesg, ID2SYM(id_deprecated));
556 }
557 
558 void
559 rb_warn_deprecated(const char *fmt, const char *suggest, ...)
560 {
561  if (!deprecation_warning_enabled()) return;
562 
563  with_warning_string_from(mesg, 0, fmt, suggest) {
564  warn_deprecated(mesg, NULL, suggest);
565  }
566 }
567 
568 void
569 rb_warn_deprecated_to_remove(const char *removal, const char *fmt, const char *suggest, ...)
570 {
571  if (!deprecation_warning_enabled()) return;
572 
573  with_warning_string_from(mesg, 0, fmt, suggest) {
574  warn_deprecated(mesg, removal, suggest);
575  }
576 }
577 
578 static inline int
579 end_with_asciichar(VALUE str, int c)
580 {
581  return RB_TYPE_P(str, T_STRING) &&
582  rb_str_end_with_asciichar(str, c);
583 }
584 
585 /* :nodoc: */
586 static VALUE
587 warning_write(int argc, VALUE *argv, VALUE buf)
588 {
589  while (argc-- > 0) {
590  rb_str_append(buf, *argv++);
591  }
592  return buf;
593 }
594 
595 VALUE rb_ec_backtrace_location_ary(const rb_execution_context_t *ec, long lev, long n, bool skip_internal);
596 
597 static VALUE
598 rb_warn_m(rb_execution_context_t *ec, VALUE exc, VALUE msgs, VALUE uplevel, VALUE category)
599 {
600  VALUE location = Qnil;
601  int argc = RARRAY_LENINT(msgs);
602  const VALUE *argv = RARRAY_CONST_PTR(msgs);
603 
604  if (!NIL_P(ruby_verbose) && argc > 0) {
605  VALUE str = argv[0];
606  if (!NIL_P(uplevel)) {
607  long lev = NUM2LONG(uplevel);
608  if (lev < 0) {
609  rb_raise(rb_eArgError, "negative level (%ld)", lev);
610  }
611  location = rb_ec_backtrace_location_ary(ec, lev + 1, 1, TRUE);
612  if (!NIL_P(location)) {
613  location = rb_ary_entry(location, 0);
614  }
615  }
616  if (argc > 1 || !NIL_P(uplevel) || !end_with_asciichar(str, '\n')) {
617  VALUE path;
618  if (NIL_P(uplevel)) {
619  str = rb_str_tmp_new(0);
620  }
621  else if (NIL_P(location) ||
622  NIL_P(path = rb_funcall(location, rb_intern("path"), 0))) {
623  str = rb_str_new_cstr("warning: ");
624  }
625  else {
626  str = rb_sprintf("%s:%ld: warning: ",
627  rb_string_value_ptr(&path),
628  NUM2LONG(rb_funcall(location, rb_intern("lineno"), 0)));
629  }
630  RBASIC_SET_CLASS(str, rb_cWarningBuffer);
631  rb_io_puts(argc, argv, str);
632  RBASIC_SET_CLASS(str, rb_cString);
633  }
634 
635  if (!NIL_P(category)) {
636  category = rb_to_symbol_type(category);
637  rb_warning_category_from_name(category);
638  }
639 
640  if (exc == rb_mWarning) {
641  rb_must_asciicompat(str);
642  rb_write_error_str(str);
643  }
644  else {
645  rb_warn_category(str, category);
646  }
647  }
648  return Qnil;
649 }
650 
651 #define MAX_BUG_REPORTERS 0x100
652 
653 static struct bug_reporters {
654  void (*func)(FILE *out, void *data);
655  void *data;
656 } bug_reporters[MAX_BUG_REPORTERS];
657 
658 static int bug_reporters_size;
659 
660 int
661 rb_bug_reporter_add(void (*func)(FILE *, void *), void *data)
662 {
663  struct bug_reporters *reporter;
664  if (bug_reporters_size >= MAX_BUG_REPORTERS) {
665  return 0; /* failed to register */
666  }
667  reporter = &bug_reporters[bug_reporters_size++];
668  reporter->func = func;
669  reporter->data = data;
670 
671  return 1;
672 }
673 
674 /* returns true if x can not be used as file name */
675 static bool
676 path_sep_p(char x)
677 {
678 #if defined __CYGWIN__ || defined DOSISH
679 # define PATH_SEP_ENCODING 1
680  // Assume that "/" is only the first byte in any encoding.
681  if (x == ':') return true; // drive letter or ADS
682  if (x == '\\') return true;
683 #endif
684  return x == '/';
685 }
686 
687 struct path_string {
688  const char *ptr;
689  size_t len;
690 };
691 
692 static const char PATHSEP_REPLACE = '!';
693 
694 static char *
695 append_pathname(char *p, const char *pe, VALUE str)
696 {
697 #ifdef PATH_SEP_ENCODING
698  rb_encoding *enc = rb_enc_get(str);
699 #endif
700  const char *s = RSTRING_PTR(str);
701  const char *const se = s + RSTRING_LEN(str);
702  char c;
703 
704  --pe; // for terminator
705 
706  while (p < pe && s < se && (c = *s) != '\0') {
707  if (c == '.') {
708  if (s == se || !*s) break; // chomp "." basename
709  if (path_sep_p(s[1])) goto skipsep; // skip "./"
710  }
711  else if (path_sep_p(c)) {
712  // squeeze successive separators
713  *p++ = PATHSEP_REPLACE;
714  skipsep:
715  while (++s < se && path_sep_p(*s));
716  continue;
717  }
718  const char *const ss = s;
719  while (p < pe && s < se && *s && !path_sep_p(*s)) {
720 #ifdef PATH_SEP_ENCODING
721  int n = rb_enc_mbclen(s, se, enc);
722 #else
723  const int n = 1;
724 #endif
725  p += n;
726  s += n;
727  }
728  if (s > ss) memcpy(p - (s - ss), ss, s - ss);
729  }
730 
731  return p;
732 }
733 
734 static char *
735 append_basename(char *p, const char *pe, struct path_string *path, VALUE str)
736 {
737  if (!path->ptr) {
738 #ifdef PATH_SEP_ENCODING
739  rb_encoding *enc = rb_enc_get(str);
740 #endif
741  const char *const b = RSTRING_PTR(str), *const e = RSTRING_END(str), *p = e;
742 
743  while (p > b) {
744  if (path_sep_p(p[-1])) {
745 #ifdef PATH_SEP_ENCODING
746  const char *t = rb_enc_prev_char(b, p, e, enc);
747  if (t == p-1) break;
748  p = t;
749 #else
750  break;
751 #endif
752  }
753  else {
754  --p;
755  }
756  }
757 
758  path->ptr = p;
759  path->len = e - p;
760  }
761  size_t n = path->len;
762  if (p + n > pe) n = pe - p;
763  memcpy(p, path->ptr, n);
764  return p + n;
765 }
766 
767 static void
768 finish_report(FILE *out, rb_pid_t pid)
769 {
770  if (out != stdout && out != stderr) fclose(out);
771 #ifdef HAVE_WORKING_FORK
772  if (pid > 0) waitpid(pid, NULL, 0);
773 #endif
774 }
775 
777  struct path_string exe, script;
778  rb_pid_t pid;
779  time_t time;
780 };
781 
782 /*
783  * Open a bug report file to write. The `RUBY_CRASH_REPORT`
784  * environment variable can be set to define a template that is used
785  * to name bug report files. The template can contain % specifiers
786  * which are substituted by the following values when a bug report
787  * file is created:
788  *
789  * %% A single % character.
790  * %e The base name of the executable filename.
791  * %E Pathname of executable, with slashes ('/') replaced by
792  * exclamation marks ('!').
793  * %f Similar to %e with the main script filename.
794  * %F Similar to %E with the main script filename.
795  * %p PID of dumped process in decimal.
796  * %t Time of dump, expressed as seconds since the Epoch,
797  * 1970-01-01 00:00:00 +0000 (UTC).
798  * %NNN Octal char code, upto 3 digits.
799  */
800 static char *
801 expand_report_argument(const char **input_template, struct report_expansion *values,
802  char *buf, size_t size, bool word)
803 {
804  char *p = buf;
805  char *end = buf + size;
806  const char *template = *input_template;
807  bool store = true;
808 
809  if (p >= end-1 || !*template) return NULL;
810  do {
811  char c = *template++;
812  if (word && ISSPACE(c)) break;
813  if (!store) continue;
814  if (c == '%') {
815  size_t n;
816  switch (c = *template++) {
817  case 'e':
818  p = append_basename(p, end, &values->exe, rb_argv0);
819  continue;
820  case 'E':
821  p = append_pathname(p, end, rb_argv0);
822  continue;
823  case 'f':
824  p = append_basename(p, end, &values->script, GET_VM()->orig_progname);
825  continue;
826  case 'F':
827  p = append_pathname(p, end, GET_VM()->orig_progname);
828  continue;
829  case 'p':
830  if (!values->pid) values->pid = getpid();
831  snprintf(p, end-p, "%" PRI_PIDT_PREFIX "d", values->pid);
832  p += strlen(p);
833  continue;
834  case 't':
835  if (!values->time) values->time = time(NULL);
836  snprintf(p, end-p, "%" PRI_TIMET_PREFIX "d", values->time);
837  p += strlen(p);
838  continue;
839  default:
840  if (c >= '0' && c <= '7') {
841  c = (unsigned char)ruby_scan_oct(template-1, 3, &n);
842  template += n - 1;
843  if (!c) store = false;
844  }
845  break;
846  }
847  }
848  if (p < end-1) *p++ = c;
849  } while (*template);
850  *input_template = template;
851  *p = '\0';
852  return ++p;
853 }
854 
855 FILE *ruby_popen_writer(char *const *argv, rb_pid_t *pid);
856 
857 static FILE *
858 open_report_path(const char *template, char *buf, size_t size, rb_pid_t *pid)
859 {
860  struct report_expansion values = {{0}};
861 
862  if (!template) return NULL;
863  if (0) fprintf(stderr, "RUBY_CRASH_REPORT=%s\n", buf);
864  if (*template == '|') {
865  char *argv[16], *bufend = buf + size, *p;
866  int argc;
867  template++;
868  for (argc = 0; argc < numberof(argv) - 1; ++argc) {
869  while (*template && ISSPACE(*template)) template++;
870  p = expand_report_argument(&template, &values, buf, bufend-buf, true);
871  if (!p) break;
872  argv[argc] = buf;
873  buf = p;
874  }
875  argv[argc] = NULL;
876  if (!p) return ruby_popen_writer(argv, pid);
877  }
878  else if (*template) {
879  expand_report_argument(&template, &values, buf, size, false);
880  return fopen(buf, "w");
881  }
882  return NULL;
883 }
884 
885 static const char *crash_report;
886 
887 /* SIGSEGV handler might have a very small stack. Thus we need to use it carefully. */
888 #define REPORT_BUG_BUFSIZ 256
889 static FILE *
890 bug_report_file(const char *file, int line, rb_pid_t *pid)
891 {
892  char buf[REPORT_BUG_BUFSIZ];
893  const char *report = crash_report;
894  if (!report) report = getenv("RUBY_CRASH_REPORT");
895  FILE *out = open_report_path(report, buf, sizeof(buf), pid);
896  int len = err_position_0(buf, sizeof(buf), file, line);
897 
898  if (out) {
899  if ((ssize_t)fwrite(buf, 1, len, out) == (ssize_t)len) return out;
900  fclose(out);
901  }
902  if ((ssize_t)fwrite(buf, 1, len, stderr) == (ssize_t)len) {
903  return stderr;
904  }
905  if ((ssize_t)fwrite(buf, 1, len, stdout) == (ssize_t)len) {
906  return stdout;
907  }
908 
909  return NULL;
910 }
911 
912 FUNC_MINIMIZED(static void bug_important_message(FILE *out, const char *const msg, size_t len));
913 
914 static void
915 bug_important_message(FILE *out, const char *const msg, size_t len)
916 {
917  const char *const endmsg = msg + len;
918  const char *p = msg;
919 
920  if (!len) return;
921  if (isatty(fileno(out))) {
922  static const char red[] = "\033[;31;1;7m";
923  static const char green[] = "\033[;32;7m";
924  static const char reset[] = "\033[m";
925  const char *e = strchr(p, '\n');
926  const int w = (int)(e - p);
927  do {
928  int i = (int)(e - p);
929  fputs(*p == ' ' ? green : red, out);
930  fwrite(p, 1, e - p, out);
931  for (; i < w; ++i) fputc(' ', out);
932  fputs(reset, out);
933  fputc('\n', out);
934  } while ((p = e + 1) < endmsg && (e = strchr(p, '\n')) != 0 && e > p + 1);
935  }
936  fwrite(p, 1, endmsg - p, out);
937 }
938 
939 #undef CRASH_REPORTER_MAY_BE_CREATED
940 #if defined(__APPLE__) && \
941  (!defined(MAC_OS_X_VERSION_10_6) || MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_6 || defined(__POWERPC__)) /* 10.6 PPC case */
942 # define CRASH_REPORTER_MAY_BE_CREATED
943 #endif
944 static void
945 preface_dump(FILE *out)
946 {
947 #if defined __APPLE__
948  static const char msg[] = ""
949  "-- Crash Report log information "
950  "--------------------------------------------\n"
951  " See Crash Report log file in one of the following locations:\n"
952 # ifdef CRASH_REPORTER_MAY_BE_CREATED
953  " * ~/Library/Logs/CrashReporter\n"
954  " * /Library/Logs/CrashReporter\n"
955 # endif
956  " * ~/Library/Logs/DiagnosticReports\n"
957  " * /Library/Logs/DiagnosticReports\n"
958  " for more details.\n"
959  "Don't forget to include the above Crash Report log file in bug reports.\n"
960  "\n";
961  const size_t msglen = sizeof(msg) - 1;
962 #else
963  const char *msg = NULL;
964  const size_t msglen = 0;
965 #endif
966  bug_important_message(out, msg, msglen);
967 }
968 
969 static void
970 postscript_dump(FILE *out)
971 {
972 #if defined __APPLE__
973  static const char msg[] = ""
974  "[IMPORTANT]"
975  /*" ------------------------------------------------"*/
976  "\n""Don't forget to include the Crash Report log file under\n"
977 # ifdef CRASH_REPORTER_MAY_BE_CREATED
978  "CrashReporter or "
979 # endif
980  "DiagnosticReports directory in bug reports.\n"
981  /*"------------------------------------------------------------\n"*/
982  "\n";
983  const size_t msglen = sizeof(msg) - 1;
984 #else
985  const char *msg = NULL;
986  const size_t msglen = 0;
987 #endif
988  bug_important_message(out, msg, msglen);
989 }
990 
991 RBIMPL_ATTR_FORMAT(RBIMPL_PRINTF_FORMAT, 2, 0)
992 static void
993 bug_report_begin_valist(FILE *out, const char *fmt, va_list args)
994 {
995  char buf[REPORT_BUG_BUFSIZ];
996 
997  fputs("[BUG] ", out);
998  vsnprintf(buf, sizeof(buf), fmt, args);
999  fputs(buf, out);
1000  snprintf(buf, sizeof(buf), "\n%s\n\n", rb_dynamic_description);
1001  fputs(buf, out);
1002  preface_dump(out);
1003 }
1004 
1005 #define bug_report_begin(out, fmt) do { \
1006  va_list args; \
1007  va_start(args, fmt); \
1008  bug_report_begin_valist(out, fmt, args); \
1009  va_end(args); \
1010 } while (0)
1011 
1012 static void
1013 bug_report_end(FILE *out, rb_pid_t pid)
1014 {
1015  /* call additional bug reporters */
1016  {
1017  int i;
1018  for (i=0; i<bug_reporters_size; i++) {
1019  struct bug_reporters *reporter = &bug_reporters[i];
1020  (*reporter->func)(out, reporter->data);
1021  }
1022  }
1023  postscript_dump(out);
1024  finish_report(out, pid);
1025 }
1026 
1027 #define report_bug(file, line, fmt, ctx) do { \
1028  rb_pid_t pid = -1; \
1029  FILE *out = bug_report_file(file, line, &pid); \
1030  if (out) { \
1031  bug_report_begin(out, fmt); \
1032  rb_vm_bugreport(ctx, out); \
1033  bug_report_end(out, pid); \
1034  } \
1035 } while (0) \
1036 
1037 #define report_bug_valist(file, line, fmt, ctx, args) do { \
1038  rb_pid_t pid = -1; \
1039  FILE *out = bug_report_file(file, line, &pid); \
1040  if (out) { \
1041  bug_report_begin_valist(out, fmt, args); \
1042  rb_vm_bugreport(ctx, out); \
1043  bug_report_end(out, pid); \
1044  } \
1045 } while (0) \
1046 
1047 void
1048 ruby_set_crash_report(const char *template)
1049 {
1050  crash_report = template;
1051 #if RUBY_DEBUG
1052  rb_pid_t pid = -1;
1053  char buf[REPORT_BUG_BUFSIZ];
1054  FILE *out = open_report_path(template, buf, sizeof(buf), &pid);
1055  if (out) {
1056  time_t t = time(NULL);
1057  fprintf(out, "ruby_test_bug_report: %s", ctime(&t));
1058  finish_report(out, pid);
1059  }
1060 #endif
1061 }
1062 
1063 NORETURN(static void die(void));
1064 static void
1065 die(void)
1066 {
1067 #if defined(_WIN32) && defined(RUBY_MSVCRT_VERSION) && RUBY_MSVCRT_VERSION >= 80
1068  _set_abort_behavior( 0, _CALL_REPORTFAULT);
1069 #endif
1070 
1071  abort();
1072 }
1073 
1074 RBIMPL_ATTR_FORMAT(RBIMPL_PRINTF_FORMAT, 1, 0)
1075 void
1076 rb_bug_without_die(const char *fmt, va_list args)
1077 {
1078  const char *file = NULL;
1079  int line = 0;
1080 
1081  if (GET_EC()) {
1082  file = rb_source_location_cstr(&line);
1083  }
1084 
1085  report_bug_valist(file, line, fmt, NULL, args);
1086 }
1087 
1088 void
1089 rb_bug(const char *fmt, ...)
1090 {
1091  va_list args;
1092  va_start(args, fmt);
1093  rb_bug_without_die(fmt, args);
1094  va_end(args);
1095  die();
1096 }
1097 
1098 void
1099 rb_bug_for_fatal_signal(ruby_sighandler_t default_sighandler, int sig, const void *ctx, const char *fmt, ...)
1100 {
1101  const char *file = NULL;
1102  int line = 0;
1103 
1104  if (GET_EC()) {
1105  file = rb_source_location_cstr(&line);
1106  }
1107 
1108  report_bug(file, line, fmt, ctx);
1109 
1110  if (default_sighandler) default_sighandler(sig);
1111 
1112  ruby_default_signal(sig);
1113  die();
1114 }
1115 
1116 
1117 void
1118 rb_bug_errno(const char *mesg, int errno_arg)
1119 {
1120  if (errno_arg == 0)
1121  rb_bug("%s: errno == 0 (NOERROR)", mesg);
1122  else {
1123  const char *errno_str = rb_strerrno(errno_arg);
1124  if (errno_str)
1125  rb_bug("%s: %s (%s)", mesg, strerror(errno_arg), errno_str);
1126  else
1127  rb_bug("%s: %s (%d)", mesg, strerror(errno_arg), errno_arg);
1128  }
1129 }
1130 
1131 /*
1132  * this is safe to call inside signal handler and timer thread
1133  * (which isn't a Ruby Thread object)
1134  */
1135 #define write_or_abort(fd, str, len) (write((fd), (str), (len)) < 0 ? abort() : (void)0)
1136 #define WRITE_CONST(fd,str) write_or_abort((fd),(str),sizeof(str) - 1)
1137 
1138 void
1139 rb_async_bug_errno(const char *mesg, int errno_arg)
1140 {
1141  WRITE_CONST(2, "[ASYNC BUG] ");
1142  write_or_abort(2, mesg, strlen(mesg));
1143  WRITE_CONST(2, "\n");
1144 
1145  if (errno_arg == 0) {
1146  WRITE_CONST(2, "errno == 0 (NOERROR)\n");
1147  }
1148  else {
1149  const char *errno_str = rb_strerrno(errno_arg);
1150 
1151  if (!errno_str)
1152  errno_str = "undefined errno";
1153  write_or_abort(2, errno_str, strlen(errno_str));
1154  }
1155  WRITE_CONST(2, "\n\n");
1156  write_or_abort(2, rb_dynamic_description, strlen(rb_dynamic_description));
1157  abort();
1158 }
1159 
1160 void
1161 rb_report_bug_valist(VALUE file, int line, const char *fmt, va_list args)
1162 {
1163  report_bug_valist(RSTRING_PTR(file), line, fmt, NULL, args);
1164 }
1165 
1166 void
1167 rb_assert_failure(const char *file, int line, const char *name, const char *expr)
1168 {
1169  rb_assert_failure_detail(file, line, name, expr, NULL);
1170 }
1171 
1172 void
1173 rb_assert_failure_detail(const char *file, int line, const char *name, const char *expr,
1174  const char *fmt, ...)
1175 {
1176  rb_pid_t pid = -1;
1177  FILE *out = bug_report_file(file, line, &pid);
1178  if (out) {
1179  fputs("Assertion Failed: ", out);
1180  if (name) fprintf(out, "%s:", name);
1181  fputs(expr, out);
1182 
1183  if (fmt && *fmt) {
1184  va_list args;
1185  va_start(args, fmt);
1186  fputs(": ", out);
1187  vfprintf(out, fmt, args);
1188  va_end(args);
1189  }
1190  fprintf(out, "\n%s\n\n", rb_dynamic_description);
1191 
1192  preface_dump(out);
1193  rb_vm_bugreport(NULL, out);
1194  bug_report_end(out, pid);
1195  }
1196 
1197  die();
1198 }
1199 
1200 static const char builtin_types[][10] = {
1201  "", /* 0x00, */
1202  "Object",
1203  "Class",
1204  "Module",
1205  "Float",
1206  "String",
1207  "Regexp",
1208  "Array",
1209  "Hash",
1210  "Struct",
1211  "Integer",
1212  "File",
1213  "Data", /* internal use: wrapped C pointers */
1214  "MatchData", /* data of $~ */
1215  "Complex",
1216  "Rational",
1217  "", /* 0x10 */
1218  "nil",
1219  "true",
1220  "false",
1221  "Symbol", /* :symbol */
1222  "Integer",
1223  "undef", /* internal use: #undef; should not happen */
1224  "", /* 0x17 */
1225  "", /* 0x18 */
1226  "", /* 0x19 */
1227  "<Memo>", /* internal use: general memo */
1228  "<Node>", /* internal use: syntax tree node */
1229  "<iClass>", /* internal use: mixed-in module holder */
1230 };
1231 
1232 const char *
1233 rb_builtin_type_name(int t)
1234 {
1235  const char *name;
1236  if ((unsigned int)t >= numberof(builtin_types)) return 0;
1237  name = builtin_types[t];
1238  if (*name) return name;
1239  return 0;
1240 }
1241 
1242 static VALUE
1243 displaying_class_of(VALUE x)
1244 {
1245  switch (x) {
1246  case Qfalse: return rb_fstring_cstr("false");
1247  case Qnil: return rb_fstring_cstr("nil");
1248  case Qtrue: return rb_fstring_cstr("true");
1249  default: return rb_obj_class(x);
1250  }
1251 }
1252 
1253 static const char *
1254 builtin_class_name(VALUE x)
1255 {
1256  const char *etype;
1257 
1258  if (NIL_P(x)) {
1259  etype = "nil";
1260  }
1261  else if (FIXNUM_P(x)) {
1262  etype = "Integer";
1263  }
1264  else if (SYMBOL_P(x)) {
1265  etype = "Symbol";
1266  }
1267  else if (RB_TYPE_P(x, T_TRUE)) {
1268  etype = "true";
1269  }
1270  else if (RB_TYPE_P(x, T_FALSE)) {
1271  etype = "false";
1272  }
1273  else {
1274  etype = NULL;
1275  }
1276  return etype;
1277 }
1278 
1279 const char *
1280 rb_builtin_class_name(VALUE x)
1281 {
1282  const char *etype = builtin_class_name(x);
1283 
1284  if (!etype) {
1285  etype = rb_obj_classname(x);
1286  }
1287  return etype;
1288 }
1289 
1290 COLDFUNC NORETURN(static void unexpected_type(VALUE, int, int));
1291 #define UNDEF_LEAKED "undef leaked to the Ruby space"
1292 
1293 static void
1294 unexpected_type(VALUE x, int xt, int t)
1295 {
1296  const char *tname = rb_builtin_type_name(t);
1297  VALUE mesg, exc = rb_eFatal;
1298 
1299  if (tname) {
1300  mesg = rb_sprintf("wrong argument type %"PRIsVALUE" (expected %s)",
1301  displaying_class_of(x), tname);
1302  exc = rb_eTypeError;
1303  }
1304  else if (xt > T_MASK && xt <= 0x3f) {
1305  mesg = rb_sprintf("unknown type 0x%x (0x%x given, probably comes"
1306  " from extension library for ruby 1.8)", t, xt);
1307  }
1308  else {
1309  mesg = rb_sprintf("unknown type 0x%x (0x%x given)", t, xt);
1310  }
1311  rb_exc_raise(rb_exc_new_str(exc, mesg));
1312 }
1313 
1314 void
1316 {
1317  int xt;
1318 
1319  if (RB_UNLIKELY(UNDEF_P(x))) {
1320  rb_bug(UNDEF_LEAKED);
1321  }
1322 
1323  xt = TYPE(x);
1324  if (xt != t || (xt == T_DATA && rbimpl_rtypeddata_p(x))) {
1325  /*
1326  * Typed data is not simple `T_DATA`, but in a sense an
1327  * extension of `struct RVALUE`, which are incompatible with
1328  * each other except when inherited.
1329  *
1330  * So it is not enough to just check `T_DATA`, it must be
1331  * identified by its `type` using `Check_TypedStruct` instead.
1332  */
1333  unexpected_type(x, xt, t);
1334  }
1335 }
1336 
1337 void
1339 {
1340  if (RB_UNLIKELY(UNDEF_P(x))) {
1341  rb_bug(UNDEF_LEAKED);
1342  }
1343 
1344  unexpected_type(x, TYPE(x), t);
1345 }
1346 
1347 int
1349 {
1350  while (child) {
1351  if (child == parent) return 1;
1352  child = child->parent;
1353  }
1354  return 0;
1355 }
1356 
1357 int
1359 {
1360  if (!RB_TYPE_P(obj, T_DATA) ||
1361  !RTYPEDDATA_P(obj) || !rb_typeddata_inherited_p(RTYPEDDATA_TYPE(obj), data_type)) {
1362  return 0;
1363  }
1364  return 1;
1365 }
1366 
1367 #undef rb_typeddata_is_instance_of
1368 int
1369 rb_typeddata_is_instance_of(VALUE obj, const rb_data_type_t *data_type)
1370 {
1371  return rb_typeddata_is_instance_of_inline(obj, data_type);
1372 }
1373 
1374 void *
1376 {
1377  VALUE actual;
1378 
1379  if (!RB_TYPE_P(obj, T_DATA)) {
1380  actual = displaying_class_of(obj);
1381  }
1382  else if (!RTYPEDDATA_P(obj)) {
1383  actual = displaying_class_of(obj);
1384  }
1385  else if (!rb_typeddata_inherited_p(RTYPEDDATA_TYPE(obj), data_type)) {
1386  const char *name = RTYPEDDATA_TYPE(obj)->wrap_struct_name;
1387  actual = rb_str_new_cstr(name); /* or rb_fstring_cstr? not sure... */
1388  }
1389  else {
1390  return RTYPEDDATA_GET_DATA(obj);
1391  }
1392 
1393  const char *expected = data_type->wrap_struct_name;
1394  rb_raise(rb_eTypeError, "wrong argument type %"PRIsVALUE" (expected %s)",
1395  actual, expected);
1396  UNREACHABLE_RETURN(NULL);
1397 }
1398 
1399 /* exception classes */
1423 
1427 
1430 static VALUE rb_eNOERROR;
1431 
1432 ID ruby_static_id_cause;
1433 #define id_cause ruby_static_id_cause
1434 static ID id_message, id_detailed_message, id_backtrace;
1435 static ID id_key, id_matchee, id_args, id_Errno, id_errno, id_i_path;
1436 static ID id_receiver, id_recv, id_iseq, id_local_variables;
1437 static ID id_private_call_p, id_top, id_bottom;
1438 #define id_bt idBt
1439 #define id_bt_locations idBt_locations
1440 #define id_mesg idMesg
1441 #define id_name idName
1442 
1443 #undef rb_exc_new_cstr
1444 
1445 VALUE
1446 rb_exc_new(VALUE etype, const char *ptr, long len)
1447 {
1448  VALUE mesg = rb_str_new(ptr, len);
1449  return rb_class_new_instance(1, &mesg, etype);
1450 }
1451 
1452 VALUE
1453 rb_exc_new_cstr(VALUE etype, const char *s)
1454 {
1455  return rb_exc_new(etype, s, strlen(s));
1456 }
1457 
1458 VALUE
1460 {
1461  rb_yjit_lazy_push_frame(GET_EC()->cfp->pc);
1462  StringValue(str);
1463  return rb_class_new_instance(1, &str, etype);
1464 }
1465 
1466 static VALUE
1467 exc_init(VALUE exc, VALUE mesg)
1468 {
1469  rb_ivar_set(exc, id_mesg, mesg);
1470  rb_ivar_set(exc, id_bt, Qnil);
1471 
1472  return exc;
1473 }
1474 
1475 /*
1476  * call-seq:
1477  * Exception.new(message = nil) -> exception
1478  *
1479  * Returns a new exception object.
1480  *
1481  * The given +message+ should be
1482  * a {string-convertible object}[rdoc-ref:implicit_conversion.rdoc@String-Convertible+Objects];
1483  * see method #message;
1484  * if not given, the message is the class name of the new instance
1485  * (which may be the name of a subclass):
1486  *
1487  * Examples:
1488  *
1489  * Exception.new # => #<Exception: Exception>
1490  * LoadError.new # => #<LoadError: LoadError> # Subclass of Exception.
1491  * Exception.new('Boom') # => #<Exception: Boom>
1492  *
1493  */
1494 
1495 static VALUE
1496 exc_initialize(int argc, VALUE *argv, VALUE exc)
1497 {
1498  VALUE arg;
1499 
1500  arg = (!rb_check_arity(argc, 0, 1) ? Qnil : argv[0]);
1501  return exc_init(exc, arg);
1502 }
1503 
1504 /*
1505  * Document-method: exception
1506  *
1507  * call-seq:
1508  * exception(message = nil) -> self or new_exception
1509  *
1510  * Returns an exception object of the same class as +self+;
1511  * useful for creating a similar exception, but with a different message.
1512  *
1513  * With +message+ +nil+, returns +self+:
1514  *
1515  * x0 = StandardError.new('Boom') # => #<StandardError: Boom>
1516  * x1 = x0.exception # => #<StandardError: Boom>
1517  * x0.__id__ == x1.__id__ # => true
1518  *
1519  * With {string-convertible object}[rdoc-ref:implicit_conversion.rdoc@String-Convertible+Objects]
1520  * +message+ (even the same as the original message),
1521  * returns a new exception object whose class is the same as +self+,
1522  * and whose message is the given +message+:
1523  *
1524  * x1 = x0.exception('Boom') # => #<StandardError: Boom>
1525  * x0..equal?(x1) # => false
1526  *
1527  */
1528 
1529 static VALUE
1530 exc_exception(int argc, VALUE *argv, VALUE self)
1531 {
1532  VALUE exc;
1533 
1534  argc = rb_check_arity(argc, 0, 1);
1535  if (argc == 0) return self;
1536  if (argc == 1 && self == argv[0]) return self;
1537  exc = rb_obj_clone(self);
1538  rb_ivar_set(exc, id_mesg, argv[0]);
1539  return exc;
1540 }
1541 
1542 /*
1543  * call-seq:
1544  * to_s -> string
1545  *
1546  * Returns a string representation of +self+:
1547  *
1548  * x = RuntimeError.new('Boom')
1549  * x.to_s # => "Boom"
1550  * x = RuntimeError.new
1551  * x.to_s # => "RuntimeError"
1552  *
1553  */
1554 
1555 static VALUE
1556 exc_to_s(VALUE exc)
1557 {
1558  VALUE mesg = rb_attr_get(exc, idMesg);
1559 
1560  if (NIL_P(mesg)) return rb_class_name(CLASS_OF(exc));
1561  return rb_String(mesg);
1562 }
1563 
1564 /* FIXME: Include eval_error.c */
1565 void rb_error_write(VALUE errinfo, VALUE emesg, VALUE errat, VALUE str, VALUE opt, VALUE highlight, VALUE reverse);
1566 
1567 VALUE
1568 rb_get_message(VALUE exc)
1569 {
1570  VALUE e = rb_check_funcall(exc, id_message, 0, 0);
1571  if (UNDEF_P(e)) return Qnil;
1572  if (!RB_TYPE_P(e, T_STRING)) e = rb_check_string_type(e);
1573  return e;
1574 }
1575 
1576 VALUE
1577 rb_get_detailed_message(VALUE exc, VALUE opt)
1578 {
1579  VALUE e;
1580  if (NIL_P(opt)) {
1581  e = rb_check_funcall(exc, id_detailed_message, 0, 0);
1582  }
1583  else {
1584  e = rb_check_funcall_kw(exc, id_detailed_message, 1, &opt, 1);
1585  }
1586  if (UNDEF_P(e)) return Qnil;
1587  if (!RB_TYPE_P(e, T_STRING)) e = rb_check_string_type(e);
1588  return e;
1589 }
1590 
1591 /*
1592  * call-seq:
1593  * Exception.to_tty? -> true or false
1594  *
1595  * Returns +true+ if exception messages will be sent to a terminal device.
1596  */
1597 static VALUE
1598 exc_s_to_tty_p(VALUE self)
1599 {
1600  return RBOOL(rb_stderr_tty_p());
1601 }
1602 
1603 static VALUE
1604 check_highlight_keyword(VALUE opt, int auto_tty_detect)
1605 {
1606  VALUE highlight = Qnil;
1607 
1608  if (!NIL_P(opt)) {
1609  highlight = rb_hash_lookup(opt, sym_highlight);
1610 
1611  switch (highlight) {
1612  default:
1613  rb_bool_expected(highlight, "highlight", TRUE);
1614  UNREACHABLE;
1615  case Qtrue: case Qfalse: case Qnil: break;
1616  }
1617  }
1618 
1619  if (NIL_P(highlight)) {
1620  highlight = RBOOL(auto_tty_detect && rb_stderr_tty_p());
1621  }
1622 
1623  return highlight;
1624 }
1625 
1626 static VALUE
1627 check_order_keyword(VALUE opt)
1628 {
1629  VALUE order = Qnil;
1630 
1631  if (!NIL_P(opt)) {
1632  static VALUE kw_order;
1633  if (!kw_order) kw_order = ID2SYM(rb_intern_const("order"));
1634 
1635  order = rb_hash_lookup(opt, kw_order);
1636 
1637  if (order != Qnil) {
1638  ID id = rb_check_id(&order);
1639  if (id == id_bottom) order = Qtrue;
1640  else if (id == id_top) order = Qfalse;
1641  else {
1642  rb_raise(rb_eArgError, "expected :top or :bottom as "
1643  "order: %+"PRIsVALUE, order);
1644  }
1645  }
1646  }
1647 
1648  if (NIL_P(order)) order = Qfalse;
1649 
1650  return order;
1651 }
1652 
1653 /*
1654  * call-seq:
1655  * full_message(highlight: true, order: :top) -> string
1656  *
1657  * Returns an enhanced message string:
1658  *
1659  * - Includes the exception class name.
1660  * - If the value of keyword +highlight+ is true (not +nil+ or +false+),
1661  * includes bolding ANSI codes (see below) to enhance the appearance of the message.
1662  * - Includes the {backtrace}[rdoc-ref:exceptions.md@Backtraces]:
1663  *
1664  * - If the value of keyword +order+ is +:top+ (the default),
1665  * lists the error message and the innermost backtrace entry first.
1666  * - If the value of keyword +order+ is +:bottom+,
1667  * lists the error message the the innermost entry last.
1668  *
1669  * Example:
1670  *
1671  * def baz
1672  * begin
1673  * 1 / 0
1674  * rescue => x
1675  * pp x.message
1676  * pp x.full_message(highlight: false).split("\n")
1677  * pp x.full_message.split("\n")
1678  * end
1679  * end
1680  * def bar; baz; end
1681  * def foo; bar; end
1682  * foo
1683  *
1684  * Output:
1685  *
1686  * "divided by 0"
1687  * ["t.rb:3:in `/': divided by 0 (ZeroDivisionError)",
1688  * "\tfrom t.rb:3:in `baz'",
1689  * "\tfrom t.rb:10:in `bar'",
1690  * "\tfrom t.rb:11:in `foo'",
1691  * "\tfrom t.rb:12:in `<main>'"]
1692  * ["t.rb:3:in `/': \e[1mdivided by 0 (\e[1;4mZeroDivisionError\e[m\e[1m)\e[m",
1693  * "\tfrom t.rb:3:in `baz'",
1694  * "\tfrom t.rb:10:in `bar'",
1695  * "\tfrom t.rb:11:in `foo'",
1696  * "\tfrom t.rb:12:in `<main>'"]
1697  *
1698  * An overriding method should be careful with ANSI code enhancements;
1699  * see {Messages}[rdoc-ref:exceptions.md@Messages].
1700  */
1701 
1702 static VALUE
1703 exc_full_message(int argc, VALUE *argv, VALUE exc)
1704 {
1705  VALUE opt, str, emesg, errat;
1706  VALUE highlight, order;
1707 
1708  rb_scan_args(argc, argv, "0:", &opt);
1709 
1710  highlight = check_highlight_keyword(opt, 1);
1711  order = check_order_keyword(opt);
1712 
1713  {
1714  if (NIL_P(opt)) opt = rb_hash_new();
1715  rb_hash_aset(opt, sym_highlight, highlight);
1716  }
1717 
1718  str = rb_str_new2("");
1719  errat = rb_get_backtrace(exc);
1720  emesg = rb_get_detailed_message(exc, opt);
1721 
1722  rb_error_write(exc, emesg, errat, str, opt, highlight, order);
1723  return str;
1724 }
1725 
1726 /*
1727  * call-seq:
1728  * message -> string
1729  *
1730  * Returns #to_s.
1731  *
1732  * See {Messages}[rdoc-ref:exceptions.md@Messages].
1733  */
1734 
1735 static VALUE
1736 exc_message(VALUE exc)
1737 {
1738  return rb_funcallv(exc, idTo_s, 0, 0);
1739 }
1740 
1741 /*
1742  * call-seq:
1743  * detailed_message(highlight: false, **kwargs) -> string
1744  *
1745  * Returns the message string with enhancements:
1746  *
1747  * - Includes the exception class name in the first line.
1748  * - If the value of keyword +highlight+ is +true+,
1749  * includes bolding and underlining ANSI codes (see below)
1750  * to enhance the appearance of the message.
1751  *
1752  * Examples:
1753  *
1754  * begin
1755  * 1 / 0
1756  * rescue => x
1757  * p x.message
1758  * p x.detailed_message # Class name added.
1759  * p x.detailed_message(highlight: true) # Class name, bolding, and underlining added.
1760  * end
1761  *
1762  * Output:
1763  *
1764  * "divided by 0"
1765  * "divided by 0 (ZeroDivisionError)"
1766  * "\e[1mdivided by 0 (\e[1;4mZeroDivisionError\e[m\e[1m)\e[m"
1767  *
1768  * This method is overridden by some gems in the Ruby standard library to add information:
1769  *
1770  * - DidYouMean::Correctable#detailed_message.
1771  * - ErrorHighlight::CoreExt#detailed_message.
1772  * - SyntaxSuggest#detailed_message.
1773  *
1774  * An overriding method must be tolerant of passed keyword arguments,
1775  * which may include (but may not be limited to):
1776  *
1777  * - +:highlight+.
1778  * - +:did_you_mean+.
1779  * - +:error_highlight+.
1780  * - +:syntax_suggest+.
1781  *
1782  * An overriding method should also be careful with ANSI code enhancements;
1783  * see {Messages}[rdoc-ref:exceptions.md@Messages].
1784  */
1785 
1786 static VALUE
1787 exc_detailed_message(int argc, VALUE *argv, VALUE exc)
1788 {
1789  VALUE opt;
1790 
1791  rb_scan_args(argc, argv, "0:", &opt);
1792 
1793  VALUE highlight = check_highlight_keyword(opt, 0);
1794 
1795  extern VALUE rb_decorate_message(const VALUE eclass, VALUE emesg, int highlight);
1796 
1797  return rb_decorate_message(CLASS_OF(exc), rb_get_message(exc), RTEST(highlight));
1798 }
1799 
1800 /*
1801  * call-seq:
1802  * inspect -> string
1803  *
1804  * Returns a string representation of +self+:
1805  *
1806  * x = RuntimeError.new('Boom')
1807  * x.inspect # => "#<RuntimeError: Boom>"
1808  * x = RuntimeError.new
1809  * x.inspect # => "#<RuntimeError: RuntimeError>"
1810  *
1811  */
1812 
1813 static VALUE
1814 exc_inspect(VALUE exc)
1815 {
1816  VALUE str, klass;
1817 
1818  klass = CLASS_OF(exc);
1819  exc = rb_obj_as_string(exc);
1820  if (RSTRING_LEN(exc) == 0) {
1821  return rb_class_name(klass);
1822  }
1823 
1824  str = rb_str_buf_new2("#<");
1825  klass = rb_class_name(klass);
1826  rb_str_buf_append(str, klass);
1827 
1828  if (RTEST(rb_str_include(exc, rb_str_new2("\n")))) {
1829  rb_str_catf(str, ":%+"PRIsVALUE, exc);
1830  }
1831  else {
1832  rb_str_buf_cat(str, ": ", 2);
1833  rb_str_buf_append(str, exc);
1834  }
1835 
1836  rb_str_buf_cat(str, ">", 1);
1837 
1838  return str;
1839 }
1840 
1841 /*
1842  * call-seq:
1843  * backtrace -> array or nil
1844  *
1845  * Returns a backtrace value for +self+;
1846  * the returned value depends on the form of the stored backtrace value:
1847  *
1848  * - \Array of Thread::Backtrace::Location objects:
1849  * returns the array of strings given by
1850  * <tt>Exception#backtrace_locations.map {|loc| loc.to_s }</tt>.
1851  * This is the normal case, where the backtrace value was stored by Kernel#raise.
1852  * - \Array of strings: returns that array.
1853  * This is the unusual case, where the backtrace value was explicitly
1854  * stored as an array of strings.
1855  * - +nil+: returns +nil+.
1856  *
1857  * Example:
1858  *
1859  * begin
1860  * 1 / 0
1861  * rescue => x
1862  * x.backtrace.take(2)
1863  * end
1864  * # => ["(irb):132:in `/'", "(irb):132:in `<top (required)>'"]
1865  *
1866  * see {Backtraces}[rdoc-ref:exceptions.md@Backtraces].
1867  */
1868 
1869 static VALUE
1870 exc_backtrace(VALUE exc)
1871 {
1872  VALUE obj;
1873 
1874  obj = rb_attr_get(exc, id_bt);
1875 
1876  if (rb_backtrace_p(obj)) {
1877  obj = rb_backtrace_to_str_ary(obj);
1878  /* rb_ivar_set(exc, id_bt, obj); */
1879  }
1880 
1881  return obj;
1882 }
1883 
1884 static VALUE rb_check_backtrace(VALUE);
1885 
1886 VALUE
1887 rb_get_backtrace(VALUE exc)
1888 {
1889  ID mid = id_backtrace;
1890  VALUE info;
1891  if (rb_method_basic_definition_p(CLASS_OF(exc), id_backtrace)) {
1892  VALUE klass = rb_eException;
1893  rb_execution_context_t *ec = GET_EC();
1894  if (NIL_P(exc))
1895  return Qnil;
1896  EXEC_EVENT_HOOK(ec, RUBY_EVENT_C_CALL, exc, mid, mid, klass, Qundef);
1897  info = exc_backtrace(exc);
1898  EXEC_EVENT_HOOK(ec, RUBY_EVENT_C_RETURN, exc, mid, mid, klass, info);
1899  }
1900  else {
1901  info = rb_funcallv(exc, mid, 0, 0);
1902  }
1903  if (NIL_P(info)) return Qnil;
1904  return rb_check_backtrace(info);
1905 }
1906 
1907 /*
1908  * call-seq:
1909  * backtrace_locations -> array or nil
1910  *
1911  * Returns a backtrace value for +self+;
1912  * the returned value depends on the form of the stored backtrace value:
1913  *
1914  * - \Array of Thread::Backtrace::Location objects: returns that array.
1915  * - \Array of strings or +nil+: returns +nil+.
1916  *
1917  * Example:
1918  *
1919  * begin
1920  * 1 / 0
1921  * rescue => x
1922  * x.backtrace_locations.take(2)
1923  * end
1924  * # => ["(irb):150:in `/'", "(irb):150:in `<top (required)>'"]
1925  *
1926  * See {Backtraces}[rdoc-ref:exceptions.md@Backtraces].
1927  */
1928 static VALUE
1929 exc_backtrace_locations(VALUE exc)
1930 {
1931  VALUE obj;
1932 
1933  obj = rb_attr_get(exc, id_bt_locations);
1934  if (!NIL_P(obj)) {
1935  obj = rb_backtrace_to_location_ary(obj);
1936  }
1937  return obj;
1938 }
1939 
1940 static VALUE
1941 rb_check_backtrace(VALUE bt)
1942 {
1943  long i;
1944  static const char err[] = "backtrace must be an Array of String or an Array of Thread::Backtrace::Location";
1945 
1946  if (!NIL_P(bt)) {
1947  if (RB_TYPE_P(bt, T_STRING)) return rb_ary_new3(1, bt);
1948  if (rb_backtrace_p(bt)) return bt;
1949  if (!RB_TYPE_P(bt, T_ARRAY)) {
1950  rb_raise(rb_eTypeError, err);
1951  }
1952  for (i=0;i<RARRAY_LEN(bt);i++) {
1953  VALUE e = RARRAY_AREF(bt, i);
1954  if (!RB_TYPE_P(e, T_STRING)) {
1955  rb_raise(rb_eTypeError, err);
1956  }
1957  }
1958  }
1959  return bt;
1960 }
1961 
1962 /*
1963  * call-seq:
1964  * set_backtrace(value) -> value
1965  *
1966  * Sets the backtrace value for +self+; returns the given +value:
1967  *
1968  * x = RuntimeError.new('Boom')
1969  * x.set_backtrace(%w[foo bar baz]) # => ["foo", "bar", "baz"]
1970  * x.backtrace # => ["foo", "bar", "baz"]
1971  *
1972  * The given +value+ must be an array of strings, a single string, or +nil+.
1973  *
1974  * Does not affect the value returned by #backtrace_locations.
1975  *
1976  * See {Backtraces}[rdoc-ref:exceptions.md@Backtraces].
1977  */
1978 
1979 static VALUE
1980 exc_set_backtrace(VALUE exc, VALUE bt)
1981 {
1982  VALUE btobj = rb_location_ary_to_backtrace(bt);
1983  if (RTEST(btobj)) {
1984  rb_ivar_set(exc, id_bt, btobj);
1985  rb_ivar_set(exc, id_bt_locations, btobj);
1986  return bt;
1987  }
1988  else {
1989  return rb_ivar_set(exc, id_bt, rb_check_backtrace(bt));
1990  }
1991 }
1992 
1993 VALUE
1994 rb_exc_set_backtrace(VALUE exc, VALUE bt)
1995 {
1996  return exc_set_backtrace(exc, bt);
1997 }
1998 
1999 /*
2000  * call-seq:
2001  * cause -> exception or nil
2002  *
2003  * Returns the previous value of global variable <tt>$!</tt>,
2004  * which may be +nil+
2005  * (see {Global Variables}[rdoc-ref:exceptions.md@Global+Variables]):
2006  *
2007  * begin
2008  * raise('Boom 0')
2009  * rescue => x0
2010  * puts "Exception: #{x0}; $!: #{$!}; cause: #{x0.cause.inspect}."
2011  * begin
2012  * raise('Boom 1')
2013  * rescue => x1
2014  * puts "Exception: #{x1}; $!: #{$!}; cause: #{x1.cause}."
2015  * begin
2016  * raise('Boom 2')
2017  * rescue => x2
2018  * puts "Exception: #{x2}; $!: #{$!}; cause: #{x2.cause}."
2019  * end
2020  * end
2021  * end
2022  *
2023  * Output:
2024  *
2025  * Exception: Boom 0; $!: Boom 0; cause: nil.
2026  * Exception: Boom 1; $!: Boom 1; cause: Boom 0.
2027  * Exception: Boom 2; $!: Boom 2; cause: Boom 1.
2028  *
2029  */
2030 
2031 static VALUE
2032 exc_cause(VALUE exc)
2033 {
2034  return rb_attr_get(exc, id_cause);
2035 }
2036 
2037 static VALUE
2038 try_convert_to_exception(VALUE obj)
2039 {
2040  return rb_check_funcall(obj, idException, 0, 0);
2041 }
2042 
2043 /*
2044  * call-seq:
2045  * self == object -> true or false
2046  *
2047  * Returns whether +object+ is the same class as +self+
2048  * and its #message and #backtrace are equal to those of +self+.
2049  *
2050  */
2051 
2052 static VALUE
2053 exc_equal(VALUE exc, VALUE obj)
2054 {
2055  VALUE mesg, backtrace;
2056 
2057  if (exc == obj) return Qtrue;
2058 
2059  if (rb_obj_class(exc) != rb_obj_class(obj)) {
2060  int state;
2061 
2062  obj = rb_protect(try_convert_to_exception, obj, &state);
2063  if (state || UNDEF_P(obj)) {
2065  return Qfalse;
2066  }
2067  if (rb_obj_class(exc) != rb_obj_class(obj)) return Qfalse;
2068  mesg = rb_check_funcall(obj, id_message, 0, 0);
2069  if (UNDEF_P(mesg)) return Qfalse;
2070  backtrace = rb_check_funcall(obj, id_backtrace, 0, 0);
2071  if (UNDEF_P(backtrace)) return Qfalse;
2072  }
2073  else {
2074  mesg = rb_attr_get(obj, id_mesg);
2075  backtrace = exc_backtrace(obj);
2076  }
2077 
2078  if (!rb_equal(rb_attr_get(exc, id_mesg), mesg))
2079  return Qfalse;
2080  return rb_equal(exc_backtrace(exc), backtrace);
2081 }
2082 
2083 /*
2084  * call-seq:
2085  * SystemExit.new -> system_exit
2086  * SystemExit.new(status) -> system_exit
2087  * SystemExit.new(status, msg) -> system_exit
2088  * SystemExit.new(msg) -> system_exit
2089  *
2090  * Create a new +SystemExit+ exception with the given status and message.
2091  * Status is true, false, or an integer.
2092  * If status is not given, true is used.
2093  */
2094 
2095 static VALUE
2096 exit_initialize(int argc, VALUE *argv, VALUE exc)
2097 {
2098  VALUE status;
2099  if (argc > 0) {
2100  status = *argv;
2101 
2102  switch (status) {
2103  case Qtrue:
2104  status = INT2FIX(EXIT_SUCCESS);
2105  ++argv;
2106  --argc;
2107  break;
2108  case Qfalse:
2109  status = INT2FIX(EXIT_FAILURE);
2110  ++argv;
2111  --argc;
2112  break;
2113  default:
2114  status = rb_check_to_int(status);
2115  if (NIL_P(status)) {
2116  status = INT2FIX(EXIT_SUCCESS);
2117  }
2118  else {
2119 #if EXIT_SUCCESS != 0
2120  if (status == INT2FIX(0))
2121  status = INT2FIX(EXIT_SUCCESS);
2122 #endif
2123  ++argv;
2124  --argc;
2125  }
2126  break;
2127  }
2128  }
2129  else {
2130  status = INT2FIX(EXIT_SUCCESS);
2131  }
2132  rb_call_super(argc, argv);
2133  rb_ivar_set(exc, id_status, status);
2134  return exc;
2135 }
2136 
2137 
2138 /*
2139  * call-seq:
2140  * system_exit.status -> integer
2141  *
2142  * Return the status value associated with this system exit.
2143  */
2144 
2145 static VALUE
2146 exit_status(VALUE exc)
2147 {
2148  return rb_attr_get(exc, id_status);
2149 }
2150 
2151 
2152 /*
2153  * call-seq:
2154  * system_exit.success? -> true or false
2155  *
2156  * Returns +true+ if exiting successful, +false+ if not.
2157  */
2158 
2159 static VALUE
2160 exit_success_p(VALUE exc)
2161 {
2162  VALUE status_val = rb_attr_get(exc, id_status);
2163  int status;
2164 
2165  if (NIL_P(status_val))
2166  return Qtrue;
2167  status = NUM2INT(status_val);
2168  return RBOOL(WIFEXITED(status) && WEXITSTATUS(status) == EXIT_SUCCESS);
2169 }
2170 
2171 static VALUE
2172 err_init_recv(VALUE exc, VALUE recv)
2173 {
2174  if (!UNDEF_P(recv)) rb_ivar_set(exc, id_recv, recv);
2175  return exc;
2176 }
2177 
2178 /*
2179  * call-seq:
2180  * FrozenError.new(msg=nil, receiver: nil) -> frozen_error
2181  *
2182  * Construct a new FrozenError exception. If given the <i>receiver</i>
2183  * parameter may subsequently be examined using the FrozenError#receiver
2184  * method.
2185  *
2186  * a = [].freeze
2187  * raise FrozenError.new("can't modify frozen array", receiver: a)
2188  */
2189 
2190 static VALUE
2191 frozen_err_initialize(int argc, VALUE *argv, VALUE self)
2192 {
2193  ID keywords[1];
2194  VALUE values[numberof(keywords)], options;
2195 
2196  argc = rb_scan_args(argc, argv, "*:", NULL, &options);
2197  keywords[0] = id_receiver;
2198  rb_get_kwargs(options, keywords, 0, numberof(values), values);
2199  rb_call_super(argc, argv);
2200  err_init_recv(self, values[0]);
2201  return self;
2202 }
2203 
2204 /*
2205  * Document-method: FrozenError#receiver
2206  * call-seq:
2207  * frozen_error.receiver -> object
2208  *
2209  * Return the receiver associated with this FrozenError exception.
2210  */
2211 
2212 #define frozen_err_receiver name_err_receiver
2213 
2214 void
2215 rb_name_error(ID id, const char *fmt, ...)
2216 {
2217  VALUE exc, argv[2];
2218  va_list args;
2219 
2220  va_start(args, fmt);
2221  argv[0] = rb_vsprintf(fmt, args);
2222  va_end(args);
2223 
2224  argv[1] = ID2SYM(id);
2225  exc = rb_class_new_instance(2, argv, rb_eNameError);
2226  rb_exc_raise(exc);
2227 }
2228 
2229 void
2230 rb_name_error_str(VALUE str, const char *fmt, ...)
2231 {
2232  VALUE exc, argv[2];
2233  va_list args;
2234 
2235  va_start(args, fmt);
2236  argv[0] = rb_vsprintf(fmt, args);
2237  va_end(args);
2238 
2239  argv[1] = str;
2240  exc = rb_class_new_instance(2, argv, rb_eNameError);
2241  rb_exc_raise(exc);
2242 }
2243 
2244 static VALUE
2245 name_err_init_attr(VALUE exc, VALUE recv, VALUE method)
2246 {
2247  const rb_execution_context_t *ec = GET_EC();
2248  rb_control_frame_t *cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(ec->cfp);
2249  cfp = rb_vm_get_ruby_level_next_cfp(ec, cfp);
2250  rb_ivar_set(exc, id_name, method);
2251  err_init_recv(exc, recv);
2252  if (cfp && VM_FRAME_TYPE(cfp) != VM_FRAME_MAGIC_DUMMY) {
2253  rb_ivar_set(exc, id_iseq, rb_iseqw_new(cfp->iseq));
2254  }
2255  return exc;
2256 }
2257 
2258 /*
2259  * call-seq:
2260  * NameError.new(msg=nil, name=nil, receiver: nil) -> name_error
2261  *
2262  * Construct a new NameError exception. If given the <i>name</i>
2263  * parameter may subsequently be examined using the NameError#name
2264  * method. <i>receiver</i> parameter allows to pass object in
2265  * context of which the error happened. Example:
2266  *
2267  * [1, 2, 3].method(:rject) # NameError with name "rject" and receiver: Array
2268  * [1, 2, 3].singleton_method(:rject) # NameError with name "rject" and receiver: [1, 2, 3]
2269  */
2270 
2271 static VALUE
2272 name_err_initialize(int argc, VALUE *argv, VALUE self)
2273 {
2274  ID keywords[1];
2275  VALUE values[numberof(keywords)], name, options;
2276 
2277  argc = rb_scan_args(argc, argv, "*:", NULL, &options);
2278  keywords[0] = id_receiver;
2279  rb_get_kwargs(options, keywords, 0, numberof(values), values);
2280  name = (argc > 1) ? argv[--argc] : Qnil;
2281  rb_call_super(argc, argv);
2282  name_err_init_attr(self, values[0], name);
2283  return self;
2284 }
2285 
2286 static VALUE rb_name_err_mesg_new(VALUE mesg, VALUE recv, VALUE method);
2287 
2288 static VALUE
2289 name_err_init(VALUE exc, VALUE mesg, VALUE recv, VALUE method)
2290 {
2291  exc_init(exc, rb_name_err_mesg_new(mesg, recv, method));
2292  return name_err_init_attr(exc, recv, method);
2293 }
2294 
2295 VALUE
2296 rb_name_err_new(VALUE mesg, VALUE recv, VALUE method)
2297 {
2299  return name_err_init(exc, mesg, recv, method);
2300 }
2301 
2302 /*
2303  * call-seq:
2304  * name_error.name -> string or nil
2305  *
2306  * Return the name associated with this NameError exception.
2307  */
2308 
2309 static VALUE
2310 name_err_name(VALUE self)
2311 {
2312  return rb_attr_get(self, id_name);
2313 }
2314 
2315 /*
2316  * call-seq:
2317  * name_error.local_variables -> array
2318  *
2319  * Return a list of the local variable names defined where this
2320  * NameError exception was raised.
2321  *
2322  * Internal use only.
2323  */
2324 
2325 static VALUE
2326 name_err_local_variables(VALUE self)
2327 {
2328  VALUE vars = rb_attr_get(self, id_local_variables);
2329 
2330  if (NIL_P(vars)) {
2331  VALUE iseqw = rb_attr_get(self, id_iseq);
2332  if (!NIL_P(iseqw)) vars = rb_iseqw_local_variables(iseqw);
2333  if (NIL_P(vars)) vars = rb_ary_new();
2334  rb_ivar_set(self, id_local_variables, vars);
2335  }
2336  return vars;
2337 }
2338 
2339 static VALUE
2340 nometh_err_init_attr(VALUE exc, VALUE args, int priv)
2341 {
2342  rb_ivar_set(exc, id_args, args);
2343  rb_ivar_set(exc, id_private_call_p, RBOOL(priv));
2344  return exc;
2345 }
2346 
2347 /*
2348  * call-seq:
2349  * NoMethodError.new(msg=nil, name=nil, args=nil, private=false, receiver: nil) -> no_method_error
2350  *
2351  * Construct a NoMethodError exception for a method of the given name
2352  * called with the given arguments. The name may be accessed using
2353  * the <code>#name</code> method on the resulting object, and the
2354  * arguments using the <code>#args</code> method.
2355  *
2356  * If <i>private</i> argument were passed, it designates method was
2357  * attempted to call in private context, and can be accessed with
2358  * <code>#private_call?</code> method.
2359  *
2360  * <i>receiver</i> argument stores an object whose method was called.
2361  */
2362 
2363 static VALUE
2364 nometh_err_initialize(int argc, VALUE *argv, VALUE self)
2365 {
2366  int priv;
2367  VALUE args, options;
2368  argc = rb_scan_args(argc, argv, "*:", NULL, &options);
2369  priv = (argc > 3) && (--argc, RTEST(argv[argc]));
2370  args = (argc > 2) ? argv[--argc] : Qnil;
2371  if (!NIL_P(options)) argv[argc++] = options;
2373  return nometh_err_init_attr(self, args, priv);
2374 }
2375 
2376 VALUE
2377 rb_nomethod_err_new(VALUE mesg, VALUE recv, VALUE method, VALUE args, int priv)
2378 {
2380  name_err_init(exc, mesg, recv, method);
2381  return nometh_err_init_attr(exc, args, priv);
2382 }
2383 
2385  VALUE mesg;
2386  VALUE recv;
2387  VALUE name;
2389 
2390 static void
2391 name_err_mesg_mark(void *p)
2392 {
2394  rb_gc_mark_movable(ptr->mesg);
2395  rb_gc_mark_movable(ptr->recv);
2396  rb_gc_mark_movable(ptr->name);
2397 }
2398 
2399 static void
2400 name_err_mesg_update(void *p)
2401 {
2403  ptr->mesg = rb_gc_location(ptr->mesg);
2404  ptr->recv = rb_gc_location(ptr->recv);
2405  ptr->name = rb_gc_location(ptr->name);
2406 }
2407 
2408 static const rb_data_type_t name_err_mesg_data_type = {
2409  "name_err_mesg",
2410  {
2411  name_err_mesg_mark,
2413  NULL, // No external memory to report,
2414  name_err_mesg_update,
2415  },
2416  0, 0, RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_EMBEDDABLE
2417 };
2418 
2419 /* :nodoc: */
2420 static VALUE
2421 rb_name_err_mesg_init(VALUE klass, VALUE mesg, VALUE recv, VALUE name)
2422 {
2423  name_error_message_t *message;
2424  VALUE result = TypedData_Make_Struct(klass, name_error_message_t, &name_err_mesg_data_type, message);
2425  RB_OBJ_WRITE(result, &message->mesg, mesg);
2426  RB_OBJ_WRITE(result, &message->recv, recv);
2427  RB_OBJ_WRITE(result, &message->name, name);
2428  return result;
2429 }
2430 
2431 /* :nodoc: */
2432 static VALUE
2433 rb_name_err_mesg_new(VALUE mesg, VALUE recv, VALUE method)
2434 {
2435  return rb_name_err_mesg_init(rb_cNameErrorMesg, mesg, recv, method);
2436 }
2437 
2438 /* :nodoc: */
2439 static VALUE
2440 name_err_mesg_alloc(VALUE klass)
2441 {
2442  return rb_name_err_mesg_init(klass, Qnil, Qnil, Qnil);
2443 }
2444 
2445 /* :nodoc: */
2446 static VALUE
2447 name_err_mesg_init_copy(VALUE obj1, VALUE obj2)
2448 {
2449  if (obj1 == obj2) return obj1;
2450  rb_obj_init_copy(obj1, obj2);
2451 
2452  name_error_message_t *ptr1, *ptr2;
2453  TypedData_Get_Struct(obj1, name_error_message_t, &name_err_mesg_data_type, ptr1);
2454  TypedData_Get_Struct(obj2, name_error_message_t, &name_err_mesg_data_type, ptr2);
2455 
2456  RB_OBJ_WRITE(obj1, &ptr1->mesg, ptr2->mesg);
2457  RB_OBJ_WRITE(obj1, &ptr1->recv, ptr2->recv);
2458  RB_OBJ_WRITE(obj1, &ptr1->name, ptr2->name);
2459  return obj1;
2460 }
2461 
2462 /* :nodoc: */
2463 static VALUE
2464 name_err_mesg_equal(VALUE obj1, VALUE obj2)
2465 {
2466  if (obj1 == obj2) return Qtrue;
2467 
2468  if (rb_obj_class(obj2) != rb_cNameErrorMesg)
2469  return Qfalse;
2470 
2471  name_error_message_t *ptr1, *ptr2;
2472  TypedData_Get_Struct(obj1, name_error_message_t, &name_err_mesg_data_type, ptr1);
2473  TypedData_Get_Struct(obj2, name_error_message_t, &name_err_mesg_data_type, ptr2);
2474 
2475  if (!rb_equal(ptr1->mesg, ptr2->mesg)) return Qfalse;
2476  if (!rb_equal(ptr1->recv, ptr2->recv)) return Qfalse;
2477  if (!rb_equal(ptr1->name, ptr2->name)) return Qfalse;
2478  return Qtrue;
2479 }
2480 
2481 /* :nodoc: */
2482 static VALUE
2483 name_err_mesg_receiver_name(VALUE obj)
2484 {
2485  if (RB_SPECIAL_CONST_P(obj)) return Qundef;
2486  if (RB_BUILTIN_TYPE(obj) == T_MODULE || RB_BUILTIN_TYPE(obj) == T_CLASS) {
2487  return rb_check_funcall(obj, rb_intern("name"), 0, 0);
2488  }
2489  return Qundef;
2490 }
2491 
2492 /* :nodoc: */
2493 static VALUE
2494 name_err_mesg_to_str(VALUE obj)
2495 {
2497  TypedData_Get_Struct(obj, name_error_message_t, &name_err_mesg_data_type, ptr);
2498 
2499  VALUE mesg = ptr->mesg;
2500  if (NIL_P(mesg)) return Qnil;
2501  else {
2502  struct RString s_str, c_str, d_str;
2503  VALUE c, s, d = 0, args[4], c2;
2504  int state = 0;
2505  rb_encoding *usascii = rb_usascii_encoding();
2506 
2507 #define FAKE_CSTR(v, str) rb_setup_fake_str((v), (str), rb_strlen_lit(str), usascii)
2508  c = s = FAKE_CSTR(&s_str, "");
2509  obj = ptr->recv;
2510  switch (obj) {
2511  case Qnil:
2512  c = d = FAKE_CSTR(&d_str, "nil");
2513  break;
2514  case Qtrue:
2515  c = d = FAKE_CSTR(&d_str, "true");
2516  break;
2517  case Qfalse:
2518  c = d = FAKE_CSTR(&d_str, "false");
2519  break;
2520  default:
2521  if (strstr(RSTRING_PTR(mesg), "%2$s")) {
2522  d = rb_protect(name_err_mesg_receiver_name, obj, &state);
2523  if (state || NIL_OR_UNDEF_P(d))
2524  d = rb_protect(rb_inspect, obj, &state);
2525  if (state) {
2527  }
2528  d = rb_check_string_type(d);
2529  if (NIL_P(d)) {
2530  d = rb_any_to_s(obj);
2531  }
2532  }
2533 
2534  if (!RB_SPECIAL_CONST_P(obj)) {
2535  switch (RB_BUILTIN_TYPE(obj)) {
2536  case T_MODULE:
2537  s = FAKE_CSTR(&s_str, "module ");
2538  c = obj;
2539  break;
2540  case T_CLASS:
2541  s = FAKE_CSTR(&s_str, "class ");
2542  c = obj;
2543  break;
2544  default:
2545  goto object;
2546  }
2547  }
2548  else {
2549  VALUE klass;
2550  object:
2551  klass = CLASS_OF(obj);
2552  if (RB_TYPE_P(klass, T_CLASS) && RCLASS_SINGLETON_P(klass)) {
2553  s = FAKE_CSTR(&s_str, "");
2554  if (obj == rb_vm_top_self()) {
2555  c = FAKE_CSTR(&c_str, "main");
2556  }
2557  else {
2558  c = rb_any_to_s(obj);
2559  }
2560  break;
2561  }
2562  else {
2563  s = FAKE_CSTR(&s_str, "an instance of ");
2564  c = rb_class_real(klass);
2565  }
2566  }
2567  c2 = rb_protect(name_err_mesg_receiver_name, c, &state);
2568  if (state || NIL_OR_UNDEF_P(c2))
2569  c2 = rb_protect(rb_inspect, c, &state);
2570  if (state) {
2572  }
2573  c2 = rb_check_string_type(c2);
2574  if (NIL_P(c2)) {
2575  c2 = rb_any_to_s(c);
2576  }
2577  c = c2;
2578  break;
2579  }
2580  args[0] = rb_obj_as_string(ptr->name);
2581  args[1] = d;
2582  args[2] = s;
2583  args[3] = c;
2584  mesg = rb_str_format(4, args, mesg);
2585  }
2586  return mesg;
2587 }
2588 
2589 /* :nodoc: */
2590 static VALUE
2591 name_err_mesg_dump(VALUE obj, VALUE limit)
2592 {
2593  return name_err_mesg_to_str(obj);
2594 }
2595 
2596 /* :nodoc: */
2597 static VALUE
2598 name_err_mesg_load(VALUE klass, VALUE str)
2599 {
2600  return str;
2601 }
2602 
2603 /*
2604  * call-seq:
2605  * name_error.receiver -> object
2606  *
2607  * Return the receiver associated with this NameError exception.
2608  */
2609 
2610 static VALUE
2611 name_err_receiver(VALUE self)
2612 {
2613  VALUE recv = rb_ivar_lookup(self, id_recv, Qundef);
2614  if (!UNDEF_P(recv)) return recv;
2615 
2616  VALUE mesg = rb_attr_get(self, id_mesg);
2617  if (!rb_typeddata_is_kind_of(mesg, &name_err_mesg_data_type)) {
2618  rb_raise(rb_eArgError, "no receiver is available");
2619  }
2620 
2622  TypedData_Get_Struct(mesg, name_error_message_t, &name_err_mesg_data_type, ptr);
2623  return ptr->recv;
2624 }
2625 
2626 /*
2627  * call-seq:
2628  * no_method_error.args -> obj
2629  *
2630  * Return the arguments passed in as the third parameter to
2631  * the constructor.
2632  */
2633 
2634 static VALUE
2635 nometh_err_args(VALUE self)
2636 {
2637  return rb_attr_get(self, id_args);
2638 }
2639 
2640 /*
2641  * call-seq:
2642  * no_method_error.private_call? -> true or false
2643  *
2644  * Return true if the caused method was called as private.
2645  */
2646 
2647 static VALUE
2648 nometh_err_private_call_p(VALUE self)
2649 {
2650  return rb_attr_get(self, id_private_call_p);
2651 }
2652 
2653 void
2654 rb_invalid_str(const char *str, const char *type)
2655 {
2656  VALUE s = rb_str_new2(str);
2657 
2658  rb_raise(rb_eArgError, "invalid value for %s: %+"PRIsVALUE, type, s);
2659 }
2660 
2661 /*
2662  * call-seq:
2663  * key_error.receiver -> object
2664  *
2665  * Return the receiver associated with this KeyError exception.
2666  */
2667 
2668 static VALUE
2669 key_err_receiver(VALUE self)
2670 {
2671  VALUE recv;
2672 
2673  recv = rb_ivar_lookup(self, id_receiver, Qundef);
2674  if (!UNDEF_P(recv)) return recv;
2675  rb_raise(rb_eArgError, "no receiver is available");
2676 }
2677 
2678 /*
2679  * call-seq:
2680  * key_error.key -> object
2681  *
2682  * Return the key caused this KeyError exception.
2683  */
2684 
2685 static VALUE
2686 key_err_key(VALUE self)
2687 {
2688  VALUE key;
2689 
2690  key = rb_ivar_lookup(self, id_key, Qundef);
2691  if (!UNDEF_P(key)) return key;
2692  rb_raise(rb_eArgError, "no key is available");
2693 }
2694 
2695 VALUE
2696 rb_key_err_new(VALUE mesg, VALUE recv, VALUE key)
2697 {
2699  rb_ivar_set(exc, id_mesg, mesg);
2700  rb_ivar_set(exc, id_bt, Qnil);
2701  rb_ivar_set(exc, id_key, key);
2702  rb_ivar_set(exc, id_receiver, recv);
2703  return exc;
2704 }
2705 
2706 /*
2707  * call-seq:
2708  * KeyError.new(message=nil, receiver: nil, key: nil) -> key_error
2709  *
2710  * Construct a new +KeyError+ exception with the given message,
2711  * receiver and key.
2712  */
2713 
2714 static VALUE
2715 key_err_initialize(int argc, VALUE *argv, VALUE self)
2716 {
2717  VALUE options;
2718 
2719  rb_call_super(rb_scan_args(argc, argv, "01:", NULL, &options), argv);
2720 
2721  if (!NIL_P(options)) {
2722  ID keywords[2];
2723  VALUE values[numberof(keywords)];
2724  int i;
2725  keywords[0] = id_receiver;
2726  keywords[1] = id_key;
2727  rb_get_kwargs(options, keywords, 0, numberof(values), values);
2728  for (i = 0; i < numberof(values); ++i) {
2729  if (!UNDEF_P(values[i])) {
2730  rb_ivar_set(self, keywords[i], values[i]);
2731  }
2732  }
2733  }
2734 
2735  return self;
2736 }
2737 
2738 /*
2739  * call-seq:
2740  * no_matching_pattern_key_error.matchee -> object
2741  *
2742  * Return the matchee associated with this NoMatchingPatternKeyError exception.
2743  */
2744 
2745 static VALUE
2746 no_matching_pattern_key_err_matchee(VALUE self)
2747 {
2748  VALUE matchee;
2749 
2750  matchee = rb_ivar_lookup(self, id_matchee, Qundef);
2751  if (!UNDEF_P(matchee)) return matchee;
2752  rb_raise(rb_eArgError, "no matchee is available");
2753 }
2754 
2755 /*
2756  * call-seq:
2757  * no_matching_pattern_key_error.key -> object
2758  *
2759  * Return the key caused this NoMatchingPatternKeyError exception.
2760  */
2761 
2762 static VALUE
2763 no_matching_pattern_key_err_key(VALUE self)
2764 {
2765  VALUE key;
2766 
2767  key = rb_ivar_lookup(self, id_key, Qundef);
2768  if (!UNDEF_P(key)) return key;
2769  rb_raise(rb_eArgError, "no key is available");
2770 }
2771 
2772 /*
2773  * call-seq:
2774  * NoMatchingPatternKeyError.new(message=nil, matchee: nil, key: nil) -> no_matching_pattern_key_error
2775  *
2776  * Construct a new +NoMatchingPatternKeyError+ exception with the given message,
2777  * matchee and key.
2778  */
2779 
2780 static VALUE
2781 no_matching_pattern_key_err_initialize(int argc, VALUE *argv, VALUE self)
2782 {
2783  VALUE options;
2784 
2785  rb_call_super(rb_scan_args(argc, argv, "01:", NULL, &options), argv);
2786 
2787  if (!NIL_P(options)) {
2788  ID keywords[2];
2789  VALUE values[numberof(keywords)];
2790  int i;
2791  keywords[0] = id_matchee;
2792  keywords[1] = id_key;
2793  rb_get_kwargs(options, keywords, 0, numberof(values), values);
2794  for (i = 0; i < numberof(values); ++i) {
2795  if (!UNDEF_P(values[i])) {
2796  rb_ivar_set(self, keywords[i], values[i]);
2797  }
2798  }
2799  }
2800 
2801  return self;
2802 }
2803 
2804 
2805 /*
2806  * call-seq:
2807  * SyntaxError.new([msg]) -> syntax_error
2808  *
2809  * Construct a SyntaxError exception.
2810  */
2811 
2812 static VALUE
2813 syntax_error_initialize(int argc, VALUE *argv, VALUE self)
2814 {
2815  VALUE mesg;
2816  if (argc == 0) {
2817  mesg = rb_fstring_lit("compile error");
2818  argc = 1;
2819  argv = &mesg;
2820  }
2821  return rb_call_super(argc, argv);
2822 }
2823 
2824 static VALUE
2825 syntax_error_with_path(VALUE exc, VALUE path, VALUE *mesg, rb_encoding *enc)
2826 {
2827  if (NIL_P(exc)) {
2828  *mesg = rb_enc_str_new(0, 0, enc);
2829  exc = rb_class_new_instance(1, mesg, rb_eSyntaxError);
2830  rb_ivar_set(exc, id_i_path, path);
2831  }
2832  else {
2833  VALUE old_path = rb_attr_get(exc, id_i_path);
2834  if (old_path != path) {
2835  if (rb_str_equal(path, old_path)) {
2836  rb_raise(rb_eArgError, "SyntaxError#path changed: %+"PRIsVALUE" (%p->%p)",
2837  old_path, (void *)old_path, (void *)path);
2838  }
2839  else {
2840  rb_raise(rb_eArgError, "SyntaxError#path changed: %+"PRIsVALUE"(%s%s)->%+"PRIsVALUE"(%s)",
2841  old_path, rb_enc_name(rb_enc_get(old_path)),
2842  (FL_TEST(old_path, RSTRING_FSTR) ? ":FSTR" : ""),
2843  path, rb_enc_name(rb_enc_get(path)));
2844  }
2845  }
2846  VALUE s = *mesg = rb_attr_get(exc, idMesg);
2847  if (RSTRING_LEN(s) > 0 && *(RSTRING_END(s)-1) != '\n')
2848  rb_str_cat_cstr(s, "\n");
2849  }
2850  return exc;
2851 }
2852 
2853 /*
2854  * Document-module: Errno
2855 
2856  * When an operating system encounters an error,
2857  * it typically reports the error as an integer error code:
2858  *
2859  * $ ls nosuch.txt
2860  * ls: cannot access 'nosuch.txt': No such file or directory
2861  * $ echo $? # Code for last error.
2862  * 2
2863  *
2864  * When the Ruby interpreter interacts with the operating system
2865  * and receives such an error code (e.g., +2+),
2866  * it maps the code to a particular Ruby exception class (e.g., +Errno::ENOENT+):
2867  *
2868  * File.open('nosuch.txt')
2869  * # => No such file or directory @ rb_sysopen - nosuch.txt (Errno::ENOENT)
2870  *
2871  * Each such class is:
2872  *
2873  * - A nested class in this module, +Errno+.
2874  * - A subclass of class SystemCallError.
2875  * - Associated with an error code.
2876  *
2877  * Thus:
2878  *
2879  * Errno::ENOENT.superclass # => SystemCallError
2880  * Errno::ENOENT::Errno # => 2
2881  *
2882  * The names of nested classes are returned by method +Errno.constants+:
2883  *
2884  * Errno.constants.size # => 158
2885  * Errno.constants.sort.take(5) # => [:E2BIG, :EACCES, :EADDRINUSE, :EADDRNOTAVAIL, :EADV]
2886  *
2887  * As seen above, the error code associated with each class
2888  * is available as the value of a constant;
2889  * the value for a particular class may vary among operating systems.
2890  * If the class is not needed for the particular operating system,
2891  * the value is zero:
2892  *
2893  * Errno::ENOENT::Errno # => 2
2894  * Errno::ENOTCAPABLE::Errno # => 0
2895  *
2896  */
2897 
2898 static st_table *syserr_tbl;
2899 
2900 void
2901 rb_free_warning(void)
2902 {
2903  st_free_table(warning_categories.id2enum);
2904  st_free_table(warning_categories.enum2id);
2905  st_free_table(syserr_tbl);
2906 }
2907 
2908 static VALUE
2909 setup_syserr(int n, const char *name)
2910 {
2912 
2913  /* capture nonblock errnos for WaitReadable/WaitWritable subclasses */
2914  switch (n) {
2915  case EAGAIN:
2916  rb_eEAGAIN = error;
2917 
2918 #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
2919  break;
2920  case EWOULDBLOCK:
2921 #endif
2922 
2923  rb_eEWOULDBLOCK = error;
2924  break;
2925  case EINPROGRESS:
2926  rb_eEINPROGRESS = error;
2927  break;
2928  }
2929 
2930  rb_define_const(error, "Errno", INT2NUM(n));
2931  st_add_direct(syserr_tbl, n, (st_data_t)error);
2932  return error;
2933 }
2934 
2935 static VALUE
2936 set_syserr(int n, const char *name)
2937 {
2938  st_data_t error;
2939 
2940  if (!st_lookup(syserr_tbl, n, &error)) {
2941  return setup_syserr(n, name);
2942  }
2943  else {
2944  VALUE errclass = (VALUE)error;
2945  rb_define_const(rb_mErrno, name, errclass);
2946  return errclass;
2947  }
2948 }
2949 
2950 static VALUE
2951 get_syserr(int n)
2952 {
2953  st_data_t error;
2954 
2955  if (!st_lookup(syserr_tbl, n, &error)) {
2956  char name[DECIMAL_SIZE_OF(n) + sizeof("E-")];
2957 
2958  snprintf(name, sizeof(name), "E%03d", n);
2959  return setup_syserr(n, name);
2960  }
2961  return (VALUE)error;
2962 }
2963 
2964 /*
2965  * call-seq:
2966  * SystemCallError.new(msg, errno) -> system_call_error_subclass
2967  *
2968  * If _errno_ corresponds to a known system error code, constructs the
2969  * appropriate Errno class for that error, otherwise constructs a
2970  * generic SystemCallError object. The error number is subsequently
2971  * available via the #errno method.
2972  */
2973 
2974 static VALUE
2975 syserr_initialize(int argc, VALUE *argv, VALUE self)
2976 {
2977  const char *err;
2978  VALUE mesg, error, func, errmsg;
2979  VALUE klass = rb_obj_class(self);
2980 
2981  if (klass == rb_eSystemCallError) {
2982  st_data_t data = (st_data_t)klass;
2983  rb_scan_args(argc, argv, "12", &mesg, &error, &func);
2984  if (argc == 1 && FIXNUM_P(mesg)) {
2985  error = mesg; mesg = Qnil;
2986  }
2987  if (!NIL_P(error) && st_lookup(syserr_tbl, NUM2LONG(error), &data)) {
2988  klass = (VALUE)data;
2989  /* change class */
2990  if (!RB_TYPE_P(self, T_OBJECT)) { /* insurance to avoid type crash */
2991  rb_raise(rb_eTypeError, "invalid instance type");
2992  }
2993  RBASIC_SET_CLASS(self, klass);
2994  }
2995  }
2996  else {
2997  rb_scan_args(argc, argv, "02", &mesg, &func);
2998  error = rb_const_get(klass, id_Errno);
2999  }
3000  if (!NIL_P(error)) err = strerror(NUM2INT(error));
3001  else err = "unknown error";
3002 
3003  errmsg = rb_enc_str_new_cstr(err, rb_locale_encoding());
3004  if (!NIL_P(mesg)) {
3005  VALUE str = StringValue(mesg);
3006 
3007  if (!NIL_P(func)) rb_str_catf(errmsg, " @ %"PRIsVALUE, func);
3008  rb_str_catf(errmsg, " - %"PRIsVALUE, str);
3009  }
3010  mesg = errmsg;
3011 
3012  rb_call_super(1, &mesg);
3013  rb_ivar_set(self, id_errno, error);
3014  return self;
3015 }
3016 
3017 /*
3018  * call-seq:
3019  * system_call_error.errno -> integer
3020  *
3021  * Return this SystemCallError's error number.
3022  */
3023 
3024 static VALUE
3025 syserr_errno(VALUE self)
3026 {
3027  return rb_attr_get(self, id_errno);
3028 }
3029 
3030 /*
3031  * call-seq:
3032  * system_call_error === other -> true or false
3033  *
3034  * Return +true+ if the receiver is a generic +SystemCallError+, or
3035  * if the error numbers +self+ and _other_ are the same.
3036  */
3037 
3038 static VALUE
3039 syserr_eqq(VALUE self, VALUE exc)
3040 {
3041  VALUE num, e;
3042 
3044  if (!rb_respond_to(exc, id_errno)) return Qfalse;
3045  }
3046  else if (self == rb_eSystemCallError) return Qtrue;
3047 
3048  num = rb_attr_get(exc, id_errno);
3049  if (NIL_P(num)) {
3050  num = rb_funcallv(exc, id_errno, 0, 0);
3051  }
3052  e = rb_const_get(self, id_Errno);
3053  return RBOOL(FIXNUM_P(num) ? num == e : rb_equal(num, e));
3054 }
3055 
3056 
3057 /*
3058  * Document-class: StandardError
3059  *
3060  * The most standard error types are subclasses of StandardError. A
3061  * rescue clause without an explicit Exception class will rescue all
3062  * StandardErrors (and only those).
3063  *
3064  * def foo
3065  * raise "Oups"
3066  * end
3067  * foo rescue "Hello" #=> "Hello"
3068  *
3069  * On the other hand:
3070  *
3071  * require 'does/not/exist' rescue "Hi"
3072  *
3073  * <em>raises the exception:</em>
3074  *
3075  * LoadError: no such file to load -- does/not/exist
3076  *
3077  */
3078 
3079 /*
3080  * Document-class: SystemExit
3081  *
3082  * Raised by +exit+ to initiate the termination of the script.
3083  */
3084 
3085 /*
3086  * Document-class: SignalException
3087  *
3088  * Raised when a signal is received.
3089  *
3090  * begin
3091  * Process.kill('HUP',Process.pid)
3092  * sleep # wait for receiver to handle signal sent by Process.kill
3093  * rescue SignalException => e
3094  * puts "received Exception #{e}"
3095  * end
3096  *
3097  * <em>produces:</em>
3098  *
3099  * received Exception SIGHUP
3100  */
3101 
3102 /*
3103  * Document-class: Interrupt
3104  *
3105  * Raised when the interrupt signal is received, typically because the
3106  * user has pressed Control-C (on most posix platforms). As such, it is a
3107  * subclass of +SignalException+.
3108  *
3109  * begin
3110  * puts "Press ctrl-C when you get bored"
3111  * loop {}
3112  * rescue Interrupt => e
3113  * puts "Note: You will typically use Signal.trap instead."
3114  * end
3115  *
3116  * <em>produces:</em>
3117  *
3118  * Press ctrl-C when you get bored
3119  *
3120  * <em>then waits until it is interrupted with Control-C and then prints:</em>
3121  *
3122  * Note: You will typically use Signal.trap instead.
3123  */
3124 
3125 /*
3126  * Document-class: TypeError
3127  *
3128  * Raised when encountering an object that is not of the expected type.
3129  *
3130  * [1, 2, 3].first("two")
3131  *
3132  * <em>raises the exception:</em>
3133  *
3134  * TypeError: no implicit conversion of String into Integer
3135  *
3136  */
3137 
3138 /*
3139  * Document-class: ArgumentError
3140  *
3141  * Raised when the arguments are wrong and there isn't a more specific
3142  * Exception class.
3143  *
3144  * Ex: passing the wrong number of arguments
3145  *
3146  * [1, 2, 3].first(4, 5)
3147  *
3148  * <em>raises the exception:</em>
3149  *
3150  * ArgumentError: wrong number of arguments (given 2, expected 1)
3151  *
3152  * Ex: passing an argument that is not acceptable:
3153  *
3154  * [1, 2, 3].first(-4)
3155  *
3156  * <em>raises the exception:</em>
3157  *
3158  * ArgumentError: negative array size
3159  */
3160 
3161 /*
3162  * Document-class: IndexError
3163  *
3164  * Raised when the given index is invalid.
3165  *
3166  * a = [:foo, :bar]
3167  * a.fetch(0) #=> :foo
3168  * a[4] #=> nil
3169  * a.fetch(4) #=> IndexError: index 4 outside of array bounds: -2...2
3170  *
3171  */
3172 
3173 /*
3174  * Document-class: KeyError
3175  *
3176  * Raised when the specified key is not found. It is a subclass of
3177  * IndexError.
3178  *
3179  * h = {"foo" => :bar}
3180  * h.fetch("foo") #=> :bar
3181  * h.fetch("baz") #=> KeyError: key not found: "baz"
3182  *
3183  */
3184 
3185 /*
3186  * Document-class: RangeError
3187  *
3188  * Raised when a given numerical value is out of range.
3189  *
3190  * [1, 2, 3].drop(1 << 100)
3191  *
3192  * <em>raises the exception:</em>
3193  *
3194  * RangeError: bignum too big to convert into `long'
3195  */
3196 
3197 /*
3198  * Document-class: ScriptError
3199  *
3200  * ScriptError is the superclass for errors raised when a script
3201  * can not be executed because of a +LoadError+,
3202  * +NotImplementedError+ or a +SyntaxError+. Note these type of
3203  * +ScriptErrors+ are not +StandardError+ and will not be
3204  * rescued unless it is specified explicitly (or its ancestor
3205  * +Exception+).
3206  */
3207 
3208 /*
3209  * Document-class: SyntaxError
3210  *
3211  * Raised when encountering Ruby code with an invalid syntax.
3212  *
3213  * eval("1+1=2")
3214  *
3215  * <em>raises the exception:</em>
3216  *
3217  * SyntaxError: (eval):1: syntax error, unexpected '=', expecting $end
3218  */
3219 
3220 /*
3221  * Document-class: LoadError
3222  *
3223  * Raised when a file required (a Ruby script, extension library, ...)
3224  * fails to load.
3225  *
3226  * require 'this/file/does/not/exist'
3227  *
3228  * <em>raises the exception:</em>
3229  *
3230  * LoadError: no such file to load -- this/file/does/not/exist
3231  */
3232 
3233 /*
3234  * Document-class: NotImplementedError
3235  *
3236  * Raised when a feature is not implemented on the current platform. For
3237  * example, methods depending on the +fsync+ or +fork+ system calls may
3238  * raise this exception if the underlying operating system or Ruby
3239  * runtime does not support them.
3240  *
3241  * Note that if +fork+ raises a +NotImplementedError+, then
3242  * <code>respond_to?(:fork)</code> returns +false+.
3243  */
3244 
3245 /*
3246  * Document-class: NameError
3247  *
3248  * Raised when a given name is invalid or undefined.
3249  *
3250  * puts foo
3251  *
3252  * <em>raises the exception:</em>
3253  *
3254  * NameError: undefined local variable or method `foo' for main:Object
3255  *
3256  * Since constant names must start with a capital:
3257  *
3258  * Integer.const_set :answer, 42
3259  *
3260  * <em>raises the exception:</em>
3261  *
3262  * NameError: wrong constant name answer
3263  */
3264 
3265 /*
3266  * Document-class: NoMethodError
3267  *
3268  * Raised when a method is called on a receiver which doesn't have it
3269  * defined and also fails to respond with +method_missing+.
3270  *
3271  * "hello".to_ary
3272  *
3273  * <em>raises the exception:</em>
3274  *
3275  * NoMethodError: undefined method `to_ary' for an instance of String
3276  */
3277 
3278 /*
3279  * Document-class: FrozenError
3280  *
3281  * Raised when there is an attempt to modify a frozen object.
3282  *
3283  * [1, 2, 3].freeze << 4
3284  *
3285  * <em>raises the exception:</em>
3286  *
3287  * FrozenError: can't modify frozen Array
3288  */
3289 
3290 /*
3291  * Document-class: RuntimeError
3292  *
3293  * A generic error class raised when an invalid operation is attempted.
3294  * Kernel#raise will raise a RuntimeError if no Exception class is
3295  * specified.
3296  *
3297  * raise "ouch"
3298  *
3299  * <em>raises the exception:</em>
3300  *
3301  * RuntimeError: ouch
3302  */
3303 
3304 /*
3305  * Document-class: SecurityError
3306  *
3307  * No longer used by internal code.
3308  */
3309 
3310 /*
3311  * Document-class: NoMemoryError
3312  *
3313  * Raised when memory allocation fails.
3314  */
3315 
3316 /*
3317  * Document-class: SystemCallError
3318  *
3319  * SystemCallError is the base class for all low-level
3320  * platform-dependent errors.
3321  *
3322  * The errors available on the current platform are subclasses of
3323  * SystemCallError and are defined in the Errno module.
3324  *
3325  * File.open("does/not/exist")
3326  *
3327  * <em>raises the exception:</em>
3328  *
3329  * Errno::ENOENT: No such file or directory - does/not/exist
3330  */
3331 
3332 /*
3333  * Document-class: EncodingError
3334  *
3335  * EncodingError is the base class for encoding errors.
3336  */
3337 
3338 /*
3339  * Document-class: Encoding::CompatibilityError
3340  *
3341  * Raised by Encoding and String methods when the source encoding is
3342  * incompatible with the target encoding.
3343  */
3344 
3345 /*
3346  * Document-class: fatal
3347  *
3348  * +fatal+ is an Exception that is raised when Ruby has encountered a fatal
3349  * error and must exit.
3350  */
3351 
3352 /*
3353  * Document-class: NameError::message
3354  * :nodoc:
3355  */
3356 
3357 /*
3358  * Document-class: Exception
3359  *
3360  * \Class +Exception+ and its subclasses are used to indicate that an error
3361  * or other problem has occurred,
3362  * and may need to be handled.
3363  * See {Exceptions}[rdoc-ref:exceptions.md].
3364  *
3365  * An +Exception+ object carries certain information:
3366  *
3367  * - The type (the exception's class),
3368  * commonly StandardError, RuntimeError, or a subclass of one or the other;
3369  * see {Built-In Exception Class Hierarchy}[rdoc-ref:Exception@Built-In+Exception+Class+Hierarchy].
3370  * - An optional descriptive message;
3371  * see methods ::new, #message.
3372  * - Optional backtrace information;
3373  * see methods #backtrace, #backtrace_locations, #set_backtrace.
3374  * - An optional cause;
3375  * see method #cause.
3376  *
3377  * == Built-In \Exception \Class Hierarchy
3378  *
3379  * The hierarchy of built-in subclasses of class +Exception+:
3380  *
3381  * * NoMemoryError
3382  * * ScriptError
3383  * * {LoadError}[https://docs.ruby-lang.org/en/master/LoadError.html]
3384  * * NotImplementedError
3385  * * SyntaxError
3386  * * SecurityError
3387  * * SignalException
3388  * * Interrupt
3389  * * StandardError
3390  * * ArgumentError
3391  * * UncaughtThrowError
3392  * * EncodingError
3393  * * FiberError
3394  * * IOError
3395  * * EOFError
3396  * * IndexError
3397  * * KeyError
3398  * * StopIteration
3399  * * ClosedQueueError
3400  * * LocalJumpError
3401  * * NameError
3402  * * NoMethodError
3403  * * RangeError
3404  * * FloatDomainError
3405  * * RegexpError
3406  * * RuntimeError
3407  * * FrozenError
3408  * * SystemCallError
3409  * * Errno (and its subclasses, representing system errors)
3410  * * ThreadError
3411  * * TypeError
3412  * * ZeroDivisionError
3413  * * SystemExit
3414  * * SystemStackError
3415  * * {fatal}[https://docs.ruby-lang.org/en/master/fatal.html]
3416  *
3417  */
3418 
3419 static VALUE
3420 exception_alloc(VALUE klass)
3421 {
3422  return rb_class_allocate_instance(klass);
3423 }
3424 
3425 static VALUE
3426 exception_dumper(VALUE exc)
3427 {
3428  // TODO: Currently, the instance variables "bt" and "bt_locations"
3429  // refers to the same object (Array of String). But "bt_locations"
3430  // should have an Array of Thread::Backtrace::Locations.
3431 
3432  return exc;
3433 }
3434 
3435 static int
3436 ivar_copy_i(ID key, VALUE val, st_data_t exc)
3437 {
3438  rb_ivar_set((VALUE)exc, key, val);
3439  return ST_CONTINUE;
3440 }
3441 
3442 void rb_exc_check_circular_cause(VALUE exc);
3443 
3444 static VALUE
3445 exception_loader(VALUE exc, VALUE obj)
3446 {
3447  // The loader function of rb_marshal_define_compat seems to be called for two events:
3448  // one is for fixup (r_fixup_compat), the other is for TYPE_USERDEF.
3449  // In the former case, the first argument is an instance of Exception (because
3450  // we pass rb_eException to rb_marshal_define_compat). In the latter case, the first
3451  // argument is a class object (see TYPE_USERDEF case in r_object0).
3452  // We want to copy all instance variables (but "bt_locations") from obj to exc.
3453  // But we do not want to do so in the second case, so the following branch is for that.
3454  if (RB_TYPE_P(exc, T_CLASS)) return obj; // maybe called from Marshal's TYPE_USERDEF
3455 
3456  rb_ivar_foreach(obj, ivar_copy_i, exc);
3457 
3458  rb_exc_check_circular_cause(exc);
3459 
3460  if (rb_attr_get(exc, id_bt) == rb_attr_get(exc, id_bt_locations)) {
3461  rb_ivar_set(exc, id_bt_locations, Qnil);
3462  }
3463 
3464  return exc;
3465 }
3466 
3467 void
3468 Init_Exception(void)
3469 {
3470  rb_eException = rb_define_class("Exception", rb_cObject);
3471  rb_define_alloc_func(rb_eException, exception_alloc);
3472  rb_marshal_define_compat(rb_eException, rb_eException, exception_dumper, exception_loader);
3474  rb_define_singleton_method(rb_eException, "to_tty?", exc_s_to_tty_p, 0);
3475  rb_define_method(rb_eException, "exception", exc_exception, -1);
3476  rb_define_method(rb_eException, "initialize", exc_initialize, -1);
3477  rb_define_method(rb_eException, "==", exc_equal, 1);
3478  rb_define_method(rb_eException, "to_s", exc_to_s, 0);
3479  rb_define_method(rb_eException, "message", exc_message, 0);
3480  rb_define_method(rb_eException, "detailed_message", exc_detailed_message, -1);
3481  rb_define_method(rb_eException, "full_message", exc_full_message, -1);
3482  rb_define_method(rb_eException, "inspect", exc_inspect, 0);
3483  rb_define_method(rb_eException, "backtrace", exc_backtrace, 0);
3484  rb_define_method(rb_eException, "backtrace_locations", exc_backtrace_locations, 0);
3485  rb_define_method(rb_eException, "set_backtrace", exc_set_backtrace, 1);
3486  rb_define_method(rb_eException, "cause", exc_cause, 0);
3487 
3488  rb_eSystemExit = rb_define_class("SystemExit", rb_eException);
3489  rb_define_method(rb_eSystemExit, "initialize", exit_initialize, -1);
3490  rb_define_method(rb_eSystemExit, "status", exit_status, 0);
3491  rb_define_method(rb_eSystemExit, "success?", exit_success_p, 0);
3492 
3494  rb_eSignal = rb_define_class("SignalException", rb_eException);
3495  rb_eInterrupt = rb_define_class("Interrupt", rb_eSignal);
3496 
3497  rb_eStandardError = rb_define_class("StandardError", rb_eException);
3499  rb_eArgError = rb_define_class("ArgumentError", rb_eStandardError);
3502  rb_define_method(rb_eKeyError, "initialize", key_err_initialize, -1);
3503  rb_define_method(rb_eKeyError, "receiver", key_err_receiver, 0);
3504  rb_define_method(rb_eKeyError, "key", key_err_key, 0);
3506 
3507  rb_eScriptError = rb_define_class("ScriptError", rb_eException);
3509  rb_define_method(rb_eSyntaxError, "initialize", syntax_error_initialize, -1);
3510 
3511  /* RDoc will use literal name value while parsing rb_attr,
3512  * and will render `idPath` as an attribute name without this trick */
3513  ID path = idPath;
3514 
3515  /* the path that failed to parse */
3516  rb_attr(rb_eSyntaxError, path, TRUE, FALSE, FALSE);
3517 
3519  /* the path that failed to load */
3520  rb_attr(rb_eLoadError, path, TRUE, FALSE, FALSE);
3521 
3522  rb_eNotImpError = rb_define_class("NotImplementedError", rb_eScriptError);
3523 
3525  rb_define_method(rb_eNameError, "initialize", name_err_initialize, -1);
3526  rb_define_method(rb_eNameError, "name", name_err_name, 0);
3527  rb_define_method(rb_eNameError, "receiver", name_err_receiver, 0);
3528  rb_define_method(rb_eNameError, "local_variables", name_err_local_variables, 0);
3529  rb_cNameErrorMesg = rb_define_class_under(rb_eNameError, "message", rb_cObject);
3530  rb_define_alloc_func(rb_cNameErrorMesg, name_err_mesg_alloc);
3531  rb_define_method(rb_cNameErrorMesg, "initialize_copy", name_err_mesg_init_copy, 1);
3532  rb_define_method(rb_cNameErrorMesg, "==", name_err_mesg_equal, 1);
3533  rb_define_method(rb_cNameErrorMesg, "to_str", name_err_mesg_to_str, 0);
3534  rb_define_method(rb_cNameErrorMesg, "_dump", name_err_mesg_dump, 1);
3535  rb_define_singleton_method(rb_cNameErrorMesg, "_load", name_err_mesg_load, 1);
3536  rb_eNoMethodError = rb_define_class("NoMethodError", rb_eNameError);
3537  rb_define_method(rb_eNoMethodError, "initialize", nometh_err_initialize, -1);
3538  rb_define_method(rb_eNoMethodError, "args", nometh_err_args, 0);
3539  rb_define_method(rb_eNoMethodError, "private_call?", nometh_err_private_call_p, 0);
3540 
3543  rb_define_method(rb_eFrozenError, "initialize", frozen_err_initialize, -1);
3544  rb_define_method(rb_eFrozenError, "receiver", frozen_err_receiver, 0);
3545  rb_eSecurityError = rb_define_class("SecurityError", rb_eException);
3546  rb_eNoMemError = rb_define_class("NoMemoryError", rb_eException);
3549  rb_eNoMatchingPatternError = rb_define_class("NoMatchingPatternError", rb_eStandardError);
3551  rb_define_method(rb_eNoMatchingPatternKeyError, "initialize", no_matching_pattern_key_err_initialize, -1);
3552  rb_define_method(rb_eNoMatchingPatternKeyError, "matchee", no_matching_pattern_key_err_matchee, 0);
3553  rb_define_method(rb_eNoMatchingPatternKeyError, "key", no_matching_pattern_key_err_key, 0);
3554 
3555  syserr_tbl = st_init_numtable();
3557  rb_define_method(rb_eSystemCallError, "initialize", syserr_initialize, -1);
3558  rb_define_method(rb_eSystemCallError, "errno", syserr_errno, 0);
3559  rb_define_singleton_method(rb_eSystemCallError, "===", syserr_eqq, 1);
3560 
3561  rb_mErrno = rb_define_module("Errno");
3562 
3563  rb_mWarning = rb_define_module("Warning");
3564  rb_define_singleton_method(rb_mWarning, "[]", rb_warning_s_aref, 1);
3565  rb_define_singleton_method(rb_mWarning, "[]=", rb_warning_s_aset, 2);
3566  rb_define_singleton_method(rb_mWarning, "categories", rb_warning_s_categories, 0);
3567  rb_define_method(rb_mWarning, "warn", rb_warning_s_warn, -1);
3568  rb_extend_object(rb_mWarning, rb_mWarning);
3569 
3570  /* :nodoc: */
3571  rb_cWarningBuffer = rb_define_class_under(rb_mWarning, "buffer", rb_cString);
3572  rb_define_method(rb_cWarningBuffer, "write", warning_write, -1);
3573 
3574  id_cause = rb_intern_const("cause");
3575  id_message = rb_intern_const("message");
3576  id_detailed_message = rb_intern_const("detailed_message");
3577  id_backtrace = rb_intern_const("backtrace");
3578  id_key = rb_intern_const("key");
3579  id_matchee = rb_intern_const("matchee");
3580  id_args = rb_intern_const("args");
3581  id_receiver = rb_intern_const("receiver");
3582  id_private_call_p = rb_intern_const("private_call?");
3583  id_local_variables = rb_intern_const("local_variables");
3584  id_Errno = rb_intern_const("Errno");
3585  id_errno = rb_intern_const("errno");
3586  id_i_path = rb_intern_const("@path");
3587  id_warn = rb_intern_const("warn");
3588  id_category = rb_intern_const("category");
3589  id_deprecated = rb_intern_const("deprecated");
3590  id_experimental = rb_intern_const("experimental");
3591  id_performance = rb_intern_const("performance");
3592  id_strict_unused_block = rb_intern_const("strict_unused_block");
3593  id_top = rb_intern_const("top");
3594  id_bottom = rb_intern_const("bottom");
3595  id_iseq = rb_make_internal_id();
3596  id_recv = rb_make_internal_id();
3597 
3598  sym_category = ID2SYM(id_category);
3599  sym_highlight = ID2SYM(rb_intern_const("highlight"));
3600 
3601  warning_categories.id2enum = rb_init_identtable();
3602  st_add_direct(warning_categories.id2enum, id_deprecated, RB_WARN_CATEGORY_DEPRECATED);
3603  st_add_direct(warning_categories.id2enum, id_experimental, RB_WARN_CATEGORY_EXPERIMENTAL);
3604  st_add_direct(warning_categories.id2enum, id_performance, RB_WARN_CATEGORY_PERFORMANCE);
3605  st_add_direct(warning_categories.id2enum, id_strict_unused_block, RB_WARN_CATEGORY_STRICT_UNUSED_BLOCK);
3606 
3607  warning_categories.enum2id = rb_init_identtable();
3608  st_add_direct(warning_categories.enum2id, RB_WARN_CATEGORY_NONE, 0);
3609  st_add_direct(warning_categories.enum2id, RB_WARN_CATEGORY_DEPRECATED, id_deprecated);
3610  st_add_direct(warning_categories.enum2id, RB_WARN_CATEGORY_EXPERIMENTAL, id_experimental);
3611  st_add_direct(warning_categories.enum2id, RB_WARN_CATEGORY_PERFORMANCE, id_performance);
3612  st_add_direct(warning_categories.enum2id, RB_WARN_CATEGORY_STRICT_UNUSED_BLOCK, id_strict_unused_block);
3613 }
3614 
3615 void
3616 rb_enc_raise(rb_encoding *enc, VALUE exc, const char *fmt, ...)
3617 {
3618  va_list args;
3619  VALUE mesg;
3620 
3621  va_start(args, fmt);
3622  mesg = rb_enc_vsprintf(enc, fmt, args);
3623  va_end(args);
3624 
3625  rb_exc_raise(rb_exc_new3(exc, mesg));
3626 }
3627 
3628 void
3629 rb_vraise(VALUE exc, const char *fmt, va_list ap)
3630 {
3631  rb_exc_raise(rb_exc_new3(exc, rb_vsprintf(fmt, ap)));
3632 }
3633 
3634 void
3635 rb_raise(VALUE exc, const char *fmt, ...)
3636 {
3637  va_list args;
3638  va_start(args, fmt);
3639  rb_vraise(exc, fmt, args);
3640  va_end(args);
3641 }
3642 
3643 NORETURN(static void raise_loaderror(VALUE path, VALUE mesg));
3644 
3645 static void
3646 raise_loaderror(VALUE path, VALUE mesg)
3647 {
3648  VALUE err = rb_exc_new3(rb_eLoadError, mesg);
3649  rb_ivar_set(err, id_i_path, path);
3650  rb_exc_raise(err);
3651 }
3652 
3653 void
3654 rb_loaderror(const char *fmt, ...)
3655 {
3656  va_list args;
3657  VALUE mesg;
3658 
3659  va_start(args, fmt);
3660  mesg = rb_enc_vsprintf(rb_locale_encoding(), fmt, args);
3661  va_end(args);
3662  raise_loaderror(Qnil, mesg);
3663 }
3664 
3665 void
3666 rb_loaderror_with_path(VALUE path, const char *fmt, ...)
3667 {
3668  va_list args;
3669  VALUE mesg;
3670 
3671  va_start(args, fmt);
3672  mesg = rb_enc_vsprintf(rb_locale_encoding(), fmt, args);
3673  va_end(args);
3674  raise_loaderror(path, mesg);
3675 }
3676 
3677 void
3679 {
3681  "%"PRIsVALUE"() function is unimplemented on this machine",
3683 }
3684 
3685 void
3686 rb_fatal(const char *fmt, ...)
3687 {
3688  va_list args;
3689  VALUE mesg;
3690 
3691  if (! ruby_thread_has_gvl_p()) {
3692  /* The thread has no GVL. Object allocation impossible (cant run GC),
3693  * thus no message can be printed out. */
3694  fprintf(stderr, "[FATAL] rb_fatal() outside of GVL\n");
3695  rb_print_backtrace(stderr);
3696  die();
3697  }
3698 
3699  va_start(args, fmt);
3700  mesg = rb_vsprintf(fmt, args);
3701  va_end(args);
3702 
3704 }
3705 
3706 static VALUE
3707 make_errno_exc(const char *mesg)
3708 {
3709  int n = errno;
3710 
3711  errno = 0;
3712  if (n == 0) {
3713  rb_bug("rb_sys_fail(%s) - errno == 0", mesg ? mesg : "");
3714  }
3715  return rb_syserr_new(n, mesg);
3716 }
3717 
3718 static VALUE
3719 make_errno_exc_str(VALUE mesg)
3720 {
3721  int n = errno;
3722 
3723  errno = 0;
3724  if (!mesg) mesg = Qnil;
3725  if (n == 0) {
3726  const char *s = !NIL_P(mesg) ? RSTRING_PTR(mesg) : "";
3727  rb_bug("rb_sys_fail_str(%s) - errno == 0", s);
3728  }
3729  return rb_syserr_new_str(n, mesg);
3730 }
3731 
3732 VALUE
3733 rb_syserr_new(int n, const char *mesg)
3734 {
3735  VALUE arg;
3736  arg = mesg ? rb_str_new2(mesg) : Qnil;
3737  return rb_syserr_new_str(n, arg);
3738 }
3739 
3740 VALUE
3742 {
3743  return rb_class_new_instance(1, &arg, get_syserr(n));
3744 }
3745 
3746 void
3747 rb_syserr_fail(int e, const char *mesg)
3748 {
3749  rb_exc_raise(rb_syserr_new(e, mesg));
3750 }
3751 
3752 void
3754 {
3755  rb_exc_raise(rb_syserr_new_str(e, mesg));
3756 }
3757 
3758 #undef rb_sys_fail
3759 void
3760 rb_sys_fail(const char *mesg)
3761 {
3762  rb_exc_raise(make_errno_exc(mesg));
3763 }
3764 
3765 #undef rb_sys_fail_str
3766 void
3768 {
3769  rb_exc_raise(make_errno_exc_str(mesg));
3770 }
3771 
3772 #ifdef RUBY_FUNCTION_NAME_STRING
3773 void
3774 rb_sys_fail_path_in(const char *func_name, VALUE path)
3775 {
3776  int n = errno;
3777 
3778  errno = 0;
3779  rb_syserr_fail_path_in(func_name, n, path);
3780 }
3781 
3782 void
3783 rb_syserr_fail_path_in(const char *func_name, int n, VALUE path)
3784 {
3785  rb_exc_raise(rb_syserr_new_path_in(func_name, n, path));
3786 }
3787 
3788 VALUE
3789 rb_syserr_new_path_in(const char *func_name, int n, VALUE path)
3790 {
3791  VALUE args[2];
3792 
3793  if (!path) path = Qnil;
3794  if (n == 0) {
3795  const char *s = !NIL_P(path) ? RSTRING_PTR(path) : "";
3796  if (!func_name) func_name = "(null)";
3797  rb_bug("rb_sys_fail_path_in(%s, %s) - errno == 0",
3798  func_name, s);
3799  }
3800  args[0] = path;
3801  args[1] = rb_str_new_cstr(func_name);
3802  return rb_class_new_instance(2, args, get_syserr(n));
3803 }
3804 #endif
3805 
3806 NORETURN(static void rb_mod_exc_raise(VALUE exc, VALUE mod));
3807 
3808 static void
3809 rb_mod_exc_raise(VALUE exc, VALUE mod)
3810 {
3811  rb_extend_object(exc, mod);
3812  rb_exc_raise(exc);
3813 }
3814 
3815 void
3816 rb_mod_sys_fail(VALUE mod, const char *mesg)
3817 {
3818  VALUE exc = make_errno_exc(mesg);
3819  rb_mod_exc_raise(exc, mod);
3820 }
3821 
3822 void
3824 {
3825  VALUE exc = make_errno_exc_str(mesg);
3826  rb_mod_exc_raise(exc, mod);
3827 }
3828 
3829 void
3830 rb_mod_syserr_fail(VALUE mod, int e, const char *mesg)
3831 {
3832  VALUE exc = rb_syserr_new(e, mesg);
3833  rb_mod_exc_raise(exc, mod);
3834 }
3835 
3836 void
3838 {
3839  VALUE exc = rb_syserr_new_str(e, mesg);
3840  rb_mod_exc_raise(exc, mod);
3841 }
3842 
3843 static void
3844 syserr_warning(VALUE mesg, int err)
3845 {
3846  rb_str_set_len(mesg, RSTRING_LEN(mesg)-1);
3847  rb_str_catf(mesg, ": %s\n", strerror(err));
3848  rb_write_warning_str(mesg);
3849 }
3850 
3851 #if 0
3852 void
3853 rb_sys_warn(const char *fmt, ...)
3854 {
3855  if (!NIL_P(ruby_verbose)) {
3856  int errno_save = errno;
3857  with_warning_string(mesg, 0, fmt) {
3858  syserr_warning(mesg, errno_save);
3859  }
3860  errno = errno_save;
3861  }
3862 }
3863 
3864 void
3865 rb_syserr_warn(int err, const char *fmt, ...)
3866 {
3867  if (!NIL_P(ruby_verbose)) {
3868  with_warning_string(mesg, 0, fmt) {
3869  syserr_warning(mesg, err);
3870  }
3871  }
3872 }
3873 
3874 void
3875 rb_sys_enc_warn(rb_encoding *enc, const char *fmt, ...)
3876 {
3877  if (!NIL_P(ruby_verbose)) {
3878  int errno_save = errno;
3879  with_warning_string(mesg, enc, fmt) {
3880  syserr_warning(mesg, errno_save);
3881  }
3882  errno = errno_save;
3883  }
3884 }
3885 
3886 void
3887 rb_syserr_enc_warn(int err, rb_encoding *enc, const char *fmt, ...)
3888 {
3889  if (!NIL_P(ruby_verbose)) {
3890  with_warning_string(mesg, enc, fmt) {
3891  syserr_warning(mesg, err);
3892  }
3893  }
3894 }
3895 #endif
3896 
3897 void
3898 rb_sys_warning(const char *fmt, ...)
3899 {
3900  if (RTEST(ruby_verbose)) {
3901  int errno_save = errno;
3902  with_warning_string(mesg, 0, fmt) {
3903  syserr_warning(mesg, errno_save);
3904  }
3905  errno = errno_save;
3906  }
3907 }
3908 
3909 #if 0
3910 void
3911 rb_syserr_warning(int err, const char *fmt, ...)
3912 {
3913  if (RTEST(ruby_verbose)) {
3914  with_warning_string(mesg, 0, fmt) {
3915  syserr_warning(mesg, err);
3916  }
3917  }
3918 }
3919 #endif
3920 
3921 void
3922 rb_sys_enc_warning(rb_encoding *enc, const char *fmt, ...)
3923 {
3924  if (RTEST(ruby_verbose)) {
3925  int errno_save = errno;
3926  with_warning_string(mesg, enc, fmt) {
3927  syserr_warning(mesg, errno_save);
3928  }
3929  errno = errno_save;
3930  }
3931 }
3932 
3933 void
3934 rb_syserr_enc_warning(int err, rb_encoding *enc, const char *fmt, ...)
3935 {
3936  if (RTEST(ruby_verbose)) {
3937  with_warning_string(mesg, enc, fmt) {
3938  syserr_warning(mesg, err);
3939  }
3940  }
3941 }
3942 
3943 void
3944 rb_load_fail(VALUE path, const char *err)
3945 {
3946  VALUE mesg = rb_str_buf_new_cstr(err);
3947  rb_str_cat2(mesg, " -- ");
3948  rb_str_append(mesg, path); /* should be ASCII compatible */
3949  raise_loaderror(path, mesg);
3950 }
3951 
3952 void
3953 rb_error_frozen(const char *what)
3954 {
3955  rb_raise(rb_eFrozenError, "can't modify frozen %s", what);
3956 }
3957 
3958 void
3959 rb_frozen_error_raise(VALUE frozen_obj, const char *fmt, ...)
3960 {
3961  va_list args;
3962  VALUE exc, mesg;
3963 
3964  va_start(args, fmt);
3965  mesg = rb_vsprintf(fmt, args);
3966  va_end(args);
3967  exc = rb_exc_new3(rb_eFrozenError, mesg);
3968  rb_ivar_set(exc, id_recv, frozen_obj);
3969  rb_exc_raise(exc);
3970 }
3971 
3972 static VALUE
3973 inspect_frozen_obj(VALUE obj, VALUE mesg, int recur)
3974 {
3975  if (recur) {
3976  rb_str_cat_cstr(mesg, " ...");
3977  }
3978  else {
3979  rb_str_append(mesg, rb_inspect(obj));
3980  }
3981  return mesg;
3982 }
3983 
3984 static VALUE
3985 get_created_info(VALUE obj, int *pline)
3986 {
3987  VALUE info = rb_attr_get(obj, id_debug_created_info);
3988 
3989  if (NIL_P(info)) return Qnil;
3990 
3991  VALUE path = rb_ary_entry(info, 0);
3992  VALUE line = rb_ary_entry(info, 1);
3993  if (NIL_P(path)) return Qnil;
3994  *pline = NUM2INT(line);
3995  return StringValue(path);
3996 }
3997 
3998 void
4000 {
4001  rb_yjit_lazy_push_frame(GET_EC()->cfp->pc);
4002 
4003  VALUE mesg = rb_sprintf("can't modify frozen %"PRIsVALUE": ",
4004  CLASS_OF(frozen_obj));
4005  VALUE exc = rb_exc_new_str(rb_eFrozenError, mesg);
4006 
4007  rb_ivar_set(exc, id_recv, frozen_obj);
4008  rb_exec_recursive(inspect_frozen_obj, frozen_obj, mesg);
4009 
4010  int created_line;
4011  VALUE created_path = get_created_info(frozen_obj, &created_line);
4012  if (!NIL_P(created_path)) {
4013  rb_str_catf(mesg, ", created at %"PRIsVALUE":%d", created_path, created_line);
4014  }
4015  rb_exc_raise(exc);
4016 }
4017 
4018 void
4019 rb_warn_unchilled_literal(VALUE obj)
4020 {
4022  if (!NIL_P(ruby_verbose) && rb_warning_category_enabled_p(category)) {
4023  int line;
4024  VALUE file = rb_source_location(&line);
4025  VALUE mesg = NIL_P(file) ? rb_str_new(0, 0) : rb_str_dup(file);
4026 
4027  if (!NIL_P(file)) {
4028  if (line) rb_str_catf(mesg, ":%d", line);
4029  rb_str_cat2(mesg, ": ");
4030  }
4031  rb_str_cat2(mesg, "warning: literal string will be frozen in the future");
4032 
4033  VALUE str = obj;
4034  if (STR_SHARED_P(str)) {
4035  str = RSTRING(obj)->as.heap.aux.shared;
4036  }
4037  VALUE created = get_created_info(str, &line);
4038  if (NIL_P(created)) {
4039  rb_str_cat2(mesg, " (run with --debug-frozen-string-literal for more information)\n");
4040  } else {
4041  rb_str_cat2(mesg, "\n");
4042  rb_str_append(mesg, created);
4043  if (line) rb_str_catf(mesg, ":%d", line);
4044  rb_str_cat2(mesg, ": info: the string was created here\n");
4045  }
4046  rb_warn_category(mesg, rb_warning_category_to_name(category));
4047  }
4048 }
4049 
4050 void
4051 rb_warn_unchilled_symbol_to_s(VALUE obj)
4052 {
4055  "warning: string returned by :%s.to_s will be frozen in the future", RSTRING_PTR(obj)
4056  );
4057 }
4058 
4059 #undef rb_check_frozen
4060 void
4062 {
4064 }
4065 
4066 void
4068 {
4069  if (!FL_ABLE(obj)) return;
4070  rb_check_frozen(obj);
4071  if (!FL_ABLE(orig)) return;
4072 }
4073 
4074 void
4075 Init_syserr(void)
4076 {
4077  rb_eNOERROR = setup_syserr(0, "NOERROR");
4078 #if 0
4079  /* No error */
4080  rb_define_const(rb_mErrno, "NOERROR", rb_eNOERROR);
4081 #endif
4082 #define defined_error(name, num) set_syserr((num), (name));
4083 #define undefined_error(name) rb_define_const(rb_mErrno, (name), rb_eNOERROR);
4084 #include "known_errors.inc"
4085 #undef defined_error
4086 #undef undefined_error
4087 }
4088 
4089 #include "warning.rbinc"
4090 
#define RUBY_DEBUG
Define this macro when you want assertions.
Definition: assert.h:88
#define RB_UNLIKELY(x)
Asserts that the given Boolean expression likely doesn't hold.
Definition: assume.h:50
#define rb_define_singleton_method(klass, mid, func, arity)
Defines klass.mid.
Definition: cxxanyargs.hpp:685
VALUE rb_enc_vsprintf(rb_encoding *enc, const char *fmt, va_list ap)
Identical to rb_enc_sprintf(), except it takes a va_list instead of variadic arguments.
Definition: sprintf.c:1179
#define RUBY_EVENT_C_CALL
A method, written in C, is called.
Definition: event.h:43
#define RUBY_EVENT_C_RETURN
Return from a method, written in C.
Definition: event.h:44
#define RBIMPL_ATTR_FORMAT(x, y, z)
Wraps (or simulates) __attribute__((format))
Definition: format.h:27
VALUE rb_define_class(const char *name, VALUE super)
Defines a top-level class.
Definition: class.c:980
void rb_extend_object(VALUE obj, VALUE module)
Extend the object with the module.
Definition: eval.c:1735
VALUE rb_singleton_class(VALUE obj)
Finds or creates the singleton class of the passed object.
Definition: class.c:2297
VALUE rb_define_class_under(VALUE outer, const char *name, VALUE super)
Defines a class under the namespace of outer.
Definition: class.c:1012
VALUE rb_define_module(const char *name)
Defines a top-level module.
Definition: class.c:1095
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_get_kwargs(VALUE keyword_hash, const ID *table, int required, int optional, VALUE *values)
Keyword argument deconstructor.
Definition: class.c:2424
#define rb_str_new2
Old name of rb_str_new_cstr.
Definition: string.h:1675
#define TYPE(_)
Old name of rb_type.
Definition: value_type.h:108
#define ISSPACE
Old name of rb_isspace.
Definition: ctype.h:88
#define T_STRING
Old name of RUBY_T_STRING.
Definition: value_type.h:78
#define T_MASK
Old name of RUBY_T_MASK.
Definition: value_type.h:68
#define Qundef
Old name of RUBY_Qundef.
#define INT2FIX
Old name of RB_INT2FIX.
Definition: long.h:48
#define UNREACHABLE
Old name of RBIMPL_UNREACHABLE.
Definition: assume.h:28
#define ID2SYM
Old name of RB_ID2SYM.
Definition: symbol.h:44
#define rb_str_buf_new2
Old name of rb_str_buf_new_cstr.
Definition: string.h:1679
#define UNREACHABLE_RETURN
Old name of RBIMPL_UNREACHABLE_RETURN.
Definition: assume.h:29
#define T_DATA
Old name of RUBY_T_DATA.
Definition: value_type.h:60
#define CLASS_OF
Old name of rb_class_of.
Definition: globals.h:203
#define T_MODULE
Old name of RUBY_T_MODULE.
Definition: value_type.h:70
#define T_TRUE
Old name of RUBY_T_TRUE.
Definition: value_type.h:81
#define FL_ABLE
Old name of RB_FL_ABLE.
Definition: fl_type.h:122
#define rb_ary_new3
Old name of rb_ary_new_from_args.
Definition: array.h:658
#define rb_exc_new3
Old name of rb_exc_new_str.
Definition: error.h:38
#define T_FALSE
Old name of RUBY_T_FALSE.
Definition: value_type.h:61
#define Qtrue
Old name of RUBY_Qtrue.
#define NUM2INT
Old name of RB_NUM2INT.
Definition: int.h:44
#define INT2NUM
Old name of RB_INT2NUM.
Definition: int.h:43
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define T_ARRAY
Old name of RUBY_T_ARRAY.
Definition: value_type.h:56
#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_SYMBOL
Old name of RUBY_T_SYMBOL.
Definition: value_type.h:80
#define T_CLASS
Old name of RUBY_T_CLASS.
Definition: value_type.h:58
#define FL_TEST
Old name of RB_FL_TEST.
Definition: fl_type.h:131
#define NUM2LONG
Old name of RB_NUM2LONG.
Definition: long.h:51
#define FIXNUM_P
Old name of RB_FIXNUM_P.
#define SYMBOL_P
Old name of RB_SYMBOL_P.
Definition: value_type.h:88
void rb_notimplement(void)
Definition: error.c:3678
void rb_mod_sys_fail(VALUE mod, const char *mesg)
Identical to rb_sys_fail(), except it takes additional module to extend the exception object before r...
Definition: error.c:3816
void * rb_check_typeddata(VALUE obj, const rb_data_type_t *data_type)
Identical to rb_typeddata_is_kind_of(), except it raises exceptions instead of returning false.
Definition: error.c:1375
rb_warning_category_t
Warning categories.
Definition: error.h:43
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:476
void rb_raise(VALUE exc, const char *fmt,...)
Exception entry point.
Definition: error.c:3635
int rb_typeddata_inherited_p(const rb_data_type_t *child, const rb_data_type_t *parent)
Checks for the domestic relationship between the two.
Definition: error.c:1348
void rb_compile_warn(const char *file, int line, const char *fmt,...)
Identical to rb_compile_warning(), except it reports unless $VERBOSE is nil.
Definition: error.c:397
void rb_category_warning(rb_warning_category_t category, const char *fmt,...)
Identical to rb_warning(), except it takes additional "category" parameter.
Definition: error.c:508
void rb_mod_syserr_fail(VALUE mod, int e, const char *mesg)
Identical to rb_mod_sys_fail(), except it does not depend on C global variable errno.
Definition: error.c:3830
void rb_check_frozen(VALUE obj)
Queries if the passed object is frozen.
Definition: error.c:4061
VALUE rb_eNotImpError
NotImplementedError exception.
Definition: error.c:1418
VALUE rb_eScriptError
ScriptError exception.
Definition: error.c:1424
void rb_exc_raise(VALUE mesg)
Raises an exception in the current thread.
Definition: eval.c:676
int rb_typeddata_is_kind_of(VALUE obj, const rb_data_type_t *data_type)
Checks if the given object is of given kind.
Definition: error.c:1358
void rb_syserr_fail(int e, const char *mesg)
Raises appropriate exception that represents a C errno.
Definition: error.c:3747
VALUE rb_eKeyError
KeyError exception.
Definition: error.c:1411
void rb_bug(const char *fmt,...)
Interpreter panic switch.
Definition: error.c:1089
VALUE rb_cNameErrorMesg
NameError::Message class.
Definition: error.c:1420
VALUE rb_eSystemExit
SystemExit exception.
Definition: error.c:1401
void rb_sys_fail(const char *mesg)
Converts a C errno into a Ruby exception, then raises it.
Definition: error.c:3760
void rb_name_error(ID id, const char *fmt,...)
Raises an instance of rb_eNameError.
Definition: error.c:2215
void rb_sys_warning(const char *fmt,...)
Identical to rb_sys_fail(), except it does not raise an exception to render a warning instead.
Definition: error.c:3898
void rb_check_copyable(VALUE obj, VALUE orig)
Ensures that the passed object can be initialize_copy relationship.
Definition: error.c:4067
VALUE rb_eStandardError
StandardError exception.
Definition: error.c:1405
VALUE rb_mErrno
Errno module.
Definition: error.c:1429
VALUE rb_syserr_new_str(int n, VALUE arg)
Identical to rb_syserr_new(), except it takes the message in Ruby's String instead of C's.
Definition: error.c:3741
void rb_mod_syserr_fail_str(VALUE mod, int e, VALUE mesg)
Identical to rb_mod_syserr_fail(), except it takes the message in Ruby's String instead of C's.
Definition: error.c:3837
void rb_error_frozen(const char *what)
Identical to rb_frozen_error_raise(), except its raising exception has a message like "can't modify f...
Definition: error.c:3953
void rb_set_errinfo(VALUE err)
Sets the current exception ($!) to the given value.
Definition: eval.c:1926
VALUE rb_eFrozenError
FrozenError exception.
Definition: error.c:1407
VALUE rb_eNoMemError
NoMemoryError exception.
Definition: error.c:1419
VALUE rb_eRangeError
RangeError exception.
Definition: error.c:1412
VALUE rb_eLoadError
LoadError exception.
Definition: error.c:1426
void rb_syserr_fail_str(int e, VALUE mesg)
Identical to rb_syserr_fail(), except it takes the message in Ruby's String instead of C's.
Definition: error.c:3753
#define ruby_verbose
This variable controls whether the interpreter is in debug mode.
Definition: error.h:475
VALUE rb_eTypeError
TypeError exception.
Definition: error.c:1408
VALUE rb_eNoMatchingPatternError
NoMatchingPatternError exception.
Definition: error.c:1421
void rb_name_error_str(VALUE str, const char *fmt,...)
Identical to rb_name_error(), except it takes a VALUE instead of ID.
Definition: error.c:2230
void rb_fatal(const char *fmt,...)
Raises the unsung "fatal" exception.
Definition: error.c:3686
void rb_frozen_error_raise(VALUE frozen_obj, const char *fmt,...)
Raises an instance of rb_eFrozenError.
Definition: error.c:3959
VALUE rb_eEncCompatError
Encoding::CompatibilityError exception.
Definition: error.c:1415
void rb_category_compile_warn(rb_warning_category_t category, const char *file, int line, const char *fmt,...)
Identical to rb_compile_warn(), except it also accepts category.
Definition: error.c:439
VALUE rb_eFatal
fatal exception.
Definition: error.c:1404
void rb_invalid_str(const char *str, const char *type)
Honestly I don't understand the name, but it raises an instance of rb_eArgError.
Definition: error.c:2654
VALUE rb_eInterrupt
Interrupt exception.
Definition: error.c:1402
VALUE rb_eNameError
NameError exception.
Definition: error.c:1413
VALUE rb_eNoMethodError
NoMethodError exception.
Definition: error.c:1416
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
VALUE rb_exc_new_cstr(VALUE etype, const char *s)
Identical to rb_exc_new(), except it assumes the passed pointer is a pointer to a C string.
Definition: error.c:1453
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_eNoMatchingPatternKeyError
NoMatchingPatternKeyError exception.
Definition: error.c:1422
void rb_error_frozen_object(VALUE frozen_obj)
Identical to rb_error_frozen(), except it takes arbitrary Ruby object instead of C's string.
Definition: error.c:3999
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:1459
VALUE rb_eArgError
ArgumentError exception.
Definition: error.c:1409
void rb_bug_errno(const char *mesg, int errno_arg)
This is a wrapper of rb_bug() which automatically constructs appropriate message from the passed errn...
Definition: error.c:1118
void rb_enc_raise(rb_encoding *enc, VALUE exc, const char *fmt,...)
Identical to rb_raise(), except it additionally takes an encoding.
Definition: error.c:3616
void rb_compile_warning(const char *file, int line, const char *fmt,...)
Issues a compile-time warning that happens at __file__:__line__.
Definition: error.c:418
void rb_loaderror(const char *fmt,...)
Raises an instance of rb_eLoadError.
Definition: error.c:3654
VALUE rb_eException
Mother of all exceptions.
Definition: error.c:1400
VALUE rb_eIndexError
IndexError exception.
Definition: error.c:1410
void rb_loaderror_with_path(VALUE path, const char *fmt,...)
Identical to rb_loaderror(), except it additionally takes which file is unable to load.
Definition: error.c:3666
VALUE rb_eSyntaxError
SyntaxError exception.
Definition: error.c:1425
VALUE rb_eEncodingError
EncodingError exception.
Definition: error.c:1414
VALUE rb_syserr_new(int n, const char *mesg)
Creates an exception object that represents the given C errno.
Definition: error.c:3733
VALUE rb_eSecurityError
SecurityError exception.
Definition: error.c:1417
void rb_sys_fail_str(VALUE mesg)
Identical to rb_sys_fail(), except it takes the message in Ruby's String instead of C's.
Definition: error.c:3767
void rb_unexpected_type(VALUE x, int t)
Fails with the given object's type incompatibility to the type.
Definition: error.c:1338
void rb_mod_sys_fail_str(VALUE mod, VALUE mesg)
Identical to rb_mod_sys_fail(), except it takes the message in Ruby's String instead of C's.
Definition: error.c:3823
void rb_check_type(VALUE x, int t)
This was the old implementation of Check_Type(), but they diverged.
Definition: error.c:1315
VALUE rb_eSystemCallError
SystemCallError exception.
Definition: error.c:1428
void rb_warning(const char *fmt,...)
Issues a warning.
Definition: error.c:497
VALUE rb_eSignal
SignalException exception.
Definition: error.c:1403
@ RB_WARN_CATEGORY_STRICT_UNUSED_BLOCK
Warning is for checking unused block strictly.
Definition: error.h:57
@ RB_WARN_CATEGORY_DEPRECATED
Warning is for deprecated features.
Definition: error.h:48
@ RB_WARN_CATEGORY_EXPERIMENTAL
Warning is for experimental features.
Definition: error.h:51
@ RB_WARN_CATEGORY_PERFORMANCE
Warning is for performance issues (not enabled by -w).
Definition: error.h:54
@ RB_WARN_CATEGORY_NONE
Category unspecified.
Definition: error.h:45
VALUE rb_check_to_int(VALUE val)
Identical to rb_check_to_integer(), except it uses #to_int for conversion.
Definition: object.c:3194
VALUE rb_any_to_s(VALUE obj)
Generates a textual representation of the given object.
Definition: object.c:669
VALUE rb_obj_alloc(VALUE klass)
Allocates an instance of the given class.
Definition: object.c:2093
VALUE rb_class_new_instance(int argc, const VALUE *argv, VALUE klass)
Allocates, then initialises an instance of the given class.
Definition: object.c:2134
VALUE rb_obj_init_copy(VALUE src, VALUE dst)
Default implementation of #initialize_copy, #initialize_dup and #initialize_clone.
Definition: object.c:616
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
Definition: object.c:247
VALUE rb_cEncoding
Encoding class.
Definition: encoding.c:57
VALUE rb_inspect(VALUE obj)
Generates a human-readable textual representation of the given object.
Definition: object.c:680
VALUE rb_class_real(VALUE klass)
Finds a "real" class.
Definition: object.c:237
VALUE rb_equal(VALUE lhs, VALUE rhs)
This function is an optimised version of calling #==.
Definition: object.c:179
VALUE rb_obj_clone(VALUE obj)
Produces a shallow copy of the given object.
Definition: object.c:521
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
VALUE rb_String(VALUE val)
This is the logic behind Kernel#String.
Definition: object.c:3718
VALUE rb_cString
String class.
Definition: string.c:78
#define RB_OBJ_WRITE(old, slot, young)
Declaration of a "back" pointer.
Definition: gc.h:603
Encoding relates APIs.
rb_encoding * rb_locale_encoding(void)
Queries the encoding that represents the current locale.
Definition: encoding.c:1523
rb_encoding * rb_usascii_encoding(void)
Queries the encoding that represents US-ASCII.
Definition: encoding.c:1487
static char * rb_enc_prev_char(const char *s, const char *p, const char *e, rb_encoding *enc)
Queries the previous (left) character.
Definition: encoding.h:662
int rb_enc_mbclen(const char *p, const char *e, rb_encoding *enc)
Queries the number of bytes of the character at the passed pointer.
Definition: encoding.c:1179
rb_encoding * rb_enc_get(VALUE obj)
Identical to rb_enc_get_index(), except the return type.
Definition: encoding.c:1028
static const char * rb_enc_name(rb_encoding *enc)
Queries the (canonical) name of the passed encoding.
Definition: encoding.h:417
VALUE rb_enc_str_new_cstr(const char *ptr, rb_encoding *enc)
Identical to rb_enc_str_new(), except it assumes the passed pointer is a pointer to a C string.
Definition: string.c:1098
VALUE rb_enc_str_new(const char *ptr, long len, rb_encoding *enc)
Identical to rb_str_new(), except it additionally takes an encoding.
Definition: string.c:1068
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_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:1058
VALUE rb_call_super_kw(int argc, const VALUE *argv, int kw_splat)
Identical to rb_call_super(), except you can specify how to handle the last element of the given arra...
Definition: vm_eval.c:354
VALUE rb_call_super(int argc, const VALUE *argv)
This resembles ruby's super.
Definition: vm_eval.c:362
void rb_gc_mark_movable(VALUE obj)
Maybe this is the only function provided for C extensions to control the pinning of objects,...
Definition: gc.c:2091
VALUE rb_gc_location(VALUE obj)
Finds a new "location" of an object.
Definition: gc.c:3038
Defines RBIMPL_HAS_BUILTIN.
VALUE rb_ary_new(void)
Allocates a new, empty array.
Definition: array.c:747
VALUE rb_ary_new_capa(long capa)
Identical to rb_ary_new(), except it additionally specifies how many rooms of objects it should alloc...
Definition: array.c:741
VALUE rb_ary_push(VALUE ary, VALUE elem)
Special case of rb_ary_cat() that it adds only one element.
Definition: array.c:1384
VALUE rb_ary_freeze(VALUE obj)
Freeze an array, preventing further modifications.
Definition: array.c:648
VALUE rb_ary_entry(VALUE ary, long off)
Queries an element of an array.
Definition: array.c:1737
static void rb_check_frozen_inline(VALUE obj)
Just another name of rb_check_frozen.
Definition: error.h:253
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_this_func(void)
Queries the name of the Ruby level method that is calling this function.
Definition: eval.c:1094
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_new(void)
Creates a new, empty hash object.
Definition: hash.c:1475
VALUE rb_io_puts(int argc, const VALUE *argv, VALUE io)
Iterates over the passed array to apply rb_io_write() individually.
Definition: io.c:8924
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
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:3677
VALUE rb_str_tmp_new(long len)
Allocates a "temporary" string.
Definition: string.c:1671
VALUE rb_str_buf_cat(VALUE, const char *, long)
Just another name of rb_str_cat.
VALUE rb_str_cat2(VALUE, const char *)
Just another name of rb_str_cat_cstr.
VALUE rb_str_dup(VALUE str)
Duplicates a string.
Definition: string.c:1927
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:3643
VALUE rb_str_equal(VALUE str1, VALUE str2)
Equality of two strings.
Definition: string.c:4148
void rb_str_set_len(VALUE str, long len)
Overwrites the length of the string.
Definition: string.c:3269
void rb_must_asciicompat(VALUE obj)
Asserts that the given string's encoding is (Ruby's definition of) ASCII compatible.
Definition: string.c:2703
VALUE rb_str_buf_new_cstr(const char *ptr)
This is a rb_str_buf_new() + rb_str_buf_cat() combo.
Definition: string.c:1659
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_str_new_cstr(const char *ptr)
Identical to rb_str_new(), except it assumes the passed pointer is a pointer to a C string.
Definition: string.c:1074
VALUE rb_str_cat_cstr(VALUE dst, const char *src)
Identical to rb_str_cat(), except it assumes the passed pointer is a pointer to a C string.
Definition: string.c:3455
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_exec_recursive(VALUE(*f)(VALUE g, VALUE h, int r), VALUE g, VALUE h)
"Recursion" API entry point.
VALUE rb_const_get(VALUE space, ID name)
Identical to rb_const_defined(), except it returns the actual defined value.
Definition: variable.c:3151
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
void rb_ivar_foreach(VALUE obj, int(*func)(ID name, VALUE val, st_data_t arg), st_data_t arg)
Iterates over an object's instance variables.
VALUE rb_class_name(VALUE obj)
Queries the name of the given object's class.
Definition: variable.c:412
int rb_respond_to(VALUE obj, ID mid)
Queries if the object responds to the method.
Definition: vm_method.c:2955
int rb_method_basic_definition_p(VALUE klass, ID mid)
Well...
Definition: vm_method.c:2833
void rb_attr(VALUE klass, ID name, int need_reader, int need_writer, int honour_visibility)
This function resembles now-deprecated Module#attr.
Definition: vm_method.c:1864
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
VALUE rb_check_funcall_kw(VALUE recv, ID mid, int argc, const VALUE *argv, int kw_splat)
Identical to rb_check_funcall(), except you can specify how to handle the last element of the given a...
Definition: vm_eval.c:662
void rb_define_alloc_func(VALUE klass, rb_alloc_func_t func)
Sets the allocator function of a class.
static ID rb_intern_const(const char *str)
This is a "tiny optimisation" over rb_intern().
Definition: symbol.h:276
ID rb_check_id(volatile VALUE *namep)
Detects if the given name is already interned or not.
Definition: symbol.c:1117
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_const(VALUE klass, const char *name, VALUE val)
Defines a Ruby level constant under a namespace.
Definition: variable.c:3714
char * ptr
Pointer to the underlying memory region, of at least capa bytes.
Definition: io.h:2
int len
Length of the buffer.
Definition: io.h:8
#define DECIMAL_SIZE_OF(expr)
An approximation of decimal representation size.
Definition: util.h:48
unsigned long ruby_scan_oct(const char *str, size_t len, size_t *consumed)
Interprets the passed string as an octal unsigned integer.
Definition: util.c:43
VALUE rb_str_format(int argc, const VALUE *argv, VALUE fmt)
Formats a string.
Definition: sprintf.c:215
VALUE rb_sprintf(const char *fmt,...)
Ruby's extended sprintf(3).
Definition: sprintf.c:1217
VALUE rb_str_vcatf(VALUE dst, const char *fmt, va_list ap)
Identical to rb_str_catf(), except it takes a va_list.
Definition: sprintf.c:1230
VALUE rb_vsprintf(const char *fmt, va_list ap)
Identical to rb_sprintf(), except it takes a va_list.
Definition: sprintf.c:1211
VALUE rb_str_catf(VALUE dst, const char *fmt,...)
Identical to rb_sprintf(), except it renders the output to the specified object rather than creating ...
Definition: sprintf.c:1240
void rb_marshal_define_compat(VALUE newclass, VALUE oldclass, VALUE(*dumper)(VALUE), VALUE(*loader)(VALUE, VALUE))
Marshal format compatibility layer.
Definition: marshal.c:134
#define ALLOCA_N(type, n)
Definition: memory.h:287
VALUE type(ANYARGS)
ANYARGS-ed function type.
Definition: cxxanyargs.hpp:56
#define PRI_PIDT_PREFIX
A rb_sprintf() format prefix to be used for a pid_t parameter.
Definition: pid_t.h:38
#define RARRAY_LEN
Just another name of rb_array_len.
Definition: rarray.h:51
static int RARRAY_LENINT(VALUE ary)
Identical to rb_array_len(), except it differs for the return type.
Definition: rarray.h:281
#define RARRAY_AREF(a, i)
Definition: rarray.h:403
#define RARRAY_CONST_PTR
Just another name of rb_array_const_ptr.
Definition: rarray.h:52
#define StringValue(v)
Ensures that the parameter object is a String.
Definition: rstring.h:66
static char * RSTRING_END(VALUE str)
Queries the end of the contents pointer of the string.
Definition: rstring.h:442
static char * RSTRING_PTR(VALUE str)
Queries the contents pointer of the string.
Definition: rstring.h:416
char * rb_string_value_ptr(volatile VALUE *ptr)
Identical to rb_str_to_str(), except it returns the converted string's backend memory region.
Definition: string.c:2726
static long RSTRING_LEN(VALUE str)
Queries the length of the string.
Definition: rstring.h:367
#define RSTRING(obj)
Convenient casting macro.
Definition: rstring.h:41
static bool RTYPEDDATA_P(VALUE obj)
Checks whether the passed object is RTypedData or RData.
Definition: rtypeddata.h:579
#define RUBY_TYPED_DEFAULT_FREE
This is a value you can set to rb_data_type_struct::dfree.
Definition: rtypeddata.h:79
#define TypedData_Get_Struct(obj, type, data_type, sval)
Obtains a C struct from inside of a wrapper Ruby object.
Definition: rtypeddata.h:515
static const struct rb_data_type_struct * RTYPEDDATA_TYPE(VALUE obj)
Queries for the type of given object.
Definition: rtypeddata.h:602
#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:497
VALUE rb_argv0
The value of $0 at process bootup.
Definition: ruby.c:1848
const char * rb_obj_classname(VALUE obj)
Queries the name of the class of the passed object.
Definition: variable.c:427
#define errno
Ractor-aware version of errno.
Definition: ruby.h:388
#define RB_PASS_KEYWORDS
Pass keywords, final argument should be a hash of keywords.
Definition: scan_args.h:72
#define RB_PASS_CALLED_KEYWORDS
Pass keywords if current method is called with keywords, useful for argument delegation.
Definition: scan_args.h:78
static bool RB_SPECIAL_CONST_P(VALUE obj)
Checks if the given object is of enum ruby_special_consts.
#define RTEST
This is an old name of RB_TEST.
Defines old _.
Ruby's String.
Definition: rstring.h:196
This is the struct that holds necessary info for a struct.
Definition: rtypeddata.h:200
const rb_data_type_t * parent
Parent of this class.
Definition: rtypeddata.h:290
const char * wrap_struct_name
Name of structs of this kind.
Definition: rtypeddata.h:207
Definition: method.h:54
Definition: st.h:79
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 enum ruby_value_type RB_BUILTIN_TYPE(VALUE obj)
Queries the type of the object.
Definition: value_type.h:182
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