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