diagnostics: fix bad interaction between line spans and line numbers
[official-gcc.git] / gcc / diagnostic.c
blob7e8bcf52dc1e533a62b853cd438afcb65fff2c06
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_labels_p = false;
179 context->show_line_numbers_p = false;
180 context->show_ruler_p = false;
181 context->parseable_fixits_p = false;
182 context->edit_context_ptr = NULL;
185 /* Maybe initialize the color support. We require clients to do this
186 explicitly, since most clients don't want color. When called
187 without a VALUE, it initializes with DIAGNOSTICS_COLOR_DEFAULT. */
189 void
190 diagnostic_color_init (diagnostic_context *context, int value /*= -1 */)
192 /* value == -1 is the default value. */
193 if (value < 0)
195 /* If DIAGNOSTICS_COLOR_DEFAULT is -1, default to
196 -fdiagnostics-color=auto if GCC_COLORS is in the environment,
197 otherwise default to -fdiagnostics-color=never, for other
198 values default to that
199 -fdiagnostics-color={never,auto,always}. */
200 if (DIAGNOSTICS_COLOR_DEFAULT == -1)
202 if (!getenv ("GCC_COLORS"))
203 return;
204 value = DIAGNOSTICS_COLOR_AUTO;
206 else
207 value = DIAGNOSTICS_COLOR_DEFAULT;
209 pp_show_color (context->printer)
210 = colorize_init ((diagnostic_color_rule_t) value);
213 /* Do any cleaning up required after the last diagnostic is emitted. */
215 void
216 diagnostic_finish (diagnostic_context *context)
218 /* Some of the errors may actually have been warnings. */
219 if (diagnostic_kind_count (context, DK_WERROR))
221 /* -Werror was given. */
222 if (context->warning_as_error_requested)
223 pp_verbatim (context->printer,
224 _("%s: all warnings being treated as errors"),
225 progname);
226 /* At least one -Werror= was given. */
227 else
228 pp_verbatim (context->printer,
229 _("%s: some warnings being treated as errors"),
230 progname);
231 pp_newline_and_flush (context->printer);
234 diagnostic_file_cache_fini ();
236 XDELETEVEC (context->classify_diagnostic);
237 context->classify_diagnostic = NULL;
239 /* diagnostic_initialize allocates context->printer using XNEW
240 and placement-new. */
241 context->printer->~pretty_printer ();
242 XDELETE (context->printer);
243 context->printer = NULL;
245 if (context->edit_context_ptr)
247 delete context->edit_context_ptr;
248 context->edit_context_ptr = NULL;
252 /* Initialize DIAGNOSTIC, where the message MSG has already been
253 translated. */
254 void
255 diagnostic_set_info_translated (diagnostic_info *diagnostic, const char *msg,
256 va_list *args, rich_location *richloc,
257 diagnostic_t kind)
259 gcc_assert (richloc);
260 diagnostic->message.err_no = errno;
261 diagnostic->message.args_ptr = args;
262 diagnostic->message.format_spec = msg;
263 diagnostic->message.m_richloc = richloc;
264 diagnostic->richloc = richloc;
265 diagnostic->kind = kind;
266 diagnostic->option_index = 0;
269 /* Initialize DIAGNOSTIC, where the message GMSGID has not yet been
270 translated. */
271 void
272 diagnostic_set_info (diagnostic_info *diagnostic, const char *gmsgid,
273 va_list *args, rich_location *richloc,
274 diagnostic_t kind)
276 gcc_assert (richloc);
277 diagnostic_set_info_translated (diagnostic, _(gmsgid), args, richloc, kind);
280 static const char *const diagnostic_kind_color[] = {
281 #define DEFINE_DIAGNOSTIC_KIND(K, T, C) (C),
282 #include "diagnostic.def"
283 #undef DEFINE_DIAGNOSTIC_KIND
284 NULL
287 /* Get a color name for diagnostics of type KIND
288 Result could be NULL. */
290 const char *
291 diagnostic_get_color_for_kind (diagnostic_t kind)
293 return diagnostic_kind_color[kind];
296 /* Return a formatted line and column ':%line:%column'. Elided if
297 zero. The result is a statically allocated buffer. */
299 static const char *
300 maybe_line_and_column (int line, int col)
302 static char result[32];
304 if (line)
306 size_t l = snprintf (result, sizeof (result),
307 col ? ":%d:%d" : ":%d", line, col);
308 gcc_checking_assert (l < sizeof (result));
310 else
311 result[0] = 0;
312 return result;
315 /* Return a malloc'd string describing a location e.g. "foo.c:42:10".
316 The caller is responsible for freeing the memory. */
318 static char *
319 diagnostic_get_location_text (diagnostic_context *context,
320 expanded_location s)
322 pretty_printer *pp = context->printer;
323 const char *locus_cs = colorize_start (pp_show_color (pp), "locus");
324 const char *locus_ce = colorize_stop (pp_show_color (pp));
325 const char *file = s.file ? s.file : progname;
326 int line = strcmp (file, N_("<built-in>")) ? s.line : 0;
327 int col = context->show_column ? s.column : 0;
329 const char *line_col = maybe_line_and_column (line, col);
330 return build_message_string ("%s%s%s:%s", locus_cs, file,
331 line_col, locus_ce);
334 /* Return a malloc'd string describing a location and the severity of the
335 diagnostic, e.g. "foo.c:42:10: error: ". The caller is responsible for
336 freeing the memory. */
337 char *
338 diagnostic_build_prefix (diagnostic_context *context,
339 const diagnostic_info *diagnostic)
341 static const char *const diagnostic_kind_text[] = {
342 #define DEFINE_DIAGNOSTIC_KIND(K, T, C) (T),
343 #include "diagnostic.def"
344 #undef DEFINE_DIAGNOSTIC_KIND
345 "must-not-happen"
347 gcc_assert (diagnostic->kind < DK_LAST_DIAGNOSTIC_KIND);
349 const char *text = _(diagnostic_kind_text[diagnostic->kind]);
350 const char *text_cs = "", *text_ce = "";
351 pretty_printer *pp = context->printer;
353 if (diagnostic_kind_color[diagnostic->kind])
355 text_cs = colorize_start (pp_show_color (pp),
356 diagnostic_kind_color[diagnostic->kind]);
357 text_ce = colorize_stop (pp_show_color (pp));
360 expanded_location s = diagnostic_expand_location (diagnostic);
361 char *location_text = diagnostic_get_location_text (context, s);
363 char *result = build_message_string ("%s %s%s%s", location_text,
364 text_cs, text, text_ce);
365 free (location_text);
366 return result;
369 /* Functions at which to stop the backtrace print. It's not
370 particularly helpful to print the callers of these functions. */
372 static const char * const bt_stop[] =
374 "main",
375 "toplev::main",
376 "execute_one_pass",
377 "compile_file",
380 /* A callback function passed to the backtrace_full function. */
382 static int
383 bt_callback (void *data, uintptr_t pc, const char *filename, int lineno,
384 const char *function)
386 int *pcount = (int *) data;
388 /* If we don't have any useful information, don't print
389 anything. */
390 if (filename == NULL && function == NULL)
391 return 0;
393 /* Skip functions in diagnostic.c. */
394 if (*pcount == 0
395 && filename != NULL
396 && strcmp (lbasename (filename), "diagnostic.c") == 0)
397 return 0;
399 /* Print up to 20 functions. We could make this a --param, but
400 since this is only for debugging just use a constant for now. */
401 if (*pcount >= 20)
403 /* Returning a non-zero value stops the backtrace. */
404 return 1;
406 ++*pcount;
408 char *alc = NULL;
409 if (function != NULL)
411 char *str = cplus_demangle_v3 (function,
412 (DMGL_VERBOSE | DMGL_ANSI
413 | DMGL_GNU_V3 | DMGL_PARAMS));
414 if (str != NULL)
416 alc = str;
417 function = str;
420 for (size_t i = 0; i < ARRAY_SIZE (bt_stop); ++i)
422 size_t len = strlen (bt_stop[i]);
423 if (strncmp (function, bt_stop[i], len) == 0
424 && (function[len] == '\0' || function[len] == '('))
426 if (alc != NULL)
427 free (alc);
428 /* Returning a non-zero value stops the backtrace. */
429 return 1;
434 fprintf (stderr, "0x%lx %s\n\t%s:%d\n",
435 (unsigned long) pc,
436 function == NULL ? "???" : function,
437 filename == NULL ? "???" : filename,
438 lineno);
440 if (alc != NULL)
441 free (alc);
443 return 0;
446 /* A callback function passed to the backtrace_full function. This is
447 called if backtrace_full has an error. */
449 static void
450 bt_err_callback (void *data ATTRIBUTE_UNUSED, const char *msg, int errnum)
452 if (errnum < 0)
454 /* This means that no debug info was available. Just quietly
455 skip printing backtrace info. */
456 return;
458 fprintf (stderr, "%s%s%s\n", msg, errnum == 0 ? "" : ": ",
459 errnum == 0 ? "" : xstrerror (errnum));
462 /* Check if we've met the maximum error limit, and if so fatally exit
463 with a message. CONTEXT is the context to check, and FLUSH
464 indicates whether a diagnostic_finish call is needed. */
466 void
467 diagnostic_check_max_errors (diagnostic_context *context, bool flush)
469 if (!context->max_errors)
470 return;
472 int count = (diagnostic_kind_count (context, DK_ERROR)
473 + diagnostic_kind_count (context, DK_SORRY)
474 + diagnostic_kind_count (context, DK_WERROR));
476 if (count >= context->max_errors)
478 fnotice (stderr,
479 "compilation terminated due to -fmax-errors=%u.\n",
480 context->max_errors);
481 if (flush)
482 diagnostic_finish (context);
483 exit (FATAL_EXIT_CODE);
487 /* Take any action which is expected to happen after the diagnostic
488 is written out. This function does not always return. */
489 void
490 diagnostic_action_after_output (diagnostic_context *context,
491 diagnostic_t diag_kind)
493 switch (diag_kind)
495 case DK_DEBUG:
496 case DK_NOTE:
497 case DK_ANACHRONISM:
498 case DK_WARNING:
499 break;
501 case DK_ERROR:
502 case DK_SORRY:
503 if (context->abort_on_error)
504 real_abort ();
505 if (context->fatal_errors)
507 fnotice (stderr, "compilation terminated due to -Wfatal-errors.\n");
508 diagnostic_finish (context);
509 exit (FATAL_EXIT_CODE);
511 break;
513 case DK_ICE:
514 case DK_ICE_NOBT:
516 struct backtrace_state *state = NULL;
517 if (diag_kind == DK_ICE)
518 state = backtrace_create_state (NULL, 0, bt_err_callback, NULL);
519 int count = 0;
520 if (state != NULL)
521 backtrace_full (state, 2, bt_callback, bt_err_callback,
522 (void *) &count);
524 if (context->abort_on_error)
525 real_abort ();
527 fnotice (stderr, "Please submit a full bug report,\n"
528 "with preprocessed source if appropriate.\n");
529 if (count > 0)
530 fnotice (stderr,
531 ("Please include the complete backtrace "
532 "with any bug report.\n"));
533 fnotice (stderr, "See %s for instructions.\n", bug_report_url);
535 exit (ICE_EXIT_CODE);
538 case DK_FATAL:
539 if (context->abort_on_error)
540 real_abort ();
541 diagnostic_finish (context);
542 fnotice (stderr, "compilation terminated.\n");
543 exit (FATAL_EXIT_CODE);
545 default:
546 gcc_unreachable ();
550 /* True if the last module or file in which a diagnostic was reported is
551 different from the current one. */
553 static bool
554 last_module_changed_p (diagnostic_context *context,
555 const line_map_ordinary *map)
557 return context->last_module != map;
560 /* Remember the current module or file as being the last one in which we
561 report a diagnostic. */
563 static void
564 set_last_module (diagnostic_context *context, const line_map_ordinary *map)
566 context->last_module = map;
569 void
570 diagnostic_report_current_module (diagnostic_context *context, location_t where)
572 const line_map_ordinary *map = NULL;
574 if (pp_needs_newline (context->printer))
576 pp_newline (context->printer);
577 pp_needs_newline (context->printer) = false;
580 if (where <= BUILTINS_LOCATION)
581 return;
583 linemap_resolve_location (line_table, where,
584 LRK_MACRO_DEFINITION_LOCATION,
585 &map);
587 if (map && last_module_changed_p (context, map))
589 set_last_module (context, map);
590 if (! MAIN_FILE_P (map))
592 bool first = true;
595 where = linemap_included_from (map);
596 map = linemap_included_from_linemap (line_table, map);
597 const char *line_col
598 = maybe_line_and_column (SOURCE_LINE (map, where),
599 first && context->show_column
600 ? SOURCE_COLUMN (map, where) : 0);
601 static const char *const msgs[] =
603 N_("In file included from"),
604 N_(" from"),
606 unsigned index = !first;
607 pp_verbatim (context->printer, "%s%s %r%s%s%R",
608 first ? "" : ",\n", _(msgs[index]),
609 "locus", LINEMAP_FILE (map), line_col);
610 first = false;
612 while (! MAIN_FILE_P (map));
613 pp_verbatim (context->printer, ":");
614 pp_newline (context->printer);
619 void
620 default_diagnostic_starter (diagnostic_context *context,
621 diagnostic_info *diagnostic)
623 diagnostic_report_current_module (context, diagnostic_location (diagnostic));
624 pp_set_prefix (context->printer, diagnostic_build_prefix (context,
625 diagnostic));
628 void
629 default_diagnostic_start_span_fn (diagnostic_context *context,
630 expanded_location exploc)
632 char *text = diagnostic_get_location_text (context, exploc);
633 pp_string (context->printer, text);
634 free (text);
635 pp_newline (context->printer);
638 void
639 default_diagnostic_finalizer (diagnostic_context *context,
640 diagnostic_info *diagnostic)
642 diagnostic_show_locus (context, diagnostic->richloc, diagnostic->kind);
643 pp_destroy_prefix (context->printer);
644 pp_flush (context->printer);
647 /* Interface to specify diagnostic kind overrides. Returns the
648 previous setting, or DK_UNSPECIFIED if the parameters are out of
649 range. If OPTION_INDEX is zero, the new setting is for all the
650 diagnostics. */
651 diagnostic_t
652 diagnostic_classify_diagnostic (diagnostic_context *context,
653 int option_index,
654 diagnostic_t new_kind,
655 location_t where)
657 diagnostic_t old_kind;
659 if (option_index < 0
660 || option_index >= context->n_opts
661 || new_kind >= DK_LAST_DIAGNOSTIC_KIND)
662 return DK_UNSPECIFIED;
664 old_kind = context->classify_diagnostic[option_index];
666 /* Handle pragmas separately, since we need to keep track of *where*
667 the pragmas were. */
668 if (where != UNKNOWN_LOCATION)
670 int i;
672 /* Record the command-line status, so we can reset it back on DK_POP. */
673 if (old_kind == DK_UNSPECIFIED)
675 old_kind = !context->option_enabled (option_index,
676 context->option_state)
677 ? DK_IGNORED : (context->warning_as_error_requested
678 ? DK_ERROR : DK_WARNING);
679 context->classify_diagnostic[option_index] = old_kind;
682 for (i = context->n_classification_history - 1; i >= 0; i --)
683 if (context->classification_history[i].option == option_index)
685 old_kind = context->classification_history[i].kind;
686 break;
689 i = context->n_classification_history;
690 context->classification_history =
691 (diagnostic_classification_change_t *) xrealloc (context->classification_history, (i + 1)
692 * sizeof (diagnostic_classification_change_t));
693 context->classification_history[i].location = where;
694 context->classification_history[i].option = option_index;
695 context->classification_history[i].kind = new_kind;
696 context->n_classification_history ++;
698 else
699 context->classify_diagnostic[option_index] = new_kind;
701 return old_kind;
704 /* Save all diagnostic classifications in a stack. */
705 void
706 diagnostic_push_diagnostics (diagnostic_context *context, location_t where ATTRIBUTE_UNUSED)
708 context->push_list = (int *) xrealloc (context->push_list, (context->n_push + 1) * sizeof (int));
709 context->push_list[context->n_push ++] = context->n_classification_history;
712 /* Restore the topmost classification set off the stack. If the stack
713 is empty, revert to the state based on command line parameters. */
714 void
715 diagnostic_pop_diagnostics (diagnostic_context *context, location_t where)
717 int jump_to;
718 int i;
720 if (context->n_push)
721 jump_to = context->push_list [-- context->n_push];
722 else
723 jump_to = 0;
725 i = context->n_classification_history;
726 context->classification_history =
727 (diagnostic_classification_change_t *) xrealloc (context->classification_history, (i + 1)
728 * sizeof (diagnostic_classification_change_t));
729 context->classification_history[i].location = where;
730 context->classification_history[i].option = jump_to;
731 context->classification_history[i].kind = DK_POP;
732 context->n_classification_history ++;
735 /* Helper function for print_parseable_fixits. Print TEXT to PP, obeying the
736 escaping rules for -fdiagnostics-parseable-fixits. */
738 static void
739 print_escaped_string (pretty_printer *pp, const char *text)
741 gcc_assert (pp);
742 gcc_assert (text);
744 pp_character (pp, '"');
745 for (const char *ch = text; *ch; ch++)
747 switch (*ch)
749 case '\\':
750 /* Escape backslash as two backslashes. */
751 pp_string (pp, "\\\\");
752 break;
753 case '\t':
754 /* Escape tab as "\t". */
755 pp_string (pp, "\\t");
756 break;
757 case '\n':
758 /* Escape newline as "\n". */
759 pp_string (pp, "\\n");
760 break;
761 case '"':
762 /* Escape doublequotes as \". */
763 pp_string (pp, "\\\"");
764 break;
765 default:
766 if (ISPRINT (*ch))
767 pp_character (pp, *ch);
768 else
769 /* Use octal for non-printable chars. */
771 unsigned char c = (*ch & 0xff);
772 pp_printf (pp, "\\%o%o%o", (c / 64), (c / 8) & 007, c & 007);
774 break;
777 pp_character (pp, '"');
780 /* Implementation of -fdiagnostics-parseable-fixits. Print a
781 machine-parseable version of all fixits in RICHLOC to PP. */
783 static void
784 print_parseable_fixits (pretty_printer *pp, rich_location *richloc)
786 gcc_assert (pp);
787 gcc_assert (richloc);
789 for (unsigned i = 0; i < richloc->get_num_fixit_hints (); i++)
791 const fixit_hint *hint = richloc->get_fixit_hint (i);
792 source_location start_loc = hint->get_start_loc ();
793 expanded_location start_exploc = expand_location (start_loc);
794 pp_string (pp, "fix-it:");
795 print_escaped_string (pp, start_exploc.file);
796 /* For compatibility with clang, print as a half-open range. */
797 source_location next_loc = hint->get_next_loc ();
798 expanded_location next_exploc = expand_location (next_loc);
799 pp_printf (pp, ":{%i:%i-%i:%i}:",
800 start_exploc.line, start_exploc.column,
801 next_exploc.line, next_exploc.column);
802 print_escaped_string (pp, hint->get_string ());
803 pp_newline (pp);
807 /* Update the diag_class of DIAGNOSTIC based on its location
808 relative to any
809 #pragma GCC diagnostic
810 directives recorded within CONTEXT.
812 Return the new diag_class of DIAGNOSTIC if it was updated, or
813 DK_UNSPECIFIED otherwise. */
815 static diagnostic_t
816 update_effective_level_from_pragmas (diagnostic_context *context,
817 diagnostic_info *diagnostic)
819 diagnostic_t diag_class = DK_UNSPECIFIED;
821 if (context->n_classification_history > 0)
823 location_t location = diagnostic_location (diagnostic);
825 /* FIXME: Stupid search. Optimize later. */
826 for (int i = context->n_classification_history - 1; i >= 0; i --)
828 if (linemap_location_before_p
829 (line_table,
830 context->classification_history[i].location,
831 location))
833 if (context->classification_history[i].kind == (int) DK_POP)
835 i = context->classification_history[i].option;
836 continue;
838 int option = context->classification_history[i].option;
839 /* The option 0 is for all the diagnostics. */
840 if (option == 0 || option == diagnostic->option_index)
842 diag_class = context->classification_history[i].kind;
843 if (diag_class != DK_UNSPECIFIED)
844 diagnostic->kind = diag_class;
845 break;
851 return diag_class;
854 /* Print any metadata about the option used to control DIAGNOSTIC to CONTEXT's
855 printer, e.g. " [-Werror=uninitialized]".
856 Subroutine of diagnostic_report_diagnostic. */
858 static void
859 print_option_information (diagnostic_context *context,
860 const diagnostic_info *diagnostic,
861 diagnostic_t orig_diag_kind)
863 char *option_text;
865 option_text = context->option_name (context, diagnostic->option_index,
866 orig_diag_kind, diagnostic->kind);
868 if (option_text)
870 pretty_printer *pp = context->printer;
871 pp_string (pp, " [");
872 pp_string (pp, colorize_start (pp_show_color (pp),
873 diagnostic_kind_color[diagnostic->kind]));
874 pp_string (pp, option_text);
875 pp_string (pp, colorize_stop (pp_show_color (pp)));
876 pp_character (pp, ']');
877 free (option_text);
881 /* Report a diagnostic message (an error or a warning) as specified by
882 DC. This function is *the* subroutine in terms of which front-ends
883 should implement their specific diagnostic handling modules. The
884 front-end independent format specifiers are exactly those described
885 in the documentation of output_format.
886 Return true if a diagnostic was printed, false otherwise. */
888 bool
889 diagnostic_report_diagnostic (diagnostic_context *context,
890 diagnostic_info *diagnostic)
892 location_t location = diagnostic_location (diagnostic);
893 diagnostic_t orig_diag_kind = diagnostic->kind;
895 /* Give preference to being able to inhibit warnings, before they
896 get reclassified to something else. */
897 if ((diagnostic->kind == DK_WARNING || diagnostic->kind == DK_PEDWARN)
898 && !diagnostic_report_warnings_p (context, location))
899 return false;
901 if (diagnostic->kind == DK_PEDWARN)
903 diagnostic->kind = pedantic_warning_kind (context);
904 /* We do this to avoid giving the message for -pedantic-errors. */
905 orig_diag_kind = diagnostic->kind;
908 if (diagnostic->kind == DK_NOTE && context->inhibit_notes_p)
909 return false;
911 if (context->lock > 0)
913 /* If we're reporting an ICE in the middle of some other error,
914 try to flush out the previous error, then let this one
915 through. Don't do this more than once. */
916 if ((diagnostic->kind == DK_ICE || diagnostic->kind == DK_ICE_NOBT)
917 && context->lock == 1)
918 pp_newline_and_flush (context->printer);
919 else
920 error_recursion (context);
923 /* If the user requested that warnings be treated as errors, so be
924 it. Note that we do this before the next block so that
925 individual warnings can be overridden back to warnings with
926 -Wno-error=*. */
927 if (context->warning_as_error_requested
928 && diagnostic->kind == DK_WARNING)
929 diagnostic->kind = DK_ERROR;
931 if (diagnostic->option_index
932 && diagnostic->option_index != permissive_error_option (context))
934 /* This tests if the user provided the appropriate -Wfoo or
935 -Wno-foo option. */
936 if (! context->option_enabled (diagnostic->option_index,
937 context->option_state))
938 return false;
940 /* This tests for #pragma diagnostic changes. */
941 diagnostic_t diag_class
942 = update_effective_level_from_pragmas (context, diagnostic);
944 /* This tests if the user provided the appropriate -Werror=foo
945 option. */
946 if (diag_class == DK_UNSPECIFIED
947 && (context->classify_diagnostic[diagnostic->option_index]
948 != DK_UNSPECIFIED))
949 diagnostic->kind
950 = context->classify_diagnostic[diagnostic->option_index];
952 /* This allows for future extensions, like temporarily disabling
953 warnings for ranges of source code. */
954 if (diagnostic->kind == DK_IGNORED)
955 return false;
958 if (diagnostic->kind != DK_NOTE)
959 diagnostic_check_max_errors (context);
961 context->lock++;
963 if (diagnostic->kind == DK_ICE || diagnostic->kind == DK_ICE_NOBT)
965 /* When not checking, ICEs are converted to fatal errors when an
966 error has already occurred. This is counteracted by
967 abort_on_error. */
968 if (!CHECKING_P
969 && (diagnostic_kind_count (context, DK_ERROR) > 0
970 || diagnostic_kind_count (context, DK_SORRY) > 0)
971 && !context->abort_on_error)
973 expanded_location s
974 = expand_location (diagnostic_location (diagnostic));
975 fnotice (stderr, "%s:%d: confused by earlier errors, bailing out\n",
976 s.file, s.line);
977 exit (ICE_EXIT_CODE);
979 if (context->internal_error)
980 (*context->internal_error) (context,
981 diagnostic->message.format_spec,
982 diagnostic->message.args_ptr);
984 if (diagnostic->kind == DK_ERROR && orig_diag_kind == DK_WARNING)
985 ++diagnostic_kind_count (context, DK_WERROR);
986 else
987 ++diagnostic_kind_count (context, diagnostic->kind);
989 diagnostic->message.x_data = &diagnostic->x_data;
990 diagnostic->x_data = NULL;
991 pp_format (context->printer, &diagnostic->message);
992 (*diagnostic_starter (context)) (context, diagnostic);
993 pp_output_formatted_text (context->printer);
994 if (context->show_option_requested)
995 print_option_information (context, diagnostic, orig_diag_kind);
996 (*diagnostic_finalizer (context)) (context, diagnostic);
997 if (context->parseable_fixits_p)
999 print_parseable_fixits (context->printer, diagnostic->richloc);
1000 pp_flush (context->printer);
1002 diagnostic_action_after_output (context, diagnostic->kind);
1003 diagnostic->x_data = NULL;
1005 if (context->edit_context_ptr)
1006 if (diagnostic->richloc->fixits_can_be_auto_applied_p ())
1007 context->edit_context_ptr->add_fixits (diagnostic->richloc);
1009 context->lock--;
1011 return true;
1014 /* Given a partial pathname as input, return another pathname that
1015 shares no directory elements with the pathname of __FILE__. This
1016 is used by fancy_abort() to print `Internal compiler error in expr.c'
1017 instead of `Internal compiler error in ../../GCC/gcc/expr.c'. */
1019 const char *
1020 trim_filename (const char *name)
1022 static const char this_file[] = __FILE__;
1023 const char *p = name, *q = this_file;
1025 /* First skip any "../" in each filename. This allows us to give a proper
1026 reference to a file in a subdirectory. */
1027 while (p[0] == '.' && p[1] == '.' && IS_DIR_SEPARATOR (p[2]))
1028 p += 3;
1030 while (q[0] == '.' && q[1] == '.' && IS_DIR_SEPARATOR (q[2]))
1031 q += 3;
1033 /* Now skip any parts the two filenames have in common. */
1034 while (*p == *q && *p != 0 && *q != 0)
1035 p++, q++;
1037 /* Now go backwards until the previous directory separator. */
1038 while (p > name && !IS_DIR_SEPARATOR (p[-1]))
1039 p--;
1041 return p;
1044 /* Standard error reporting routines in increasing order of severity.
1045 All of these take arguments like printf. */
1047 /* Text to be emitted verbatim to the error message stream; this
1048 produces no prefix and disables line-wrapping. Use rarely. */
1049 void
1050 verbatim (const char *gmsgid, ...)
1052 text_info text;
1053 va_list ap;
1055 va_start (ap, gmsgid);
1056 text.err_no = errno;
1057 text.args_ptr = &ap;
1058 text.format_spec = _(gmsgid);
1059 text.x_data = NULL;
1060 pp_format_verbatim (global_dc->printer, &text);
1061 pp_newline_and_flush (global_dc->printer);
1062 va_end (ap);
1065 /* Add a note with text GMSGID and with LOCATION to the diagnostic CONTEXT. */
1066 void
1067 diagnostic_append_note (diagnostic_context *context,
1068 location_t location,
1069 const char * gmsgid, ...)
1071 diagnostic_info diagnostic;
1072 va_list ap;
1073 rich_location richloc (line_table, location);
1075 va_start (ap, gmsgid);
1076 diagnostic_set_info (&diagnostic, gmsgid, &ap, &richloc, DK_NOTE);
1077 if (context->inhibit_notes_p)
1079 va_end (ap);
1080 return;
1082 char *saved_prefix = pp_take_prefix (context->printer);
1083 pp_set_prefix (context->printer,
1084 diagnostic_build_prefix (context, &diagnostic));
1085 pp_format (context->printer, &diagnostic.message);
1086 pp_output_formatted_text (context->printer);
1087 pp_destroy_prefix (context->printer);
1088 pp_set_prefix (context->printer, saved_prefix);
1089 diagnostic_show_locus (context, &richloc, DK_NOTE);
1090 va_end (ap);
1093 /* Implement emit_diagnostic, inform, warning, warning_at, pedwarn,
1094 permerror, error, error_at, error_at, sorry, fatal_error, internal_error,
1095 and internal_error_no_backtrace, as documented and defined below. */
1096 static bool
1097 diagnostic_impl (rich_location *richloc, int opt,
1098 const char *gmsgid,
1099 va_list *ap, diagnostic_t kind)
1101 diagnostic_info diagnostic;
1102 if (kind == DK_PERMERROR)
1104 diagnostic_set_info (&diagnostic, gmsgid, ap, richloc,
1105 permissive_error_kind (global_dc));
1106 diagnostic.option_index = permissive_error_option (global_dc);
1108 else
1110 diagnostic_set_info (&diagnostic, gmsgid, ap, richloc, kind);
1111 if (kind == DK_WARNING || kind == DK_PEDWARN)
1112 diagnostic.option_index = opt;
1114 return diagnostic_report_diagnostic (global_dc, &diagnostic);
1117 /* Implement inform_n, warning_n, and error_n, as documented and
1118 defined below. */
1119 static bool
1120 diagnostic_n_impl (rich_location *richloc, int opt, unsigned HOST_WIDE_INT n,
1121 const char *singular_gmsgid,
1122 const char *plural_gmsgid,
1123 va_list *ap, diagnostic_t kind)
1125 diagnostic_info diagnostic;
1126 unsigned long gtn;
1128 if (sizeof n <= sizeof gtn)
1129 gtn = n;
1130 else
1131 /* Use the largest number ngettext can handle, otherwise
1132 preserve the six least significant decimal digits for
1133 languages where the plural form depends on them. */
1134 gtn = n <= ULONG_MAX ? n : n % 1000000LU + 1000000LU;
1136 const char *text = ngettext (singular_gmsgid, plural_gmsgid, gtn);
1137 diagnostic_set_info_translated (&diagnostic, text, ap, richloc, kind);
1138 if (kind == DK_WARNING)
1139 diagnostic.option_index = opt;
1140 return diagnostic_report_diagnostic (global_dc, &diagnostic);
1143 /* Wrapper around diagnostic_impl taking a variable argument list. */
1145 bool
1146 emit_diagnostic (diagnostic_t kind, location_t location, int opt,
1147 const char *gmsgid, ...)
1149 va_list ap;
1150 va_start (ap, gmsgid);
1151 rich_location richloc (line_table, location);
1152 bool ret = diagnostic_impl (&richloc, opt, gmsgid, &ap, kind);
1153 va_end (ap);
1154 return ret;
1157 /* Wrapper around diagnostic_impl taking a va_list parameter. */
1159 bool
1160 emit_diagnostic_valist (diagnostic_t kind, location_t location, int opt,
1161 const char *gmsgid, va_list *ap)
1163 rich_location richloc (line_table, location);
1164 return diagnostic_impl (&richloc, opt, gmsgid, ap, kind);
1167 /* An informative note at LOCATION. Use this for additional details on an error
1168 message. */
1169 void
1170 inform (location_t location, const char *gmsgid, ...)
1172 va_list ap;
1173 va_start (ap, gmsgid);
1174 rich_location richloc (line_table, location);
1175 diagnostic_impl (&richloc, -1, gmsgid, &ap, DK_NOTE);
1176 va_end (ap);
1179 /* Same as "inform" above, but at RICHLOC. */
1180 void
1181 inform (rich_location *richloc, const char *gmsgid, ...)
1183 gcc_assert (richloc);
1185 va_list ap;
1186 va_start (ap, gmsgid);
1187 diagnostic_impl (richloc, -1, gmsgid, &ap, DK_NOTE);
1188 va_end (ap);
1191 /* An informative note at LOCATION. Use this for additional details on an
1192 error message. */
1193 void
1194 inform_n (location_t location, unsigned HOST_WIDE_INT n,
1195 const char *singular_gmsgid, const char *plural_gmsgid, ...)
1197 va_list ap;
1198 va_start (ap, plural_gmsgid);
1199 rich_location richloc (line_table, location);
1200 diagnostic_n_impl (&richloc, -1, n, singular_gmsgid, plural_gmsgid,
1201 &ap, DK_NOTE);
1202 va_end (ap);
1205 /* A warning at INPUT_LOCATION. Use this for code which is correct according
1206 to the relevant language specification but is likely to be buggy anyway.
1207 Returns true if the warning was printed, false if it was inhibited. */
1208 bool
1209 warning (int opt, const char *gmsgid, ...)
1211 va_list ap;
1212 va_start (ap, gmsgid);
1213 rich_location richloc (line_table, input_location);
1214 bool ret = diagnostic_impl (&richloc, opt, gmsgid, &ap, DK_WARNING);
1215 va_end (ap);
1216 return ret;
1219 /* A warning at LOCATION. Use this for code which is correct according to the
1220 relevant language specification but is likely to be buggy anyway.
1221 Returns true if the warning was printed, false if it was inhibited. */
1223 bool
1224 warning_at (location_t location, int opt, const char *gmsgid, ...)
1226 va_list ap;
1227 va_start (ap, gmsgid);
1228 rich_location richloc (line_table, location);
1229 bool ret = diagnostic_impl (&richloc, opt, gmsgid, &ap, DK_WARNING);
1230 va_end (ap);
1231 return ret;
1234 /* Same as "warning at" above, but using RICHLOC. */
1236 bool
1237 warning_at (rich_location *richloc, int opt, const char *gmsgid, ...)
1239 gcc_assert (richloc);
1241 va_list ap;
1242 va_start (ap, gmsgid);
1243 bool ret = diagnostic_impl (richloc, opt, gmsgid, &ap, DK_WARNING);
1244 va_end (ap);
1245 return ret;
1248 /* Same as warning_n plural variant below, but using RICHLOC. */
1250 bool
1251 warning_n (rich_location *richloc, int opt, unsigned HOST_WIDE_INT n,
1252 const char *singular_gmsgid, const char *plural_gmsgid, ...)
1254 gcc_assert (richloc);
1256 va_list ap;
1257 va_start (ap, plural_gmsgid);
1258 bool ret = diagnostic_n_impl (richloc, opt, n,
1259 singular_gmsgid, plural_gmsgid,
1260 &ap, DK_WARNING);
1261 va_end (ap);
1262 return ret;
1265 /* A warning at LOCATION. Use this for code which is correct according to the
1266 relevant language specification but is likely to be buggy anyway.
1267 Returns true if the warning was printed, false if it was inhibited. */
1269 bool
1270 warning_n (location_t location, int opt, unsigned HOST_WIDE_INT n,
1271 const char *singular_gmsgid, const char *plural_gmsgid, ...)
1273 va_list ap;
1274 va_start (ap, plural_gmsgid);
1275 rich_location richloc (line_table, location);
1276 bool ret = diagnostic_n_impl (&richloc, opt, n,
1277 singular_gmsgid, plural_gmsgid,
1278 &ap, DK_WARNING);
1279 va_end (ap);
1280 return ret;
1283 /* A "pedantic" warning at LOCATION: issues a warning unless
1284 -pedantic-errors was given on the command line, in which case it
1285 issues an error. Use this for diagnostics required by the relevant
1286 language standard, if you have chosen not to make them errors.
1288 Note that these diagnostics are issued independent of the setting
1289 of the -Wpedantic command-line switch. To get a warning enabled
1290 only with that switch, use either "if (pedantic) pedwarn
1291 (OPT_Wpedantic,...)" or just "pedwarn (OPT_Wpedantic,..)". To get a
1292 pedwarn independently of the -Wpedantic switch use "pedwarn (0,...)".
1294 Returns true if the warning was printed, false if it was inhibited. */
1296 bool
1297 pedwarn (location_t location, int opt, const char *gmsgid, ...)
1299 va_list ap;
1300 va_start (ap, gmsgid);
1301 rich_location richloc (line_table, location);
1302 bool ret = diagnostic_impl (&richloc, opt, gmsgid, &ap, DK_PEDWARN);
1303 va_end (ap);
1304 return ret;
1307 /* Same as pedwarn above, but using RICHLOC. */
1309 bool
1310 pedwarn (rich_location *richloc, int opt, const char *gmsgid, ...)
1312 gcc_assert (richloc);
1314 va_list ap;
1315 va_start (ap, gmsgid);
1316 bool ret = diagnostic_impl (richloc, opt, gmsgid, &ap, DK_PEDWARN);
1317 va_end (ap);
1318 return ret;
1321 /* A "permissive" error at LOCATION: issues an error unless
1322 -fpermissive was given on the command line, in which case it issues
1323 a warning. Use this for things that really should be errors but we
1324 want to support legacy code.
1326 Returns true if the warning was printed, false if it was inhibited. */
1328 bool
1329 permerror (location_t location, const char *gmsgid, ...)
1331 va_list ap;
1332 va_start (ap, gmsgid);
1333 rich_location richloc (line_table, location);
1334 bool ret = diagnostic_impl (&richloc, -1, gmsgid, &ap, DK_PERMERROR);
1335 va_end (ap);
1336 return ret;
1339 /* Same as "permerror" above, but at RICHLOC. */
1341 bool
1342 permerror (rich_location *richloc, const char *gmsgid, ...)
1344 gcc_assert (richloc);
1346 va_list ap;
1347 va_start (ap, gmsgid);
1348 bool ret = diagnostic_impl (richloc, -1, gmsgid, &ap, DK_PERMERROR);
1349 va_end (ap);
1350 return ret;
1353 /* A hard error: the code is definitely ill-formed, and an object file
1354 will not be produced. */
1355 void
1356 error (const char *gmsgid, ...)
1358 va_list ap;
1359 va_start (ap, gmsgid);
1360 rich_location richloc (line_table, input_location);
1361 diagnostic_impl (&richloc, -1, gmsgid, &ap, DK_ERROR);
1362 va_end (ap);
1365 /* A hard error: the code is definitely ill-formed, and an object file
1366 will not be produced. */
1367 void
1368 error_n (location_t location, unsigned HOST_WIDE_INT n,
1369 const char *singular_gmsgid, const char *plural_gmsgid, ...)
1371 va_list ap;
1372 va_start (ap, plural_gmsgid);
1373 rich_location richloc (line_table, location);
1374 diagnostic_n_impl (&richloc, -1, n, singular_gmsgid, plural_gmsgid,
1375 &ap, DK_ERROR);
1376 va_end (ap);
1379 /* Same as above, but use location LOC instead of input_location. */
1380 void
1381 error_at (location_t loc, const char *gmsgid, ...)
1383 va_list ap;
1384 va_start (ap, gmsgid);
1385 rich_location richloc (line_table, loc);
1386 diagnostic_impl (&richloc, -1, gmsgid, &ap, DK_ERROR);
1387 va_end (ap);
1390 /* Same as above, but use RICH_LOC. */
1392 void
1393 error_at (rich_location *richloc, const char *gmsgid, ...)
1395 gcc_assert (richloc);
1397 va_list ap;
1398 va_start (ap, gmsgid);
1399 diagnostic_impl (richloc, -1, gmsgid, &ap, DK_ERROR);
1400 va_end (ap);
1403 /* "Sorry, not implemented." Use for a language feature which is
1404 required by the relevant specification but not implemented by GCC.
1405 An object file will not be produced. */
1406 void
1407 sorry (const char *gmsgid, ...)
1409 va_list ap;
1410 va_start (ap, gmsgid);
1411 rich_location richloc (line_table, input_location);
1412 diagnostic_impl (&richloc, -1, gmsgid, &ap, DK_SORRY);
1413 va_end (ap);
1416 /* Return true if an error or a "sorry" has been seen. Various
1417 processing is disabled after errors. */
1418 bool
1419 seen_error (void)
1421 return errorcount || sorrycount;
1424 /* An error which is severe enough that we make no attempt to
1425 continue. Do not use this for internal consistency checks; that's
1426 internal_error. Use of this function should be rare. */
1427 void
1428 fatal_error (location_t loc, const char *gmsgid, ...)
1430 va_list ap;
1431 va_start (ap, gmsgid);
1432 rich_location richloc (line_table, loc);
1433 diagnostic_impl (&richloc, -1, gmsgid, &ap, DK_FATAL);
1434 va_end (ap);
1436 gcc_unreachable ();
1439 /* An internal consistency check has failed. We make no attempt to
1440 continue. Note that unless there is debugging value to be had from
1441 a more specific message, or some other good reason, you should use
1442 abort () instead of calling this function directly. */
1443 void
1444 internal_error (const char *gmsgid, ...)
1446 va_list ap;
1447 va_start (ap, gmsgid);
1448 rich_location richloc (line_table, input_location);
1449 diagnostic_impl (&richloc, -1, gmsgid, &ap, DK_ICE);
1450 va_end (ap);
1452 gcc_unreachable ();
1455 /* Like internal_error, but no backtrace will be printed. Used when
1456 the internal error does not happen at the current location, but happened
1457 somewhere else. */
1458 void
1459 internal_error_no_backtrace (const char *gmsgid, ...)
1461 va_list ap;
1462 va_start (ap, gmsgid);
1463 rich_location richloc (line_table, input_location);
1464 diagnostic_impl (&richloc, -1, gmsgid, &ap, DK_ICE_NOBT);
1465 va_end (ap);
1467 gcc_unreachable ();
1470 /* Special case error functions. Most are implemented in terms of the
1471 above, or should be. */
1473 /* Print a diagnostic MSGID on FILE. This is just fprintf, except it
1474 runs its second argument through gettext. */
1475 void
1476 fnotice (FILE *file, const char *cmsgid, ...)
1478 va_list ap;
1480 va_start (ap, cmsgid);
1481 vfprintf (file, _(cmsgid), ap);
1482 va_end (ap);
1485 /* Inform the user that an error occurred while trying to report some
1486 other error. This indicates catastrophic internal inconsistencies,
1487 so give up now. But do try to flush out the previous error.
1488 This mustn't use internal_error, that will cause infinite recursion. */
1490 static void
1491 error_recursion (diagnostic_context *context)
1493 if (context->lock < 3)
1494 pp_newline_and_flush (context->printer);
1496 fnotice (stderr,
1497 "Internal compiler error: Error reporting routines re-entered.\n");
1499 /* Call diagnostic_action_after_output to get the "please submit a bug
1500 report" message. */
1501 diagnostic_action_after_output (context, DK_ICE);
1503 /* Do not use gcc_unreachable here; that goes through internal_error
1504 and therefore would cause infinite recursion. */
1505 real_abort ();
1508 /* Report an internal compiler error in a friendly manner. This is
1509 the function that gets called upon use of abort() in the source
1510 code generally, thanks to a special macro. */
1512 void
1513 fancy_abort (const char *file, int line, const char *function)
1515 internal_error ("in %s, at %s:%d", function, trim_filename (file), line);
1518 /* Really call the system 'abort'. This has to go right at the end of
1519 this file, so that there are no functions after it that call abort
1520 and get the system abort instead of our macro. */
1521 #undef abort
1522 static void
1523 real_abort (void)
1525 abort ();
1528 #if CHECKING_P
1530 namespace selftest {
1532 /* Helper function for test_print_escaped_string. */
1534 static void
1535 assert_print_escaped_string (const location &loc, const char *expected_output,
1536 const char *input)
1538 pretty_printer pp;
1539 print_escaped_string (&pp, input);
1540 ASSERT_STREQ_AT (loc, expected_output, pp_formatted_text (&pp));
1543 #define ASSERT_PRINT_ESCAPED_STRING_STREQ(EXPECTED_OUTPUT, INPUT) \
1544 assert_print_escaped_string (SELFTEST_LOCATION, EXPECTED_OUTPUT, INPUT)
1546 /* Tests of print_escaped_string. */
1548 static void
1549 test_print_escaped_string ()
1551 /* Empty string. */
1552 ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"\"", "");
1554 /* Non-empty string. */
1555 ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"hello world\"", "hello world");
1557 /* Various things that need to be escaped: */
1558 /* Backslash. */
1559 ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"before\\\\after\"",
1560 "before\\after");
1561 /* Tab. */
1562 ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"before\\tafter\"",
1563 "before\tafter");
1564 /* Newline. */
1565 ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"before\\nafter\"",
1566 "before\nafter");
1567 /* Double quote. */
1568 ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"before\\\"after\"",
1569 "before\"after");
1571 /* Non-printable characters: BEL: '\a': 0x07 */
1572 ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"before\\007after\"",
1573 "before\aafter");
1574 /* Non-printable characters: vertical tab: '\v': 0x0b */
1575 ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"before\\013after\"",
1576 "before\vafter");
1579 /* Tests of print_parseable_fixits. */
1581 /* Verify that print_parseable_fixits emits the empty string if there
1582 are no fixits. */
1584 static void
1585 test_print_parseable_fixits_none ()
1587 pretty_printer pp;
1588 rich_location richloc (line_table, UNKNOWN_LOCATION);
1590 print_parseable_fixits (&pp, &richloc);
1591 ASSERT_STREQ ("", pp_formatted_text (&pp));
1594 /* Verify that print_parseable_fixits does the right thing if there
1595 is an insertion fixit hint. */
1597 static void
1598 test_print_parseable_fixits_insert ()
1600 pretty_printer pp;
1601 rich_location richloc (line_table, UNKNOWN_LOCATION);
1603 linemap_add (line_table, LC_ENTER, false, "test.c", 0);
1604 linemap_line_start (line_table, 5, 100);
1605 linemap_add (line_table, LC_LEAVE, false, NULL, 0);
1606 location_t where = linemap_position_for_column (line_table, 10);
1607 richloc.add_fixit_insert_before (where, "added content");
1609 print_parseable_fixits (&pp, &richloc);
1610 ASSERT_STREQ ("fix-it:\"test.c\":{5:10-5:10}:\"added content\"\n",
1611 pp_formatted_text (&pp));
1614 /* Verify that print_parseable_fixits does the right thing if there
1615 is an removal fixit hint. */
1617 static void
1618 test_print_parseable_fixits_remove ()
1620 pretty_printer pp;
1621 rich_location richloc (line_table, UNKNOWN_LOCATION);
1623 linemap_add (line_table, LC_ENTER, false, "test.c", 0);
1624 linemap_line_start (line_table, 5, 100);
1625 linemap_add (line_table, LC_LEAVE, false, NULL, 0);
1626 source_range where;
1627 where.m_start = linemap_position_for_column (line_table, 10);
1628 where.m_finish = linemap_position_for_column (line_table, 20);
1629 richloc.add_fixit_remove (where);
1631 print_parseable_fixits (&pp, &richloc);
1632 ASSERT_STREQ ("fix-it:\"test.c\":{5:10-5:21}:\"\"\n",
1633 pp_formatted_text (&pp));
1636 /* Verify that print_parseable_fixits does the right thing if there
1637 is an replacement fixit hint. */
1639 static void
1640 test_print_parseable_fixits_replace ()
1642 pretty_printer pp;
1643 rich_location richloc (line_table, UNKNOWN_LOCATION);
1645 linemap_add (line_table, LC_ENTER, false, "test.c", 0);
1646 linemap_line_start (line_table, 5, 100);
1647 linemap_add (line_table, LC_LEAVE, false, NULL, 0);
1648 source_range where;
1649 where.m_start = linemap_position_for_column (line_table, 10);
1650 where.m_finish = linemap_position_for_column (line_table, 20);
1651 richloc.add_fixit_replace (where, "replacement");
1653 print_parseable_fixits (&pp, &richloc);
1654 ASSERT_STREQ ("fix-it:\"test.c\":{5:10-5:21}:\"replacement\"\n",
1655 pp_formatted_text (&pp));
1658 /* Verify that
1659 diagnostic_get_location_text (..., SHOW_COLUMN)
1660 generates EXPECTED_LOC_TEXT, given FILENAME, LINE, COLUMN, with
1661 colorization disabled. */
1663 static void
1664 assert_location_text (const char *expected_loc_text,
1665 const char *filename, int line, int column,
1666 bool show_column)
1668 test_diagnostic_context dc;
1669 dc.show_column = show_column;
1671 expanded_location xloc;
1672 xloc.file = filename;
1673 xloc.line = line;
1674 xloc.column = column;
1675 xloc.data = NULL;
1676 xloc.sysp = false;
1678 char *actual_loc_text = diagnostic_get_location_text (&dc, xloc);
1679 ASSERT_STREQ (expected_loc_text, actual_loc_text);
1680 free (actual_loc_text);
1683 /* Verify that diagnostic_get_location_text works as expected. */
1685 static void
1686 test_diagnostic_get_location_text ()
1688 const char *old_progname = progname;
1689 progname = "PROGNAME";
1690 assert_location_text ("PROGNAME:", NULL, 0, 0, true);
1691 assert_location_text ("<built-in>:", "<built-in>", 42, 10, true);
1692 assert_location_text ("foo.c:42:10:", "foo.c", 42, 10, true);
1693 assert_location_text ("foo.c:42:", "foo.c", 42, 0, true);
1694 assert_location_text ("foo.c:", "foo.c", 0, 10, true);
1695 assert_location_text ("foo.c:42:", "foo.c", 42, 10, false);
1696 assert_location_text ("foo.c:", "foo.c", 0, 10, false);
1698 maybe_line_and_column (INT_MAX, INT_MAX);
1699 maybe_line_and_column (INT_MIN, INT_MIN);
1701 progname = old_progname;
1704 /* Run all of the selftests within this file. */
1706 void
1707 diagnostic_c_tests ()
1709 test_print_escaped_string ();
1710 test_print_parseable_fixits_none ();
1711 test_print_parseable_fixits_insert ();
1712 test_print_parseable_fixits_remove ();
1713 test_print_parseable_fixits_replace ();
1714 test_diagnostic_get_location_text ();
1717 } // namespace selftest
1719 #endif /* #if CHECKING_P */