fix __builtin___clear_cache overrider fallout
[official-gcc.git] / gcc / diagnostic.c
blobda20cdb27039cdae147ba035b03d7456b96f63c7
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"
41 #include "cpplib.h"
43 #ifdef HAVE_TERMIOS_H
44 # include <termios.h>
45 #endif
47 #ifdef GWINSZ_IN_SYS_IOCTL
48 # include <sys/ioctl.h>
49 #endif
51 /* Disable warnings about quoting issues in the pp_xxx calls below
52 that (intentionally) don't follow GCC diagnostic conventions. */
53 #if __GNUC__ >= 10
54 # pragma GCC diagnostic push
55 # pragma GCC diagnostic ignored "-Wformat-diag"
56 #endif
58 #define pedantic_warning_kind(DC) \
59 ((DC)->pedantic_errors ? DK_ERROR : DK_WARNING)
60 #define permissive_error_kind(DC) ((DC)->permissive ? DK_WARNING : DK_ERROR)
61 #define permissive_error_option(DC) ((DC)->opt_permissive)
63 /* Prototypes. */
64 static bool diagnostic_impl (rich_location *, const diagnostic_metadata *,
65 int, const char *,
66 va_list *, diagnostic_t) ATTRIBUTE_GCC_DIAG(4,0);
67 static bool diagnostic_n_impl (rich_location *, const diagnostic_metadata *,
68 int, unsigned HOST_WIDE_INT,
69 const char *, const char *, va_list *,
70 diagnostic_t) ATTRIBUTE_GCC_DIAG(6,0);
72 static void error_recursion (diagnostic_context *) ATTRIBUTE_NORETURN;
73 static void real_abort (void) ATTRIBUTE_NORETURN;
75 /* Name of program invoked, sans directories. */
77 const char *progname;
79 /* A diagnostic_context surrogate for stderr. */
80 static diagnostic_context global_diagnostic_context;
81 diagnostic_context *global_dc = &global_diagnostic_context;
83 /* Return a malloc'd string containing MSG formatted a la printf. The
84 caller is responsible for freeing the memory. */
85 char *
86 build_message_string (const char *msg, ...)
88 char *str;
89 va_list ap;
91 va_start (ap, msg);
92 str = xvasprintf (msg, ap);
93 va_end (ap);
95 return str;
98 /* Same as diagnostic_build_prefix, but only the source FILE is given. */
99 char *
100 file_name_as_prefix (diagnostic_context *context, const char *f)
102 const char *locus_cs
103 = colorize_start (pp_show_color (context->printer), "locus");
104 const char *locus_ce = colorize_stop (pp_show_color (context->printer));
105 return build_message_string ("%s%s:%s ", locus_cs, f, locus_ce);
110 /* Return the value of the getenv("COLUMNS") as an integer. If the
111 value is not set to a positive integer, use ioctl to get the
112 terminal width. If it fails, return INT_MAX. */
114 get_terminal_width (void)
116 const char * s = getenv ("COLUMNS");
117 if (s != NULL) {
118 int n = atoi (s);
119 if (n > 0)
120 return n;
123 #ifdef TIOCGWINSZ
124 struct winsize w;
125 w.ws_col = 0;
126 if (ioctl (0, TIOCGWINSZ, &w) == 0 && w.ws_col > 0)
127 return w.ws_col;
128 #endif
130 return INT_MAX;
133 /* Set caret_max_width to value. */
134 void
135 diagnostic_set_caret_max_width (diagnostic_context *context, int value)
137 /* One minus to account for the leading empty space. */
138 value = value ? value - 1
139 : (isatty (fileno (pp_buffer (context->printer)->stream))
140 ? get_terminal_width () - 1: INT_MAX);
142 if (value <= 0)
143 value = INT_MAX;
145 context->caret_max_width = value;
148 /* Default implementation of final_cb. */
150 static void
151 default_diagnostic_final_cb (diagnostic_context *context)
153 /* Some of the errors may actually have been warnings. */
154 if (diagnostic_kind_count (context, DK_WERROR))
156 /* -Werror was given. */
157 if (context->warning_as_error_requested)
158 pp_verbatim (context->printer,
159 _("%s: all warnings being treated as errors"),
160 progname);
161 /* At least one -Werror= was given. */
162 else
163 pp_verbatim (context->printer,
164 _("%s: some warnings being treated as errors"),
165 progname);
166 pp_newline_and_flush (context->printer);
170 /* Initialize the diagnostic message outputting machinery. */
171 void
172 diagnostic_initialize (diagnostic_context *context, int n_opts)
174 int i;
176 /* Allocate a basic pretty-printer. Clients will replace this a
177 much more elaborated pretty-printer if they wish. */
178 context->printer = XNEW (pretty_printer);
179 new (context->printer) pretty_printer ();
181 memset (context->diagnostic_count, 0, sizeof context->diagnostic_count);
182 context->warning_as_error_requested = false;
183 context->n_opts = n_opts;
184 context->classify_diagnostic = XNEWVEC (diagnostic_t, n_opts);
185 for (i = 0; i < n_opts; i++)
186 context->classify_diagnostic[i] = DK_UNSPECIFIED;
187 context->show_caret = false;
188 diagnostic_set_caret_max_width (context, pp_line_cutoff (context->printer));
189 for (i = 0; i < rich_location::STATICALLY_ALLOCATED_RANGES; i++)
190 context->caret_chars[i] = '^';
191 context->show_cwe = false;
192 context->path_format = DPF_NONE;
193 context->show_path_depths = false;
194 context->show_option_requested = false;
195 context->abort_on_error = false;
196 context->show_column = false;
197 context->pedantic_errors = false;
198 context->permissive = false;
199 context->opt_permissive = 0;
200 context->fatal_errors = false;
201 context->dc_inhibit_warnings = false;
202 context->dc_warn_system_headers = false;
203 context->max_errors = 0;
204 context->internal_error = NULL;
205 diagnostic_starter (context) = default_diagnostic_starter;
206 context->start_span = default_diagnostic_start_span_fn;
207 diagnostic_finalizer (context) = default_diagnostic_finalizer;
208 context->option_enabled = NULL;
209 context->option_state = NULL;
210 context->option_name = NULL;
211 context->get_option_url = NULL;
212 context->last_location = UNKNOWN_LOCATION;
213 context->last_module = 0;
214 context->x_data = NULL;
215 context->lock = 0;
216 context->inhibit_notes_p = false;
217 context->colorize_source_p = false;
218 context->show_labels_p = false;
219 context->show_line_numbers_p = false;
220 context->min_margin_width = 0;
221 context->show_ruler_p = false;
222 context->parseable_fixits_p = false;
223 context->column_unit = DIAGNOSTICS_COLUMN_UNIT_DISPLAY;
224 context->column_origin = 1;
225 context->tabstop = 8;
226 context->edit_context_ptr = NULL;
227 context->diagnostic_group_nesting_depth = 0;
228 context->diagnostic_group_emission_count = 0;
229 context->begin_group_cb = NULL;
230 context->end_group_cb = NULL;
231 context->final_cb = default_diagnostic_final_cb;
234 /* Maybe initialize the color support. We require clients to do this
235 explicitly, since most clients don't want color. When called
236 without a VALUE, it initializes with DIAGNOSTICS_COLOR_DEFAULT. */
238 void
239 diagnostic_color_init (diagnostic_context *context, int value /*= -1 */)
241 /* value == -1 is the default value. */
242 if (value < 0)
244 /* If DIAGNOSTICS_COLOR_DEFAULT is -1, default to
245 -fdiagnostics-color=auto if GCC_COLORS is in the environment,
246 otherwise default to -fdiagnostics-color=never, for other
247 values default to that
248 -fdiagnostics-color={never,auto,always}. */
249 if (DIAGNOSTICS_COLOR_DEFAULT == -1)
251 if (!getenv ("GCC_COLORS"))
252 return;
253 value = DIAGNOSTICS_COLOR_AUTO;
255 else
256 value = DIAGNOSTICS_COLOR_DEFAULT;
258 pp_show_color (context->printer)
259 = colorize_init ((diagnostic_color_rule_t) value);
262 /* Initialize URL support within CONTEXT based on VALUE, handling "auto". */
264 void
265 diagnostic_urls_init (diagnostic_context *context, int value /*= -1 */)
267 /* value == -1 is the default value. */
268 if (value < 0)
270 /* If DIAGNOSTICS_URLS_DEFAULT is -1, default to
271 -fdiagnostics-urls=auto if GCC_URLS or TERM_URLS is in the
272 environment, otherwise default to -fdiagnostics-urls=never,
273 for other values default to that
274 -fdiagnostics-urls={never,auto,always}. */
275 if (DIAGNOSTICS_URLS_DEFAULT == -1)
277 if (!getenv ("GCC_URLS") && !getenv ("TERM_URLS"))
278 return;
279 value = DIAGNOSTICS_URL_AUTO;
281 else
282 value = DIAGNOSTICS_URLS_DEFAULT;
285 context->printer->url_format
286 = determine_url_format ((diagnostic_url_rule_t) value);
289 /* Do any cleaning up required after the last diagnostic is emitted. */
291 void
292 diagnostic_finish (diagnostic_context *context)
294 if (context->final_cb)
295 context->final_cb (context);
297 diagnostic_file_cache_fini ();
299 XDELETEVEC (context->classify_diagnostic);
300 context->classify_diagnostic = NULL;
302 /* diagnostic_initialize allocates context->printer using XNEW
303 and placement-new. */
304 context->printer->~pretty_printer ();
305 XDELETE (context->printer);
306 context->printer = NULL;
308 if (context->edit_context_ptr)
310 delete context->edit_context_ptr;
311 context->edit_context_ptr = NULL;
315 /* Initialize DIAGNOSTIC, where the message MSG has already been
316 translated. */
317 void
318 diagnostic_set_info_translated (diagnostic_info *diagnostic, const char *msg,
319 va_list *args, rich_location *richloc,
320 diagnostic_t kind)
322 gcc_assert (richloc);
323 diagnostic->message.err_no = errno;
324 diagnostic->message.args_ptr = args;
325 diagnostic->message.format_spec = msg;
326 diagnostic->message.m_richloc = richloc;
327 diagnostic->richloc = richloc;
328 diagnostic->metadata = NULL;
329 diagnostic->kind = kind;
330 diagnostic->option_index = 0;
333 /* Initialize DIAGNOSTIC, where the message GMSGID has not yet been
334 translated. */
335 void
336 diagnostic_set_info (diagnostic_info *diagnostic, const char *gmsgid,
337 va_list *args, rich_location *richloc,
338 diagnostic_t kind)
340 gcc_assert (richloc);
341 diagnostic_set_info_translated (diagnostic, _(gmsgid), args, richloc, kind);
344 static const char *const diagnostic_kind_color[] = {
345 #define DEFINE_DIAGNOSTIC_KIND(K, T, C) (C),
346 #include "diagnostic.def"
347 #undef DEFINE_DIAGNOSTIC_KIND
348 NULL
351 /* Get a color name for diagnostics of type KIND
352 Result could be NULL. */
354 const char *
355 diagnostic_get_color_for_kind (diagnostic_t kind)
357 return diagnostic_kind_color[kind];
360 /* Given an expanded_location, convert the column (which is in 1-based bytes)
361 to the requested units and origin. Return -1 if the column is
362 invalid (<= 0). */
364 diagnostic_converted_column (diagnostic_context *context, expanded_location s)
366 if (s.column <= 0)
367 return -1;
369 int one_based_col;
370 switch (context->column_unit)
372 case DIAGNOSTICS_COLUMN_UNIT_DISPLAY:
373 one_based_col = location_compute_display_column (s, context->tabstop);
374 break;
376 case DIAGNOSTICS_COLUMN_UNIT_BYTE:
377 one_based_col = s.column;
378 break;
380 default:
381 gcc_unreachable ();
384 return one_based_col + (context->column_origin - 1);
387 /* Return a formatted line and column ':%line:%column'. Elided if
388 line == 0 or col < 0. (A column of 0 may be valid due to the
389 -fdiagnostics-column-origin option.)
390 The result is a statically allocated buffer. */
392 static const char *
393 maybe_line_and_column (int line, int col)
395 static char result[32];
397 if (line)
399 size_t l
400 = snprintf (result, sizeof (result),
401 col >= 0 ? ":%d:%d" : ":%d", line, col);
402 gcc_checking_assert (l < sizeof (result));
404 else
405 result[0] = 0;
406 return result;
409 /* Return a malloc'd string describing a location e.g. "foo.c:42:10".
410 The caller is responsible for freeing the memory. */
412 static char *
413 diagnostic_get_location_text (diagnostic_context *context,
414 expanded_location s)
416 pretty_printer *pp = context->printer;
417 const char *locus_cs = colorize_start (pp_show_color (pp), "locus");
418 const char *locus_ce = colorize_stop (pp_show_color (pp));
419 const char *file = s.file ? s.file : progname;
420 int line = 0;
421 int col = -1;
422 if (strcmp (file, N_("<built-in>")))
424 line = s.line;
425 if (context->show_column)
426 col = diagnostic_converted_column (context, s);
429 const char *line_col = maybe_line_and_column (line, col);
430 return build_message_string ("%s%s%s:%s", locus_cs, file,
431 line_col, locus_ce);
434 /* Return a malloc'd string describing a location and the severity of the
435 diagnostic, e.g. "foo.c:42:10: error: ". The caller is responsible for
436 freeing the memory. */
437 char *
438 diagnostic_build_prefix (diagnostic_context *context,
439 const diagnostic_info *diagnostic)
441 static const char *const diagnostic_kind_text[] = {
442 #define DEFINE_DIAGNOSTIC_KIND(K, T, C) (T),
443 #include "diagnostic.def"
444 #undef DEFINE_DIAGNOSTIC_KIND
445 "must-not-happen"
447 gcc_assert (diagnostic->kind < DK_LAST_DIAGNOSTIC_KIND);
449 const char *text = _(diagnostic_kind_text[diagnostic->kind]);
450 const char *text_cs = "", *text_ce = "";
451 pretty_printer *pp = context->printer;
453 if (diagnostic_kind_color[diagnostic->kind])
455 text_cs = colorize_start (pp_show_color (pp),
456 diagnostic_kind_color[diagnostic->kind]);
457 text_ce = colorize_stop (pp_show_color (pp));
460 expanded_location s = diagnostic_expand_location (diagnostic);
461 char *location_text = diagnostic_get_location_text (context, s);
463 char *result = build_message_string ("%s %s%s%s", location_text,
464 text_cs, text, text_ce);
465 free (location_text);
466 return result;
469 /* Functions at which to stop the backtrace print. It's not
470 particularly helpful to print the callers of these functions. */
472 static const char * const bt_stop[] =
474 "main",
475 "toplev::main",
476 "execute_one_pass",
477 "compile_file",
480 /* A callback function passed to the backtrace_full function. */
482 static int
483 bt_callback (void *data, uintptr_t pc, const char *filename, int lineno,
484 const char *function)
486 int *pcount = (int *) data;
488 /* If we don't have any useful information, don't print
489 anything. */
490 if (filename == NULL && function == NULL)
491 return 0;
493 /* Skip functions in diagnostic.c. */
494 if (*pcount == 0
495 && filename != NULL
496 && strcmp (lbasename (filename), "diagnostic.c") == 0)
497 return 0;
499 /* Print up to 20 functions. We could make this a --param, but
500 since this is only for debugging just use a constant for now. */
501 if (*pcount >= 20)
503 /* Returning a non-zero value stops the backtrace. */
504 return 1;
506 ++*pcount;
508 char *alc = NULL;
509 if (function != NULL)
511 char *str = cplus_demangle_v3 (function,
512 (DMGL_VERBOSE | DMGL_ANSI
513 | DMGL_GNU_V3 | DMGL_PARAMS));
514 if (str != NULL)
516 alc = str;
517 function = str;
520 for (size_t i = 0; i < ARRAY_SIZE (bt_stop); ++i)
522 size_t len = strlen (bt_stop[i]);
523 if (strncmp (function, bt_stop[i], len) == 0
524 && (function[len] == '\0' || function[len] == '('))
526 if (alc != NULL)
527 free (alc);
528 /* Returning a non-zero value stops the backtrace. */
529 return 1;
534 fprintf (stderr, "0x%lx %s\n\t%s:%d\n",
535 (unsigned long) pc,
536 function == NULL ? "???" : function,
537 filename == NULL ? "???" : filename,
538 lineno);
540 if (alc != NULL)
541 free (alc);
543 return 0;
546 /* A callback function passed to the backtrace_full function. This is
547 called if backtrace_full has an error. */
549 static void
550 bt_err_callback (void *data ATTRIBUTE_UNUSED, const char *msg, int errnum)
552 if (errnum < 0)
554 /* This means that no debug info was available. Just quietly
555 skip printing backtrace info. */
556 return;
558 fprintf (stderr, "%s%s%s\n", msg, errnum == 0 ? "" : ": ",
559 errnum == 0 ? "" : xstrerror (errnum));
562 /* Check if we've met the maximum error limit, and if so fatally exit
563 with a message. CONTEXT is the context to check, and FLUSH
564 indicates whether a diagnostic_finish call is needed. */
566 void
567 diagnostic_check_max_errors (diagnostic_context *context, bool flush)
569 if (!context->max_errors)
570 return;
572 int count = (diagnostic_kind_count (context, DK_ERROR)
573 + diagnostic_kind_count (context, DK_SORRY)
574 + diagnostic_kind_count (context, DK_WERROR));
576 if (count >= context->max_errors)
578 fnotice (stderr,
579 "compilation terminated due to -fmax-errors=%u.\n",
580 context->max_errors);
581 if (flush)
582 diagnostic_finish (context);
583 exit (FATAL_EXIT_CODE);
587 /* Take any action which is expected to happen after the diagnostic
588 is written out. This function does not always return. */
589 void
590 diagnostic_action_after_output (diagnostic_context *context,
591 diagnostic_t diag_kind)
593 switch (diag_kind)
595 case DK_DEBUG:
596 case DK_NOTE:
597 case DK_ANACHRONISM:
598 case DK_WARNING:
599 break;
601 case DK_ERROR:
602 case DK_SORRY:
603 if (context->abort_on_error)
604 real_abort ();
605 if (context->fatal_errors)
607 fnotice (stderr, "compilation terminated due to -Wfatal-errors.\n");
608 diagnostic_finish (context);
609 exit (FATAL_EXIT_CODE);
611 break;
613 case DK_ICE:
614 case DK_ICE_NOBT:
616 struct backtrace_state *state = NULL;
617 if (diag_kind == DK_ICE)
618 state = backtrace_create_state (NULL, 0, bt_err_callback, NULL);
619 int count = 0;
620 if (state != NULL)
621 backtrace_full (state, 2, bt_callback, bt_err_callback,
622 (void *) &count);
624 if (context->abort_on_error)
625 real_abort ();
627 fnotice (stderr, "Please submit a full bug report,\n"
628 "with preprocessed source if appropriate.\n");
629 if (count > 0)
630 fnotice (stderr,
631 ("Please include the complete backtrace "
632 "with any bug report.\n"));
633 fnotice (stderr, "See %s for instructions.\n", bug_report_url);
635 exit (ICE_EXIT_CODE);
638 case DK_FATAL:
639 if (context->abort_on_error)
640 real_abort ();
641 diagnostic_finish (context);
642 fnotice (stderr, "compilation terminated.\n");
643 exit (FATAL_EXIT_CODE);
645 default:
646 gcc_unreachable ();
650 /* True if the last module or file in which a diagnostic was reported is
651 different from the current one. */
653 static bool
654 last_module_changed_p (diagnostic_context *context,
655 const line_map_ordinary *map)
657 return context->last_module != map;
660 /* Remember the current module or file as being the last one in which we
661 report a diagnostic. */
663 static void
664 set_last_module (diagnostic_context *context, const line_map_ordinary *map)
666 context->last_module = map;
669 void
670 diagnostic_report_current_module (diagnostic_context *context, location_t where)
672 const line_map_ordinary *map = NULL;
674 if (pp_needs_newline (context->printer))
676 pp_newline (context->printer);
677 pp_needs_newline (context->printer) = false;
680 if (where <= BUILTINS_LOCATION)
681 return;
683 linemap_resolve_location (line_table, where,
684 LRK_MACRO_DEFINITION_LOCATION,
685 &map);
687 if (map && last_module_changed_p (context, map))
689 set_last_module (context, map);
690 if (! MAIN_FILE_P (map))
692 bool first = true, need_inc = true, was_module = MAP_MODULE_P (map);
693 expanded_location s = {};
696 where = linemap_included_from (map);
697 map = linemap_included_from_linemap (line_table, map);
698 bool is_module = MAP_MODULE_P (map);
699 s.file = LINEMAP_FILE (map);
700 s.line = SOURCE_LINE (map, where);
701 int col = -1;
702 if (first && context->show_column)
704 s.column = SOURCE_COLUMN (map, where);
705 col = diagnostic_converted_column (context, s);
707 const char *line_col = maybe_line_and_column (s.line, col);
708 static const char *const msgs[] =
710 NULL,
711 N_(" from"),
712 N_("In file included from"), /* 2 */
713 N_(" included from"),
714 N_("In module"), /* 4 */
715 N_("of module"),
716 N_("In module imported at"), /* 6 */
717 N_("imported at"),
720 unsigned index = (was_module ? 6 : is_module ? 4
721 : need_inc ? 2 : 0) + !first;
723 pp_verbatim (context->printer, "%s%s %r%s%s%R",
724 first ? "" : was_module ? ", " : ",\n",
725 _(msgs[index]),
726 "locus", s.file, line_col);
727 first = false, need_inc = was_module, was_module = is_module;
729 while (! MAIN_FILE_P (map));
730 pp_verbatim (context->printer, ":");
731 pp_newline (context->printer);
736 /* If DIAGNOSTIC has a diagnostic_path and CONTEXT supports printing paths,
737 print the path. */
739 void
740 diagnostic_show_any_path (diagnostic_context *context,
741 diagnostic_info *diagnostic)
743 const diagnostic_path *path = diagnostic->richloc->get_path ();
744 if (!path)
745 return;
747 if (context->print_path)
748 context->print_path (context, path);
751 /* Return true if the events in this path involve more than one
752 function, or false if it is purely intraprocedural. */
754 bool
755 diagnostic_path::interprocedural_p () const
757 const unsigned num = num_events ();
758 for (unsigned i = 0; i < num; i++)
760 if (get_event (i).get_fndecl () != get_event (0).get_fndecl ())
761 return true;
762 if (get_event (i).get_stack_depth () != get_event (0).get_stack_depth ())
763 return true;
765 return false;
768 void
769 default_diagnostic_starter (diagnostic_context *context,
770 diagnostic_info *diagnostic)
772 diagnostic_report_current_module (context, diagnostic_location (diagnostic));
773 pp_set_prefix (context->printer, diagnostic_build_prefix (context,
774 diagnostic));
777 void
778 default_diagnostic_start_span_fn (diagnostic_context *context,
779 expanded_location exploc)
781 char *text = diagnostic_get_location_text (context, exploc);
782 pp_string (context->printer, text);
783 free (text);
784 pp_newline (context->printer);
787 void
788 default_diagnostic_finalizer (diagnostic_context *context,
789 diagnostic_info *diagnostic,
790 diagnostic_t)
792 char *saved_prefix = pp_take_prefix (context->printer);
793 pp_set_prefix (context->printer, NULL);
794 pp_newline (context->printer);
795 diagnostic_show_locus (context, diagnostic->richloc, diagnostic->kind);
796 pp_set_prefix (context->printer, saved_prefix);
797 pp_flush (context->printer);
800 /* Interface to specify diagnostic kind overrides. Returns the
801 previous setting, or DK_UNSPECIFIED if the parameters are out of
802 range. If OPTION_INDEX is zero, the new setting is for all the
803 diagnostics. */
804 diagnostic_t
805 diagnostic_classify_diagnostic (diagnostic_context *context,
806 int option_index,
807 diagnostic_t new_kind,
808 location_t where)
810 diagnostic_t old_kind;
812 if (option_index < 0
813 || option_index >= context->n_opts
814 || new_kind >= DK_LAST_DIAGNOSTIC_KIND)
815 return DK_UNSPECIFIED;
817 old_kind = context->classify_diagnostic[option_index];
819 /* Handle pragmas separately, since we need to keep track of *where*
820 the pragmas were. */
821 if (where != UNKNOWN_LOCATION)
823 int i;
825 /* Record the command-line status, so we can reset it back on DK_POP. */
826 if (old_kind == DK_UNSPECIFIED)
828 old_kind = !context->option_enabled (option_index,
829 context->lang_mask,
830 context->option_state)
831 ? DK_IGNORED : (context->warning_as_error_requested
832 ? DK_ERROR : DK_WARNING);
833 context->classify_diagnostic[option_index] = old_kind;
836 for (i = context->n_classification_history - 1; i >= 0; i --)
837 if (context->classification_history[i].option == option_index)
839 old_kind = context->classification_history[i].kind;
840 break;
843 i = context->n_classification_history;
844 context->classification_history =
845 (diagnostic_classification_change_t *) xrealloc (context->classification_history, (i + 1)
846 * sizeof (diagnostic_classification_change_t));
847 context->classification_history[i].location = where;
848 context->classification_history[i].option = option_index;
849 context->classification_history[i].kind = new_kind;
850 context->n_classification_history ++;
852 else
853 context->classify_diagnostic[option_index] = new_kind;
855 return old_kind;
858 /* Save all diagnostic classifications in a stack. */
859 void
860 diagnostic_push_diagnostics (diagnostic_context *context, location_t where ATTRIBUTE_UNUSED)
862 context->push_list = (int *) xrealloc (context->push_list, (context->n_push + 1) * sizeof (int));
863 context->push_list[context->n_push ++] = context->n_classification_history;
866 /* Restore the topmost classification set off the stack. If the stack
867 is empty, revert to the state based on command line parameters. */
868 void
869 diagnostic_pop_diagnostics (diagnostic_context *context, location_t where)
871 int jump_to;
872 int i;
874 if (context->n_push)
875 jump_to = context->push_list [-- context->n_push];
876 else
877 jump_to = 0;
879 i = context->n_classification_history;
880 context->classification_history =
881 (diagnostic_classification_change_t *) xrealloc (context->classification_history, (i + 1)
882 * sizeof (diagnostic_classification_change_t));
883 context->classification_history[i].location = where;
884 context->classification_history[i].option = jump_to;
885 context->classification_history[i].kind = DK_POP;
886 context->n_classification_history ++;
889 /* Helper function for print_parseable_fixits. Print TEXT to PP, obeying the
890 escaping rules for -fdiagnostics-parseable-fixits. */
892 static void
893 print_escaped_string (pretty_printer *pp, const char *text)
895 gcc_assert (pp);
896 gcc_assert (text);
898 pp_character (pp, '"');
899 for (const char *ch = text; *ch; ch++)
901 switch (*ch)
903 case '\\':
904 /* Escape backslash as two backslashes. */
905 pp_string (pp, "\\\\");
906 break;
907 case '\t':
908 /* Escape tab as "\t". */
909 pp_string (pp, "\\t");
910 break;
911 case '\n':
912 /* Escape newline as "\n". */
913 pp_string (pp, "\\n");
914 break;
915 case '"':
916 /* Escape doublequotes as \". */
917 pp_string (pp, "\\\"");
918 break;
919 default:
920 if (ISPRINT (*ch))
921 pp_character (pp, *ch);
922 else
923 /* Use octal for non-printable chars. */
925 unsigned char c = (*ch & 0xff);
926 pp_printf (pp, "\\%o%o%o", (c / 64), (c / 8) & 007, c & 007);
928 break;
931 pp_character (pp, '"');
934 /* Implementation of -fdiagnostics-parseable-fixits. Print a
935 machine-parseable version of all fixits in RICHLOC to PP. */
937 static void
938 print_parseable_fixits (pretty_printer *pp, rich_location *richloc)
940 gcc_assert (pp);
941 gcc_assert (richloc);
943 char *saved_prefix = pp_take_prefix (pp);
944 pp_set_prefix (pp, NULL);
946 for (unsigned i = 0; i < richloc->get_num_fixit_hints (); i++)
948 const fixit_hint *hint = richloc->get_fixit_hint (i);
949 location_t start_loc = hint->get_start_loc ();
950 expanded_location start_exploc = expand_location (start_loc);
951 pp_string (pp, "fix-it:");
952 print_escaped_string (pp, start_exploc.file);
953 /* For compatibility with clang, print as a half-open range. */
954 location_t next_loc = hint->get_next_loc ();
955 expanded_location next_exploc = expand_location (next_loc);
956 pp_printf (pp, ":{%i:%i-%i:%i}:",
957 start_exploc.line, start_exploc.column,
958 next_exploc.line, next_exploc.column);
959 print_escaped_string (pp, hint->get_string ());
960 pp_newline (pp);
963 pp_set_prefix (pp, saved_prefix);
966 /* Update the diag_class of DIAGNOSTIC based on its location
967 relative to any
968 #pragma GCC diagnostic
969 directives recorded within CONTEXT.
971 Return the new diag_class of DIAGNOSTIC if it was updated, or
972 DK_UNSPECIFIED otherwise. */
974 static diagnostic_t
975 update_effective_level_from_pragmas (diagnostic_context *context,
976 diagnostic_info *diagnostic)
978 diagnostic_t diag_class = DK_UNSPECIFIED;
980 if (context->n_classification_history > 0)
982 location_t location = diagnostic_location (diagnostic);
984 /* FIXME: Stupid search. Optimize later. */
985 for (int i = context->n_classification_history - 1; i >= 0; i --)
987 if (linemap_location_before_p
988 (line_table,
989 context->classification_history[i].location,
990 location))
992 if (context->classification_history[i].kind == (int) DK_POP)
994 i = context->classification_history[i].option;
995 continue;
997 int option = context->classification_history[i].option;
998 /* The option 0 is for all the diagnostics. */
999 if (option == 0 || option == diagnostic->option_index)
1001 diag_class = context->classification_history[i].kind;
1002 if (diag_class != DK_UNSPECIFIED)
1003 diagnostic->kind = diag_class;
1004 break;
1010 return diag_class;
1013 /* Generate a URL string describing CWE. The caller is responsible for
1014 freeing the string. */
1016 static char *
1017 get_cwe_url (int cwe)
1019 return xasprintf ("https://cwe.mitre.org/data/definitions/%i.html", cwe);
1022 /* If DIAGNOSTIC has a CWE identifier, print it.
1024 For example, if the diagnostic metadata associates it with CWE-119,
1025 " [CWE-119]" will be printed, suitably colorized, and with a URL of a
1026 description of the security issue. */
1028 static void
1029 print_any_cwe (diagnostic_context *context,
1030 const diagnostic_info *diagnostic)
1032 if (diagnostic->metadata == NULL)
1033 return;
1035 int cwe = diagnostic->metadata->get_cwe ();
1036 if (cwe)
1038 pretty_printer *pp = context->printer;
1039 char *saved_prefix = pp_take_prefix (context->printer);
1040 pp_string (pp, " [");
1041 pp_string (pp, colorize_start (pp_show_color (pp),
1042 diagnostic_kind_color[diagnostic->kind]));
1043 if (pp->url_format != URL_FORMAT_NONE)
1045 char *cwe_url = get_cwe_url (cwe);
1046 pp_begin_url (pp, cwe_url);
1047 free (cwe_url);
1049 pp_printf (pp, "CWE-%i", cwe);
1050 pp_set_prefix (context->printer, saved_prefix);
1051 if (pp->url_format != URL_FORMAT_NONE)
1052 pp_end_url (pp);
1053 pp_string (pp, colorize_stop (pp_show_color (pp)));
1054 pp_character (pp, ']');
1058 /* Print any metadata about the option used to control DIAGNOSTIC to CONTEXT's
1059 printer, e.g. " [-Werror=uninitialized]".
1060 Subroutine of diagnostic_report_diagnostic. */
1062 static void
1063 print_option_information (diagnostic_context *context,
1064 const diagnostic_info *diagnostic,
1065 diagnostic_t orig_diag_kind)
1067 char *option_text;
1069 option_text = context->option_name (context, diagnostic->option_index,
1070 orig_diag_kind, diagnostic->kind);
1072 if (option_text)
1074 char *option_url = NULL;
1075 if (context->get_option_url
1076 && context->printer->url_format != URL_FORMAT_NONE)
1077 option_url = context->get_option_url (context,
1078 diagnostic->option_index);
1079 pretty_printer *pp = context->printer;
1080 pp_string (pp, " [");
1081 pp_string (pp, colorize_start (pp_show_color (pp),
1082 diagnostic_kind_color[diagnostic->kind]));
1083 if (option_url)
1084 pp_begin_url (pp, option_url);
1085 pp_string (pp, option_text);
1086 if (option_url)
1088 pp_end_url (pp);
1089 free (option_url);
1091 pp_string (pp, colorize_stop (pp_show_color (pp)));
1092 pp_character (pp, ']');
1093 free (option_text);
1097 /* Report a diagnostic message (an error or a warning) as specified by
1098 DC. This function is *the* subroutine in terms of which front-ends
1099 should implement their specific diagnostic handling modules. The
1100 front-end independent format specifiers are exactly those described
1101 in the documentation of output_format.
1102 Return true if a diagnostic was printed, false otherwise. */
1104 bool
1105 diagnostic_report_diagnostic (diagnostic_context *context,
1106 diagnostic_info *diagnostic)
1108 location_t location = diagnostic_location (diagnostic);
1109 diagnostic_t orig_diag_kind = diagnostic->kind;
1111 /* Give preference to being able to inhibit warnings, before they
1112 get reclassified to something else. */
1113 if ((diagnostic->kind == DK_WARNING || diagnostic->kind == DK_PEDWARN)
1114 && !diagnostic_report_warnings_p (context, location))
1115 return false;
1117 if (diagnostic->kind == DK_PEDWARN)
1119 diagnostic->kind = pedantic_warning_kind (context);
1120 /* We do this to avoid giving the message for -pedantic-errors. */
1121 orig_diag_kind = diagnostic->kind;
1124 if (diagnostic->kind == DK_NOTE && context->inhibit_notes_p)
1125 return false;
1127 if (context->lock > 0)
1129 /* If we're reporting an ICE in the middle of some other error,
1130 try to flush out the previous error, then let this one
1131 through. Don't do this more than once. */
1132 if ((diagnostic->kind == DK_ICE || diagnostic->kind == DK_ICE_NOBT)
1133 && context->lock == 1)
1134 pp_newline_and_flush (context->printer);
1135 else
1136 error_recursion (context);
1139 /* If the user requested that warnings be treated as errors, so be
1140 it. Note that we do this before the next block so that
1141 individual warnings can be overridden back to warnings with
1142 -Wno-error=*. */
1143 if (context->warning_as_error_requested
1144 && diagnostic->kind == DK_WARNING)
1145 diagnostic->kind = DK_ERROR;
1147 if (diagnostic->option_index
1148 && diagnostic->option_index != permissive_error_option (context))
1150 /* This tests if the user provided the appropriate -Wfoo or
1151 -Wno-foo option. */
1152 if (! context->option_enabled (diagnostic->option_index,
1153 context->lang_mask,
1154 context->option_state))
1155 return false;
1157 /* This tests for #pragma diagnostic changes. */
1158 diagnostic_t diag_class
1159 = update_effective_level_from_pragmas (context, diagnostic);
1161 /* This tests if the user provided the appropriate -Werror=foo
1162 option. */
1163 if (diag_class == DK_UNSPECIFIED
1164 && (context->classify_diagnostic[diagnostic->option_index]
1165 != DK_UNSPECIFIED))
1166 diagnostic->kind
1167 = context->classify_diagnostic[diagnostic->option_index];
1169 /* This allows for future extensions, like temporarily disabling
1170 warnings for ranges of source code. */
1171 if (diagnostic->kind == DK_IGNORED)
1172 return false;
1175 if (diagnostic->kind != DK_NOTE && diagnostic->kind != DK_ICE)
1176 diagnostic_check_max_errors (context);
1178 context->lock++;
1180 if (diagnostic->kind == DK_ICE || diagnostic->kind == DK_ICE_NOBT)
1182 /* When not checking, ICEs are converted to fatal errors when an
1183 error has already occurred. This is counteracted by
1184 abort_on_error. */
1185 if (!CHECKING_P
1186 && (diagnostic_kind_count (context, DK_ERROR) > 0
1187 || diagnostic_kind_count (context, DK_SORRY) > 0)
1188 && !context->abort_on_error)
1190 expanded_location s
1191 = expand_location (diagnostic_location (diagnostic));
1192 fnotice (stderr, "%s:%d: confused by earlier errors, bailing out\n",
1193 s.file, s.line);
1194 exit (ICE_EXIT_CODE);
1196 if (context->internal_error)
1197 (*context->internal_error) (context,
1198 diagnostic->message.format_spec,
1199 diagnostic->message.args_ptr);
1201 if (diagnostic->kind == DK_ERROR && orig_diag_kind == DK_WARNING)
1202 ++diagnostic_kind_count (context, DK_WERROR);
1203 else
1204 ++diagnostic_kind_count (context, diagnostic->kind);
1206 /* Is this the initial diagnostic within the stack of groups? */
1207 if (context->diagnostic_group_emission_count == 0)
1209 if (context->begin_group_cb)
1210 context->begin_group_cb (context);
1212 context->diagnostic_group_emission_count++;
1214 diagnostic->message.x_data = &diagnostic->x_data;
1215 diagnostic->x_data = NULL;
1216 pp_format (context->printer, &diagnostic->message);
1217 (*diagnostic_starter (context)) (context, diagnostic);
1218 pp_output_formatted_text (context->printer);
1219 if (context->show_cwe)
1220 print_any_cwe (context, diagnostic);
1221 if (context->show_option_requested)
1222 print_option_information (context, diagnostic, orig_diag_kind);
1223 (*diagnostic_finalizer (context)) (context, diagnostic, orig_diag_kind);
1224 if (context->parseable_fixits_p)
1226 print_parseable_fixits (context->printer, diagnostic->richloc);
1227 pp_flush (context->printer);
1229 diagnostic_action_after_output (context, diagnostic->kind);
1230 diagnostic->x_data = NULL;
1232 if (context->edit_context_ptr)
1233 if (diagnostic->richloc->fixits_can_be_auto_applied_p ())
1234 context->edit_context_ptr->add_fixits (diagnostic->richloc);
1236 context->lock--;
1238 diagnostic_show_any_path (context, diagnostic);
1240 return true;
1243 /* Get the number of digits in the decimal representation of VALUE. */
1246 num_digits (int value)
1248 /* Perhaps simpler to use log10 for this, but doing it this way avoids
1249 using floating point. */
1250 gcc_assert (value >= 0);
1252 if (value == 0)
1253 return 1;
1255 int digits = 0;
1256 while (value > 0)
1258 digits++;
1259 value /= 10;
1261 return digits;
1264 /* Given a partial pathname as input, return another pathname that
1265 shares no directory elements with the pathname of __FILE__. This
1266 is used by fancy_abort() to print `Internal compiler error in expr.c'
1267 instead of `Internal compiler error in ../../GCC/gcc/expr.c'. */
1269 const char *
1270 trim_filename (const char *name)
1272 static const char this_file[] = __FILE__;
1273 const char *p = name, *q = this_file;
1275 /* First skip any "../" in each filename. This allows us to give a proper
1276 reference to a file in a subdirectory. */
1277 while (p[0] == '.' && p[1] == '.' && IS_DIR_SEPARATOR (p[2]))
1278 p += 3;
1280 while (q[0] == '.' && q[1] == '.' && IS_DIR_SEPARATOR (q[2]))
1281 q += 3;
1283 /* Now skip any parts the two filenames have in common. */
1284 while (*p == *q && *p != 0 && *q != 0)
1285 p++, q++;
1287 /* Now go backwards until the previous directory separator. */
1288 while (p > name && !IS_DIR_SEPARATOR (p[-1]))
1289 p--;
1291 return p;
1294 /* Standard error reporting routines in increasing order of severity.
1295 All of these take arguments like printf. */
1297 /* Text to be emitted verbatim to the error message stream; this
1298 produces no prefix and disables line-wrapping. Use rarely. */
1299 void
1300 verbatim (const char *gmsgid, ...)
1302 text_info text;
1303 va_list ap;
1305 va_start (ap, gmsgid);
1306 text.err_no = errno;
1307 text.args_ptr = &ap;
1308 text.format_spec = _(gmsgid);
1309 text.x_data = NULL;
1310 pp_format_verbatim (global_dc->printer, &text);
1311 pp_newline_and_flush (global_dc->printer);
1312 va_end (ap);
1315 /* Add a note with text GMSGID and with LOCATION to the diagnostic CONTEXT. */
1316 void
1317 diagnostic_append_note (diagnostic_context *context,
1318 location_t location,
1319 const char * gmsgid, ...)
1321 diagnostic_info diagnostic;
1322 va_list ap;
1323 rich_location richloc (line_table, location);
1325 va_start (ap, gmsgid);
1326 diagnostic_set_info (&diagnostic, gmsgid, &ap, &richloc, DK_NOTE);
1327 if (context->inhibit_notes_p)
1329 va_end (ap);
1330 return;
1332 char *saved_prefix = pp_take_prefix (context->printer);
1333 pp_set_prefix (context->printer,
1334 diagnostic_build_prefix (context, &diagnostic));
1335 pp_format (context->printer, &diagnostic.message);
1336 pp_output_formatted_text (context->printer);
1337 pp_destroy_prefix (context->printer);
1338 pp_set_prefix (context->printer, saved_prefix);
1339 pp_newline (context->printer);
1340 diagnostic_show_locus (context, &richloc, DK_NOTE);
1341 va_end (ap);
1344 /* Implement emit_diagnostic, inform, warning, warning_at, pedwarn,
1345 permerror, error, error_at, error_at, sorry, fatal_error, internal_error,
1346 and internal_error_no_backtrace, as documented and defined below. */
1347 static bool
1348 diagnostic_impl (rich_location *richloc, const diagnostic_metadata *metadata,
1349 int opt, const char *gmsgid,
1350 va_list *ap, diagnostic_t kind)
1352 diagnostic_info diagnostic;
1353 if (kind == DK_PERMERROR)
1355 diagnostic_set_info (&diagnostic, gmsgid, ap, richloc,
1356 permissive_error_kind (global_dc));
1357 diagnostic.option_index = permissive_error_option (global_dc);
1359 else
1361 diagnostic_set_info (&diagnostic, gmsgid, ap, richloc, kind);
1362 if (kind == DK_WARNING || kind == DK_PEDWARN)
1363 diagnostic.option_index = opt;
1365 diagnostic.metadata = metadata;
1366 return diagnostic_report_diagnostic (global_dc, &diagnostic);
1369 /* Implement inform_n, warning_n, and error_n, as documented and
1370 defined below. */
1371 static bool
1372 diagnostic_n_impl (rich_location *richloc, const diagnostic_metadata *metadata,
1373 int opt, unsigned HOST_WIDE_INT n,
1374 const char *singular_gmsgid,
1375 const char *plural_gmsgid,
1376 va_list *ap, diagnostic_t kind)
1378 diagnostic_info diagnostic;
1379 unsigned long gtn;
1381 if (sizeof n <= sizeof gtn)
1382 gtn = n;
1383 else
1384 /* Use the largest number ngettext can handle, otherwise
1385 preserve the six least significant decimal digits for
1386 languages where the plural form depends on them. */
1387 gtn = n <= ULONG_MAX ? n : n % 1000000LU + 1000000LU;
1389 const char *text = ngettext (singular_gmsgid, plural_gmsgid, gtn);
1390 diagnostic_set_info_translated (&diagnostic, text, ap, richloc, kind);
1391 if (kind == DK_WARNING)
1392 diagnostic.option_index = opt;
1393 diagnostic.metadata = metadata;
1394 return diagnostic_report_diagnostic (global_dc, &diagnostic);
1397 /* Wrapper around diagnostic_impl taking a variable argument list. */
1399 bool
1400 emit_diagnostic (diagnostic_t kind, location_t location, int opt,
1401 const char *gmsgid, ...)
1403 auto_diagnostic_group d;
1404 va_list ap;
1405 va_start (ap, gmsgid);
1406 rich_location richloc (line_table, location);
1407 bool ret = diagnostic_impl (&richloc, NULL, opt, gmsgid, &ap, kind);
1408 va_end (ap);
1409 return ret;
1412 /* As above, but for rich_location *. */
1414 bool
1415 emit_diagnostic (diagnostic_t kind, rich_location *richloc, int opt,
1416 const char *gmsgid, ...)
1418 auto_diagnostic_group d;
1419 va_list ap;
1420 va_start (ap, gmsgid);
1421 bool ret = diagnostic_impl (richloc, NULL, opt, gmsgid, &ap, kind);
1422 va_end (ap);
1423 return ret;
1426 /* Wrapper around diagnostic_impl taking a va_list parameter. */
1428 bool
1429 emit_diagnostic_valist (diagnostic_t kind, location_t location, int opt,
1430 const char *gmsgid, va_list *ap)
1432 rich_location richloc (line_table, location);
1433 return diagnostic_impl (&richloc, NULL, opt, gmsgid, ap, kind);
1436 /* An informative note at LOCATION. Use this for additional details on an error
1437 message. */
1438 void
1439 inform (location_t location, const char *gmsgid, ...)
1441 auto_diagnostic_group d;
1442 va_list ap;
1443 va_start (ap, gmsgid);
1444 rich_location richloc (line_table, location);
1445 diagnostic_impl (&richloc, NULL, -1, gmsgid, &ap, DK_NOTE);
1446 va_end (ap);
1449 /* Same as "inform" above, but at RICHLOC. */
1450 void
1451 inform (rich_location *richloc, const char *gmsgid, ...)
1453 gcc_assert (richloc);
1455 auto_diagnostic_group d;
1456 va_list ap;
1457 va_start (ap, gmsgid);
1458 diagnostic_impl (richloc, NULL, -1, gmsgid, &ap, DK_NOTE);
1459 va_end (ap);
1462 /* An informative note at LOCATION. Use this for additional details on an
1463 error message. */
1464 void
1465 inform_n (location_t location, unsigned HOST_WIDE_INT n,
1466 const char *singular_gmsgid, const char *plural_gmsgid, ...)
1468 va_list ap;
1469 va_start (ap, plural_gmsgid);
1470 auto_diagnostic_group d;
1471 rich_location richloc (line_table, location);
1472 diagnostic_n_impl (&richloc, NULL, -1, n, singular_gmsgid, plural_gmsgid,
1473 &ap, DK_NOTE);
1474 va_end (ap);
1477 /* A warning at INPUT_LOCATION. Use this for code which is correct according
1478 to the relevant language specification but is likely to be buggy anyway.
1479 Returns true if the warning was printed, false if it was inhibited. */
1480 bool
1481 warning (int opt, const char *gmsgid, ...)
1483 auto_diagnostic_group d;
1484 va_list ap;
1485 va_start (ap, gmsgid);
1486 rich_location richloc (line_table, input_location);
1487 bool ret = diagnostic_impl (&richloc, NULL, opt, gmsgid, &ap, DK_WARNING);
1488 va_end (ap);
1489 return ret;
1492 /* A warning at LOCATION. Use this for code which is correct according to the
1493 relevant language specification but is likely to be buggy anyway.
1494 Returns true if the warning was printed, false if it was inhibited. */
1496 bool
1497 warning_at (location_t location, int opt, const char *gmsgid, ...)
1499 auto_diagnostic_group d;
1500 va_list ap;
1501 va_start (ap, gmsgid);
1502 rich_location richloc (line_table, location);
1503 bool ret = diagnostic_impl (&richloc, NULL, opt, gmsgid, &ap, DK_WARNING);
1504 va_end (ap);
1505 return ret;
1508 /* Same as "warning at" above, but using RICHLOC. */
1510 bool
1511 warning_at (rich_location *richloc, int opt, const char *gmsgid, ...)
1513 gcc_assert (richloc);
1515 auto_diagnostic_group d;
1516 va_list ap;
1517 va_start (ap, gmsgid);
1518 bool ret = diagnostic_impl (richloc, NULL, opt, gmsgid, &ap, DK_WARNING);
1519 va_end (ap);
1520 return ret;
1523 /* Same as "warning at" above, but using METADATA. */
1525 bool
1526 warning_meta (rich_location *richloc,
1527 const diagnostic_metadata &metadata,
1528 int opt, const char *gmsgid, ...)
1530 gcc_assert (richloc);
1532 auto_diagnostic_group d;
1533 va_list ap;
1534 va_start (ap, gmsgid);
1535 bool ret
1536 = diagnostic_impl (richloc, &metadata, opt, gmsgid, &ap,
1537 DK_WARNING);
1538 va_end (ap);
1539 return ret;
1542 /* Same as warning_n plural variant below, but using RICHLOC. */
1544 bool
1545 warning_n (rich_location *richloc, int opt, unsigned HOST_WIDE_INT n,
1546 const char *singular_gmsgid, const char *plural_gmsgid, ...)
1548 gcc_assert (richloc);
1550 auto_diagnostic_group d;
1551 va_list ap;
1552 va_start (ap, plural_gmsgid);
1553 bool ret = diagnostic_n_impl (richloc, NULL, opt, n,
1554 singular_gmsgid, plural_gmsgid,
1555 &ap, DK_WARNING);
1556 va_end (ap);
1557 return ret;
1560 /* A warning at LOCATION. Use this for code which is correct according to the
1561 relevant language specification but is likely to be buggy anyway.
1562 Returns true if the warning was printed, false if it was inhibited. */
1564 bool
1565 warning_n (location_t location, int opt, unsigned HOST_WIDE_INT n,
1566 const char *singular_gmsgid, const char *plural_gmsgid, ...)
1568 auto_diagnostic_group d;
1569 va_list ap;
1570 va_start (ap, plural_gmsgid);
1571 rich_location richloc (line_table, location);
1572 bool ret = diagnostic_n_impl (&richloc, NULL, opt, n,
1573 singular_gmsgid, plural_gmsgid,
1574 &ap, DK_WARNING);
1575 va_end (ap);
1576 return ret;
1579 /* A "pedantic" warning at LOCATION: issues a warning unless
1580 -pedantic-errors was given on the command line, in which case it
1581 issues an error. Use this for diagnostics required by the relevant
1582 language standard, if you have chosen not to make them errors.
1584 Note that these diagnostics are issued independent of the setting
1585 of the -Wpedantic command-line switch. To get a warning enabled
1586 only with that switch, use either "if (pedantic) pedwarn
1587 (OPT_Wpedantic,...)" or just "pedwarn (OPT_Wpedantic,..)". To get a
1588 pedwarn independently of the -Wpedantic switch use "pedwarn (0,...)".
1590 Returns true if the warning was printed, false if it was inhibited. */
1592 bool
1593 pedwarn (location_t location, int opt, const char *gmsgid, ...)
1595 auto_diagnostic_group d;
1596 va_list ap;
1597 va_start (ap, gmsgid);
1598 rich_location richloc (line_table, location);
1599 bool ret = diagnostic_impl (&richloc, NULL, opt, gmsgid, &ap, DK_PEDWARN);
1600 va_end (ap);
1601 return ret;
1604 /* Same as pedwarn above, but using RICHLOC. */
1606 bool
1607 pedwarn (rich_location *richloc, int opt, const char *gmsgid, ...)
1609 gcc_assert (richloc);
1611 auto_diagnostic_group d;
1612 va_list ap;
1613 va_start (ap, gmsgid);
1614 bool ret = diagnostic_impl (richloc, NULL, opt, gmsgid, &ap, DK_PEDWARN);
1615 va_end (ap);
1616 return ret;
1619 /* A "permissive" error at LOCATION: issues an error unless
1620 -fpermissive was given on the command line, in which case it issues
1621 a warning. Use this for things that really should be errors but we
1622 want to support legacy code.
1624 Returns true if the warning was printed, false if it was inhibited. */
1626 bool
1627 permerror (location_t location, const char *gmsgid, ...)
1629 auto_diagnostic_group d;
1630 va_list ap;
1631 va_start (ap, gmsgid);
1632 rich_location richloc (line_table, location);
1633 bool ret = diagnostic_impl (&richloc, NULL, -1, gmsgid, &ap, DK_PERMERROR);
1634 va_end (ap);
1635 return ret;
1638 /* Same as "permerror" above, but at RICHLOC. */
1640 bool
1641 permerror (rich_location *richloc, const char *gmsgid, ...)
1643 gcc_assert (richloc);
1645 auto_diagnostic_group d;
1646 va_list ap;
1647 va_start (ap, gmsgid);
1648 bool ret = diagnostic_impl (richloc, NULL, -1, gmsgid, &ap, DK_PERMERROR);
1649 va_end (ap);
1650 return ret;
1653 /* A hard error: the code is definitely ill-formed, and an object file
1654 will not be produced. */
1655 void
1656 error (const char *gmsgid, ...)
1658 auto_diagnostic_group d;
1659 va_list ap;
1660 va_start (ap, gmsgid);
1661 rich_location richloc (line_table, input_location);
1662 diagnostic_impl (&richloc, NULL, -1, gmsgid, &ap, DK_ERROR);
1663 va_end (ap);
1666 /* A hard error: the code is definitely ill-formed, and an object file
1667 will not be produced. */
1668 void
1669 error_n (location_t location, unsigned HOST_WIDE_INT n,
1670 const char *singular_gmsgid, const char *plural_gmsgid, ...)
1672 auto_diagnostic_group d;
1673 va_list ap;
1674 va_start (ap, plural_gmsgid);
1675 rich_location richloc (line_table, location);
1676 diagnostic_n_impl (&richloc, NULL, -1, n, singular_gmsgid, plural_gmsgid,
1677 &ap, DK_ERROR);
1678 va_end (ap);
1681 /* Same as above, but use location LOC instead of input_location. */
1682 void
1683 error_at (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_ERROR);
1690 va_end (ap);
1693 /* Same as above, but use RICH_LOC. */
1695 void
1696 error_at (rich_location *richloc, const char *gmsgid, ...)
1698 gcc_assert (richloc);
1700 auto_diagnostic_group d;
1701 va_list ap;
1702 va_start (ap, gmsgid);
1703 diagnostic_impl (richloc, NULL, -1, gmsgid, &ap, DK_ERROR);
1704 va_end (ap);
1707 /* "Sorry, not implemented." Use for a language feature which is
1708 required by the relevant specification but not implemented by GCC.
1709 An object file will not be produced. */
1710 void
1711 sorry (const char *gmsgid, ...)
1713 auto_diagnostic_group d;
1714 va_list ap;
1715 va_start (ap, gmsgid);
1716 rich_location richloc (line_table, input_location);
1717 diagnostic_impl (&richloc, NULL, -1, gmsgid, &ap, DK_SORRY);
1718 va_end (ap);
1721 /* Same as above, but use location LOC instead of input_location. */
1722 void
1723 sorry_at (location_t loc, const char *gmsgid, ...)
1725 auto_diagnostic_group d;
1726 va_list ap;
1727 va_start (ap, gmsgid);
1728 rich_location richloc (line_table, loc);
1729 diagnostic_impl (&richloc, NULL, -1, gmsgid, &ap, DK_SORRY);
1730 va_end (ap);
1733 /* Return true if an error or a "sorry" has been seen. Various
1734 processing is disabled after errors. */
1735 bool
1736 seen_error (void)
1738 return errorcount || sorrycount;
1741 /* An error which is severe enough that we make no attempt to
1742 continue. Do not use this for internal consistency checks; that's
1743 internal_error. Use of this function should be rare. */
1744 void
1745 fatal_error (location_t loc, const char *gmsgid, ...)
1747 auto_diagnostic_group d;
1748 va_list ap;
1749 va_start (ap, gmsgid);
1750 rich_location richloc (line_table, loc);
1751 diagnostic_impl (&richloc, NULL, -1, gmsgid, &ap, DK_FATAL);
1752 va_end (ap);
1754 gcc_unreachable ();
1757 /* An internal consistency check has failed. We make no attempt to
1758 continue. Note that unless there is debugging value to be had from
1759 a more specific message, or some other good reason, you should use
1760 abort () instead of calling this function directly. */
1761 void
1762 internal_error (const char *gmsgid, ...)
1764 auto_diagnostic_group d;
1765 va_list ap;
1766 va_start (ap, gmsgid);
1767 rich_location richloc (line_table, input_location);
1768 diagnostic_impl (&richloc, NULL, -1, gmsgid, &ap, DK_ICE);
1769 va_end (ap);
1771 gcc_unreachable ();
1774 /* Like internal_error, but no backtrace will be printed. Used when
1775 the internal error does not happen at the current location, but happened
1776 somewhere else. */
1777 void
1778 internal_error_no_backtrace (const char *gmsgid, ...)
1780 auto_diagnostic_group d;
1781 va_list ap;
1782 va_start (ap, gmsgid);
1783 rich_location richloc (line_table, input_location);
1784 diagnostic_impl (&richloc, NULL, -1, gmsgid, &ap, DK_ICE_NOBT);
1785 va_end (ap);
1787 gcc_unreachable ();
1790 /* Special case error functions. Most are implemented in terms of the
1791 above, or should be. */
1793 /* Print a diagnostic MSGID on FILE. This is just fprintf, except it
1794 runs its second argument through gettext. */
1795 void
1796 fnotice (FILE *file, const char *cmsgid, ...)
1798 va_list ap;
1800 va_start (ap, cmsgid);
1801 vfprintf (file, _(cmsgid), ap);
1802 va_end (ap);
1805 /* Inform the user that an error occurred while trying to report some
1806 other error. This indicates catastrophic internal inconsistencies,
1807 so give up now. But do try to flush out the previous error.
1808 This mustn't use internal_error, that will cause infinite recursion. */
1810 static void
1811 error_recursion (diagnostic_context *context)
1813 if (context->lock < 3)
1814 pp_newline_and_flush (context->printer);
1816 fnotice (stderr,
1817 "Internal compiler error: Error reporting routines re-entered.\n");
1819 /* Call diagnostic_action_after_output to get the "please submit a bug
1820 report" message. */
1821 diagnostic_action_after_output (context, DK_ICE);
1823 /* Do not use gcc_unreachable here; that goes through internal_error
1824 and therefore would cause infinite recursion. */
1825 real_abort ();
1828 /* Report an internal compiler error in a friendly manner. This is
1829 the function that gets called upon use of abort() in the source
1830 code generally, thanks to a special macro. */
1832 void
1833 fancy_abort (const char *file, int line, const char *function)
1835 internal_error ("in %s, at %s:%d", function, trim_filename (file), line);
1838 /* class auto_diagnostic_group. */
1840 /* Constructor: "push" this group into global_dc. */
1842 auto_diagnostic_group::auto_diagnostic_group ()
1844 global_dc->diagnostic_group_nesting_depth++;
1847 /* Destructor: "pop" this group from global_dc. */
1849 auto_diagnostic_group::~auto_diagnostic_group ()
1851 if (--global_dc->diagnostic_group_nesting_depth == 0)
1853 /* Handle the case where we've popped the final diagnostic group.
1854 If any diagnostics were emitted, give the context a chance
1855 to do something. */
1856 if (global_dc->diagnostic_group_emission_count > 0)
1858 if (global_dc->end_group_cb)
1859 global_dc->end_group_cb (global_dc);
1861 global_dc->diagnostic_group_emission_count = 0;
1865 /* Implementation of diagnostic_path::num_events vfunc for
1866 simple_diagnostic_path: simply get the number of events in the vec. */
1868 unsigned
1869 simple_diagnostic_path::num_events () const
1871 return m_events.length ();
1874 /* Implementation of diagnostic_path::get_event vfunc for
1875 simple_diagnostic_path: simply return the event in the vec. */
1877 const diagnostic_event &
1878 simple_diagnostic_path::get_event (int idx) const
1880 return *m_events[idx];
1883 /* Add an event to this path at LOC within function FNDECL at
1884 stack depth DEPTH.
1886 Use m_context's printer to format FMT, as the text of the new
1887 event.
1889 Return the id of the new event. */
1891 diagnostic_event_id_t
1892 simple_diagnostic_path::add_event (location_t loc, tree fndecl, int depth,
1893 const char *fmt, ...)
1895 pretty_printer *pp = m_event_pp;
1896 pp_clear_output_area (pp);
1898 text_info ti;
1899 rich_location rich_loc (line_table, UNKNOWN_LOCATION);
1901 va_list ap;
1903 va_start (ap, fmt);
1905 ti.format_spec = _(fmt);
1906 ti.args_ptr = &ap;
1907 ti.err_no = 0;
1908 ti.x_data = NULL;
1909 ti.m_richloc = &rich_loc;
1911 pp_format (pp, &ti);
1912 pp_output_formatted_text (pp);
1914 va_end (ap);
1916 simple_diagnostic_event *new_event
1917 = new simple_diagnostic_event (loc, fndecl, depth, pp_formatted_text (pp));
1918 m_events.safe_push (new_event);
1920 pp_clear_output_area (pp);
1922 return diagnostic_event_id_t (m_events.length () - 1);
1925 /* struct simple_diagnostic_event. */
1927 /* simple_diagnostic_event's ctor. */
1929 simple_diagnostic_event::simple_diagnostic_event (location_t loc,
1930 tree fndecl,
1931 int depth,
1932 const char *desc)
1933 : m_loc (loc), m_fndecl (fndecl), m_depth (depth), m_desc (xstrdup (desc))
1937 /* simple_diagnostic_event's dtor. */
1939 simple_diagnostic_event::~simple_diagnostic_event ()
1941 free (m_desc);
1944 /* Print PATH by emitting a dummy "note" associated with it. */
1946 DEBUG_FUNCTION
1947 void debug (diagnostic_path *path)
1949 rich_location richloc (line_table, UNKNOWN_LOCATION);
1950 richloc.set_path (path);
1951 inform (&richloc, "debug path");
1954 /* Really call the system 'abort'. This has to go right at the end of
1955 this file, so that there are no functions after it that call abort
1956 and get the system abort instead of our macro. */
1957 #undef abort
1958 static void
1959 real_abort (void)
1961 abort ();
1964 #if CHECKING_P
1966 namespace selftest {
1968 /* Helper function for test_print_escaped_string. */
1970 static void
1971 assert_print_escaped_string (const location &loc, const char *expected_output,
1972 const char *input)
1974 pretty_printer pp;
1975 print_escaped_string (&pp, input);
1976 ASSERT_STREQ_AT (loc, expected_output, pp_formatted_text (&pp));
1979 #define ASSERT_PRINT_ESCAPED_STRING_STREQ(EXPECTED_OUTPUT, INPUT) \
1980 assert_print_escaped_string (SELFTEST_LOCATION, EXPECTED_OUTPUT, INPUT)
1982 /* Tests of print_escaped_string. */
1984 static void
1985 test_print_escaped_string ()
1987 /* Empty string. */
1988 ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"\"", "");
1990 /* Non-empty string. */
1991 ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"hello world\"", "hello world");
1993 /* Various things that need to be escaped: */
1994 /* Backslash. */
1995 ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"before\\\\after\"",
1996 "before\\after");
1997 /* Tab. */
1998 ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"before\\tafter\"",
1999 "before\tafter");
2000 /* Newline. */
2001 ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"before\\nafter\"",
2002 "before\nafter");
2003 /* Double quote. */
2004 ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"before\\\"after\"",
2005 "before\"after");
2007 /* Non-printable characters: BEL: '\a': 0x07 */
2008 ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"before\\007after\"",
2009 "before\aafter");
2010 /* Non-printable characters: vertical tab: '\v': 0x0b */
2011 ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"before\\013after\"",
2012 "before\vafter");
2015 /* Tests of print_parseable_fixits. */
2017 /* Verify that print_parseable_fixits emits the empty string if there
2018 are no fixits. */
2020 static void
2021 test_print_parseable_fixits_none ()
2023 pretty_printer pp;
2024 rich_location richloc (line_table, UNKNOWN_LOCATION);
2026 print_parseable_fixits (&pp, &richloc);
2027 ASSERT_STREQ ("", pp_formatted_text (&pp));
2030 /* Verify that print_parseable_fixits does the right thing if there
2031 is an insertion fixit hint. */
2033 static void
2034 test_print_parseable_fixits_insert ()
2036 pretty_printer pp;
2037 rich_location richloc (line_table, UNKNOWN_LOCATION);
2039 linemap_add (line_table, LC_ENTER, false, "test.c", 0);
2040 linemap_line_start (line_table, 5, 100);
2041 linemap_add (line_table, LC_LEAVE, false, NULL, 0);
2042 location_t where = linemap_position_for_column (line_table, 10);
2043 richloc.add_fixit_insert_before (where, "added content");
2045 print_parseable_fixits (&pp, &richloc);
2046 ASSERT_STREQ ("fix-it:\"test.c\":{5:10-5:10}:\"added content\"\n",
2047 pp_formatted_text (&pp));
2050 /* Verify that print_parseable_fixits does the right thing if there
2051 is an removal fixit hint. */
2053 static void
2054 test_print_parseable_fixits_remove ()
2056 pretty_printer pp;
2057 rich_location richloc (line_table, UNKNOWN_LOCATION);
2059 linemap_add (line_table, LC_ENTER, false, "test.c", 0);
2060 linemap_line_start (line_table, 5, 100);
2061 linemap_add (line_table, LC_LEAVE, false, NULL, 0);
2062 source_range where;
2063 where.m_start = linemap_position_for_column (line_table, 10);
2064 where.m_finish = linemap_position_for_column (line_table, 20);
2065 richloc.add_fixit_remove (where);
2067 print_parseable_fixits (&pp, &richloc);
2068 ASSERT_STREQ ("fix-it:\"test.c\":{5:10-5:21}:\"\"\n",
2069 pp_formatted_text (&pp));
2072 /* Verify that print_parseable_fixits does the right thing if there
2073 is an replacement fixit hint. */
2075 static void
2076 test_print_parseable_fixits_replace ()
2078 pretty_printer pp;
2079 rich_location richloc (line_table, UNKNOWN_LOCATION);
2081 linemap_add (line_table, LC_ENTER, false, "test.c", 0);
2082 linemap_line_start (line_table, 5, 100);
2083 linemap_add (line_table, LC_LEAVE, false, NULL, 0);
2084 source_range where;
2085 where.m_start = linemap_position_for_column (line_table, 10);
2086 where.m_finish = linemap_position_for_column (line_table, 20);
2087 richloc.add_fixit_replace (where, "replacement");
2089 print_parseable_fixits (&pp, &richloc);
2090 ASSERT_STREQ ("fix-it:\"test.c\":{5:10-5:21}:\"replacement\"\n",
2091 pp_formatted_text (&pp));
2094 /* Verify that
2095 diagnostic_get_location_text (..., SHOW_COLUMN)
2096 generates EXPECTED_LOC_TEXT, given FILENAME, LINE, COLUMN, with
2097 colorization disabled. */
2099 static void
2100 assert_location_text (const char *expected_loc_text,
2101 const char *filename, int line, int column,
2102 bool show_column,
2103 int origin = 1,
2104 enum diagnostics_column_unit column_unit
2105 = DIAGNOSTICS_COLUMN_UNIT_BYTE)
2107 test_diagnostic_context dc;
2108 dc.show_column = show_column;
2109 dc.column_unit = column_unit;
2110 dc.column_origin = origin;
2112 expanded_location xloc;
2113 xloc.file = filename;
2114 xloc.line = line;
2115 xloc.column = column;
2116 xloc.data = NULL;
2117 xloc.sysp = false;
2119 char *actual_loc_text = diagnostic_get_location_text (&dc, xloc);
2120 ASSERT_STREQ (expected_loc_text, actual_loc_text);
2121 free (actual_loc_text);
2124 /* Verify that diagnostic_get_location_text works as expected. */
2126 static void
2127 test_diagnostic_get_location_text ()
2129 const char *old_progname = progname;
2130 progname = "PROGNAME";
2131 assert_location_text ("PROGNAME:", NULL, 0, 0, true);
2132 assert_location_text ("<built-in>:", "<built-in>", 42, 10, true);
2133 assert_location_text ("foo.c:42:10:", "foo.c", 42, 10, true);
2134 assert_location_text ("foo.c:42:9:", "foo.c", 42, 10, true, 0);
2135 assert_location_text ("foo.c:42:1010:", "foo.c", 42, 10, true, 1001);
2136 for (int origin = 0; origin != 2; ++origin)
2137 assert_location_text ("foo.c:42:", "foo.c", 42, 0, true, origin);
2138 assert_location_text ("foo.c:", "foo.c", 0, 10, true);
2139 assert_location_text ("foo.c:42:", "foo.c", 42, 10, false);
2140 assert_location_text ("foo.c:", "foo.c", 0, 10, false);
2142 maybe_line_and_column (INT_MAX, INT_MAX);
2143 maybe_line_and_column (INT_MIN, INT_MIN);
2146 /* In order to test display columns vs byte columns, we need to create a
2147 file for location_get_source_line() to read. */
2149 const char *const content = "smile \xf0\x9f\x98\x82\n";
2150 const int line_bytes = strlen (content) - 1;
2151 const int def_tabstop = 8;
2152 const int display_width = cpp_display_width (content, line_bytes,
2153 def_tabstop);
2154 ASSERT_EQ (line_bytes - 2, display_width);
2155 temp_source_file tmp (SELFTEST_LOCATION, ".c", content);
2156 const char *const fname = tmp.get_filename ();
2157 const int buf_len = strlen (fname) + 16;
2158 char *const expected = XNEWVEC (char, buf_len);
2160 snprintf (expected, buf_len, "%s:1:%d:", fname, line_bytes);
2161 assert_location_text (expected, fname, 1, line_bytes, true,
2162 1, DIAGNOSTICS_COLUMN_UNIT_BYTE);
2164 snprintf (expected, buf_len, "%s:1:%d:", fname, line_bytes - 1);
2165 assert_location_text (expected, fname, 1, line_bytes, true,
2166 0, DIAGNOSTICS_COLUMN_UNIT_BYTE);
2168 snprintf (expected, buf_len, "%s:1:%d:", fname, display_width);
2169 assert_location_text (expected, fname, 1, line_bytes, true,
2170 1, DIAGNOSTICS_COLUMN_UNIT_DISPLAY);
2172 snprintf (expected, buf_len, "%s:1:%d:", fname, display_width - 1);
2173 assert_location_text (expected, fname, 1, line_bytes, true,
2174 0, DIAGNOSTICS_COLUMN_UNIT_DISPLAY);
2176 XDELETEVEC (expected);
2180 progname = old_progname;
2183 /* Selftest for num_digits. */
2185 static void
2186 test_num_digits ()
2188 ASSERT_EQ (1, num_digits (0));
2189 ASSERT_EQ (1, num_digits (9));
2190 ASSERT_EQ (2, num_digits (10));
2191 ASSERT_EQ (2, num_digits (99));
2192 ASSERT_EQ (3, num_digits (100));
2193 ASSERT_EQ (3, num_digits (999));
2194 ASSERT_EQ (4, num_digits (1000));
2195 ASSERT_EQ (4, num_digits (9999));
2196 ASSERT_EQ (5, num_digits (10000));
2197 ASSERT_EQ (5, num_digits (99999));
2198 ASSERT_EQ (6, num_digits (100000));
2199 ASSERT_EQ (6, num_digits (999999));
2200 ASSERT_EQ (7, num_digits (1000000));
2201 ASSERT_EQ (7, num_digits (9999999));
2202 ASSERT_EQ (8, num_digits (10000000));
2203 ASSERT_EQ (8, num_digits (99999999));
2206 /* Run all of the selftests within this file. */
2208 void
2209 diagnostic_c_tests ()
2211 test_print_escaped_string ();
2212 test_print_parseable_fixits_none ();
2213 test_print_parseable_fixits_insert ();
2214 test_print_parseable_fixits_remove ();
2215 test_print_parseable_fixits_replace ();
2216 test_diagnostic_get_location_text ();
2217 test_num_digits ();
2221 } // namespace selftest
2223 #endif /* #if CHECKING_P */
2225 #if __GNUC__ >= 10
2226 # pragma GCC diagnostic pop
2227 #endif