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>
5 This file is part of GCC.
7 GCC is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 3, or (at your option) any later
12 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>. */
22 /* This file implements the language independent aspect of diagnostic
26 #define INCLUDE_VECTOR
28 #include "coretypes.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"
42 #include "selftest-diagnostic.h"
45 #include "text-art/theme.h"
46 #include "pretty-print-urlifier.h"
52 #ifdef GWINSZ_IN_SYS_IOCTL
53 # include <sys/ioctl.h>
56 /* Disable warnings about quoting issues in the pp_xxx calls below
57 that (intentionally) don't follow GCC diagnostic conventions. */
59 # pragma GCC diagnostic push
60 # pragma GCC diagnostic ignored "-Wformat-diag"
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)
69 static bool diagnostic_impl (rich_location
*, const diagnostic_metadata
*,
71 va_list *, diagnostic_t
) ATTRIBUTE_GCC_DIAG(4,0);
72 static 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);
77 static void real_abort (void) ATTRIBUTE_NORETURN
;
79 /* Name of program invoked, sans directories. */
83 /* A diagnostic_context surrogate for stderr. */
84 static diagnostic_context global_diagnostic_context
;
85 diagnostic_context
*global_dc
= &global_diagnostic_context
;
87 /* Return a malloc'd string containing MSG formatted a la printf. The
88 caller is responsible for freeing the memory. */
90 build_message_string (const char *msg
, ...)
96 str
= xvasprintf (msg
, ap
);
102 /* Same as diagnostic_build_prefix, but only the source FILE is given. */
104 file_name_as_prefix (diagnostic_context
*context
, const char *f
)
107 = colorize_start (pp_show_color (context
->printer
), "locus");
108 const char *locus_ce
= colorize_stop (pp_show_color (context
->printer
));
109 return build_message_string ("%s%s:%s ", locus_cs
, f
, locus_ce
);
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. */
118 get_terminal_width (void)
120 const char * s
= getenv ("COLUMNS");
130 if (ioctl (0, TIOCGWINSZ
, &w
) == 0 && w
.ws_col
> 0)
137 /* Set caret_max_width to value. */
139 diagnostic_set_caret_max_width (diagnostic_context
*context
, int value
)
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
);
149 context
->m_source_printing
.max_width
= value
;
153 diagnostic_option_classifier::init (int 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;
164 diagnostic_option_classifier::fini ()
166 XDELETEVEC (m_classify_diagnostic
);
167 m_classify_diagnostic
= nullptr;
172 /* Save all diagnostic classifications in a stack. */
175 diagnostic_option_classifier::push ()
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
;
181 /* Restore the topmost classification set off the stack. If the stack
182 is empty, revert to the state based on command line parameters. */
185 diagnostic_option_classifier::pop (location_t where
)
190 jump_to
= m_push_list
[-- m_n_push
];
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
++;
204 /* Initialize the diagnostic message outputting machinery. */
207 diagnostic_context::initialize (int n_opts
)
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 ();
214 m_file_cache
= nullptr;
215 memset (m_diagnostic_count
, 0, sizeof m_diagnostic_count
);
216 m_warning_as_error_requested
= false;
218 m_option_classifier
.init (n_opts
);
219 m_source_printing
.enabled
= false;
220 diagnostic_set_caret_max_width (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
] = '^';
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;
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;
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 ("GCC_EXTRA_DIAGNOSTIC_OUTPUT"))
260 if (!strcmp (var
, "fixits-v1"))
261 m_extra_output_kind
= EXTRA_DIAGNOSTIC_OUTPUT_fixits_v1
;
262 else if (!strcmp (var
, "fixits-v2"))
263 m_extra_output_kind
= EXTRA_DIAGNOSTIC_OUTPUT_fixits_v2
;
264 /* Silently ignore unrecognized values. */
266 m_column_unit
= DIAGNOSTICS_COLUMN_UNIT_DISPLAY
;
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;
280 enum diagnostic_text_art_charset text_art_charset
281 = DIAGNOSTICS_TEXT_ART_CHARSET_EMOJI
;
282 if (const char *lang
= getenv ("LANG"))
284 /* For LANG=C, don't assume the terminal supports anything
286 if (!strcmp (lang
, "C"))
287 text_art_charset
= DIAGNOSTICS_TEXT_ART_CHARSET_ASCII
;
289 set_text_art_charset (text_art_charset
);
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. */
297 diagnostic_context::color_init (int value
)
299 /* value == -1 is the default value. */
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)
309 if (!getenv ("GCC_COLORS"))
311 value
= DIAGNOSTICS_COLOR_AUTO
;
314 value
= DIAGNOSTICS_COLOR_DEFAULT
;
316 pp_show_color (this->printer
)
317 = colorize_init ((diagnostic_color_rule_t
) value
);
320 /* Initialize URL support within this context based on VALUE,
324 diagnostic_context::urls_init (int value
)
326 /* value == -1 is the default value. */
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)
336 if (!getenv ("GCC_URLS") && !getenv ("TERM_URLS"))
338 value
= DIAGNOSTICS_URL_AUTO
;
341 value
= DIAGNOSTICS_URLS_DEFAULT
;
344 this->printer
->url_format
345 = determine_url_format ((diagnostic_url_rule_t
) value
);
348 /* Create the file_cache, if not already created, and tell it how to
349 translate files on input. */
352 initialize_input_context (diagnostic_input_charset_callback ccb
,
353 bool should_skip_bom
)
356 m_file_cache
= new file_cache
;
357 m_file_cache
->initialize_input_context (ccb
, should_skip_bom
);
360 /* Do any cleaning up required after the last diagnostic is emitted. */
363 diagnostic_context::finish ()
365 delete m_output_format
;
366 m_output_format
= nullptr;
368 if (m_diagrams
.m_theme
)
370 delete m_diagrams
.m_theme
;
371 m_diagrams
.m_theme
= nullptr;
375 m_file_cache
= nullptr;
377 m_option_classifier
.fini ();
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;
385 if (m_edit_context_ptr
)
387 delete m_edit_context_ptr
;
388 m_edit_context_ptr
= nullptr;
393 delete m_includes_seen
;
394 m_includes_seen
= nullptr;
397 if (m_client_data_hooks
)
399 delete m_client_data_hooks
;
400 m_client_data_hooks
= nullptr;
404 m_urlifier
= nullptr;
408 diagnostic_context::set_output_format (diagnostic_output_format
*output_format
)
410 /* Ideally we'd use a std::unique_ptr here. */
411 delete m_output_format
;
412 m_output_format
= output_format
;
416 diagnostic_context::set_client_data_hooks (diagnostic_client_data_hooks
*hooks
)
418 /* Ideally we'd use a std::unique_ptr here. */
419 delete m_client_data_hooks
;
420 m_client_data_hooks
= hooks
;
424 diagnostic_context::set_urlifier (urlifier
*urlifier
)
426 /* Ideally we'd use a std::unique_ptr here. */
428 m_urlifier
= urlifier
;
432 diagnostic_context::create_edit_context ()
434 delete m_edit_context_ptr
;
435 m_edit_context_ptr
= new edit_context ();
438 /* Initialize DIAGNOSTIC, where the message MSG has already been
441 diagnostic_set_info_translated (diagnostic_info
*diagnostic
, const char *msg
,
442 va_list *args
, rich_location
*richloc
,
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;
456 /* Initialize DIAGNOSTIC, where the message GMSGID has not yet been
459 diagnostic_set_info (diagnostic_info
*diagnostic
, const char *gmsgid
,
460 va_list *args
, rich_location
*richloc
,
463 gcc_assert (richloc
);
464 diagnostic_set_info_translated (diagnostic
, _(gmsgid
), args
, richloc
, kind
);
467 static const char *const diagnostic_kind_color
[] = {
468 #define DEFINE_DIAGNOSTIC_KIND(K, T, C) (C),
469 #include "diagnostic.def"
470 #undef DEFINE_DIAGNOSTIC_KIND
474 /* Get a color name for diagnostics of type KIND
475 Result could be NULL. */
478 diagnostic_get_color_for_kind (diagnostic_t kind
)
480 return diagnostic_kind_color
[kind
];
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). */
488 convert_column_unit (enum diagnostics_column_unit column_unit
,
500 case DIAGNOSTICS_COLUMN_UNIT_DISPLAY
:
502 cpp_char_column_policy
policy (tabstop
, cpp_wcwidth
);
503 return location_compute_display_column (s
, policy
);
506 case DIAGNOSTICS_COLUMN_UNIT_BYTE
:
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
515 diagnostic_context::converted_column (expanded_location s
) const
517 int one_based_col
= convert_column_unit (m_column_unit
, m_tabstop
, s
);
518 if (one_based_col
<= 0)
520 return one_based_col
+ (m_column_origin
- 1);
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. */
529 maybe_line_and_column (int line
, int col
)
531 static char result
[32];
536 = snprintf (result
, sizeof (result
),
537 col
>= 0 ? ":%d:%d" : ":%d", line
, col
);
538 gcc_checking_assert (l
< sizeof (result
));
545 /* Return a malloc'd string describing a location e.g. "foo.c:42:10".
546 The caller is responsible for freeing the memory. */
549 diagnostic_get_location_text (diagnostic_context
*context
,
552 pretty_printer
*pp
= context
->printer
;
553 const char *locus_cs
= colorize_start (pp_show_color (pp
), "locus");
554 const char *locus_ce
= colorize_stop (pp_show_color (pp
));
555 const char *file
= s
.file
? s
.file
: progname
;
558 if (strcmp (file
, special_fname_builtin ()))
561 if (context
->m_show_column
)
562 col
= context
->converted_column (s
);
565 const char *line_col
= maybe_line_and_column (line
, col
);
566 return build_message_string ("%s%s%s:%s", locus_cs
, file
,
570 static const char *const diagnostic_kind_text
[] = {
571 #define DEFINE_DIAGNOSTIC_KIND(K, T, C) (T),
572 #include "diagnostic.def"
573 #undef DEFINE_DIAGNOSTIC_KIND
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. */
581 diagnostic_build_prefix (diagnostic_context
*context
,
582 const diagnostic_info
*diagnostic
)
584 gcc_assert (diagnostic
->kind
< DK_LAST_DIAGNOSTIC_KIND
);
586 const char *text
= _(diagnostic_kind_text
[diagnostic
->kind
]);
587 const char *text_cs
= "", *text_ce
= "";
588 pretty_printer
*pp
= context
->printer
;
590 if (diagnostic_kind_color
[diagnostic
->kind
])
592 text_cs
= colorize_start (pp_show_color (pp
),
593 diagnostic_kind_color
[diagnostic
->kind
]);
594 text_ce
= colorize_stop (pp_show_color (pp
));
597 expanded_location s
= diagnostic_expand_location (diagnostic
);
598 char *location_text
= diagnostic_get_location_text (context
, s
);
600 char *result
= build_message_string ("%s %s%s%s", location_text
,
601 text_cs
, text
, text_ce
);
602 free (location_text
);
606 /* Functions at which to stop the backtrace print. It's not
607 particularly helpful to print the callers of these functions. */
609 static const char * const bt_stop
[] =
617 /* A callback function passed to the backtrace_full function. */
620 bt_callback (void *data
, uintptr_t pc
, const char *filename
, int lineno
,
621 const char *function
)
623 int *pcount
= (int *) data
;
625 /* If we don't have any useful information, don't print
627 if (filename
== NULL
&& function
== NULL
)
630 /* Skip functions in diagnostic.cc. */
633 && strcmp (lbasename (filename
), "diagnostic.cc") == 0)
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. */
640 /* Returning a non-zero value stops the backtrace. */
646 if (function
!= NULL
)
648 char *str
= cplus_demangle_v3 (function
,
649 (DMGL_VERBOSE
| DMGL_ANSI
650 | DMGL_GNU_V3
| DMGL_PARAMS
));
657 for (size_t i
= 0; i
< ARRAY_SIZE (bt_stop
); ++i
)
659 size_t len
= strlen (bt_stop
[i
]);
660 if (strncmp (function
, bt_stop
[i
], len
) == 0
661 && (function
[len
] == '\0' || function
[len
] == '('))
665 /* Returning a non-zero value stops the backtrace. */
671 fprintf (stderr
, "0x%lx %s\n\t%s:%d\n",
673 function
== NULL
? "???" : function
,
674 filename
== NULL
? "???" : filename
,
683 /* A callback function passed to the backtrace_full function. This is
684 called if backtrace_full has an error. */
687 bt_err_callback (void *data ATTRIBUTE_UNUSED
, const char *msg
, int errnum
)
691 /* This means that no debug info was available. Just quietly
692 skip printing backtrace info. */
695 fprintf (stderr
, "%s%s%s\n", msg
, errnum
== 0 ? "" : ": ",
696 errnum
== 0 ? "" : xstrerror (errnum
));
699 /* Check if we've met the maximum error limit, and if so fatally exit
701 FLUSH indicates whether a diagnostic_context::finish call is needed. */
704 diagnostic_context::check_max_errors (bool flush
)
709 int count
= (m_diagnostic_count
[DK_ERROR
]
710 + m_diagnostic_count
[DK_SORRY
]
711 + m_diagnostic_count
[DK_WERROR
]);
713 if (count
>= m_max_errors
)
716 "compilation terminated due to -fmax-errors=%u.\n",
720 exit (FATAL_EXIT_CODE
);
724 /* Take any action which is expected to happen after the diagnostic
725 is written out. This function does not always return. */
727 diagnostic_context::action_after_output (diagnostic_t diag_kind
)
739 if (m_abort_on_error
)
743 fnotice (stderr
, "compilation terminated due to -Wfatal-errors.\n");
745 exit (FATAL_EXIT_CODE
);
752 /* Optional callback for attempting to handle ICEs gracefully. */
753 if (void (*ice_handler_cb
) (diagnostic_context
*) = m_ice_handler_cb
)
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);
760 /* The context might have had diagnostic_finish called on
763 struct backtrace_state
*state
= NULL
;
764 if (diag_kind
== DK_ICE
)
765 state
= backtrace_create_state (NULL
, 0, bt_err_callback
, NULL
);
768 backtrace_full (state
, 2, bt_callback
, bt_err_callback
,
771 if (m_abort_on_error
)
775 fnotice (stderr
, "Please submit a full bug report, "
776 "with preprocessed source.\n");
778 fnotice (stderr
, "Please submit a full bug report, "
779 "with preprocessed source (by using -freport-bug).\n");
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
);
786 exit (ICE_EXIT_CODE
);
790 if (m_abort_on_error
)
793 fnotice (stderr
, "compilation terminated.\n");
794 exit (FATAL_EXIT_CODE
);
801 /* Only dump the "In file included from..." stack once for each file. */
804 diagnostic_context::includes_seen_p (const line_map_ordinary
*map
)
806 /* No include path for main. */
807 if (MAIN_FILE_P (map
))
810 /* Always identify C++ modules, at least for now. */
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 (line_table
, map
);
815 if (MAP_MODULE_P (probe
))
818 if (!m_includes_seen
)
819 m_includes_seen
= new hash_set
<location_t
, false, location_hash
>;
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 (linemap_included_from (map
));
827 diagnostic_context::report_current_module (location_t where
)
829 const line_map_ordinary
*map
= NULL
;
831 if (pp_needs_newline (this->printer
))
833 pp_newline (this->printer
);
834 pp_needs_newline (this->printer
) = false;
837 if (where
<= BUILTINS_LOCATION
)
840 linemap_resolve_location (line_table
, where
,
841 LRK_MACRO_DEFINITION_LOCATION
,
844 if (map
&& m_last_module
!= map
)
847 if (!includes_seen_p (map
))
849 bool first
= true, need_inc
= true, was_module
= MAP_MODULE_P (map
);
850 expanded_location s
= {};
853 where
= linemap_included_from (map
);
854 map
= linemap_included_from_linemap (line_table
, map
);
855 bool is_module
= MAP_MODULE_P (map
);
856 s
.file
= LINEMAP_FILE (map
);
857 s
.line
= SOURCE_LINE (map
, where
);
859 if (first
&& m_show_column
)
861 s
.column
= SOURCE_COLUMN (map
, where
);
862 col
= converted_column (s
);
864 const char *line_col
= maybe_line_and_column (s
.line
, col
);
865 static const char *const msgs
[] =
869 N_("In file included from"), /* 2 */
870 N_(" included from"),
871 N_("In module"), /* 4 */
873 N_("In module imported at"), /* 6 */
877 unsigned index
= (was_module
? 6 : is_module
? 4
878 : need_inc
? 2 : 0) + !first
;
880 pp_verbatim (this->printer
, "%s%s %r%s%s%R",
881 first
? "" : was_module
? ", " : ",\n",
883 "locus", s
.file
, line_col
);
884 first
= false, need_inc
= was_module
, was_module
= is_module
;
886 while (!includes_seen_p (map
));
887 pp_verbatim (this->printer
, ":");
888 pp_newline (this->printer
);
893 /* If DIAGNOSTIC has a diagnostic_path and this context supports
894 printing paths, print the path. */
897 diagnostic_context::show_any_path (const diagnostic_info
&diagnostic
)
899 const diagnostic_path
*path
= diagnostic
.richloc
->get_path ();
904 m_print_path (this, path
);
907 /* class diagnostic_event. */
909 /* struct diagnostic_event::meaning. */
912 diagnostic_event::meaning::dump_to_pp (pretty_printer
*pp
) const
914 bool need_comma
= false;
915 pp_character (pp
, '{');
916 if (const char *verb_str
= maybe_get_verb_str (m_verb
))
918 pp_printf (pp
, "verb: %qs", verb_str
);
921 if (const char *noun_str
= maybe_get_noun_str (m_noun
))
924 pp_string (pp
, ", ");
925 pp_printf (pp
, "noun: %qs", noun_str
);
928 if (const char *property_str
= maybe_get_property_str (m_property
))
931 pp_string (pp
, ", ");
932 pp_printf (pp
, "property: %qs", property_str
);
935 pp_character (pp
, '}');
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). */
942 diagnostic_event::meaning::maybe_get_verb_str (enum verb v
)
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). */
973 diagnostic_event::meaning::maybe_get_noun_str (enum noun n
)
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). */
1000 diagnostic_event::meaning::maybe_get_property_str (enum property p
)
1006 case PROPERTY_unknown
:
1010 case PROPERTY_false
:
1015 /* class diagnostic_path. */
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. */
1024 diagnostic_path::get_first_event_in_a_function (unsigned *out_idx
) const
1026 const unsigned num
= num_events ();
1027 for (unsigned i
= 0; i
< num
; i
++)
1029 if (!(get_event (i
).get_fndecl () == NULL
1030 && get_event (i
).get_stack_depth () == 0))
1039 /* Return true if the events in this path involve more than one
1040 function, or false if it is purely intraprocedural. */
1043 diagnostic_path::interprocedural_p () const
1045 /* Ignore leading events that are outside of any function. */
1046 unsigned first_fn_event_idx
;
1047 if (!get_first_event_in_a_function (&first_fn_event_idx
))
1050 const diagnostic_event
&first_fn_event
= get_event (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 ();
1054 const unsigned num
= num_events ();
1055 for (unsigned i
= first_fn_event_idx
+ 1; i
< num
; i
++)
1057 if (get_event (i
).get_fndecl () != first_fndecl
)
1059 if (get_event (i
).get_stack_depth () != first_fn_stack_depth
)
1066 default_diagnostic_starter (diagnostic_context
*context
,
1067 diagnostic_info
*diagnostic
)
1069 diagnostic_report_current_module (context
, diagnostic_location (diagnostic
));
1070 pp_set_prefix (context
->printer
, diagnostic_build_prefix (context
,
1075 default_diagnostic_start_span_fn (diagnostic_context
*context
,
1076 expanded_location exploc
)
1078 char *text
= diagnostic_get_location_text (context
, exploc
);
1079 pp_string (context
->printer
, text
);
1081 pp_newline (context
->printer
);
1085 default_diagnostic_finalizer (diagnostic_context
*context
,
1086 diagnostic_info
*diagnostic
,
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
, diagnostic
->richloc
, diagnostic
->kind
);
1093 pp_set_prefix (context
->printer
, saved_prefix
);
1094 pp_flush (context
->printer
);
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
1102 diagnostic_option_classifier::
1103 classify_diagnostic (const diagnostic_context
*context
,
1105 diagnostic_t new_kind
,
1108 diagnostic_t old_kind
;
1110 if (option_index
< 0
1111 || option_index
>= m_n_opts
1112 || new_kind
>= DK_LAST_DIAGNOSTIC_KIND
)
1113 return DK_UNSPECIFIED
;
1115 old_kind
= m_classify_diagnostic
[option_index
];
1117 /* Handle pragmas separately, since we need to keep track of *where*
1118 the pragmas were. */
1119 if (where
!= UNKNOWN_LOCATION
)
1123 /* Record the command-line status, so we can reset it back on DK_POP. */
1124 if (old_kind
== DK_UNSPECIFIED
)
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
;
1134 for (i
= m_n_classification_history
- 1; i
>= 0; i
--)
1135 if (m_classification_history
[i
].option
== option_index
)
1137 old_kind
= m_classification_history
[i
].kind
;
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
++;
1151 m_classify_diagnostic
[option_index
] = new_kind
;
1156 /* Helper function for print_parseable_fixits. Print TEXT to PP, obeying the
1157 escaping rules for -fdiagnostics-parseable-fixits. */
1160 print_escaped_string (pretty_printer
*pp
, const char *text
)
1165 pp_character (pp
, '"');
1166 for (const char *ch
= text
; *ch
; ch
++)
1171 /* Escape backslash as two backslashes. */
1172 pp_string (pp
, "\\\\");
1175 /* Escape tab as "\t". */
1176 pp_string (pp
, "\\t");
1179 /* Escape newline as "\n". */
1180 pp_string (pp
, "\\n");
1183 /* Escape doublequotes as \". */
1184 pp_string (pp
, "\\\"");
1188 pp_character (pp
, *ch
);
1190 /* Use octal for non-printable chars. */
1192 unsigned char c
= (*ch
& 0xff);
1193 pp_printf (pp
, "\\%o%o%o", (c
/ 64), (c
/ 8) & 007, c
& 007);
1198 pp_character (pp
, '"');
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. */
1208 print_parseable_fixits (pretty_printer
*pp
, rich_location
*richloc
,
1209 enum diagnostics_column_unit column_unit
,
1213 gcc_assert (richloc
);
1215 char *saved_prefix
= pp_take_prefix (pp
);
1216 pp_set_prefix (pp
, NULL
);
1218 for (unsigned i
= 0; i
< richloc
->get_num_fixit_hints (); i
++)
1220 const fixit_hint
*hint
= richloc
->get_fixit_hint (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
, 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
);
1229 = convert_column_unit (column_unit
, tabstop
, start_exploc
);
1231 = convert_column_unit (column_unit
, tabstop
, 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
, hint
->get_string ());
1239 pp_set_prefix (pp
, saved_prefix
);
1242 /* Update the inlining info in this context for a DIAGNOSTIC. */
1245 diagnostic_context::get_any_inlining_info (diagnostic_info
*diagnostic
)
1247 auto &ilocs
= diagnostic
->m_iinfo
.m_ilocs
;
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
);
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 (loc
);
1260 diagnostic
->m_iinfo
.m_allsyslocs
= in_system_header_at (loc
);
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.
1269 Return the new kind of DIAGNOSTIC if it was updated, or DK_UNSPECIFIED
1273 diagnostic_option_classifier::
1274 update_effective_level_from_pragmas (diagnostic_info
*diagnostic
) const
1276 if (m_n_classification_history
<= 0)
1277 return DK_UNSPECIFIED
;
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
)
1285 /* FIXME: Stupid search. Optimize later. */
1286 for (int i
= m_n_classification_history
- 1; i
>= 0; i
--)
1288 const diagnostic_classification_change_t
&hist
1289 = m_classification_history
[i
];
1291 location_t pragloc
= hist
.location
;
1292 if (!linemap_location_before_p (line_table
, pragloc
, loc
))
1295 if (hist
.kind
== (int) DK_POP
)
1297 /* Move on to the next region. */
1302 int option
= hist
.option
;
1303 /* The option 0 is for all the diagnostics. */
1304 if (option
== 0 || option
== diagnostic
->option_index
)
1306 diagnostic_t kind
= hist
.kind
;
1307 if (kind
!= DK_UNSPECIFIED
)
1308 diagnostic
->kind
= kind
;
1314 return DK_UNSPECIFIED
;
1317 /* Generate a URL string describing CWE. The caller is responsible for
1318 freeing the string. */
1321 get_cwe_url (int cwe
)
1323 return xasprintf ("https://cwe.mitre.org/data/definitions/%i.html", cwe
);
1326 /* If DIAGNOSTIC has a CWE identifier, print it.
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. */
1333 diagnostic_context::print_any_cwe (const diagnostic_info
&diagnostic
)
1335 if (diagnostic
.metadata
== NULL
)
1338 int cwe
= diagnostic
.metadata
->get_cwe ();
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 diagnostic_kind_color
[diagnostic
.kind
]));
1346 if (pp
->url_format
!= URL_FORMAT_NONE
)
1348 char *cwe_url
= get_cwe_url (cwe
);
1349 pp_begin_url (pp
, cwe_url
);
1352 pp_printf (pp
, "CWE-%i", cwe
);
1353 pp_set_prefix (pp
, saved_prefix
);
1354 if (pp
->url_format
!= URL_FORMAT_NONE
)
1356 pp_string (pp
, colorize_stop (pp_show_color (pp
)));
1357 pp_character (pp
, ']');
1361 /* If DIAGNOSTIC has any rules associated with it, print them.
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. */
1368 diagnostic_context::print_any_rules (const diagnostic_info
&diagnostic
)
1370 if (diagnostic
.metadata
== NULL
)
1373 for (unsigned idx
= 0; idx
< diagnostic
.metadata
->get_num_rules (); idx
++)
1375 const diagnostic_metadata::rule
&rule
1376 = diagnostic
.metadata
->get_rule (idx
);
1377 if (char *desc
= rule
.make_description ())
1379 pretty_printer
* const pp
= this->printer
;
1380 char *saved_prefix
= pp_take_prefix (pp
);
1381 pp_string (pp
, " [");
1383 colorize_start (pp_show_color (pp
),
1384 diagnostic_kind_color
[diagnostic
.kind
]));
1386 if (pp
->url_format
!= URL_FORMAT_NONE
)
1388 url
= rule
.make_url ();
1390 pp_begin_url (pp
, url
);
1392 pp_string (pp
, desc
);
1393 pp_set_prefix (pp
, saved_prefix
);
1394 if (pp
->url_format
!= URL_FORMAT_NONE
)
1398 pp_string (pp
, colorize_stop (pp_show_color (pp
)));
1399 pp_character (pp
, ']');
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. */
1410 diagnostic_context::print_option_information (const diagnostic_info
&diagnostic
,
1411 diagnostic_t orig_diag_kind
)
1415 option_text
= m_option_name (this, diagnostic
.option_index
,
1416 orig_diag_kind
, diagnostic
.kind
);
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 diagnostic_kind_color
[diagnostic
.kind
]));
1430 pp_begin_url (pp
, option_url
);
1431 pp_string (pp
, option_text
);
1437 pp_string (pp
, colorize_stop (pp_show_color (pp
)));
1438 pp_character (pp
, ']');
1443 /* Returns whether a DIAGNOSTIC should be printed, and adjusts diagnostic->kind
1444 as appropriate for #pragma GCC diagnostic and -Werror=foo. */
1447 diagnostic_context::diagnostic_enabled (diagnostic_info
*diagnostic
)
1449 /* Update the inlining stack for this diagnostic. */
1450 get_any_inlining_info (diagnostic
);
1452 /* Diagnostics with no option or -fpermissive are always enabled. */
1453 if (!diagnostic
->option_index
1454 || diagnostic
->option_index
== permissive_error_option (this))
1457 /* This tests if the user provided the appropriate -Wfoo or
1459 if (! m_option_enabled (diagnostic
->option_index
,
1464 /* This tests for #pragma diagnostic changes. */
1465 diagnostic_t diag_class
1466 = m_option_classifier
.update_effective_level_from_pragmas (diagnostic
);
1468 /* This tests if the user provided the appropriate -Werror=foo
1470 if (diag_class
== DK_UNSPECIFIED
1471 && !option_unspecified_p (diagnostic
->option_index
))
1472 diagnostic
->kind
= m_option_classifier
.get_current_override (diagnostic
->option_index
);
1474 /* This allows for future extensions, like temporarily disabling
1475 warnings for ranges of source code. */
1476 if (diagnostic
->kind
== DK_IGNORED
)
1482 /* Returns whether warning OPT is enabled at LOC. */
1485 diagnostic_context::warning_enabled_at (location_t loc
, int opt
)
1487 if (!diagnostic_report_warnings_p (this, loc
))
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
);
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. */
1506 diagnostic_context::report_diagnostic (diagnostic_info
*diagnostic
)
1508 diagnostic_t orig_diag_kind
= diagnostic
->kind
;
1510 gcc_assert (m_output_format
);
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
)
1519 if (diagnostic
->kind
== DK_PEDWARN
)
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
;
1526 if (diagnostic
->kind
== DK_NOTE
&& m_inhibit_notes_p
)
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
)
1536 pp_newline_and_flush (this->printer
);
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
1545 if (m_warning_as_error_requested
1546 && diagnostic
->kind
== DK_WARNING
)
1547 diagnostic
->kind
= DK_ERROR
;
1549 diagnostic
->message
.m_data
= &diagnostic
->x_data
;
1551 /* Check to see if the diagnostic is enabled at the location and
1552 not disabled by #pragma GCC diagnostic anywhere along the inlining
1554 if (!diagnostic_enabled (diagnostic
))
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. */
1565 if (diagnostic
->kind
!= DK_NOTE
&& diagnostic
->kind
!= DK_ICE
)
1566 diagnostic_check_max_errors (this);
1570 if (diagnostic
->kind
== DK_ICE
|| diagnostic
->kind
== DK_ICE_NOBT
)
1572 /* When not checking, ICEs are converted to fatal errors when an
1573 error has already occurred. This is counteracted by
1576 && (m_diagnostic_count
[DK_ERROR
] > 0
1577 || m_diagnostic_count
[DK_SORRY
] > 0)
1578 && !m_abort_on_error
)
1581 = expand_location (diagnostic_location (diagnostic
));
1582 fnotice (stderr
, "%s:%d: confused by earlier errors, bailing out\n",
1584 exit (ICE_EXIT_CODE
);
1586 if (m_internal_error
)
1587 (*m_internal_error
) (this,
1588 diagnostic
->message
.m_format_spec
,
1589 diagnostic
->message
.m_args_ptr
);
1591 if (diagnostic
->kind
== DK_ERROR
&& orig_diag_kind
== DK_WARNING
)
1592 ++m_diagnostic_count
[DK_WERROR
];
1594 ++m_diagnostic_count
[diagnostic
->kind
];
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
++;
1601 pp_format (this->printer
, &diagnostic
->message
, m_urlifier
);
1602 m_output_format
->on_begin_diagnostic (diagnostic
);
1603 pp_output_formatted_text (this->printer
);
1605 print_any_cwe (*diagnostic
);
1607 print_any_rules (*diagnostic
);
1608 if (m_show_option_requested
)
1609 print_option_information (*diagnostic
, orig_diag_kind
);
1610 m_output_format
->on_end_diagnostic (diagnostic
, orig_diag_kind
);
1611 switch (m_extra_output_kind
)
1615 case EXTRA_DIAGNOSTIC_OUTPUT_fixits_v1
:
1616 print_parseable_fixits (this->printer
, diagnostic
->richloc
,
1617 DIAGNOSTICS_COLUMN_UNIT_BYTE
,
1619 pp_flush (this->printer
);
1621 case EXTRA_DIAGNOSTIC_OUTPUT_fixits_v2
:
1622 print_parseable_fixits (this->printer
, diagnostic
->richloc
,
1623 DIAGNOSTICS_COLUMN_UNIT_DISPLAY
,
1625 pp_flush (this->printer
);
1628 diagnostic_action_after_output (this, diagnostic
->kind
);
1629 diagnostic
->x_data
= NULL
;
1631 if (m_edit_context_ptr
)
1632 if (diagnostic
->richloc
->fixits_can_be_auto_applied_p ())
1633 m_edit_context_ptr
->add_fixits (diagnostic
->richloc
);
1637 show_any_path (*diagnostic
);
1642 /* Get the number of digits in the decimal representation of VALUE. */
1645 num_digits (int value
)
1647 /* Perhaps simpler to use log10 for this, but doing it this way avoids
1648 using floating point. */
1649 gcc_assert (value
>= 0);
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'. */
1669 trim_filename (const char *name
)
1671 static const char this_file
[] = __FILE__
;
1672 const char *p
= name
, *q
= this_file
;
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]))
1679 while (q
[0] == '.' && q
[1] == '.' && IS_DIR_SEPARATOR (q
[2]))
1682 /* Now skip any parts the two filenames have in common. */
1683 while (*p
== *q
&& *p
!= 0 && *q
!= 0)
1686 /* Now go backwards until the previous directory separator. */
1687 while (p
> name
&& !IS_DIR_SEPARATOR (p
[-1]))
1693 /* Standard error reporting routines in increasing order of severity.
1694 All of these take arguments like printf. */
1696 /* Text to be emitted verbatim to the error message stream; this
1697 produces no prefix and disables line-wrapping. Use rarely. */
1699 verbatim (const char *gmsgid
, ...)
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
);
1710 /* Add a note with text GMSGID and with LOCATION to the diagnostic CONTEXT. */
1712 diagnostic_append_note (diagnostic_context
*context
,
1713 location_t location
,
1714 const char * gmsgid
, ...)
1716 diagnostic_info diagnostic
;
1718 rich_location
richloc (line_table
, location
);
1720 va_start (ap
, gmsgid
);
1721 diagnostic_set_info (&diagnostic
, gmsgid
, &ap
, &richloc
, DK_NOTE
);
1722 if (context
->m_inhibit_notes_p
)
1727 char *saved_prefix
= pp_take_prefix (context
->printer
);
1728 pp_set_prefix (context
->printer
,
1729 diagnostic_build_prefix (context
, &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
, DK_NOTE
);
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. */
1743 diagnostic_impl (rich_location
*richloc
, const diagnostic_metadata
*metadata
,
1744 int opt
, const char *gmsgid
,
1745 va_list *ap
, diagnostic_t kind
)
1747 diagnostic_info diagnostic
;
1748 if (kind
== DK_PERMERROR
)
1750 diagnostic_set_info (&diagnostic
, gmsgid
, ap
, richloc
,
1751 permissive_error_kind (global_dc
));
1752 diagnostic
.option_index
= (opt
!= -1 ? opt
1753 : permissive_error_option (global_dc
));
1757 diagnostic_set_info (&diagnostic
, gmsgid
, ap
, richloc
, kind
);
1758 if (kind
== DK_WARNING
|| kind
== DK_PEDWARN
)
1759 diagnostic
.option_index
= opt
;
1761 diagnostic
.metadata
= metadata
;
1762 return global_dc
->report_diagnostic (&diagnostic
);
1765 /* Implement inform_n, warning_n, and error_n, as documented and
1768 diagnostic_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
)
1774 diagnostic_info diagnostic
;
1777 if (sizeof n
<= sizeof gtn
)
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;
1785 const char *text
= ngettext (singular_gmsgid
, plural_gmsgid
, gtn
);
1786 diagnostic_set_info_translated (&diagnostic
, text
, ap
, richloc
, kind
);
1787 if (kind
== DK_WARNING
)
1788 diagnostic
.option_index
= opt
;
1789 diagnostic
.metadata
= metadata
;
1790 return global_dc
->report_diagnostic (&diagnostic
);
1793 /* Wrapper around diagnostic_impl taking a variable argument list. */
1796 emit_diagnostic (diagnostic_t kind
, location_t location
, int opt
,
1797 const char *gmsgid
, ...)
1799 auto_diagnostic_group d
;
1801 va_start (ap
, gmsgid
);
1802 rich_location
richloc (line_table
, location
);
1803 bool ret
= diagnostic_impl (&richloc
, NULL
, opt
, gmsgid
, &ap
, kind
);
1808 /* As above, but for rich_location *. */
1811 emit_diagnostic (diagnostic_t kind
, rich_location
*richloc
, int opt
,
1812 const char *gmsgid
, ...)
1814 auto_diagnostic_group d
;
1816 va_start (ap
, gmsgid
);
1817 bool ret
= diagnostic_impl (richloc
, NULL
, opt
, gmsgid
, &ap
, kind
);
1822 /* Wrapper around diagnostic_impl taking a va_list parameter. */
1825 emit_diagnostic_valist (diagnostic_t kind
, location_t location
, int opt
,
1826 const char *gmsgid
, va_list *ap
)
1828 rich_location
richloc (line_table
, location
);
1829 return diagnostic_impl (&richloc
, NULL
, opt
, gmsgid
, ap
, kind
);
1832 /* An informative note at LOCATION. Use this for additional details on an error
1835 inform (location_t location
, const char *gmsgid
, ...)
1837 auto_diagnostic_group d
;
1839 va_start (ap
, gmsgid
);
1840 rich_location
richloc (line_table
, location
);
1841 diagnostic_impl (&richloc
, NULL
, -1, gmsgid
, &ap
, DK_NOTE
);
1845 /* Same as "inform" above, but at RICHLOC. */
1847 inform (rich_location
*richloc
, const char *gmsgid
, ...)
1849 gcc_assert (richloc
);
1851 auto_diagnostic_group d
;
1853 va_start (ap
, gmsgid
);
1854 diagnostic_impl (richloc
, NULL
, -1, gmsgid
, &ap
, DK_NOTE
);
1858 /* An informative note at LOCATION. Use this for additional details on an
1861 inform_n (location_t location
, unsigned HOST_WIDE_INT n
,
1862 const char *singular_gmsgid
, const char *plural_gmsgid
, ...)
1865 va_start (ap
, plural_gmsgid
);
1866 auto_diagnostic_group d
;
1867 rich_location
richloc (line_table
, location
);
1868 diagnostic_n_impl (&richloc
, NULL
, -1, n
, singular_gmsgid
, plural_gmsgid
,
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. */
1877 warning (int opt
, const char *gmsgid
, ...)
1879 auto_diagnostic_group d
;
1881 va_start (ap
, gmsgid
);
1882 rich_location
richloc (line_table
, input_location
);
1883 bool ret
= diagnostic_impl (&richloc
, NULL
, opt
, gmsgid
, &ap
, DK_WARNING
);
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. */
1893 warning_at (location_t location
, int opt
, const char *gmsgid
, ...)
1895 auto_diagnostic_group d
;
1897 va_start (ap
, gmsgid
);
1898 rich_location
richloc (line_table
, location
);
1899 bool ret
= diagnostic_impl (&richloc
, NULL
, opt
, gmsgid
, &ap
, DK_WARNING
);
1904 /* Same as "warning at" above, but using RICHLOC. */
1907 warning_at (rich_location
*richloc
, int opt
, const char *gmsgid
, ...)
1909 gcc_assert (richloc
);
1911 auto_diagnostic_group d
;
1913 va_start (ap
, gmsgid
);
1914 bool ret
= diagnostic_impl (richloc
, NULL
, opt
, gmsgid
, &ap
, DK_WARNING
);
1919 /* Same as "warning at" above, but using METADATA. */
1922 warning_meta (rich_location
*richloc
,
1923 const diagnostic_metadata
&metadata
,
1924 int opt
, const char *gmsgid
, ...)
1926 gcc_assert (richloc
);
1928 auto_diagnostic_group d
;
1930 va_start (ap
, gmsgid
);
1932 = diagnostic_impl (richloc
, &metadata
, opt
, gmsgid
, &ap
,
1938 /* Same as warning_n plural variant below, but using RICHLOC. */
1941 warning_n (rich_location
*richloc
, int opt
, unsigned HOST_WIDE_INT n
,
1942 const char *singular_gmsgid
, const char *plural_gmsgid
, ...)
1944 gcc_assert (richloc
);
1946 auto_diagnostic_group d
;
1948 va_start (ap
, plural_gmsgid
);
1949 bool ret
= diagnostic_n_impl (richloc
, NULL
, opt
, n
,
1950 singular_gmsgid
, plural_gmsgid
,
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. */
1961 warning_n (location_t location
, int opt
, unsigned HOST_WIDE_INT n
,
1962 const char *singular_gmsgid
, const char *plural_gmsgid
, ...)
1964 auto_diagnostic_group d
;
1966 va_start (ap
, plural_gmsgid
);
1967 rich_location
richloc (line_table
, location
);
1968 bool ret
= diagnostic_n_impl (&richloc
, NULL
, opt
, n
,
1969 singular_gmsgid
, plural_gmsgid
,
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.
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,...)".
1986 Returns true if the warning was printed, false if it was inhibited. */
1989 pedwarn (location_t location
, int opt
, const char *gmsgid
, ...)
1991 auto_diagnostic_group d
;
1993 va_start (ap
, gmsgid
);
1994 rich_location
richloc (line_table
, location
);
1995 bool ret
= diagnostic_impl (&richloc
, NULL
, opt
, gmsgid
, &ap
, DK_PEDWARN
);
2000 /* Same as pedwarn above, but using RICHLOC. */
2003 pedwarn (rich_location
*richloc
, int opt
, const char *gmsgid
, ...)
2005 gcc_assert (richloc
);
2007 auto_diagnostic_group d
;
2009 va_start (ap
, gmsgid
);
2010 bool ret
= diagnostic_impl (richloc
, NULL
, opt
, gmsgid
, &ap
, DK_PEDWARN
);
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.
2020 Returns true if the warning was printed, false if it was inhibited. */
2023 permerror (location_t location
, const char *gmsgid
, ...)
2025 auto_diagnostic_group d
;
2027 va_start (ap
, gmsgid
);
2028 rich_location
richloc (line_table
, location
);
2029 bool ret
= diagnostic_impl (&richloc
, NULL
, -1, gmsgid
, &ap
, DK_PERMERROR
);
2034 /* Same as "permerror" above, but at RICHLOC. */
2037 permerror (rich_location
*richloc
, const char *gmsgid
, ...)
2039 gcc_assert (richloc
);
2041 auto_diagnostic_group d
;
2043 va_start (ap
, gmsgid
);
2044 bool ret
= diagnostic_impl (richloc
, NULL
, -1, gmsgid
, &ap
, DK_PERMERROR
);
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. */
2054 permerror_opt (location_t location
, int opt
, const char *gmsgid
, ...)
2056 auto_diagnostic_group d
;
2058 va_start (ap
, gmsgid
);
2059 rich_location
richloc (line_table
, location
);
2060 bool ret
= diagnostic_impl (&richloc
, NULL
, opt
, gmsgid
, &ap
, DK_PERMERROR
);
2065 /* Same as "permerror" above, but at RICHLOC. */
2068 permerror_opt (rich_location
*richloc
, int opt
, const char *gmsgid
, ...)
2070 gcc_assert (richloc
);
2072 auto_diagnostic_group d
;
2074 va_start (ap
, gmsgid
);
2075 bool ret
= diagnostic_impl (richloc
, NULL
, opt
, gmsgid
, &ap
, DK_PERMERROR
);
2080 /* A hard error: the code is definitely ill-formed, and an object file
2081 will not be produced. */
2083 error (const char *gmsgid
, ...)
2085 auto_diagnostic_group d
;
2087 va_start (ap
, gmsgid
);
2088 rich_location
richloc (line_table
, input_location
);
2089 diagnostic_impl (&richloc
, NULL
, -1, gmsgid
, &ap
, DK_ERROR
);
2093 /* A hard error: the code is definitely ill-formed, and an object file
2094 will not be produced. */
2096 error_n (location_t location
, unsigned HOST_WIDE_INT n
,
2097 const char *singular_gmsgid
, const char *plural_gmsgid
, ...)
2099 auto_diagnostic_group d
;
2101 va_start (ap
, plural_gmsgid
);
2102 rich_location
richloc (line_table
, location
);
2103 diagnostic_n_impl (&richloc
, NULL
, -1, n
, singular_gmsgid
, plural_gmsgid
,
2108 /* Same as above, but use location LOC instead of input_location. */
2110 error_at (location_t loc
, const char *gmsgid
, ...)
2112 auto_diagnostic_group d
;
2114 va_start (ap
, gmsgid
);
2115 rich_location
richloc (line_table
, loc
);
2116 diagnostic_impl (&richloc
, NULL
, -1, gmsgid
, &ap
, DK_ERROR
);
2120 /* Same as above, but use RICH_LOC. */
2123 error_at (rich_location
*richloc
, const char *gmsgid
, ...)
2125 gcc_assert (richloc
);
2127 auto_diagnostic_group d
;
2129 va_start (ap
, gmsgid
);
2130 diagnostic_impl (richloc
, NULL
, -1, gmsgid
, &ap
, DK_ERROR
);
2134 /* Same as above, but with metadata. */
2137 error_meta (rich_location
*richloc
, const diagnostic_metadata
&metadata
,
2138 const char *gmsgid
, ...)
2140 gcc_assert (richloc
);
2142 auto_diagnostic_group d
;
2144 va_start (ap
, gmsgid
);
2145 diagnostic_impl (richloc
, &metadata
, -1, gmsgid
, &ap
, DK_ERROR
);
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. */
2153 sorry (const char *gmsgid
, ...)
2155 auto_diagnostic_group d
;
2157 va_start (ap
, gmsgid
);
2158 rich_location
richloc (line_table
, input_location
);
2159 diagnostic_impl (&richloc
, NULL
, -1, gmsgid
, &ap
, DK_SORRY
);
2163 /* Same as above, but use location LOC instead of input_location. */
2165 sorry_at (location_t loc
, const char *gmsgid
, ...)
2167 auto_diagnostic_group d
;
2169 va_start (ap
, gmsgid
);
2170 rich_location
richloc (line_table
, loc
);
2171 diagnostic_impl (&richloc
, NULL
, -1, gmsgid
, &ap
, DK_SORRY
);
2175 /* Return true if an error or a "sorry" has been seen. Various
2176 processing is disabled after errors. */
2180 return errorcount
|| sorrycount
;
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. */
2187 fatal_error (location_t loc
, const char *gmsgid
, ...)
2189 auto_diagnostic_group d
;
2191 va_start (ap
, gmsgid
);
2192 rich_location
richloc (line_table
, loc
);
2193 diagnostic_impl (&richloc
, NULL
, -1, gmsgid
, &ap
, DK_FATAL
);
2199 /* An internal consistency check has failed. We make no attempt to
2202 internal_error (const char *gmsgid
, ...)
2204 auto_diagnostic_group d
;
2206 va_start (ap
, gmsgid
);
2207 rich_location
richloc (line_table
, input_location
);
2208 diagnostic_impl (&richloc
, NULL
, -1, gmsgid
, &ap
, DK_ICE
);
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
2218 internal_error_no_backtrace (const char *gmsgid
, ...)
2220 auto_diagnostic_group d
;
2222 va_start (ap
, gmsgid
);
2223 rich_location
richloc (line_table
, input_location
);
2224 diagnostic_impl (&richloc
, NULL
, -1, gmsgid
, &ap
, DK_ICE_NOBT
);
2230 /* Emit DIAGRAM to this context, respecting the output format. */
2233 diagnostic_context::emit_diagram (const diagnostic_diagram
&diagram
)
2235 if (m_diagrams
.m_theme
== nullptr)
2238 gcc_assert (m_output_format
);
2239 m_output_format
->on_diagram (diagram
);
2242 /* Special case error functions. Most are implemented in terms of the
2243 above, or should be. */
2245 /* Print a diagnostic MSGID on FILE. This is just fprintf, except it
2246 runs its second argument through gettext. */
2248 fnotice (FILE *file
, const char *cmsgid
, ...)
2252 va_start (ap
, cmsgid
);
2253 vfprintf (file
, _(cmsgid
), ap
);
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. */
2263 diagnostic_context::error_recursion ()
2266 pp_newline_and_flush (this->printer
);
2269 "internal compiler error: error reporting routines re-entered.\n");
2271 /* Call diagnostic_action_after_output to get the "please submit a bug
2273 diagnostic_action_after_output (this, DK_ICE
);
2275 /* Do not use gcc_unreachable here; that goes through internal_error
2276 and therefore would cause infinite recursion. */
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. */
2285 fancy_abort (const char *file
, int line
, const char *function
)
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
)
2298 /* Print the error message. */
2299 fnotice (stderr
, diagnostic_kind_text
[DK_ICE
]);
2300 fnotice (stderr
, "in %s, at %s:%d", function
, trim_filename (file
), line
);
2301 fputc ('\n', stderr
);
2303 /* Attempt to print a backtrace. */
2304 struct backtrace_state
*state
2305 = backtrace_create_state (NULL
, 0, bt_err_callback
, NULL
);
2308 backtrace_full (state
, 2, bt_callback
, bt_err_callback
,
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. */
2315 /* Abort the process. */
2319 internal_error ("in %s, at %s:%d", function
, trim_filename (file
), line
);
2322 /* class diagnostic_context. */
2325 diagnostic_context::begin_group ()
2327 m_diagnostic_groups
.m_nesting_depth
++;
2331 diagnostic_context::end_group ()
2333 if (--m_diagnostic_groups
.m_nesting_depth
== 0)
2335 /* Handle the case where we've popped the final diagnostic group.
2336 If any diagnostics were emitted, give the context a chance
2338 if (m_diagnostic_groups
.m_emission_count
> 0)
2339 m_output_format
->on_end_group ();
2340 m_diagnostic_groups
.m_emission_count
= 0;
2344 /* class auto_diagnostic_group. */
2346 /* Constructor: "push" this group into global_dc. */
2348 auto_diagnostic_group::auto_diagnostic_group ()
2350 global_dc
->begin_group ();
2353 /* Destructor: "pop" this group from global_dc. */
2355 auto_diagnostic_group::~auto_diagnostic_group ()
2357 global_dc
->end_group ();
2360 /* class diagnostic_text_output_format : public diagnostic_output_format. */
2362 diagnostic_text_output_format::~diagnostic_text_output_format ()
2364 /* Some of the errors may actually have been warnings. */
2365 if (m_context
.diagnostic_count (DK_WERROR
))
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"),
2372 /* At least one -Werror= was given. */
2374 pp_verbatim (m_context
.printer
,
2375 _("%s: some warnings being treated as errors"),
2377 pp_newline_and_flush (m_context
.printer
);
2382 diagnostic_text_output_format::on_begin_diagnostic (diagnostic_info
*diagnostic
)
2384 (*diagnostic_starter (&m_context
)) (&m_context
, diagnostic
);
2388 diagnostic_text_output_format::on_end_diagnostic (diagnostic_info
*diagnostic
,
2389 diagnostic_t orig_diag_kind
)
2391 (*diagnostic_finalizer (&m_context
)) (&m_context
, diagnostic
, orig_diag_kind
);
2395 diagnostic_text_output_format::on_diagram (const diagnostic_diagram
&diagram
)
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 (m_context
.printer
, " ");
2403 pp_newline (m_context
.printer
);
2404 pp_set_prefix (m_context
.printer
, saved_prefix
);
2405 pp_flush (m_context
.printer
);
2408 /* Set the output format for CONTEXT to FORMAT, using BASE_FILE_NAME for
2409 file-based output formats. */
2412 diagnostic_output_format_init (diagnostic_context
*context
,
2413 const char *base_file_name
,
2414 enum diagnostics_output_format format
)
2420 case DIAGNOSTICS_OUTPUT_FORMAT_TEXT
:
2421 /* The default; do nothing. */
2424 case DIAGNOSTICS_OUTPUT_FORMAT_JSON_STDERR
:
2425 diagnostic_output_format_init_json_stderr (context
);
2428 case DIAGNOSTICS_OUTPUT_FORMAT_JSON_FILE
:
2429 diagnostic_output_format_init_json_file (context
, base_file_name
);
2432 case DIAGNOSTICS_OUTPUT_FORMAT_SARIF_STDERR
:
2433 diagnostic_output_format_init_sarif_stderr (context
);
2436 case DIAGNOSTICS_OUTPUT_FORMAT_SARIF_FILE
:
2437 diagnostic_output_format_init_sarif_file (context
, base_file_name
);
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"). */
2447 diagnostic_context::
2448 set_text_art_charset (enum diagnostic_text_art_charset charset
)
2450 delete m_diagrams
.m_theme
;
2456 case DIAGNOSTICS_TEXT_ART_CHARSET_NONE
:
2457 m_diagrams
.m_theme
= nullptr;
2460 case DIAGNOSTICS_TEXT_ART_CHARSET_ASCII
:
2461 m_diagrams
.m_theme
= new text_art::ascii_theme ();
2464 case DIAGNOSTICS_TEXT_ART_CHARSET_UNICODE
:
2465 m_diagrams
.m_theme
= new text_art::unicode_theme ();
2468 case DIAGNOSTICS_TEXT_ART_CHARSET_EMOJI
:
2469 m_diagrams
.m_theme
= new text_art::emoji_theme ();
2474 /* class simple_diagnostic_path : public diagnostic_path. */
2476 simple_diagnostic_path::simple_diagnostic_path (pretty_printer
*event_pp
)
2477 : m_event_pp (event_pp
)
2479 add_thread ("main");
2482 /* Implementation of diagnostic_path::num_events vfunc for
2483 simple_diagnostic_path: simply get the number of events in the vec. */
2486 simple_diagnostic_path::num_events () const
2488 return m_events
.length ();
2491 /* Implementation of diagnostic_path::get_event vfunc for
2492 simple_diagnostic_path: simply return the event in the vec. */
2494 const diagnostic_event
&
2495 simple_diagnostic_path::get_event (int idx
) const
2497 return *m_events
[idx
];
2501 simple_diagnostic_path::num_threads () const
2503 return m_threads
.length ();
2506 const diagnostic_thread
&
2507 simple_diagnostic_path::get_thread (diagnostic_thread_id_t idx
) const
2509 return *m_threads
[idx
];
2512 diagnostic_thread_id_t
2513 simple_diagnostic_path::add_thread (const char *name
)
2515 m_threads
.safe_push (new simple_diagnostic_thread (name
));
2516 return m_threads
.length () - 1;
2519 /* Add an event to this path at LOC within function FNDECL at
2522 Use m_context's printer to format FMT, as the text of the new
2525 Return the id of the new event. */
2527 diagnostic_event_id_t
2528 simple_diagnostic_path::add_event (location_t loc
, tree fndecl
, int depth
,
2529 const char *fmt
, ...)
2531 pretty_printer
*pp
= m_event_pp
;
2532 pp_clear_output_area (pp
);
2534 rich_location
rich_loc (line_table
, UNKNOWN_LOCATION
);
2540 text_info
ti (_(fmt
), &ap
, 0, nullptr, &rich_loc
);
2541 pp_format (pp
, &ti
);
2542 pp_output_formatted_text (pp
);
2546 simple_diagnostic_event
*new_event
2547 = new simple_diagnostic_event (loc
, fndecl
, depth
, pp_formatted_text (pp
));
2548 m_events
.safe_push (new_event
);
2550 pp_clear_output_area (pp
);
2552 return diagnostic_event_id_t (m_events
.length () - 1);
2555 diagnostic_event_id_t
2556 simple_diagnostic_path::add_thread_event (diagnostic_thread_id_t thread_id
,
2560 const char *fmt
, ...)
2562 pretty_printer
*pp
= m_event_pp
;
2563 pp_clear_output_area (pp
);
2565 rich_location
rich_loc (line_table
, UNKNOWN_LOCATION
);
2571 text_info
ti (_(fmt
), &ap
, 0, nullptr, &rich_loc
);
2573 pp_format (pp
, &ti
);
2574 pp_output_formatted_text (pp
);
2578 simple_diagnostic_event
*new_event
2579 = new simple_diagnostic_event (loc
, fndecl
, depth
, pp_formatted_text (pp
),
2581 m_events
.safe_push (new_event
);
2583 pp_clear_output_area (pp
);
2585 return diagnostic_event_id_t (m_events
.length () - 1);
2588 /* struct simple_diagnostic_event. */
2590 /* simple_diagnostic_event's ctor. */
2592 simple_diagnostic_event::
2593 simple_diagnostic_event (location_t loc
,
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
)
2603 /* simple_diagnostic_event's dtor. */
2605 simple_diagnostic_event::~simple_diagnostic_event ()
2610 /* Print PATH by emitting a dummy "note" associated with it. */
2613 void debug (diagnostic_path
*path
)
2615 rich_location
richloc (line_table
, UNKNOWN_LOCATION
);
2616 richloc
.set_path (path
);
2617 inform (&richloc
, "debug path");
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. */
2632 namespace selftest
{
2634 /* Helper function for test_print_escaped_string. */
2637 assert_print_escaped_string (const location
&loc
, const char *expected_output
,
2641 print_escaped_string (&pp
, input
);
2642 ASSERT_STREQ_AT (loc
, expected_output
, pp_formatted_text (&pp
));
2645 #define ASSERT_PRINT_ESCAPED_STRING_STREQ(EXPECTED_OUTPUT, INPUT) \
2646 assert_print_escaped_string (SELFTEST_LOCATION, EXPECTED_OUTPUT, INPUT)
2648 /* Tests of print_escaped_string. */
2651 test_print_escaped_string ()
2654 ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"\"", "");
2656 /* Non-empty string. */
2657 ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"hello world\"", "hello world");
2659 /* Various things that need to be escaped: */
2661 ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"before\\\\after\"",
2664 ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"before\\tafter\"",
2667 ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"before\\nafter\"",
2670 ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"before\\\"after\"",
2673 /* Non-printable characters: BEL: '\a': 0x07 */
2674 ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"before\\007after\"",
2676 /* Non-printable characters: vertical tab: '\v': 0x0b */
2677 ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"before\\013after\"",
2681 /* Tests of print_parseable_fixits. */
2683 /* Verify that print_parseable_fixits emits the empty string if there
2687 test_print_parseable_fixits_none ()
2690 rich_location
richloc (line_table
, UNKNOWN_LOCATION
);
2692 print_parseable_fixits (&pp
, &richloc
, DIAGNOSTICS_COLUMN_UNIT_BYTE
, 8);
2693 ASSERT_STREQ ("", pp_formatted_text (&pp
));
2696 /* Verify that print_parseable_fixits does the right thing if there
2697 is an insertion fixit hint. */
2700 test_print_parseable_fixits_insert ()
2703 rich_location
richloc (line_table
, UNKNOWN_LOCATION
);
2705 linemap_add (line_table
, LC_ENTER
, false, "test.c", 0);
2706 linemap_line_start (line_table
, 5, 100);
2707 linemap_add (line_table
, LC_LEAVE
, false, NULL
, 0);
2708 location_t where
= linemap_position_for_column (line_table
, 10);
2709 richloc
.add_fixit_insert_before (where
, "added content");
2711 print_parseable_fixits (&pp
, &richloc
, DIAGNOSTICS_COLUMN_UNIT_BYTE
, 8);
2712 ASSERT_STREQ ("fix-it:\"test.c\":{5:10-5:10}:\"added content\"\n",
2713 pp_formatted_text (&pp
));
2716 /* Verify that print_parseable_fixits does the right thing if there
2717 is an removal fixit hint. */
2720 test_print_parseable_fixits_remove ()
2723 rich_location
richloc (line_table
, UNKNOWN_LOCATION
);
2725 linemap_add (line_table
, LC_ENTER
, false, "test.c", 0);
2726 linemap_line_start (line_table
, 5, 100);
2727 linemap_add (line_table
, LC_LEAVE
, false, NULL
, 0);
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 (where
);
2733 print_parseable_fixits (&pp
, &richloc
, DIAGNOSTICS_COLUMN_UNIT_BYTE
, 8);
2734 ASSERT_STREQ ("fix-it:\"test.c\":{5:10-5:21}:\"\"\n",
2735 pp_formatted_text (&pp
));
2738 /* Verify that print_parseable_fixits does the right thing if there
2739 is an replacement fixit hint. */
2742 test_print_parseable_fixits_replace ()
2745 rich_location
richloc (line_table
, UNKNOWN_LOCATION
);
2747 linemap_add (line_table
, LC_ENTER
, false, "test.c", 0);
2748 linemap_line_start (line_table
, 5, 100);
2749 linemap_add (line_table
, LC_LEAVE
, false, NULL
, 0);
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 (where
, "replacement");
2755 print_parseable_fixits (&pp
, &richloc
, DIAGNOSTICS_COLUMN_UNIT_BYTE
, 8);
2756 ASSERT_STREQ ("fix-it:\"test.c\":{5:10-5:21}:\"replacement\"\n",
2757 pp_formatted_text (&pp
));
2760 /* Verify that print_parseable_fixits correctly handles
2761 DIAGNOSTICS_COLUMN_UNIT_BYTE vs DIAGNOSTICS_COLUMN_UNIT_COLUMN. */
2764 test_print_parseable_fixits_bytes_vs_display_columns ()
2766 line_table_test ltt
;
2767 rich_location
richloc (line_table
, UNKNOWN_LOCATION
);
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;
2774 temp_source_file
tmp (SELFTEST_LOCATION
, ".c", content
);
2775 const char *const fname
= tmp
.get_filename ();
2777 linemap_add (line_table
, LC_ENTER
, false, fname
, 0);
2778 linemap_line_start (line_table
, 1, 100);
2779 linemap_add (line_table
, LC_LEAVE
, false, NULL
, 0);
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 (where
, "color");
2786 pretty_printer tmp_pp
;
2787 print_escaped_string (&tmp_pp
, fname
);
2788 char *escaped_fname
= xstrdup (pp_formatted_text (&tmp_pp
));
2790 const int buf_len
= strlen (escaped_fname
) + 100;
2791 char *const expected
= XNEWVEC (char, buf_len
);
2795 print_parseable_fixits (&pp
, &richloc
, DIAGNOSTICS_COLUMN_UNIT_BYTE
,
2797 snprintf (expected
, buf_len
,
2798 "fix-it:%s:{1:12-1:18}:\"color\"\n", escaped_fname
);
2799 ASSERT_STREQ (expected
, pp_formatted_text (&pp
));
2803 print_parseable_fixits (&pp
, &richloc
, DIAGNOSTICS_COLUMN_UNIT_DISPLAY
,
2805 snprintf (expected
, buf_len
,
2806 "fix-it:%s:{1:10-1:16}:\"color\"\n", escaped_fname
);
2807 ASSERT_STREQ (expected
, pp_formatted_text (&pp
));
2810 XDELETEVEC (expected
);
2811 free (escaped_fname
);
2815 diagnostic_get_location_text (..., SHOW_COLUMN)
2816 generates EXPECTED_LOC_TEXT, given FILENAME, LINE, COLUMN, with
2817 colorization disabled. */
2820 assert_location_text (const char *expected_loc_text
,
2821 const char *filename
, int line
, int column
,
2824 enum diagnostics_column_unit column_unit
2825 = DIAGNOSTICS_COLUMN_UNIT_BYTE
)
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
;
2832 expanded_location xloc
;
2833 xloc
.file
= filename
;
2835 xloc
.column
= column
;
2839 char *actual_loc_text
= diagnostic_get_location_text (&dc
, xloc
);
2840 ASSERT_STREQ (expected_loc_text
, actual_loc_text
);
2841 free (actual_loc_text
);
2844 /* Verify that diagnostic_get_location_text works as expected. */
2847 test_diagnostic_get_location_text ()
2849 const char *old_progname
= progname
;
2850 progname
= "PROGNAME";
2851 assert_location_text ("PROGNAME:", NULL
, 0, 0, true);
2852 char *built_in_colon
= concat (special_fname_builtin (), ":", (char *) 0);
2853 assert_location_text (built_in_colon
, special_fname_builtin (),
2855 free (built_in_colon
);
2856 assert_location_text ("foo.c:42:10:", "foo.c", 42, 10, true);
2857 assert_location_text ("foo.c:42:9:", "foo.c", 42, 10, true, 0);
2858 assert_location_text ("foo.c:42:1010:", "foo.c", 42, 10, true, 1001);
2859 for (int origin
= 0; origin
!= 2; ++origin
)
2860 assert_location_text ("foo.c:42:", "foo.c", 42, 0, true, origin
);
2861 assert_location_text ("foo.c:", "foo.c", 0, 10, true);
2862 assert_location_text ("foo.c:42:", "foo.c", 42, 10, false);
2863 assert_location_text ("foo.c:", "foo.c", 0, 10, false);
2865 maybe_line_and_column (INT_MAX
, INT_MAX
);
2866 maybe_line_and_column (INT_MIN
, INT_MIN
);
2869 /* In order to test display columns vs byte columns, we need to create a
2870 file for location_get_source_line() to read. */
2872 const char *const content
= "smile \xf0\x9f\x98\x82\n";
2873 const int line_bytes
= strlen (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 (content
, 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 (fname
) + 16;
2881 char *const expected
= XNEWVEC (char, buf_len
);
2883 snprintf (expected
, buf_len
, "%s:1:%d:", fname
, line_bytes
);
2884 assert_location_text (expected
, fname
, 1, line_bytes
, true,
2885 1, DIAGNOSTICS_COLUMN_UNIT_BYTE
);
2887 snprintf (expected
, buf_len
, "%s:1:%d:", fname
, line_bytes
- 1);
2888 assert_location_text (expected
, fname
, 1, line_bytes
, true,
2889 0, DIAGNOSTICS_COLUMN_UNIT_BYTE
);
2891 snprintf (expected
, buf_len
, "%s:1:%d:", fname
, display_width
);
2892 assert_location_text (expected
, fname
, 1, line_bytes
, true,
2893 1, DIAGNOSTICS_COLUMN_UNIT_DISPLAY
);
2895 snprintf (expected
, buf_len
, "%s:1:%d:", fname
, display_width
- 1);
2896 assert_location_text (expected
, fname
, 1, line_bytes
, true,
2897 0, DIAGNOSTICS_COLUMN_UNIT_DISPLAY
);
2899 XDELETEVEC (expected
);
2903 progname
= old_progname
;
2906 /* Selftest for num_digits. */
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));
2929 /* Run all of the selftests within this file. */
2932 c_diagnostic_cc_tests ()
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 ();
2945 } // namespace selftest
2947 #endif /* #if CHECKING_P */
2950 # pragma GCC diagnostic pop