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