PR 87488: Add --with-diagnostics-urls configuration option
[official-gcc.git] / gcc / diagnostic.c
blobe4a08f76defea9812615b84b92983ab05aac2a16
1 /* Language-independent diagnostic subroutines for the GNU Compiler Collection
2 Copyright (C) 1999-2020 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 "diagnostic-url.h"
35 #include "diagnostic-metadata.h"
36 #include "diagnostic-path.h"
37 #include "edit-context.h"
38 #include "selftest.h"
39 #include "selftest-diagnostic.h"
40 #include "opts.h"
42 #ifdef HAVE_TERMIOS_H
43 # include <termios.h>
44 #endif
46 #ifdef GWINSZ_IN_SYS_IOCTL
47 # include <sys/ioctl.h>
48 #endif
50 /* Disable warnings about quoting issues in the pp_xxx calls below
51 that (intentionally) don't follow GCC diagnostic conventions. */
52 #if __GNUC__ >= 10
53 # pragma GCC diagnostic push
54 # pragma GCC diagnostic ignored "-Wformat-diag"
55 #endif
57 #define pedantic_warning_kind(DC) \
58 ((DC)->pedantic_errors ? DK_ERROR : DK_WARNING)
59 #define permissive_error_kind(DC) ((DC)->permissive ? DK_WARNING : DK_ERROR)
60 #define permissive_error_option(DC) ((DC)->opt_permissive)
62 /* Prototypes. */
63 static bool diagnostic_impl (rich_location *, const diagnostic_metadata *,
64 int, const char *,
65 va_list *, diagnostic_t) ATTRIBUTE_GCC_DIAG(4,0);
66 static bool diagnostic_n_impl (rich_location *, const diagnostic_metadata *,
67 int, unsigned HOST_WIDE_INT,
68 const char *, const char *, va_list *,
69 diagnostic_t) ATTRIBUTE_GCC_DIAG(6,0);
71 static void error_recursion (diagnostic_context *) ATTRIBUTE_NORETURN;
72 static void real_abort (void) ATTRIBUTE_NORETURN;
74 /* Name of program invoked, sans directories. */
76 const char *progname;
78 /* A diagnostic_context surrogate for stderr. */
79 static diagnostic_context global_diagnostic_context;
80 diagnostic_context *global_dc = &global_diagnostic_context;
82 /* Return a malloc'd string containing MSG formatted a la printf. The
83 caller is responsible for freeing the memory. */
84 char *
85 build_message_string (const char *msg, ...)
87 char *str;
88 va_list ap;
90 va_start (ap, msg);
91 str = xvasprintf (msg, ap);
92 va_end (ap);
94 return str;
97 /* Same as diagnostic_build_prefix, but only the source FILE is given. */
98 char *
99 file_name_as_prefix (diagnostic_context *context, const char *f)
101 const char *locus_cs
102 = colorize_start (pp_show_color (context->printer), "locus");
103 const char *locus_ce = colorize_stop (pp_show_color (context->printer));
104 return build_message_string ("%s%s:%s ", locus_cs, f, locus_ce);
109 /* Return the value of the getenv("COLUMNS") as an integer. If the
110 value is not set to a positive integer, use ioctl to get the
111 terminal width. If it fails, return INT_MAX. */
113 get_terminal_width (void)
115 const char * s = getenv ("COLUMNS");
116 if (s != NULL) {
117 int n = atoi (s);
118 if (n > 0)
119 return n;
122 #ifdef TIOCGWINSZ
123 struct winsize w;
124 w.ws_col = 0;
125 if (ioctl (0, TIOCGWINSZ, &w) == 0 && w.ws_col > 0)
126 return w.ws_col;
127 #endif
129 return INT_MAX;
132 /* Set caret_max_width to value. */
133 void
134 diagnostic_set_caret_max_width (diagnostic_context *context, int value)
136 /* One minus to account for the leading empty space. */
137 value = value ? value - 1
138 : (isatty (fileno (pp_buffer (context->printer)->stream))
139 ? get_terminal_width () - 1: INT_MAX);
141 if (value <= 0)
142 value = INT_MAX;
144 context->caret_max_width = value;
147 /* Default implementation of final_cb. */
149 static void
150 default_diagnostic_final_cb (diagnostic_context *context)
152 /* Some of the errors may actually have been warnings. */
153 if (diagnostic_kind_count (context, DK_WERROR))
155 /* -Werror was given. */
156 if (context->warning_as_error_requested)
157 pp_verbatim (context->printer,
158 _("%s: all warnings being treated as errors"),
159 progname);
160 /* At least one -Werror= was given. */
161 else
162 pp_verbatim (context->printer,
163 _("%s: some warnings being treated as errors"),
164 progname);
165 pp_newline_and_flush (context->printer);
169 /* Initialize the diagnostic message outputting machinery. */
170 void
171 diagnostic_initialize (diagnostic_context *context, int n_opts)
173 int i;
175 /* Allocate a basic pretty-printer. Clients will replace this a
176 much more elaborated pretty-printer if they wish. */
177 context->printer = XNEW (pretty_printer);
178 new (context->printer) pretty_printer ();
180 memset (context->diagnostic_count, 0, sizeof context->diagnostic_count);
181 context->warning_as_error_requested = false;
182 context->n_opts = n_opts;
183 context->classify_diagnostic = XNEWVEC (diagnostic_t, n_opts);
184 for (i = 0; i < n_opts; i++)
185 context->classify_diagnostic[i] = DK_UNSPECIFIED;
186 context->show_caret = false;
187 diagnostic_set_caret_max_width (context, pp_line_cutoff (context->printer));
188 for (i = 0; i < rich_location::STATICALLY_ALLOCATED_RANGES; i++)
189 context->caret_chars[i] = '^';
190 context->show_cwe = false;
191 context->path_format = DPF_NONE;
192 context->show_path_depths = false;
193 context->show_option_requested = false;
194 context->abort_on_error = false;
195 context->show_column = false;
196 context->pedantic_errors = false;
197 context->permissive = false;
198 context->opt_permissive = 0;
199 context->fatal_errors = false;
200 context->dc_inhibit_warnings = false;
201 context->dc_warn_system_headers = false;
202 context->max_errors = 0;
203 context->internal_error = NULL;
204 diagnostic_starter (context) = default_diagnostic_starter;
205 context->start_span = default_diagnostic_start_span_fn;
206 diagnostic_finalizer (context) = default_diagnostic_finalizer;
207 context->option_enabled = NULL;
208 context->option_state = NULL;
209 context->option_name = NULL;
210 context->get_option_url = NULL;
211 context->last_location = UNKNOWN_LOCATION;
212 context->last_module = 0;
213 context->x_data = NULL;
214 context->lock = 0;
215 context->inhibit_notes_p = false;
216 context->colorize_source_p = false;
217 context->show_labels_p = false;
218 context->show_line_numbers_p = false;
219 context->min_margin_width = 0;
220 context->show_ruler_p = false;
221 context->parseable_fixits_p = false;
222 context->edit_context_ptr = NULL;
223 context->diagnostic_group_nesting_depth = 0;
224 context->diagnostic_group_emission_count = 0;
225 context->begin_group_cb = NULL;
226 context->end_group_cb = NULL;
227 context->final_cb = default_diagnostic_final_cb;
230 /* Maybe initialize the color support. We require clients to do this
231 explicitly, since most clients don't want color. When called
232 without a VALUE, it initializes with DIAGNOSTICS_COLOR_DEFAULT. */
234 void
235 diagnostic_color_init (diagnostic_context *context, int value /*= -1 */)
237 /* value == -1 is the default value. */
238 if (value < 0)
240 /* If DIAGNOSTICS_COLOR_DEFAULT is -1, default to
241 -fdiagnostics-color=auto if GCC_COLORS is in the environment,
242 otherwise default to -fdiagnostics-color=never, for other
243 values default to that
244 -fdiagnostics-color={never,auto,always}. */
245 if (DIAGNOSTICS_COLOR_DEFAULT == -1)
247 if (!getenv ("GCC_COLORS"))
248 return;
249 value = DIAGNOSTICS_COLOR_AUTO;
251 else
252 value = DIAGNOSTICS_COLOR_DEFAULT;
254 pp_show_color (context->printer)
255 = colorize_init ((diagnostic_color_rule_t) value);
258 /* Initialize URL support within CONTEXT based on VALUE, handling "auto". */
260 void
261 diagnostic_urls_init (diagnostic_context *context, int value /*= -1 */)
263 /* value == -1 is the default value. */
264 if (value < 0)
266 /* If DIAGNOSTICS_URLS_DEFAULT is -1, default to
267 -fdiagnostics-urls=auto if GCC_URLS or TERM_URLS is in the
268 environment, otherwise default to -fdiagnostics-urls=never,
269 for other values default to that
270 -fdiagnostics-urls={never,auto,always}. */
271 if (DIAGNOSTICS_URLS_DEFAULT == -1)
273 if (!getenv ("GCC_URLS") && !getenv ("TERM_URLS"))
274 return;
275 value = DIAGNOSTICS_URL_AUTO;
277 else
278 value = DIAGNOSTICS_URLS_DEFAULT;
281 context->printer->url_format
282 = determine_url_format ((diagnostic_url_rule_t) value);
285 /* Do any cleaning up required after the last diagnostic is emitted. */
287 void
288 diagnostic_finish (diagnostic_context *context)
290 if (context->final_cb)
291 context->final_cb (context);
293 diagnostic_file_cache_fini ();
295 XDELETEVEC (context->classify_diagnostic);
296 context->classify_diagnostic = NULL;
298 /* diagnostic_initialize allocates context->printer using XNEW
299 and placement-new. */
300 context->printer->~pretty_printer ();
301 XDELETE (context->printer);
302 context->printer = NULL;
304 if (context->edit_context_ptr)
306 delete context->edit_context_ptr;
307 context->edit_context_ptr = NULL;
311 /* Initialize DIAGNOSTIC, where the message MSG has already been
312 translated. */
313 void
314 diagnostic_set_info_translated (diagnostic_info *diagnostic, const char *msg,
315 va_list *args, rich_location *richloc,
316 diagnostic_t kind)
318 gcc_assert (richloc);
319 diagnostic->message.err_no = errno;
320 diagnostic->message.args_ptr = args;
321 diagnostic->message.format_spec = msg;
322 diagnostic->message.m_richloc = richloc;
323 diagnostic->richloc = richloc;
324 diagnostic->metadata = NULL;
325 diagnostic->kind = kind;
326 diagnostic->option_index = 0;
329 /* Initialize DIAGNOSTIC, where the message GMSGID has not yet been
330 translated. */
331 void
332 diagnostic_set_info (diagnostic_info *diagnostic, const char *gmsgid,
333 va_list *args, rich_location *richloc,
334 diagnostic_t kind)
336 gcc_assert (richloc);
337 diagnostic_set_info_translated (diagnostic, _(gmsgid), args, richloc, kind);
340 static const char *const diagnostic_kind_color[] = {
341 #define DEFINE_DIAGNOSTIC_KIND(K, T, C) (C),
342 #include "diagnostic.def"
343 #undef DEFINE_DIAGNOSTIC_KIND
344 NULL
347 /* Get a color name for diagnostics of type KIND
348 Result could be NULL. */
350 const char *
351 diagnostic_get_color_for_kind (diagnostic_t kind)
353 return diagnostic_kind_color[kind];
356 /* Return a formatted line and column ':%line:%column'. Elided if
357 zero. The result is a statically allocated buffer. */
359 static const char *
360 maybe_line_and_column (int line, int col)
362 static char result[32];
364 if (line)
366 size_t l = snprintf (result, sizeof (result),
367 col ? ":%d:%d" : ":%d", line, col);
368 gcc_checking_assert (l < sizeof (result));
370 else
371 result[0] = 0;
372 return result;
375 /* Return a malloc'd string describing a location e.g. "foo.c:42:10".
376 The caller is responsible for freeing the memory. */
378 static char *
379 diagnostic_get_location_text (diagnostic_context *context,
380 expanded_location s)
382 pretty_printer *pp = context->printer;
383 const char *locus_cs = colorize_start (pp_show_color (pp), "locus");
384 const char *locus_ce = colorize_stop (pp_show_color (pp));
385 const char *file = s.file ? s.file : progname;
386 int line = strcmp (file, N_("<built-in>")) ? s.line : 0;
387 int col = context->show_column ? s.column : 0;
389 const char *line_col = maybe_line_and_column (line, col);
390 return build_message_string ("%s%s%s:%s", locus_cs, file,
391 line_col, locus_ce);
394 /* Return a malloc'd string describing a location and the severity of the
395 diagnostic, e.g. "foo.c:42:10: error: ". The caller is responsible for
396 freeing the memory. */
397 char *
398 diagnostic_build_prefix (diagnostic_context *context,
399 const diagnostic_info *diagnostic)
401 static const char *const diagnostic_kind_text[] = {
402 #define DEFINE_DIAGNOSTIC_KIND(K, T, C) (T),
403 #include "diagnostic.def"
404 #undef DEFINE_DIAGNOSTIC_KIND
405 "must-not-happen"
407 gcc_assert (diagnostic->kind < DK_LAST_DIAGNOSTIC_KIND);
409 const char *text = _(diagnostic_kind_text[diagnostic->kind]);
410 const char *text_cs = "", *text_ce = "";
411 pretty_printer *pp = context->printer;
413 if (diagnostic_kind_color[diagnostic->kind])
415 text_cs = colorize_start (pp_show_color (pp),
416 diagnostic_kind_color[diagnostic->kind]);
417 text_ce = colorize_stop (pp_show_color (pp));
420 expanded_location s = diagnostic_expand_location (diagnostic);
421 char *location_text = diagnostic_get_location_text (context, s);
423 char *result = build_message_string ("%s %s%s%s", location_text,
424 text_cs, text, text_ce);
425 free (location_text);
426 return result;
429 /* Functions at which to stop the backtrace print. It's not
430 particularly helpful to print the callers of these functions. */
432 static const char * const bt_stop[] =
434 "main",
435 "toplev::main",
436 "execute_one_pass",
437 "compile_file",
440 /* A callback function passed to the backtrace_full function. */
442 static int
443 bt_callback (void *data, uintptr_t pc, const char *filename, int lineno,
444 const char *function)
446 int *pcount = (int *) data;
448 /* If we don't have any useful information, don't print
449 anything. */
450 if (filename == NULL && function == NULL)
451 return 0;
453 /* Skip functions in diagnostic.c. */
454 if (*pcount == 0
455 && filename != NULL
456 && strcmp (lbasename (filename), "diagnostic.c") == 0)
457 return 0;
459 /* Print up to 20 functions. We could make this a --param, but
460 since this is only for debugging just use a constant for now. */
461 if (*pcount >= 20)
463 /* Returning a non-zero value stops the backtrace. */
464 return 1;
466 ++*pcount;
468 char *alc = NULL;
469 if (function != NULL)
471 char *str = cplus_demangle_v3 (function,
472 (DMGL_VERBOSE | DMGL_ANSI
473 | DMGL_GNU_V3 | DMGL_PARAMS));
474 if (str != NULL)
476 alc = str;
477 function = str;
480 for (size_t i = 0; i < ARRAY_SIZE (bt_stop); ++i)
482 size_t len = strlen (bt_stop[i]);
483 if (strncmp (function, bt_stop[i], len) == 0
484 && (function[len] == '\0' || function[len] == '('))
486 if (alc != NULL)
487 free (alc);
488 /* Returning a non-zero value stops the backtrace. */
489 return 1;
494 fprintf (stderr, "0x%lx %s\n\t%s:%d\n",
495 (unsigned long) pc,
496 function == NULL ? "???" : function,
497 filename == NULL ? "???" : filename,
498 lineno);
500 if (alc != NULL)
501 free (alc);
503 return 0;
506 /* A callback function passed to the backtrace_full function. This is
507 called if backtrace_full has an error. */
509 static void
510 bt_err_callback (void *data ATTRIBUTE_UNUSED, const char *msg, int errnum)
512 if (errnum < 0)
514 /* This means that no debug info was available. Just quietly
515 skip printing backtrace info. */
516 return;
518 fprintf (stderr, "%s%s%s\n", msg, errnum == 0 ? "" : ": ",
519 errnum == 0 ? "" : xstrerror (errnum));
522 /* Check if we've met the maximum error limit, and if so fatally exit
523 with a message. CONTEXT is the context to check, and FLUSH
524 indicates whether a diagnostic_finish call is needed. */
526 void
527 diagnostic_check_max_errors (diagnostic_context *context, bool flush)
529 if (!context->max_errors)
530 return;
532 int count = (diagnostic_kind_count (context, DK_ERROR)
533 + diagnostic_kind_count (context, DK_SORRY)
534 + diagnostic_kind_count (context, DK_WERROR));
536 if (count >= context->max_errors)
538 fnotice (stderr,
539 "compilation terminated due to -fmax-errors=%u.\n",
540 context->max_errors);
541 if (flush)
542 diagnostic_finish (context);
543 exit (FATAL_EXIT_CODE);
547 /* Take any action which is expected to happen after the diagnostic
548 is written out. This function does not always return. */
549 void
550 diagnostic_action_after_output (diagnostic_context *context,
551 diagnostic_t diag_kind)
553 switch (diag_kind)
555 case DK_DEBUG:
556 case DK_NOTE:
557 case DK_ANACHRONISM:
558 case DK_WARNING:
559 break;
561 case DK_ERROR:
562 case DK_SORRY:
563 if (context->abort_on_error)
564 real_abort ();
565 if (context->fatal_errors)
567 fnotice (stderr, "compilation terminated due to -Wfatal-errors.\n");
568 diagnostic_finish (context);
569 exit (FATAL_EXIT_CODE);
571 break;
573 case DK_ICE:
574 case DK_ICE_NOBT:
576 struct backtrace_state *state = NULL;
577 if (diag_kind == DK_ICE)
578 state = backtrace_create_state (NULL, 0, bt_err_callback, NULL);
579 int count = 0;
580 if (state != NULL)
581 backtrace_full (state, 2, bt_callback, bt_err_callback,
582 (void *) &count);
584 if (context->abort_on_error)
585 real_abort ();
587 fnotice (stderr, "Please submit a full bug report,\n"
588 "with preprocessed source if appropriate.\n");
589 if (count > 0)
590 fnotice (stderr,
591 ("Please include the complete backtrace "
592 "with any bug report.\n"));
593 fnotice (stderr, "See %s for instructions.\n", bug_report_url);
595 exit (ICE_EXIT_CODE);
598 case DK_FATAL:
599 if (context->abort_on_error)
600 real_abort ();
601 diagnostic_finish (context);
602 fnotice (stderr, "compilation terminated.\n");
603 exit (FATAL_EXIT_CODE);
605 default:
606 gcc_unreachable ();
610 /* True if the last module or file in which a diagnostic was reported is
611 different from the current one. */
613 static bool
614 last_module_changed_p (diagnostic_context *context,
615 const line_map_ordinary *map)
617 return context->last_module != map;
620 /* Remember the current module or file as being the last one in which we
621 report a diagnostic. */
623 static void
624 set_last_module (diagnostic_context *context, const line_map_ordinary *map)
626 context->last_module = map;
629 void
630 diagnostic_report_current_module (diagnostic_context *context, location_t where)
632 const line_map_ordinary *map = NULL;
634 if (pp_needs_newline (context->printer))
636 pp_newline (context->printer);
637 pp_needs_newline (context->printer) = false;
640 if (where <= BUILTINS_LOCATION)
641 return;
643 linemap_resolve_location (line_table, where,
644 LRK_MACRO_DEFINITION_LOCATION,
645 &map);
647 if (map && last_module_changed_p (context, map))
649 set_last_module (context, map);
650 if (! MAIN_FILE_P (map))
652 bool first = true;
655 where = linemap_included_from (map);
656 map = linemap_included_from_linemap (line_table, map);
657 const char *line_col
658 = maybe_line_and_column (SOURCE_LINE (map, where),
659 first && context->show_column
660 ? SOURCE_COLUMN (map, where) : 0);
661 static const char *const msgs[] =
663 N_("In file included from"),
664 N_(" from"),
666 unsigned index = !first;
667 pp_verbatim (context->printer, "%s%s %r%s%s%R",
668 first ? "" : ",\n", _(msgs[index]),
669 "locus", LINEMAP_FILE (map), line_col);
670 first = false;
672 while (! MAIN_FILE_P (map));
673 pp_verbatim (context->printer, ":");
674 pp_newline (context->printer);
679 /* If DIAGNOSTIC has a diagnostic_path and CONTEXT supports printing paths,
680 print the path. */
682 void
683 diagnostic_show_any_path (diagnostic_context *context,
684 diagnostic_info *diagnostic)
686 const diagnostic_path *path = diagnostic->richloc->get_path ();
687 if (!path)
688 return;
690 if (context->print_path)
691 context->print_path (context, path);
694 /* Return true if the events in this path involve more than one
695 function, or false if it is purely intraprocedural. */
697 bool
698 diagnostic_path::interprocedural_p () const
700 const unsigned num = num_events ();
701 for (unsigned i = 0; i < num; i++)
703 if (get_event (i).get_fndecl () != get_event (0).get_fndecl ())
704 return true;
705 if (get_event (i).get_stack_depth () != get_event (0).get_stack_depth ())
706 return true;
708 return false;
711 void
712 default_diagnostic_starter (diagnostic_context *context,
713 diagnostic_info *diagnostic)
715 diagnostic_report_current_module (context, diagnostic_location (diagnostic));
716 pp_set_prefix (context->printer, diagnostic_build_prefix (context,
717 diagnostic));
720 void
721 default_diagnostic_start_span_fn (diagnostic_context *context,
722 expanded_location exploc)
724 char *text = diagnostic_get_location_text (context, exploc);
725 pp_string (context->printer, text);
726 free (text);
727 pp_newline (context->printer);
730 void
731 default_diagnostic_finalizer (diagnostic_context *context,
732 diagnostic_info *diagnostic,
733 diagnostic_t)
735 char *saved_prefix = pp_take_prefix (context->printer);
736 pp_set_prefix (context->printer, NULL);
737 pp_newline (context->printer);
738 diagnostic_show_locus (context, diagnostic->richloc, diagnostic->kind);
739 pp_set_prefix (context->printer, saved_prefix);
740 pp_flush (context->printer);
743 /* Interface to specify diagnostic kind overrides. Returns the
744 previous setting, or DK_UNSPECIFIED if the parameters are out of
745 range. If OPTION_INDEX is zero, the new setting is for all the
746 diagnostics. */
747 diagnostic_t
748 diagnostic_classify_diagnostic (diagnostic_context *context,
749 int option_index,
750 diagnostic_t new_kind,
751 location_t where)
753 diagnostic_t old_kind;
755 if (option_index < 0
756 || option_index >= context->n_opts
757 || new_kind >= DK_LAST_DIAGNOSTIC_KIND)
758 return DK_UNSPECIFIED;
760 old_kind = context->classify_diagnostic[option_index];
762 /* Handle pragmas separately, since we need to keep track of *where*
763 the pragmas were. */
764 if (where != UNKNOWN_LOCATION)
766 int i;
768 /* Record the command-line status, so we can reset it back on DK_POP. */
769 if (old_kind == DK_UNSPECIFIED)
771 old_kind = !context->option_enabled (option_index,
772 context->lang_mask,
773 context->option_state)
774 ? DK_IGNORED : (context->warning_as_error_requested
775 ? DK_ERROR : DK_WARNING);
776 context->classify_diagnostic[option_index] = old_kind;
779 for (i = context->n_classification_history - 1; i >= 0; i --)
780 if (context->classification_history[i].option == option_index)
782 old_kind = context->classification_history[i].kind;
783 break;
786 i = context->n_classification_history;
787 context->classification_history =
788 (diagnostic_classification_change_t *) xrealloc (context->classification_history, (i + 1)
789 * sizeof (diagnostic_classification_change_t));
790 context->classification_history[i].location = where;
791 context->classification_history[i].option = option_index;
792 context->classification_history[i].kind = new_kind;
793 context->n_classification_history ++;
795 else
796 context->classify_diagnostic[option_index] = new_kind;
798 return old_kind;
801 /* Save all diagnostic classifications in a stack. */
802 void
803 diagnostic_push_diagnostics (diagnostic_context *context, location_t where ATTRIBUTE_UNUSED)
805 context->push_list = (int *) xrealloc (context->push_list, (context->n_push + 1) * sizeof (int));
806 context->push_list[context->n_push ++] = context->n_classification_history;
809 /* Restore the topmost classification set off the stack. If the stack
810 is empty, revert to the state based on command line parameters. */
811 void
812 diagnostic_pop_diagnostics (diagnostic_context *context, location_t where)
814 int jump_to;
815 int i;
817 if (context->n_push)
818 jump_to = context->push_list [-- context->n_push];
819 else
820 jump_to = 0;
822 i = context->n_classification_history;
823 context->classification_history =
824 (diagnostic_classification_change_t *) xrealloc (context->classification_history, (i + 1)
825 * sizeof (diagnostic_classification_change_t));
826 context->classification_history[i].location = where;
827 context->classification_history[i].option = jump_to;
828 context->classification_history[i].kind = DK_POP;
829 context->n_classification_history ++;
832 /* Helper function for print_parseable_fixits. Print TEXT to PP, obeying the
833 escaping rules for -fdiagnostics-parseable-fixits. */
835 static void
836 print_escaped_string (pretty_printer *pp, const char *text)
838 gcc_assert (pp);
839 gcc_assert (text);
841 pp_character (pp, '"');
842 for (const char *ch = text; *ch; ch++)
844 switch (*ch)
846 case '\\':
847 /* Escape backslash as two backslashes. */
848 pp_string (pp, "\\\\");
849 break;
850 case '\t':
851 /* Escape tab as "\t". */
852 pp_string (pp, "\\t");
853 break;
854 case '\n':
855 /* Escape newline as "\n". */
856 pp_string (pp, "\\n");
857 break;
858 case '"':
859 /* Escape doublequotes as \". */
860 pp_string (pp, "\\\"");
861 break;
862 default:
863 if (ISPRINT (*ch))
864 pp_character (pp, *ch);
865 else
866 /* Use octal for non-printable chars. */
868 unsigned char c = (*ch & 0xff);
869 pp_printf (pp, "\\%o%o%o", (c / 64), (c / 8) & 007, c & 007);
871 break;
874 pp_character (pp, '"');
877 /* Implementation of -fdiagnostics-parseable-fixits. Print a
878 machine-parseable version of all fixits in RICHLOC to PP. */
880 static void
881 print_parseable_fixits (pretty_printer *pp, rich_location *richloc)
883 gcc_assert (pp);
884 gcc_assert (richloc);
886 char *saved_prefix = pp_take_prefix (pp);
887 pp_set_prefix (pp, NULL);
889 for (unsigned i = 0; i < richloc->get_num_fixit_hints (); i++)
891 const fixit_hint *hint = richloc->get_fixit_hint (i);
892 location_t start_loc = hint->get_start_loc ();
893 expanded_location start_exploc = expand_location (start_loc);
894 pp_string (pp, "fix-it:");
895 print_escaped_string (pp, start_exploc.file);
896 /* For compatibility with clang, print as a half-open range. */
897 location_t next_loc = hint->get_next_loc ();
898 expanded_location next_exploc = expand_location (next_loc);
899 pp_printf (pp, ":{%i:%i-%i:%i}:",
900 start_exploc.line, start_exploc.column,
901 next_exploc.line, next_exploc.column);
902 print_escaped_string (pp, hint->get_string ());
903 pp_newline (pp);
906 pp_set_prefix (pp, saved_prefix);
909 /* Update the diag_class of DIAGNOSTIC based on its location
910 relative to any
911 #pragma GCC diagnostic
912 directives recorded within CONTEXT.
914 Return the new diag_class of DIAGNOSTIC if it was updated, or
915 DK_UNSPECIFIED otherwise. */
917 static diagnostic_t
918 update_effective_level_from_pragmas (diagnostic_context *context,
919 diagnostic_info *diagnostic)
921 diagnostic_t diag_class = DK_UNSPECIFIED;
923 if (context->n_classification_history > 0)
925 location_t location = diagnostic_location (diagnostic);
927 /* FIXME: Stupid search. Optimize later. */
928 for (int i = context->n_classification_history - 1; i >= 0; i --)
930 if (linemap_location_before_p
931 (line_table,
932 context->classification_history[i].location,
933 location))
935 if (context->classification_history[i].kind == (int) DK_POP)
937 i = context->classification_history[i].option;
938 continue;
940 int option = context->classification_history[i].option;
941 /* The option 0 is for all the diagnostics. */
942 if (option == 0 || option == diagnostic->option_index)
944 diag_class = context->classification_history[i].kind;
945 if (diag_class != DK_UNSPECIFIED)
946 diagnostic->kind = diag_class;
947 break;
953 return diag_class;
956 /* Generate a URL string describing CWE. The caller is responsible for
957 freeing the string. */
959 static char *
960 get_cwe_url (int cwe)
962 return xasprintf ("https://cwe.mitre.org/data/definitions/%i.html", cwe);
965 /* If DIAGNOSTIC has a CWE identifier, print it.
967 For example, if the diagnostic metadata associates it with CWE-119,
968 " [CWE-119]" will be printed, suitably colorized, and with a URL of a
969 description of the security issue. */
971 static void
972 print_any_cwe (diagnostic_context *context,
973 const diagnostic_info *diagnostic)
975 if (diagnostic->metadata == NULL)
976 return;
978 int cwe = diagnostic->metadata->get_cwe ();
979 if (cwe)
981 pretty_printer *pp = context->printer;
982 char *saved_prefix = pp_take_prefix (context->printer);
983 pp_string (pp, " [");
984 pp_string (pp, colorize_start (pp_show_color (pp),
985 diagnostic_kind_color[diagnostic->kind]));
986 char *cwe_url = get_cwe_url (cwe);
987 pp_begin_url (pp, cwe_url);
988 free (cwe_url);
989 pp_printf (pp, "CWE-%i", cwe);
990 pp_set_prefix (context->printer, saved_prefix);
991 pp_end_url (pp);
992 pp_string (pp, colorize_stop (pp_show_color (pp)));
993 pp_character (pp, ']');
997 /* Print any metadata about the option used to control DIAGNOSTIC to CONTEXT's
998 printer, e.g. " [-Werror=uninitialized]".
999 Subroutine of diagnostic_report_diagnostic. */
1001 static void
1002 print_option_information (diagnostic_context *context,
1003 const diagnostic_info *diagnostic,
1004 diagnostic_t orig_diag_kind)
1006 char *option_text;
1008 option_text = context->option_name (context, diagnostic->option_index,
1009 orig_diag_kind, diagnostic->kind);
1011 if (option_text)
1013 char *option_url = NULL;
1014 if (context->get_option_url)
1015 option_url = context->get_option_url (context,
1016 diagnostic->option_index);
1017 pretty_printer *pp = context->printer;
1018 pp_string (pp, " [");
1019 pp_string (pp, colorize_start (pp_show_color (pp),
1020 diagnostic_kind_color[diagnostic->kind]));
1021 if (option_url)
1022 pp_begin_url (pp, option_url);
1023 pp_string (pp, option_text);
1024 if (option_url)
1026 pp_end_url (pp);
1027 free (option_url);
1029 pp_string (pp, colorize_stop (pp_show_color (pp)));
1030 pp_character (pp, ']');
1031 free (option_text);
1035 /* Report a diagnostic message (an error or a warning) as specified by
1036 DC. This function is *the* subroutine in terms of which front-ends
1037 should implement their specific diagnostic handling modules. The
1038 front-end independent format specifiers are exactly those described
1039 in the documentation of output_format.
1040 Return true if a diagnostic was printed, false otherwise. */
1042 bool
1043 diagnostic_report_diagnostic (diagnostic_context *context,
1044 diagnostic_info *diagnostic)
1046 location_t location = diagnostic_location (diagnostic);
1047 diagnostic_t orig_diag_kind = diagnostic->kind;
1049 /* Give preference to being able to inhibit warnings, before they
1050 get reclassified to something else. */
1051 if ((diagnostic->kind == DK_WARNING || diagnostic->kind == DK_PEDWARN)
1052 && !diagnostic_report_warnings_p (context, location))
1053 return false;
1055 if (diagnostic->kind == DK_PEDWARN)
1057 diagnostic->kind = pedantic_warning_kind (context);
1058 /* We do this to avoid giving the message for -pedantic-errors. */
1059 orig_diag_kind = diagnostic->kind;
1062 if (diagnostic->kind == DK_NOTE && context->inhibit_notes_p)
1063 return false;
1065 if (context->lock > 0)
1067 /* If we're reporting an ICE in the middle of some other error,
1068 try to flush out the previous error, then let this one
1069 through. Don't do this more than once. */
1070 if ((diagnostic->kind == DK_ICE || diagnostic->kind == DK_ICE_NOBT)
1071 && context->lock == 1)
1072 pp_newline_and_flush (context->printer);
1073 else
1074 error_recursion (context);
1077 /* If the user requested that warnings be treated as errors, so be
1078 it. Note that we do this before the next block so that
1079 individual warnings can be overridden back to warnings with
1080 -Wno-error=*. */
1081 if (context->warning_as_error_requested
1082 && diagnostic->kind == DK_WARNING)
1083 diagnostic->kind = DK_ERROR;
1085 if (diagnostic->option_index
1086 && diagnostic->option_index != permissive_error_option (context))
1088 /* This tests if the user provided the appropriate -Wfoo or
1089 -Wno-foo option. */
1090 if (! context->option_enabled (diagnostic->option_index,
1091 context->lang_mask,
1092 context->option_state))
1093 return false;
1095 /* This tests for #pragma diagnostic changes. */
1096 diagnostic_t diag_class
1097 = update_effective_level_from_pragmas (context, diagnostic);
1099 /* This tests if the user provided the appropriate -Werror=foo
1100 option. */
1101 if (diag_class == DK_UNSPECIFIED
1102 && (context->classify_diagnostic[diagnostic->option_index]
1103 != DK_UNSPECIFIED))
1104 diagnostic->kind
1105 = context->classify_diagnostic[diagnostic->option_index];
1107 /* This allows for future extensions, like temporarily disabling
1108 warnings for ranges of source code. */
1109 if (diagnostic->kind == DK_IGNORED)
1110 return false;
1113 if (diagnostic->kind != DK_NOTE)
1114 diagnostic_check_max_errors (context);
1116 context->lock++;
1118 if (diagnostic->kind == DK_ICE || diagnostic->kind == DK_ICE_NOBT)
1120 /* When not checking, ICEs are converted to fatal errors when an
1121 error has already occurred. This is counteracted by
1122 abort_on_error. */
1123 if (!CHECKING_P
1124 && (diagnostic_kind_count (context, DK_ERROR) > 0
1125 || diagnostic_kind_count (context, DK_SORRY) > 0)
1126 && !context->abort_on_error)
1128 expanded_location s
1129 = expand_location (diagnostic_location (diagnostic));
1130 fnotice (stderr, "%s:%d: confused by earlier errors, bailing out\n",
1131 s.file, s.line);
1132 exit (ICE_EXIT_CODE);
1134 if (context->internal_error)
1135 (*context->internal_error) (context,
1136 diagnostic->message.format_spec,
1137 diagnostic->message.args_ptr);
1139 if (diagnostic->kind == DK_ERROR && orig_diag_kind == DK_WARNING)
1140 ++diagnostic_kind_count (context, DK_WERROR);
1141 else
1142 ++diagnostic_kind_count (context, diagnostic->kind);
1144 /* Is this the initial diagnostic within the stack of groups? */
1145 if (context->diagnostic_group_emission_count == 0)
1147 if (context->begin_group_cb)
1148 context->begin_group_cb (context);
1150 context->diagnostic_group_emission_count++;
1152 diagnostic->message.x_data = &diagnostic->x_data;
1153 diagnostic->x_data = NULL;
1154 pp_format (context->printer, &diagnostic->message);
1155 (*diagnostic_starter (context)) (context, diagnostic);
1156 pp_output_formatted_text (context->printer);
1157 if (context->show_cwe)
1158 print_any_cwe (context, diagnostic);
1159 if (context->show_option_requested)
1160 print_option_information (context, diagnostic, orig_diag_kind);
1161 (*diagnostic_finalizer (context)) (context, diagnostic, orig_diag_kind);
1162 if (context->parseable_fixits_p)
1164 print_parseable_fixits (context->printer, diagnostic->richloc);
1165 pp_flush (context->printer);
1167 diagnostic_action_after_output (context, diagnostic->kind);
1168 diagnostic->x_data = NULL;
1170 if (context->edit_context_ptr)
1171 if (diagnostic->richloc->fixits_can_be_auto_applied_p ())
1172 context->edit_context_ptr->add_fixits (diagnostic->richloc);
1174 context->lock--;
1176 diagnostic_show_any_path (context, diagnostic);
1178 return true;
1181 /* Get the number of digits in the decimal representation of VALUE. */
1184 num_digits (int value)
1186 /* Perhaps simpler to use log10 for this, but doing it this way avoids
1187 using floating point. */
1188 gcc_assert (value >= 0);
1190 if (value == 0)
1191 return 1;
1193 int digits = 0;
1194 while (value > 0)
1196 digits++;
1197 value /= 10;
1199 return digits;
1202 /* Given a partial pathname as input, return another pathname that
1203 shares no directory elements with the pathname of __FILE__. This
1204 is used by fancy_abort() to print `Internal compiler error in expr.c'
1205 instead of `Internal compiler error in ../../GCC/gcc/expr.c'. */
1207 const char *
1208 trim_filename (const char *name)
1210 static const char this_file[] = __FILE__;
1211 const char *p = name, *q = this_file;
1213 /* First skip any "../" in each filename. This allows us to give a proper
1214 reference to a file in a subdirectory. */
1215 while (p[0] == '.' && p[1] == '.' && IS_DIR_SEPARATOR (p[2]))
1216 p += 3;
1218 while (q[0] == '.' && q[1] == '.' && IS_DIR_SEPARATOR (q[2]))
1219 q += 3;
1221 /* Now skip any parts the two filenames have in common. */
1222 while (*p == *q && *p != 0 && *q != 0)
1223 p++, q++;
1225 /* Now go backwards until the previous directory separator. */
1226 while (p > name && !IS_DIR_SEPARATOR (p[-1]))
1227 p--;
1229 return p;
1232 /* Standard error reporting routines in increasing order of severity.
1233 All of these take arguments like printf. */
1235 /* Text to be emitted verbatim to the error message stream; this
1236 produces no prefix and disables line-wrapping. Use rarely. */
1237 void
1238 verbatim (const char *gmsgid, ...)
1240 text_info text;
1241 va_list ap;
1243 va_start (ap, gmsgid);
1244 text.err_no = errno;
1245 text.args_ptr = &ap;
1246 text.format_spec = _(gmsgid);
1247 text.x_data = NULL;
1248 pp_format_verbatim (global_dc->printer, &text);
1249 pp_newline_and_flush (global_dc->printer);
1250 va_end (ap);
1253 /* Add a note with text GMSGID and with LOCATION to the diagnostic CONTEXT. */
1254 void
1255 diagnostic_append_note (diagnostic_context *context,
1256 location_t location,
1257 const char * gmsgid, ...)
1259 diagnostic_info diagnostic;
1260 va_list ap;
1261 rich_location richloc (line_table, location);
1263 va_start (ap, gmsgid);
1264 diagnostic_set_info (&diagnostic, gmsgid, &ap, &richloc, DK_NOTE);
1265 if (context->inhibit_notes_p)
1267 va_end (ap);
1268 return;
1270 char *saved_prefix = pp_take_prefix (context->printer);
1271 pp_set_prefix (context->printer,
1272 diagnostic_build_prefix (context, &diagnostic));
1273 pp_format (context->printer, &diagnostic.message);
1274 pp_output_formatted_text (context->printer);
1275 pp_destroy_prefix (context->printer);
1276 pp_set_prefix (context->printer, saved_prefix);
1277 pp_newline (context->printer);
1278 diagnostic_show_locus (context, &richloc, DK_NOTE);
1279 va_end (ap);
1282 /* Implement emit_diagnostic, inform, warning, warning_at, pedwarn,
1283 permerror, error, error_at, error_at, sorry, fatal_error, internal_error,
1284 and internal_error_no_backtrace, as documented and defined below. */
1285 static bool
1286 diagnostic_impl (rich_location *richloc, const diagnostic_metadata *metadata,
1287 int opt, const char *gmsgid,
1288 va_list *ap, diagnostic_t kind)
1290 diagnostic_info diagnostic;
1291 if (kind == DK_PERMERROR)
1293 diagnostic_set_info (&diagnostic, gmsgid, ap, richloc,
1294 permissive_error_kind (global_dc));
1295 diagnostic.option_index = permissive_error_option (global_dc);
1297 else
1299 diagnostic_set_info (&diagnostic, gmsgid, ap, richloc, kind);
1300 if (kind == DK_WARNING || kind == DK_PEDWARN)
1301 diagnostic.option_index = opt;
1303 diagnostic.metadata = metadata;
1304 return diagnostic_report_diagnostic (global_dc, &diagnostic);
1307 /* Implement inform_n, warning_n, and error_n, as documented and
1308 defined below. */
1309 static bool
1310 diagnostic_n_impl (rich_location *richloc, const diagnostic_metadata *metadata,
1311 int opt, unsigned HOST_WIDE_INT n,
1312 const char *singular_gmsgid,
1313 const char *plural_gmsgid,
1314 va_list *ap, diagnostic_t kind)
1316 diagnostic_info diagnostic;
1317 unsigned long gtn;
1319 if (sizeof n <= sizeof gtn)
1320 gtn = n;
1321 else
1322 /* Use the largest number ngettext can handle, otherwise
1323 preserve the six least significant decimal digits for
1324 languages where the plural form depends on them. */
1325 gtn = n <= ULONG_MAX ? n : n % 1000000LU + 1000000LU;
1327 const char *text = ngettext (singular_gmsgid, plural_gmsgid, gtn);
1328 diagnostic_set_info_translated (&diagnostic, text, ap, richloc, kind);
1329 if (kind == DK_WARNING)
1330 diagnostic.option_index = opt;
1331 diagnostic.metadata = metadata;
1332 return diagnostic_report_diagnostic (global_dc, &diagnostic);
1335 /* Wrapper around diagnostic_impl taking a variable argument list. */
1337 bool
1338 emit_diagnostic (diagnostic_t kind, location_t location, int opt,
1339 const char *gmsgid, ...)
1341 auto_diagnostic_group d;
1342 va_list ap;
1343 va_start (ap, gmsgid);
1344 rich_location richloc (line_table, location);
1345 bool ret = diagnostic_impl (&richloc, NULL, opt, gmsgid, &ap, kind);
1346 va_end (ap);
1347 return ret;
1350 /* As above, but for rich_location *. */
1352 bool
1353 emit_diagnostic (diagnostic_t kind, rich_location *richloc, int opt,
1354 const char *gmsgid, ...)
1356 auto_diagnostic_group d;
1357 va_list ap;
1358 va_start (ap, gmsgid);
1359 bool ret = diagnostic_impl (richloc, NULL, opt, gmsgid, &ap, kind);
1360 va_end (ap);
1361 return ret;
1364 /* Wrapper around diagnostic_impl taking a va_list parameter. */
1366 bool
1367 emit_diagnostic_valist (diagnostic_t kind, location_t location, int opt,
1368 const char *gmsgid, va_list *ap)
1370 rich_location richloc (line_table, location);
1371 return diagnostic_impl (&richloc, NULL, opt, gmsgid, ap, kind);
1374 /* An informative note at LOCATION. Use this for additional details on an error
1375 message. */
1376 void
1377 inform (location_t location, const char *gmsgid, ...)
1379 auto_diagnostic_group d;
1380 va_list ap;
1381 va_start (ap, gmsgid);
1382 rich_location richloc (line_table, location);
1383 diagnostic_impl (&richloc, NULL, -1, gmsgid, &ap, DK_NOTE);
1384 va_end (ap);
1387 /* Same as "inform" above, but at RICHLOC. */
1388 void
1389 inform (rich_location *richloc, const char *gmsgid, ...)
1391 gcc_assert (richloc);
1393 auto_diagnostic_group d;
1394 va_list ap;
1395 va_start (ap, gmsgid);
1396 diagnostic_impl (richloc, NULL, -1, gmsgid, &ap, DK_NOTE);
1397 va_end (ap);
1400 /* An informative note at LOCATION. Use this for additional details on an
1401 error message. */
1402 void
1403 inform_n (location_t location, unsigned HOST_WIDE_INT n,
1404 const char *singular_gmsgid, const char *plural_gmsgid, ...)
1406 va_list ap;
1407 va_start (ap, plural_gmsgid);
1408 auto_diagnostic_group d;
1409 rich_location richloc (line_table, location);
1410 diagnostic_n_impl (&richloc, NULL, -1, n, singular_gmsgid, plural_gmsgid,
1411 &ap, DK_NOTE);
1412 va_end (ap);
1415 /* A warning at INPUT_LOCATION. Use this for code which is correct according
1416 to the relevant language specification but is likely to be buggy anyway.
1417 Returns true if the warning was printed, false if it was inhibited. */
1418 bool
1419 warning (int opt, const char *gmsgid, ...)
1421 auto_diagnostic_group d;
1422 va_list ap;
1423 va_start (ap, gmsgid);
1424 rich_location richloc (line_table, input_location);
1425 bool ret = diagnostic_impl (&richloc, NULL, opt, gmsgid, &ap, DK_WARNING);
1426 va_end (ap);
1427 return ret;
1430 /* A warning at LOCATION. Use this for code which is correct according to the
1431 relevant language specification but is likely to be buggy anyway.
1432 Returns true if the warning was printed, false if it was inhibited. */
1434 bool
1435 warning_at (location_t location, int opt, const char *gmsgid, ...)
1437 auto_diagnostic_group d;
1438 va_list ap;
1439 va_start (ap, gmsgid);
1440 rich_location richloc (line_table, location);
1441 bool ret = diagnostic_impl (&richloc, NULL, opt, gmsgid, &ap, DK_WARNING);
1442 va_end (ap);
1443 return ret;
1446 /* Same as "warning at" above, but using RICHLOC. */
1448 bool
1449 warning_at (rich_location *richloc, int opt, const char *gmsgid, ...)
1451 gcc_assert (richloc);
1453 auto_diagnostic_group d;
1454 va_list ap;
1455 va_start (ap, gmsgid);
1456 bool ret = diagnostic_impl (richloc, NULL, opt, gmsgid, &ap, DK_WARNING);
1457 va_end (ap);
1458 return ret;
1461 /* Same as "warning at" above, but using METADATA. */
1463 bool
1464 warning_meta (rich_location *richloc,
1465 const diagnostic_metadata &metadata,
1466 int opt, const char *gmsgid, ...)
1468 gcc_assert (richloc);
1470 auto_diagnostic_group d;
1471 va_list ap;
1472 va_start (ap, gmsgid);
1473 bool ret
1474 = diagnostic_impl (richloc, &metadata, opt, gmsgid, &ap,
1475 DK_WARNING);
1476 va_end (ap);
1477 return ret;
1480 /* Same as warning_n plural variant below, but using RICHLOC. */
1482 bool
1483 warning_n (rich_location *richloc, int opt, unsigned HOST_WIDE_INT n,
1484 const char *singular_gmsgid, const char *plural_gmsgid, ...)
1486 gcc_assert (richloc);
1488 auto_diagnostic_group d;
1489 va_list ap;
1490 va_start (ap, plural_gmsgid);
1491 bool ret = diagnostic_n_impl (richloc, NULL, opt, n,
1492 singular_gmsgid, plural_gmsgid,
1493 &ap, DK_WARNING);
1494 va_end (ap);
1495 return ret;
1498 /* A warning at LOCATION. Use this for code which is correct according to the
1499 relevant language specification but is likely to be buggy anyway.
1500 Returns true if the warning was printed, false if it was inhibited. */
1502 bool
1503 warning_n (location_t location, int opt, unsigned HOST_WIDE_INT n,
1504 const char *singular_gmsgid, const char *plural_gmsgid, ...)
1506 auto_diagnostic_group d;
1507 va_list ap;
1508 va_start (ap, plural_gmsgid);
1509 rich_location richloc (line_table, location);
1510 bool ret = diagnostic_n_impl (&richloc, NULL, opt, n,
1511 singular_gmsgid, plural_gmsgid,
1512 &ap, DK_WARNING);
1513 va_end (ap);
1514 return ret;
1517 /* A "pedantic" warning at LOCATION: issues a warning unless
1518 -pedantic-errors was given on the command line, in which case it
1519 issues an error. Use this for diagnostics required by the relevant
1520 language standard, if you have chosen not to make them errors.
1522 Note that these diagnostics are issued independent of the setting
1523 of the -Wpedantic command-line switch. To get a warning enabled
1524 only with that switch, use either "if (pedantic) pedwarn
1525 (OPT_Wpedantic,...)" or just "pedwarn (OPT_Wpedantic,..)". To get a
1526 pedwarn independently of the -Wpedantic switch use "pedwarn (0,...)".
1528 Returns true if the warning was printed, false if it was inhibited. */
1530 bool
1531 pedwarn (location_t location, int opt, const char *gmsgid, ...)
1533 auto_diagnostic_group d;
1534 va_list ap;
1535 va_start (ap, gmsgid);
1536 rich_location richloc (line_table, location);
1537 bool ret = diagnostic_impl (&richloc, NULL, opt, gmsgid, &ap, DK_PEDWARN);
1538 va_end (ap);
1539 return ret;
1542 /* Same as pedwarn above, but using RICHLOC. */
1544 bool
1545 pedwarn (rich_location *richloc, int opt, const char *gmsgid, ...)
1547 gcc_assert (richloc);
1549 auto_diagnostic_group d;
1550 va_list ap;
1551 va_start (ap, gmsgid);
1552 bool ret = diagnostic_impl (richloc, NULL, opt, gmsgid, &ap, DK_PEDWARN);
1553 va_end (ap);
1554 return ret;
1557 /* A "permissive" error at LOCATION: issues an error unless
1558 -fpermissive was given on the command line, in which case it issues
1559 a warning. Use this for things that really should be errors but we
1560 want to support legacy code.
1562 Returns true if the warning was printed, false if it was inhibited. */
1564 bool
1565 permerror (location_t location, const char *gmsgid, ...)
1567 auto_diagnostic_group d;
1568 va_list ap;
1569 va_start (ap, gmsgid);
1570 rich_location richloc (line_table, location);
1571 bool ret = diagnostic_impl (&richloc, NULL, -1, gmsgid, &ap, DK_PERMERROR);
1572 va_end (ap);
1573 return ret;
1576 /* Same as "permerror" above, but at RICHLOC. */
1578 bool
1579 permerror (rich_location *richloc, const char *gmsgid, ...)
1581 gcc_assert (richloc);
1583 auto_diagnostic_group d;
1584 va_list ap;
1585 va_start (ap, gmsgid);
1586 bool ret = diagnostic_impl (richloc, NULL, -1, gmsgid, &ap, DK_PERMERROR);
1587 va_end (ap);
1588 return ret;
1591 /* A hard error: the code is definitely ill-formed, and an object file
1592 will not be produced. */
1593 void
1594 error (const char *gmsgid, ...)
1596 auto_diagnostic_group d;
1597 va_list ap;
1598 va_start (ap, gmsgid);
1599 rich_location richloc (line_table, input_location);
1600 diagnostic_impl (&richloc, NULL, -1, gmsgid, &ap, DK_ERROR);
1601 va_end (ap);
1604 /* A hard error: the code is definitely ill-formed, and an object file
1605 will not be produced. */
1606 void
1607 error_n (location_t location, unsigned HOST_WIDE_INT n,
1608 const char *singular_gmsgid, const char *plural_gmsgid, ...)
1610 auto_diagnostic_group d;
1611 va_list ap;
1612 va_start (ap, plural_gmsgid);
1613 rich_location richloc (line_table, location);
1614 diagnostic_n_impl (&richloc, NULL, -1, n, singular_gmsgid, plural_gmsgid,
1615 &ap, DK_ERROR);
1616 va_end (ap);
1619 /* Same as above, but use location LOC instead of input_location. */
1620 void
1621 error_at (location_t loc, const char *gmsgid, ...)
1623 auto_diagnostic_group d;
1624 va_list ap;
1625 va_start (ap, gmsgid);
1626 rich_location richloc (line_table, loc);
1627 diagnostic_impl (&richloc, NULL, -1, gmsgid, &ap, DK_ERROR);
1628 va_end (ap);
1631 /* Same as above, but use RICH_LOC. */
1633 void
1634 error_at (rich_location *richloc, const char *gmsgid, ...)
1636 gcc_assert (richloc);
1638 auto_diagnostic_group d;
1639 va_list ap;
1640 va_start (ap, gmsgid);
1641 diagnostic_impl (richloc, NULL, -1, gmsgid, &ap, DK_ERROR);
1642 va_end (ap);
1645 /* "Sorry, not implemented." Use for a language feature which is
1646 required by the relevant specification but not implemented by GCC.
1647 An object file will not be produced. */
1648 void
1649 sorry (const char *gmsgid, ...)
1651 auto_diagnostic_group d;
1652 va_list ap;
1653 va_start (ap, gmsgid);
1654 rich_location richloc (line_table, input_location);
1655 diagnostic_impl (&richloc, NULL, -1, gmsgid, &ap, DK_SORRY);
1656 va_end (ap);
1659 /* Same as above, but use location LOC instead of input_location. */
1660 void
1661 sorry_at (location_t loc, const char *gmsgid, ...)
1663 auto_diagnostic_group d;
1664 va_list ap;
1665 va_start (ap, gmsgid);
1666 rich_location richloc (line_table, loc);
1667 diagnostic_impl (&richloc, NULL, -1, gmsgid, &ap, DK_SORRY);
1668 va_end (ap);
1671 /* Return true if an error or a "sorry" has been seen. Various
1672 processing is disabled after errors. */
1673 bool
1674 seen_error (void)
1676 return errorcount || sorrycount;
1679 /* An error which is severe enough that we make no attempt to
1680 continue. Do not use this for internal consistency checks; that's
1681 internal_error. Use of this function should be rare. */
1682 void
1683 fatal_error (location_t loc, const char *gmsgid, ...)
1685 auto_diagnostic_group d;
1686 va_list ap;
1687 va_start (ap, gmsgid);
1688 rich_location richloc (line_table, loc);
1689 diagnostic_impl (&richloc, NULL, -1, gmsgid, &ap, DK_FATAL);
1690 va_end (ap);
1692 gcc_unreachable ();
1695 /* An internal consistency check has failed. We make no attempt to
1696 continue. Note that unless there is debugging value to be had from
1697 a more specific message, or some other good reason, you should use
1698 abort () instead of calling this function directly. */
1699 void
1700 internal_error (const char *gmsgid, ...)
1702 auto_diagnostic_group d;
1703 va_list ap;
1704 va_start (ap, gmsgid);
1705 rich_location richloc (line_table, input_location);
1706 diagnostic_impl (&richloc, NULL, -1, gmsgid, &ap, DK_ICE);
1707 va_end (ap);
1709 gcc_unreachable ();
1712 /* Like internal_error, but no backtrace will be printed. Used when
1713 the internal error does not happen at the current location, but happened
1714 somewhere else. */
1715 void
1716 internal_error_no_backtrace (const char *gmsgid, ...)
1718 auto_diagnostic_group d;
1719 va_list ap;
1720 va_start (ap, gmsgid);
1721 rich_location richloc (line_table, input_location);
1722 diagnostic_impl (&richloc, NULL, -1, gmsgid, &ap, DK_ICE_NOBT);
1723 va_end (ap);
1725 gcc_unreachable ();
1728 /* Special case error functions. Most are implemented in terms of the
1729 above, or should be. */
1731 /* Print a diagnostic MSGID on FILE. This is just fprintf, except it
1732 runs its second argument through gettext. */
1733 void
1734 fnotice (FILE *file, const char *cmsgid, ...)
1736 va_list ap;
1738 va_start (ap, cmsgid);
1739 vfprintf (file, _(cmsgid), ap);
1740 va_end (ap);
1743 /* Inform the user that an error occurred while trying to report some
1744 other error. This indicates catastrophic internal inconsistencies,
1745 so give up now. But do try to flush out the previous error.
1746 This mustn't use internal_error, that will cause infinite recursion. */
1748 static void
1749 error_recursion (diagnostic_context *context)
1751 if (context->lock < 3)
1752 pp_newline_and_flush (context->printer);
1754 fnotice (stderr,
1755 "Internal compiler error: Error reporting routines re-entered.\n");
1757 /* Call diagnostic_action_after_output to get the "please submit a bug
1758 report" message. */
1759 diagnostic_action_after_output (context, DK_ICE);
1761 /* Do not use gcc_unreachable here; that goes through internal_error
1762 and therefore would cause infinite recursion. */
1763 real_abort ();
1766 /* Report an internal compiler error in a friendly manner. This is
1767 the function that gets called upon use of abort() in the source
1768 code generally, thanks to a special macro. */
1770 void
1771 fancy_abort (const char *file, int line, const char *function)
1773 internal_error ("in %s, at %s:%d", function, trim_filename (file), line);
1776 /* class auto_diagnostic_group. */
1778 /* Constructor: "push" this group into global_dc. */
1780 auto_diagnostic_group::auto_diagnostic_group ()
1782 global_dc->diagnostic_group_nesting_depth++;
1785 /* Destructor: "pop" this group from global_dc. */
1787 auto_diagnostic_group::~auto_diagnostic_group ()
1789 if (--global_dc->diagnostic_group_nesting_depth == 0)
1791 /* Handle the case where we've popped the final diagnostic group.
1792 If any diagnostics were emitted, give the context a chance
1793 to do something. */
1794 if (global_dc->diagnostic_group_emission_count > 0)
1796 if (global_dc->end_group_cb)
1797 global_dc->end_group_cb (global_dc);
1799 global_dc->diagnostic_group_emission_count = 0;
1803 /* Implementation of diagnostic_path::num_events vfunc for
1804 simple_diagnostic_path: simply get the number of events in the vec. */
1806 unsigned
1807 simple_diagnostic_path::num_events () const
1809 return m_events.length ();
1812 /* Implementation of diagnostic_path::get_event vfunc for
1813 simple_diagnostic_path: simply return the event in the vec. */
1815 const diagnostic_event &
1816 simple_diagnostic_path::get_event (int idx) const
1818 return *m_events[idx];
1821 /* Add an event to this path at LOC within function FNDECL at
1822 stack depth DEPTH.
1824 Use m_context's printer to format FMT, as the text of the new
1825 event.
1827 Return the id of the new event. */
1829 diagnostic_event_id_t
1830 simple_diagnostic_path::add_event (location_t loc, tree fndecl, int depth,
1831 const char *fmt, ...)
1833 pretty_printer *pp = m_event_pp;
1834 pp_clear_output_area (pp);
1836 text_info ti;
1837 rich_location rich_loc (line_table, UNKNOWN_LOCATION);
1839 va_list ap;
1841 va_start (ap, fmt);
1843 ti.format_spec = _(fmt);
1844 ti.args_ptr = &ap;
1845 ti.err_no = 0;
1846 ti.x_data = NULL;
1847 ti.m_richloc = &rich_loc;
1849 pp_format (pp, &ti);
1850 pp_output_formatted_text (pp);
1852 va_end (ap);
1854 simple_diagnostic_event *new_event
1855 = new simple_diagnostic_event (loc, fndecl, depth, pp_formatted_text (pp));
1856 m_events.safe_push (new_event);
1858 pp_clear_output_area (pp);
1860 return diagnostic_event_id_t (m_events.length () - 1);
1863 /* struct simple_diagnostic_event. */
1865 /* simple_diagnostic_event's ctor. */
1867 simple_diagnostic_event::simple_diagnostic_event (location_t loc,
1868 tree fndecl,
1869 int depth,
1870 const char *desc)
1871 : m_loc (loc), m_fndecl (fndecl), m_depth (depth), m_desc (xstrdup (desc))
1875 /* simple_diagnostic_event's dtor. */
1877 simple_diagnostic_event::~simple_diagnostic_event ()
1879 free (m_desc);
1882 /* Print PATH by emitting a dummy "note" associated with it. */
1884 DEBUG_FUNCTION
1885 void debug (diagnostic_path *path)
1887 rich_location richloc (line_table, UNKNOWN_LOCATION);
1888 richloc.set_path (path);
1889 inform (&richloc, "debug path");
1892 /* Really call the system 'abort'. This has to go right at the end of
1893 this file, so that there are no functions after it that call abort
1894 and get the system abort instead of our macro. */
1895 #undef abort
1896 static void
1897 real_abort (void)
1899 abort ();
1902 #if CHECKING_P
1904 namespace selftest {
1906 /* Helper function for test_print_escaped_string. */
1908 static void
1909 assert_print_escaped_string (const location &loc, const char *expected_output,
1910 const char *input)
1912 pretty_printer pp;
1913 print_escaped_string (&pp, input);
1914 ASSERT_STREQ_AT (loc, expected_output, pp_formatted_text (&pp));
1917 #define ASSERT_PRINT_ESCAPED_STRING_STREQ(EXPECTED_OUTPUT, INPUT) \
1918 assert_print_escaped_string (SELFTEST_LOCATION, EXPECTED_OUTPUT, INPUT)
1920 /* Tests of print_escaped_string. */
1922 static void
1923 test_print_escaped_string ()
1925 /* Empty string. */
1926 ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"\"", "");
1928 /* Non-empty string. */
1929 ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"hello world\"", "hello world");
1931 /* Various things that need to be escaped: */
1932 /* Backslash. */
1933 ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"before\\\\after\"",
1934 "before\\after");
1935 /* Tab. */
1936 ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"before\\tafter\"",
1937 "before\tafter");
1938 /* Newline. */
1939 ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"before\\nafter\"",
1940 "before\nafter");
1941 /* Double quote. */
1942 ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"before\\\"after\"",
1943 "before\"after");
1945 /* Non-printable characters: BEL: '\a': 0x07 */
1946 ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"before\\007after\"",
1947 "before\aafter");
1948 /* Non-printable characters: vertical tab: '\v': 0x0b */
1949 ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"before\\013after\"",
1950 "before\vafter");
1953 /* Tests of print_parseable_fixits. */
1955 /* Verify that print_parseable_fixits emits the empty string if there
1956 are no fixits. */
1958 static void
1959 test_print_parseable_fixits_none ()
1961 pretty_printer pp;
1962 rich_location richloc (line_table, UNKNOWN_LOCATION);
1964 print_parseable_fixits (&pp, &richloc);
1965 ASSERT_STREQ ("", pp_formatted_text (&pp));
1968 /* Verify that print_parseable_fixits does the right thing if there
1969 is an insertion fixit hint. */
1971 static void
1972 test_print_parseable_fixits_insert ()
1974 pretty_printer pp;
1975 rich_location richloc (line_table, UNKNOWN_LOCATION);
1977 linemap_add (line_table, LC_ENTER, false, "test.c", 0);
1978 linemap_line_start (line_table, 5, 100);
1979 linemap_add (line_table, LC_LEAVE, false, NULL, 0);
1980 location_t where = linemap_position_for_column (line_table, 10);
1981 richloc.add_fixit_insert_before (where, "added content");
1983 print_parseable_fixits (&pp, &richloc);
1984 ASSERT_STREQ ("fix-it:\"test.c\":{5:10-5:10}:\"added content\"\n",
1985 pp_formatted_text (&pp));
1988 /* Verify that print_parseable_fixits does the right thing if there
1989 is an removal fixit hint. */
1991 static void
1992 test_print_parseable_fixits_remove ()
1994 pretty_printer pp;
1995 rich_location richloc (line_table, UNKNOWN_LOCATION);
1997 linemap_add (line_table, LC_ENTER, false, "test.c", 0);
1998 linemap_line_start (line_table, 5, 100);
1999 linemap_add (line_table, LC_LEAVE, false, NULL, 0);
2000 source_range where;
2001 where.m_start = linemap_position_for_column (line_table, 10);
2002 where.m_finish = linemap_position_for_column (line_table, 20);
2003 richloc.add_fixit_remove (where);
2005 print_parseable_fixits (&pp, &richloc);
2006 ASSERT_STREQ ("fix-it:\"test.c\":{5:10-5:21}:\"\"\n",
2007 pp_formatted_text (&pp));
2010 /* Verify that print_parseable_fixits does the right thing if there
2011 is an replacement fixit hint. */
2013 static void
2014 test_print_parseable_fixits_replace ()
2016 pretty_printer pp;
2017 rich_location richloc (line_table, UNKNOWN_LOCATION);
2019 linemap_add (line_table, LC_ENTER, false, "test.c", 0);
2020 linemap_line_start (line_table, 5, 100);
2021 linemap_add (line_table, LC_LEAVE, false, NULL, 0);
2022 source_range where;
2023 where.m_start = linemap_position_for_column (line_table, 10);
2024 where.m_finish = linemap_position_for_column (line_table, 20);
2025 richloc.add_fixit_replace (where, "replacement");
2027 print_parseable_fixits (&pp, &richloc);
2028 ASSERT_STREQ ("fix-it:\"test.c\":{5:10-5:21}:\"replacement\"\n",
2029 pp_formatted_text (&pp));
2032 /* Verify that
2033 diagnostic_get_location_text (..., SHOW_COLUMN)
2034 generates EXPECTED_LOC_TEXT, given FILENAME, LINE, COLUMN, with
2035 colorization disabled. */
2037 static void
2038 assert_location_text (const char *expected_loc_text,
2039 const char *filename, int line, int column,
2040 bool show_column)
2042 test_diagnostic_context dc;
2043 dc.show_column = show_column;
2045 expanded_location xloc;
2046 xloc.file = filename;
2047 xloc.line = line;
2048 xloc.column = column;
2049 xloc.data = NULL;
2050 xloc.sysp = false;
2052 char *actual_loc_text = diagnostic_get_location_text (&dc, xloc);
2053 ASSERT_STREQ (expected_loc_text, actual_loc_text);
2054 free (actual_loc_text);
2057 /* Verify that diagnostic_get_location_text works as expected. */
2059 static void
2060 test_diagnostic_get_location_text ()
2062 const char *old_progname = progname;
2063 progname = "PROGNAME";
2064 assert_location_text ("PROGNAME:", NULL, 0, 0, true);
2065 assert_location_text ("<built-in>:", "<built-in>", 42, 10, true);
2066 assert_location_text ("foo.c:42:10:", "foo.c", 42, 10, true);
2067 assert_location_text ("foo.c:42:", "foo.c", 42, 0, true);
2068 assert_location_text ("foo.c:", "foo.c", 0, 10, true);
2069 assert_location_text ("foo.c:42:", "foo.c", 42, 10, false);
2070 assert_location_text ("foo.c:", "foo.c", 0, 10, false);
2072 maybe_line_and_column (INT_MAX, INT_MAX);
2073 maybe_line_and_column (INT_MIN, INT_MIN);
2075 progname = old_progname;
2078 /* Selftest for num_digits. */
2080 static void
2081 test_num_digits ()
2083 ASSERT_EQ (1, num_digits (0));
2084 ASSERT_EQ (1, num_digits (9));
2085 ASSERT_EQ (2, num_digits (10));
2086 ASSERT_EQ (2, num_digits (99));
2087 ASSERT_EQ (3, num_digits (100));
2088 ASSERT_EQ (3, num_digits (999));
2089 ASSERT_EQ (4, num_digits (1000));
2090 ASSERT_EQ (4, num_digits (9999));
2091 ASSERT_EQ (5, num_digits (10000));
2092 ASSERT_EQ (5, num_digits (99999));
2093 ASSERT_EQ (6, num_digits (100000));
2094 ASSERT_EQ (6, num_digits (999999));
2095 ASSERT_EQ (7, num_digits (1000000));
2096 ASSERT_EQ (7, num_digits (9999999));
2097 ASSERT_EQ (8, num_digits (10000000));
2098 ASSERT_EQ (8, num_digits (99999999));
2101 /* Run all of the selftests within this file. */
2103 void
2104 diagnostic_c_tests ()
2106 test_print_escaped_string ();
2107 test_print_parseable_fixits_none ();
2108 test_print_parseable_fixits_insert ();
2109 test_print_parseable_fixits_remove ();
2110 test_print_parseable_fixits_replace ();
2111 test_diagnostic_get_location_text ();
2112 test_num_digits ();
2116 } // namespace selftest
2118 #endif /* #if CHECKING_P */
2120 #if __GNUC__ >= 10
2121 # pragma GCC diagnostic pop
2122 #endif