[ruby/win32ole] Undefine allocator of WIN32OLE_VARIABLE to get rid of warning
[ruby-80x24.org.git] / error.c
blob6a60919d5c7ee7e94f7bd7bf2585bde1372d45ff
1 /**********************************************************************
3 error.c -
5 $Author$
6 created at: Mon Aug 9 16:11:34 JST 1993
8 Copyright (C) 1993-2007 Yukihiro Matsumoto
10 **********************************************************************/
12 #include "ruby/internal/config.h"
14 #include <errno.h>
15 #include <stdarg.h>
16 #include <stdio.h>
18 #ifdef HAVE_STDLIB_H
19 # include <stdlib.h>
20 #endif
22 #ifdef HAVE_UNISTD_H
23 # include <unistd.h>
24 #endif
26 #if defined __APPLE__
27 # include <AvailabilityMacros.h>
28 #endif
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/symbol.h"
38 #include "internal/thread.h"
39 #include "internal/variable.h"
40 #include "ruby/encoding.h"
41 #include "ruby/st.h"
42 #include "ruby_assert.h"
43 #include "vm_core.h"
45 #include "builtin.h"
47 /*!
48 * \addtogroup exception
49 * \{
52 #ifndef EXIT_SUCCESS
53 #define EXIT_SUCCESS 0
54 #endif
56 #ifndef WIFEXITED
57 #define WIFEXITED(status) 1
58 #endif
60 #ifndef WEXITSTATUS
61 #define WEXITSTATUS(status) (status)
62 #endif
64 VALUE rb_iseqw_local_variables(VALUE iseqval);
65 VALUE rb_iseqw_new(const rb_iseq_t *);
66 int rb_str_end_with_asciichar(VALUE str, int c);
68 long rb_backtrace_length_limit = -1;
69 VALUE rb_eEAGAIN;
70 VALUE rb_eEWOULDBLOCK;
71 VALUE rb_eEINPROGRESS;
72 static VALUE rb_mWarning;
73 static VALUE rb_cWarningBuffer;
75 static ID id_warn;
76 static ID id_category;
77 static ID id_deprecated;
78 static ID id_experimental;
79 static VALUE sym_category;
80 static struct {
81 st_table *id2enum, *enum2id;
82 } warning_categories;
84 extern const char ruby_description[];
86 static const char *
87 rb_strerrno(int err)
89 #define defined_error(name, num) if (err == (num)) return (name);
90 #define undefined_error(name)
91 #include "known_errors.inc"
92 #undef defined_error
93 #undef undefined_error
94 return NULL;
97 static int
98 err_position_0(char *buf, long len, const char *file, int line)
100 if (!file) {
101 return 0;
103 else if (line == 0) {
104 return snprintf(buf, len, "%s: ", file);
106 else {
107 return snprintf(buf, len, "%s:%d: ", file, line);
111 RBIMPL_ATTR_FORMAT(RBIMPL_PRINTF_FORMAT, 5, 0)
112 static VALUE
113 err_vcatf(VALUE str, const char *pre, const char *file, int line,
114 const char *fmt, va_list args)
116 if (file) {
117 rb_str_cat2(str, file);
118 if (line) rb_str_catf(str, ":%d", line);
119 rb_str_cat2(str, ": ");
121 if (pre) rb_str_cat2(str, pre);
122 rb_str_vcatf(str, fmt, args);
123 return str;
126 VALUE
127 rb_syntax_error_append(VALUE exc, VALUE file, int line, int column,
128 rb_encoding *enc, const char *fmt, va_list args)
130 const char *fn = NIL_P(file) ? NULL : RSTRING_PTR(file);
131 if (!exc) {
132 VALUE mesg = rb_enc_str_new(0, 0, enc);
133 err_vcatf(mesg, NULL, fn, line, fmt, args);
134 rb_str_cat2(mesg, "\n");
135 rb_write_error_str(mesg);
137 else {
138 VALUE mesg;
139 if (NIL_P(exc)) {
140 mesg = rb_enc_str_new(0, 0, enc);
141 exc = rb_class_new_instance(1, &mesg, rb_eSyntaxError);
143 else {
144 mesg = rb_attr_get(exc, idMesg);
145 if (RSTRING_LEN(mesg) > 0 && *(RSTRING_END(mesg)-1) != '\n')
146 rb_str_cat_cstr(mesg, "\n");
148 err_vcatf(mesg, NULL, fn, line, fmt, args);
151 return exc;
154 static unsigned int warning_disabled_categories = (
155 1U << RB_WARN_CATEGORY_DEPRECATED |
158 static unsigned int
159 rb_warning_category_mask(VALUE category)
161 return 1U << rb_warning_category_from_name(category);
164 rb_warning_category_t
165 rb_warning_category_from_name(VALUE category)
167 st_data_t cat_value;
168 ID cat_id;
169 Check_Type(category, T_SYMBOL);
170 if (!(cat_id = rb_check_id(&category)) ||
171 !st_lookup(warning_categories.id2enum, cat_id, &cat_value)) {
172 rb_raise(rb_eArgError, "unknown category: %"PRIsVALUE, category);
174 return (rb_warning_category_t)cat_value;
177 static VALUE
178 rb_warning_category_to_name(rb_warning_category_t category)
180 st_data_t id;
181 if (!st_lookup(warning_categories.enum2id, category, &id)) {
182 rb_raise(rb_eArgError, "invalid category: %d", (int)category);
184 return id ? ID2SYM(id) : Qnil;
187 void
188 rb_warning_category_update(unsigned int mask, unsigned int bits)
190 warning_disabled_categories &= ~mask;
191 warning_disabled_categories |= mask & ~bits;
194 MJIT_FUNC_EXPORTED bool
195 rb_warning_category_enabled_p(rb_warning_category_t category)
197 return !(warning_disabled_categories & (1U << category));
201 * call-seq:
202 * Warning[category] -> true or false
204 * Returns the flag to show the warning messages for +category+.
205 * Supported categories are:
207 * +:deprecated+ :: deprecation warnings
208 * * assignment of non-nil value to <code>$,</code> and <code>$;</code>
209 * * keyword arguments
210 * * proc/lambda without block
211 * etc.
213 * +:experimental+ :: experimental features
214 * * Pattern matching
217 static VALUE
218 rb_warning_s_aref(VALUE mod, VALUE category)
220 rb_warning_category_t cat = rb_warning_category_from_name(category);
221 return RBOOL(rb_warning_category_enabled_p(cat));
225 * call-seq:
226 * Warning[category] = flag -> flag
228 * Sets the warning flags for +category+.
229 * See Warning.[] for the categories.
232 static VALUE
233 rb_warning_s_aset(VALUE mod, VALUE category, VALUE flag)
235 unsigned int mask = rb_warning_category_mask(category);
236 unsigned int disabled = warning_disabled_categories;
237 if (!RTEST(flag))
238 disabled |= mask;
239 else
240 disabled &= ~mask;
241 warning_disabled_categories = disabled;
242 return flag;
246 * call-seq:
247 * warn(msg, category: nil) -> nil
249 * Writes warning message +msg+ to $stderr. This method is called by
250 * Ruby for all emitted warnings. A +category+ may be included with
251 * the warning.
253 * See the documentation of the Warning module for how to customize this.
256 static VALUE
257 rb_warning_s_warn(int argc, VALUE *argv, VALUE mod)
259 VALUE str;
260 VALUE opt;
261 VALUE category = Qnil;
263 rb_scan_args(argc, argv, "1:", &str, &opt);
264 if (!NIL_P(opt)) rb_get_kwargs(opt, &id_category, 0, 1, &category);
266 Check_Type(str, T_STRING);
267 rb_must_asciicompat(str);
268 if (!NIL_P(category)) {
269 rb_warning_category_t cat = rb_warning_category_from_name(category);
270 if (!rb_warning_category_enabled_p(cat)) return Qnil;
272 rb_write_error_str(str);
273 return Qnil;
277 * Document-module: Warning
279 * The Warning module contains a single method named #warn, and the
280 * module extends itself, making Warning.warn available.
281 * Warning.warn is called for all warnings issued by Ruby.
282 * By default, warnings are printed to $stderr.
284 * Changing the behavior of Warning.warn is useful to customize how warnings are
285 * handled by Ruby, for instance by filtering some warnings, and/or outputting
286 * warnings somewhere other than $stderr.
288 * If you want to change the behavior of Warning.warn you should use
289 * +Warning.extend(MyNewModuleWithWarnMethod)+ and you can use `super`
290 * to get the default behavior of printing the warning to $stderr.
292 * Example:
293 * module MyWarningFilter
294 * def warn(message, category: nil, **kwargs)
295 * if /some warning I want to ignore/.match?(message)
296 * # ignore
297 * else
298 * super
299 * end
300 * end
301 * end
302 * Warning.extend MyWarningFilter
304 * You should never redefine Warning#warn (the instance method), as that will
305 * then no longer provide a way to use the default behavior.
307 * The +warning+ gem provides convenient ways to customize Warning.warn.
310 static VALUE
311 rb_warning_warn(VALUE mod, VALUE str)
313 return rb_funcallv(mod, id_warn, 1, &str);
317 static int
318 rb_warning_warn_arity(void)
320 return rb_method_entry_arity(rb_method_entry(rb_singleton_class(rb_mWarning), id_warn));
323 static VALUE
324 rb_warn_category(VALUE str, VALUE category)
326 if (RUBY_DEBUG && !NIL_P(category)) {
327 rb_warning_category_from_name(category);
330 if (rb_warning_warn_arity() == 1) {
331 return rb_warning_warn(rb_mWarning, str);
333 else {
334 VALUE args[2];
335 args[0] = str;
336 args[1] = rb_hash_new();
337 rb_hash_aset(args[1], sym_category, category);
338 return rb_funcallv_kw(rb_mWarning, id_warn, 2, args, RB_PASS_KEYWORDS);
342 static void
343 rb_write_warning_str(VALUE str)
345 rb_warning_warn(rb_mWarning, str);
348 RBIMPL_ATTR_FORMAT(RBIMPL_PRINTF_FORMAT, 4, 0)
349 static VALUE
350 warn_vsprintf(rb_encoding *enc, const char *file, int line, const char *fmt, va_list args)
352 VALUE str = rb_enc_str_new(0, 0, enc);
354 err_vcatf(str, "warning: ", file, line, fmt, args);
355 return rb_str_cat2(str, "\n");
358 void
359 rb_compile_warn(const char *file, int line, const char *fmt, ...)
361 VALUE str;
362 va_list args;
364 if (NIL_P(ruby_verbose)) return;
366 va_start(args, fmt);
367 str = warn_vsprintf(NULL, file, line, fmt, args);
368 va_end(args);
369 rb_write_warning_str(str);
372 /* rb_compile_warning() reports only in verbose mode */
373 void
374 rb_compile_warning(const char *file, int line, const char *fmt, ...)
376 VALUE str;
377 va_list args;
379 if (!RTEST(ruby_verbose)) return;
381 va_start(args, fmt);
382 str = warn_vsprintf(NULL, file, line, fmt, args);
383 va_end(args);
384 rb_write_warning_str(str);
387 void
388 rb_category_compile_warn(rb_warning_category_t category, const char *file, int line, const char *fmt, ...)
390 VALUE str;
391 va_list args;
393 if (NIL_P(ruby_verbose)) return;
395 va_start(args, fmt);
396 str = warn_vsprintf(NULL, file, line, fmt, args);
397 va_end(args);
398 rb_warn_category(str, rb_warning_category_to_name(category));
401 RBIMPL_ATTR_FORMAT(RBIMPL_PRINTF_FORMAT, 2, 0)
402 static VALUE
403 warning_string(rb_encoding *enc, const char *fmt, va_list args)
405 int line;
406 const char *file = rb_source_location_cstr(&line);
407 return warn_vsprintf(enc, file, line, fmt, args);
410 #define with_warning_string(mesg, enc, fmt) \
411 VALUE mesg; \
412 va_list args; va_start(args, fmt); \
413 mesg = warning_string(enc, fmt, args); \
414 va_end(args);
416 void
417 rb_warn(const char *fmt, ...)
419 if (!NIL_P(ruby_verbose)) {
420 with_warning_string(mesg, 0, fmt) {
421 rb_write_warning_str(mesg);
426 void
427 rb_category_warn(rb_warning_category_t category, const char *fmt, ...)
429 if (!NIL_P(ruby_verbose)) {
430 with_warning_string(mesg, 0, fmt) {
431 rb_warn_category(mesg, rb_warning_category_to_name(category));
436 void
437 rb_enc_warn(rb_encoding *enc, const char *fmt, ...)
439 if (!NIL_P(ruby_verbose)) {
440 with_warning_string(mesg, enc, fmt) {
441 rb_write_warning_str(mesg);
446 /* rb_warning() reports only in verbose mode */
447 void
448 rb_warning(const char *fmt, ...)
450 if (RTEST(ruby_verbose)) {
451 with_warning_string(mesg, 0, fmt) {
452 rb_write_warning_str(mesg);
457 /* rb_category_warning() reports only in verbose mode */
458 void
459 rb_category_warning(rb_warning_category_t category, const char *fmt, ...)
461 if (RTEST(ruby_verbose)) {
462 with_warning_string(mesg, 0, fmt) {
463 rb_warn_category(mesg, rb_warning_category_to_name(category));
468 VALUE
469 rb_warning_string(const char *fmt, ...)
471 with_warning_string(mesg, 0, fmt) {
473 return mesg;
476 #if 0
477 void
478 rb_enc_warning(rb_encoding *enc, const char *fmt, ...)
480 if (RTEST(ruby_verbose)) {
481 with_warning_string(mesg, enc, fmt) {
482 rb_write_warning_str(mesg);
486 #endif
488 static bool
489 deprecation_warning_enabled(void)
491 if (NIL_P(ruby_verbose)) return false;
492 if (!rb_warning_category_enabled_p(RB_WARN_CATEGORY_DEPRECATED)) return false;
493 return true;
496 static void
497 warn_deprecated(VALUE mesg, const char *removal, const char *suggest)
499 rb_str_set_len(mesg, RSTRING_LEN(mesg) - 1);
500 rb_str_cat_cstr(mesg, " is deprecated");
501 if (removal) {
502 rb_str_catf(mesg, " and will be removed in Ruby %s", removal);
504 if (suggest) rb_str_catf(mesg, "; use %s instead", suggest);
505 rb_str_cat_cstr(mesg, "\n");
506 rb_warn_category(mesg, ID2SYM(id_deprecated));
509 void
510 rb_warn_deprecated(const char *fmt, const char *suggest, ...)
512 if (!deprecation_warning_enabled()) return;
514 va_list args;
515 va_start(args, suggest);
516 VALUE mesg = warning_string(0, fmt, args);
517 va_end(args);
519 warn_deprecated(mesg, NULL, suggest);
522 void
523 rb_warn_deprecated_to_remove(const char *removal, const char *fmt, const char *suggest, ...)
525 if (!deprecation_warning_enabled()) return;
527 va_list args;
528 va_start(args, suggest);
529 VALUE mesg = warning_string(0, fmt, args);
530 va_end(args);
532 warn_deprecated(mesg, removal, suggest);
535 static inline int
536 end_with_asciichar(VALUE str, int c)
538 return RB_TYPE_P(str, T_STRING) &&
539 rb_str_end_with_asciichar(str, c);
542 /* :nodoc: */
543 static VALUE
544 warning_write(int argc, VALUE *argv, VALUE buf)
546 while (argc-- > 0) {
547 rb_str_append(buf, *argv++);
549 return buf;
552 VALUE rb_ec_backtrace_location_ary(const rb_execution_context_t *ec, long lev, long n, bool skip_internal);
554 static VALUE
555 rb_warn_m(rb_execution_context_t *ec, VALUE exc, VALUE msgs, VALUE uplevel, VALUE category)
557 VALUE location = Qnil;
558 int argc = RARRAY_LENINT(msgs);
559 const VALUE *argv = RARRAY_CONST_PTR(msgs);
561 if (!NIL_P(ruby_verbose) && argc > 0) {
562 VALUE str = argv[0];
563 if (!NIL_P(uplevel)) {
564 long lev = NUM2LONG(uplevel);
565 if (lev < 0) {
566 rb_raise(rb_eArgError, "negative level (%ld)", lev);
568 location = rb_ec_backtrace_location_ary(ec, lev + 1, 1, TRUE);
569 if (!NIL_P(location)) {
570 location = rb_ary_entry(location, 0);
573 if (argc > 1 || !NIL_P(uplevel) || !end_with_asciichar(str, '\n')) {
574 VALUE path;
575 if (NIL_P(uplevel)) {
576 str = rb_str_tmp_new(0);
578 else if (NIL_P(location) ||
579 NIL_P(path = rb_funcall(location, rb_intern("path"), 0))) {
580 str = rb_str_new_cstr("warning: ");
582 else {
583 str = rb_sprintf("%s:%ld: warning: ",
584 rb_string_value_ptr(&path),
585 NUM2LONG(rb_funcall(location, rb_intern("lineno"), 0)));
587 RBASIC_SET_CLASS(str, rb_cWarningBuffer);
588 rb_io_puts(argc, argv, str);
589 RBASIC_SET_CLASS(str, rb_cString);
592 if (!NIL_P(category)) {
593 category = rb_to_symbol_type(category);
594 rb_warning_category_from_name(category);
597 if (exc == rb_mWarning) {
598 rb_must_asciicompat(str);
599 rb_write_error_str(str);
601 else {
602 rb_warn_category(str, category);
605 return Qnil;
608 #define MAX_BUG_REPORTERS 0x100
610 static struct bug_reporters {
611 void (*func)(FILE *out, void *data);
612 void *data;
613 } bug_reporters[MAX_BUG_REPORTERS];
615 static int bug_reporters_size;
618 rb_bug_reporter_add(void (*func)(FILE *, void *), void *data)
620 struct bug_reporters *reporter;
621 if (bug_reporters_size >= MAX_BUG_REPORTERS) {
622 return 0; /* failed to register */
624 reporter = &bug_reporters[bug_reporters_size++];
625 reporter->func = func;
626 reporter->data = data;
628 return 1;
631 /* SIGSEGV handler might have a very small stack. Thus we need to use it carefully. */
632 #define REPORT_BUG_BUFSIZ 256
633 static FILE *
634 bug_report_file(const char *file, int line)
636 char buf[REPORT_BUG_BUFSIZ];
637 FILE *out = stderr;
638 int len = err_position_0(buf, sizeof(buf), file, line);
640 if ((ssize_t)fwrite(buf, 1, len, out) == (ssize_t)len ||
641 (ssize_t)fwrite(buf, 1, len, (out = stdout)) == (ssize_t)len) {
642 return out;
645 return NULL;
648 FUNC_MINIMIZED(static void bug_important_message(FILE *out, const char *const msg, size_t len));
650 static void
651 bug_important_message(FILE *out, const char *const msg, size_t len)
653 const char *const endmsg = msg + len;
654 const char *p = msg;
656 if (!len) return;
657 if (isatty(fileno(out))) {
658 static const char red[] = "\033[;31;1;7m";
659 static const char green[] = "\033[;32;7m";
660 static const char reset[] = "\033[m";
661 const char *e = strchr(p, '\n');
662 const int w = (int)(e - p);
663 do {
664 int i = (int)(e - p);
665 fputs(*p == ' ' ? green : red, out);
666 fwrite(p, 1, e - p, out);
667 for (; i < w; ++i) fputc(' ', out);
668 fputs(reset, out);
669 fputc('\n', out);
670 } while ((p = e + 1) < endmsg && (e = strchr(p, '\n')) != 0 && e > p + 1);
672 fwrite(p, 1, endmsg - p, out);
675 static void
676 preface_dump(FILE *out)
678 #if defined __APPLE__
679 static const char msg[] = ""
680 "-- Crash Report log information "
681 "--------------------------------------------\n"
682 " See Crash Report log file in one of the following locations:\n"
683 # if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_6
684 " * ~/Library/Logs/CrashReporter\n"
685 " * /Library/Logs/CrashReporter\n"
686 # endif
687 " * ~/Library/Logs/DiagnosticReports\n"
688 " * /Library/Logs/DiagnosticReports\n"
689 " for more details.\n"
690 "Don't forget to include the above Crash Report log file in bug reports.\n"
691 "\n";
692 const size_t msglen = sizeof(msg) - 1;
693 #else
694 const char *msg = NULL;
695 const size_t msglen = 0;
696 #endif
697 bug_important_message(out, msg, msglen);
700 static void
701 postscript_dump(FILE *out)
703 #if defined __APPLE__
704 static const char msg[] = ""
705 "[IMPORTANT]"
706 /*" ------------------------------------------------"*/
707 "\n""Don't forget to include the Crash Report log file under\n"
708 # if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_6
709 "CrashReporter or "
710 # endif
711 "DiagnosticReports directory in bug reports.\n"
712 /*"------------------------------------------------------------\n"*/
713 "\n";
714 const size_t msglen = sizeof(msg) - 1;
715 #else
716 const char *msg = NULL;
717 const size_t msglen = 0;
718 #endif
719 bug_important_message(out, msg, msglen);
722 RBIMPL_ATTR_FORMAT(RBIMPL_PRINTF_FORMAT, 2, 0)
723 static void
724 bug_report_begin_valist(FILE *out, const char *fmt, va_list args)
726 char buf[REPORT_BUG_BUFSIZ];
728 fputs("[BUG] ", out);
729 vsnprintf(buf, sizeof(buf), fmt, args);
730 fputs(buf, out);
731 snprintf(buf, sizeof(buf), "\n%s\n\n", ruby_description);
732 fputs(buf, out);
733 preface_dump(out);
736 #define bug_report_begin(out, fmt) do { \
737 va_list args; \
738 va_start(args, fmt); \
739 bug_report_begin_valist(out, fmt, args); \
740 va_end(args); \
741 } while (0)
743 static void
744 bug_report_end(FILE *out)
746 /* call additional bug reporters */
748 int i;
749 for (i=0; i<bug_reporters_size; i++) {
750 struct bug_reporters *reporter = &bug_reporters[i];
751 (*reporter->func)(out, reporter->data);
754 postscript_dump(out);
757 #define report_bug(file, line, fmt, ctx) do { \
758 FILE *out = bug_report_file(file, line); \
759 if (out) { \
760 bug_report_begin(out, fmt); \
761 rb_vm_bugreport(ctx); \
762 bug_report_end(out); \
764 } while (0) \
766 #define report_bug_valist(file, line, fmt, ctx, args) do { \
767 FILE *out = bug_report_file(file, line); \
768 if (out) { \
769 bug_report_begin_valist(out, fmt, args); \
770 rb_vm_bugreport(ctx); \
771 bug_report_end(out); \
773 } while (0) \
775 NORETURN(static void die(void));
776 static void
777 die(void)
779 #if defined(_WIN32) && defined(RUBY_MSVCRT_VERSION) && RUBY_MSVCRT_VERSION >= 80
780 _set_abort_behavior( 0, _CALL_REPORTFAULT);
781 #endif
783 abort();
786 RBIMPL_ATTR_FORMAT(RBIMPL_PRINTF_FORMAT, 1, 0)
787 void
788 rb_bug_without_die(const char *fmt, va_list args)
790 const char *file = NULL;
791 int line = 0;
793 if (GET_EC()) {
794 file = rb_source_location_cstr(&line);
797 report_bug_valist(file, line, fmt, NULL, args);
800 void
801 rb_bug(const char *fmt, ...)
803 va_list args;
804 va_start(args, fmt);
805 rb_bug_without_die(fmt, args);
806 va_end(args);
807 die();
810 void
811 rb_bug_for_fatal_signal(ruby_sighandler_t default_sighandler, int sig, const void *ctx, const char *fmt, ...)
813 const char *file = NULL;
814 int line = 0;
816 if (GET_EC()) {
817 file = rb_source_location_cstr(&line);
820 report_bug(file, line, fmt, ctx);
822 if (default_sighandler) default_sighandler(sig);
824 die();
828 void
829 rb_bug_errno(const char *mesg, int errno_arg)
831 if (errno_arg == 0)
832 rb_bug("%s: errno == 0 (NOERROR)", mesg);
833 else {
834 const char *errno_str = rb_strerrno(errno_arg);
835 if (errno_str)
836 rb_bug("%s: %s (%s)", mesg, strerror(errno_arg), errno_str);
837 else
838 rb_bug("%s: %s (%d)", mesg, strerror(errno_arg), errno_arg);
843 * this is safe to call inside signal handler and timer thread
844 * (which isn't a Ruby Thread object)
846 #define write_or_abort(fd, str, len) (write((fd), (str), (len)) < 0 ? abort() : (void)0)
847 #define WRITE_CONST(fd,str) write_or_abort((fd),(str),sizeof(str) - 1)
849 void
850 rb_async_bug_errno(const char *mesg, int errno_arg)
852 WRITE_CONST(2, "[ASYNC BUG] ");
853 write_or_abort(2, mesg, strlen(mesg));
854 WRITE_CONST(2, "\n");
856 if (errno_arg == 0) {
857 WRITE_CONST(2, "errno == 0 (NOERROR)\n");
859 else {
860 const char *errno_str = rb_strerrno(errno_arg);
862 if (!errno_str)
863 errno_str = "undefined errno";
864 write_or_abort(2, errno_str, strlen(errno_str));
866 WRITE_CONST(2, "\n\n");
867 write_or_abort(2, ruby_description, strlen(ruby_description));
868 abort();
871 void
872 rb_report_bug_valist(VALUE file, int line, const char *fmt, va_list args)
874 report_bug_valist(RSTRING_PTR(file), line, fmt, NULL, args);
877 MJIT_FUNC_EXPORTED void
878 rb_assert_failure(const char *file, int line, const char *name, const char *expr)
880 FILE *out = stderr;
881 fprintf(out, "Assertion Failed: %s:%d:", file, line);
882 if (name) fprintf(out, "%s:", name);
883 fprintf(out, "%s\n%s\n\n", expr, ruby_description);
884 preface_dump(out);
885 rb_vm_bugreport(NULL);
886 bug_report_end(out);
887 die();
890 static const char builtin_types[][10] = {
891 "", /* 0x00, */
892 "Object",
893 "Class",
894 "Module",
895 "Float",
896 "String",
897 "Regexp",
898 "Array",
899 "Hash",
900 "Struct",
901 "Integer",
902 "File",
903 "Data", /* internal use: wrapped C pointers */
904 "MatchData", /* data of $~ */
905 "Complex",
906 "Rational",
907 "", /* 0x10 */
908 "nil",
909 "true",
910 "false",
911 "Symbol", /* :symbol */
912 "Integer",
913 "undef", /* internal use: #undef; should not happen */
914 "", /* 0x17 */
915 "", /* 0x18 */
916 "", /* 0x19 */
917 "<Memo>", /* internal use: general memo */
918 "<Node>", /* internal use: syntax tree node */
919 "<iClass>", /* internal use: mixed-in module holder */
922 const char *
923 rb_builtin_type_name(int t)
925 const char *name;
926 if ((unsigned int)t >= numberof(builtin_types)) return 0;
927 name = builtin_types[t];
928 if (*name) return name;
929 return 0;
932 static VALUE
933 displaying_class_of(VALUE x)
935 switch (x) {
936 case Qfalse: return rb_fstring_cstr("false");
937 case Qnil: return rb_fstring_cstr("nil");
938 case Qtrue: return rb_fstring_cstr("true");
939 default: return rb_obj_class(x);
943 static const char *
944 builtin_class_name(VALUE x)
946 const char *etype;
948 if (NIL_P(x)) {
949 etype = "nil";
951 else if (FIXNUM_P(x)) {
952 etype = "Integer";
954 else if (SYMBOL_P(x)) {
955 etype = "Symbol";
957 else if (RB_TYPE_P(x, T_TRUE)) {
958 etype = "true";
960 else if (RB_TYPE_P(x, T_FALSE)) {
961 etype = "false";
963 else {
964 etype = NULL;
966 return etype;
969 const char *
970 rb_builtin_class_name(VALUE x)
972 const char *etype = builtin_class_name(x);
974 if (!etype) {
975 etype = rb_obj_classname(x);
977 return etype;
980 COLDFUNC NORETURN(static void unexpected_type(VALUE, int, int));
981 #define UNDEF_LEAKED "undef leaked to the Ruby space"
983 static void
984 unexpected_type(VALUE x, int xt, int t)
986 const char *tname = rb_builtin_type_name(t);
987 VALUE mesg, exc = rb_eFatal;
989 if (tname) {
990 mesg = rb_sprintf("wrong argument type %"PRIsVALUE" (expected %s)",
991 displaying_class_of(x), tname);
992 exc = rb_eTypeError;
994 else if (xt > T_MASK && xt <= 0x3f) {
995 mesg = rb_sprintf("unknown type 0x%x (0x%x given, probably comes"
996 " from extension library for ruby 1.8)", t, xt);
998 else {
999 mesg = rb_sprintf("unknown type 0x%x (0x%x given)", t, xt);
1001 rb_exc_raise(rb_exc_new_str(exc, mesg));
1004 void
1005 rb_check_type(VALUE x, int t)
1007 int xt;
1009 if (RB_UNLIKELY(x == Qundef)) {
1010 rb_bug(UNDEF_LEAKED);
1013 xt = TYPE(x);
1014 if (xt != t || (xt == T_DATA && rbimpl_rtypeddata_p(x))) {
1016 * Typed data is not simple `T_DATA`, but in a sense an
1017 * extension of `struct RVALUE`, which are incompatible with
1018 * each other except when inherited.
1020 * So it is not enough to just check `T_DATA`, it must be
1021 * identified by its `type` using `Check_TypedStruct` instead.
1023 unexpected_type(x, xt, t);
1027 void
1028 rb_unexpected_type(VALUE x, int t)
1030 if (RB_UNLIKELY(x == Qundef)) {
1031 rb_bug(UNDEF_LEAKED);
1034 unexpected_type(x, TYPE(x), t);
1038 rb_typeddata_inherited_p(const rb_data_type_t *child, const rb_data_type_t *parent)
1040 while (child) {
1041 if (child == parent) return 1;
1042 child = child->parent;
1044 return 0;
1048 rb_typeddata_is_kind_of(VALUE obj, const rb_data_type_t *data_type)
1050 if (!RB_TYPE_P(obj, T_DATA) ||
1051 !RTYPEDDATA_P(obj) || !rb_typeddata_inherited_p(RTYPEDDATA_TYPE(obj), data_type)) {
1052 return 0;
1054 return 1;
1057 #undef rb_typeddata_is_instance_of
1059 rb_typeddata_is_instance_of(VALUE obj, const rb_data_type_t *data_type)
1061 return rb_typeddata_is_instance_of_inline(obj, data_type);
1064 void *
1065 rb_check_typeddata(VALUE obj, const rb_data_type_t *data_type)
1067 VALUE actual;
1069 if (!RB_TYPE_P(obj, T_DATA)) {
1070 actual = displaying_class_of(obj);
1072 else if (!RTYPEDDATA_P(obj)) {
1073 actual = displaying_class_of(obj);
1075 else if (!rb_typeddata_inherited_p(RTYPEDDATA_TYPE(obj), data_type)) {
1076 const char *name = RTYPEDDATA_TYPE(obj)->wrap_struct_name;
1077 actual = rb_str_new_cstr(name); /* or rb_fstring_cstr? not sure... */
1079 else {
1080 return DATA_PTR(obj);
1083 const char *expected = data_type->wrap_struct_name;
1084 rb_raise(rb_eTypeError, "wrong argument type %"PRIsVALUE" (expected %s)",
1085 actual, expected);
1086 UNREACHABLE_RETURN(NULL);
1089 /* exception classes */
1090 VALUE rb_eException;
1091 VALUE rb_eSystemExit;
1092 VALUE rb_eInterrupt;
1093 VALUE rb_eSignal;
1094 VALUE rb_eFatal;
1095 VALUE rb_eStandardError;
1096 VALUE rb_eRuntimeError;
1097 VALUE rb_eFrozenError;
1098 VALUE rb_eTypeError;
1099 VALUE rb_eArgError;
1100 VALUE rb_eIndexError;
1101 VALUE rb_eKeyError;
1102 VALUE rb_eRangeError;
1103 VALUE rb_eNameError;
1104 VALUE rb_eEncodingError;
1105 VALUE rb_eEncCompatError;
1106 VALUE rb_eNoMethodError;
1107 VALUE rb_eSecurityError;
1108 VALUE rb_eNotImpError;
1109 VALUE rb_eNoMemError;
1110 VALUE rb_cNameErrorMesg;
1111 VALUE rb_eNoMatchingPatternError;
1112 VALUE rb_eNoMatchingPatternKeyError;
1114 VALUE rb_eScriptError;
1115 VALUE rb_eSyntaxError;
1116 VALUE rb_eLoadError;
1118 VALUE rb_eSystemCallError;
1119 VALUE rb_mErrno;
1120 static VALUE rb_eNOERROR;
1122 ID ruby_static_id_cause;
1123 #define id_cause ruby_static_id_cause
1124 static ID id_message, id_backtrace;
1125 static ID id_key, id_matchee, id_args, id_Errno, id_errno, id_i_path;
1126 static ID id_receiver, id_recv, id_iseq, id_local_variables;
1127 static ID id_private_call_p, id_top, id_bottom;
1128 #define id_bt idBt
1129 #define id_bt_locations idBt_locations
1130 #define id_mesg idMesg
1131 #define id_name idName
1133 #undef rb_exc_new_cstr
1135 VALUE
1136 rb_exc_new(VALUE etype, const char *ptr, long len)
1138 VALUE mesg = rb_str_new(ptr, len);
1139 return rb_class_new_instance(1, &mesg, etype);
1142 VALUE
1143 rb_exc_new_cstr(VALUE etype, const char *s)
1145 return rb_exc_new(etype, s, strlen(s));
1148 VALUE
1149 rb_exc_new_str(VALUE etype, VALUE str)
1151 StringValue(str);
1152 return rb_class_new_instance(1, &str, etype);
1155 static VALUE
1156 exc_init(VALUE exc, VALUE mesg)
1158 rb_ivar_set(exc, id_mesg, mesg);
1159 rb_ivar_set(exc, id_bt, Qnil);
1161 return exc;
1165 * call-seq:
1166 * Exception.new(msg = nil) -> exception
1167 * Exception.exception(msg = nil) -> exception
1169 * Construct a new Exception object, optionally passing in
1170 * a message.
1173 static VALUE
1174 exc_initialize(int argc, VALUE *argv, VALUE exc)
1176 VALUE arg;
1178 arg = (!rb_check_arity(argc, 0, 1) ? Qnil : argv[0]);
1179 return exc_init(exc, arg);
1183 * Document-method: exception
1185 * call-seq:
1186 * exc.exception([string]) -> an_exception or exc
1188 * With no argument, or if the argument is the same as the receiver,
1189 * return the receiver. Otherwise, create a new
1190 * exception object of the same class as the receiver, but with a
1191 * message equal to <code>string.to_str</code>.
1195 static VALUE
1196 exc_exception(int argc, VALUE *argv, VALUE self)
1198 VALUE exc;
1200 argc = rb_check_arity(argc, 0, 1);
1201 if (argc == 0) return self;
1202 if (argc == 1 && self == argv[0]) return self;
1203 exc = rb_obj_clone(self);
1204 rb_ivar_set(exc, id_mesg, argv[0]);
1205 return exc;
1209 * call-seq:
1210 * exception.to_s -> string
1212 * Returns exception's message (or the name of the exception if
1213 * no message is set).
1216 static VALUE
1217 exc_to_s(VALUE exc)
1219 VALUE mesg = rb_attr_get(exc, idMesg);
1221 if (NIL_P(mesg)) return rb_class_name(CLASS_OF(exc));
1222 return rb_String(mesg);
1225 /* FIXME: Include eval_error.c */
1226 void rb_error_write(VALUE errinfo, VALUE emesg, VALUE errat, VALUE str, VALUE highlight, VALUE reverse);
1228 VALUE
1229 rb_get_message(VALUE exc)
1231 VALUE e = rb_check_funcall(exc, id_message, 0, 0);
1232 if (e == Qundef) return Qnil;
1233 if (!RB_TYPE_P(e, T_STRING)) e = rb_check_string_type(e);
1234 return e;
1238 * call-seq:
1239 * Exception.to_tty? -> true or false
1241 * Returns +true+ if exception messages will be sent to a tty.
1243 static VALUE
1244 exc_s_to_tty_p(VALUE self)
1246 return RBOOL(rb_stderr_tty_p());
1250 * call-seq:
1251 * exception.full_message(highlight: bool, order: [:top or :bottom]) -> string
1253 * Returns formatted string of _exception_.
1254 * The returned string is formatted using the same format that Ruby uses
1255 * when printing an uncaught exceptions to stderr.
1257 * If _highlight_ is +true+ the default error handler will send the
1258 * messages to a tty.
1260 * _order_ must be either of +:top+ or +:bottom+, and places the error
1261 * message and the innermost backtrace come at the top or the bottom.
1263 * The default values of these options depend on <code>$stderr</code>
1264 * and its +tty?+ at the timing of a call.
1267 static VALUE
1268 exc_full_message(int argc, VALUE *argv, VALUE exc)
1270 VALUE opt, str, emesg, errat;
1271 enum {kw_highlight, kw_order, kw_max_};
1272 static ID kw[kw_max_];
1273 VALUE args[kw_max_] = {Qnil, Qnil};
1275 rb_scan_args(argc, argv, "0:", &opt);
1276 if (!NIL_P(opt)) {
1277 if (!kw[0]) {
1278 #define INIT_KW(n) kw[kw_##n] = rb_intern_const(#n)
1279 INIT_KW(highlight);
1280 INIT_KW(order);
1281 #undef INIT_KW
1283 rb_get_kwargs(opt, kw, 0, kw_max_, args);
1284 switch (args[kw_highlight]) {
1285 default:
1286 rb_bool_expected(args[kw_highlight], "highlight");
1287 UNREACHABLE;
1288 case Qundef: args[kw_highlight] = Qnil; break;
1289 case Qtrue: case Qfalse: case Qnil: break;
1291 if (args[kw_order] == Qundef) {
1292 args[kw_order] = Qnil;
1294 else {
1295 ID id = rb_check_id(&args[kw_order]);
1296 if (id == id_bottom) args[kw_order] = Qtrue;
1297 else if (id == id_top) args[kw_order] = Qfalse;
1298 else {
1299 rb_raise(rb_eArgError, "expected :top or :bottom as "
1300 "order: %+"PRIsVALUE, args[kw_order]);
1304 str = rb_str_new2("");
1305 errat = rb_get_backtrace(exc);
1306 emesg = rb_get_message(exc);
1308 rb_error_write(exc, emesg, errat, str, args[kw_highlight], args[kw_order]);
1309 return str;
1313 * call-seq:
1314 * exception.message -> string
1316 * Returns the result of invoking <code>exception.to_s</code>.
1317 * Normally this returns the exception's message or name.
1320 static VALUE
1321 exc_message(VALUE exc)
1323 return rb_funcallv(exc, idTo_s, 0, 0);
1327 * call-seq:
1328 * exception.inspect -> string
1330 * Return this exception's class name and message.
1333 static VALUE
1334 exc_inspect(VALUE exc)
1336 VALUE str, klass;
1338 klass = CLASS_OF(exc);
1339 exc = rb_obj_as_string(exc);
1340 if (RSTRING_LEN(exc) == 0) {
1341 return rb_class_name(klass);
1344 str = rb_str_buf_new2("#<");
1345 klass = rb_class_name(klass);
1346 rb_str_buf_append(str, klass);
1347 rb_str_buf_cat(str, ": ", 2);
1348 rb_str_buf_append(str, exc);
1349 rb_str_buf_cat(str, ">", 1);
1351 return str;
1355 * call-seq:
1356 * exception.backtrace -> array or nil
1358 * Returns any backtrace associated with the exception. The backtrace
1359 * is an array of strings, each containing either ``filename:lineNo: in
1360 * `method''' or ``filename:lineNo.''
1362 * def a
1363 * raise "boom"
1364 * end
1366 * def b
1367 * a()
1368 * end
1370 * begin
1371 * b()
1372 * rescue => detail
1373 * print detail.backtrace.join("\n")
1374 * end
1376 * <em>produces:</em>
1378 * prog.rb:2:in `a'
1379 * prog.rb:6:in `b'
1380 * prog.rb:10
1382 * In the case no backtrace has been set, +nil+ is returned
1384 * ex = StandardError.new
1385 * ex.backtrace
1386 * #=> nil
1389 static VALUE
1390 exc_backtrace(VALUE exc)
1392 VALUE obj;
1394 obj = rb_attr_get(exc, id_bt);
1396 if (rb_backtrace_p(obj)) {
1397 obj = rb_backtrace_to_str_ary(obj);
1398 /* rb_ivar_set(exc, id_bt, obj); */
1401 return obj;
1404 static VALUE rb_check_backtrace(VALUE);
1406 VALUE
1407 rb_get_backtrace(VALUE exc)
1409 ID mid = id_backtrace;
1410 VALUE info;
1411 if (rb_method_basic_definition_p(CLASS_OF(exc), id_backtrace)) {
1412 VALUE klass = rb_eException;
1413 rb_execution_context_t *ec = GET_EC();
1414 if (NIL_P(exc))
1415 return Qnil;
1416 EXEC_EVENT_HOOK(ec, RUBY_EVENT_C_CALL, exc, mid, mid, klass, Qundef);
1417 info = exc_backtrace(exc);
1418 EXEC_EVENT_HOOK(ec, RUBY_EVENT_C_RETURN, exc, mid, mid, klass, info);
1420 else {
1421 info = rb_funcallv(exc, mid, 0, 0);
1423 if (NIL_P(info)) return Qnil;
1424 return rb_check_backtrace(info);
1428 * call-seq:
1429 * exception.backtrace_locations -> array or nil
1431 * Returns any backtrace associated with the exception. This method is
1432 * similar to Exception#backtrace, but the backtrace is an array of
1433 * Thread::Backtrace::Location.
1435 * This method is not affected by Exception#set_backtrace().
1437 static VALUE
1438 exc_backtrace_locations(VALUE exc)
1440 VALUE obj;
1442 obj = rb_attr_get(exc, id_bt_locations);
1443 if (!NIL_P(obj)) {
1444 obj = rb_backtrace_to_location_ary(obj);
1446 return obj;
1449 static VALUE
1450 rb_check_backtrace(VALUE bt)
1452 long i;
1453 static const char err[] = "backtrace must be Array of String";
1455 if (!NIL_P(bt)) {
1456 if (RB_TYPE_P(bt, T_STRING)) return rb_ary_new3(1, bt);
1457 if (rb_backtrace_p(bt)) return bt;
1458 if (!RB_TYPE_P(bt, T_ARRAY)) {
1459 rb_raise(rb_eTypeError, err);
1461 for (i=0;i<RARRAY_LEN(bt);i++) {
1462 VALUE e = RARRAY_AREF(bt, i);
1463 if (!RB_TYPE_P(e, T_STRING)) {
1464 rb_raise(rb_eTypeError, err);
1468 return bt;
1472 * call-seq:
1473 * exc.set_backtrace(backtrace) -> array
1475 * Sets the backtrace information associated with +exc+. The +backtrace+ must
1476 * be an array of String objects or a single String in the format described
1477 * in Exception#backtrace.
1481 static VALUE
1482 exc_set_backtrace(VALUE exc, VALUE bt)
1484 return rb_ivar_set(exc, id_bt, rb_check_backtrace(bt));
1487 MJIT_FUNC_EXPORTED VALUE
1488 rb_exc_set_backtrace(VALUE exc, VALUE bt)
1490 return exc_set_backtrace(exc, bt);
1494 * call-seq:
1495 * exception.cause -> an_exception or nil
1497 * Returns the previous exception ($!) at the time this exception was raised.
1498 * This is useful for wrapping exceptions and retaining the original exception
1499 * information.
1502 static VALUE
1503 exc_cause(VALUE exc)
1505 return rb_attr_get(exc, id_cause);
1508 static VALUE
1509 try_convert_to_exception(VALUE obj)
1511 return rb_check_funcall(obj, idException, 0, 0);
1515 * call-seq:
1516 * exc == obj -> true or false
1518 * Equality---If <i>obj</i> is not an Exception, returns
1519 * <code>false</code>. Otherwise, returns <code>true</code> if <i>exc</i> and
1520 * <i>obj</i> share same class, messages, and backtrace.
1523 static VALUE
1524 exc_equal(VALUE exc, VALUE obj)
1526 VALUE mesg, backtrace;
1528 if (exc == obj) return Qtrue;
1530 if (rb_obj_class(exc) != rb_obj_class(obj)) {
1531 int state;
1533 obj = rb_protect(try_convert_to_exception, obj, &state);
1534 if (state || obj == Qundef) {
1535 rb_set_errinfo(Qnil);
1536 return Qfalse;
1538 if (rb_obj_class(exc) != rb_obj_class(obj)) return Qfalse;
1539 mesg = rb_check_funcall(obj, id_message, 0, 0);
1540 if (mesg == Qundef) return Qfalse;
1541 backtrace = rb_check_funcall(obj, id_backtrace, 0, 0);
1542 if (backtrace == Qundef) return Qfalse;
1544 else {
1545 mesg = rb_attr_get(obj, id_mesg);
1546 backtrace = exc_backtrace(obj);
1549 if (!rb_equal(rb_attr_get(exc, id_mesg), mesg))
1550 return Qfalse;
1551 return rb_equal(exc_backtrace(exc), backtrace);
1555 * call-seq:
1556 * SystemExit.new -> system_exit
1557 * SystemExit.new(status) -> system_exit
1558 * SystemExit.new(status, msg) -> system_exit
1559 * SystemExit.new(msg) -> system_exit
1561 * Create a new +SystemExit+ exception with the given status and message.
1562 * Status is true, false, or an integer.
1563 * If status is not given, true is used.
1566 static VALUE
1567 exit_initialize(int argc, VALUE *argv, VALUE exc)
1569 VALUE status;
1570 if (argc > 0) {
1571 status = *argv;
1573 switch (status) {
1574 case Qtrue:
1575 status = INT2FIX(EXIT_SUCCESS);
1576 ++argv;
1577 --argc;
1578 break;
1579 case Qfalse:
1580 status = INT2FIX(EXIT_FAILURE);
1581 ++argv;
1582 --argc;
1583 break;
1584 default:
1585 status = rb_check_to_int(status);
1586 if (NIL_P(status)) {
1587 status = INT2FIX(EXIT_SUCCESS);
1589 else {
1590 #if EXIT_SUCCESS != 0
1591 if (status == INT2FIX(0))
1592 status = INT2FIX(EXIT_SUCCESS);
1593 #endif
1594 ++argv;
1595 --argc;
1597 break;
1600 else {
1601 status = INT2FIX(EXIT_SUCCESS);
1603 rb_call_super(argc, argv);
1604 rb_ivar_set(exc, id_status, status);
1605 return exc;
1610 * call-seq:
1611 * system_exit.status -> integer
1613 * Return the status value associated with this system exit.
1616 static VALUE
1617 exit_status(VALUE exc)
1619 return rb_attr_get(exc, id_status);
1624 * call-seq:
1625 * system_exit.success? -> true or false
1627 * Returns +true+ if exiting successful, +false+ if not.
1630 static VALUE
1631 exit_success_p(VALUE exc)
1633 VALUE status_val = rb_attr_get(exc, id_status);
1634 int status;
1636 if (NIL_P(status_val))
1637 return Qtrue;
1638 status = NUM2INT(status_val);
1639 return RBOOL(WIFEXITED(status) && WEXITSTATUS(status) == EXIT_SUCCESS);
1642 static VALUE
1643 err_init_recv(VALUE exc, VALUE recv)
1645 if (recv != Qundef) rb_ivar_set(exc, id_recv, recv);
1646 return exc;
1650 * call-seq:
1651 * FrozenError.new(msg=nil, receiver: nil) -> frozen_error
1653 * Construct a new FrozenError exception. If given the <i>receiver</i>
1654 * parameter may subsequently be examined using the FrozenError#receiver
1655 * method.
1657 * a = [].freeze
1658 * raise FrozenError.new("can't modify frozen array", receiver: a)
1661 static VALUE
1662 frozen_err_initialize(int argc, VALUE *argv, VALUE self)
1664 ID keywords[1];
1665 VALUE values[numberof(keywords)], options;
1667 argc = rb_scan_args(argc, argv, "*:", NULL, &options);
1668 keywords[0] = id_receiver;
1669 rb_get_kwargs(options, keywords, 0, numberof(values), values);
1670 rb_call_super(argc, argv);
1671 err_init_recv(self, values[0]);
1672 return self;
1676 * Document-method: FrozenError#receiver
1677 * call-seq:
1678 * frozen_error.receiver -> object
1680 * Return the receiver associated with this FrozenError exception.
1683 #define frozen_err_receiver name_err_receiver
1685 void
1686 rb_name_error(ID id, const char *fmt, ...)
1688 VALUE exc, argv[2];
1689 va_list args;
1691 va_start(args, fmt);
1692 argv[0] = rb_vsprintf(fmt, args);
1693 va_end(args);
1695 argv[1] = ID2SYM(id);
1696 exc = rb_class_new_instance(2, argv, rb_eNameError);
1697 rb_exc_raise(exc);
1700 void
1701 rb_name_error_str(VALUE str, const char *fmt, ...)
1703 VALUE exc, argv[2];
1704 va_list args;
1706 va_start(args, fmt);
1707 argv[0] = rb_vsprintf(fmt, args);
1708 va_end(args);
1710 argv[1] = str;
1711 exc = rb_class_new_instance(2, argv, rb_eNameError);
1712 rb_exc_raise(exc);
1715 static VALUE
1716 name_err_init_attr(VALUE exc, VALUE recv, VALUE method)
1718 const rb_execution_context_t *ec = GET_EC();
1719 rb_control_frame_t *cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(ec->cfp);
1720 cfp = rb_vm_get_ruby_level_next_cfp(ec, cfp);
1721 rb_ivar_set(exc, id_name, method);
1722 err_init_recv(exc, recv);
1723 if (cfp) rb_ivar_set(exc, id_iseq, rb_iseqw_new(cfp->iseq));
1724 return exc;
1728 * call-seq:
1729 * NameError.new(msg=nil, name=nil, receiver: nil) -> name_error
1731 * Construct a new NameError exception. If given the <i>name</i>
1732 * parameter may subsequently be examined using the NameError#name
1733 * method. <i>receiver</i> parameter allows to pass object in
1734 * context of which the error happened. Example:
1736 * [1, 2, 3].method(:rject) # NameError with name "rject" and receiver: Array
1737 * [1, 2, 3].singleton_method(:rject) # NameError with name "rject" and receiver: [1, 2, 3]
1740 static VALUE
1741 name_err_initialize(int argc, VALUE *argv, VALUE self)
1743 ID keywords[1];
1744 VALUE values[numberof(keywords)], name, options;
1746 argc = rb_scan_args(argc, argv, "*:", NULL, &options);
1747 keywords[0] = id_receiver;
1748 rb_get_kwargs(options, keywords, 0, numberof(values), values);
1749 name = (argc > 1) ? argv[--argc] : Qnil;
1750 rb_call_super(argc, argv);
1751 name_err_init_attr(self, values[0], name);
1752 return self;
1755 static VALUE rb_name_err_mesg_new(VALUE mesg, VALUE recv, VALUE method);
1757 static VALUE
1758 name_err_init(VALUE exc, VALUE mesg, VALUE recv, VALUE method)
1760 exc_init(exc, rb_name_err_mesg_new(mesg, recv, method));
1761 return name_err_init_attr(exc, recv, method);
1764 VALUE
1765 rb_name_err_new(VALUE mesg, VALUE recv, VALUE method)
1767 VALUE exc = rb_obj_alloc(rb_eNameError);
1768 return name_err_init(exc, mesg, recv, method);
1772 * call-seq:
1773 * name_error.name -> string or nil
1775 * Return the name associated with this NameError exception.
1778 static VALUE
1779 name_err_name(VALUE self)
1781 return rb_attr_get(self, id_name);
1785 * call-seq:
1786 * name_error.local_variables -> array
1788 * Return a list of the local variable names defined where this
1789 * NameError exception was raised.
1791 * Internal use only.
1794 static VALUE
1795 name_err_local_variables(VALUE self)
1797 VALUE vars = rb_attr_get(self, id_local_variables);
1799 if (NIL_P(vars)) {
1800 VALUE iseqw = rb_attr_get(self, id_iseq);
1801 if (!NIL_P(iseqw)) vars = rb_iseqw_local_variables(iseqw);
1802 if (NIL_P(vars)) vars = rb_ary_new();
1803 rb_ivar_set(self, id_local_variables, vars);
1805 return vars;
1808 static VALUE
1809 nometh_err_init_attr(VALUE exc, VALUE args, int priv)
1811 rb_ivar_set(exc, id_args, args);
1812 rb_ivar_set(exc, id_private_call_p, RBOOL(priv));
1813 return exc;
1817 * call-seq:
1818 * NoMethodError.new(msg=nil, name=nil, args=nil, private=false, receiver: nil) -> no_method_error
1820 * Construct a NoMethodError exception for a method of the given name
1821 * called with the given arguments. The name may be accessed using
1822 * the <code>#name</code> method on the resulting object, and the
1823 * arguments using the <code>#args</code> method.
1825 * If <i>private</i> argument were passed, it designates method was
1826 * attempted to call in private context, and can be accessed with
1827 * <code>#private_call?</code> method.
1829 * <i>receiver</i> argument stores an object whose method was called.
1832 static VALUE
1833 nometh_err_initialize(int argc, VALUE *argv, VALUE self)
1835 int priv;
1836 VALUE args, options;
1837 argc = rb_scan_args(argc, argv, "*:", NULL, &options);
1838 priv = (argc > 3) && (--argc, RTEST(argv[argc]));
1839 args = (argc > 2) ? argv[--argc] : Qnil;
1840 if (!NIL_P(options)) argv[argc++] = options;
1841 rb_call_super_kw(argc, argv, RB_PASS_CALLED_KEYWORDS);
1842 return nometh_err_init_attr(self, args, priv);
1845 VALUE
1846 rb_nomethod_err_new(VALUE mesg, VALUE recv, VALUE method, VALUE args, int priv)
1848 VALUE exc = rb_obj_alloc(rb_eNoMethodError);
1849 name_err_init(exc, mesg, recv, method);
1850 return nometh_err_init_attr(exc, args, priv);
1853 /* :nodoc: */
1854 enum {
1855 NAME_ERR_MESG__MESG,
1856 NAME_ERR_MESG__RECV,
1857 NAME_ERR_MESG__NAME,
1858 NAME_ERR_MESG_COUNT
1861 static void
1862 name_err_mesg_mark(void *p)
1864 VALUE *ptr = p;
1865 rb_gc_mark_locations(ptr, ptr+NAME_ERR_MESG_COUNT);
1868 #define name_err_mesg_free RUBY_TYPED_DEFAULT_FREE
1870 static size_t
1871 name_err_mesg_memsize(const void *p)
1873 return NAME_ERR_MESG_COUNT * sizeof(VALUE);
1876 static const rb_data_type_t name_err_mesg_data_type = {
1877 "name_err_mesg",
1879 name_err_mesg_mark,
1880 name_err_mesg_free,
1881 name_err_mesg_memsize,
1883 0, 0, RUBY_TYPED_FREE_IMMEDIATELY
1886 /* :nodoc: */
1887 static VALUE
1888 rb_name_err_mesg_init(VALUE klass, VALUE mesg, VALUE recv, VALUE method)
1890 VALUE result = TypedData_Wrap_Struct(klass, &name_err_mesg_data_type, 0);
1891 VALUE *ptr = ALLOC_N(VALUE, NAME_ERR_MESG_COUNT);
1893 ptr[NAME_ERR_MESG__MESG] = mesg;
1894 ptr[NAME_ERR_MESG__RECV] = recv;
1895 ptr[NAME_ERR_MESG__NAME] = method;
1896 RTYPEDDATA_DATA(result) = ptr;
1897 return result;
1900 /* :nodoc: */
1901 static VALUE
1902 rb_name_err_mesg_new(VALUE mesg, VALUE recv, VALUE method)
1904 return rb_name_err_mesg_init(rb_cNameErrorMesg, mesg, recv, method);
1907 /* :nodoc: */
1908 static VALUE
1909 name_err_mesg_alloc(VALUE klass)
1911 return rb_name_err_mesg_init(klass, Qnil, Qnil, Qnil);
1914 /* :nodoc: */
1915 static VALUE
1916 name_err_mesg_init_copy(VALUE obj1, VALUE obj2)
1918 VALUE *ptr1, *ptr2;
1920 if (obj1 == obj2) return obj1;
1921 rb_obj_init_copy(obj1, obj2);
1923 TypedData_Get_Struct(obj1, VALUE, &name_err_mesg_data_type, ptr1);
1924 TypedData_Get_Struct(obj2, VALUE, &name_err_mesg_data_type, ptr2);
1925 MEMCPY(ptr1, ptr2, VALUE, NAME_ERR_MESG_COUNT);
1926 return obj1;
1929 /* :nodoc: */
1930 static VALUE
1931 name_err_mesg_equal(VALUE obj1, VALUE obj2)
1933 VALUE *ptr1, *ptr2;
1934 int i;
1936 if (obj1 == obj2) return Qtrue;
1937 if (rb_obj_class(obj2) != rb_cNameErrorMesg)
1938 return Qfalse;
1940 TypedData_Get_Struct(obj1, VALUE, &name_err_mesg_data_type, ptr1);
1941 TypedData_Get_Struct(obj2, VALUE, &name_err_mesg_data_type, ptr2);
1942 for (i=0; i<NAME_ERR_MESG_COUNT; i++) {
1943 if (!rb_equal(ptr1[i], ptr2[i]))
1944 return Qfalse;
1946 return Qtrue;
1949 /* :nodoc: */
1950 static VALUE
1951 name_err_mesg_receiver_name(VALUE obj)
1953 if (RB_SPECIAL_CONST_P(obj)) return Qundef;
1954 if (RB_BUILTIN_TYPE(obj) == T_MODULE || RB_BUILTIN_TYPE(obj) == T_CLASS) {
1955 return rb_check_funcall(obj, rb_intern("name"), 0, 0);
1957 return Qundef;
1960 /* :nodoc: */
1961 static VALUE
1962 name_err_mesg_to_str(VALUE obj)
1964 VALUE *ptr, mesg;
1965 TypedData_Get_Struct(obj, VALUE, &name_err_mesg_data_type, ptr);
1967 mesg = ptr[NAME_ERR_MESG__MESG];
1968 if (NIL_P(mesg)) return Qnil;
1969 else {
1970 struct RString s_str, d_str;
1971 VALUE c, s, d = 0, args[4];
1972 int state = 0, singleton = 0;
1973 rb_encoding *usascii = rb_usascii_encoding();
1975 #define FAKE_CSTR(v, str) rb_setup_fake_str((v), (str), rb_strlen_lit(str), usascii)
1976 obj = ptr[NAME_ERR_MESG__RECV];
1977 switch (obj) {
1978 case Qnil:
1979 d = FAKE_CSTR(&d_str, "nil");
1980 break;
1981 case Qtrue:
1982 d = FAKE_CSTR(&d_str, "true");
1983 break;
1984 case Qfalse:
1985 d = FAKE_CSTR(&d_str, "false");
1986 break;
1987 default:
1988 d = rb_protect(name_err_mesg_receiver_name, obj, &state);
1989 if (state || d == Qundef || NIL_P(d))
1990 d = rb_protect(rb_inspect, obj, &state);
1991 if (state) {
1992 rb_set_errinfo(Qnil);
1994 d = rb_check_string_type(d);
1995 if (NIL_P(d)) {
1996 d = rb_any_to_s(obj);
1998 singleton = (RSTRING_LEN(d) > 0 && RSTRING_PTR(d)[0] == '#');
1999 break;
2001 if (!singleton) {
2002 s = FAKE_CSTR(&s_str, ":");
2003 c = rb_class_name(CLASS_OF(obj));
2005 else {
2006 c = s = FAKE_CSTR(&s_str, "");
2008 args[0] = rb_obj_as_string(ptr[NAME_ERR_MESG__NAME]);
2009 args[1] = d;
2010 args[2] = s;
2011 args[3] = c;
2012 mesg = rb_str_format(4, args, mesg);
2014 return mesg;
2017 /* :nodoc: */
2018 static VALUE
2019 name_err_mesg_dump(VALUE obj, VALUE limit)
2021 return name_err_mesg_to_str(obj);
2024 /* :nodoc: */
2025 static VALUE
2026 name_err_mesg_load(VALUE klass, VALUE str)
2028 return str;
2032 * call-seq:
2033 * name_error.receiver -> object
2035 * Return the receiver associated with this NameError exception.
2038 static VALUE
2039 name_err_receiver(VALUE self)
2041 VALUE *ptr, recv, mesg;
2043 recv = rb_ivar_lookup(self, id_recv, Qundef);
2044 if (recv != Qundef) return recv;
2046 mesg = rb_attr_get(self, id_mesg);
2047 if (!rb_typeddata_is_kind_of(mesg, &name_err_mesg_data_type)) {
2048 rb_raise(rb_eArgError, "no receiver is available");
2050 ptr = DATA_PTR(mesg);
2051 return ptr[NAME_ERR_MESG__RECV];
2055 * call-seq:
2056 * no_method_error.args -> obj
2058 * Return the arguments passed in as the third parameter to
2059 * the constructor.
2062 static VALUE
2063 nometh_err_args(VALUE self)
2065 return rb_attr_get(self, id_args);
2069 * call-seq:
2070 * no_method_error.private_call? -> true or false
2072 * Return true if the caused method was called as private.
2075 static VALUE
2076 nometh_err_private_call_p(VALUE self)
2078 return rb_attr_get(self, id_private_call_p);
2081 void
2082 rb_invalid_str(const char *str, const char *type)
2084 VALUE s = rb_str_new2(str);
2086 rb_raise(rb_eArgError, "invalid value for %s: %+"PRIsVALUE, type, s);
2090 * call-seq:
2091 * key_error.receiver -> object
2093 * Return the receiver associated with this KeyError exception.
2096 static VALUE
2097 key_err_receiver(VALUE self)
2099 VALUE recv;
2101 recv = rb_ivar_lookup(self, id_receiver, Qundef);
2102 if (recv != Qundef) return recv;
2103 rb_raise(rb_eArgError, "no receiver is available");
2107 * call-seq:
2108 * key_error.key -> object
2110 * Return the key caused this KeyError exception.
2113 static VALUE
2114 key_err_key(VALUE self)
2116 VALUE key;
2118 key = rb_ivar_lookup(self, id_key, Qundef);
2119 if (key != Qundef) return key;
2120 rb_raise(rb_eArgError, "no key is available");
2123 VALUE
2124 rb_key_err_new(VALUE mesg, VALUE recv, VALUE key)
2126 VALUE exc = rb_obj_alloc(rb_eKeyError);
2127 rb_ivar_set(exc, id_mesg, mesg);
2128 rb_ivar_set(exc, id_bt, Qnil);
2129 rb_ivar_set(exc, id_key, key);
2130 rb_ivar_set(exc, id_receiver, recv);
2131 return exc;
2135 * call-seq:
2136 * KeyError.new(message=nil, receiver: nil, key: nil) -> key_error
2138 * Construct a new +KeyError+ exception with the given message,
2139 * receiver and key.
2142 static VALUE
2143 key_err_initialize(int argc, VALUE *argv, VALUE self)
2145 VALUE options;
2147 rb_call_super(rb_scan_args(argc, argv, "01:", NULL, &options), argv);
2149 if (!NIL_P(options)) {
2150 ID keywords[2];
2151 VALUE values[numberof(keywords)];
2152 int i;
2153 keywords[0] = id_receiver;
2154 keywords[1] = id_key;
2155 rb_get_kwargs(options, keywords, 0, numberof(values), values);
2156 for (i = 0; i < numberof(values); ++i) {
2157 if (values[i] != Qundef) {
2158 rb_ivar_set(self, keywords[i], values[i]);
2163 return self;
2167 * call-seq:
2168 * no_matching_pattern_key_error.matchee -> object
2170 * Return the matchee associated with this NoMatchingPatternKeyError exception.
2173 static VALUE
2174 no_matching_pattern_key_err_matchee(VALUE self)
2176 VALUE matchee;
2178 matchee = rb_ivar_lookup(self, id_matchee, Qundef);
2179 if (matchee != Qundef) return matchee;
2180 rb_raise(rb_eArgError, "no matchee is available");
2184 * call-seq:
2185 * no_matching_pattern_key_error.key -> object
2187 * Return the key caused this NoMatchingPatternKeyError exception.
2190 static VALUE
2191 no_matching_pattern_key_err_key(VALUE self)
2193 VALUE key;
2195 key = rb_ivar_lookup(self, id_key, Qundef);
2196 if (key != Qundef) return key;
2197 rb_raise(rb_eArgError, "no key is available");
2201 * call-seq:
2202 * NoMatchingPatternKeyError.new(message=nil, matchee: nil, key: nil) -> no_matching_pattern_key_error
2204 * Construct a new +NoMatchingPatternKeyError+ exception with the given message,
2205 * matchee and key.
2208 static VALUE
2209 no_matching_pattern_key_err_initialize(int argc, VALUE *argv, VALUE self)
2211 VALUE options;
2213 rb_call_super(rb_scan_args(argc, argv, "01:", NULL, &options), argv);
2215 if (!NIL_P(options)) {
2216 ID keywords[2];
2217 VALUE values[numberof(keywords)];
2218 int i;
2219 keywords[0] = id_matchee;
2220 keywords[1] = id_key;
2221 rb_get_kwargs(options, keywords, 0, numberof(values), values);
2222 for (i = 0; i < numberof(values); ++i) {
2223 if (values[i] != Qundef) {
2224 rb_ivar_set(self, keywords[i], values[i]);
2229 return self;
2234 * call-seq:
2235 * SyntaxError.new([msg]) -> syntax_error
2237 * Construct a SyntaxError exception.
2240 static VALUE
2241 syntax_error_initialize(int argc, VALUE *argv, VALUE self)
2243 VALUE mesg;
2244 if (argc == 0) {
2245 mesg = rb_fstring_lit("compile error");
2246 argc = 1;
2247 argv = &mesg;
2249 return rb_call_super(argc, argv);
2253 * Document-module: Errno
2255 * Ruby exception objects are subclasses of Exception. However,
2256 * operating systems typically report errors using plain
2257 * integers. Module Errno is created dynamically to map these
2258 * operating system errors to Ruby classes, with each error number
2259 * generating its own subclass of SystemCallError. As the subclass
2260 * is created in module Errno, its name will start
2261 * <code>Errno::</code>.
2263 * The names of the <code>Errno::</code> classes depend on the
2264 * environment in which Ruby runs. On a typical Unix or Windows
2265 * platform, there are Errno classes such as Errno::EACCES,
2266 * Errno::EAGAIN, Errno::EINTR, and so on.
2268 * The integer operating system error number corresponding to a
2269 * particular error is available as the class constant
2270 * <code>Errno::</code><em>error</em><code>::Errno</code>.
2272 * Errno::EACCES::Errno #=> 13
2273 * Errno::EAGAIN::Errno #=> 11
2274 * Errno::EINTR::Errno #=> 4
2276 * The full list of operating system errors on your particular platform
2277 * are available as the constants of Errno.
2279 * Errno.constants #=> :E2BIG, :EACCES, :EADDRINUSE, :EADDRNOTAVAIL, ...
2282 static st_table *syserr_tbl;
2284 static VALUE
2285 set_syserr(int n, const char *name)
2287 st_data_t error;
2289 if (!st_lookup(syserr_tbl, n, &error)) {
2290 error = rb_define_class_under(rb_mErrno, name, rb_eSystemCallError);
2292 /* capture nonblock errnos for WaitReadable/WaitWritable subclasses */
2293 switch (n) {
2294 case EAGAIN:
2295 rb_eEAGAIN = error;
2297 #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
2298 break;
2299 case EWOULDBLOCK:
2300 #endif
2302 rb_eEWOULDBLOCK = error;
2303 break;
2304 case EINPROGRESS:
2305 rb_eEINPROGRESS = error;
2306 break;
2309 rb_define_const(error, "Errno", INT2NUM(n));
2310 st_add_direct(syserr_tbl, n, error);
2312 else {
2313 rb_define_const(rb_mErrno, name, error);
2315 return error;
2318 static VALUE
2319 get_syserr(int n)
2321 st_data_t error;
2323 if (!st_lookup(syserr_tbl, n, &error)) {
2324 char name[8]; /* some Windows' errno have 5 digits. */
2326 snprintf(name, sizeof(name), "E%03d", n);
2327 error = set_syserr(n, name);
2329 return error;
2333 * call-seq:
2334 * SystemCallError.new(msg, errno) -> system_call_error_subclass
2336 * If _errno_ corresponds to a known system error code, constructs the
2337 * appropriate Errno class for that error, otherwise constructs a
2338 * generic SystemCallError object. The error number is subsequently
2339 * available via the #errno method.
2342 static VALUE
2343 syserr_initialize(int argc, VALUE *argv, VALUE self)
2345 #if !defined(_WIN32)
2346 char *strerror();
2347 #endif
2348 const char *err;
2349 VALUE mesg, error, func, errmsg;
2350 VALUE klass = rb_obj_class(self);
2352 if (klass == rb_eSystemCallError) {
2353 st_data_t data = (st_data_t)klass;
2354 rb_scan_args(argc, argv, "12", &mesg, &error, &func);
2355 if (argc == 1 && FIXNUM_P(mesg)) {
2356 error = mesg; mesg = Qnil;
2358 if (!NIL_P(error) && st_lookup(syserr_tbl, NUM2LONG(error), &data)) {
2359 klass = (VALUE)data;
2360 /* change class */
2361 if (!RB_TYPE_P(self, T_OBJECT)) { /* insurance to avoid type crash */
2362 rb_raise(rb_eTypeError, "invalid instance type");
2364 RBASIC_SET_CLASS(self, klass);
2367 else {
2368 rb_scan_args(argc, argv, "02", &mesg, &func);
2369 error = rb_const_get(klass, id_Errno);
2371 if (!NIL_P(error)) err = strerror(NUM2INT(error));
2372 else err = "unknown error";
2374 errmsg = rb_enc_str_new_cstr(err, rb_locale_encoding());
2375 if (!NIL_P(mesg)) {
2376 VALUE str = StringValue(mesg);
2378 if (!NIL_P(func)) rb_str_catf(errmsg, " @ %"PRIsVALUE, func);
2379 rb_str_catf(errmsg, " - %"PRIsVALUE, str);
2381 mesg = errmsg;
2383 rb_call_super(1, &mesg);
2384 rb_ivar_set(self, id_errno, error);
2385 return self;
2389 * call-seq:
2390 * system_call_error.errno -> integer
2392 * Return this SystemCallError's error number.
2395 static VALUE
2396 syserr_errno(VALUE self)
2398 return rb_attr_get(self, id_errno);
2402 * call-seq:
2403 * system_call_error === other -> true or false
2405 * Return +true+ if the receiver is a generic +SystemCallError+, or
2406 * if the error numbers +self+ and _other_ are the same.
2409 static VALUE
2410 syserr_eqq(VALUE self, VALUE exc)
2412 VALUE num, e;
2414 if (!rb_obj_is_kind_of(exc, rb_eSystemCallError)) {
2415 if (!rb_respond_to(exc, id_errno)) return Qfalse;
2417 else if (self == rb_eSystemCallError) return Qtrue;
2419 num = rb_attr_get(exc, id_errno);
2420 if (NIL_P(num)) {
2421 num = rb_funcallv(exc, id_errno, 0, 0);
2423 e = rb_const_get(self, id_Errno);
2424 return RBOOL(FIXNUM_P(num) ? num == e : rb_equal(num, e));
2429 * Document-class: StandardError
2431 * The most standard error types are subclasses of StandardError. A
2432 * rescue clause without an explicit Exception class will rescue all
2433 * StandardErrors (and only those).
2435 * def foo
2436 * raise "Oups"
2437 * end
2438 * foo rescue "Hello" #=> "Hello"
2440 * On the other hand:
2442 * require 'does/not/exist' rescue "Hi"
2444 * <em>raises the exception:</em>
2446 * LoadError: no such file to load -- does/not/exist
2451 * Document-class: SystemExit
2453 * Raised by +exit+ to initiate the termination of the script.
2457 * Document-class: SignalException
2459 * Raised when a signal is received.
2461 * begin
2462 * Process.kill('HUP',Process.pid)
2463 * sleep # wait for receiver to handle signal sent by Process.kill
2464 * rescue SignalException => e
2465 * puts "received Exception #{e}"
2466 * end
2468 * <em>produces:</em>
2470 * received Exception SIGHUP
2474 * Document-class: Interrupt
2476 * Raised when the interrupt signal is received, typically because the
2477 * user has pressed Control-C (on most posix platforms). As such, it is a
2478 * subclass of +SignalException+.
2480 * begin
2481 * puts "Press ctrl-C when you get bored"
2482 * loop {}
2483 * rescue Interrupt => e
2484 * puts "Note: You will typically use Signal.trap instead."
2485 * end
2487 * <em>produces:</em>
2489 * Press ctrl-C when you get bored
2491 * <em>then waits until it is interrupted with Control-C and then prints:</em>
2493 * Note: You will typically use Signal.trap instead.
2497 * Document-class: TypeError
2499 * Raised when encountering an object that is not of the expected type.
2501 * [1, 2, 3].first("two")
2503 * <em>raises the exception:</em>
2505 * TypeError: no implicit conversion of String into Integer
2510 * Document-class: ArgumentError
2512 * Raised when the arguments are wrong and there isn't a more specific
2513 * Exception class.
2515 * Ex: passing the wrong number of arguments
2517 * [1, 2, 3].first(4, 5)
2519 * <em>raises the exception:</em>
2521 * ArgumentError: wrong number of arguments (given 2, expected 1)
2523 * Ex: passing an argument that is not acceptable:
2525 * [1, 2, 3].first(-4)
2527 * <em>raises the exception:</em>
2529 * ArgumentError: negative array size
2533 * Document-class: IndexError
2535 * Raised when the given index is invalid.
2537 * a = [:foo, :bar]
2538 * a.fetch(0) #=> :foo
2539 * a[4] #=> nil
2540 * a.fetch(4) #=> IndexError: index 4 outside of array bounds: -2...2
2545 * Document-class: KeyError
2547 * Raised when the specified key is not found. It is a subclass of
2548 * IndexError.
2550 * h = {"foo" => :bar}
2551 * h.fetch("foo") #=> :bar
2552 * h.fetch("baz") #=> KeyError: key not found: "baz"
2557 * Document-class: RangeError
2559 * Raised when a given numerical value is out of range.
2561 * [1, 2, 3].drop(1 << 100)
2563 * <em>raises the exception:</em>
2565 * RangeError: bignum too big to convert into `long'
2569 * Document-class: ScriptError
2571 * ScriptError is the superclass for errors raised when a script
2572 * can not be executed because of a +LoadError+,
2573 * +NotImplementedError+ or a +SyntaxError+. Note these type of
2574 * +ScriptErrors+ are not +StandardError+ and will not be
2575 * rescued unless it is specified explicitly (or its ancestor
2576 * +Exception+).
2580 * Document-class: SyntaxError
2582 * Raised when encountering Ruby code with an invalid syntax.
2584 * eval("1+1=2")
2586 * <em>raises the exception:</em>
2588 * SyntaxError: (eval):1: syntax error, unexpected '=', expecting $end
2592 * Document-class: LoadError
2594 * Raised when a file required (a Ruby script, extension library, ...)
2595 * fails to load.
2597 * require 'this/file/does/not/exist'
2599 * <em>raises the exception:</em>
2601 * LoadError: no such file to load -- this/file/does/not/exist
2605 * Document-class: NotImplementedError
2607 * Raised when a feature is not implemented on the current platform. For
2608 * example, methods depending on the +fsync+ or +fork+ system calls may
2609 * raise this exception if the underlying operating system or Ruby
2610 * runtime does not support them.
2612 * Note that if +fork+ raises a +NotImplementedError+, then
2613 * <code>respond_to?(:fork)</code> returns +false+.
2617 * Document-class: NameError
2619 * Raised when a given name is invalid or undefined.
2621 * puts foo
2623 * <em>raises the exception:</em>
2625 * NameError: undefined local variable or method `foo' for main:Object
2627 * Since constant names must start with a capital:
2629 * Integer.const_set :answer, 42
2631 * <em>raises the exception:</em>
2633 * NameError: wrong constant name answer
2637 * Document-class: NoMethodError
2639 * Raised when a method is called on a receiver which doesn't have it
2640 * defined and also fails to respond with +method_missing+.
2642 * "hello".to_ary
2644 * <em>raises the exception:</em>
2646 * NoMethodError: undefined method `to_ary' for "hello":String
2650 * Document-class: FrozenError
2652 * Raised when there is an attempt to modify a frozen object.
2654 * [1, 2, 3].freeze << 4
2656 * <em>raises the exception:</em>
2658 * FrozenError: can't modify frozen Array
2662 * Document-class: RuntimeError
2664 * A generic error class raised when an invalid operation is attempted.
2665 * Kernel#raise will raise a RuntimeError if no Exception class is
2666 * specified.
2668 * raise "ouch"
2670 * <em>raises the exception:</em>
2672 * RuntimeError: ouch
2676 * Document-class: SecurityError
2678 * No longer used by internal code.
2682 * Document-class: NoMemoryError
2684 * Raised when memory allocation fails.
2688 * Document-class: SystemCallError
2690 * SystemCallError is the base class for all low-level
2691 * platform-dependent errors.
2693 * The errors available on the current platform are subclasses of
2694 * SystemCallError and are defined in the Errno module.
2696 * File.open("does/not/exist")
2698 * <em>raises the exception:</em>
2700 * Errno::ENOENT: No such file or directory - does/not/exist
2704 * Document-class: EncodingError
2706 * EncodingError is the base class for encoding errors.
2710 * Document-class: Encoding::CompatibilityError
2712 * Raised by Encoding and String methods when the source encoding is
2713 * incompatible with the target encoding.
2717 * Document-class: fatal
2719 * fatal is an Exception that is raised when Ruby has encountered a fatal
2720 * error and must exit.
2724 * Document-class: NameError::message
2725 * :nodoc:
2729 * Document-class: Exception
2731 * \Class Exception and its subclasses are used to communicate between
2732 * Kernel#raise and +rescue+ statements in <code>begin ... end</code> blocks.
2734 * An Exception object carries information about an exception:
2735 * - Its type (the exception's class).
2736 * - An optional descriptive message.
2737 * - Optional backtrace information.
2739 * Some built-in subclasses of Exception have additional methods: e.g., NameError#name.
2741 * == Defaults
2743 * Two Ruby statements have default exception classes:
2744 * - +raise+: defaults to RuntimeError.
2745 * - +rescue+: defaults to StandardError.
2747 * == Global Variables
2749 * When an exception has been raised but not yet handled (in +rescue+,
2750 * +ensure+, +at_exit+ and +END+ blocks), two global variables are set:
2751 * - <code>$!</code> contains the current exception.
2752 * - <code>$@</code> contains its backtrace.
2754 * == Custom Exceptions
2756 * To provide additional or alternate information,
2757 * a program may create custom exception classes
2758 * that derive from the built-in exception classes.
2760 * A good practice is for a library to create a single "generic" exception class
2761 * (typically a subclass of StandardError or RuntimeError)
2762 * and have its other exception classes derive from that class.
2763 * This allows the user to rescue the generic exception, thus catching all exceptions
2764 * the library may raise even if future versions of the library add new
2765 * exception subclasses.
2767 * For example:
2769 * class MyLibrary
2770 * class Error < ::StandardError
2771 * end
2773 * class WidgetError < Error
2774 * end
2776 * class FrobError < Error
2777 * end
2779 * end
2781 * To handle both MyLibrary::WidgetError and MyLibrary::FrobError the library
2782 * user can rescue MyLibrary::Error.
2784 * == Built-In Exception Classes
2786 * The built-in subclasses of Exception are:
2788 * * NoMemoryError
2789 * * ScriptError
2790 * * LoadError
2791 * * NotImplementedError
2792 * * SyntaxError
2793 * * SecurityError
2794 * * SignalException
2795 * * Interrupt
2796 * * StandardError
2797 * * ArgumentError
2798 * * UncaughtThrowError
2799 * * EncodingError
2800 * * FiberError
2801 * * IOError
2802 * * EOFError
2803 * * IndexError
2804 * * KeyError
2805 * * StopIteration
2806 * * ClosedQueueError
2807 * * LocalJumpError
2808 * * NameError
2809 * * NoMethodError
2810 * * RangeError
2811 * * FloatDomainError
2812 * * RegexpError
2813 * * RuntimeError
2814 * * FrozenError
2815 * * SystemCallError
2816 * * Errno::*
2817 * * ThreadError
2818 * * TypeError
2819 * * ZeroDivisionError
2820 * * SystemExit
2821 * * SystemStackError
2822 * * fatal
2825 static VALUE
2826 exception_alloc(VALUE klass)
2828 return rb_class_allocate_instance(klass);
2831 static VALUE
2832 exception_dumper(VALUE exc)
2834 // TODO: Currently, the instance variables "bt" and "bt_locations"
2835 // refers to the same object (Array of String). But "bt_locations"
2836 // should have an Array of Thread::Backtrace::Locations.
2838 return exc;
2841 static int
2842 ivar_copy_i(st_data_t key, st_data_t val, st_data_t exc)
2844 rb_ivar_set((VALUE) exc, (ID) key, (VALUE) val);
2845 return ST_CONTINUE;
2848 static VALUE
2849 exception_loader(VALUE exc, VALUE obj)
2851 // The loader function of rb_marshal_define_compat seems to be called for two events:
2852 // one is for fixup (r_fixup_compat), the other is for TYPE_USERDEF.
2853 // In the former case, the first argument is an instance of Exception (because
2854 // we pass rb_eException to rb_marshal_define_compat). In the latter case, the first
2855 // argument is a class object (see TYPE_USERDEF case in r_object0).
2856 // We want to copy all instance variables (but "bt_locations") from obj to exc.
2857 // But we do not want to do so in the second case, so the following branch is for that.
2858 if (RB_TYPE_P(exc, T_CLASS)) return obj; // maybe called from Marshal's TYPE_USERDEF
2860 rb_ivar_foreach(obj, ivar_copy_i, exc);
2862 if (rb_attr_get(exc, id_bt) == rb_attr_get(exc, id_bt_locations)) {
2863 rb_ivar_set(exc, id_bt_locations, Qnil);
2866 return exc;
2869 void
2870 Init_Exception(void)
2872 rb_eException = rb_define_class("Exception", rb_cObject);
2873 rb_define_alloc_func(rb_eException, exception_alloc);
2874 rb_marshal_define_compat(rb_eException, rb_eException, exception_dumper, exception_loader);
2875 rb_define_singleton_method(rb_eException, "exception", rb_class_new_instance, -1);
2876 rb_define_singleton_method(rb_eException, "to_tty?", exc_s_to_tty_p, 0);
2877 rb_define_method(rb_eException, "exception", exc_exception, -1);
2878 rb_define_method(rb_eException, "initialize", exc_initialize, -1);
2879 rb_define_method(rb_eException, "==", exc_equal, 1);
2880 rb_define_method(rb_eException, "to_s", exc_to_s, 0);
2881 rb_define_method(rb_eException, "message", exc_message, 0);
2882 rb_define_method(rb_eException, "full_message", exc_full_message, -1);
2883 rb_define_method(rb_eException, "inspect", exc_inspect, 0);
2884 rb_define_method(rb_eException, "backtrace", exc_backtrace, 0);
2885 rb_define_method(rb_eException, "backtrace_locations", exc_backtrace_locations, 0);
2886 rb_define_method(rb_eException, "set_backtrace", exc_set_backtrace, 1);
2887 rb_define_method(rb_eException, "cause", exc_cause, 0);
2889 rb_eSystemExit = rb_define_class("SystemExit", rb_eException);
2890 rb_define_method(rb_eSystemExit, "initialize", exit_initialize, -1);
2891 rb_define_method(rb_eSystemExit, "status", exit_status, 0);
2892 rb_define_method(rb_eSystemExit, "success?", exit_success_p, 0);
2894 rb_eFatal = rb_define_class("fatal", rb_eException);
2895 rb_eSignal = rb_define_class("SignalException", rb_eException);
2896 rb_eInterrupt = rb_define_class("Interrupt", rb_eSignal);
2898 rb_eStandardError = rb_define_class("StandardError", rb_eException);
2899 rb_eTypeError = rb_define_class("TypeError", rb_eStandardError);
2900 rb_eArgError = rb_define_class("ArgumentError", rb_eStandardError);
2901 rb_eIndexError = rb_define_class("IndexError", rb_eStandardError);
2902 rb_eKeyError = rb_define_class("KeyError", rb_eIndexError);
2903 rb_define_method(rb_eKeyError, "initialize", key_err_initialize, -1);
2904 rb_define_method(rb_eKeyError, "receiver", key_err_receiver, 0);
2905 rb_define_method(rb_eKeyError, "key", key_err_key, 0);
2906 rb_eRangeError = rb_define_class("RangeError", rb_eStandardError);
2908 rb_eScriptError = rb_define_class("ScriptError", rb_eException);
2909 rb_eSyntaxError = rb_define_class("SyntaxError", rb_eScriptError);
2910 rb_define_method(rb_eSyntaxError, "initialize", syntax_error_initialize, -1);
2912 rb_eLoadError = rb_define_class("LoadError", rb_eScriptError);
2913 /* the path failed to load */
2914 rb_attr(rb_eLoadError, rb_intern_const("path"), 1, 0, Qfalse);
2916 rb_eNotImpError = rb_define_class("NotImplementedError", rb_eScriptError);
2918 rb_eNameError = rb_define_class("NameError", rb_eStandardError);
2919 rb_define_method(rb_eNameError, "initialize", name_err_initialize, -1);
2920 rb_define_method(rb_eNameError, "name", name_err_name, 0);
2921 rb_define_method(rb_eNameError, "receiver", name_err_receiver, 0);
2922 rb_define_method(rb_eNameError, "local_variables", name_err_local_variables, 0);
2923 rb_cNameErrorMesg = rb_define_class_under(rb_eNameError, "message", rb_cObject);
2924 rb_define_alloc_func(rb_cNameErrorMesg, name_err_mesg_alloc);
2925 rb_define_method(rb_cNameErrorMesg, "initialize_copy", name_err_mesg_init_copy, 1);
2926 rb_define_method(rb_cNameErrorMesg, "==", name_err_mesg_equal, 1);
2927 rb_define_method(rb_cNameErrorMesg, "to_str", name_err_mesg_to_str, 0);
2928 rb_define_method(rb_cNameErrorMesg, "_dump", name_err_mesg_dump, 1);
2929 rb_define_singleton_method(rb_cNameErrorMesg, "_load", name_err_mesg_load, 1);
2930 rb_eNoMethodError = rb_define_class("NoMethodError", rb_eNameError);
2931 rb_define_method(rb_eNoMethodError, "initialize", nometh_err_initialize, -1);
2932 rb_define_method(rb_eNoMethodError, "args", nometh_err_args, 0);
2933 rb_define_method(rb_eNoMethodError, "private_call?", nometh_err_private_call_p, 0);
2935 rb_eRuntimeError = rb_define_class("RuntimeError", rb_eStandardError);
2936 rb_eFrozenError = rb_define_class("FrozenError", rb_eRuntimeError);
2937 rb_define_method(rb_eFrozenError, "initialize", frozen_err_initialize, -1);
2938 rb_define_method(rb_eFrozenError, "receiver", frozen_err_receiver, 0);
2939 rb_eSecurityError = rb_define_class("SecurityError", rb_eException);
2940 rb_eNoMemError = rb_define_class("NoMemoryError", rb_eException);
2941 rb_eEncodingError = rb_define_class("EncodingError", rb_eStandardError);
2942 rb_eEncCompatError = rb_define_class_under(rb_cEncoding, "CompatibilityError", rb_eEncodingError);
2943 rb_eNoMatchingPatternError = rb_define_class("NoMatchingPatternError", rb_eStandardError);
2944 rb_eNoMatchingPatternKeyError = rb_define_class("NoMatchingPatternKeyError", rb_eNoMatchingPatternError);
2945 rb_define_method(rb_eNoMatchingPatternKeyError, "initialize", no_matching_pattern_key_err_initialize, -1);
2946 rb_define_method(rb_eNoMatchingPatternKeyError, "matchee", no_matching_pattern_key_err_matchee, 0);
2947 rb_define_method(rb_eNoMatchingPatternKeyError, "key", no_matching_pattern_key_err_key, 0);
2949 syserr_tbl = st_init_numtable();
2950 rb_eSystemCallError = rb_define_class("SystemCallError", rb_eStandardError);
2951 rb_define_method(rb_eSystemCallError, "initialize", syserr_initialize, -1);
2952 rb_define_method(rb_eSystemCallError, "errno", syserr_errno, 0);
2953 rb_define_singleton_method(rb_eSystemCallError, "===", syserr_eqq, 1);
2955 rb_mErrno = rb_define_module("Errno");
2957 rb_mWarning = rb_define_module("Warning");
2958 rb_define_singleton_method(rb_mWarning, "[]", rb_warning_s_aref, 1);
2959 rb_define_singleton_method(rb_mWarning, "[]=", rb_warning_s_aset, 2);
2960 rb_define_method(rb_mWarning, "warn", rb_warning_s_warn, -1);
2961 rb_extend_object(rb_mWarning, rb_mWarning);
2963 /* :nodoc: */
2964 rb_cWarningBuffer = rb_define_class_under(rb_mWarning, "buffer", rb_cString);
2965 rb_define_method(rb_cWarningBuffer, "write", warning_write, -1);
2967 id_cause = rb_intern_const("cause");
2968 id_message = rb_intern_const("message");
2969 id_backtrace = rb_intern_const("backtrace");
2970 id_key = rb_intern_const("key");
2971 id_matchee = rb_intern_const("matchee");
2972 id_args = rb_intern_const("args");
2973 id_receiver = rb_intern_const("receiver");
2974 id_private_call_p = rb_intern_const("private_call?");
2975 id_local_variables = rb_intern_const("local_variables");
2976 id_Errno = rb_intern_const("Errno");
2977 id_errno = rb_intern_const("errno");
2978 id_i_path = rb_intern_const("@path");
2979 id_warn = rb_intern_const("warn");
2980 id_category = rb_intern_const("category");
2981 id_deprecated = rb_intern_const("deprecated");
2982 id_experimental = rb_intern_const("experimental");
2983 id_top = rb_intern_const("top");
2984 id_bottom = rb_intern_const("bottom");
2985 id_iseq = rb_make_internal_id();
2986 id_recv = rb_make_internal_id();
2988 sym_category = ID2SYM(id_category);
2990 warning_categories.id2enum = rb_init_identtable();
2991 st_add_direct(warning_categories.id2enum, id_deprecated, RB_WARN_CATEGORY_DEPRECATED);
2992 st_add_direct(warning_categories.id2enum, id_experimental, RB_WARN_CATEGORY_EXPERIMENTAL);
2994 warning_categories.enum2id = rb_init_identtable();
2995 st_add_direct(warning_categories.enum2id, RB_WARN_CATEGORY_NONE, 0);
2996 st_add_direct(warning_categories.enum2id, RB_WARN_CATEGORY_DEPRECATED, id_deprecated);
2997 st_add_direct(warning_categories.enum2id, RB_WARN_CATEGORY_EXPERIMENTAL, id_experimental);
3000 void
3001 rb_enc_raise(rb_encoding *enc, VALUE exc, const char *fmt, ...)
3003 va_list args;
3004 VALUE mesg;
3006 va_start(args, fmt);
3007 mesg = rb_enc_vsprintf(enc, fmt, args);
3008 va_end(args);
3010 rb_exc_raise(rb_exc_new3(exc, mesg));
3013 void
3014 rb_vraise(VALUE exc, const char *fmt, va_list ap)
3016 rb_exc_raise(rb_exc_new3(exc, rb_vsprintf(fmt, ap)));
3019 void
3020 rb_raise(VALUE exc, const char *fmt, ...)
3022 va_list args;
3023 va_start(args, fmt);
3024 rb_vraise(exc, fmt, args);
3025 va_end(args);
3028 NORETURN(static void raise_loaderror(VALUE path, VALUE mesg));
3030 static void
3031 raise_loaderror(VALUE path, VALUE mesg)
3033 VALUE err = rb_exc_new3(rb_eLoadError, mesg);
3034 rb_ivar_set(err, id_i_path, path);
3035 rb_exc_raise(err);
3038 void
3039 rb_loaderror(const char *fmt, ...)
3041 va_list args;
3042 VALUE mesg;
3044 va_start(args, fmt);
3045 mesg = rb_enc_vsprintf(rb_locale_encoding(), fmt, args);
3046 va_end(args);
3047 raise_loaderror(Qnil, mesg);
3050 void
3051 rb_loaderror_with_path(VALUE path, const char *fmt, ...)
3053 va_list args;
3054 VALUE mesg;
3056 va_start(args, fmt);
3057 mesg = rb_enc_vsprintf(rb_locale_encoding(), fmt, args);
3058 va_end(args);
3059 raise_loaderror(path, mesg);
3062 void
3063 rb_notimplement(void)
3065 rb_raise(rb_eNotImpError,
3066 "%"PRIsVALUE"() function is unimplemented on this machine",
3067 rb_id2str(rb_frame_this_func()));
3070 void
3071 rb_fatal(const char *fmt, ...)
3073 va_list args;
3074 VALUE mesg;
3076 if (! ruby_thread_has_gvl_p()) {
3077 /* The thread has no GVL. Object allocation impossible (cant run GC),
3078 * thus no message can be printed out. */
3079 fprintf(stderr, "[FATAL] rb_fatal() outside of GVL\n");
3080 rb_print_backtrace();
3081 die();
3084 va_start(args, fmt);
3085 mesg = rb_vsprintf(fmt, args);
3086 va_end(args);
3088 rb_exc_fatal(rb_exc_new3(rb_eFatal, mesg));
3091 static VALUE
3092 make_errno_exc(const char *mesg)
3094 int n = errno;
3096 errno = 0;
3097 if (n == 0) {
3098 rb_bug("rb_sys_fail(%s) - errno == 0", mesg ? mesg : "");
3100 return rb_syserr_new(n, mesg);
3103 static VALUE
3104 make_errno_exc_str(VALUE mesg)
3106 int n = errno;
3108 errno = 0;
3109 if (!mesg) mesg = Qnil;
3110 if (n == 0) {
3111 const char *s = !NIL_P(mesg) ? RSTRING_PTR(mesg) : "";
3112 rb_bug("rb_sys_fail_str(%s) - errno == 0", s);
3114 return rb_syserr_new_str(n, mesg);
3117 VALUE
3118 rb_syserr_new(int n, const char *mesg)
3120 VALUE arg;
3121 arg = mesg ? rb_str_new2(mesg) : Qnil;
3122 return rb_syserr_new_str(n, arg);
3125 VALUE
3126 rb_syserr_new_str(int n, VALUE arg)
3128 return rb_class_new_instance(1, &arg, get_syserr(n));
3131 void
3132 rb_syserr_fail(int e, const char *mesg)
3134 rb_exc_raise(rb_syserr_new(e, mesg));
3137 void
3138 rb_syserr_fail_str(int e, VALUE mesg)
3140 rb_exc_raise(rb_syserr_new_str(e, mesg));
3143 void
3144 rb_sys_fail(const char *mesg)
3146 rb_exc_raise(make_errno_exc(mesg));
3149 void
3150 rb_sys_fail_str(VALUE mesg)
3152 rb_exc_raise(make_errno_exc_str(mesg));
3155 #ifdef RUBY_FUNCTION_NAME_STRING
3156 void
3157 rb_sys_fail_path_in(const char *func_name, VALUE path)
3159 int n = errno;
3161 errno = 0;
3162 rb_syserr_fail_path_in(func_name, n, path);
3165 void
3166 rb_syserr_fail_path_in(const char *func_name, int n, VALUE path)
3168 rb_exc_raise(rb_syserr_new_path_in(func_name, n, path));
3171 VALUE
3172 rb_syserr_new_path_in(const char *func_name, int n, VALUE path)
3174 VALUE args[2];
3176 if (!path) path = Qnil;
3177 if (n == 0) {
3178 const char *s = !NIL_P(path) ? RSTRING_PTR(path) : "";
3179 if (!func_name) func_name = "(null)";
3180 rb_bug("rb_sys_fail_path_in(%s, %s) - errno == 0",
3181 func_name, s);
3183 args[0] = path;
3184 args[1] = rb_str_new_cstr(func_name);
3185 return rb_class_new_instance(2, args, get_syserr(n));
3187 #endif
3189 NORETURN(static void rb_mod_exc_raise(VALUE exc, VALUE mod));
3191 static void
3192 rb_mod_exc_raise(VALUE exc, VALUE mod)
3194 rb_extend_object(exc, mod);
3195 rb_exc_raise(exc);
3198 void
3199 rb_mod_sys_fail(VALUE mod, const char *mesg)
3201 VALUE exc = make_errno_exc(mesg);
3202 rb_mod_exc_raise(exc, mod);
3205 void
3206 rb_mod_sys_fail_str(VALUE mod, VALUE mesg)
3208 VALUE exc = make_errno_exc_str(mesg);
3209 rb_mod_exc_raise(exc, mod);
3212 void
3213 rb_mod_syserr_fail(VALUE mod, int e, const char *mesg)
3215 VALUE exc = rb_syserr_new(e, mesg);
3216 rb_mod_exc_raise(exc, mod);
3219 void
3220 rb_mod_syserr_fail_str(VALUE mod, int e, VALUE mesg)
3222 VALUE exc = rb_syserr_new_str(e, mesg);
3223 rb_mod_exc_raise(exc, mod);
3226 static void
3227 syserr_warning(VALUE mesg, int err)
3229 rb_str_set_len(mesg, RSTRING_LEN(mesg)-1);
3230 rb_str_catf(mesg, ": %s\n", strerror(err));
3231 rb_write_warning_str(mesg);
3234 #if 0
3235 void
3236 rb_sys_warn(const char *fmt, ...)
3238 if (!NIL_P(ruby_verbose)) {
3239 int errno_save = errno;
3240 with_warning_string(mesg, 0, fmt) {
3241 syserr_warning(mesg, errno_save);
3243 errno = errno_save;
3247 void
3248 rb_syserr_warn(int err, const char *fmt, ...)
3250 if (!NIL_P(ruby_verbose)) {
3251 with_warning_string(mesg, 0, fmt) {
3252 syserr_warning(mesg, err);
3257 void
3258 rb_sys_enc_warn(rb_encoding *enc, const char *fmt, ...)
3260 if (!NIL_P(ruby_verbose)) {
3261 int errno_save = errno;
3262 with_warning_string(mesg, enc, fmt) {
3263 syserr_warning(mesg, errno_save);
3265 errno = errno_save;
3269 void
3270 rb_syserr_enc_warn(int err, rb_encoding *enc, const char *fmt, ...)
3272 if (!NIL_P(ruby_verbose)) {
3273 with_warning_string(mesg, enc, fmt) {
3274 syserr_warning(mesg, err);
3278 #endif
3280 void
3281 rb_sys_warning(const char *fmt, ...)
3283 if (RTEST(ruby_verbose)) {
3284 int errno_save = errno;
3285 with_warning_string(mesg, 0, fmt) {
3286 syserr_warning(mesg, errno_save);
3288 errno = errno_save;
3292 #if 0
3293 void
3294 rb_syserr_warning(int err, const char *fmt, ...)
3296 if (RTEST(ruby_verbose)) {
3297 with_warning_string(mesg, 0, fmt) {
3298 syserr_warning(mesg, err);
3302 #endif
3304 void
3305 rb_sys_enc_warning(rb_encoding *enc, const char *fmt, ...)
3307 if (RTEST(ruby_verbose)) {
3308 int errno_save = errno;
3309 with_warning_string(mesg, enc, fmt) {
3310 syserr_warning(mesg, errno_save);
3312 errno = errno_save;
3316 void
3317 rb_syserr_enc_warning(int err, rb_encoding *enc, const char *fmt, ...)
3319 if (RTEST(ruby_verbose)) {
3320 with_warning_string(mesg, enc, fmt) {
3321 syserr_warning(mesg, err);
3326 void
3327 rb_load_fail(VALUE path, const char *err)
3329 VALUE mesg = rb_str_buf_new_cstr(err);
3330 rb_str_cat2(mesg, " -- ");
3331 rb_str_append(mesg, path); /* should be ASCII compatible */
3332 raise_loaderror(path, mesg);
3335 void
3336 rb_error_frozen(const char *what)
3338 rb_raise(rb_eFrozenError, "can't modify frozen %s", what);
3341 void
3342 rb_frozen_error_raise(VALUE frozen_obj, const char *fmt, ...)
3344 va_list args;
3345 VALUE exc, mesg;
3347 va_start(args, fmt);
3348 mesg = rb_vsprintf(fmt, args);
3349 va_end(args);
3350 exc = rb_exc_new3(rb_eFrozenError, mesg);
3351 rb_ivar_set(exc, id_recv, frozen_obj);
3352 rb_exc_raise(exc);
3355 static VALUE
3356 inspect_frozen_obj(VALUE obj, VALUE mesg, int recur)
3358 if (recur) {
3359 rb_str_cat_cstr(mesg, " ...");
3361 else {
3362 rb_str_append(mesg, rb_inspect(obj));
3364 return mesg;
3367 void
3368 rb_error_frozen_object(VALUE frozen_obj)
3370 VALUE debug_info;
3371 const ID created_info = id_debug_created_info;
3372 VALUE mesg = rb_sprintf("can't modify frozen %"PRIsVALUE": ",
3373 CLASS_OF(frozen_obj));
3374 VALUE exc = rb_exc_new_str(rb_eFrozenError, mesg);
3376 rb_ivar_set(exc, id_recv, frozen_obj);
3377 rb_exec_recursive(inspect_frozen_obj, frozen_obj, mesg);
3379 if (!NIL_P(debug_info = rb_attr_get(frozen_obj, created_info))) {
3380 VALUE path = rb_ary_entry(debug_info, 0);
3381 VALUE line = rb_ary_entry(debug_info, 1);
3383 rb_str_catf(mesg, ", created at %"PRIsVALUE":%"PRIsVALUE, path, line);
3385 rb_exc_raise(exc);
3388 #undef rb_check_frozen
3389 void
3390 rb_check_frozen(VALUE obj)
3392 rb_check_frozen_internal(obj);
3395 void
3396 rb_check_copyable(VALUE obj, VALUE orig)
3398 if (!FL_ABLE(obj)) return;
3399 rb_check_frozen_internal(obj);
3400 if (!FL_ABLE(orig)) return;
3403 void
3404 Init_syserr(void)
3406 rb_eNOERROR = set_syserr(0, "NOERROR");
3407 #define defined_error(name, num) set_syserr((num), (name));
3408 #define undefined_error(name) set_syserr(0, (name));
3409 #include "known_errors.inc"
3410 #undef defined_error
3411 #undef undefined_error
3414 #include "warning.rbinc"
3417 * \}