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