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