diagnostics: add line numbers to source (PR other/84889)
[official-gcc.git] / gcc / diagnostic.c
blobe9d93d531d5125c5d3d15d455e49a847d9fecf71
1 /* Language-independent diagnostic subroutines for the GNU Compiler Collection
2 Copyright (C) 1999-2018 Free Software Foundation, Inc.
3 Contributed by Gabriel Dos Reis <gdr@codesourcery.com>
5 This file is part of GCC.
7 GCC is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 3, or (at your option) any later
10 version.
12 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 for more details.
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>. */
22 /* This file implements the language independent aspect of diagnostic
23 message module. */
25 #include "config.h"
26 #include "system.h"
27 #include "coretypes.h"
28 #include "version.h"
29 #include "demangle.h"
30 #include "intl.h"
31 #include "backtrace.h"
32 #include "diagnostic.h"
33 #include "diagnostic-color.h"
34 #include "edit-context.h"
35 #include "selftest.h"
36 #include "selftest-diagnostic.h"
38 #ifdef HAVE_TERMIOS_H
39 # include <termios.h>
40 #endif
42 #ifdef GWINSZ_IN_SYS_IOCTL
43 # include <sys/ioctl.h>
44 #endif
46 #define pedantic_warning_kind(DC) \
47 ((DC)->pedantic_errors ? DK_ERROR : DK_WARNING)
48 #define permissive_error_kind(DC) ((DC)->permissive ? DK_WARNING : DK_ERROR)
49 #define permissive_error_option(DC) ((DC)->opt_permissive)
51 /* Prototypes. */
52 static bool diagnostic_impl (rich_location *, int, const char *,
53 va_list *, diagnostic_t) ATTRIBUTE_GCC_DIAG(3,0);
54 static bool diagnostic_n_impl (rich_location *, int, unsigned HOST_WIDE_INT,
55 const char *, const char *, va_list *,
56 diagnostic_t) ATTRIBUTE_GCC_DIAG(5,0);
58 static void error_recursion (diagnostic_context *) ATTRIBUTE_NORETURN;
59 static void real_abort (void) ATTRIBUTE_NORETURN;
61 /* Name of program invoked, sans directories. */
63 const char *progname;
65 /* A diagnostic_context surrogate for stderr. */
66 static diagnostic_context global_diagnostic_context;
67 diagnostic_context *global_dc = &global_diagnostic_context;
69 /* Return a malloc'd string containing MSG formatted a la printf. The
70 caller is responsible for freeing the memory. */
71 char *
72 build_message_string (const char *msg, ...)
74 char *str;
75 va_list ap;
77 va_start (ap, msg);
78 str = xvasprintf (msg, ap);
79 va_end (ap);
81 return str;
84 /* Same as diagnostic_build_prefix, but only the source FILE is given. */
85 char *
86 file_name_as_prefix (diagnostic_context *context, const char *f)
88 const char *locus_cs
89 = colorize_start (pp_show_color (context->printer), "locus");
90 const char *locus_ce = colorize_stop (pp_show_color (context->printer));
91 return build_message_string ("%s%s:%s ", locus_cs, f, locus_ce);
96 /* Return the value of the getenv("COLUMNS") as an integer. If the
97 value is not set to a positive integer, use ioctl to get the
98 terminal width. If it fails, return INT_MAX. */
99 int
100 get_terminal_width (void)
102 const char * s = getenv ("COLUMNS");
103 if (s != NULL) {
104 int n = atoi (s);
105 if (n > 0)
106 return n;
109 #ifdef TIOCGWINSZ
110 struct winsize w;
111 w.ws_col = 0;
112 if (ioctl (0, TIOCGWINSZ, &w) == 0 && w.ws_col > 0)
113 return w.ws_col;
114 #endif
116 return INT_MAX;
119 /* Set caret_max_width to value. */
120 void
121 diagnostic_set_caret_max_width (diagnostic_context *context, int value)
123 /* One minus to account for the leading empty space. */
124 value = value ? value - 1
125 : (isatty (fileno (pp_buffer (context->printer)->stream))
126 ? get_terminal_width () - 1: INT_MAX);
128 if (value <= 0)
129 value = INT_MAX;
131 context->caret_max_width = value;
134 /* Initialize the diagnostic message outputting machinery. */
135 void
136 diagnostic_initialize (diagnostic_context *context, int n_opts)
138 int i;
140 /* Allocate a basic pretty-printer. Clients will replace this a
141 much more elaborated pretty-printer if they wish. */
142 context->printer = XNEW (pretty_printer);
143 new (context->printer) pretty_printer ();
145 memset (context->diagnostic_count, 0, sizeof context->diagnostic_count);
146 context->warning_as_error_requested = false;
147 context->n_opts = n_opts;
148 context->classify_diagnostic = XNEWVEC (diagnostic_t, n_opts);
149 for (i = 0; i < n_opts; i++)
150 context->classify_diagnostic[i] = DK_UNSPECIFIED;
151 context->show_caret = false;
152 diagnostic_set_caret_max_width (context, pp_line_cutoff (context->printer));
153 for (i = 0; i < rich_location::STATICALLY_ALLOCATED_RANGES; i++)
154 context->caret_chars[i] = '^';
155 context->show_option_requested = false;
156 context->abort_on_error = false;
157 context->show_column = false;
158 context->pedantic_errors = false;
159 context->permissive = false;
160 context->opt_permissive = 0;
161 context->fatal_errors = false;
162 context->dc_inhibit_warnings = false;
163 context->dc_warn_system_headers = false;
164 context->max_errors = 0;
165 context->internal_error = NULL;
166 diagnostic_starter (context) = default_diagnostic_starter;
167 context->start_span = default_diagnostic_start_span_fn;
168 diagnostic_finalizer (context) = default_diagnostic_finalizer;
169 context->option_enabled = NULL;
170 context->option_state = NULL;
171 context->option_name = NULL;
172 context->last_location = UNKNOWN_LOCATION;
173 context->last_module = 0;
174 context->x_data = NULL;
175 context->lock = 0;
176 context->inhibit_notes_p = false;
177 context->colorize_source_p = false;
178 context->show_line_numbers_p = false;
179 context->show_ruler_p = false;
180 context->parseable_fixits_p = false;
181 context->edit_context_ptr = NULL;
184 /* Maybe initialize the color support. We require clients to do this
185 explicitly, since most clients don't want color. When called
186 without a VALUE, it initializes with DIAGNOSTICS_COLOR_DEFAULT. */
188 void
189 diagnostic_color_init (diagnostic_context *context, int value /*= -1 */)
191 /* value == -1 is the default value. */
192 if (value < 0)
194 /* If DIAGNOSTICS_COLOR_DEFAULT is -1, default to
195 -fdiagnostics-color=auto if GCC_COLORS is in the environment,
196 otherwise default to -fdiagnostics-color=never, for other
197 values default to that
198 -fdiagnostics-color={never,auto,always}. */
199 if (DIAGNOSTICS_COLOR_DEFAULT == -1)
201 if (!getenv ("GCC_COLORS"))
202 return;
203 value = DIAGNOSTICS_COLOR_AUTO;
205 else
206 value = DIAGNOSTICS_COLOR_DEFAULT;
208 pp_show_color (context->printer)
209 = colorize_init ((diagnostic_color_rule_t) value);
212 /* Do any cleaning up required after the last diagnostic is emitted. */
214 void
215 diagnostic_finish (diagnostic_context *context)
217 /* Some of the errors may actually have been warnings. */
218 if (diagnostic_kind_count (context, DK_WERROR))
220 /* -Werror was given. */
221 if (context->warning_as_error_requested)
222 pp_verbatim (context->printer,
223 _("%s: all warnings being treated as errors"),
224 progname);
225 /* At least one -Werror= was given. */
226 else
227 pp_verbatim (context->printer,
228 _("%s: some warnings being treated as errors"),
229 progname);
230 pp_newline_and_flush (context->printer);
233 diagnostic_file_cache_fini ();
235 XDELETEVEC (context->classify_diagnostic);
236 context->classify_diagnostic = NULL;
238 /* diagnostic_initialize allocates context->printer using XNEW
239 and placement-new. */
240 context->printer->~pretty_printer ();
241 XDELETE (context->printer);
242 context->printer = NULL;
244 if (context->edit_context_ptr)
246 delete context->edit_context_ptr;
247 context->edit_context_ptr = NULL;
251 /* Initialize DIAGNOSTIC, where the message MSG has already been
252 translated. */
253 void
254 diagnostic_set_info_translated (diagnostic_info *diagnostic, const char *msg,
255 va_list *args, rich_location *richloc,
256 diagnostic_t kind)
258 gcc_assert (richloc);
259 diagnostic->message.err_no = errno;
260 diagnostic->message.args_ptr = args;
261 diagnostic->message.format_spec = msg;
262 diagnostic->message.m_richloc = richloc;
263 diagnostic->richloc = richloc;
264 diagnostic->kind = kind;
265 diagnostic->option_index = 0;
268 /* Initialize DIAGNOSTIC, where the message GMSGID has not yet been
269 translated. */
270 void
271 diagnostic_set_info (diagnostic_info *diagnostic, const char *gmsgid,
272 va_list *args, rich_location *richloc,
273 diagnostic_t kind)
275 gcc_assert (richloc);
276 diagnostic_set_info_translated (diagnostic, _(gmsgid), args, richloc, kind);
279 static const char *const diagnostic_kind_color[] = {
280 #define DEFINE_DIAGNOSTIC_KIND(K, T, C) (C),
281 #include "diagnostic.def"
282 #undef DEFINE_DIAGNOSTIC_KIND
283 NULL
286 /* Get a color name for diagnostics of type KIND
287 Result could be NULL. */
289 const char *
290 diagnostic_get_color_for_kind (diagnostic_t kind)
292 return diagnostic_kind_color[kind];
295 /* Return a formatted line and column ':%line:%column'. Elided if
296 zero. The result is a statically allocated buffer. */
298 static const char *
299 maybe_line_and_column (int line, int col)
301 static char result[32];
303 if (line)
305 size_t l = snprintf (result, sizeof (result),
306 col ? ":%d:%d" : ":%d", line, col);
307 gcc_checking_assert (l < sizeof (result));
309 else
310 result[0] = 0;
311 return result;
314 /* Return a malloc'd string describing a location e.g. "foo.c:42:10".
315 The caller is responsible for freeing the memory. */
317 static char *
318 diagnostic_get_location_text (diagnostic_context *context,
319 expanded_location s)
321 pretty_printer *pp = context->printer;
322 const char *locus_cs = colorize_start (pp_show_color (pp), "locus");
323 const char *locus_ce = colorize_stop (pp_show_color (pp));
324 const char *file = s.file ? s.file : progname;
325 int line = strcmp (file, N_("<built-in>")) ? s.line : 0;
326 int col = context->show_column ? s.column : 0;
328 const char *line_col = maybe_line_and_column (line, col);
329 return build_message_string ("%s%s%s:%s", locus_cs, file,
330 line_col, locus_ce);
333 /* Return a malloc'd string describing a location and the severity of the
334 diagnostic, e.g. "foo.c:42:10: error: ". The caller is responsible for
335 freeing the memory. */
336 char *
337 diagnostic_build_prefix (diagnostic_context *context,
338 const diagnostic_info *diagnostic)
340 static const char *const diagnostic_kind_text[] = {
341 #define DEFINE_DIAGNOSTIC_KIND(K, T, C) (T),
342 #include "diagnostic.def"
343 #undef DEFINE_DIAGNOSTIC_KIND
344 "must-not-happen"
346 gcc_assert (diagnostic->kind < DK_LAST_DIAGNOSTIC_KIND);
348 const char *text = _(diagnostic_kind_text[diagnostic->kind]);
349 const char *text_cs = "", *text_ce = "";
350 pretty_printer *pp = context->printer;
352 if (diagnostic_kind_color[diagnostic->kind])
354 text_cs = colorize_start (pp_show_color (pp),
355 diagnostic_kind_color[diagnostic->kind]);
356 text_ce = colorize_stop (pp_show_color (pp));
359 expanded_location s = diagnostic_expand_location (diagnostic);
360 char *location_text = diagnostic_get_location_text (context, s);
362 char *result = build_message_string ("%s %s%s%s", location_text,
363 text_cs, text, text_ce);
364 free (location_text);
365 return result;
368 /* Functions at which to stop the backtrace print. It's not
369 particularly helpful to print the callers of these functions. */
371 static const char * const bt_stop[] =
373 "main",
374 "toplev::main",
375 "execute_one_pass",
376 "compile_file",
379 /* A callback function passed to the backtrace_full function. */
381 static int
382 bt_callback (void *data, uintptr_t pc, const char *filename, int lineno,
383 const char *function)
385 int *pcount = (int *) data;
387 /* If we don't have any useful information, don't print
388 anything. */
389 if (filename == NULL && function == NULL)
390 return 0;
392 /* Skip functions in diagnostic.c. */
393 if (*pcount == 0
394 && filename != NULL
395 && strcmp (lbasename (filename), "diagnostic.c") == 0)
396 return 0;
398 /* Print up to 20 functions. We could make this a --param, but
399 since this is only for debugging just use a constant for now. */
400 if (*pcount >= 20)
402 /* Returning a non-zero value stops the backtrace. */
403 return 1;
405 ++*pcount;
407 char *alc = NULL;
408 if (function != NULL)
410 char *str = cplus_demangle_v3 (function,
411 (DMGL_VERBOSE | DMGL_ANSI
412 | DMGL_GNU_V3 | DMGL_PARAMS));
413 if (str != NULL)
415 alc = str;
416 function = str;
419 for (size_t i = 0; i < ARRAY_SIZE (bt_stop); ++i)
421 size_t len = strlen (bt_stop[i]);
422 if (strncmp (function, bt_stop[i], len) == 0
423 && (function[len] == '\0' || function[len] == '('))
425 if (alc != NULL)
426 free (alc);
427 /* Returning a non-zero value stops the backtrace. */
428 return 1;
433 fprintf (stderr, "0x%lx %s\n\t%s:%d\n",
434 (unsigned long) pc,
435 function == NULL ? "???" : function,
436 filename == NULL ? "???" : filename,
437 lineno);
439 if (alc != NULL)
440 free (alc);
442 return 0;
445 /* A callback function passed to the backtrace_full function. This is
446 called if backtrace_full has an error. */
448 static void
449 bt_err_callback (void *data ATTRIBUTE_UNUSED, const char *msg, int errnum)
451 if (errnum < 0)
453 /* This means that no debug info was available. Just quietly
454 skip printing backtrace info. */
455 return;
457 fprintf (stderr, "%s%s%s\n", msg, errnum == 0 ? "" : ": ",
458 errnum == 0 ? "" : xstrerror (errnum));
461 /* Check if we've met the maximum error limit, and if so fatally exit
462 with a message. CONTEXT is the context to check, and FLUSH
463 indicates whether a diagnostic_finish call is needed. */
465 void
466 diagnostic_check_max_errors (diagnostic_context *context, bool flush)
468 if (!context->max_errors)
469 return;
471 int count = (diagnostic_kind_count (context, DK_ERROR)
472 + diagnostic_kind_count (context, DK_SORRY)
473 + diagnostic_kind_count (context, DK_WERROR));
475 if (count >= context->max_errors)
477 fnotice (stderr,
478 "compilation terminated due to -fmax-errors=%u.\n",
479 context->max_errors);
480 if (flush)
481 diagnostic_finish (context);
482 exit (FATAL_EXIT_CODE);
486 /* Take any action which is expected to happen after the diagnostic
487 is written out. This function does not always return. */
488 void
489 diagnostic_action_after_output (diagnostic_context *context,
490 diagnostic_t diag_kind)
492 switch (diag_kind)
494 case DK_DEBUG:
495 case DK_NOTE:
496 case DK_ANACHRONISM:
497 case DK_WARNING:
498 break;
500 case DK_ERROR:
501 case DK_SORRY:
502 if (context->abort_on_error)
503 real_abort ();
504 if (context->fatal_errors)
506 fnotice (stderr, "compilation terminated due to -Wfatal-errors.\n");
507 diagnostic_finish (context);
508 exit (FATAL_EXIT_CODE);
510 break;
512 case DK_ICE:
513 case DK_ICE_NOBT:
515 struct backtrace_state *state = NULL;
516 if (diag_kind == DK_ICE)
517 state = backtrace_create_state (NULL, 0, bt_err_callback, NULL);
518 int count = 0;
519 if (state != NULL)
520 backtrace_full (state, 2, bt_callback, bt_err_callback,
521 (void *) &count);
523 if (context->abort_on_error)
524 real_abort ();
526 fnotice (stderr, "Please submit a full bug report,\n"
527 "with preprocessed source if appropriate.\n");
528 if (count > 0)
529 fnotice (stderr,
530 ("Please include the complete backtrace "
531 "with any bug report.\n"));
532 fnotice (stderr, "See %s for instructions.\n", bug_report_url);
534 exit (ICE_EXIT_CODE);
537 case DK_FATAL:
538 if (context->abort_on_error)
539 real_abort ();
540 diagnostic_finish (context);
541 fnotice (stderr, "compilation terminated.\n");
542 exit (FATAL_EXIT_CODE);
544 default:
545 gcc_unreachable ();
549 /* True if the last module or file in which a diagnostic was reported is
550 different from the current one. */
552 static bool
553 last_module_changed_p (diagnostic_context *context,
554 const line_map_ordinary *map)
556 return context->last_module != map;
559 /* Remember the current module or file as being the last one in which we
560 report a diagnostic. */
562 static void
563 set_last_module (diagnostic_context *context, const line_map_ordinary *map)
565 context->last_module = map;
568 void
569 diagnostic_report_current_module (diagnostic_context *context, location_t where)
571 const line_map_ordinary *map = NULL;
573 if (pp_needs_newline (context->printer))
575 pp_newline (context->printer);
576 pp_needs_newline (context->printer) = false;
579 if (where <= BUILTINS_LOCATION)
580 return;
582 linemap_resolve_location (line_table, where,
583 LRK_MACRO_DEFINITION_LOCATION,
584 &map);
586 if (map && last_module_changed_p (context, map))
588 set_last_module (context, map);
589 if (! MAIN_FILE_P (map))
591 bool first = true;
594 where = linemap_included_from (map);
595 map = linemap_included_from_linemap (line_table, map);
596 const char *line_col
597 = maybe_line_and_column (SOURCE_LINE (map, where),
598 first && context->show_column
599 ? SOURCE_COLUMN (map, where) : 0);
600 static const char *const msgs[] =
602 N_("In file included from"),
603 N_(" from"),
605 unsigned index = !first;
606 pp_verbatim (context->printer, "%s%s %r%s%s%R",
607 first ? "" : ",\n", _(msgs[index]),
608 "locus", LINEMAP_FILE (map), line_col);
609 first = false;
611 while (! MAIN_FILE_P (map));
612 pp_verbatim (context->printer, ":");
613 pp_newline (context->printer);
618 void
619 default_diagnostic_starter (diagnostic_context *context,
620 diagnostic_info *diagnostic)
622 diagnostic_report_current_module (context, diagnostic_location (diagnostic));
623 pp_set_prefix (context->printer, diagnostic_build_prefix (context,
624 diagnostic));
627 void
628 default_diagnostic_start_span_fn (diagnostic_context *context,
629 expanded_location exploc)
631 pp_set_prefix (context->printer,
632 diagnostic_get_location_text (context, exploc));
633 pp_string (context->printer, "");
634 pp_newline (context->printer);
637 void
638 default_diagnostic_finalizer (diagnostic_context *context,
639 diagnostic_info *diagnostic)
641 diagnostic_show_locus (context, diagnostic->richloc, diagnostic->kind);
642 pp_destroy_prefix (context->printer);
643 pp_flush (context->printer);
646 /* Interface to specify diagnostic kind overrides. Returns the
647 previous setting, or DK_UNSPECIFIED if the parameters are out of
648 range. If OPTION_INDEX is zero, the new setting is for all the
649 diagnostics. */
650 diagnostic_t
651 diagnostic_classify_diagnostic (diagnostic_context *context,
652 int option_index,
653 diagnostic_t new_kind,
654 location_t where)
656 diagnostic_t old_kind;
658 if (option_index < 0
659 || option_index >= context->n_opts
660 || new_kind >= DK_LAST_DIAGNOSTIC_KIND)
661 return DK_UNSPECIFIED;
663 old_kind = context->classify_diagnostic[option_index];
665 /* Handle pragmas separately, since we need to keep track of *where*
666 the pragmas were. */
667 if (where != UNKNOWN_LOCATION)
669 int i;
671 /* Record the command-line status, so we can reset it back on DK_POP. */
672 if (old_kind == DK_UNSPECIFIED)
674 old_kind = !context->option_enabled (option_index,
675 context->option_state)
676 ? DK_IGNORED : (context->warning_as_error_requested
677 ? DK_ERROR : DK_WARNING);
678 context->classify_diagnostic[option_index] = old_kind;
681 for (i = context->n_classification_history - 1; i >= 0; i --)
682 if (context->classification_history[i].option == option_index)
684 old_kind = context->classification_history[i].kind;
685 break;
688 i = context->n_classification_history;
689 context->classification_history =
690 (diagnostic_classification_change_t *) xrealloc (context->classification_history, (i + 1)
691 * sizeof (diagnostic_classification_change_t));
692 context->classification_history[i].location = where;
693 context->classification_history[i].option = option_index;
694 context->classification_history[i].kind = new_kind;
695 context->n_classification_history ++;
697 else
698 context->classify_diagnostic[option_index] = new_kind;
700 return old_kind;
703 /* Save all diagnostic classifications in a stack. */
704 void
705 diagnostic_push_diagnostics (diagnostic_context *context, location_t where ATTRIBUTE_UNUSED)
707 context->push_list = (int *) xrealloc (context->push_list, (context->n_push + 1) * sizeof (int));
708 context->push_list[context->n_push ++] = context->n_classification_history;
711 /* Restore the topmost classification set off the stack. If the stack
712 is empty, revert to the state based on command line parameters. */
713 void
714 diagnostic_pop_diagnostics (diagnostic_context *context, location_t where)
716 int jump_to;
717 int i;
719 if (context->n_push)
720 jump_to = context->push_list [-- context->n_push];
721 else
722 jump_to = 0;
724 i = context->n_classification_history;
725 context->classification_history =
726 (diagnostic_classification_change_t *) xrealloc (context->classification_history, (i + 1)
727 * sizeof (diagnostic_classification_change_t));
728 context->classification_history[i].location = where;
729 context->classification_history[i].option = jump_to;
730 context->classification_history[i].kind = DK_POP;
731 context->n_classification_history ++;
734 /* Helper function for print_parseable_fixits. Print TEXT to PP, obeying the
735 escaping rules for -fdiagnostics-parseable-fixits. */
737 static void
738 print_escaped_string (pretty_printer *pp, const char *text)
740 gcc_assert (pp);
741 gcc_assert (text);
743 pp_character (pp, '"');
744 for (const char *ch = text; *ch; ch++)
746 switch (*ch)
748 case '\\':
749 /* Escape backslash as two backslashes. */
750 pp_string (pp, "\\\\");
751 break;
752 case '\t':
753 /* Escape tab as "\t". */
754 pp_string (pp, "\\t");
755 break;
756 case '\n':
757 /* Escape newline as "\n". */
758 pp_string (pp, "\\n");
759 break;
760 case '"':
761 /* Escape doublequotes as \". */
762 pp_string (pp, "\\\"");
763 break;
764 default:
765 if (ISPRINT (*ch))
766 pp_character (pp, *ch);
767 else
768 /* Use octal for non-printable chars. */
770 unsigned char c = (*ch & 0xff);
771 pp_printf (pp, "\\%o%o%o", (c / 64), (c / 8) & 007, c & 007);
773 break;
776 pp_character (pp, '"');
779 /* Implementation of -fdiagnostics-parseable-fixits. Print a
780 machine-parseable version of all fixits in RICHLOC to PP. */
782 static void
783 print_parseable_fixits (pretty_printer *pp, rich_location *richloc)
785 gcc_assert (pp);
786 gcc_assert (richloc);
788 for (unsigned i = 0; i < richloc->get_num_fixit_hints (); i++)
790 const fixit_hint *hint = richloc->get_fixit_hint (i);
791 source_location start_loc = hint->get_start_loc ();
792 expanded_location start_exploc = expand_location (start_loc);
793 pp_string (pp, "fix-it:");
794 print_escaped_string (pp, start_exploc.file);
795 /* For compatibility with clang, print as a half-open range. */
796 source_location next_loc = hint->get_next_loc ();
797 expanded_location next_exploc = expand_location (next_loc);
798 pp_printf (pp, ":{%i:%i-%i:%i}:",
799 start_exploc.line, start_exploc.column,
800 next_exploc.line, next_exploc.column);
801 print_escaped_string (pp, hint->get_string ());
802 pp_newline (pp);
806 /* Update the diag_class of DIAGNOSTIC based on its location
807 relative to any
808 #pragma GCC diagnostic
809 directives recorded within CONTEXT.
811 Return the new diag_class of DIAGNOSTIC if it was updated, or
812 DK_UNSPECIFIED otherwise. */
814 static diagnostic_t
815 update_effective_level_from_pragmas (diagnostic_context *context,
816 diagnostic_info *diagnostic)
818 diagnostic_t diag_class = DK_UNSPECIFIED;
820 if (context->n_classification_history > 0)
822 location_t location = diagnostic_location (diagnostic);
824 /* FIXME: Stupid search. Optimize later. */
825 for (int i = context->n_classification_history - 1; i >= 0; i --)
827 if (linemap_location_before_p
828 (line_table,
829 context->classification_history[i].location,
830 location))
832 if (context->classification_history[i].kind == (int) DK_POP)
834 i = context->classification_history[i].option;
835 continue;
837 int option = context->classification_history[i].option;
838 /* The option 0 is for all the diagnostics. */
839 if (option == 0 || option == diagnostic->option_index)
841 diag_class = context->classification_history[i].kind;
842 if (diag_class != DK_UNSPECIFIED)
843 diagnostic->kind = diag_class;
844 break;
850 return diag_class;
853 /* Print any metadata about the option used to control DIAGNOSTIC to CONTEXT's
854 printer, e.g. " [-Werror=uninitialized]".
855 Subroutine of diagnostic_report_diagnostic. */
857 static void
858 print_option_information (diagnostic_context *context,
859 const diagnostic_info *diagnostic,
860 diagnostic_t orig_diag_kind)
862 char *option_text;
864 option_text = context->option_name (context, diagnostic->option_index,
865 orig_diag_kind, diagnostic->kind);
867 if (option_text)
869 pretty_printer *pp = context->printer;
870 pp_string (pp, " [");
871 pp_string (pp, colorize_start (pp_show_color (pp),
872 diagnostic_kind_color[diagnostic->kind]));
873 pp_string (pp, option_text);
874 pp_string (pp, colorize_stop (pp_show_color (pp)));
875 pp_character (pp, ']');
876 free (option_text);
880 /* Report a diagnostic message (an error or a warning) as specified by
881 DC. This function is *the* subroutine in terms of which front-ends
882 should implement their specific diagnostic handling modules. The
883 front-end independent format specifiers are exactly those described
884 in the documentation of output_format.
885 Return true if a diagnostic was printed, false otherwise. */
887 bool
888 diagnostic_report_diagnostic (diagnostic_context *context,
889 diagnostic_info *diagnostic)
891 location_t location = diagnostic_location (diagnostic);
892 diagnostic_t orig_diag_kind = diagnostic->kind;
894 /* Give preference to being able to inhibit warnings, before they
895 get reclassified to something else. */
896 if ((diagnostic->kind == DK_WARNING || diagnostic->kind == DK_PEDWARN)
897 && !diagnostic_report_warnings_p (context, location))
898 return false;
900 if (diagnostic->kind == DK_PEDWARN)
902 diagnostic->kind = pedantic_warning_kind (context);
903 /* We do this to avoid giving the message for -pedantic-errors. */
904 orig_diag_kind = diagnostic->kind;
907 if (diagnostic->kind == DK_NOTE && context->inhibit_notes_p)
908 return false;
910 if (context->lock > 0)
912 /* If we're reporting an ICE in the middle of some other error,
913 try to flush out the previous error, then let this one
914 through. Don't do this more than once. */
915 if ((diagnostic->kind == DK_ICE || diagnostic->kind == DK_ICE_NOBT)
916 && context->lock == 1)
917 pp_newline_and_flush (context->printer);
918 else
919 error_recursion (context);
922 /* If the user requested that warnings be treated as errors, so be
923 it. Note that we do this before the next block so that
924 individual warnings can be overridden back to warnings with
925 -Wno-error=*. */
926 if (context->warning_as_error_requested
927 && diagnostic->kind == DK_WARNING)
928 diagnostic->kind = DK_ERROR;
930 if (diagnostic->option_index
931 && diagnostic->option_index != permissive_error_option (context))
933 /* This tests if the user provided the appropriate -Wfoo or
934 -Wno-foo option. */
935 if (! context->option_enabled (diagnostic->option_index,
936 context->option_state))
937 return false;
939 /* This tests for #pragma diagnostic changes. */
940 diagnostic_t diag_class
941 = update_effective_level_from_pragmas (context, diagnostic);
943 /* This tests if the user provided the appropriate -Werror=foo
944 option. */
945 if (diag_class == DK_UNSPECIFIED
946 && (context->classify_diagnostic[diagnostic->option_index]
947 != DK_UNSPECIFIED))
948 diagnostic->kind
949 = context->classify_diagnostic[diagnostic->option_index];
951 /* This allows for future extensions, like temporarily disabling
952 warnings for ranges of source code. */
953 if (diagnostic->kind == DK_IGNORED)
954 return false;
957 if (diagnostic->kind != DK_NOTE)
958 diagnostic_check_max_errors (context);
960 context->lock++;
962 if (diagnostic->kind == DK_ICE || diagnostic->kind == DK_ICE_NOBT)
964 /* When not checking, ICEs are converted to fatal errors when an
965 error has already occurred. This is counteracted by
966 abort_on_error. */
967 if (!CHECKING_P
968 && (diagnostic_kind_count (context, DK_ERROR) > 0
969 || diagnostic_kind_count (context, DK_SORRY) > 0)
970 && !context->abort_on_error)
972 expanded_location s
973 = expand_location (diagnostic_location (diagnostic));
974 fnotice (stderr, "%s:%d: confused by earlier errors, bailing out\n",
975 s.file, s.line);
976 exit (ICE_EXIT_CODE);
978 if (context->internal_error)
979 (*context->internal_error) (context,
980 diagnostic->message.format_spec,
981 diagnostic->message.args_ptr);
983 if (diagnostic->kind == DK_ERROR && orig_diag_kind == DK_WARNING)
984 ++diagnostic_kind_count (context, DK_WERROR);
985 else
986 ++diagnostic_kind_count (context, diagnostic->kind);
988 diagnostic->message.x_data = &diagnostic->x_data;
989 diagnostic->x_data = NULL;
990 pp_format (context->printer, &diagnostic->message);
991 (*diagnostic_starter (context)) (context, diagnostic);
992 pp_output_formatted_text (context->printer);
993 if (context->show_option_requested)
994 print_option_information (context, diagnostic, orig_diag_kind);
995 (*diagnostic_finalizer (context)) (context, diagnostic);
996 if (context->parseable_fixits_p)
998 print_parseable_fixits (context->printer, diagnostic->richloc);
999 pp_flush (context->printer);
1001 diagnostic_action_after_output (context, diagnostic->kind);
1002 diagnostic->x_data = NULL;
1004 if (context->edit_context_ptr)
1005 if (diagnostic->richloc->fixits_can_be_auto_applied_p ())
1006 context->edit_context_ptr->add_fixits (diagnostic->richloc);
1008 context->lock--;
1010 return true;
1013 /* Given a partial pathname as input, return another pathname that
1014 shares no directory elements with the pathname of __FILE__. This
1015 is used by fancy_abort() to print `Internal compiler error in expr.c'
1016 instead of `Internal compiler error in ../../GCC/gcc/expr.c'. */
1018 const char *
1019 trim_filename (const char *name)
1021 static const char this_file[] = __FILE__;
1022 const char *p = name, *q = this_file;
1024 /* First skip any "../" in each filename. This allows us to give a proper
1025 reference to a file in a subdirectory. */
1026 while (p[0] == '.' && p[1] == '.' && IS_DIR_SEPARATOR (p[2]))
1027 p += 3;
1029 while (q[0] == '.' && q[1] == '.' && IS_DIR_SEPARATOR (q[2]))
1030 q += 3;
1032 /* Now skip any parts the two filenames have in common. */
1033 while (*p == *q && *p != 0 && *q != 0)
1034 p++, q++;
1036 /* Now go backwards until the previous directory separator. */
1037 while (p > name && !IS_DIR_SEPARATOR (p[-1]))
1038 p--;
1040 return p;
1043 /* Standard error reporting routines in increasing order of severity.
1044 All of these take arguments like printf. */
1046 /* Text to be emitted verbatim to the error message stream; this
1047 produces no prefix and disables line-wrapping. Use rarely. */
1048 void
1049 verbatim (const char *gmsgid, ...)
1051 text_info text;
1052 va_list ap;
1054 va_start (ap, gmsgid);
1055 text.err_no = errno;
1056 text.args_ptr = &ap;
1057 text.format_spec = _(gmsgid);
1058 text.x_data = NULL;
1059 pp_format_verbatim (global_dc->printer, &text);
1060 pp_newline_and_flush (global_dc->printer);
1061 va_end (ap);
1064 /* Add a note with text GMSGID and with LOCATION to the diagnostic CONTEXT. */
1065 void
1066 diagnostic_append_note (diagnostic_context *context,
1067 location_t location,
1068 const char * gmsgid, ...)
1070 diagnostic_info diagnostic;
1071 va_list ap;
1072 rich_location richloc (line_table, location);
1074 va_start (ap, gmsgid);
1075 diagnostic_set_info (&diagnostic, gmsgid, &ap, &richloc, DK_NOTE);
1076 if (context->inhibit_notes_p)
1078 va_end (ap);
1079 return;
1081 char *saved_prefix = pp_take_prefix (context->printer);
1082 pp_set_prefix (context->printer,
1083 diagnostic_build_prefix (context, &diagnostic));
1084 pp_format (context->printer, &diagnostic.message);
1085 pp_output_formatted_text (context->printer);
1086 pp_destroy_prefix (context->printer);
1087 pp_set_prefix (context->printer, saved_prefix);
1088 diagnostic_show_locus (context, &richloc, DK_NOTE);
1089 va_end (ap);
1092 /* Implement emit_diagnostic, inform, warning, warning_at, pedwarn,
1093 permerror, error, error_at, error_at, sorry, fatal_error, internal_error,
1094 and internal_error_no_backtrace, as documented and defined below. */
1095 static bool
1096 diagnostic_impl (rich_location *richloc, int opt,
1097 const char *gmsgid,
1098 va_list *ap, diagnostic_t kind)
1100 diagnostic_info diagnostic;
1101 if (kind == DK_PERMERROR)
1103 diagnostic_set_info (&diagnostic, gmsgid, ap, richloc,
1104 permissive_error_kind (global_dc));
1105 diagnostic.option_index = permissive_error_option (global_dc);
1107 else
1109 diagnostic_set_info (&diagnostic, gmsgid, ap, richloc, kind);
1110 if (kind == DK_WARNING || kind == DK_PEDWARN)
1111 diagnostic.option_index = opt;
1113 return diagnostic_report_diagnostic (global_dc, &diagnostic);
1116 /* Implement inform_n, warning_n, and error_n, as documented and
1117 defined below. */
1118 static bool
1119 diagnostic_n_impl (rich_location *richloc, int opt, unsigned HOST_WIDE_INT n,
1120 const char *singular_gmsgid,
1121 const char *plural_gmsgid,
1122 va_list *ap, diagnostic_t kind)
1124 diagnostic_info diagnostic;
1125 unsigned long gtn;
1127 if (sizeof n <= sizeof gtn)
1128 gtn = n;
1129 else
1130 /* Use the largest number ngettext can handle, otherwise
1131 preserve the six least significant decimal digits for
1132 languages where the plural form depends on them. */
1133 gtn = n <= ULONG_MAX ? n : n % 1000000LU + 1000000LU;
1135 const char *text = ngettext (singular_gmsgid, plural_gmsgid, gtn);
1136 diagnostic_set_info_translated (&diagnostic, text, ap, richloc, kind);
1137 if (kind == DK_WARNING)
1138 diagnostic.option_index = opt;
1139 return diagnostic_report_diagnostic (global_dc, &diagnostic);
1142 /* Wrapper around diagnostic_impl taking a variable argument list. */
1144 bool
1145 emit_diagnostic (diagnostic_t kind, location_t location, int opt,
1146 const char *gmsgid, ...)
1148 va_list ap;
1149 va_start (ap, gmsgid);
1150 rich_location richloc (line_table, location);
1151 bool ret = diagnostic_impl (&richloc, opt, gmsgid, &ap, kind);
1152 va_end (ap);
1153 return ret;
1156 /* Wrapper around diagnostic_impl taking a va_list parameter. */
1158 bool
1159 emit_diagnostic_valist (diagnostic_t kind, location_t location, int opt,
1160 const char *gmsgid, va_list *ap)
1162 rich_location richloc (line_table, location);
1163 return diagnostic_impl (&richloc, opt, gmsgid, ap, kind);
1166 /* An informative note at LOCATION. Use this for additional details on an error
1167 message. */
1168 void
1169 inform (location_t location, const char *gmsgid, ...)
1171 va_list ap;
1172 va_start (ap, gmsgid);
1173 rich_location richloc (line_table, location);
1174 diagnostic_impl (&richloc, -1, gmsgid, &ap, DK_NOTE);
1175 va_end (ap);
1178 /* Same as "inform" above, but at RICHLOC. */
1179 void
1180 inform (rich_location *richloc, const char *gmsgid, ...)
1182 gcc_assert (richloc);
1184 va_list ap;
1185 va_start (ap, gmsgid);
1186 diagnostic_impl (richloc, -1, gmsgid, &ap, DK_NOTE);
1187 va_end (ap);
1190 /* An informative note at LOCATION. Use this for additional details on an
1191 error message. */
1192 void
1193 inform_n (location_t location, unsigned HOST_WIDE_INT n,
1194 const char *singular_gmsgid, const char *plural_gmsgid, ...)
1196 va_list ap;
1197 va_start (ap, plural_gmsgid);
1198 rich_location richloc (line_table, location);
1199 diagnostic_n_impl (&richloc, -1, n, singular_gmsgid, plural_gmsgid,
1200 &ap, DK_NOTE);
1201 va_end (ap);
1204 /* A warning at INPUT_LOCATION. Use this for code which is correct according
1205 to the relevant language specification but is likely to be buggy anyway.
1206 Returns true if the warning was printed, false if it was inhibited. */
1207 bool
1208 warning (int opt, const char *gmsgid, ...)
1210 va_list ap;
1211 va_start (ap, gmsgid);
1212 rich_location richloc (line_table, input_location);
1213 bool ret = diagnostic_impl (&richloc, opt, gmsgid, &ap, DK_WARNING);
1214 va_end (ap);
1215 return ret;
1218 /* A warning at LOCATION. Use this for code which is correct according to the
1219 relevant language specification but is likely to be buggy anyway.
1220 Returns true if the warning was printed, false if it was inhibited. */
1222 bool
1223 warning_at (location_t location, int opt, const char *gmsgid, ...)
1225 va_list ap;
1226 va_start (ap, gmsgid);
1227 rich_location richloc (line_table, location);
1228 bool ret = diagnostic_impl (&richloc, opt, gmsgid, &ap, DK_WARNING);
1229 va_end (ap);
1230 return ret;
1233 /* Same as "warning at" above, but using RICHLOC. */
1235 bool
1236 warning_at (rich_location *richloc, int opt, const char *gmsgid, ...)
1238 gcc_assert (richloc);
1240 va_list ap;
1241 va_start (ap, gmsgid);
1242 bool ret = diagnostic_impl (richloc, opt, gmsgid, &ap, DK_WARNING);
1243 va_end (ap);
1244 return ret;
1247 /* Same as warning_n plural variant below, but using RICHLOC. */
1249 bool
1250 warning_n (rich_location *richloc, int opt, unsigned HOST_WIDE_INT n,
1251 const char *singular_gmsgid, const char *plural_gmsgid, ...)
1253 gcc_assert (richloc);
1255 va_list ap;
1256 va_start (ap, plural_gmsgid);
1257 bool ret = diagnostic_n_impl (richloc, opt, n,
1258 singular_gmsgid, plural_gmsgid,
1259 &ap, DK_WARNING);
1260 va_end (ap);
1261 return ret;
1264 /* A warning at LOCATION. Use this for code which is correct according to the
1265 relevant language specification but is likely to be buggy anyway.
1266 Returns true if the warning was printed, false if it was inhibited. */
1268 bool
1269 warning_n (location_t location, int opt, unsigned HOST_WIDE_INT n,
1270 const char *singular_gmsgid, const char *plural_gmsgid, ...)
1272 va_list ap;
1273 va_start (ap, plural_gmsgid);
1274 rich_location richloc (line_table, location);
1275 bool ret = diagnostic_n_impl (&richloc, opt, n,
1276 singular_gmsgid, plural_gmsgid,
1277 &ap, DK_WARNING);
1278 va_end (ap);
1279 return ret;
1282 /* A "pedantic" warning at LOCATION: issues a warning unless
1283 -pedantic-errors was given on the command line, in which case it
1284 issues an error. Use this for diagnostics required by the relevant
1285 language standard, if you have chosen not to make them errors.
1287 Note that these diagnostics are issued independent of the setting
1288 of the -Wpedantic command-line switch. To get a warning enabled
1289 only with that switch, use either "if (pedantic) pedwarn
1290 (OPT_Wpedantic,...)" or just "pedwarn (OPT_Wpedantic,..)". To get a
1291 pedwarn independently of the -Wpedantic switch use "pedwarn (0,...)".
1293 Returns true if the warning was printed, false if it was inhibited. */
1295 bool
1296 pedwarn (location_t location, int opt, const char *gmsgid, ...)
1298 va_list ap;
1299 va_start (ap, gmsgid);
1300 rich_location richloc (line_table, location);
1301 bool ret = diagnostic_impl (&richloc, opt, gmsgid, &ap, DK_PEDWARN);
1302 va_end (ap);
1303 return ret;
1306 /* Same as pedwarn above, but using RICHLOC. */
1308 bool
1309 pedwarn (rich_location *richloc, int opt, const char *gmsgid, ...)
1311 gcc_assert (richloc);
1313 va_list ap;
1314 va_start (ap, gmsgid);
1315 bool ret = diagnostic_impl (richloc, opt, gmsgid, &ap, DK_PEDWARN);
1316 va_end (ap);
1317 return ret;
1320 /* A "permissive" error at LOCATION: issues an error unless
1321 -fpermissive was given on the command line, in which case it issues
1322 a warning. Use this for things that really should be errors but we
1323 want to support legacy code.
1325 Returns true if the warning was printed, false if it was inhibited. */
1327 bool
1328 permerror (location_t location, const char *gmsgid, ...)
1330 va_list ap;
1331 va_start (ap, gmsgid);
1332 rich_location richloc (line_table, location);
1333 bool ret = diagnostic_impl (&richloc, -1, gmsgid, &ap, DK_PERMERROR);
1334 va_end (ap);
1335 return ret;
1338 /* Same as "permerror" above, but at RICHLOC. */
1340 bool
1341 permerror (rich_location *richloc, const char *gmsgid, ...)
1343 gcc_assert (richloc);
1345 va_list ap;
1346 va_start (ap, gmsgid);
1347 bool ret = diagnostic_impl (richloc, -1, gmsgid, &ap, DK_PERMERROR);
1348 va_end (ap);
1349 return ret;
1352 /* A hard error: the code is definitely ill-formed, and an object file
1353 will not be produced. */
1354 void
1355 error (const char *gmsgid, ...)
1357 va_list ap;
1358 va_start (ap, gmsgid);
1359 rich_location richloc (line_table, input_location);
1360 diagnostic_impl (&richloc, -1, gmsgid, &ap, DK_ERROR);
1361 va_end (ap);
1364 /* A hard error: the code is definitely ill-formed, and an object file
1365 will not be produced. */
1366 void
1367 error_n (location_t location, unsigned HOST_WIDE_INT n,
1368 const char *singular_gmsgid, const char *plural_gmsgid, ...)
1370 va_list ap;
1371 va_start (ap, plural_gmsgid);
1372 rich_location richloc (line_table, location);
1373 diagnostic_n_impl (&richloc, -1, n, singular_gmsgid, plural_gmsgid,
1374 &ap, DK_ERROR);
1375 va_end (ap);
1378 /* Same as above, but use location LOC instead of input_location. */
1379 void
1380 error_at (location_t loc, const char *gmsgid, ...)
1382 va_list ap;
1383 va_start (ap, gmsgid);
1384 rich_location richloc (line_table, loc);
1385 diagnostic_impl (&richloc, -1, gmsgid, &ap, DK_ERROR);
1386 va_end (ap);
1389 /* Same as above, but use RICH_LOC. */
1391 void
1392 error_at (rich_location *richloc, const char *gmsgid, ...)
1394 gcc_assert (richloc);
1396 va_list ap;
1397 va_start (ap, gmsgid);
1398 diagnostic_impl (richloc, -1, gmsgid, &ap, DK_ERROR);
1399 va_end (ap);
1402 /* "Sorry, not implemented." Use for a language feature which is
1403 required by the relevant specification but not implemented by GCC.
1404 An object file will not be produced. */
1405 void
1406 sorry (const char *gmsgid, ...)
1408 va_list ap;
1409 va_start (ap, gmsgid);
1410 rich_location richloc (line_table, input_location);
1411 diagnostic_impl (&richloc, -1, gmsgid, &ap, DK_SORRY);
1412 va_end (ap);
1415 /* Return true if an error or a "sorry" has been seen. Various
1416 processing is disabled after errors. */
1417 bool
1418 seen_error (void)
1420 return errorcount || sorrycount;
1423 /* An error which is severe enough that we make no attempt to
1424 continue. Do not use this for internal consistency checks; that's
1425 internal_error. Use of this function should be rare. */
1426 void
1427 fatal_error (location_t loc, const char *gmsgid, ...)
1429 va_list ap;
1430 va_start (ap, gmsgid);
1431 rich_location richloc (line_table, loc);
1432 diagnostic_impl (&richloc, -1, gmsgid, &ap, DK_FATAL);
1433 va_end (ap);
1435 gcc_unreachable ();
1438 /* An internal consistency check has failed. We make no attempt to
1439 continue. Note that unless there is debugging value to be had from
1440 a more specific message, or some other good reason, you should use
1441 abort () instead of calling this function directly. */
1442 void
1443 internal_error (const char *gmsgid, ...)
1445 va_list ap;
1446 va_start (ap, gmsgid);
1447 rich_location richloc (line_table, input_location);
1448 diagnostic_impl (&richloc, -1, gmsgid, &ap, DK_ICE);
1449 va_end (ap);
1451 gcc_unreachable ();
1454 /* Like internal_error, but no backtrace will be printed. Used when
1455 the internal error does not happen at the current location, but happened
1456 somewhere else. */
1457 void
1458 internal_error_no_backtrace (const char *gmsgid, ...)
1460 va_list ap;
1461 va_start (ap, gmsgid);
1462 rich_location richloc (line_table, input_location);
1463 diagnostic_impl (&richloc, -1, gmsgid, &ap, DK_ICE_NOBT);
1464 va_end (ap);
1466 gcc_unreachable ();
1469 /* Special case error functions. Most are implemented in terms of the
1470 above, or should be. */
1472 /* Print a diagnostic MSGID on FILE. This is just fprintf, except it
1473 runs its second argument through gettext. */
1474 void
1475 fnotice (FILE *file, const char *cmsgid, ...)
1477 va_list ap;
1479 va_start (ap, cmsgid);
1480 vfprintf (file, _(cmsgid), ap);
1481 va_end (ap);
1484 /* Inform the user that an error occurred while trying to report some
1485 other error. This indicates catastrophic internal inconsistencies,
1486 so give up now. But do try to flush out the previous error.
1487 This mustn't use internal_error, that will cause infinite recursion. */
1489 static void
1490 error_recursion (diagnostic_context *context)
1492 if (context->lock < 3)
1493 pp_newline_and_flush (context->printer);
1495 fnotice (stderr,
1496 "Internal compiler error: Error reporting routines re-entered.\n");
1498 /* Call diagnostic_action_after_output to get the "please submit a bug
1499 report" message. */
1500 diagnostic_action_after_output (context, DK_ICE);
1502 /* Do not use gcc_unreachable here; that goes through internal_error
1503 and therefore would cause infinite recursion. */
1504 real_abort ();
1507 /* Report an internal compiler error in a friendly manner. This is
1508 the function that gets called upon use of abort() in the source
1509 code generally, thanks to a special macro. */
1511 void
1512 fancy_abort (const char *file, int line, const char *function)
1514 internal_error ("in %s, at %s:%d", function, trim_filename (file), line);
1517 /* Really call the system 'abort'. This has to go right at the end of
1518 this file, so that there are no functions after it that call abort
1519 and get the system abort instead of our macro. */
1520 #undef abort
1521 static void
1522 real_abort (void)
1524 abort ();
1527 #if CHECKING_P
1529 namespace selftest {
1531 /* Helper function for test_print_escaped_string. */
1533 static void
1534 assert_print_escaped_string (const location &loc, const char *expected_output,
1535 const char *input)
1537 pretty_printer pp;
1538 print_escaped_string (&pp, input);
1539 ASSERT_STREQ_AT (loc, expected_output, pp_formatted_text (&pp));
1542 #define ASSERT_PRINT_ESCAPED_STRING_STREQ(EXPECTED_OUTPUT, INPUT) \
1543 assert_print_escaped_string (SELFTEST_LOCATION, EXPECTED_OUTPUT, INPUT)
1545 /* Tests of print_escaped_string. */
1547 static void
1548 test_print_escaped_string ()
1550 /* Empty string. */
1551 ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"\"", "");
1553 /* Non-empty string. */
1554 ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"hello world\"", "hello world");
1556 /* Various things that need to be escaped: */
1557 /* Backslash. */
1558 ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"before\\\\after\"",
1559 "before\\after");
1560 /* Tab. */
1561 ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"before\\tafter\"",
1562 "before\tafter");
1563 /* Newline. */
1564 ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"before\\nafter\"",
1565 "before\nafter");
1566 /* Double quote. */
1567 ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"before\\\"after\"",
1568 "before\"after");
1570 /* Non-printable characters: BEL: '\a': 0x07 */
1571 ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"before\\007after\"",
1572 "before\aafter");
1573 /* Non-printable characters: vertical tab: '\v': 0x0b */
1574 ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"before\\013after\"",
1575 "before\vafter");
1578 /* Tests of print_parseable_fixits. */
1580 /* Verify that print_parseable_fixits emits the empty string if there
1581 are no fixits. */
1583 static void
1584 test_print_parseable_fixits_none ()
1586 pretty_printer pp;
1587 rich_location richloc (line_table, UNKNOWN_LOCATION);
1589 print_parseable_fixits (&pp, &richloc);
1590 ASSERT_STREQ ("", pp_formatted_text (&pp));
1593 /* Verify that print_parseable_fixits does the right thing if there
1594 is an insertion fixit hint. */
1596 static void
1597 test_print_parseable_fixits_insert ()
1599 pretty_printer pp;
1600 rich_location richloc (line_table, UNKNOWN_LOCATION);
1602 linemap_add (line_table, LC_ENTER, false, "test.c", 0);
1603 linemap_line_start (line_table, 5, 100);
1604 linemap_add (line_table, LC_LEAVE, false, NULL, 0);
1605 location_t where = linemap_position_for_column (line_table, 10);
1606 richloc.add_fixit_insert_before (where, "added content");
1608 print_parseable_fixits (&pp, &richloc);
1609 ASSERT_STREQ ("fix-it:\"test.c\":{5:10-5:10}:\"added content\"\n",
1610 pp_formatted_text (&pp));
1613 /* Verify that print_parseable_fixits does the right thing if there
1614 is an removal fixit hint. */
1616 static void
1617 test_print_parseable_fixits_remove ()
1619 pretty_printer pp;
1620 rich_location richloc (line_table, UNKNOWN_LOCATION);
1622 linemap_add (line_table, LC_ENTER, false, "test.c", 0);
1623 linemap_line_start (line_table, 5, 100);
1624 linemap_add (line_table, LC_LEAVE, false, NULL, 0);
1625 source_range where;
1626 where.m_start = linemap_position_for_column (line_table, 10);
1627 where.m_finish = linemap_position_for_column (line_table, 20);
1628 richloc.add_fixit_remove (where);
1630 print_parseable_fixits (&pp, &richloc);
1631 ASSERT_STREQ ("fix-it:\"test.c\":{5:10-5:21}:\"\"\n",
1632 pp_formatted_text (&pp));
1635 /* Verify that print_parseable_fixits does the right thing if there
1636 is an replacement fixit hint. */
1638 static void
1639 test_print_parseable_fixits_replace ()
1641 pretty_printer pp;
1642 rich_location richloc (line_table, UNKNOWN_LOCATION);
1644 linemap_add (line_table, LC_ENTER, false, "test.c", 0);
1645 linemap_line_start (line_table, 5, 100);
1646 linemap_add (line_table, LC_LEAVE, false, NULL, 0);
1647 source_range where;
1648 where.m_start = linemap_position_for_column (line_table, 10);
1649 where.m_finish = linemap_position_for_column (line_table, 20);
1650 richloc.add_fixit_replace (where, "replacement");
1652 print_parseable_fixits (&pp, &richloc);
1653 ASSERT_STREQ ("fix-it:\"test.c\":{5:10-5:21}:\"replacement\"\n",
1654 pp_formatted_text (&pp));
1657 /* Verify that
1658 diagnostic_get_location_text (..., SHOW_COLUMN)
1659 generates EXPECTED_LOC_TEXT, given FILENAME, LINE, COLUMN, with
1660 colorization disabled. */
1662 static void
1663 assert_location_text (const char *expected_loc_text,
1664 const char *filename, int line, int column,
1665 bool show_column)
1667 test_diagnostic_context dc;
1668 dc.show_column = show_column;
1670 expanded_location xloc;
1671 xloc.file = filename;
1672 xloc.line = line;
1673 xloc.column = column;
1674 xloc.data = NULL;
1675 xloc.sysp = false;
1677 char *actual_loc_text = diagnostic_get_location_text (&dc, xloc);
1678 ASSERT_STREQ (expected_loc_text, actual_loc_text);
1679 free (actual_loc_text);
1682 /* Verify that diagnostic_get_location_text works as expected. */
1684 static void
1685 test_diagnostic_get_location_text ()
1687 const char *old_progname = progname;
1688 progname = "PROGNAME";
1689 assert_location_text ("PROGNAME:", NULL, 0, 0, true);
1690 assert_location_text ("<built-in>:", "<built-in>", 42, 10, true);
1691 assert_location_text ("foo.c:42:10:", "foo.c", 42, 10, true);
1692 assert_location_text ("foo.c:42:", "foo.c", 42, 0, true);
1693 assert_location_text ("foo.c:", "foo.c", 0, 10, true);
1694 assert_location_text ("foo.c:42:", "foo.c", 42, 10, false);
1695 assert_location_text ("foo.c:", "foo.c", 0, 10, false);
1697 maybe_line_and_column (INT_MAX, INT_MAX);
1698 maybe_line_and_column (INT_MIN, INT_MIN);
1700 progname = old_progname;
1703 /* Run all of the selftests within this file. */
1705 void
1706 diagnostic_c_tests ()
1708 test_print_escaped_string ();
1709 test_print_parseable_fixits_none ();
1710 test_print_parseable_fixits_insert ();
1711 test_print_parseable_fixits_remove ();
1712 test_print_parseable_fixits_replace ();
1713 test_diagnostic_get_location_text ();
1716 } // namespace selftest
1718 #endif /* #if CHECKING_P */