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