1/* Language-independent diagnostic subroutines for the GNU Compiler Collection
2 Copyright (C) 1999-2023 Free Software Foundation, Inc.
3 Contributed by Gabriel Dos Reis <gdr@codesourcery.com>
4
5This file is part of GCC.
6
7GCC is free software; you can redistribute it and/or modify it under
8the terms of the GNU General Public License as published by the Free
9Software Foundation; either version 3, or (at your option) any later
10version.
11
12GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or
14FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15for more details.
16
17You should have received a copy of the GNU General Public License
18along with GCC; see the file COPYING3. If not see
19<http://www.gnu.org/licenses/>. */
20
21
22/* This file implements the language independent aspect of diagnostic
23 message module. */
24
25#include "config.h"
26#define INCLUDE_VECTOR
27#include "system.h"
28#include "coretypes.h"
29#include "version.h"
30#include "demangle.h"
31#include "intl.h"
32#include "backtrace.h"
33#include "diagnostic.h"
34#include "diagnostic-color.h"
35#include "diagnostic-url.h"
36#include "diagnostic-metadata.h"
37#include "diagnostic-path.h"
38#include "diagnostic-client-data-hooks.h"
39#include "diagnostic-diagram.h"
40#include "edit-context.h"
41#include "selftest.h"
42#include "selftest-diagnostic.h"
43#include "opts.h"
44#include "cpplib.h"
45#include "text-art/theme.h"
46#include "pretty-print-urlifier.h"
47
48#ifdef HAVE_TERMIOS_H
49# include <termios.h>
50#endif
51
52#ifdef GWINSZ_IN_SYS_IOCTL
53# include <sys/ioctl.h>
54#endif
55
56/* Disable warnings about quoting issues in the pp_xxx calls below
57 that (intentionally) don't follow GCC diagnostic conventions. */
58#if __GNUC__ >= 10
59# pragma GCC diagnostic push
60# pragma GCC diagnostic ignored "-Wformat-diag"
61#endif
62
63#define pedantic_warning_kind(DC) \
64 ((DC)->m_pedantic_errors ? DK_ERROR : DK_WARNING)
65#define permissive_error_kind(DC) ((DC)->m_permissive ? DK_WARNING : DK_ERROR)
66#define permissive_error_option(DC) ((DC)->m_opt_permissive)
67
68/* Prototypes. */
69static bool diagnostic_impl (rich_location *, const diagnostic_metadata *,
70 int, const char *,
71 va_list *, diagnostic_t) ATTRIBUTE_GCC_DIAG(4,0);
72static bool diagnostic_n_impl (rich_location *, const diagnostic_metadata *,
73 int, unsigned HOST_WIDE_INT,
74 const char *, const char *, va_list *,
75 diagnostic_t) ATTRIBUTE_GCC_DIAG(6,0);
76
77static void real_abort (void) ATTRIBUTE_NORETURN;
78
79/* Name of program invoked, sans directories. */
80
81const char *progname;
82
83/* A diagnostic_context surrogate for stderr. */
84static diagnostic_context global_diagnostic_context;
85diagnostic_context *global_dc = &global_diagnostic_context;
86
87/* Return a malloc'd string containing MSG formatted a la printf. The
88 caller is responsible for freeing the memory. */
89char *
90build_message_string (const char *msg, ...)
91{
92 char *str;
93 va_list ap;
94
95 va_start (ap, msg);
96 str = xvasprintf (msg, ap);
97 va_end (ap);
98
99 return str;
100}
101
102/* Same as diagnostic_build_prefix, but only the source FILE is given. */
103char *
104file_name_as_prefix (diagnostic_context *context, const char *f)
105{
106 const char *locus_cs
107 = colorize_start (pp_show_color (context->printer), name: "locus");
108 const char *locus_ce = colorize_stop (pp_show_color (context->printer));
109 return build_message_string (msg: "%s%s:%s ", locus_cs, f, locus_ce);
110}
111
112
113
114/* Return the value of the getenv("COLUMNS") as an integer. If the
115 value is not set to a positive integer, use ioctl to get the
116 terminal width. If it fails, return INT_MAX. */
117int
118get_terminal_width (void)
119{
120 const char * s = getenv (name: "COLUMNS");
121 if (s != NULL) {
122 int n = atoi (nptr: s);
123 if (n > 0)
124 return n;
125 }
126
127#ifdef TIOCGWINSZ
128 struct winsize w;
129 w.ws_col = 0;
130 if (ioctl (fd: 0, TIOCGWINSZ, &w) == 0 && w.ws_col > 0)
131 return w.ws_col;
132#endif
133
134 return INT_MAX;
135}
136
137/* Set caret_max_width to value. */
138void
139diagnostic_set_caret_max_width (diagnostic_context *context, int value)
140{
141 /* One minus to account for the leading empty space. */
142 value = value ? value - 1
143 : (isatty (fileno (pp_buffer (context->printer)->stream))
144 ? get_terminal_width () - 1: INT_MAX);
145
146 if (value <= 0)
147 value = INT_MAX;
148
149 context->m_source_printing.max_width = value;
150}
151
152void
153diagnostic_option_classifier::init (int n_opts)
154{
155 m_n_opts = n_opts;
156 m_classify_diagnostic = XNEWVEC (diagnostic_t, n_opts);
157 for (int i = 0; i < n_opts; i++)
158 m_classify_diagnostic[i] = DK_UNSPECIFIED;
159 m_push_list = nullptr;
160 m_n_push = 0;
161}
162
163void
164diagnostic_option_classifier::fini ()
165{
166 XDELETEVEC (m_classify_diagnostic);
167 m_classify_diagnostic = nullptr;
168 free (ptr: m_push_list);
169 m_n_push = 0;
170}
171
172/* Save all diagnostic classifications in a stack. */
173
174void
175diagnostic_option_classifier::push ()
176{
177 m_push_list = (int *) xrealloc (m_push_list, (m_n_push + 1) * sizeof (int));
178 m_push_list[m_n_push ++] = m_n_classification_history;
179}
180
181/* Restore the topmost classification set off the stack. If the stack
182 is empty, revert to the state based on command line parameters. */
183
184void
185diagnostic_option_classifier::pop (location_t where)
186{
187 int jump_to;
188
189 if (m_n_push)
190 jump_to = m_push_list [-- m_n_push];
191 else
192 jump_to = 0;
193
194 const int i = m_n_classification_history;
195 m_classification_history =
196 (diagnostic_classification_change_t *) xrealloc (m_classification_history, (i + 1)
197 * sizeof (diagnostic_classification_change_t));
198 m_classification_history[i].location = where;
199 m_classification_history[i].option = jump_to;
200 m_classification_history[i].kind = DK_POP;
201 m_n_classification_history ++;
202}
203
204/* Initialize the diagnostic message outputting machinery. */
205
206void
207diagnostic_context::initialize (int n_opts)
208{
209 /* Allocate a basic pretty-printer. Clients will replace this a
210 much more elaborated pretty-printer if they wish. */
211 this->printer = XNEW (pretty_printer);
212 new (this->printer) pretty_printer ();
213
214 m_file_cache = nullptr;
215 memset (s: m_diagnostic_count, c: 0, n: sizeof m_diagnostic_count);
216 m_warning_as_error_requested = false;
217 m_n_opts = n_opts;
218 m_option_classifier.init (n_opts);
219 m_source_printing.enabled = false;
220 diagnostic_set_caret_max_width (context: this, pp_line_cutoff (this->printer));
221 for (int i = 0; i < rich_location::STATICALLY_ALLOCATED_RANGES; i++)
222 m_source_printing.caret_chars[i] = '^';
223 m_show_cwe = false;
224 m_show_rules = false;
225 m_path_format = DPF_NONE;
226 m_show_path_depths = false;
227 m_show_option_requested = false;
228 m_abort_on_error = false;
229 m_show_column = false;
230 m_pedantic_errors = false;
231 m_permissive = false;
232 m_opt_permissive = 0;
233 m_fatal_errors = false;
234 m_inhibit_warnings = false;
235 m_warn_system_headers = false;
236 m_max_errors = 0;
237 m_internal_error = nullptr;
238 m_text_callbacks.begin_diagnostic = default_diagnostic_starter;
239 m_text_callbacks.start_span = default_diagnostic_start_span_fn;
240 m_text_callbacks.end_diagnostic = default_diagnostic_finalizer;
241 m_option_enabled = nullptr;
242 m_option_state = nullptr;
243 m_option_name = nullptr;
244 m_get_option_url = nullptr;
245 m_urlifier = nullptr;
246 m_last_location = UNKNOWN_LOCATION;
247 m_last_module = nullptr;
248 m_client_aux_data = nullptr;
249 m_lock = 0;
250 m_inhibit_notes_p = false;
251 m_source_printing.colorize_source_p = false;
252 m_source_printing.show_labels_p = false;
253 m_source_printing.show_line_numbers_p = false;
254 m_source_printing.min_margin_width = 0;
255 m_source_printing.show_ruler_p = false;
256 m_report_bug = false;
257 m_extra_output_kind = EXTRA_DIAGNOSTIC_OUTPUT_none;
258 if (const char *var = getenv (name: "GCC_EXTRA_DIAGNOSTIC_OUTPUT"))
259 {
260 if (!strcmp (s1: var, s2: "fixits-v1"))
261 m_extra_output_kind = EXTRA_DIAGNOSTIC_OUTPUT_fixits_v1;
262 else if (!strcmp (s1: var, s2: "fixits-v2"))
263 m_extra_output_kind = EXTRA_DIAGNOSTIC_OUTPUT_fixits_v2;
264 /* Silently ignore unrecognized values. */
265 }
266 m_column_unit = DIAGNOSTICS_COLUMN_UNIT_DISPLAY;
267 m_column_origin = 1;
268 m_tabstop = 8;
269 m_escape_format = DIAGNOSTICS_ESCAPE_FORMAT_UNICODE;
270 m_edit_context_ptr = nullptr;
271 m_diagnostic_groups.m_nesting_depth = 0;
272 m_diagnostic_groups.m_emission_count = 0;
273 m_output_format = new diagnostic_text_output_format (*this);
274 m_set_locations_cb = nullptr;
275 m_ice_handler_cb = nullptr;
276 m_includes_seen = nullptr;
277 m_client_data_hooks = nullptr;
278 m_diagrams.m_theme = nullptr;
279
280 enum diagnostic_text_art_charset text_art_charset
281 = DIAGNOSTICS_TEXT_ART_CHARSET_EMOJI;
282 if (const char *lang = getenv (name: "LANG"))
283 {
284 /* For LANG=C, don't assume the terminal supports anything
285 other than ASCII. */
286 if (!strcmp (s1: lang, s2: "C"))
287 text_art_charset = DIAGNOSTICS_TEXT_ART_CHARSET_ASCII;
288 }
289 set_text_art_charset (text_art_charset);
290}
291
292/* Maybe initialize the color support. We require clients to do this
293 explicitly, since most clients don't want color. When called
294 without a VALUE, it initializes with DIAGNOSTICS_COLOR_DEFAULT. */
295
296void
297diagnostic_context::color_init (int value)
298{
299 /* value == -1 is the default value. */
300 if (value < 0)
301 {
302 /* If DIAGNOSTICS_COLOR_DEFAULT is -1, default to
303 -fdiagnostics-color=auto if GCC_COLORS is in the environment,
304 otherwise default to -fdiagnostics-color=never, for other
305 values default to that
306 -fdiagnostics-color={never,auto,always}. */
307 if (DIAGNOSTICS_COLOR_DEFAULT == -1)
308 {
309 if (!getenv (name: "GCC_COLORS"))
310 return;
311 value = DIAGNOSTICS_COLOR_AUTO;
312 }
313 else
314 value = DIAGNOSTICS_COLOR_DEFAULT;
315 }
316 pp_show_color (this->printer)
317 = colorize_init ((diagnostic_color_rule_t) value);
318}
319
320/* Initialize URL support within this context based on VALUE,
321 handling "auto". */
322
323void
324diagnostic_context::urls_init (int value)
325{
326 /* value == -1 is the default value. */
327 if (value < 0)
328 {
329 /* If DIAGNOSTICS_URLS_DEFAULT is -1, default to
330 -fdiagnostics-urls=auto if GCC_URLS or TERM_URLS is in the
331 environment, otherwise default to -fdiagnostics-urls=never,
332 for other values default to that
333 -fdiagnostics-urls={never,auto,always}. */
334 if (DIAGNOSTICS_URLS_DEFAULT == -1)
335 {
336 if (!getenv (name: "GCC_URLS") && !getenv (name: "TERM_URLS"))
337 return;
338 value = DIAGNOSTICS_URL_AUTO;
339 }
340 else
341 value = DIAGNOSTICS_URLS_DEFAULT;
342 }
343
344 this->printer->url_format
345 = determine_url_format ((diagnostic_url_rule_t) value);
346}
347
348/* Create the file_cache, if not already created, and tell it how to
349 translate files on input. */
350void
351diagnostic_context::
352initialize_input_context (diagnostic_input_charset_callback ccb,
353 bool should_skip_bom)
354{
355 if (!m_file_cache)
356 m_file_cache = new file_cache;
357 m_file_cache->initialize_input_context (ccb, should_skip_bom);
358}
359
360/* Do any cleaning up required after the last diagnostic is emitted. */
361
362void
363diagnostic_context::finish ()
364{
365 delete m_output_format;
366 m_output_format= nullptr;
367
368 if (m_diagrams.m_theme)
369 {
370 delete m_diagrams.m_theme;
371 m_diagrams.m_theme = nullptr;
372 }
373
374 delete m_file_cache;
375 m_file_cache = nullptr;
376
377 m_option_classifier.fini ();
378
379 /* diagnostic_context::initialize allocates this->printer using XNEW
380 and placement-new. */
381 this->printer->~pretty_printer ();
382 XDELETE (this->printer);
383 this->printer = nullptr;
384
385 if (m_edit_context_ptr)
386 {
387 delete m_edit_context_ptr;
388 m_edit_context_ptr = nullptr;
389 }
390
391 if (m_includes_seen)
392 {
393 delete m_includes_seen;
394 m_includes_seen = nullptr;
395 }
396
397 if (m_client_data_hooks)
398 {
399 delete m_client_data_hooks;
400 m_client_data_hooks = nullptr;
401 }
402
403 delete m_urlifier;
404 m_urlifier = nullptr;
405}
406
407void
408diagnostic_context::set_output_format (diagnostic_output_format *output_format)
409{
410 /* Ideally we'd use a std::unique_ptr here. */
411 delete m_output_format;
412 m_output_format = output_format;
413}
414
415void
416diagnostic_context::set_client_data_hooks (diagnostic_client_data_hooks *hooks)
417{
418 /* Ideally we'd use a std::unique_ptr here. */
419 delete m_client_data_hooks;
420 m_client_data_hooks = hooks;
421}
422
423void
424diagnostic_context::set_urlifier (urlifier *urlifier)
425{
426 /* Ideally we'd use a std::unique_ptr here. */
427 delete m_urlifier;
428 m_urlifier = urlifier;
429}
430
431void
432diagnostic_context::create_edit_context ()
433{
434 delete m_edit_context_ptr;
435 m_edit_context_ptr = new edit_context ();
436}
437
438/* Initialize DIAGNOSTIC, where the message MSG has already been
439 translated. */
440void
441diagnostic_set_info_translated (diagnostic_info *diagnostic, const char *msg,
442 va_list *args, rich_location *richloc,
443 diagnostic_t kind)
444{
445 gcc_assert (richloc);
446 diagnostic->message.m_err_no = errno;
447 diagnostic->message.m_args_ptr = args;
448 diagnostic->message.m_format_spec = msg;
449 diagnostic->message.m_richloc = richloc;
450 diagnostic->richloc = richloc;
451 diagnostic->metadata = NULL;
452 diagnostic->kind = kind;
453 diagnostic->option_index = 0;
454}
455
456/* Initialize DIAGNOSTIC, where the message GMSGID has not yet been
457 translated. */
458void
459diagnostic_set_info (diagnostic_info *diagnostic, const char *gmsgid,
460 va_list *args, rich_location *richloc,
461 diagnostic_t kind)
462{
463 gcc_assert (richloc);
464 diagnostic_set_info_translated (diagnostic, _(gmsgid), args, richloc, kind);
465}
466
467static const char *const diagnostic_kind_color[] = {
468#define DEFINE_DIAGNOSTIC_KIND(K, T, C) (C),
469#include "diagnostic.def"
470#undef DEFINE_DIAGNOSTIC_KIND
471 NULL
472};
473
474/* Get a color name for diagnostics of type KIND
475 Result could be NULL. */
476
477const char *
478diagnostic_get_color_for_kind (diagnostic_t kind)
479{
480 return diagnostic_kind_color[kind];
481}
482
483/* Given an expanded_location, convert the column (which is in 1-based bytes)
484 to the requested units, without converting the origin.
485 Return -1 if the column is invalid (<= 0). */
486
487static int
488convert_column_unit (enum diagnostics_column_unit column_unit,
489 int tabstop,
490 expanded_location s)
491{
492 if (s.column <= 0)
493 return -1;
494
495 switch (column_unit)
496 {
497 default:
498 gcc_unreachable ();
499
500 case DIAGNOSTICS_COLUMN_UNIT_DISPLAY:
501 {
502 cpp_char_column_policy policy (tabstop, cpp_wcwidth);
503 return location_compute_display_column (exploc: s, policy);
504 }
505
506 case DIAGNOSTICS_COLUMN_UNIT_BYTE:
507 return s.column;
508 }
509}
510
511/* Given an expanded_location, convert the column (which is in 1-based bytes)
512 to the requested units and origin. Return -1 if the column is
513 invalid (<= 0). */
514int
515diagnostic_context::converted_column (expanded_location s) const
516{
517 int one_based_col = convert_column_unit (column_unit: m_column_unit, tabstop: m_tabstop, s);
518 if (one_based_col <= 0)
519 return -1;
520 return one_based_col + (m_column_origin - 1);
521}
522
523/* Return a formatted line and column ':%line:%column'. Elided if
524 line == 0 or col < 0. (A column of 0 may be valid due to the
525 -fdiagnostics-column-origin option.)
526 The result is a statically allocated buffer. */
527
528static const char *
529maybe_line_and_column (int line, int col)
530{
531 static char result[32];
532
533 if (line)
534 {
535 size_t l
536 = snprintf (s: result, maxlen: sizeof (result),
537 format: col >= 0 ? ":%d:%d" : ":%d", line, col);
538 gcc_checking_assert (l < sizeof (result));
539 }
540 else
541 result[0] = 0;
542 return result;
543}
544
545/* Return a malloc'd string describing a location e.g. "foo.c:42:10".
546 The caller is responsible for freeing the memory. */
547
548static char *
549diagnostic_get_location_text (diagnostic_context *context,
550 expanded_location s)
551{
552 pretty_printer *pp = context->printer;
553 const char *locus_cs = colorize_start (pp_show_color (pp), name: "locus");
554 const char *locus_ce = colorize_stop (pp_show_color (pp));
555 const char *file = s.file ? s.file : progname;
556 int line = 0;
557 int col = -1;
558 if (strcmp (s1: file, s2: special_fname_builtin ()))
559 {
560 line = s.line;
561 if (context->m_show_column)
562 col = context->converted_column (s);
563 }
564
565 const char *line_col = maybe_line_and_column (line, col);
566 return build_message_string (msg: "%s%s%s:%s", locus_cs, file,
567 line_col, locus_ce);
568}
569
570static const char *const diagnostic_kind_text[] = {
571#define DEFINE_DIAGNOSTIC_KIND(K, T, C) (T),
572#include "diagnostic.def"
573#undef DEFINE_DIAGNOSTIC_KIND
574 "must-not-happen"
575};
576
577/* Return a malloc'd string describing a location and the severity of the
578 diagnostic, e.g. "foo.c:42:10: error: ". The caller is responsible for
579 freeing the memory. */
580char *
581diagnostic_build_prefix (diagnostic_context *context,
582 const diagnostic_info *diagnostic)
583{
584 gcc_assert (diagnostic->kind < DK_LAST_DIAGNOSTIC_KIND);
585
586 const char *text = _(diagnostic_kind_text[diagnostic->kind]);
587 const char *text_cs = "", *text_ce = "";
588 pretty_printer *pp = context->printer;
589
590 if (diagnostic_kind_color[diagnostic->kind])
591 {
592 text_cs = colorize_start (pp_show_color (pp),
593 name: diagnostic_kind_color[diagnostic->kind]);
594 text_ce = colorize_stop (pp_show_color (pp));
595 }
596
597 expanded_location s = diagnostic_expand_location (diagnostic);
598 char *location_text = diagnostic_get_location_text (context, s);
599
600 char *result = build_message_string (msg: "%s %s%s%s", location_text,
601 text_cs, text, text_ce);
602 free (ptr: location_text);
603 return result;
604}
605
606/* Functions at which to stop the backtrace print. It's not
607 particularly helpful to print the callers of these functions. */
608
609static const char * const bt_stop[] =
610{
611 "main",
612 "toplev::main",
613 "execute_one_pass",
614 "compile_file",
615};
616
617/* A callback function passed to the backtrace_full function. */
618
619static int
620bt_callback (void *data, uintptr_t pc, const char *filename, int lineno,
621 const char *function)
622{
623 int *pcount = (int *) data;
624
625 /* If we don't have any useful information, don't print
626 anything. */
627 if (filename == NULL && function == NULL)
628 return 0;
629
630 /* Skip functions in diagnostic.cc. */
631 if (*pcount == 0
632 && filename != NULL
633 && strcmp (s1: lbasename (filename), s2: "diagnostic.cc") == 0)
634 return 0;
635
636 /* Print up to 20 functions. We could make this a --param, but
637 since this is only for debugging just use a constant for now. */
638 if (*pcount >= 20)
639 {
640 /* Returning a non-zero value stops the backtrace. */
641 return 1;
642 }
643 ++*pcount;
644
645 char *alc = NULL;
646 if (function != NULL)
647 {
648 char *str = cplus_demangle_v3 (mangled: function,
649 options: (DMGL_VERBOSE | DMGL_ANSI
650 | DMGL_GNU_V3 | DMGL_PARAMS));
651 if (str != NULL)
652 {
653 alc = str;
654 function = str;
655 }
656
657 for (size_t i = 0; i < ARRAY_SIZE (bt_stop); ++i)
658 {
659 size_t len = strlen (s: bt_stop[i]);
660 if (strncmp (s1: function, s2: bt_stop[i], n: len) == 0
661 && (function[len] == '\0' || function[len] == '('))
662 {
663 if (alc != NULL)
664 free (ptr: alc);
665 /* Returning a non-zero value stops the backtrace. */
666 return 1;
667 }
668 }
669 }
670
671 fprintf (stderr, format: "0x%lx %s\n\t%s:%d\n",
672 (unsigned long) pc,
673 function == NULL ? "???" : function,
674 filename == NULL ? "???" : filename,
675 lineno);
676
677 if (alc != NULL)
678 free (ptr: alc);
679
680 return 0;
681}
682
683/* A callback function passed to the backtrace_full function. This is
684 called if backtrace_full has an error. */
685
686static void
687bt_err_callback (void *data ATTRIBUTE_UNUSED, const char *msg, int errnum)
688{
689 if (errnum < 0)
690 {
691 /* This means that no debug info was available. Just quietly
692 skip printing backtrace info. */
693 return;
694 }
695 fprintf (stderr, format: "%s%s%s\n", msg, errnum == 0 ? "" : ": ",
696 errnum == 0 ? "" : xstrerror (errnum));
697}
698
699/* Check if we've met the maximum error limit, and if so fatally exit
700 with a message.
701 FLUSH indicates whether a diagnostic_context::finish call is needed. */
702
703void
704diagnostic_context::check_max_errors (bool flush)
705{
706 if (!m_max_errors)
707 return;
708
709 int count = (m_diagnostic_count[DK_ERROR]
710 + m_diagnostic_count[DK_SORRY]
711 + m_diagnostic_count[DK_WERROR]);
712
713 if (count >= m_max_errors)
714 {
715 fnotice (stderr,
716 "compilation terminated due to -fmax-errors=%u.\n",
717 m_max_errors);
718 if (flush)
719 finish ();
720 exit (FATAL_EXIT_CODE);
721 }
722}
723
724/* Take any action which is expected to happen after the diagnostic
725 is written out. This function does not always return. */
726void
727diagnostic_context::action_after_output (diagnostic_t diag_kind)
728{
729 switch (diag_kind)
730 {
731 case DK_DEBUG:
732 case DK_NOTE:
733 case DK_ANACHRONISM:
734 case DK_WARNING:
735 break;
736
737 case DK_ERROR:
738 case DK_SORRY:
739 if (m_abort_on_error)
740 real_abort ();
741 if (m_fatal_errors)
742 {
743 fnotice (stderr, "compilation terminated due to -Wfatal-errors.\n");
744 finish ();
745 exit (FATAL_EXIT_CODE);
746 }
747 break;
748
749 case DK_ICE:
750 case DK_ICE_NOBT:
751 {
752 /* Optional callback for attempting to handle ICEs gracefully. */
753 if (void (*ice_handler_cb) (diagnostic_context *) = m_ice_handler_cb)
754 {
755 /* Clear the callback, to avoid potentially re-entering
756 the routine if there's a crash within the handler. */
757 m_ice_handler_cb = NULL;
758 ice_handler_cb (this);
759 }
760 /* The context might have had diagnostic_finish called on
761 it at this point. */
762
763 struct backtrace_state *state = NULL;
764 if (diag_kind == DK_ICE)
765 state = backtrace_create_state (NULL, threaded: 0, error_callback: bt_err_callback, NULL);
766 int count = 0;
767 if (state != NULL)
768 backtrace_full (state, skip: 2, callback: bt_callback, error_callback: bt_err_callback,
769 data: (void *) &count);
770
771 if (m_abort_on_error)
772 real_abort ();
773
774 if (m_report_bug)
775 fnotice (stderr, "Please submit a full bug report, "
776 "with preprocessed source.\n");
777 else
778 fnotice (stderr, "Please submit a full bug report, "
779 "with preprocessed source (by using -freport-bug).\n");
780
781 if (count > 0)
782 fnotice (stderr, "Please include the complete backtrace "
783 "with any bug report.\n");
784 fnotice (stderr, "See %s for instructions.\n", bug_report_url);
785
786 exit (ICE_EXIT_CODE);
787 }
788
789 case DK_FATAL:
790 if (m_abort_on_error)
791 real_abort ();
792 finish ();
793 fnotice (stderr, "compilation terminated.\n");
794 exit (FATAL_EXIT_CODE);
795
796 default:
797 gcc_unreachable ();
798 }
799}
800
801/* Only dump the "In file included from..." stack once for each file. */
802
803bool
804diagnostic_context::includes_seen_p (const line_map_ordinary *map)
805{
806 /* No include path for main. */
807 if (MAIN_FILE_P (ord_map: map))
808 return true;
809
810 /* Always identify C++ modules, at least for now. */
811 auto probe = map;
812 if (linemap_check_ordinary (map)->reason == LC_RENAME)
813 /* The module source file shows up as LC_RENAME inside LC_MODULE. */
814 probe = linemap_included_from_linemap (set: line_table, map);
815 if (MAP_MODULE_P (map: probe))
816 return false;
817
818 if (!m_includes_seen)
819 m_includes_seen = new hash_set<location_t, false, location_hash>;
820
821 /* Hash the location of the #include directive to better handle files
822 that are included multiple times with different macros defined. */
823 return m_includes_seen->add (k: linemap_included_from (ord_map: map));
824}
825
826void
827diagnostic_context::report_current_module (location_t where)
828{
829 const line_map_ordinary *map = NULL;
830
831 if (pp_needs_newline (this->printer))
832 {
833 pp_newline (this->printer);
834 pp_needs_newline (this->printer) = false;
835 }
836
837 if (where <= BUILTINS_LOCATION)
838 return;
839
840 linemap_resolve_location (line_table, loc: where,
841 lrk: LRK_MACRO_DEFINITION_LOCATION,
842 loc_map: &map);
843
844 if (map && m_last_module != map)
845 {
846 m_last_module = map;
847 if (!includes_seen_p (map))
848 {
849 bool first = true, need_inc = true, was_module = MAP_MODULE_P (map);
850 expanded_location s = {};
851 do
852 {
853 where = linemap_included_from (ord_map: map);
854 map = linemap_included_from_linemap (set: line_table, map);
855 bool is_module = MAP_MODULE_P (map);
856 s.file = LINEMAP_FILE (ord_map: map);
857 s.line = SOURCE_LINE (ord_map: map, loc: where);
858 int col = -1;
859 if (first && m_show_column)
860 {
861 s.column = SOURCE_COLUMN (ord_map: map, loc: where);
862 col = converted_column (s);
863 }
864 const char *line_col = maybe_line_and_column (line: s.line, col);
865 static const char *const msgs[] =
866 {
867 NULL,
868 N_(" from"),
869 N_("In file included from"), /* 2 */
870 N_(" included from"),
871 N_("In module"), /* 4 */
872 N_("of module"),
873 N_("In module imported at"), /* 6 */
874 N_("imported at"),
875 };
876
877 unsigned index = (was_module ? 6 : is_module ? 4
878 : need_inc ? 2 : 0) + !first;
879
880 pp_verbatim (this->printer, "%s%s %r%s%s%R",
881 first ? "" : was_module ? ", " : ",\n",
882 _(msgs[index]),
883 "locus", s.file, line_col);
884 first = false, need_inc = was_module, was_module = is_module;
885 }
886 while (!includes_seen_p (map));
887 pp_verbatim (this->printer, ":");
888 pp_newline (this->printer);
889 }
890 }
891}
892
893/* If DIAGNOSTIC has a diagnostic_path and this context supports
894 printing paths, print the path. */
895
896void
897diagnostic_context::show_any_path (const diagnostic_info &diagnostic)
898{
899 const diagnostic_path *path = diagnostic.richloc->get_path ();
900 if (!path)
901 return;
902
903 if (m_print_path)
904 m_print_path (this, path);
905}
906
907/* class diagnostic_event. */
908
909/* struct diagnostic_event::meaning. */
910
911void
912diagnostic_event::meaning::dump_to_pp (pretty_printer *pp) const
913{
914 bool need_comma = false;
915 pp_character (pp, '{');
916 if (const char *verb_str = maybe_get_verb_str (m_verb))
917 {
918 pp_printf (pp, "verb: %qs", verb_str);
919 need_comma = true;
920 }
921 if (const char *noun_str = maybe_get_noun_str (m_noun))
922 {
923 if (need_comma)
924 pp_string (pp, ", ");
925 pp_printf (pp, "noun: %qs", noun_str);
926 need_comma = true;
927 }
928 if (const char *property_str = maybe_get_property_str (m_property))
929 {
930 if (need_comma)
931 pp_string (pp, ", ");
932 pp_printf (pp, "property: %qs", property_str);
933 need_comma = true;
934 }
935 pp_character (pp, '}');
936}
937
938/* Get a string (or NULL) for V suitable for use within a SARIF
939 threadFlowLocation "kinds" property (SARIF v2.1.0 section 3.38.8). */
940
941const char *
942diagnostic_event::meaning::maybe_get_verb_str (enum verb v)
943{
944 switch (v)
945 {
946 default:
947 gcc_unreachable ();
948 case VERB_unknown:
949 return NULL;
950 case VERB_acquire:
951 return "acquire";
952 case VERB_release:
953 return "release";
954 case VERB_enter:
955 return "enter";
956 case VERB_exit:
957 return "exit";
958 case VERB_call:
959 return "call";
960 case VERB_return:
961 return "return";
962 case VERB_branch:
963 return "branch";
964 case VERB_danger:
965 return "danger";
966 }
967}
968
969/* Get a string (or NULL) for N suitable for use within a SARIF
970 threadFlowLocation "kinds" property (SARIF v2.1.0 section 3.38.8). */
971
972const char *
973diagnostic_event::meaning::maybe_get_noun_str (enum noun n)
974{
975 switch (n)
976 {
977 default:
978 gcc_unreachable ();
979 case NOUN_unknown:
980 return NULL;
981 case NOUN_taint:
982 return "taint";
983 case NOUN_sensitive:
984 return "sensitive";
985 case NOUN_function:
986 return "function";
987 case NOUN_lock:
988 return "lock";
989 case NOUN_memory:
990 return "memory";
991 case NOUN_resource:
992 return "resource";
993 }
994}
995
996/* Get a string (or NULL) for P suitable for use within a SARIF
997 threadFlowLocation "kinds" property (SARIF v2.1.0 section 3.38.8). */
998
999const char *
1000diagnostic_event::meaning::maybe_get_property_str (enum property p)
1001{
1002 switch (p)
1003 {
1004 default:
1005 gcc_unreachable ();
1006 case PROPERTY_unknown:
1007 return NULL;
1008 case PROPERTY_true:
1009 return "true";
1010 case PROPERTY_false:
1011 return "false";
1012 }
1013}
1014
1015/* class diagnostic_path. */
1016
1017/* Subroutint of diagnostic_path::interprocedural_p.
1018 Look for the first event in this path that is within a function
1019 i.e. has a non-NULL fndecl, and a non-zero stack depth.
1020 If found, write its index to *OUT_IDX and return true.
1021 Otherwise return false. */
1022
1023bool
1024diagnostic_path::get_first_event_in_a_function (unsigned *out_idx) const
1025{
1026 const unsigned num = num_events ();
1027 for (unsigned i = 0; i < num; i++)
1028 {
1029 if (!(get_event (idx: i).get_fndecl () == NULL
1030 && get_event (idx: i).get_stack_depth () == 0))
1031 {
1032 *out_idx = i;
1033 return true;
1034 }
1035 }
1036 return false;
1037}
1038
1039/* Return true if the events in this path involve more than one
1040 function, or false if it is purely intraprocedural. */
1041
1042bool
1043diagnostic_path::interprocedural_p () const
1044{
1045 /* Ignore leading events that are outside of any function. */
1046 unsigned first_fn_event_idx;
1047 if (!get_first_event_in_a_function (out_idx: &first_fn_event_idx))
1048 return false;
1049
1050 const diagnostic_event &first_fn_event = get_event (idx: first_fn_event_idx);
1051 tree first_fndecl = first_fn_event.get_fndecl ();
1052 int first_fn_stack_depth = first_fn_event.get_stack_depth ();
1053
1054 const unsigned num = num_events ();
1055 for (unsigned i = first_fn_event_idx + 1; i < num; i++)
1056 {
1057 if (get_event (idx: i).get_fndecl () != first_fndecl)
1058 return true;
1059 if (get_event (idx: i).get_stack_depth () != first_fn_stack_depth)
1060 return true;
1061 }
1062 return false;
1063}
1064
1065void
1066default_diagnostic_starter (diagnostic_context *context,
1067 diagnostic_info *diagnostic)
1068{
1069 diagnostic_report_current_module (context, where: diagnostic_location (diagnostic));
1070 pp_set_prefix (context->printer, diagnostic_build_prefix (context,
1071 diagnostic));
1072}
1073
1074void
1075default_diagnostic_start_span_fn (diagnostic_context *context,
1076 expanded_location exploc)
1077{
1078 char *text = diagnostic_get_location_text (context, s: exploc);
1079 pp_string (context->printer, text);
1080 free (ptr: text);
1081 pp_newline (context->printer);
1082}
1083
1084void
1085default_diagnostic_finalizer (diagnostic_context *context,
1086 diagnostic_info *diagnostic,
1087 diagnostic_t)
1088{
1089 char *saved_prefix = pp_take_prefix (context->printer);
1090 pp_set_prefix (context->printer, NULL);
1091 pp_newline (context->printer);
1092 diagnostic_show_locus (context, richloc: diagnostic->richloc, diagnostic_kind: diagnostic->kind);
1093 pp_set_prefix (context->printer, saved_prefix);
1094 pp_flush (context->printer);
1095}
1096
1097/* Interface to specify diagnostic kind overrides. Returns the
1098 previous setting, or DK_UNSPECIFIED if the parameters are out of
1099 range. If OPTION_INDEX is zero, the new setting is for all the
1100 diagnostics. */
1101diagnostic_t
1102diagnostic_option_classifier::
1103classify_diagnostic (const diagnostic_context *context,
1104 int option_index,
1105 diagnostic_t new_kind,
1106 location_t where)
1107{
1108 diagnostic_t old_kind;
1109
1110 if (option_index < 0
1111 || option_index >= m_n_opts
1112 || new_kind >= DK_LAST_DIAGNOSTIC_KIND)
1113 return DK_UNSPECIFIED;
1114
1115 old_kind = m_classify_diagnostic[option_index];
1116
1117 /* Handle pragmas separately, since we need to keep track of *where*
1118 the pragmas were. */
1119 if (where != UNKNOWN_LOCATION)
1120 {
1121 int i;
1122
1123 /* Record the command-line status, so we can reset it back on DK_POP. */
1124 if (old_kind == DK_UNSPECIFIED)
1125 {
1126 old_kind = !context->m_option_enabled (option_index,
1127 context->m_lang_mask,
1128 context->m_option_state)
1129 ? DK_IGNORED : (context->warning_as_error_requested_p ()
1130 ? DK_ERROR : DK_WARNING);
1131 m_classify_diagnostic[option_index] = old_kind;
1132 }
1133
1134 for (i = m_n_classification_history - 1; i >= 0; i --)
1135 if (m_classification_history[i].option == option_index)
1136 {
1137 old_kind = m_classification_history[i].kind;
1138 break;
1139 }
1140
1141 i = m_n_classification_history;
1142 m_classification_history =
1143 (diagnostic_classification_change_t *) xrealloc (m_classification_history, (i + 1)
1144 * sizeof (diagnostic_classification_change_t));
1145 m_classification_history[i].location = where;
1146 m_classification_history[i].option = option_index;
1147 m_classification_history[i].kind = new_kind;
1148 m_n_classification_history ++;
1149 }
1150 else
1151 m_classify_diagnostic[option_index] = new_kind;
1152
1153 return old_kind;
1154}
1155
1156/* Helper function for print_parseable_fixits. Print TEXT to PP, obeying the
1157 escaping rules for -fdiagnostics-parseable-fixits. */
1158
1159static void
1160print_escaped_string (pretty_printer *pp, const char *text)
1161{
1162 gcc_assert (pp);
1163 gcc_assert (text);
1164
1165 pp_character (pp, '"');
1166 for (const char *ch = text; *ch; ch++)
1167 {
1168 switch (*ch)
1169 {
1170 case '\\':
1171 /* Escape backslash as two backslashes. */
1172 pp_string (pp, "\\\\");
1173 break;
1174 case '\t':
1175 /* Escape tab as "\t". */
1176 pp_string (pp, "\\t");
1177 break;
1178 case '\n':
1179 /* Escape newline as "\n". */
1180 pp_string (pp, "\\n");
1181 break;
1182 case '"':
1183 /* Escape doublequotes as \". */
1184 pp_string (pp, "\\\"");
1185 break;
1186 default:
1187 if (ISPRINT (*ch))
1188 pp_character (pp, *ch);
1189 else
1190 /* Use octal for non-printable chars. */
1191 {
1192 unsigned char c = (*ch & 0xff);
1193 pp_printf (pp, "\\%o%o%o", (c / 64), (c / 8) & 007, c & 007);
1194 }
1195 break;
1196 }
1197 }
1198 pp_character (pp, '"');
1199}
1200
1201/* Implementation of -fdiagnostics-parseable-fixits and
1202 GCC_EXTRA_DIAGNOSTIC_OUTPUT.
1203 Print a machine-parseable version of all fixits in RICHLOC to PP,
1204 using COLUMN_UNIT to express columns.
1205 Use TABSTOP when handling DIAGNOSTICS_COLUMN_UNIT_DISPLAY. */
1206
1207static void
1208print_parseable_fixits (pretty_printer *pp, rich_location *richloc,
1209 enum diagnostics_column_unit column_unit,
1210 int tabstop)
1211{
1212 gcc_assert (pp);
1213 gcc_assert (richloc);
1214
1215 char *saved_prefix = pp_take_prefix (pp);
1216 pp_set_prefix (pp, NULL);
1217
1218 for (unsigned i = 0; i < richloc->get_num_fixit_hints (); i++)
1219 {
1220 const fixit_hint *hint = richloc->get_fixit_hint (idx: i);
1221 location_t start_loc = hint->get_start_loc ();
1222 expanded_location start_exploc = expand_location (start_loc);
1223 pp_string (pp, "fix-it:");
1224 print_escaped_string (pp, text: start_exploc.file);
1225 /* For compatibility with clang, print as a half-open range. */
1226 location_t next_loc = hint->get_next_loc ();
1227 expanded_location next_exploc = expand_location (next_loc);
1228 int start_col
1229 = convert_column_unit (column_unit, tabstop, s: start_exploc);
1230 int next_col
1231 = convert_column_unit (column_unit, tabstop, s: next_exploc);
1232 pp_printf (pp, ":{%i:%i-%i:%i}:",
1233 start_exploc.line, start_col,
1234 next_exploc.line, next_col);
1235 print_escaped_string (pp, text: hint->get_string ());
1236 pp_newline (pp);
1237 }
1238
1239 pp_set_prefix (pp, saved_prefix);
1240}
1241
1242/* Update the inlining info in this context for a DIAGNOSTIC. */
1243
1244void
1245diagnostic_context::get_any_inlining_info (diagnostic_info *diagnostic)
1246{
1247 auto &ilocs = diagnostic->m_iinfo.m_ilocs;
1248
1249 if (m_set_locations_cb)
1250 /* Retrieve the locations into which the expression about to be
1251 diagnosed has been inlined, including those of all the callers
1252 all the way down the inlining stack. */
1253 m_set_locations_cb (this, diagnostic);
1254 else
1255 {
1256 /* When there's no callback use just the one location provided
1257 by the caller of the diagnostic function. */
1258 location_t loc = diagnostic_location (diagnostic);
1259 ilocs.safe_push (obj: loc);
1260 diagnostic->m_iinfo.m_allsyslocs = in_system_header_at (loc);
1261 }
1262}
1263
1264/* Update the kind of DIAGNOSTIC based on its location(s), including
1265 any of those in its inlining stack, relative to any
1266 #pragma GCC diagnostic
1267 directives recorded within this object.
1268
1269 Return the new kind of DIAGNOSTIC if it was updated, or DK_UNSPECIFIED
1270 otherwise. */
1271
1272diagnostic_t
1273diagnostic_option_classifier::
1274update_effective_level_from_pragmas (diagnostic_info *diagnostic) const
1275{
1276 if (m_n_classification_history <= 0)
1277 return DK_UNSPECIFIED;
1278
1279 /* Iterate over the locations, checking the diagnostic disposition
1280 for the diagnostic at each. If it's explicitly set as opposed
1281 to unspecified, update the disposition for this instance of
1282 the diagnostic and return it. */
1283 for (location_t loc: diagnostic->m_iinfo.m_ilocs)
1284 {
1285 /* FIXME: Stupid search. Optimize later. */
1286 for (int i = m_n_classification_history - 1; i >= 0; i --)
1287 {
1288 const diagnostic_classification_change_t &hist
1289 = m_classification_history[i];
1290
1291 location_t pragloc = hist.location;
1292 if (!linemap_location_before_p (set: line_table, loc_a: pragloc, loc_b: loc))
1293 continue;
1294
1295 if (hist.kind == (int) DK_POP)
1296 {
1297 /* Move on to the next region. */
1298 i = hist.option;
1299 continue;
1300 }
1301
1302 int option = hist.option;
1303 /* The option 0 is for all the diagnostics. */
1304 if (option == 0 || option == diagnostic->option_index)
1305 {
1306 diagnostic_t kind = hist.kind;
1307 if (kind != DK_UNSPECIFIED)
1308 diagnostic->kind = kind;
1309 return kind;
1310 }
1311 }
1312 }
1313
1314 return DK_UNSPECIFIED;
1315}
1316
1317/* Generate a URL string describing CWE. The caller is responsible for
1318 freeing the string. */
1319
1320char *
1321get_cwe_url (int cwe)
1322{
1323 return xasprintf ("https://cwe.mitre.org/data/definitions/%i.html", cwe);
1324}
1325
1326/* If DIAGNOSTIC has a CWE identifier, print it.
1327
1328 For example, if the diagnostic metadata associates it with CWE-119,
1329 " [CWE-119]" will be printed, suitably colorized, and with a URL of a
1330 description of the security issue. */
1331
1332void
1333diagnostic_context::print_any_cwe (const diagnostic_info &diagnostic)
1334{
1335 if (diagnostic.metadata == NULL)
1336 return;
1337
1338 int cwe = diagnostic.metadata->get_cwe ();
1339 if (cwe)
1340 {
1341 pretty_printer * const pp = this->printer;
1342 char *saved_prefix = pp_take_prefix (pp);
1343 pp_string (pp, " [");
1344 pp_string (pp, colorize_start (pp_show_color (pp),
1345 name: diagnostic_kind_color[diagnostic.kind]));
1346 if (pp->url_format != URL_FORMAT_NONE)
1347 {
1348 char *cwe_url = get_cwe_url (cwe);
1349 pp_begin_url (pp, url: cwe_url);
1350 free (ptr: cwe_url);
1351 }
1352 pp_printf (pp, "CWE-%i", cwe);
1353 pp_set_prefix (pp, saved_prefix);
1354 if (pp->url_format != URL_FORMAT_NONE)
1355 pp_end_url (pp);
1356 pp_string (pp, colorize_stop (pp_show_color (pp)));
1357 pp_character (pp, ']');
1358 }
1359}
1360
1361/* If DIAGNOSTIC has any rules associated with it, print them.
1362
1363 For example, if the diagnostic metadata associates it with a rule
1364 named "STR34-C", then " [STR34-C]" will be printed, suitably colorized,
1365 with any URL provided by the rule. */
1366
1367void
1368diagnostic_context::print_any_rules (const diagnostic_info &diagnostic)
1369{
1370 if (diagnostic.metadata == NULL)
1371 return;
1372
1373 for (unsigned idx = 0; idx < diagnostic.metadata->get_num_rules (); idx++)
1374 {
1375 const diagnostic_metadata::rule &rule
1376 = diagnostic.metadata->get_rule (idx);
1377 if (char *desc = rule.make_description ())
1378 {
1379 pretty_printer * const pp = this->printer;
1380 char *saved_prefix = pp_take_prefix (pp);
1381 pp_string (pp, " [");
1382 pp_string (pp,
1383 colorize_start (pp_show_color (pp),
1384 name: diagnostic_kind_color[diagnostic.kind]));
1385 char *url = NULL;
1386 if (pp->url_format != URL_FORMAT_NONE)
1387 {
1388 url = rule.make_url ();
1389 if (url)
1390 pp_begin_url (pp, url);
1391 }
1392 pp_string (pp, desc);
1393 pp_set_prefix (pp, saved_prefix);
1394 if (pp->url_format != URL_FORMAT_NONE)
1395 if (url)
1396 pp_end_url (pp);
1397 free (ptr: url);
1398 pp_string (pp, colorize_stop (pp_show_color (pp)));
1399 pp_character (pp, ']');
1400 free (ptr: desc);
1401 }
1402 }
1403}
1404
1405/* Print any metadata about the option used to control DIAGNOSTIC to CONTEXT's
1406 printer, e.g. " [-Werror=uninitialized]".
1407 Subroutine of diagnostic_context::report_diagnostic. */
1408
1409void
1410diagnostic_context::print_option_information (const diagnostic_info &diagnostic,
1411 diagnostic_t orig_diag_kind)
1412{
1413 char *option_text;
1414
1415 option_text = m_option_name (this, diagnostic.option_index,
1416 orig_diag_kind, diagnostic.kind);
1417
1418 if (option_text)
1419 {
1420 char *option_url = NULL;
1421 if (m_get_option_url
1422 && this->printer->url_format != URL_FORMAT_NONE)
1423 option_url = m_get_option_url (this,
1424 diagnostic.option_index);
1425 pretty_printer * const pp = this->printer;
1426 pp_string (pp, " [");
1427 pp_string (pp, colorize_start (pp_show_color (pp),
1428 name: diagnostic_kind_color[diagnostic.kind]));
1429 if (option_url)
1430 pp_begin_url (pp, url: option_url);
1431 pp_string (pp, option_text);
1432 if (option_url)
1433 {
1434 pp_end_url (pp);
1435 free (ptr: option_url);
1436 }
1437 pp_string (pp, colorize_stop (pp_show_color (pp)));
1438 pp_character (pp, ']');
1439 free (ptr: option_text);
1440 }
1441}
1442
1443/* Returns whether a DIAGNOSTIC should be printed, and adjusts diagnostic->kind
1444 as appropriate for #pragma GCC diagnostic and -Werror=foo. */
1445
1446bool
1447diagnostic_context::diagnostic_enabled (diagnostic_info *diagnostic)
1448{
1449 /* Update the inlining stack for this diagnostic. */
1450 get_any_inlining_info (diagnostic);
1451
1452 /* Diagnostics with no option or -fpermissive are always enabled. */
1453 if (!diagnostic->option_index
1454 || diagnostic->option_index == permissive_error_option (this))
1455 return true;
1456
1457 /* This tests if the user provided the appropriate -Wfoo or
1458 -Wno-foo option. */
1459 if (! m_option_enabled (diagnostic->option_index,
1460 m_lang_mask,
1461 m_option_state))
1462 return false;
1463
1464 /* This tests for #pragma diagnostic changes. */
1465 diagnostic_t diag_class
1466 = m_option_classifier.update_effective_level_from_pragmas (diagnostic);
1467
1468 /* This tests if the user provided the appropriate -Werror=foo
1469 option. */
1470 if (diag_class == DK_UNSPECIFIED
1471 && !option_unspecified_p (opt: diagnostic->option_index))
1472 diagnostic->kind = m_option_classifier.get_current_override (opt: diagnostic->option_index);
1473
1474 /* This allows for future extensions, like temporarily disabling
1475 warnings for ranges of source code. */
1476 if (diagnostic->kind == DK_IGNORED)
1477 return false;
1478
1479 return true;
1480}
1481
1482/* Returns whether warning OPT is enabled at LOC. */
1483
1484bool
1485diagnostic_context::warning_enabled_at (location_t loc, int opt)
1486{
1487 if (!diagnostic_report_warnings_p (this, loc))
1488 return false;
1489
1490 rich_location richloc (line_table, loc);
1491 diagnostic_info diagnostic = {};
1492 diagnostic.option_index = opt;
1493 diagnostic.richloc = &richloc;
1494 diagnostic.message.m_richloc = &richloc;
1495 diagnostic.kind = DK_WARNING;
1496 return diagnostic_enabled (diagnostic: &diagnostic);
1497}
1498
1499/* Report a diagnostic message (an error or a warning) as specified by
1500 this diagnostic_context.
1501 front-end independent format specifiers are exactly those described
1502 in the documentation of output_format.
1503 Return true if a diagnostic was printed, false otherwise. */
1504
1505bool
1506diagnostic_context::report_diagnostic (diagnostic_info *diagnostic)
1507{
1508 diagnostic_t orig_diag_kind = diagnostic->kind;
1509
1510 gcc_assert (m_output_format);
1511
1512 /* Give preference to being able to inhibit warnings, before they
1513 get reclassified to something else. */
1514 bool was_warning = (diagnostic->kind == DK_WARNING
1515 || diagnostic->kind == DK_PEDWARN);
1516 if (was_warning && m_inhibit_warnings)
1517 return false;
1518
1519 if (diagnostic->kind == DK_PEDWARN)
1520 {
1521 diagnostic->kind = pedantic_warning_kind (this);
1522 /* We do this to avoid giving the message for -pedantic-errors. */
1523 orig_diag_kind = diagnostic->kind;
1524 }
1525
1526 if (diagnostic->kind == DK_NOTE && m_inhibit_notes_p)
1527 return false;
1528
1529 if (m_lock > 0)
1530 {
1531 /* If we're reporting an ICE in the middle of some other error,
1532 try to flush out the previous error, then let this one
1533 through. Don't do this more than once. */
1534 if ((diagnostic->kind == DK_ICE || diagnostic->kind == DK_ICE_NOBT)
1535 && m_lock == 1)
1536 pp_newline_and_flush (this->printer);
1537 else
1538 error_recursion ();
1539 }
1540
1541 /* If the user requested that warnings be treated as errors, so be
1542 it. Note that we do this before the next block so that
1543 individual warnings can be overridden back to warnings with
1544 -Wno-error=*. */
1545 if (m_warning_as_error_requested
1546 && diagnostic->kind == DK_WARNING)
1547 diagnostic->kind = DK_ERROR;
1548
1549 diagnostic->message.m_data = &diagnostic->x_data;
1550
1551 /* Check to see if the diagnostic is enabled at the location and
1552 not disabled by #pragma GCC diagnostic anywhere along the inlining
1553 stack. . */
1554 if (!diagnostic_enabled (diagnostic))
1555 return false;
1556
1557 if ((was_warning || diagnostic->kind == DK_WARNING)
1558 && ((!m_warn_system_headers
1559 && diagnostic->m_iinfo.m_allsyslocs)
1560 || m_inhibit_warnings))
1561 /* Bail if the warning is not to be reported because all locations in the
1562 inlining stack (if there is one) are in system headers. */
1563 return false;
1564
1565 if (diagnostic->kind != DK_NOTE && diagnostic->kind != DK_ICE)
1566 diagnostic_check_max_errors (context: this);
1567
1568 m_lock++;
1569
1570 if (diagnostic->kind == DK_ICE || diagnostic->kind == DK_ICE_NOBT)
1571 {
1572 /* When not checking, ICEs are converted to fatal errors when an
1573 error has already occurred. This is counteracted by
1574 abort_on_error. */
1575 if (!CHECKING_P
1576 && (m_diagnostic_count[DK_ERROR] > 0
1577 || m_diagnostic_count[DK_SORRY] > 0)
1578 && !m_abort_on_error)
1579 {
1580 expanded_location s
1581 = expand_location (diagnostic_location (diagnostic));
1582 fnotice (stderr, "%s:%d: confused by earlier errors, bailing out\n",
1583 s.file, s.line);
1584 exit (ICE_EXIT_CODE);
1585 }
1586 if (m_internal_error)
1587 (*m_internal_error) (this,
1588 diagnostic->message.m_format_spec,
1589 diagnostic->message.m_args_ptr);
1590 }
1591 if (diagnostic->kind == DK_ERROR && orig_diag_kind == DK_WARNING)
1592 ++m_diagnostic_count[DK_WERROR];
1593 else
1594 ++m_diagnostic_count[diagnostic->kind];
1595
1596 /* Is this the initial diagnostic within the stack of groups? */
1597 if (m_diagnostic_groups.m_emission_count == 0)
1598 m_output_format->on_begin_group ();
1599 m_diagnostic_groups.m_emission_count++;
1600
1601 pp_format (this->printer, &diagnostic->message, m_urlifier);
1602 m_output_format->on_begin_diagnostic (diagnostic);
1603 pp_output_formatted_text (this->printer);
1604 if (m_show_cwe)
1605 print_any_cwe (diagnostic: *diagnostic);
1606 if (m_show_rules)
1607 print_any_rules (diagnostic: *diagnostic);
1608 if (m_show_option_requested)
1609 print_option_information (diagnostic: *diagnostic, orig_diag_kind);
1610 m_output_format->on_end_diagnostic (diagnostic, orig_diag_kind);
1611 switch (m_extra_output_kind)
1612 {
1613 default:
1614 break;
1615 case EXTRA_DIAGNOSTIC_OUTPUT_fixits_v1:
1616 print_parseable_fixits (pp: this->printer, richloc: diagnostic->richloc,
1617 column_unit: DIAGNOSTICS_COLUMN_UNIT_BYTE,
1618 tabstop: m_tabstop);
1619 pp_flush (this->printer);
1620 break;
1621 case EXTRA_DIAGNOSTIC_OUTPUT_fixits_v2:
1622 print_parseable_fixits (pp: this->printer, richloc: diagnostic->richloc,
1623 column_unit: DIAGNOSTICS_COLUMN_UNIT_DISPLAY,
1624 tabstop: m_tabstop);
1625 pp_flush (this->printer);
1626 break;
1627 }
1628 diagnostic_action_after_output (context: this, diag_kind: diagnostic->kind);
1629 diagnostic->x_data = NULL;
1630
1631 if (m_edit_context_ptr)
1632 if (diagnostic->richloc->fixits_can_be_auto_applied_p ())
1633 m_edit_context_ptr->add_fixits (richloc: diagnostic->richloc);
1634
1635 m_lock--;
1636
1637 show_any_path (diagnostic: *diagnostic);
1638
1639 return true;
1640}
1641
1642/* Get the number of digits in the decimal representation of VALUE. */
1643
1644int
1645num_digits (int value)
1646{
1647 /* Perhaps simpler to use log10 for this, but doing it this way avoids
1648 using floating point. */
1649 gcc_assert (value >= 0);
1650
1651 if (value == 0)
1652 return 1;
1653
1654 int digits = 0;
1655 while (value > 0)
1656 {
1657 digits++;
1658 value /= 10;
1659 }
1660 return digits;
1661}
1662
1663/* Given a partial pathname as input, return another pathname that
1664 shares no directory elements with the pathname of __FILE__. This
1665 is used by fancy_abort() to print `internal compiler error in expr.cc'
1666 instead of `internal compiler error in ../../GCC/gcc/expr.cc'. */
1667
1668const char *
1669trim_filename (const char *name)
1670{
1671 static const char this_file[] = __FILE__;
1672 const char *p = name, *q = this_file;
1673
1674 /* First skip any "../" in each filename. This allows us to give a proper
1675 reference to a file in a subdirectory. */
1676 while (p[0] == '.' && p[1] == '.' && IS_DIR_SEPARATOR (p[2]))
1677 p += 3;
1678
1679 while (q[0] == '.' && q[1] == '.' && IS_DIR_SEPARATOR (q[2]))
1680 q += 3;
1681
1682 /* Now skip any parts the two filenames have in common. */
1683 while (*p == *q && *p != 0 && *q != 0)
1684 p++, q++;
1685
1686 /* Now go backwards until the previous directory separator. */
1687 while (p > name && !IS_DIR_SEPARATOR (p[-1]))
1688 p--;
1689
1690 return p;
1691}
1692
1693/* Standard error reporting routines in increasing order of severity.
1694 All of these take arguments like printf. */
1695
1696/* Text to be emitted verbatim to the error message stream; this
1697 produces no prefix and disables line-wrapping. Use rarely. */
1698void
1699verbatim (const char *gmsgid, ...)
1700{
1701 va_list ap;
1702
1703 va_start (ap, gmsgid);
1704 text_info text (_(gmsgid), &ap, errno);
1705 pp_format_verbatim (global_dc->printer, &text);
1706 pp_newline_and_flush (global_dc->printer);
1707 va_end (ap);
1708}
1709
1710/* Add a note with text GMSGID and with LOCATION to the diagnostic CONTEXT. */
1711void
1712diagnostic_append_note (diagnostic_context *context,
1713 location_t location,
1714 const char * gmsgid, ...)
1715{
1716 diagnostic_info diagnostic;
1717 va_list ap;
1718 rich_location richloc (line_table, location);
1719
1720 va_start (ap, gmsgid);
1721 diagnostic_set_info (diagnostic: &diagnostic, gmsgid, args: &ap, richloc: &richloc, kind: DK_NOTE);
1722 if (context->m_inhibit_notes_p)
1723 {
1724 va_end (ap);
1725 return;
1726 }
1727 char *saved_prefix = pp_take_prefix (context->printer);
1728 pp_set_prefix (context->printer,
1729 diagnostic_build_prefix (context, diagnostic: &diagnostic));
1730 pp_format (context->printer, &diagnostic.message);
1731 pp_output_formatted_text (context->printer);
1732 pp_destroy_prefix (context->printer);
1733 pp_set_prefix (context->printer, saved_prefix);
1734 pp_newline (context->printer);
1735 diagnostic_show_locus (context, richloc: &richloc, diagnostic_kind: DK_NOTE);
1736 va_end (ap);
1737}
1738
1739/* Implement emit_diagnostic, inform, warning, warning_at, pedwarn,
1740 permerror, error, error_at, error_at, sorry, fatal_error, internal_error,
1741 and internal_error_no_backtrace, as documented and defined below. */
1742static bool
1743diagnostic_impl (rich_location *richloc, const diagnostic_metadata *metadata,
1744 int opt, const char *gmsgid,
1745 va_list *ap, diagnostic_t kind)
1746{
1747 diagnostic_info diagnostic;
1748 if (kind == DK_PERMERROR)
1749 {
1750 diagnostic_set_info (diagnostic: &diagnostic, gmsgid, args: ap, richloc,
1751 permissive_error_kind (global_dc));
1752 diagnostic.option_index = (opt != -1 ? opt
1753 : permissive_error_option (global_dc));
1754 }
1755 else
1756 {
1757 diagnostic_set_info (diagnostic: &diagnostic, gmsgid, args: ap, richloc, kind);
1758 if (kind == DK_WARNING || kind == DK_PEDWARN)
1759 diagnostic.option_index = opt;
1760 }
1761 diagnostic.metadata = metadata;
1762 return global_dc->report_diagnostic (diagnostic: &diagnostic);
1763}
1764
1765/* Implement inform_n, warning_n, and error_n, as documented and
1766 defined below. */
1767static bool
1768diagnostic_n_impl (rich_location *richloc, const diagnostic_metadata *metadata,
1769 int opt, unsigned HOST_WIDE_INT n,
1770 const char *singular_gmsgid,
1771 const char *plural_gmsgid,
1772 va_list *ap, diagnostic_t kind)
1773{
1774 diagnostic_info diagnostic;
1775 unsigned long gtn;
1776
1777 if (sizeof n <= sizeof gtn)
1778 gtn = n;
1779 else
1780 /* Use the largest number ngettext can handle, otherwise
1781 preserve the six least significant decimal digits for
1782 languages where the plural form depends on them. */
1783 gtn = n <= ULONG_MAX ? n : n % 1000000LU + 1000000LU;
1784
1785 const char *text = ngettext (msgid1: singular_gmsgid, msgid2: plural_gmsgid, n: gtn);
1786 diagnostic_set_info_translated (diagnostic: &diagnostic, msg: text, args: ap, richloc, kind);
1787 if (kind == DK_WARNING)
1788 diagnostic.option_index = opt;
1789 diagnostic.metadata = metadata;
1790 return global_dc->report_diagnostic (diagnostic: &diagnostic);
1791}
1792
1793/* Wrapper around diagnostic_impl taking a variable argument list. */
1794
1795bool
1796emit_diagnostic (diagnostic_t kind, location_t location, int opt,
1797 const char *gmsgid, ...)
1798{
1799 auto_diagnostic_group d;
1800 va_list ap;
1801 va_start (ap, gmsgid);
1802 rich_location richloc (line_table, location);
1803 bool ret = diagnostic_impl (richloc: &richloc, NULL, opt, gmsgid, ap: &ap, kind);
1804 va_end (ap);
1805 return ret;
1806}
1807
1808/* As above, but for rich_location *. */
1809
1810bool
1811emit_diagnostic (diagnostic_t kind, rich_location *richloc, int opt,
1812 const char *gmsgid, ...)
1813{
1814 auto_diagnostic_group d;
1815 va_list ap;
1816 va_start (ap, gmsgid);
1817 bool ret = diagnostic_impl (richloc, NULL, opt, gmsgid, ap: &ap, kind);
1818 va_end (ap);
1819 return ret;
1820}
1821
1822/* Wrapper around diagnostic_impl taking a va_list parameter. */
1823
1824bool
1825emit_diagnostic_valist (diagnostic_t kind, location_t location, int opt,
1826 const char *gmsgid, va_list *ap)
1827{
1828 rich_location richloc (line_table, location);
1829 return diagnostic_impl (richloc: &richloc, NULL, opt, gmsgid, ap, kind);
1830}
1831
1832/* An informative note at LOCATION. Use this for additional details on an error
1833 message. */
1834void
1835inform (location_t location, const char *gmsgid, ...)
1836{
1837 auto_diagnostic_group d;
1838 va_list ap;
1839 va_start (ap, gmsgid);
1840 rich_location richloc (line_table, location);
1841 diagnostic_impl (richloc: &richloc, NULL, opt: -1, gmsgid, ap: &ap, kind: DK_NOTE);
1842 va_end (ap);
1843}
1844
1845/* Same as "inform" above, but at RICHLOC. */
1846void
1847inform (rich_location *richloc, const char *gmsgid, ...)
1848{
1849 gcc_assert (richloc);
1850
1851 auto_diagnostic_group d;
1852 va_list ap;
1853 va_start (ap, gmsgid);
1854 diagnostic_impl (richloc, NULL, opt: -1, gmsgid, ap: &ap, kind: DK_NOTE);
1855 va_end (ap);
1856}
1857
1858/* An informative note at LOCATION. Use this for additional details on an
1859 error message. */
1860void
1861inform_n (location_t location, unsigned HOST_WIDE_INT n,
1862 const char *singular_gmsgid, const char *plural_gmsgid, ...)
1863{
1864 va_list ap;
1865 va_start (ap, plural_gmsgid);
1866 auto_diagnostic_group d;
1867 rich_location richloc (line_table, location);
1868 diagnostic_n_impl (richloc: &richloc, NULL, opt: -1, n, singular_gmsgid, plural_gmsgid,
1869 ap: &ap, kind: DK_NOTE);
1870 va_end (ap);
1871}
1872
1873/* A warning at INPUT_LOCATION. Use this for code which is correct according
1874 to the relevant language specification but is likely to be buggy anyway.
1875 Returns true if the warning was printed, false if it was inhibited. */
1876bool
1877warning (int opt, const char *gmsgid, ...)
1878{
1879 auto_diagnostic_group d;
1880 va_list ap;
1881 va_start (ap, gmsgid);
1882 rich_location richloc (line_table, input_location);
1883 bool ret = diagnostic_impl (richloc: &richloc, NULL, opt, gmsgid, ap: &ap, kind: DK_WARNING);
1884 va_end (ap);
1885 return ret;
1886}
1887
1888/* A warning at LOCATION. Use this for code which is correct according to the
1889 relevant language specification but is likely to be buggy anyway.
1890 Returns true if the warning was printed, false if it was inhibited. */
1891
1892bool
1893warning_at (location_t location, int opt, const char *gmsgid, ...)
1894{
1895 auto_diagnostic_group d;
1896 va_list ap;
1897 va_start (ap, gmsgid);
1898 rich_location richloc (line_table, location);
1899 bool ret = diagnostic_impl (richloc: &richloc, NULL, opt, gmsgid, ap: &ap, kind: DK_WARNING);
1900 va_end (ap);
1901 return ret;
1902}
1903
1904/* Same as "warning at" above, but using RICHLOC. */
1905
1906bool
1907warning_at (rich_location *richloc, int opt, const char *gmsgid, ...)
1908{
1909 gcc_assert (richloc);
1910
1911 auto_diagnostic_group d;
1912 va_list ap;
1913 va_start (ap, gmsgid);
1914 bool ret = diagnostic_impl (richloc, NULL, opt, gmsgid, ap: &ap, kind: DK_WARNING);
1915 va_end (ap);
1916 return ret;
1917}
1918
1919/* Same as "warning at" above, but using METADATA. */
1920
1921bool
1922warning_meta (rich_location *richloc,
1923 const diagnostic_metadata &metadata,
1924 int opt, const char *gmsgid, ...)
1925{
1926 gcc_assert (richloc);
1927
1928 auto_diagnostic_group d;
1929 va_list ap;
1930 va_start (ap, gmsgid);
1931 bool ret
1932 = diagnostic_impl (richloc, metadata: &metadata, opt, gmsgid, ap: &ap,
1933 kind: DK_WARNING);
1934 va_end (ap);
1935 return ret;
1936}
1937
1938/* Same as warning_n plural variant below, but using RICHLOC. */
1939
1940bool
1941warning_n (rich_location *richloc, int opt, unsigned HOST_WIDE_INT n,
1942 const char *singular_gmsgid, const char *plural_gmsgid, ...)
1943{
1944 gcc_assert (richloc);
1945
1946 auto_diagnostic_group d;
1947 va_list ap;
1948 va_start (ap, plural_gmsgid);
1949 bool ret = diagnostic_n_impl (richloc, NULL, opt, n,
1950 singular_gmsgid, plural_gmsgid,
1951 ap: &ap, kind: DK_WARNING);
1952 va_end (ap);
1953 return ret;
1954}
1955
1956/* A warning at LOCATION. Use this for code which is correct according to the
1957 relevant language specification but is likely to be buggy anyway.
1958 Returns true if the warning was printed, false if it was inhibited. */
1959
1960bool
1961warning_n (location_t location, int opt, unsigned HOST_WIDE_INT n,
1962 const char *singular_gmsgid, const char *plural_gmsgid, ...)
1963{
1964 auto_diagnostic_group d;
1965 va_list ap;
1966 va_start (ap, plural_gmsgid);
1967 rich_location richloc (line_table, location);
1968 bool ret = diagnostic_n_impl (richloc: &richloc, NULL, opt, n,
1969 singular_gmsgid, plural_gmsgid,
1970 ap: &ap, kind: DK_WARNING);
1971 va_end (ap);
1972 return ret;
1973}
1974
1975/* A "pedantic" warning at LOCATION: issues a warning unless
1976 -pedantic-errors was given on the command line, in which case it
1977 issues an error. Use this for diagnostics required by the relevant
1978 language standard, if you have chosen not to make them errors.
1979
1980 Note that these diagnostics are issued independent of the setting
1981 of the -Wpedantic command-line switch. To get a warning enabled
1982 only with that switch, use either "if (pedantic) pedwarn
1983 (OPT_Wpedantic,...)" or just "pedwarn (OPT_Wpedantic,..)". To get a
1984 pedwarn independently of the -Wpedantic switch use "pedwarn (0,...)".
1985
1986 Returns true if the warning was printed, false if it was inhibited. */
1987
1988bool
1989pedwarn (location_t location, int opt, const char *gmsgid, ...)
1990{
1991 auto_diagnostic_group d;
1992 va_list ap;
1993 va_start (ap, gmsgid);
1994 rich_location richloc (line_table, location);
1995 bool ret = diagnostic_impl (richloc: &richloc, NULL, opt, gmsgid, ap: &ap, kind: DK_PEDWARN);
1996 va_end (ap);
1997 return ret;
1998}
1999
2000/* Same as pedwarn above, but using RICHLOC. */
2001
2002bool
2003pedwarn (rich_location *richloc, int opt, const char *gmsgid, ...)
2004{
2005 gcc_assert (richloc);
2006
2007 auto_diagnostic_group d;
2008 va_list ap;
2009 va_start (ap, gmsgid);
2010 bool ret = diagnostic_impl (richloc, NULL, opt, gmsgid, ap: &ap, kind: DK_PEDWARN);
2011 va_end (ap);
2012 return ret;
2013}
2014
2015/* A "permissive" error at LOCATION: issues an error unless
2016 -fpermissive was given on the command line, in which case it issues
2017 a warning. Use this for things that really should be errors but we
2018 want to support legacy code.
2019
2020 Returns true if the warning was printed, false if it was inhibited. */
2021
2022bool
2023permerror (location_t location, const char *gmsgid, ...)
2024{
2025 auto_diagnostic_group d;
2026 va_list ap;
2027 va_start (ap, gmsgid);
2028 rich_location richloc (line_table, location);
2029 bool ret = diagnostic_impl (richloc: &richloc, NULL, opt: -1, gmsgid, ap: &ap, kind: DK_PERMERROR);
2030 va_end (ap);
2031 return ret;
2032}
2033
2034/* Same as "permerror" above, but at RICHLOC. */
2035
2036bool
2037permerror (rich_location *richloc, const char *gmsgid, ...)
2038{
2039 gcc_assert (richloc);
2040
2041 auto_diagnostic_group d;
2042 va_list ap;
2043 va_start (ap, gmsgid);
2044 bool ret = diagnostic_impl (richloc, NULL, opt: -1, gmsgid, ap: &ap, kind: DK_PERMERROR);
2045 va_end (ap);
2046 return ret;
2047}
2048
2049/* Similar to the above, but controlled by a flag other than -fpermissive.
2050 As above, an error by default or a warning with -fpermissive, but this
2051 diagnostic can also be downgraded by -Wno-error=opt. */
2052
2053bool
2054permerror_opt (location_t location, int opt, const char *gmsgid, ...)
2055{
2056 auto_diagnostic_group d;
2057 va_list ap;
2058 va_start (ap, gmsgid);
2059 rich_location richloc (line_table, location);
2060 bool ret = diagnostic_impl (richloc: &richloc, NULL, opt, gmsgid, ap: &ap, kind: DK_PERMERROR);
2061 va_end (ap);
2062 return ret;
2063}
2064
2065/* Same as "permerror" above, but at RICHLOC. */
2066
2067bool
2068permerror_opt (rich_location *richloc, int opt, const char *gmsgid, ...)
2069{
2070 gcc_assert (richloc);
2071
2072 auto_diagnostic_group d;
2073 va_list ap;
2074 va_start (ap, gmsgid);
2075 bool ret = diagnostic_impl (richloc, NULL, opt, gmsgid, ap: &ap, kind: DK_PERMERROR);
2076 va_end (ap);
2077 return ret;
2078}
2079
2080/* A hard error: the code is definitely ill-formed, and an object file
2081 will not be produced. */
2082void
2083error (const char *gmsgid, ...)
2084{
2085 auto_diagnostic_group d;
2086 va_list ap;
2087 va_start (ap, gmsgid);
2088 rich_location richloc (line_table, input_location);
2089 diagnostic_impl (richloc: &richloc, NULL, opt: -1, gmsgid, ap: &ap, kind: DK_ERROR);
2090 va_end (ap);
2091}
2092
2093/* A hard error: the code is definitely ill-formed, and an object file
2094 will not be produced. */
2095void
2096error_n (location_t location, unsigned HOST_WIDE_INT n,
2097 const char *singular_gmsgid, const char *plural_gmsgid, ...)
2098{
2099 auto_diagnostic_group d;
2100 va_list ap;
2101 va_start (ap, plural_gmsgid);
2102 rich_location richloc (line_table, location);
2103 diagnostic_n_impl (richloc: &richloc, NULL, opt: -1, n, singular_gmsgid, plural_gmsgid,
2104 ap: &ap, kind: DK_ERROR);
2105 va_end (ap);
2106}
2107
2108/* Same as above, but use location LOC instead of input_location. */
2109void
2110error_at (location_t loc, const char *gmsgid, ...)
2111{
2112 auto_diagnostic_group d;
2113 va_list ap;
2114 va_start (ap, gmsgid);
2115 rich_location richloc (line_table, loc);
2116 diagnostic_impl (richloc: &richloc, NULL, opt: -1, gmsgid, ap: &ap, kind: DK_ERROR);
2117 va_end (ap);
2118}
2119
2120/* Same as above, but use RICH_LOC. */
2121
2122void
2123error_at (rich_location *richloc, const char *gmsgid, ...)
2124{
2125 gcc_assert (richloc);
2126
2127 auto_diagnostic_group d;
2128 va_list ap;
2129 va_start (ap, gmsgid);
2130 diagnostic_impl (richloc, NULL, opt: -1, gmsgid, ap: &ap, kind: DK_ERROR);
2131 va_end (ap);
2132}
2133
2134/* Same as above, but with metadata. */
2135
2136void
2137error_meta (rich_location *richloc, const diagnostic_metadata &metadata,
2138 const char *gmsgid, ...)
2139{
2140 gcc_assert (richloc);
2141
2142 auto_diagnostic_group d;
2143 va_list ap;
2144 va_start (ap, gmsgid);
2145 diagnostic_impl (richloc, metadata: &metadata, opt: -1, gmsgid, ap: &ap, kind: DK_ERROR);
2146 va_end (ap);
2147}
2148
2149/* "Sorry, not implemented." Use for a language feature which is
2150 required by the relevant specification but not implemented by GCC.
2151 An object file will not be produced. */
2152void
2153sorry (const char *gmsgid, ...)
2154{
2155 auto_diagnostic_group d;
2156 va_list ap;
2157 va_start (ap, gmsgid);
2158 rich_location richloc (line_table, input_location);
2159 diagnostic_impl (richloc: &richloc, NULL, opt: -1, gmsgid, ap: &ap, kind: DK_SORRY);
2160 va_end (ap);
2161}
2162
2163/* Same as above, but use location LOC instead of input_location. */
2164void
2165sorry_at (location_t loc, const char *gmsgid, ...)
2166{
2167 auto_diagnostic_group d;
2168 va_list ap;
2169 va_start (ap, gmsgid);
2170 rich_location richloc (line_table, loc);
2171 diagnostic_impl (richloc: &richloc, NULL, opt: -1, gmsgid, ap: &ap, kind: DK_SORRY);
2172 va_end (ap);
2173}
2174
2175/* Return true if an error or a "sorry" has been seen. Various
2176 processing is disabled after errors. */
2177bool
2178seen_error (void)
2179{
2180 return errorcount || sorrycount;
2181}
2182
2183/* An error which is severe enough that we make no attempt to
2184 continue. Do not use this for internal consistency checks; that's
2185 internal_error. Use of this function should be rare. */
2186void
2187fatal_error (location_t loc, const char *gmsgid, ...)
2188{
2189 auto_diagnostic_group d;
2190 va_list ap;
2191 va_start (ap, gmsgid);
2192 rich_location richloc (line_table, loc);
2193 diagnostic_impl (richloc: &richloc, NULL, opt: -1, gmsgid, ap: &ap, kind: DK_FATAL);
2194 va_end (ap);
2195
2196 gcc_unreachable ();
2197}
2198
2199/* An internal consistency check has failed. We make no attempt to
2200 continue. */
2201void
2202internal_error (const char *gmsgid, ...)
2203{
2204 auto_diagnostic_group d;
2205 va_list ap;
2206 va_start (ap, gmsgid);
2207 rich_location richloc (line_table, input_location);
2208 diagnostic_impl (richloc: &richloc, NULL, opt: -1, gmsgid, ap: &ap, kind: DK_ICE);
2209 va_end (ap);
2210
2211 gcc_unreachable ();
2212}
2213
2214/* Like internal_error, but no backtrace will be printed. Used when
2215 the internal error does not happen at the current location, but happened
2216 somewhere else. */
2217void
2218internal_error_no_backtrace (const char *gmsgid, ...)
2219{
2220 auto_diagnostic_group d;
2221 va_list ap;
2222 va_start (ap, gmsgid);
2223 rich_location richloc (line_table, input_location);
2224 diagnostic_impl (richloc: &richloc, NULL, opt: -1, gmsgid, ap: &ap, kind: DK_ICE_NOBT);
2225 va_end (ap);
2226
2227 gcc_unreachable ();
2228}
2229
2230/* Emit DIAGRAM to this context, respecting the output format. */
2231
2232void
2233diagnostic_context::emit_diagram (const diagnostic_diagram &diagram)
2234{
2235 if (m_diagrams.m_theme == nullptr)
2236 return;
2237
2238 gcc_assert (m_output_format);
2239 m_output_format->on_diagram (diagram);
2240}
2241
2242/* Special case error functions. Most are implemented in terms of the
2243 above, or should be. */
2244
2245/* Print a diagnostic MSGID on FILE. This is just fprintf, except it
2246 runs its second argument through gettext. */
2247void
2248fnotice (FILE *file, const char *cmsgid, ...)
2249{
2250 va_list ap;
2251
2252 va_start (ap, cmsgid);
2253 vfprintf (s: file, _(cmsgid), arg: ap);
2254 va_end (ap);
2255}
2256
2257/* Inform the user that an error occurred while trying to report some
2258 other error. This indicates catastrophic internal inconsistencies,
2259 so give up now. But do try to flush out the previous error.
2260 This mustn't use internal_error, that will cause infinite recursion. */
2261
2262void
2263diagnostic_context::error_recursion ()
2264{
2265 if (m_lock < 3)
2266 pp_newline_and_flush (this->printer);
2267
2268 fnotice (stderr,
2269 cmsgid: "internal compiler error: error reporting routines re-entered.\n");
2270
2271 /* Call diagnostic_action_after_output to get the "please submit a bug
2272 report" message. */
2273 diagnostic_action_after_output (context: this, diag_kind: DK_ICE);
2274
2275 /* Do not use gcc_unreachable here; that goes through internal_error
2276 and therefore would cause infinite recursion. */
2277 real_abort ();
2278}
2279
2280/* Report an internal compiler error in a friendly manner. This is
2281 the function that gets called upon use of abort() in the source
2282 code generally, thanks to a special macro. */
2283
2284void
2285fancy_abort (const char *file, int line, const char *function)
2286{
2287 /* If fancy_abort is called before the diagnostic subsystem is initialized,
2288 internal_error will crash internally in a way that prevents a
2289 useful message reaching the user.
2290 This can happen with libgccjit in the case of gcc_assert failures
2291 that occur outside of the libgccjit mutex that guards the rest of
2292 gcc's state, including global_dc (when global_dc may not be
2293 initialized yet, or might be in use by another thread).
2294 Handle such cases as gracefully as possible by falling back to a
2295 minimal abort handler that only relies on i18n. */
2296 if (global_dc->printer == NULL)
2297 {
2298 /* Print the error message. */
2299 fnotice (stderr, cmsgid: diagnostic_kind_text[DK_ICE]);
2300 fnotice (stderr, cmsgid: "in %s, at %s:%d", function, trim_filename (name: file), line);
2301 fputc (c: '\n', stderr);
2302
2303 /* Attempt to print a backtrace. */
2304 struct backtrace_state *state
2305 = backtrace_create_state (NULL, threaded: 0, error_callback: bt_err_callback, NULL);
2306 int count = 0;
2307 if (state != NULL)
2308 backtrace_full (state, skip: 2, callback: bt_callback, error_callback: bt_err_callback,
2309 data: (void *) &count);
2310
2311 /* We can't call warn_if_plugins or emergency_dump_function as these
2312 rely on GCC state that might not be initialized, or might be in
2313 use by another thread. */
2314
2315 /* Abort the process. */
2316 real_abort ();
2317 }
2318
2319 internal_error (gmsgid: "in %s, at %s:%d", function, trim_filename (name: file), line);
2320}
2321
2322/* class diagnostic_context. */
2323
2324void
2325diagnostic_context::begin_group ()
2326{
2327 m_diagnostic_groups.m_nesting_depth++;
2328}
2329
2330void
2331diagnostic_context::end_group ()
2332{
2333 if (--m_diagnostic_groups.m_nesting_depth == 0)
2334 {
2335 /* Handle the case where we've popped the final diagnostic group.
2336 If any diagnostics were emitted, give the context a chance
2337 to do something. */
2338 if (m_diagnostic_groups.m_emission_count > 0)
2339 m_output_format->on_end_group ();
2340 m_diagnostic_groups.m_emission_count = 0;
2341 }
2342}
2343
2344/* class auto_diagnostic_group. */
2345
2346/* Constructor: "push" this group into global_dc. */
2347
2348auto_diagnostic_group::auto_diagnostic_group ()
2349{
2350 global_dc->begin_group ();
2351}
2352
2353/* Destructor: "pop" this group from global_dc. */
2354
2355auto_diagnostic_group::~auto_diagnostic_group ()
2356{
2357 global_dc->end_group ();
2358}
2359
2360/* class diagnostic_text_output_format : public diagnostic_output_format. */
2361
2362diagnostic_text_output_format::~diagnostic_text_output_format ()
2363{
2364 /* Some of the errors may actually have been warnings. */
2365 if (m_context.diagnostic_count (kind: DK_WERROR))
2366 {
2367 /* -Werror was given. */
2368 if (m_context.warning_as_error_requested_p ())
2369 pp_verbatim (m_context.printer,
2370 _("%s: all warnings being treated as errors"),
2371 progname);
2372 /* At least one -Werror= was given. */
2373 else
2374 pp_verbatim (m_context.printer,
2375 _("%s: some warnings being treated as errors"),
2376 progname);
2377 pp_newline_and_flush (m_context.printer);
2378 }
2379}
2380
2381void
2382diagnostic_text_output_format::on_begin_diagnostic (diagnostic_info *diagnostic)
2383{
2384 (*diagnostic_starter (&m_context)) (&m_context, diagnostic);
2385}
2386
2387void
2388diagnostic_text_output_format::on_end_diagnostic (diagnostic_info *diagnostic,
2389 diagnostic_t orig_diag_kind)
2390{
2391 (*diagnostic_finalizer (&m_context)) (&m_context, diagnostic, orig_diag_kind);
2392}
2393
2394void
2395diagnostic_text_output_format::on_diagram (const diagnostic_diagram &diagram)
2396{
2397 char *saved_prefix = pp_take_prefix (m_context.printer);
2398 pp_set_prefix (m_context.printer, NULL);
2399 /* Use a newline before and after and a two-space indent
2400 to make the diagram stand out a little from the wall of text. */
2401 pp_newline (m_context.printer);
2402 diagram.get_canvas ().print_to_pp (pp: m_context.printer, per_line_prefix: " ");
2403 pp_newline (m_context.printer);
2404 pp_set_prefix (m_context.printer, saved_prefix);
2405 pp_flush (m_context.printer);
2406}
2407
2408/* Set the output format for CONTEXT to FORMAT, using BASE_FILE_NAME for
2409 file-based output formats. */
2410
2411void
2412diagnostic_output_format_init (diagnostic_context *context,
2413 const char *base_file_name,
2414 enum diagnostics_output_format format)
2415{
2416 switch (format)
2417 {
2418 default:
2419 gcc_unreachable ();
2420 case DIAGNOSTICS_OUTPUT_FORMAT_TEXT:
2421 /* The default; do nothing. */
2422 break;
2423
2424 case DIAGNOSTICS_OUTPUT_FORMAT_JSON_STDERR:
2425 diagnostic_output_format_init_json_stderr (context);
2426 break;
2427
2428 case DIAGNOSTICS_OUTPUT_FORMAT_JSON_FILE:
2429 diagnostic_output_format_init_json_file (context, base_file_name);
2430 break;
2431
2432 case DIAGNOSTICS_OUTPUT_FORMAT_SARIF_STDERR:
2433 diagnostic_output_format_init_sarif_stderr (context);
2434 break;
2435
2436 case DIAGNOSTICS_OUTPUT_FORMAT_SARIF_FILE:
2437 diagnostic_output_format_init_sarif_file (context, base_file_name);
2438 break;
2439 }
2440}
2441
2442/* Initialize this context's m_diagrams based on CHARSET.
2443 Specifically, make a text_art::theme object for m_diagrams.m_theme,
2444 (or NULL for "no diagrams"). */
2445
2446void
2447diagnostic_context::
2448set_text_art_charset (enum diagnostic_text_art_charset charset)
2449{
2450 delete m_diagrams.m_theme;
2451 switch (charset)
2452 {
2453 default:
2454 gcc_unreachable ();
2455
2456 case DIAGNOSTICS_TEXT_ART_CHARSET_NONE:
2457 m_diagrams.m_theme = nullptr;
2458 break;
2459
2460 case DIAGNOSTICS_TEXT_ART_CHARSET_ASCII:
2461 m_diagrams.m_theme = new text_art::ascii_theme ();
2462 break;
2463
2464 case DIAGNOSTICS_TEXT_ART_CHARSET_UNICODE:
2465 m_diagrams.m_theme = new text_art::unicode_theme ();
2466 break;
2467
2468 case DIAGNOSTICS_TEXT_ART_CHARSET_EMOJI:
2469 m_diagrams.m_theme = new text_art::emoji_theme ();
2470 break;
2471 }
2472}
2473
2474/* class simple_diagnostic_path : public diagnostic_path. */
2475
2476simple_diagnostic_path::simple_diagnostic_path (pretty_printer *event_pp)
2477 : m_event_pp (event_pp)
2478{
2479 add_thread (name: "main");
2480}
2481
2482/* Implementation of diagnostic_path::num_events vfunc for
2483 simple_diagnostic_path: simply get the number of events in the vec. */
2484
2485unsigned
2486simple_diagnostic_path::num_events () const
2487{
2488 return m_events.length ();
2489}
2490
2491/* Implementation of diagnostic_path::get_event vfunc for
2492 simple_diagnostic_path: simply return the event in the vec. */
2493
2494const diagnostic_event &
2495simple_diagnostic_path::get_event (int idx) const
2496{
2497 return *m_events[idx];
2498}
2499
2500unsigned
2501simple_diagnostic_path::num_threads () const
2502{
2503 return m_threads.length ();
2504}
2505
2506const diagnostic_thread &
2507simple_diagnostic_path::get_thread (diagnostic_thread_id_t idx) const
2508{
2509 return *m_threads[idx];
2510}
2511
2512diagnostic_thread_id_t
2513simple_diagnostic_path::add_thread (const char *name)
2514{
2515 m_threads.safe_push (obj: new simple_diagnostic_thread (name));
2516 return m_threads.length () - 1;
2517}
2518
2519/* Add an event to this path at LOC within function FNDECL at
2520 stack depth DEPTH.
2521
2522 Use m_context's printer to format FMT, as the text of the new
2523 event.
2524
2525 Return the id of the new event. */
2526
2527diagnostic_event_id_t
2528simple_diagnostic_path::add_event (location_t loc, tree fndecl, int depth,
2529 const char *fmt, ...)
2530{
2531 pretty_printer *pp = m_event_pp;
2532 pp_clear_output_area (pp);
2533
2534 rich_location rich_loc (line_table, UNKNOWN_LOCATION);
2535
2536 va_list ap;
2537
2538 va_start (ap, fmt);
2539
2540 text_info ti (_(fmt), &ap, 0, nullptr, &rich_loc);
2541 pp_format (pp, &ti);
2542 pp_output_formatted_text (pp);
2543
2544 va_end (ap);
2545
2546 simple_diagnostic_event *new_event
2547 = new simple_diagnostic_event (loc, fndecl, depth, pp_formatted_text (pp));
2548 m_events.safe_push (obj: new_event);
2549
2550 pp_clear_output_area (pp);
2551
2552 return diagnostic_event_id_t (m_events.length () - 1);
2553}
2554
2555diagnostic_event_id_t
2556simple_diagnostic_path::add_thread_event (diagnostic_thread_id_t thread_id,
2557 location_t loc,
2558 tree fndecl,
2559 int depth,
2560 const char *fmt, ...)
2561{
2562 pretty_printer *pp = m_event_pp;
2563 pp_clear_output_area (pp);
2564
2565 rich_location rich_loc (line_table, UNKNOWN_LOCATION);
2566
2567 va_list ap;
2568
2569 va_start (ap, fmt);
2570
2571 text_info ti (_(fmt), &ap, 0, nullptr, &rich_loc);
2572
2573 pp_format (pp, &ti);
2574 pp_output_formatted_text (pp);
2575
2576 va_end (ap);
2577
2578 simple_diagnostic_event *new_event
2579 = new simple_diagnostic_event (loc, fndecl, depth, pp_formatted_text (pp),
2580 thread_id);
2581 m_events.safe_push (obj: new_event);
2582
2583 pp_clear_output_area (pp);
2584
2585 return diagnostic_event_id_t (m_events.length () - 1);
2586}
2587
2588/* struct simple_diagnostic_event. */
2589
2590/* simple_diagnostic_event's ctor. */
2591
2592simple_diagnostic_event::
2593simple_diagnostic_event (location_t loc,
2594 tree fndecl,
2595 int depth,
2596 const char *desc,
2597 diagnostic_thread_id_t thread_id)
2598: m_loc (loc), m_fndecl (fndecl), m_depth (depth), m_desc (xstrdup (desc)),
2599 m_thread_id (thread_id)
2600{
2601}
2602
2603/* simple_diagnostic_event's dtor. */
2604
2605simple_diagnostic_event::~simple_diagnostic_event ()
2606{
2607 free (ptr: m_desc);
2608}
2609
2610/* Print PATH by emitting a dummy "note" associated with it. */
2611
2612DEBUG_FUNCTION
2613void debug (diagnostic_path *path)
2614{
2615 rich_location richloc (line_table, UNKNOWN_LOCATION);
2616 richloc.set_path (path);
2617 inform (richloc: &richloc, gmsgid: "debug path");
2618}
2619
2620/* Really call the system 'abort'. This has to go right at the end of
2621 this file, so that there are no functions after it that call abort
2622 and get the system abort instead of our macro. */
2623#undef abort
2624static void
2625real_abort (void)
2626{
2627 abort ();
2628}
2629
2630#if CHECKING_P
2631
2632namespace selftest {
2633
2634/* Helper function for test_print_escaped_string. */
2635
2636static void
2637assert_print_escaped_string (const location &loc, const char *expected_output,
2638 const char *input)
2639{
2640 pretty_printer pp;
2641 print_escaped_string (pp: &pp, text: input);
2642 ASSERT_STREQ_AT (loc, expected_output, pp_formatted_text (&pp));
2643}
2644
2645#define ASSERT_PRINT_ESCAPED_STRING_STREQ(EXPECTED_OUTPUT, INPUT) \
2646 assert_print_escaped_string (SELFTEST_LOCATION, EXPECTED_OUTPUT, INPUT)
2647
2648/* Tests of print_escaped_string. */
2649
2650static void
2651test_print_escaped_string ()
2652{
2653 /* Empty string. */
2654 ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"\"", "");
2655
2656 /* Non-empty string. */
2657 ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"hello world\"", "hello world");
2658
2659 /* Various things that need to be escaped: */
2660 /* Backslash. */
2661 ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"before\\\\after\"",
2662 "before\\after");
2663 /* Tab. */
2664 ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"before\\tafter\"",
2665 "before\tafter");
2666 /* Newline. */
2667 ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"before\\nafter\"",
2668 "before\nafter");
2669 /* Double quote. */
2670 ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"before\\\"after\"",
2671 "before\"after");
2672
2673 /* Non-printable characters: BEL: '\a': 0x07 */
2674 ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"before\\007after\"",
2675 "before\aafter");
2676 /* Non-printable characters: vertical tab: '\v': 0x0b */
2677 ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"before\\013after\"",
2678 "before\vafter");
2679}
2680
2681/* Tests of print_parseable_fixits. */
2682
2683/* Verify that print_parseable_fixits emits the empty string if there
2684 are no fixits. */
2685
2686static void
2687test_print_parseable_fixits_none ()
2688{
2689 pretty_printer pp;
2690 rich_location richloc (line_table, UNKNOWN_LOCATION);
2691
2692 print_parseable_fixits (pp: &pp, richloc: &richloc, column_unit: DIAGNOSTICS_COLUMN_UNIT_BYTE, tabstop: 8);
2693 ASSERT_STREQ ("", pp_formatted_text (&pp));
2694}
2695
2696/* Verify that print_parseable_fixits does the right thing if there
2697 is an insertion fixit hint. */
2698
2699static void
2700test_print_parseable_fixits_insert ()
2701{
2702 pretty_printer pp;
2703 rich_location richloc (line_table, UNKNOWN_LOCATION);
2704
2705 linemap_add (line_table, LC_ENTER, sysp: false, to_file: "test.c", to_line: 0);
2706 linemap_line_start (set: line_table, to_line: 5, max_column_hint: 100);
2707 linemap_add (line_table, LC_LEAVE, sysp: false, NULL, to_line: 0);
2708 location_t where = linemap_position_for_column (line_table, 10);
2709 richloc.add_fixit_insert_before (where, new_content: "added content");
2710
2711 print_parseable_fixits (pp: &pp, richloc: &richloc, column_unit: DIAGNOSTICS_COLUMN_UNIT_BYTE, tabstop: 8);
2712 ASSERT_STREQ ("fix-it:\"test.c\":{5:10-5:10}:\"added content\"\n",
2713 pp_formatted_text (&pp));
2714}
2715
2716/* Verify that print_parseable_fixits does the right thing if there
2717 is an removal fixit hint. */
2718
2719static void
2720test_print_parseable_fixits_remove ()
2721{
2722 pretty_printer pp;
2723 rich_location richloc (line_table, UNKNOWN_LOCATION);
2724
2725 linemap_add (line_table, LC_ENTER, sysp: false, to_file: "test.c", to_line: 0);
2726 linemap_line_start (set: line_table, to_line: 5, max_column_hint: 100);
2727 linemap_add (line_table, LC_LEAVE, sysp: false, NULL, to_line: 0);
2728 source_range where;
2729 where.m_start = linemap_position_for_column (line_table, 10);
2730 where.m_finish = linemap_position_for_column (line_table, 20);
2731 richloc.add_fixit_remove (src_range: where);
2732
2733 print_parseable_fixits (pp: &pp, richloc: &richloc, column_unit: DIAGNOSTICS_COLUMN_UNIT_BYTE, tabstop: 8);
2734 ASSERT_STREQ ("fix-it:\"test.c\":{5:10-5:21}:\"\"\n",
2735 pp_formatted_text (&pp));
2736}
2737
2738/* Verify that print_parseable_fixits does the right thing if there
2739 is an replacement fixit hint. */
2740
2741static void
2742test_print_parseable_fixits_replace ()
2743{
2744 pretty_printer pp;
2745 rich_location richloc (line_table, UNKNOWN_LOCATION);
2746
2747 linemap_add (line_table, LC_ENTER, sysp: false, to_file: "test.c", to_line: 0);
2748 linemap_line_start (set: line_table, to_line: 5, max_column_hint: 100);
2749 linemap_add (line_table, LC_LEAVE, sysp: false, NULL, to_line: 0);
2750 source_range where;
2751 where.m_start = linemap_position_for_column (line_table, 10);
2752 where.m_finish = linemap_position_for_column (line_table, 20);
2753 richloc.add_fixit_replace (src_range: where, new_content: "replacement");
2754
2755 print_parseable_fixits (pp: &pp, richloc: &richloc, column_unit: DIAGNOSTICS_COLUMN_UNIT_BYTE, tabstop: 8);
2756 ASSERT_STREQ ("fix-it:\"test.c\":{5:10-5:21}:\"replacement\"\n",
2757 pp_formatted_text (&pp));
2758}
2759
2760/* Verify that print_parseable_fixits correctly handles
2761 DIAGNOSTICS_COLUMN_UNIT_BYTE vs DIAGNOSTICS_COLUMN_UNIT_COLUMN. */
2762
2763static void
2764test_print_parseable_fixits_bytes_vs_display_columns ()
2765{
2766 line_table_test ltt;
2767 rich_location richloc (line_table, UNKNOWN_LOCATION);
2768
2769 /* 1-based byte offsets: 12345677778888999900001234567. */
2770 const char *const content = "smile \xf0\x9f\x98\x82 colour\n";
2771 /* 1-based display cols: 123456[......7-8.....]9012345. */
2772 const int tabstop = 8;
2773
2774 temp_source_file tmp (SELFTEST_LOCATION, ".c", content);
2775 const char *const fname = tmp.get_filename ();
2776
2777 linemap_add (line_table, LC_ENTER, sysp: false, to_file: fname, to_line: 0);
2778 linemap_line_start (set: line_table, to_line: 1, max_column_hint: 100);
2779 linemap_add (line_table, LC_LEAVE, sysp: false, NULL, to_line: 0);
2780 source_range where;
2781 where.m_start = linemap_position_for_column (line_table, 12);
2782 where.m_finish = linemap_position_for_column (line_table, 17);
2783 richloc.add_fixit_replace (src_range: where, new_content: "color");
2784
2785 /* Escape fname. */
2786 pretty_printer tmp_pp;
2787 print_escaped_string (pp: &tmp_pp, text: fname);
2788 char *escaped_fname = xstrdup (pp_formatted_text (&tmp_pp));
2789
2790 const int buf_len = strlen (s: escaped_fname) + 100;
2791 char *const expected = XNEWVEC (char, buf_len);
2792
2793 {
2794 pretty_printer pp;
2795 print_parseable_fixits (pp: &pp, richloc: &richloc, column_unit: DIAGNOSTICS_COLUMN_UNIT_BYTE,
2796 tabstop);
2797 snprintf (s: expected, maxlen: buf_len,
2798 format: "fix-it:%s:{1:12-1:18}:\"color\"\n", escaped_fname);
2799 ASSERT_STREQ (expected, pp_formatted_text (&pp));
2800 }
2801 {
2802 pretty_printer pp;
2803 print_parseable_fixits (pp: &pp, richloc: &richloc, column_unit: DIAGNOSTICS_COLUMN_UNIT_DISPLAY,
2804 tabstop);
2805 snprintf (s: expected, maxlen: buf_len,
2806 format: "fix-it:%s:{1:10-1:16}:\"color\"\n", escaped_fname);
2807 ASSERT_STREQ (expected, pp_formatted_text (&pp));
2808 }
2809
2810 XDELETEVEC (expected);
2811 free (ptr: escaped_fname);
2812}
2813
2814/* Verify that
2815 diagnostic_get_location_text (..., SHOW_COLUMN)
2816 generates EXPECTED_LOC_TEXT, given FILENAME, LINE, COLUMN, with
2817 colorization disabled. */
2818
2819static void
2820assert_location_text (const char *expected_loc_text,
2821 const char *filename, int line, int column,
2822 bool show_column,
2823 int origin = 1,
2824 enum diagnostics_column_unit column_unit
2825 = DIAGNOSTICS_COLUMN_UNIT_BYTE)
2826{
2827 test_diagnostic_context dc;
2828 dc.m_show_column = show_column;
2829 dc.m_column_unit = column_unit;
2830 dc.m_column_origin = origin;
2831
2832 expanded_location xloc;
2833 xloc.file = filename;
2834 xloc.line = line;
2835 xloc.column = column;
2836 xloc.data = NULL;
2837 xloc.sysp = false;
2838
2839 char *actual_loc_text = diagnostic_get_location_text (context: &dc, s: xloc);
2840 ASSERT_STREQ (expected_loc_text, actual_loc_text);
2841 free (ptr: actual_loc_text);
2842}
2843
2844/* Verify that diagnostic_get_location_text works as expected. */
2845
2846static void
2847test_diagnostic_get_location_text ()
2848{
2849 const char *old_progname = progname;
2850 progname = "PROGNAME";
2851 assert_location_text (expected_loc_text: "PROGNAME:", NULL, line: 0, column: 0, show_column: true);
2852 char *built_in_colon = concat (special_fname_builtin (), ":", (char *) 0);
2853 assert_location_text (expected_loc_text: built_in_colon, filename: special_fname_builtin (),
2854 line: 42, column: 10, show_column: true);
2855 free (ptr: built_in_colon);
2856 assert_location_text (expected_loc_text: "foo.c:42:10:", filename: "foo.c", line: 42, column: 10, show_column: true);
2857 assert_location_text (expected_loc_text: "foo.c:42:9:", filename: "foo.c", line: 42, column: 10, show_column: true, origin: 0);
2858 assert_location_text (expected_loc_text: "foo.c:42:1010:", filename: "foo.c", line: 42, column: 10, show_column: true, origin: 1001);
2859 for (int origin = 0; origin != 2; ++origin)
2860 assert_location_text (expected_loc_text: "foo.c:42:", filename: "foo.c", line: 42, column: 0, show_column: true, origin);
2861 assert_location_text (expected_loc_text: "foo.c:", filename: "foo.c", line: 0, column: 10, show_column: true);
2862 assert_location_text (expected_loc_text: "foo.c:42:", filename: "foo.c", line: 42, column: 10, show_column: false);
2863 assert_location_text (expected_loc_text: "foo.c:", filename: "foo.c", line: 0, column: 10, show_column: false);
2864
2865 maybe_line_and_column (INT_MAX, INT_MAX);
2866 maybe_line_and_column (INT_MIN, INT_MIN);
2867
2868 {
2869 /* In order to test display columns vs byte columns, we need to create a
2870 file for location_get_source_line() to read. */
2871
2872 const char *const content = "smile \xf0\x9f\x98\x82\n";
2873 const int line_bytes = strlen (s: content) - 1;
2874 const int def_tabstop = 8;
2875 const cpp_char_column_policy policy (def_tabstop, cpp_wcwidth);
2876 const int display_width = cpp_display_width (data: content, data_length: line_bytes, policy);
2877 ASSERT_EQ (line_bytes - 2, display_width);
2878 temp_source_file tmp (SELFTEST_LOCATION, ".c", content);
2879 const char *const fname = tmp.get_filename ();
2880 const int buf_len = strlen (s: fname) + 16;
2881 char *const expected = XNEWVEC (char, buf_len);
2882
2883 snprintf (s: expected, maxlen: buf_len, format: "%s:1:%d:", fname, line_bytes);
2884 assert_location_text (expected_loc_text: expected, filename: fname, line: 1, column: line_bytes, show_column: true,
2885 origin: 1, column_unit: DIAGNOSTICS_COLUMN_UNIT_BYTE);
2886
2887 snprintf (s: expected, maxlen: buf_len, format: "%s:1:%d:", fname, line_bytes - 1);
2888 assert_location_text (expected_loc_text: expected, filename: fname, line: 1, column: line_bytes, show_column: true,
2889 origin: 0, column_unit: DIAGNOSTICS_COLUMN_UNIT_BYTE);
2890
2891 snprintf (s: expected, maxlen: buf_len, format: "%s:1:%d:", fname, display_width);
2892 assert_location_text (expected_loc_text: expected, filename: fname, line: 1, column: line_bytes, show_column: true,
2893 origin: 1, column_unit: DIAGNOSTICS_COLUMN_UNIT_DISPLAY);
2894
2895 snprintf (s: expected, maxlen: buf_len, format: "%s:1:%d:", fname, display_width - 1);
2896 assert_location_text (expected_loc_text: expected, filename: fname, line: 1, column: line_bytes, show_column: true,
2897 origin: 0, column_unit: DIAGNOSTICS_COLUMN_UNIT_DISPLAY);
2898
2899 XDELETEVEC (expected);
2900 }
2901
2902
2903 progname = old_progname;
2904}
2905
2906/* Selftest for num_digits. */
2907
2908static void
2909test_num_digits ()
2910{
2911 ASSERT_EQ (1, num_digits (0));
2912 ASSERT_EQ (1, num_digits (9));
2913 ASSERT_EQ (2, num_digits (10));
2914 ASSERT_EQ (2, num_digits (99));
2915 ASSERT_EQ (3, num_digits (100));
2916 ASSERT_EQ (3, num_digits (999));
2917 ASSERT_EQ (4, num_digits (1000));
2918 ASSERT_EQ (4, num_digits (9999));
2919 ASSERT_EQ (5, num_digits (10000));
2920 ASSERT_EQ (5, num_digits (99999));
2921 ASSERT_EQ (6, num_digits (100000));
2922 ASSERT_EQ (6, num_digits (999999));
2923 ASSERT_EQ (7, num_digits (1000000));
2924 ASSERT_EQ (7, num_digits (9999999));
2925 ASSERT_EQ (8, num_digits (10000000));
2926 ASSERT_EQ (8, num_digits (99999999));
2927}
2928
2929/* Run all of the selftests within this file. */
2930
2931void
2932c_diagnostic_cc_tests ()
2933{
2934 test_print_escaped_string ();
2935 test_print_parseable_fixits_none ();
2936 test_print_parseable_fixits_insert ();
2937 test_print_parseable_fixits_remove ();
2938 test_print_parseable_fixits_replace ();
2939 test_print_parseable_fixits_bytes_vs_display_columns ();
2940 test_diagnostic_get_location_text ();
2941 test_num_digits ();
2942
2943}
2944
2945} // namespace selftest
2946
2947#endif /* #if CHECKING_P */
2948
2949#if __GNUC__ >= 10
2950# pragma GCC diagnostic pop
2951#endif
2952

source code of gcc/diagnostic.cc