LCOV - code coverage report
Current view: top level - gcc/diagnostics - context.cc (source / functions) Coverage Total Hit
Test: gcc.info Lines: 86.2 % 1061 915
Test Date: 2026-02-28 14:20:25 Functions: 87.6 % 97 85
Legend: Lines:     hit not hit

            Line data    Source code
       1              : /* Language-independent diagnostic subroutines for the GNU Compiler Collection
       2              :    Copyright (C) 1999-2026 Free Software Foundation, Inc.
       3              :    Contributed by Gabriel Dos Reis <gdr@codesourcery.com>
       4              : 
       5              : This file is part of GCC.
       6              : 
       7              : GCC is free software; you can redistribute it and/or modify it under
       8              : the terms of the GNU General Public License as published by the Free
       9              : Software Foundation; either version 3, or (at your option) any later
      10              : version.
      11              : 
      12              : GCC is distributed in the hope that it will be useful, but WITHOUT ANY
      13              : WARRANTY; without even the implied warranty of MERCHANTABILITY or
      14              : FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
      15              : for more details.
      16              : 
      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/>.  */
      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 "diagnostics/color.h"
      35              : #include "diagnostics/url.h"
      36              : #include "diagnostics/metadata.h"
      37              : #include "diagnostics/paths.h"
      38              : #include "diagnostics/client-data-hooks.h"
      39              : #include "diagnostics/diagram.h"
      40              : #include "diagnostics/sink.h"
      41              : #include "diagnostics/sarif-sink.h"
      42              : #include "diagnostics/text-sink.h"
      43              : #include "diagnostics/changes.h"
      44              : #include "selftest.h"
      45              : #include "diagnostics/selftest-context.h"
      46              : #include "opts.h"
      47              : #include "cpplib.h"
      48              : #include "text-art/theme.h"
      49              : #include "pretty-print-urlifier.h"
      50              : #include "diagnostics/logical-locations.h"
      51              : #include "diagnostics/buffering.h"
      52              : #include "diagnostics/file-cache.h"
      53              : #include "diagnostics/dumping.h"
      54              : #include "diagnostics/logging.h"
      55              : 
      56              : #ifdef HAVE_TERMIOS_H
      57              : # include <termios.h>
      58              : #endif
      59              : 
      60              : #ifdef GWINSZ_IN_SYS_IOCTL
      61              : # include <sys/ioctl.h>
      62              : #endif
      63              : 
      64              : /* Disable warnings about quoting issues in the pp_xxx calls below
      65              :    that (intentionally) don't follow GCC diagnostic conventions.  */
      66              : #if __GNUC__ >= 10
      67              : #  pragma GCC diagnostic push
      68              : #  pragma GCC diagnostic ignored "-Wformat-diag"
      69              : #endif
      70              : 
      71              : static void real_abort (void) ATTRIBUTE_NORETURN;
      72              : 
      73              : /* Name of program invoked, sans directories.  */
      74              : 
      75              : const char *progname;
      76              : 
      77              : 
      78              : /* Return a malloc'd string containing MSG formatted a la printf.  The
      79              :    caller is responsible for freeing the memory.  */
      80              : char *
      81      3188453 : build_message_string (const char *msg, ...)
      82              : {
      83      3188453 :   char *str;
      84      3188453 :   va_list ap;
      85              : 
      86      3188453 :   va_start (ap, msg);
      87      3188453 :   str = xvasprintf (msg, ap);
      88      3188453 :   va_end (ap);
      89              : 
      90      3188453 :   return str;
      91              : }
      92              : 
      93              : 
      94              : /* Return the value of the getenv("COLUMNS") as an integer. If the
      95              :    value is not set to a positive integer, use ioctl to get the
      96              :    terminal width. If it fails, return INT_MAX.  */
      97              : int
      98       763005 : get_terminal_width (void)
      99              : {
     100       763005 :   const char * s = getenv ("COLUMNS");
     101       763005 :   if (s != nullptr) {
     102          144 :     int n = atoi (s);
     103          144 :     if (n > 0)
     104              :       return n;
     105              :   }
     106              : 
     107              : #ifdef TIOCGWINSZ
     108       762861 :   struct winsize w;
     109       762861 :   w.ws_col = 0;
     110       762861 :   if (ioctl (0, TIOCGWINSZ, &w) == 0 && w.ws_col > 0)
     111            0 :     return w.ws_col;
     112              : #endif
     113              : 
     114              :   return INT_MAX;
     115              : }
     116              : 
     117              : namespace diagnostics {
     118              : 
     119              : /* Set caret_max_width to value.  */
     120              : 
     121              : void
     122       809534 : context::set_caret_max_width (int value)
     123              : {
     124              :   /* One minus to account for the leading empty space.  */
     125      1572469 :   value = value ? value - 1
     126       809534 :     : (isatty (fileno (pp_buffer (get_reference_printer ())->m_stream))
     127       809534 :        ? get_terminal_width () - 1 : INT_MAX);
     128              : 
     129       762935 :   if (value <= 0)
     130        46599 :     value = INT_MAX;
     131              : 
     132       809534 :   m_source_printing.max_width = value;
     133       809534 : }
     134              : 
     135              : /* Initialize the diagnostic message outputting machinery.  */
     136              : 
     137              : void
     138       705442 : context::initialize (int n_opts)
     139              : {
     140              :   /* Allocate a basic pretty-printer.  Clients will replace this a
     141              :      much more elaborated pretty-printer if they wish.  */
     142       705442 :   m_reference_printer = std::make_unique<pretty_printer> ().release ();
     143              : 
     144       705442 :   m_file_cache = new file_cache ();
     145       705442 :   m_diagnostic_counters.clear ();
     146       705442 :   m_warning_as_error_requested = false;
     147       705442 :   m_n_opts = n_opts;
     148       705442 :   m_option_classifier.init (n_opts);
     149       705442 :   m_source_printing.enabled = false;
     150       705442 :   set_caret_max_width (pp_line_cutoff (get_reference_printer ()));
     151      2821768 :   for (int i = 0; i < rich_location::STATICALLY_ALLOCATED_RANGES; i++)
     152      2116326 :     m_source_printing.caret_chars[i] = '^';
     153       705442 :   m_show_cwe = false;
     154       705442 :   m_show_rules = false;
     155       705442 :   m_path_format = DPF_NONE;
     156       705442 :   m_show_path_depths = false;
     157       705442 :   m_show_option_requested = false;
     158       705442 :   m_abort_on_error = false;
     159       705442 :   m_show_column = false;
     160       705442 :   m_pedantic_errors = false;
     161       705442 :   m_permissive = false;
     162       705442 :   m_opt_permissive = 0;
     163       705442 :   m_fatal_errors = false;
     164       705442 :   m_inhibit_warnings = false;
     165       705442 :   m_warn_system_headers = false;
     166       705442 :   m_max_errors = 0;
     167       705442 :   m_internal_error = nullptr;
     168       705442 :   m_adjust_diagnostic_info = nullptr;
     169       705442 :   m_text_callbacks.m_begin_diagnostic = default_text_starter;
     170       705442 :   m_text_callbacks.m_text_start_span
     171       705442 :     = default_start_span_fn<to_text>;
     172       705442 :   m_text_callbacks.m_html_start_span
     173       705442 :     = default_start_span_fn<to_html>;
     174       705442 :   m_text_callbacks.m_end_diagnostic = default_text_finalizer;
     175       705442 :   m_option_id_mgr = nullptr;
     176       705442 :   m_urlifier_stack = new auto_vec<urlifier_stack_node> ();
     177       705442 :   m_last_location = UNKNOWN_LOCATION;
     178       705442 :   m_client_aux_data = nullptr;
     179       705442 :   m_lock = 0;
     180       705442 :   m_inhibit_notes_p = false;
     181              : 
     182       705442 :   m_source_printing.colorize_source_p = false;
     183       705442 :   m_source_printing.show_labels_p = false;
     184       705442 :   m_source_printing.show_line_numbers_p = false;
     185       705442 :   m_source_printing.min_margin_width = 0;
     186       705442 :   m_source_printing.show_ruler_p = false;
     187       705442 :   m_source_printing.show_event_links_p = false;
     188              : 
     189       705442 :   m_column_options.m_column_unit = DIAGNOSTICS_COLUMN_UNIT_DISPLAY;
     190       705442 :   m_column_options.m_column_origin = 1;
     191       705442 :   m_column_options.m_tabstop = 8;
     192              : 
     193       705442 :   m_report_bug = false;
     194       705442 :   m_extra_output_kind = EXTRA_DIAGNOSTIC_OUTPUT_none;
     195       705442 :   if (const char *var = getenv ("GCC_EXTRA_DIAGNOSTIC_OUTPUT"))
     196              :     {
     197            4 :       if (!strcmp (var, "fixits-v1"))
     198            2 :         m_extra_output_kind = EXTRA_DIAGNOSTIC_OUTPUT_fixits_v1;
     199            2 :       else if (!strcmp (var, "fixits-v2"))
     200            2 :         m_extra_output_kind = EXTRA_DIAGNOSTIC_OUTPUT_fixits_v2;
     201              :       /* Silently ignore unrecognized values.  */
     202              :     }
     203       705442 :   m_escape_format = DIAGNOSTICS_ESCAPE_FORMAT_UNICODE;
     204       705442 :   m_fixits_change_set = nullptr;
     205       705442 :   m_diagnostic_groups.m_group_nesting_depth = 0;
     206       705442 :   m_diagnostic_groups.m_diagnostic_nesting_level = 0;
     207       705442 :   m_diagnostic_groups.m_emission_count = 0;
     208       705442 :   m_diagnostic_groups.m_inhibiting_notes_from = 0;
     209       705442 :   m_sinks.safe_push (new text_sink (*this, nullptr, true));
     210       705442 :   m_set_locations_cb = nullptr;
     211       705442 :   m_client_data_hooks = nullptr;
     212       705442 :   m_diagrams.m_theme = nullptr;
     213       705442 :   m_original_argv = nullptr;
     214       705442 :   m_diagnostic_buffer = nullptr;
     215       705442 :   m_logger = nullptr;
     216              : 
     217       705442 :   enum diagnostic_text_art_charset text_art_charset
     218              :     = DIAGNOSTICS_TEXT_ART_CHARSET_EMOJI;
     219       705442 :   if (const char *lang = getenv ("LANG"))
     220              :     {
     221              :       /* For LANG=C, don't assume the terminal supports anything
     222              :          other than ASCII.  */
     223       703162 :       if (!strcmp (lang, "C"))
     224       705442 :         text_art_charset = DIAGNOSTICS_TEXT_ART_CHARSET_ASCII;
     225              :     }
     226       705442 :   set_text_art_charset (text_art_charset);
     227              : 
     228       705442 :   if (const char *name = getenv ("GCC_DIAGNOSTICS_LOG"))
     229              :     {
     230            0 :       if (name[0] != '\0')
     231              :         {
     232              :           /* Try to write a log to the named path.  */
     233            0 :           if (FILE *outfile = fopen (name, "w"))
     234            0 :             m_logger = new logging::logger
     235            0 :               (output_file (outfile, true,
     236            0 :                             label_text::take (xstrdup (name))));
     237              :         }
     238              :       else
     239              :         /* Write a log to stderr.  */
     240            0 :         m_logger = new logging::logger
     241            0 :           (output_file
     242              :            (stderr, false,
     243            0 :             label_text::borrow ("stderr")));
     244              :     }
     245              : 
     246       705442 :   if (m_logger)
     247            0 :     m_logger->log_printf ("diagnostics::context::initialize");
     248       705442 : }
     249              : 
     250              : /* Maybe initialize the color support. We require clients to do this
     251              :    explicitly, since most clients don't want color.  When called
     252              :    without a VALUE, it initializes with DIAGNOSTICS_COLOR_DEFAULT.  */
     253              : 
     254              : void
     255      1400680 : context::color_init (int value)
     256              : {
     257              :   /* value == -1 is the default value.  */
     258      1400680 :   if (value < 0)
     259              :     {
     260              :       /* If DIAGNOSTICS_COLOR_DEFAULT is -1, default to
     261              :          -fdiagnostics-color=auto if GCC_COLORS is in the environment,
     262              :          otherwise default to -fdiagnostics-color=never, for other
     263              :          values default to that
     264              :          -fdiagnostics-color={never,auto,always}.  */
     265       591909 :       if (DIAGNOSTICS_COLOR_DEFAULT == -1)
     266              :         {
     267              :           if (!getenv ("GCC_COLORS"))
     268              :             return;
     269              :           value = DIAGNOSTICS_COLOR_AUTO;
     270              :         }
     271              :       else
     272       591909 :         value = DIAGNOSTICS_COLOR_DEFAULT;
     273              :     }
     274      2801360 :   pp_show_color (m_reference_printer)
     275      1400680 :     = colorize_init ((diagnostic_color_rule_t) value);
     276      5602720 :   for (auto sink_ : m_sinks)
     277      1400680 :     if (sink_->follows_reference_printer_p ())
     278      1400680 :       pp_show_color (sink_->get_printer ())
     279      1400680 :         = pp_show_color (m_reference_printer);
     280              : }
     281              : 
     282              : /* Initialize URL support within this context based on VALUE,
     283              :    handling "auto".  */
     284              : 
     285              : void
     286      1391074 : context::urls_init (int value)
     287              : {
     288              :   /* value == -1 is the default value.  */
     289      1391074 :   if (value < 0)
     290              :     {
     291              :       /* If DIAGNOSTICS_URLS_DEFAULT is -1, default to
     292              :          -fdiagnostics-urls=auto if GCC_URLS or TERM_URLS is in the
     293              :          environment, otherwise default to -fdiagnostics-urls=never,
     294              :          for other values default to that
     295              :          -fdiagnostics-urls={never,auto,always}.  */
     296       591909 :       if (DIAGNOSTICS_URLS_DEFAULT == -1)
     297              :         {
     298              :           if (!getenv ("GCC_URLS") && !getenv ("TERM_URLS"))
     299              :             return;
     300              :           value = DIAGNOSTICS_URL_AUTO;
     301              :         }
     302              :       else
     303       591909 :         value = DIAGNOSTICS_URLS_DEFAULT;
     304              :     }
     305              : 
     306      1391074 :   m_reference_printer->set_url_format
     307      1391074 :     (determine_url_format ((diagnostic_url_rule_t) value));
     308      5564296 :   for (auto sink_ : m_sinks)
     309      1391074 :     if (sink_->follows_reference_printer_p ())
     310      1391074 :       sink_->get_printer ()->set_url_format
     311      1391074 :         (m_reference_printer->get_url_format ());
     312              : }
     313              : 
     314              : void
     315       552171 : context::set_show_nesting (bool val)
     316              : {
     317      2208684 :   for (auto sink_ : m_sinks)
     318       552171 :     if (sink_->follows_reference_printer_p ())
     319       552171 :       if (auto text_sink_ = sink_->dyn_cast_text_sink ())
     320       552171 :         text_sink_->set_show_nesting (val);
     321       552171 : }
     322              : 
     323              : void
     324       285722 : context::set_show_nesting_locations (bool val)
     325              : {
     326      1142888 :   for (auto sink_ : m_sinks)
     327       285722 :     if (sink_->follows_reference_printer_p ())
     328       285722 :       if (auto text_sink_ = sink_->dyn_cast_text_sink ())
     329       285722 :         text_sink_->set_show_locations_in_nesting (val);
     330       285722 : }
     331              : 
     332              : void
     333       285722 : context::set_show_nesting_levels (bool val)
     334              : {
     335      1142888 :   for (auto sink_ : m_sinks)
     336       285722 :     if (sink_->follows_reference_printer_p ())
     337       285722 :       if (auto text_sink_ = sink_->dyn_cast_text_sink ())
     338       285722 :         text_sink_->set_show_nesting_levels (val);
     339       285722 : }
     340              : 
     341              : /* Create the file_cache, if not already created, and tell it how to
     342              :    translate files on input.  */
     343              : void
     344       209535 : context::initialize_input_context (diagnostic_input_charset_callback ccb,
     345              :                                    bool should_skip_bom)
     346              : {
     347       209535 :   m_file_cache->initialize_input_context (ccb, should_skip_bom);
     348       209535 : }
     349              : 
     350              : /* Do any cleaning up required after the last diagnostic is emitted.  */
     351              : 
     352              : void
     353       305101 : context::finish ()
     354              : {
     355       305101 :   if (m_logger)
     356              :     {
     357            0 :       m_logger->log_printf ("diagnostics::context::finish");
     358              :       /* We're cleaning up the logger before this function exits,
     359              :          so we can't use auto_inc_depth here.  */
     360            0 :       m_logger->inc_depth ();
     361            0 :       dump (m_logger->get_stream (), m_logger->get_indent ());
     362              :     }
     363              : 
     364      1220440 :   for (auto iter : m_sinks)
     365       305137 :     iter->finalize_extensions ();
     366              : 
     367              :   /* We might be handling a fatal error.
     368              :      Close any active diagnostic groups, which may trigger flushing
     369              :      sinks.  */
     370       305861 :   while (m_diagnostic_groups.m_group_nesting_depth > 0)
     371          760 :     end_group ();
     372              : 
     373       305101 :   set_diagnostic_buffer (nullptr);
     374              : 
     375              :   /* Clean ups.  */
     376              : 
     377       915339 :   while (!m_sinks.is_empty ())
     378       305137 :     delete m_sinks.pop ();
     379              : 
     380       305101 :   if (m_diagrams.m_theme)
     381              :     {
     382        40258 :       delete m_diagrams.m_theme;
     383        40258 :       m_diagrams.m_theme = nullptr;
     384              :     }
     385              : 
     386       305101 :   delete m_file_cache;
     387       305101 :   m_file_cache = nullptr;
     388              : 
     389       305101 :   m_option_classifier.fini ();
     390              : 
     391       305101 :   delete m_reference_printer;
     392       305101 :   m_reference_printer = nullptr;
     393              : 
     394       305101 :   if (m_fixits_change_set)
     395              :     {
     396           17 :       delete m_fixits_change_set;
     397           17 :       m_fixits_change_set = nullptr;
     398              :     }
     399              : 
     400       305101 :   if (m_client_data_hooks)
     401              :     {
     402       284182 :       delete m_client_data_hooks;
     403       284182 :       m_client_data_hooks = nullptr;
     404              :     }
     405              : 
     406       305101 :   delete m_option_id_mgr;
     407       305101 :   m_option_id_mgr = nullptr;
     408              : 
     409       305101 :   if (m_urlifier_stack)
     410              :     {
     411       590623 :       while (!m_urlifier_stack->is_empty ())
     412       285522 :         pop_urlifier ();
     413       305101 :       delete m_urlifier_stack;
     414       305101 :       m_urlifier_stack = nullptr;
     415              :     }
     416              : 
     417       305101 :   freeargv (m_original_argv);
     418       305101 :   m_original_argv = nullptr;
     419              : 
     420       305101 :   delete m_logger;
     421       305101 :   m_logger = nullptr;
     422       305101 : }
     423              : 
     424              : /* Dump state of this diagnostics::context to OUT, for debugging.  */
     425              : 
     426              : void
     427            0 : context::dump (FILE *outfile, int indent) const
     428              : {
     429            0 :   dumping::emit_heading (outfile, indent, "diagnostics::context");
     430            0 :   m_diagnostic_counters.dump (outfile, indent + 2);
     431            0 :   dumping::emit_heading (outfile, indent + 2, "reference printer");
     432            0 :   if (m_reference_printer)
     433            0 :     m_reference_printer->dump (outfile, indent + 4);
     434              :   else
     435            0 :     dumping::emit_none (outfile, indent + 4);
     436            0 :   dumping::emit_heading (outfile, indent + 2, "output sinks");
     437            0 :   if (m_sinks.length () > 0)
     438              :     {
     439            0 :       for (unsigned i = 0; i < m_sinks.length (); ++i)
     440              :         {
     441            0 :           dumping::emit_indent (outfile, indent + 4);
     442            0 :           const sink *s = m_sinks[i];
     443            0 :           fprintf (outfile, "sink %i (", i);
     444            0 :           s->dump_kind (outfile);
     445            0 :           fprintf (outfile, "):\n");
     446            0 :           s->dump (outfile, indent + 6);
     447              :         }
     448              :     }
     449              :   else
     450            0 :     dumping::emit_none (outfile, indent + 4);
     451            0 :   dumping::emit_heading (outfile, indent + 2, "diagnostic buffer");
     452            0 :   if (m_diagnostic_buffer)
     453            0 :     m_diagnostic_buffer->dump (outfile, indent + 4);
     454              :   else
     455            0 :     dumping::emit_none (outfile, indent + 4);
     456            0 :   dumping::emit_heading (outfile, indent + 2, "file cache");
     457            0 :   if (m_file_cache)
     458            0 :     m_file_cache->dump (outfile, indent + 4);
     459              :   else
     460            0 :     dumping::emit_none (outfile, indent + 4);
     461            0 :   dumping::emit_heading (outfile, indent + 2, "client data hooks");
     462            0 :   if (m_client_data_hooks)
     463            0 :     m_client_data_hooks->dump (outfile, indent + 4);
     464              :   else
     465            0 :     dumping::emit_none (outfile, indent + 4);
     466            0 : }
     467              : 
     468              : /* Return true if sufficiently severe diagnostics have been seen that
     469              :    we ought to exit with a non-zero exit code.  */
     470              : 
     471              : bool
     472       283971 : context::execution_failed_p () const
     473              : {
     474       283971 :   return (diagnostic_count (kind::fatal)
     475       283970 :           || diagnostic_count (kind::error)
     476       256920 :           || diagnostic_count (kind::sorry)
     477       540685 :           || diagnostic_count (kind::werror));
     478              : }
     479              : 
     480              : void
     481         1615 : context::remove_all_output_sinks ()
     482              : {
     483         4845 :   while (!m_sinks.is_empty ())
     484         1615 :     delete m_sinks.pop ();
     485         1615 : }
     486              : 
     487              : void
     488         1615 : context::set_sink (std::unique_ptr<sink> sink_)
     489              : {
     490         1615 :   DIAGNOSTICS_LOG_SCOPE_PRINTF0 (m_logger, "diagnostics::context::set_sink");
     491         1615 :   if (m_logger)
     492            0 :     sink_->dump (m_logger->get_stream (), m_logger->get_indent ());
     493         1615 :   remove_all_output_sinks ();
     494         1615 :   m_sinks.safe_push (sink_.release ());
     495         1615 : }
     496              : 
     497              : sink &
     498        18845 : context::get_sink (size_t idx) const
     499              : {
     500        18845 :   gcc_assert (idx < m_sinks.length ());
     501        18845 :   gcc_assert (m_sinks[idx]);
     502        18845 :   return *m_sinks[idx];
     503              : }
     504              : 
     505              : void
     506           36 : context::add_sink (std::unique_ptr<sink> sink_)
     507              : {
     508           36 :   DIAGNOSTICS_LOG_SCOPE_PRINTF0 (m_logger, "diagnostics::context::add_sink");
     509           36 :   if (m_logger)
     510            0 :     sink_->dump (m_logger->get_stream (), m_logger->get_indent ());
     511           36 :   m_sinks.safe_push (sink_.release ());
     512           36 : }
     513              : 
     514              : /* Return true if there are no machine-readable formats writing to stderr.  */
     515              : 
     516              : bool
     517        20265 : context::supports_fnotice_on_stderr_p () const
     518              : {
     519        80112 :   for (auto sink_ : m_sinks)
     520        19317 :     if (sink_->machine_readable_stderr_p ())
     521              :       return false;
     522              :   return true;
     523              : }
     524              : 
     525              : void
     526            0 : context::set_main_input_filename (const char *filename)
     527              : {
     528            0 :   for (auto sink_ : m_sinks)
     529            0 :     sink_->set_main_input_filename (filename);
     530            0 : }
     531              : 
     532              : std::unique_ptr<client_data_hooks>
     533       340015 : context::set_client_data_hooks (std::unique_ptr<client_data_hooks> hooks)
     534              : {
     535       340015 :   std::unique_ptr<client_data_hooks> old_hooks (m_client_data_hooks);
     536              :   /* Ideally the field would be a std::unique_ptr here.  */
     537       340015 :   m_client_data_hooks = hooks.release ();
     538       340015 :   return old_hooks;
     539              : }
     540              : 
     541              : void
     542       285722 : context::set_original_argv (unique_argv original_argv)
     543              : {
     544              :   /* Ideally we'd use a unique_argv for m_original_argv, but
     545              :      diagnostics::context doesn't yet have a ctor/dtor pair.  */
     546              : 
     547              :   // Ensure any old value is freed
     548       285722 :   freeargv (m_original_argv);
     549              : 
     550              :   // Take ownership of the new value
     551       285722 :   m_original_argv = original_argv.release ();
     552       285722 : }
     553              : 
     554              : void
     555       297928 : context::set_option_id_manager (std::unique_ptr<option_id_manager> mgr,
     556              :                                 unsigned lang_mask)
     557              : {
     558       297928 :   delete m_option_id_mgr;
     559       297928 :   m_option_id_mgr = mgr.release ();
     560       297928 :   m_lang_mask = lang_mask;
     561       297928 : }
     562              : 
     563              : void
     564       579715 : context::push_owned_urlifier (std::unique_ptr<urlifier> ptr)
     565              : {
     566       579715 :   gcc_assert (m_urlifier_stack);
     567       579715 :   const urlifier_stack_node node = { ptr.release (), true };
     568       579715 :   m_urlifier_stack->safe_push (node);
     569       579715 : }
     570              : 
     571              : void
     572   1942308833 : context::push_borrowed_urlifier (const urlifier &loan)
     573              : {
     574   1942308833 :   gcc_assert (m_urlifier_stack);
     575   1942308833 :   const urlifier_stack_node node = { const_cast <urlifier *> (&loan), false };
     576   1942308833 :   m_urlifier_stack->safe_push (node);
     577   1942308833 : }
     578              : 
     579              : void
     580   1942594354 : context::pop_urlifier ()
     581              : {
     582   1942594354 :   gcc_assert (m_urlifier_stack);
     583   1942594354 :   gcc_assert (m_urlifier_stack->length () > 0);
     584              : 
     585   1942594354 :   const urlifier_stack_node node = m_urlifier_stack->pop ();
     586   1942594354 :   if (node.m_owned)
     587       285521 :     delete node.m_urlifier;
     588   1942594354 : }
     589              : 
     590              : const logical_locations::manager *
     591         4101 : context::get_logical_location_manager () const
     592              : {
     593         4101 :   if (!m_client_data_hooks)
     594              :     return nullptr;
     595         4097 :   return m_client_data_hooks->get_logical_location_manager ();
     596              : }
     597              : 
     598              : const urlifier *
     599      1561222 : context::get_urlifier () const
     600              : {
     601      1561222 :   if (!m_urlifier_stack)
     602              :     return nullptr;
     603      1561222 :   if (m_urlifier_stack->is_empty ())
     604              :     return nullptr;
     605      1560883 :   return m_urlifier_stack->last ().m_urlifier;
     606              : }
     607              : 
     608              : 
     609              : /* Set PP as the reference printer for this context.
     610              :    Refresh all output sinks.  */
     611              : 
     612              : void
     613       208458 : context::set_pretty_printer (std::unique_ptr<pretty_printer> pp)
     614              : {
     615       208458 :   delete m_reference_printer;
     616       208458 :   m_reference_printer = pp.release ();
     617       208458 :   refresh_output_sinks ();
     618       208458 : }
     619              : 
     620              : /* Give all output sinks a chance to rebuild their pretty_printer.  */
     621              : 
     622              : void
     623       494180 : context::refresh_output_sinks ()
     624              : {
     625      1976720 :   for (auto sink_ : m_sinks)
     626       494180 :     sink_->update_printer ();
     627       494180 : }
     628              : 
     629              : /* Set FORMAT_DECODER on the reference printer and on the pretty_printer
     630              :    of all output sinks.  */
     631              : 
     632              : void
     633       579780 : context::set_format_decoder (printer_fn format_decoder)
     634              : {
     635       579780 :   pp_format_decoder (m_reference_printer) = format_decoder;
     636      2319121 :   for (auto sink_ : m_sinks)
     637       579781 :     pp_format_decoder (sink_->get_printer ()) = format_decoder;
     638       579780 : }
     639              : 
     640              : void
     641       571449 : context::set_show_highlight_colors (bool val)
     642              : {
     643       571449 :   pp_show_highlight_colors (m_reference_printer) = val;
     644      2285796 :   for (auto sink_ : m_sinks)
     645       571449 :     if (sink_->follows_reference_printer_p ())
     646       571449 :       pp_show_highlight_colors (sink_->get_printer ()) = val;
     647       571449 : }
     648              : 
     649              : void
     650          422 : context::set_prefixing_rule (diagnostic_prefixing_rule_t rule)
     651              : {
     652          422 :   pp_prefixing_rule (m_reference_printer) = rule;
     653         1688 :   for (auto sink_ : m_sinks)
     654          422 :     if (sink_->follows_reference_printer_p ())
     655          422 :       pp_prefixing_rule (sink_->get_printer ()) = rule;
     656          422 : }
     657              : 
     658              : void
     659           17 : context::initialize_fixits_change_set ()
     660              : {
     661           17 :   delete m_fixits_change_set;
     662           17 :   gcc_assert (m_file_cache);
     663           17 :   m_fixits_change_set = new changes::change_set (*m_file_cache);
     664           17 : }
     665              : 
     666              : // class client_data_hooks
     667              : 
     668              : void
     669            0 : client_data_hooks::dump (FILE *outfile, int indent) const
     670              : {
     671            0 :   dumping::emit_heading (outfile, indent, "logical location manager");
     672            0 :   if (auto mgr = get_logical_location_manager ())
     673            0 :     mgr->dump (outfile, indent + 2);
     674              :   else
     675            0 :     dumping::emit_none (outfile, indent + 2);
     676            0 : }
     677              : 
     678              : } // namespace diagnostics
     679              : 
     680              : /* Initialize DIAGNOSTIC, where the message MSG has already been
     681              :    translated.  */
     682              : void
     683    106528247 : diagnostic_set_info_translated (diagnostics::diagnostic_info *diagnostic,
     684              :                                 const char *msg, va_list *args,
     685              :                                 rich_location *richloc,
     686              :                                 enum diagnostics::kind kind)
     687              : {
     688    106528247 :   gcc_assert (richloc);
     689    106528247 :   diagnostic->m_message.m_err_no = errno;
     690    106528247 :   diagnostic->m_message.m_args_ptr = args;
     691    106528247 :   diagnostic->m_message.m_format_spec = msg;
     692    106528247 :   diagnostic->m_message.m_richloc = richloc;
     693    106528247 :   diagnostic->m_richloc = richloc;
     694    106528247 :   diagnostic->m_metadata = nullptr;
     695    106528247 :   diagnostic->m_kind = kind;
     696    106528247 :   diagnostic->m_option_id = 0;
     697    106528247 : }
     698              : 
     699              : /* Initialize DIAGNOSTIC, where the message GMSGID has not yet been
     700              :    translated.  */
     701              : void
     702    106372117 : diagnostic_set_info (diagnostics::diagnostic_info *diagnostic,
     703              :                      const char *gmsgid, va_list *args,
     704              :                      rich_location *richloc,
     705              :                      enum diagnostics::kind kind)
     706              : {
     707    106372117 :   gcc_assert (richloc);
     708    106372117 :   diagnostic_set_info_translated (diagnostic, _(gmsgid), args, richloc, kind);
     709    106372117 : }
     710              : 
     711              : namespace diagnostics {
     712              : 
     713              : static const char *const diagnostic_kind_text[] = {
     714              : #define DEFINE_DIAGNOSTIC_KIND(K, T, C) (T),
     715              : #include "diagnostics/kinds.def"
     716              : #undef DEFINE_DIAGNOSTIC_KIND
     717              :   "must-not-happen"
     718              : };
     719              : 
     720              : /* Get unlocalized string describing KIND.  */
     721              : 
     722              : const char *
     723       355116 : get_text_for_kind (enum kind kind)
     724              : {
     725       355116 :   return diagnostic_kind_text[static_cast<int> (kind)];
     726              : }
     727              : 
     728              : static const char *const diagnostic_kind_debug_text[] = {
     729              : #define DEFINE_DIAGNOSTIC_KIND(K, T, C) (#K),
     730              : #include "diagnostics/kinds.def"
     731              : #undef DEFINE_DIAGNOSTIC_KIND
     732              :   "must-not-happen"
     733              : };
     734              : 
     735              : const char *
     736            0 : get_debug_string_for_kind (enum kind kind)
     737              : {
     738            0 :   return diagnostic_kind_debug_text[static_cast<int> (kind)];
     739              : }
     740              : 
     741              : static const char *const diagnostic_kind_color[] = {
     742              : #define DEFINE_DIAGNOSTIC_KIND(K, T, C) (C),
     743              : #include "diagnostics/kinds.def"
     744              : #undef DEFINE_DIAGNOSTIC_KIND
     745              :   nullptr
     746              : };
     747              : 
     748              : /* Get a color name for diagnostics of type KIND
     749              :    Result could be nullptr.  */
     750              : 
     751              : const char *
     752      1728592 : get_color_for_kind (enum kind kind)
     753              : {
     754      1728592 :   return diagnostic_kind_color[static_cast<int> (kind)];
     755              : }
     756              : 
     757              : /* Given an expanded_location, convert the column (which is in 1-based bytes)
     758              :    to the requested units, without converting the origin.
     759              :    Return -1 if the column is invalid (<= 0).  */
     760              : 
     761              : static int
     762       318894 : convert_column_unit (file_cache &fc,
     763              :                      enum diagnostics_column_unit column_unit,
     764              :                      int tabstop,
     765              :                      expanded_location s)
     766              : {
     767       318894 :   if (s.column <= 0)
     768              :     return -1;
     769              : 
     770       316024 :   switch (column_unit)
     771              :     {
     772            0 :     default:
     773            0 :       gcc_unreachable ();
     774              : 
     775       315888 :     case DIAGNOSTICS_COLUMN_UNIT_DISPLAY:
     776       315888 :       {
     777       315888 :         cpp_char_column_policy policy (tabstop, cpp_wcwidth);
     778       315888 :         return location_compute_display_column (fc, s, policy);
     779              :       }
     780              : 
     781              :     case DIAGNOSTICS_COLUMN_UNIT_BYTE:
     782              :       return s.column;
     783              :     }
     784              : }
     785              : 
     786              : /* Given an expanded_location, convert the column (which is in 1-based bytes)
     787              :    to the requested units and origin.  Return -1 if the column is
     788              :    invalid (<= 0).  */
     789              : int
     790       318816 : column_options::convert_column (file_cache &fc,
     791              :                                 expanded_location s) const
     792              : {
     793       318816 :   int one_based_col = convert_column_unit (fc, m_column_unit, m_tabstop, s);
     794       318816 :   if (one_based_col <= 0)
     795              :     return -1;
     796       315946 :   return one_based_col + (m_column_origin - 1);
     797              : }
     798              : 
     799      2333236 : column_policy::column_policy (const context &dc)
     800      2333236 : : m_file_cache (dc.get_file_cache ()),
     801      2333236 :   m_column_options (dc.get_column_options ())
     802              : {
     803      2333236 : }
     804              : 
     805              : /* Given an expanded_location, convert the column (which is in 1-based bytes)
     806              :    to the requested units and origin.  Return -1 if the column is
     807              :    invalid (<= 0).  */
     808              : int
     809       318816 : column_policy::converted_column (expanded_location s) const
     810              : {
     811       318816 :   return m_column_options.convert_column (m_file_cache, s);
     812              : }
     813              : 
     814              : /* Return a string describing a location e.g. "foo.c:42:10".  */
     815              : 
     816              : label_text
     817       345714 : column_policy::get_location_text (const expanded_location &s,
     818              :                                   bool show_column,
     819              :                                   bool colorize) const
     820              : {
     821       345714 :   const char *locus_cs = colorize_start (colorize, "locus");
     822       345714 :   const char *locus_ce = colorize_stop (colorize);
     823       345714 :   const char *file = s.file ? s.file : progname;
     824       345714 :   int line = 0;
     825       345714 :   int col = -1;
     826       345714 :   if (strcmp (file, special_fname_builtin ()))
     827              :     {
     828       344957 :       line = s.line;
     829       344957 :       if (show_column)
     830       317653 :         col = converted_column (s);
     831              :     }
     832              : 
     833       345714 :   const char *line_col = text_sink::maybe_line_and_column (line, col);
     834       345714 :   return label_text::take (build_message_string ("%s%s%s:%s", locus_cs, file,
     835       345714 :                                                  line_col, locus_ce));
     836              : }
     837              : 
     838        50601 : location_print_policy::
     839        50601 : location_print_policy (const context &dc)
     840        50601 : : m_column_policy (dc),
     841        50601 :   m_show_column (dc.m_show_column)
     842              : {
     843        50601 : }
     844              : 
     845      1230417 : location_print_policy::
     846      1230417 : location_print_policy (const text_sink &text_output)
     847              : :
     848      1230417 :   m_column_policy (text_output.get_context ()),
     849      1230417 :   m_show_column (text_output.get_context ().m_show_column)
     850              : {
     851      1230417 : }
     852              : 
     853              : } // namespace diagnostics
     854              : 
     855              : /* Functions at which to stop the backtrace print.  It's not
     856              :    particularly helpful to print the callers of these functions.  */
     857              : 
     858              : static const char * const bt_stop[] =
     859              : {
     860              :   "main",
     861              :   "toplev::main",
     862              :   "execute_one_pass",
     863              :   "compile_file",
     864              : };
     865              : 
     866              : /* A callback function passed to the backtrace_full function.  */
     867              : 
     868              : static int
     869          297 : bt_callback (void *data, uintptr_t pc, const char *filename, int lineno,
     870              :              const char *function)
     871              : {
     872          297 :   int *pcount = (int *) data;
     873              : 
     874              :   /* If we don't have any useful information, don't print
     875              :      anything.  */
     876          297 :   if (filename == nullptr && function == nullptr)
     877              :     return 0;
     878              : 
     879              :   /* Skip functions in context.cc.  */
     880          294 :   if (*pcount == 0
     881           42 :       && filename != nullptr
     882          336 :       && strcmp (lbasename (filename), "context.cc") == 0)
     883              :     return 0;
     884              : 
     885              :   /* Print up to 20 functions.  We could make this a --param, but
     886              :      since this is only for debugging just use a constant for now.  */
     887          273 :   if (*pcount >= 20)
     888              :     {
     889              :       /* Returning a non-zero value stops the backtrace.  */
     890              :       return 1;
     891              :     }
     892          269 :   ++*pcount;
     893              : 
     894          269 :   char *alc = nullptr;
     895          269 :   if (function != nullptr)
     896              :     {
     897          269 :       char *str = cplus_demangle_v3 (function,
     898              :                                      (DMGL_VERBOSE | DMGL_ANSI
     899              :                                       | DMGL_GNU_V3 | DMGL_PARAMS));
     900          269 :       if (str != nullptr)
     901              :         {
     902          147 :           alc = str;
     903          147 :           function = str;
     904              :         }
     905              : 
     906         1314 :       for (size_t i = 0; i < ARRAY_SIZE (bt_stop); ++i)
     907              :         {
     908         1062 :           size_t len = strlen (bt_stop[i]);
     909         1062 :           if (strncmp (function, bt_stop[i], len) == 0
     910           17 :               && (function[len] == '\0' || function[len] == '('))
     911              :             {
     912           17 :               if (alc != nullptr)
     913           14 :                 free (alc);
     914              :               /* Returning a non-zero value stops the backtrace.  */
     915           17 :               return 1;
     916              :             }
     917              :         }
     918              :     }
     919              : 
     920          504 :   fprintf (stderr, "0x%lx %s\n\t%s:%d\n",
     921              :            (unsigned long) pc,
     922              :            function == nullptr ? "???" : function,
     923              :            filename == nullptr ? "???" : filename,
     924              :            lineno);
     925              : 
     926          252 :   if (alc != nullptr)
     927          133 :     free (alc);
     928              : 
     929              :   return 0;
     930              : }
     931              : 
     932              : /* A callback function passed to the backtrace_full function.  This is
     933              :    called if backtrace_full has an error.  */
     934              : 
     935              : static void
     936            0 : bt_err_callback (void *data ATTRIBUTE_UNUSED, const char *msg, int errnum)
     937              : {
     938            0 :   if (errnum < 0)
     939              :     {
     940              :       /* This means that no debug info was available.  Just quietly
     941              :          skip printing backtrace info.  */
     942              :       return;
     943              :     }
     944            0 :   fprintf (stderr, "%s%s%s\n", msg, errnum == 0 ? "" : ": ",
     945            0 :            errnum == 0 ? "" : xstrerror (errnum));
     946              : }
     947              : 
     948              : namespace diagnostics {
     949              : 
     950              : /* Check if we've met the maximum error limit, and if so fatally exit
     951              :    with a message.
     952              :    FLUSH indicates whether a diagnostics::context::finish call is needed.  */
     953              : 
     954              : void
     955      1457232 : context::check_max_errors (bool flush)
     956              : {
     957      1457232 :   if (!m_max_errors)
     958              :     return;
     959              : 
     960         3665 :   int count = (diagnostic_count (kind::error)
     961         3665 :                + diagnostic_count (kind::sorry)
     962         3665 :                + diagnostic_count (kind::werror));
     963              : 
     964         3665 :   if (count >= m_max_errors)
     965              :     {
     966            7 :       fnotice (stderr,
     967              :                "compilation terminated due to -fmax-errors=%u.\n",
     968              :                m_max_errors);
     969            7 :       if (flush)
     970            3 :         finish ();
     971            7 :       exit (FATAL_EXIT_CODE);
     972              :     }
     973              : }
     974              : 
     975              : /* Take any action which is expected to happen after the diagnostic
     976              :    is written out.  This function does not always return.  */
     977              : 
     978              : void
     979       352932 : context::action_after_output (enum kind diag_kind)
     980              : {
     981       352932 :   switch (diag_kind)
     982              :     {
     983              :     case kind::debug:
     984              :     case kind::note:
     985              :     case kind::anachronism:
     986              :     case kind::warning:
     987              :       break;
     988              : 
     989       143502 :     case kind::error:
     990       143502 :     case kind::sorry:
     991       143502 :       if (m_abort_on_error)
     992            0 :         real_abort ();
     993       143502 :       if (m_fatal_errors)
     994              :         {
     995            7 :           fnotice (stderr, "compilation terminated due to -Wfatal-errors.\n");
     996            7 :           finish ();
     997            7 :           exit (FATAL_EXIT_CODE);
     998              :         }
     999              :       break;
    1000              : 
    1001           21 :     case kind::ice:
    1002           21 :     case kind::ice_nobt:
    1003           21 :       {
    1004              :         /* Attempt to ensure that any outputs are flushed e.g. that .sarif
    1005              :            files are written out.
    1006              :            Only do it once.  */
    1007           21 :         static char **saved_argv = nullptr;
    1008           21 :         if (!saved_argv)
    1009              :           {
    1010           21 :             saved_argv = m_original_argv;
    1011           21 :             m_original_argv = nullptr;
    1012           21 :             finish ();
    1013              :           }
    1014              : 
    1015           21 :         struct backtrace_state *state = nullptr;
    1016           21 :         if (diag_kind == kind::ice)
    1017           21 :           state = backtrace_create_state (nullptr, 0, bt_err_callback, nullptr);
    1018           21 :         int count = 0;
    1019           21 :         if (state != nullptr)
    1020           21 :           backtrace_full (state, 2, bt_callback, bt_err_callback,
    1021              :                           (void *) &count);
    1022              : 
    1023           21 :         if (m_abort_on_error)
    1024            0 :           real_abort ();
    1025              : 
    1026           21 :         bool space = false;
    1027          899 :         for (auto *argv = saved_argv; *argv; space = true)
    1028          878 :           fnotice (stderr, &" %s"[1 - space], *argv++);
    1029           21 :         fnotice (stderr, "\n");
    1030           21 :         freeargv (saved_argv);
    1031              : 
    1032           21 :         if (m_report_bug)
    1033            0 :           fnotice (stderr, "Please submit a full bug report, "
    1034              :                    "with preprocessed source.\n");
    1035              :         else
    1036           21 :           fnotice (stderr, "Please submit a full bug report, "
    1037              :                    "with preprocessed source (by using -freport-bug).\n");
    1038              : 
    1039           21 :         if (count > 0)
    1040           21 :           fnotice (stderr, "Please include the complete backtrace "
    1041              :                    "with any bug report.\n");
    1042           21 :         fnotice (stderr, "See %s for instructions.\n", bug_report_url);
    1043              : 
    1044           21 :         exit (ICE_EXIT_CODE);
    1045              :       }
    1046              : 
    1047          687 :     case kind::fatal:
    1048          687 :       if (m_abort_on_error)
    1049            0 :         real_abort ();
    1050          687 :       fnotice (stderr, "compilation terminated.\n");
    1051          687 :       finish ();
    1052          687 :       exit (FATAL_EXIT_CODE);
    1053              : 
    1054            0 :     default:
    1055            0 :       gcc_unreachable ();
    1056              :     }
    1057       352217 : }
    1058              : 
    1059              : /* State whether we should inhibit notes in the current diagnostic_group and
    1060              :    its future children if any.  */
    1061              : 
    1062              : void
    1063   1007880318 : context::inhibit_notes_in_group (bool inhibit)
    1064              : {
    1065   1007880318 :   int curr_depth = (m_diagnostic_groups.m_group_nesting_depth
    1066   1007880318 :                     + m_diagnostic_groups.m_diagnostic_nesting_level);
    1067              : 
    1068   1007880318 :   if (inhibit)
    1069              :     {
    1070              :       /* If we're already inhibiting, there's nothing to do.  */
    1071    104739218 :       if (m_diagnostic_groups.m_inhibiting_notes_from)
    1072              :         return;
    1073              : 
    1074              :       /* Since we're called via warning/error/... that all have their own
    1075              :          diagnostic_group, we must consider that we started inhibiting in their
    1076              :          parent.  */
    1077    104739161 :       gcc_assert (m_diagnostic_groups.m_group_nesting_depth > 0);
    1078    104739161 :       m_diagnostic_groups.m_inhibiting_notes_from = curr_depth - 1;
    1079              :     }
    1080    903141100 :   else if (m_diagnostic_groups.m_inhibiting_notes_from)
    1081              :     {
    1082              :       /* Only cancel inhibition at the depth that set it up.  */
    1083      2940164 :       if (curr_depth >= m_diagnostic_groups.m_inhibiting_notes_from)
    1084              :         return;
    1085              : 
    1086      1470040 :       m_diagnostic_groups.m_inhibiting_notes_from = 0;
    1087              :     }
    1088              : }
    1089              : 
    1090              : /* Return whether notes must be inhibited in the current diagnostic_group.  */
    1091              : 
    1092              : bool
    1093       111051 : context::notes_inhibited_in_group () const
    1094              : {
    1095       111051 :   if (m_diagnostic_groups.m_inhibiting_notes_from
    1096           17 :       && (m_diagnostic_groups.m_group_nesting_depth
    1097           17 :           + m_diagnostic_groups.m_diagnostic_nesting_level
    1098              :           >= m_diagnostic_groups.m_inhibiting_notes_from))
    1099           17 :     return true;
    1100              :   return false;
    1101              : }
    1102              : 
    1103              : /* class diagnostics::logical_locations::manager.  */
    1104              : 
    1105              : /* Return true iff this is a function or method.  */
    1106              : 
    1107              : bool
    1108         3923 : logical_locations::manager::function_p (key k) const
    1109              : {
    1110         3923 :   switch (get_kind (k))
    1111              :     {
    1112            0 :     default:
    1113            0 :       gcc_unreachable ();
    1114              :     case kind::unknown:
    1115              :     case kind::module_:
    1116              :     case kind::namespace_:
    1117              :     case kind::type:
    1118              :     case kind::return_type:
    1119              :     case kind::parameter:
    1120              :     case kind::variable:
    1121              :       return false;
    1122              : 
    1123         3923 :     case kind::function:
    1124         3923 :     case kind::member:
    1125         3923 :       return true;
    1126              :     }
    1127              : }
    1128              : 
    1129              : /* Helper function for print_parseable_fixits.  Print TEXT to PP, obeying the
    1130              :    escaping rules for -fdiagnostics-parseable-fixits.  */
    1131              : 
    1132              : static void
    1133          105 : print_escaped_string (pretty_printer *pp, const char *text)
    1134              : {
    1135          105 :   gcc_assert (pp);
    1136          105 :   gcc_assert (text);
    1137              : 
    1138          105 :   pp_character (pp, '"');
    1139         3786 :   for (const char *ch = text; *ch; ch++)
    1140              :     {
    1141         3681 :       switch (*ch)
    1142              :         {
    1143            3 :         case '\\':
    1144              :           /* Escape backslash as two backslashes.  */
    1145            3 :           pp_string (pp, "\\\\");
    1146            3 :           break;
    1147            3 :         case '\t':
    1148              :           /* Escape tab as "\t".  */
    1149            3 :           pp_string (pp, "\\t");
    1150            3 :           break;
    1151            6 :         case '\n':
    1152              :           /* Escape newline as "\n".  */
    1153            6 :           pp_string (pp, "\\n");
    1154            6 :           break;
    1155            3 :         case '"':
    1156              :           /* Escape doublequotes as \".  */
    1157            3 :           pp_string (pp, "\\\"");
    1158            3 :           break;
    1159         3666 :         default:
    1160         3666 :           if (ISPRINT (*ch))
    1161         3660 :             pp_character (pp, *ch);
    1162              :           else
    1163              :             /* Use octal for non-printable chars.  */
    1164              :             {
    1165            6 :               unsigned char c = (*ch & 0xff);
    1166            6 :               pp_printf (pp, "\\%o%o%o", (c / 64), (c / 8) & 007, c & 007);
    1167              :             }
    1168              :           break;
    1169              :         }
    1170              :     }
    1171          105 :   pp_character (pp, '"');
    1172          105 : }
    1173              : 
    1174              : /* Implementation of -fdiagnostics-parseable-fixits and
    1175              :    GCC_EXTRA_DIAGNOSTIC_OUTPUT.
    1176              :    Print a machine-parseable version of all fixits in RICHLOC to PP,
    1177              :    using COLUMN_UNIT to express columns.
    1178              :    Use TABSTOP when handling DIAGNOSTICS_COLUMN_UNIT_DISPLAY.  */
    1179              : 
    1180              : static void
    1181           39 : print_parseable_fixits (file_cache &fc,
    1182              :                         pretty_printer *pp, rich_location *richloc,
    1183              :                         enum diagnostics_column_unit column_unit,
    1184              :                         int tabstop)
    1185              : {
    1186           39 :   gcc_assert (pp);
    1187           39 :   gcc_assert (richloc);
    1188              : 
    1189           39 :   char *saved_prefix = pp_take_prefix (pp);
    1190           39 :   pp_set_prefix (pp, nullptr);
    1191              : 
    1192           78 :   for (unsigned i = 0; i < richloc->get_num_fixit_hints (); i++)
    1193              :     {
    1194           39 :       const fixit_hint *hint = richloc->get_fixit_hint (i);
    1195           39 :       location_t start_loc = hint->get_start_loc ();
    1196           39 :       expanded_location start_exploc = expand_location (start_loc);
    1197           39 :       pp_string (pp, "fix-it:");
    1198           39 :       print_escaped_string (pp, start_exploc.file);
    1199              :       /* For compatibility with clang, print as a half-open range.  */
    1200           39 :       location_t next_loc = hint->get_next_loc ();
    1201           39 :       expanded_location next_exploc = expand_location (next_loc);
    1202           39 :       int start_col
    1203           39 :         = convert_column_unit (fc, column_unit, tabstop, start_exploc);
    1204           39 :       int next_col
    1205           39 :         = convert_column_unit (fc, column_unit, tabstop, next_exploc);
    1206           39 :       pp_printf (pp, ":{%i:%i-%i:%i}:",
    1207              :                  start_exploc.line, start_col,
    1208              :                  next_exploc.line, next_col);
    1209           39 :       print_escaped_string (pp, hint->get_string ());
    1210           39 :       pp_newline (pp);
    1211              :     }
    1212              : 
    1213           39 :   pp_set_prefix (pp, saved_prefix);
    1214           39 : }
    1215              : 
    1216              : /* Update the inlining info in this context for a DIAGNOSTIC.  */
    1217              : 
    1218              : void
    1219    103760250 : context::get_any_inlining_info (diagnostic_info *diagnostic)
    1220              : {
    1221    103760250 :   auto &ilocs = diagnostic->m_iinfo.m_ilocs;
    1222              : 
    1223    103760250 :   if (m_set_locations_cb)
    1224              :     /* Retrieve the locations into which the expression about to be
    1225              :        diagnosed has been inlined, including those of all the callers
    1226              :        all the way down the inlining stack.  */
    1227    103758683 :     m_set_locations_cb (*this, diagnostic);
    1228              :   else
    1229              :     {
    1230              :       /* When there's no callback use just the one location provided
    1231              :          by the caller of the diagnostic function.  */
    1232         1567 :       location_t loc = diagnostic_location (diagnostic);
    1233         1567 :       ilocs.safe_push (loc);
    1234         1567 :       diagnostic->m_iinfo.m_allsyslocs = in_system_header_at (loc);
    1235              :     }
    1236    103760250 : }
    1237              : 
    1238              : /* Generate a URL string describing CWE.  The caller is responsible for
    1239              :    freeing the string.  */
    1240              : 
    1241              : char *
    1242           28 : get_cwe_url (int cwe)
    1243              : {
    1244           28 :   return xasprintf ("https://cwe.mitre.org/data/definitions/%i.html", cwe);
    1245              : }
    1246              : 
    1247              : /* Returns whether a DIAGNOSTIC should be printed, and adjusts diagnostic->kind
    1248              :    as appropriate for #pragma GCC diagnostic and -Werror=foo.  */
    1249              : 
    1250              : bool
    1251    103760250 : context::diagnostic_enabled (diagnostic_info *diagnostic)
    1252              : {
    1253              :   /* Update the inlining stack for this diagnostic.  */
    1254    103760250 :   get_any_inlining_info (diagnostic);
    1255              : 
    1256              :   /* Diagnostics with no option or -fpermissive are always enabled.  */
    1257    103760250 :   if (!diagnostic->m_option_id.m_idx
    1258    103760250 :       || diagnostic->m_option_id == m_opt_permissive)
    1259              :     return true;
    1260              : 
    1261              :   /* This tests if the user provided the appropriate -Wfoo or
    1262              :      -Wno-foo option.  */
    1263    102289066 :   if (!option_enabled_p (diagnostic->m_option_id))
    1264              :     return false;
    1265              : 
    1266              :   /* This tests for #pragma diagnostic changes.  */
    1267      3076070 :   enum kind diag_class
    1268      3076070 :     = m_option_classifier.update_effective_level_from_pragmas (diagnostic);
    1269              : 
    1270              :   /* This tests if the user provided the appropriate -Werror=foo
    1271              :      option.  */
    1272      3076070 :   if (diag_class == kind::unspecified
    1273      4551169 :       && !option_unspecified_p (diagnostic->m_option_id))
    1274              :     {
    1275         9033 :       const enum kind new_kind
    1276         9033 :         = m_option_classifier.get_current_override (diagnostic->m_option_id);
    1277         9033 :       if (new_kind != kind::any)
    1278              :         /* kind::any means the diagnostic is not to be ignored, but we don't want
    1279              :            to change it specifically to kind::error or kind::warning; we want to
    1280              :            preserve whatever the caller has specified.  */
    1281         5892 :         diagnostic->m_kind = new_kind;
    1282              :     }
    1283              : 
    1284              :   /* This allows for future extensions, like temporarily disabling
    1285              :      warnings for ranges of source code.  */
    1286      3076070 :   if (diagnostic->m_kind == kind::ignored)
    1287              :     return false;
    1288              : 
    1289              :   return true;
    1290              : }
    1291              : 
    1292              : /* Returns whether warning OPT_ID is enabled at LOC.  */
    1293              : 
    1294              : bool
    1295      1299522 : context::warning_enabled_at (location_t loc,
    1296              :                              option_id opt_id)
    1297              : {
    1298      2588521 :   if (!diagnostic_report_warnings_p (this, loc))
    1299       103679 :     return false;
    1300              : 
    1301      1195843 :   rich_location richloc (line_table, loc);
    1302      1195843 :   diagnostic_info diagnostic = {};
    1303      1195843 :   diagnostic.m_option_id = opt_id;
    1304      1195843 :   diagnostic.m_richloc = &richloc;
    1305      1195843 :   diagnostic.m_message.m_richloc = &richloc;
    1306      1195843 :   diagnostic.m_kind = kind::warning;
    1307      1195843 :   return diagnostic_enabled (&diagnostic);
    1308      1195843 : }
    1309              : 
    1310              : /* Emit a diagnostic within a diagnostic group on this context.  */
    1311              : 
    1312              : bool
    1313            8 : context::emit_diagnostic_with_group (enum kind kind,
    1314              :                                      rich_location &richloc,
    1315              :                                      const metadata *metadata,
    1316              :                                      option_id opt_id,
    1317              :                                      const char *gmsgid, ...)
    1318              : {
    1319            8 :   begin_group ();
    1320              : 
    1321            8 :   va_list ap;
    1322            8 :   va_start (ap, gmsgid);
    1323            8 :   bool ret = emit_diagnostic_with_group_va (kind, richloc, metadata, opt_id,
    1324              :                                             gmsgid, &ap);
    1325            8 :   va_end (ap);
    1326              : 
    1327            8 :   end_group ();
    1328              : 
    1329            8 :   return ret;
    1330              : }
    1331              : 
    1332              : /* As above, but taking a va_list *.  */
    1333              : 
    1334              : bool
    1335            8 : context::emit_diagnostic_with_group_va (enum kind kind,
    1336              :                                         rich_location &richloc,
    1337              :                                         const metadata *metadata,
    1338              :                                         option_id opt_id,
    1339              :                                         const char *gmsgid, va_list *ap)
    1340              : {
    1341            8 :   begin_group ();
    1342              : 
    1343            8 :   bool ret = diagnostic_impl (&richloc, metadata, opt_id,
    1344              :                               gmsgid, ap, kind);
    1345              : 
    1346            8 :   end_group ();
    1347              : 
    1348            8 :   return ret;
    1349              : }
    1350              : 
    1351              : /* Report a diagnostic message (an error or a warning) as specified by
    1352              :    this diagnostics::context.
    1353              :    front-end independent format specifiers are exactly those described
    1354              :    in the documentation of output_format.
    1355              :    Return true if a diagnostic was printed, false otherwise.  */
    1356              : 
    1357              : bool
    1358    106515603 : context::report_diagnostic (diagnostic_info *diagnostic)
    1359              : {
    1360    106515603 :   auto logger = get_logger ();
    1361    106515603 :   DIAGNOSTICS_LOG_SCOPE_PRINTF0 (logger, "diagnostics::context::report_diagnostic");
    1362              : 
    1363    106515603 :   enum kind orig_diag_kind = diagnostic->m_kind;
    1364              : 
    1365              :   /* Every call to report_diagnostic should be within a
    1366              :      begin_group/end_group pair so that output formats can reliably
    1367              :      flush diagnostics with on_end_group when the topmost group is ended.  */
    1368    106515603 :   gcc_assert (m_diagnostic_groups.m_group_nesting_depth > 0);
    1369              : 
    1370              :   /* Give preference to being able to inhibit warnings, before they
    1371              :      get reclassified to something else.  */
    1372    106515603 :   bool was_warning = (diagnostic->m_kind == kind::warning
    1373    106515603 :                       || diagnostic->m_kind == kind::pedwarn);
    1374    106515603 :   if (was_warning && m_inhibit_warnings)
    1375              :     {
    1376      3951196 :       inhibit_notes_in_group ();
    1377      3951196 :       if (m_logger)
    1378            0 :         m_logger->log_printf ("rejecting: inhibiting warnings");
    1379      3951196 :       return false;
    1380              :     }
    1381              : 
    1382    102564407 :   if (m_adjust_diagnostic_info)
    1383     97004138 :     m_adjust_diagnostic_info (*this, diagnostic);
    1384              : 
    1385    102564407 :   if (diagnostic->m_kind == kind::pedwarn)
    1386              :     {
    1387       755225 :       diagnostic->m_kind = m_pedantic_errors ? kind::error : kind::warning;
    1388              : 
    1389              :       /* We do this to avoid giving the message for -pedantic-errors.  */
    1390       755225 :       orig_diag_kind = diagnostic->m_kind;
    1391              :     }
    1392              : 
    1393    102564407 :   if (diagnostic->m_kind == kind::note && m_inhibit_notes_p)
    1394              :     {
    1395            0 :       if (m_logger)
    1396            0 :         m_logger->log_printf ("rejecting: inhibiting notes");
    1397            0 :       return false;
    1398              :     }
    1399              : 
    1400              :   /* If the user requested that warnings be treated as errors, so be
    1401              :      it.  Note that we do this before the next block so that
    1402              :      individual warnings can be overridden back to warnings with
    1403              :      -Wno-error=*.  */
    1404    102564407 :   if (m_warning_as_error_requested
    1405       242542 :       && diagnostic->m_kind == kind::warning)
    1406       207315 :     diagnostic->m_kind = kind::error;
    1407              : 
    1408    102564407 :   diagnostic->m_message.m_data = &diagnostic->m_x_data;
    1409              : 
    1410              :   /* Check to see if the diagnostic is enabled at the location and
    1411              :      not disabled by #pragma GCC diagnostic anywhere along the inlining
    1412              :      stack.  .  */
    1413    102564407 :   if (!diagnostic_enabled (diagnostic))
    1414              :     {
    1415    100788022 :       if (m_logger)
    1416            0 :         m_logger->log_printf ("rejecting: diagnostic not enabled");
    1417    100788022 :       inhibit_notes_in_group ();
    1418    100788022 :       return false;
    1419              :     }
    1420              : 
    1421      1776385 :   if ((was_warning || diagnostic->m_kind == kind::warning)
    1422       331864 :       && ((!m_warn_system_headers
    1423       331525 :            && diagnostic->m_iinfo.m_allsyslocs)
    1424       116507 :           || m_inhibit_warnings))
    1425              :     {
    1426              :       /* Bail if the warning is not to be reported because all locations in the
    1427              :          inlining stack (if there is one) are in system headers.  */
    1428       215372 :       if (m_logger)
    1429            0 :         m_logger->log_printf ("rejecting: warning in system header");
    1430       215372 :       return false;
    1431              :     }
    1432              : 
    1433      1561013 :   if (diagnostic->m_kind == kind::note && notes_inhibited_in_group ())
    1434              :     {
    1435              :       /* Bail for all the notes in the diagnostic_group that started to inhibit notes.  */
    1436           17 :       if (m_logger)
    1437            0 :         m_logger->log_printf ("rejecting: notes inhibited within group");
    1438           17 :       return false;
    1439              :     }
    1440              : 
    1441      1560996 :   if (diagnostic->m_kind != kind::note && diagnostic->m_kind != kind::ice)
    1442      1449941 :     check_max_errors (false);
    1443              : 
    1444      1560992 :   if (m_lock > 0)
    1445              :     {
    1446              :       /* If we're reporting an ICE in the middle of some other error,
    1447              :          try to flush out the previous error, then let this one
    1448              :          through.  Don't do this more than once.  */
    1449            0 :       if ((diagnostic->m_kind == kind::ice
    1450            0 :            || diagnostic->m_kind == kind::ice_nobt)
    1451            0 :           && m_lock == 1)
    1452            0 :         pp_newline_and_flush (m_reference_printer);
    1453              :       else
    1454            0 :         error_recursion ();
    1455              :     }
    1456              : 
    1457              :   /* We are accepting the diagnostic, so should stop inhibiting notes.  */
    1458      1560992 :   inhibit_notes_in_group (/*inhibit=*/false);
    1459              : 
    1460      1560992 :   m_lock++;
    1461              : 
    1462      1560992 :   if (diagnostic->m_kind == kind::ice || diagnostic->m_kind == kind::ice_nobt)
    1463              :     {
    1464              :       /* When not checking, ICEs are converted to fatal errors when an
    1465              :          error has already occurred.  This is counteracted by
    1466              :          abort_on_error.  */
    1467           22 :       if (!CHECKING_P
    1468              :           && (diagnostic_count (kind::error) > 0
    1469              :               || diagnostic_count (kind::sorry) > 0)
    1470              :           && !m_abort_on_error)
    1471              :         {
    1472              :           expanded_location s
    1473              :             = expand_location (diagnostic_location (diagnostic));
    1474              :           fnotice (stderr, "%s:%d: confused by earlier errors, bailing out\n",
    1475              :                    s.file, s.line);
    1476              :           exit (ICE_EXIT_CODE);
    1477              :         }
    1478           22 :       if (m_internal_error)
    1479           22 :         (*m_internal_error) (this,
    1480              :                              diagnostic->m_message.m_format_spec,
    1481              :                              diagnostic->m_message.m_args_ptr);
    1482              :     }
    1483              : 
    1484              :   /* Increment the counter for the appropriate diagnostic kind, either
    1485              :      within this context, or within the diagnostic_buffer.  */
    1486      1560992 :   {
    1487      1560679 :     const enum kind kind_for_count =
    1488      1338853 :       ((diagnostic->m_kind == kind::error && orig_diag_kind == kind::warning)
    1489      1560992 :        ? kind::werror
    1490              :        : diagnostic->m_kind);
    1491      1560992 :     counters &cs
    1492      1560992 :       = (m_diagnostic_buffer
    1493              :          ? m_diagnostic_buffer->m_diagnostic_counters
    1494              :          : m_diagnostic_counters);
    1495      1560992 :     ++cs.m_count_for_kind[static_cast<size_t> (kind_for_count)];
    1496              :   }
    1497              : 
    1498              :   /* Is this the initial diagnostic within the stack of groups?  */
    1499      1560992 :   if (m_diagnostic_groups.m_emission_count == 0)
    1500              :     {
    1501      1463948 :       DIAGNOSTICS_LOG_SCOPE_PRINTF0
    1502              :         (get_logger (),
    1503      1463948 :          "diagnostics::context: beginning group");
    1504      5855889 :       for (auto sink_ : m_sinks)
    1505      1464045 :         sink_->on_begin_group ();
    1506      1560992 :     }
    1507      1560992 :   m_diagnostic_groups.m_emission_count++;
    1508              : 
    1509      1560992 :   va_list *orig_args = diagnostic->m_message.m_args_ptr;
    1510      6244197 :   for (auto sink_ : m_sinks)
    1511              :     {
    1512              :       /* Formatting the message is done per-output-format,
    1513              :          so that each output format gets its own set of pp_token_lists
    1514              :          to work with.
    1515              : 
    1516              :          Run phases 1 and 2 of formatting the message before calling
    1517              :          the format's on_report_diagnostic.
    1518              :          In particular, some format codes may have side-effects here which
    1519              :          need to happen before sending the diagnostic to the output format.
    1520              :          For example, Fortran's %C and %L formatting codes populate the
    1521              :          rich_location.
    1522              :          Such side-effects must be idempotent, since they are run per
    1523              :          output-format.
    1524              : 
    1525              :          Make a duplicate of the varargs for each call to pp_format,
    1526              :          so that each has its own set to consume.  */
    1527      1561222 :       va_list copied_args;
    1528      1561222 :       va_copy (copied_args, *orig_args);
    1529      1561222 :       diagnostic->m_message.m_args_ptr = &copied_args;
    1530      1561222 :       pp_format (sink_->get_printer (), &diagnostic->m_message);
    1531      1561222 :       va_end (copied_args);
    1532              : 
    1533              :       /* Call vfunc in the output format.  This is responsible for
    1534              :          phase 3 of formatting, and for printing the result.  */
    1535      1561222 :       sink_->on_report_diagnostic (*diagnostic, orig_diag_kind);
    1536              :     }
    1537              : 
    1538      1560991 :   const int tabstop = get_column_options ().m_tabstop;
    1539              : 
    1540      1560991 :   switch (m_extra_output_kind)
    1541              :     {
    1542              :     default:
    1543              :       break;
    1544           15 :     case EXTRA_DIAGNOSTIC_OUTPUT_fixits_v1:
    1545           15 :       print_parseable_fixits (get_file_cache (),
    1546              :                               m_reference_printer, diagnostic->m_richloc,
    1547              :                               DIAGNOSTICS_COLUMN_UNIT_BYTE,
    1548              :                               tabstop);
    1549           15 :       pp_flush (m_reference_printer);
    1550           15 :       break;
    1551            6 :     case EXTRA_DIAGNOSTIC_OUTPUT_fixits_v2:
    1552            6 :       print_parseable_fixits (get_file_cache (),
    1553              :                               m_reference_printer, diagnostic->m_richloc,
    1554              :                               DIAGNOSTICS_COLUMN_UNIT_DISPLAY,
    1555              :                               tabstop);
    1556            6 :       pp_flush (m_reference_printer);
    1557            6 :       break;
    1558              :     }
    1559      1560991 :   if (m_diagnostic_buffer == nullptr
    1560      1215350 :       || diagnostic->m_kind == kind::ice
    1561      1215350 :       || diagnostic->m_kind == kind::ice_nobt)
    1562       345641 :     action_after_output (diagnostic->m_kind);
    1563      1560276 :   diagnostic->m_x_data = nullptr;
    1564              : 
    1565      1560276 :   if (m_fixits_change_set)
    1566           60 :     if (diagnostic->m_richloc->fixits_can_be_auto_applied_p ())
    1567           58 :       if (!m_diagnostic_buffer)
    1568           58 :         m_fixits_change_set->add_fixits (diagnostic->m_richloc);
    1569              : 
    1570      1560276 :   m_lock--;
    1571              : 
    1572      1560276 :   if (!m_diagnostic_buffer)
    1573      1379928 :     for (auto sink_ : m_sinks)
    1574       345150 :       sink_->after_diagnostic (*diagnostic);
    1575              : 
    1576              :   return true;
    1577    106514883 : }
    1578              : 
    1579              : void
    1580            0 : context::report_verbatim (text_info &text)
    1581              : {
    1582            0 :   va_list *orig_args = text.m_args_ptr;
    1583            0 :   for (auto sink_ : m_sinks)
    1584              :     {
    1585            0 :       va_list copied_args;
    1586            0 :       va_copy (copied_args, *orig_args);
    1587            0 :       text.m_args_ptr = &copied_args;
    1588            0 :       sink_->on_report_verbatim (text);
    1589            0 :       va_end (copied_args);
    1590              :     }
    1591            0 : }
    1592              : 
    1593              : void
    1594            3 : context::report_global_digraph (const lazily_created<digraphs::digraph> &ldg)
    1595              : {
    1596           14 :   for (auto sink_ : m_sinks)
    1597            5 :     sink_->report_global_digraph (ldg);
    1598            3 : }
    1599              : 
    1600              : /* Get the number of digits in the decimal representation of VALUE.  */
    1601              : 
    1602              : int
    1603        75085 : num_digits (uint64_t value)
    1604              : {
    1605              :   /* Perhaps simpler to use log10 for this, but doing it this way avoids
    1606              :      using floating point.  */
    1607              : 
    1608        75085 :   if (value == 0)
    1609              :     return 1;
    1610              : 
    1611              :   int digits = 0;
    1612       236830 :   while (value > 0)
    1613              :     {
    1614       161762 :       digits++;
    1615       161762 :       value /= 10;
    1616              :     }
    1617              :   return digits;
    1618              : }
    1619              : 
    1620              : } // namespace diagnostics
    1621              : 
    1622              : /* Given a partial pathname as input, return another pathname that
    1623              :    shares no directory elements with the pathname of __FILE__.  This
    1624              :    is used by fancy_abort() to print `internal compiler error in expr.cc'
    1625              :    instead of `internal compiler error in ../../GCC/gcc/expr.cc'.  */
    1626              : 
    1627              : const char *
    1628            8 : trim_filename (const char *name)
    1629              : {
    1630            8 :   static const char this_file[] = __FILE__;
    1631            8 :   const char *p = name, *q = this_file;
    1632              : 
    1633              :   /* First skip any "../" in each filename.  This allows us to give a proper
    1634              :      reference to a file in a subdirectory.  */
    1635            8 :   while (p[0] == '.' && p[1] == '.' && IS_DIR_SEPARATOR (p[2]))
    1636            0 :     p += 3;
    1637              : 
    1638              :   while (q[0] == '.' && q[1] == '.' && IS_DIR_SEPARATOR (q[2]))
    1639              :     q += 3;
    1640              : 
    1641              :   /* Now skip any parts the two filenames have in common.  */
    1642          376 :   while (*p == *q && *p != 0 && *q != 0)
    1643          368 :     p++, q++;
    1644              : 
    1645              :   /* Now go backwards until the previous directory separator.  */
    1646            8 :   while (p > name && !IS_DIR_SEPARATOR (p[-1]))
    1647            0 :     p--;
    1648              : 
    1649            8 :   return p;
    1650              : }
    1651              : 
    1652              : namespace diagnostics {
    1653              : 
    1654              : /* Implement emit_diagnostic, inform, warning, warning_at, pedwarn,
    1655              :    permerror, error, error_at, error_at, sorry, fatal_error, internal_error,
    1656              :    and internal_error_no_backtrace, as documented and defined below.  */
    1657              : bool
    1658    101475981 : context::diagnostic_impl (rich_location *richloc,
    1659              :                           const metadata *metadata,
    1660              :                           option_id opt_id,
    1661              :                           const char *gmsgid,
    1662              :                           va_list *ap, enum kind kind)
    1663              : {
    1664    101475981 :   logging::log_function_params
    1665    101475981 :     (m_logger, "diagnostics::context::diagnostic_impl")
    1666    101475981 :     .log_param_option_id ("option_id", opt_id)
    1667    101475981 :     .log_param_kind ("kind", kind)
    1668    101475981 :     .log_param_string ("gmsgid", gmsgid);
    1669    101475981 :   logging::auto_inc_depth depth_sentinel (m_logger);
    1670              : 
    1671    101475981 :   diagnostic_info diagnostic;
    1672    101475981 :   if (kind == diagnostics::kind::permerror)
    1673              :     {
    1674        18269 :       diagnostic_set_info (&diagnostic, gmsgid, ap, richloc,
    1675        18269 :                            (m_permissive
    1676              :                             ? diagnostics::kind::warning
    1677              :                             : diagnostics::kind::error));
    1678        18269 :       diagnostic.m_option_id = (opt_id.m_idx != -1 ? opt_id : m_opt_permissive);
    1679              :     }
    1680              :   else
    1681              :     {
    1682    101457712 :       diagnostic_set_info (&diagnostic, gmsgid, ap, richloc, kind);
    1683    101457712 :       if (kind == diagnostics::kind::warning
    1684    101457712 :           || kind == diagnostics::kind::pedwarn)
    1685    101242161 :         diagnostic.m_option_id = opt_id;
    1686              :     }
    1687    101475981 :   diagnostic.m_metadata = metadata;
    1688              : 
    1689    101475981 :   bool ret = report_diagnostic (&diagnostic);
    1690    101475639 :   if (m_logger)
    1691            0 :     m_logger->log_bool_return ("diagnostics::context::diagnostic_impl", ret);
    1692    101475639 :   return ret;
    1693    101475639 : }
    1694              : 
    1695              : /* Implement inform_n, warning_n, and error_n, as documented and
    1696              :    defined below.  */
    1697              : bool
    1698        12711 : context::diagnostic_n_impl (rich_location *richloc,
    1699              :                             const metadata *metadata,
    1700              :                             option_id opt_id,
    1701              :                             unsigned HOST_WIDE_INT n,
    1702              :                             const char *singular_gmsgid,
    1703              :                             const char *plural_gmsgid,
    1704              :                             va_list *ap, enum kind kind)
    1705              : {
    1706        12711 :   logging::log_function_params
    1707        12711 :     (m_logger, "diagnostics::context::diagnostic_n_impl")
    1708        12711 :     .log_param_option_id ("option_id", opt_id)
    1709        12711 :     .log_param_kind ("kind", kind)
    1710        12711 :     .log_params_n_gmsgids (n, singular_gmsgid, plural_gmsgid);
    1711        12711 :   logging::auto_inc_depth depth_sentinel (m_logger);
    1712              : 
    1713        12711 :   diagnostic_info diagnostic;
    1714        12711 :   unsigned long gtn;
    1715              : 
    1716        12711 :   if (sizeof n <= sizeof gtn)
    1717        12711 :     gtn = n;
    1718              :   else
    1719              :     /* Use the largest number ngettext can handle, otherwise
    1720              :        preserve the six least significant decimal digits for
    1721              :        languages where the plural form depends on them.  */
    1722              :     gtn = n <= ULONG_MAX ? n : n % 1000000LU + 1000000LU;
    1723              : 
    1724        12711 :   const char *text = ngettext (singular_gmsgid, plural_gmsgid, gtn);
    1725        12711 :   diagnostic_set_info_translated (&diagnostic, text, ap, richloc, kind);
    1726        12711 :   if (kind == diagnostics::kind::warning)
    1727         4499 :     diagnostic.m_option_id = opt_id;
    1728        12711 :   diagnostic.m_metadata = metadata;
    1729              : 
    1730        12711 :   bool ret = report_diagnostic (&diagnostic);
    1731        12711 :   if (m_logger)
    1732            0 :     m_logger->log_bool_return ("diagnostics::context::diagnostic_n_impl", ret);
    1733        12711 :   return ret;
    1734        12711 : }
    1735              : 
    1736              : 
    1737              : /* Emit DIAGRAM to this context, respecting the output format.  */
    1738              : 
    1739              : void
    1740           86 : context::emit_diagram (const diagram &diag)
    1741              : {
    1742           86 :   if (m_diagrams.m_theme == nullptr)
    1743              :     return;
    1744              : 
    1745          336 :   for (auto sink_ : m_sinks)
    1746           84 :     sink_->on_diagram (diag);
    1747              : }
    1748              : 
    1749              : /* Inform the user that an error occurred while trying to report some
    1750              :    other error.  This indicates catastrophic internal inconsistencies,
    1751              :    so give up now.  But do try to flush out the previous error.
    1752              :    This mustn't use internal_error, that will cause infinite recursion.  */
    1753              : 
    1754              : void
    1755            0 : context::error_recursion ()
    1756              : {
    1757            0 :   if (m_lock < 3)
    1758            0 :     pp_newline_and_flush (m_reference_printer);
    1759              : 
    1760            0 :   fnotice (stderr,
    1761              :            "internal compiler error: error reporting routines re-entered.\n");
    1762              : 
    1763              :   /* Call action_after_output to get the "please submit a bug report"
    1764              :      message.  */
    1765            0 :   action_after_output (kind::ice);
    1766              : 
    1767              :   /* Do not use gcc_unreachable here; that goes through internal_error
    1768              :      and therefore would cause infinite recursion.  */
    1769            0 :   real_abort ();
    1770              : }
    1771              : 
    1772              : } // namespace diagnostics
    1773              : 
    1774              : /* Report an internal compiler error in a friendly manner.  This is
    1775              :    the function that gets called upon use of abort() in the source
    1776              :    code generally, thanks to a special macro.  */
    1777              : 
    1778              : void
    1779            8 : fancy_abort (const char *file, int line, const char *function)
    1780              : {
    1781              :   /* If fancy_abort is called before the diagnostic subsystem is initialized,
    1782              :      internal_error will crash internally in a way that prevents a
    1783              :      useful message reaching the user.
    1784              :      This can happen with libgccjit in the case of gcc_assert failures
    1785              :      that occur outside of the libgccjit mutex that guards the rest of
    1786              :      gcc's state, including global_dc (when global_dc may not be
    1787              :      initialized yet, or might be in use by another thread).
    1788              :      Handle such cases as gracefully as possible by falling back to a
    1789              :      minimal abort handler that only relies on i18n.  */
    1790            8 :   if (global_dc->get_reference_printer () == nullptr)
    1791              :     {
    1792              :       /* Print the error message.  */
    1793            0 :       fnotice (stderr, diagnostics::get_text_for_kind (diagnostics::kind::ice));
    1794            0 :       fnotice (stderr, "in %s, at %s:%d", function, trim_filename (file), line);
    1795            0 :       fputc ('\n', stderr);
    1796              : 
    1797              :       /* Attempt to print a backtrace.  */
    1798            0 :       struct backtrace_state *state
    1799            0 :         = backtrace_create_state (nullptr, 0, bt_err_callback, nullptr);
    1800            0 :       int count = 0;
    1801            0 :       if (state != nullptr)
    1802            0 :         backtrace_full (state, 2, bt_callback, bt_err_callback,
    1803              :                         (void *) &count);
    1804              : 
    1805              :       /* We can't call warn_if_plugins or emergency_dump_function as these
    1806              :          rely on GCC state that might not be initialized, or might be in
    1807              :          use by another thread.  */
    1808              : 
    1809              :       /* Abort the process.  */
    1810            0 :       real_abort ();
    1811              :     }
    1812              : 
    1813            8 :   internal_error ("in %s, at %s:%d", function, trim_filename (file), line);
    1814              : }
    1815              : 
    1816              : namespace diagnostics {
    1817              : 
    1818              : /* class diagnostics::context.  */
    1819              : 
    1820              : void
    1821    901550316 : context::begin_group ()
    1822              : {
    1823    901550316 :   m_diagnostic_groups.m_group_nesting_depth++;
    1824    901550316 : }
    1825              : 
    1826              : void
    1827    901550311 : context::end_group ()
    1828              : {
    1829    901550311 :   if (--m_diagnostic_groups.m_group_nesting_depth == 0)
    1830              :     {
    1831              :       /* Handle the case where we've popped the final diagnostic group.
    1832              :          If any diagnostics were emitted, give the context a chance
    1833              :          to do something.  */
    1834    899503800 :       if (m_diagnostic_groups.m_emission_count > 0)
    1835              :         {
    1836      1463947 :           DIAGNOSTICS_LOG_SCOPE_PRINTF0
    1837              :             (get_logger (),
    1838      1463947 :              "diagnostics::context::end_group: ending group");
    1839      5855885 :           for (auto sink_ : m_sinks)
    1840      1464044 :             sink_->on_end_group ();
    1841    899503800 :         }
    1842    899503800 :       m_diagnostic_groups.m_emission_count = 0;
    1843              :     }
    1844              :   /* We're popping one level, so might need to stop inhibiting notes.  */
    1845    901550311 :   inhibit_notes_in_group (/*inhibit=*/false);
    1846    901550311 : }
    1847              : 
    1848              : void
    1849        29799 : context::push_nesting_level ()
    1850              : {
    1851        29799 :   ++m_diagnostic_groups.m_diagnostic_nesting_level;
    1852        29799 : }
    1853              : 
    1854              : void
    1855        29797 : context::pop_nesting_level ()
    1856              : {
    1857        29797 :   --m_diagnostic_groups.m_diagnostic_nesting_level;
    1858              :   /* We're popping one level, so might need to stop inhibiting notes.  */
    1859        29797 :   inhibit_notes_in_group (/*inhibit=*/false);
    1860        29797 : }
    1861              : 
    1862              : void
    1863            0 : context::set_nesting_level (int new_level)
    1864              : {
    1865            0 :   m_diagnostic_groups.m_diagnostic_nesting_level = new_level;
    1866            0 : }
    1867              : 
    1868              : void
    1869            0 : sink::dump (FILE *out, int indent) const
    1870              : {
    1871            0 :   dumping::emit_heading (out, indent, "printer");
    1872            0 :   m_printer->dump (out, indent + 2);
    1873              : 
    1874            0 :   dumping::emit_heading (out, indent, "extensions");
    1875            0 :   if (m_extensions.empty ())
    1876            0 :     dumping::emit_none (out, indent + 2);
    1877              :   else
    1878            0 :     for (auto &ext : m_extensions)
    1879            0 :       ext->dump (out, indent + 2);
    1880            0 : }
    1881              : 
    1882              : void
    1883       305137 : sink::finalize_extensions ()
    1884              : {
    1885       305139 :   for (auto &ext : m_extensions)
    1886            2 :     ext->finalize ();
    1887       305137 : }
    1888              : 
    1889              : void
    1890            0 : sink::on_report_verbatim (text_info &)
    1891              : {
    1892              :   /* No-op.  */
    1893            0 : }
    1894              : 
    1895              : /* Set the output format for DC to FORMAT, using BASE_FILE_NAME for
    1896              :    file-based output formats.  */
    1897              : 
    1898              : void
    1899           90 : output_format_init (context &dc,
    1900              :                     const char *main_input_filename_,
    1901              :                     const char *base_file_name,
    1902              :                     enum diagnostics_output_format format,
    1903              :                     bool json_formatting)
    1904              : {
    1905           90 :   sink *new_sink = nullptr;
    1906           90 :   switch (format)
    1907              :     {
    1908            0 :     default:
    1909            0 :       gcc_unreachable ();
    1910              :     case DIAGNOSTICS_OUTPUT_FORMAT_TEXT:
    1911              :       /* The default; do nothing.  */
    1912              :       break;
    1913              : 
    1914            0 :     case DIAGNOSTICS_OUTPUT_FORMAT_SARIF_STDERR:
    1915            0 :       new_sink = &init_sarif_stderr (dc,
    1916              :                                      line_table,
    1917              :                                      json_formatting);
    1918            0 :       break;
    1919              : 
    1920           90 :     case DIAGNOSTICS_OUTPUT_FORMAT_SARIF_FILE:
    1921           90 :       new_sink = &init_sarif_file (dc,
    1922              :                                    line_table,
    1923              :                                    json_formatting,
    1924              :                                    base_file_name);
    1925           90 :       break;
    1926              :     }
    1927           90 :   if (new_sink)
    1928           90 :     new_sink->set_main_input_filename (main_input_filename_);
    1929           90 : }
    1930              : 
    1931              : /* Initialize this context's m_diagrams based on CHARSET.
    1932              :    Specifically, make a text_art::theme object for m_diagrams.m_theme,
    1933              :    (or nullptr for "no diagrams").  */
    1934              : 
    1935              : void
    1936      1583947 : context::set_text_art_charset (enum diagnostic_text_art_charset charset)
    1937              : {
    1938      1583947 :   delete m_diagrams.m_theme;
    1939      1583947 :   switch (charset)
    1940              :     {
    1941            0 :     default:
    1942            0 :       gcc_unreachable ();
    1943              : 
    1944       877025 :     case DIAGNOSTICS_TEXT_ART_CHARSET_NONE:
    1945       877025 :       m_diagrams.m_theme = nullptr;
    1946       877025 :       break;
    1947              : 
    1948       621624 :     case DIAGNOSTICS_TEXT_ART_CHARSET_ASCII:
    1949       621624 :       m_diagrams.m_theme = new text_art::ascii_theme ();
    1950       621624 :       break;
    1951              : 
    1952          295 :     case DIAGNOSTICS_TEXT_ART_CHARSET_UNICODE:
    1953          295 :       m_diagrams.m_theme = new text_art::unicode_theme ();
    1954          295 :       break;
    1955              : 
    1956        85003 :     case DIAGNOSTICS_TEXT_ART_CHARSET_EMOJI:
    1957        85003 :       m_diagrams.m_theme = new text_art::emoji_theme ();
    1958        85003 :       break;
    1959              :     }
    1960      1583947 : }
    1961              : 
    1962              : /* struct diagnostics::counters.  */
    1963              : 
    1964      9240906 : counters::counters ()
    1965              : {
    1966      9240906 :   clear ();
    1967      9240906 : }
    1968              : 
    1969              : void
    1970            0 : counters::dump (FILE *out, int indent) const
    1971              : {
    1972            0 :   dumping::emit_heading (out, indent, "counts");
    1973            0 :   bool none = true;
    1974            0 :   for (int i = 0; i < static_cast<int> (kind::last_diagnostic_kind); i++)
    1975            0 :     if (m_count_for_kind[i] > 0)
    1976              :       {
    1977            0 :         dumping::emit_indent (out, indent + 2);
    1978            0 :         fprintf (out, "%s%i\n",
    1979              :                  get_text_for_kind (static_cast<enum kind> (i)),
    1980            0 :                  m_count_for_kind[i]);
    1981            0 :         none = false;
    1982              :       }
    1983            0 :   if (none)
    1984            0 :     dumping::emit_none (out, indent + 2);
    1985            0 : }
    1986              : 
    1987              : void
    1988       113293 : counters::move_to (counters &dest)
    1989              : {
    1990      1812688 :   for (int i = 0; i < static_cast<int> (kind::last_diagnostic_kind); i++)
    1991      1699395 :     dest.m_count_for_kind[i] += m_count_for_kind[i];
    1992       113293 :   clear ();
    1993       113293 : }
    1994              : 
    1995              : void
    1996     33320391 : counters::clear ()
    1997              : {
    1998     33320391 :   memset (&m_count_for_kind, 0, sizeof m_count_for_kind);
    1999     33320391 : }
    2000              : 
    2001              : #if CHECKING_P
    2002              : 
    2003              : namespace selftest {
    2004              : 
    2005              : using line_table_test = ::selftest::line_table_test;
    2006              : using temp_source_file = ::selftest::temp_source_file;
    2007              : 
    2008              : /* Helper function for test_print_escaped_string.  */
    2009              : 
    2010              : static void
    2011           24 : assert_print_escaped_string (const ::selftest::location &loc,
    2012              :                              const char *expected_output,
    2013              :                              const char *input)
    2014              : {
    2015           24 :   pretty_printer pp;
    2016           24 :   print_escaped_string (&pp, input);
    2017           24 :   ASSERT_STREQ_AT (loc, expected_output, pp_formatted_text (&pp));
    2018           24 : }
    2019              : 
    2020              : #define ASSERT_PRINT_ESCAPED_STRING_STREQ(EXPECTED_OUTPUT, INPUT) \
    2021              :     assert_print_escaped_string (SELFTEST_LOCATION, EXPECTED_OUTPUT, INPUT)
    2022              : 
    2023              : /* Tests of print_escaped_string.  */
    2024              : 
    2025              : static void
    2026            3 : test_print_escaped_string ()
    2027              : {
    2028              :   /* Empty string.  */
    2029            3 :   ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"\"", "");
    2030              : 
    2031              :   /* Non-empty string.  */
    2032            3 :   ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"hello world\"", "hello world");
    2033              : 
    2034              :   /* Various things that need to be escaped:  */
    2035              :   /* Backslash.  */
    2036            3 :   ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"before\\\\after\"",
    2037              :                                      "before\\after");
    2038              :   /* Tab.  */
    2039            3 :   ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"before\\tafter\"",
    2040              :                                      "before\tafter");
    2041              :   /* Newline.  */
    2042            3 :   ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"before\\nafter\"",
    2043              :                                      "before\nafter");
    2044              :   /* Double quote.  */
    2045            3 :   ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"before\\\"after\"",
    2046              :                                      "before\"after");
    2047              : 
    2048              :   /* Non-printable characters: BEL: '\a': 0x07 */
    2049            3 :   ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"before\\007after\"",
    2050              :                                      "before\aafter");
    2051              :   /* Non-printable characters: vertical tab: '\v': 0x0b */
    2052            3 :   ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"before\\013after\"",
    2053              :                                      "before\vafter");
    2054            3 : }
    2055              : 
    2056              : /* Tests of print_parseable_fixits.  */
    2057              : 
    2058              : /* Verify that print_parseable_fixits emits the empty string if there
    2059              :    are no fixits.  */
    2060              : 
    2061              : static void
    2062            3 : test_print_parseable_fixits_none ()
    2063              : {
    2064            3 :   pretty_printer pp;
    2065            3 :   file_cache fc;
    2066            3 :   rich_location richloc (line_table, UNKNOWN_LOCATION);
    2067              : 
    2068            3 :   print_parseable_fixits (fc, &pp, &richloc, DIAGNOSTICS_COLUMN_UNIT_BYTE, 8);
    2069            3 :   ASSERT_STREQ ("", pp_formatted_text (&pp));
    2070            3 : }
    2071              : 
    2072              : /* Verify that print_parseable_fixits does the right thing if there
    2073              :    is an insertion fixit hint.  */
    2074              : 
    2075              : static void
    2076            3 : test_print_parseable_fixits_insert ()
    2077              : {
    2078            3 :   pretty_printer pp;
    2079            3 :   file_cache fc;
    2080            3 :   rich_location richloc (line_table, UNKNOWN_LOCATION);
    2081              : 
    2082            3 :   linemap_add (line_table, LC_ENTER, false, "test.c", 0);
    2083            3 :   linemap_line_start (line_table, 5, 100);
    2084            3 :   linemap_add (line_table, LC_LEAVE, false, nullptr, 0);
    2085            3 :   location_t where = linemap_position_for_column (line_table, 10);
    2086            3 :   richloc.add_fixit_insert_before (where, "added content");
    2087              : 
    2088            3 :   print_parseable_fixits (fc, &pp, &richloc, DIAGNOSTICS_COLUMN_UNIT_BYTE, 8);
    2089            3 :   ASSERT_STREQ ("fix-it:\"test.c\":{5:10-5:10}:\"added content\"\n",
    2090              :                 pp_formatted_text (&pp));
    2091            3 : }
    2092              : 
    2093              : /* Verify that print_parseable_fixits does the right thing if there
    2094              :    is an removal fixit hint.  */
    2095              : 
    2096              : static void
    2097            3 : test_print_parseable_fixits_remove ()
    2098              : {
    2099            3 :   pretty_printer pp;
    2100            3 :   file_cache fc;
    2101            3 :   rich_location richloc (line_table, UNKNOWN_LOCATION);
    2102              : 
    2103            3 :   linemap_add (line_table, LC_ENTER, false, "test.c", 0);
    2104            3 :   linemap_line_start (line_table, 5, 100);
    2105            3 :   linemap_add (line_table, LC_LEAVE, false, nullptr, 0);
    2106            3 :   source_range where;
    2107            3 :   where.m_start = linemap_position_for_column (line_table, 10);
    2108            3 :   where.m_finish = linemap_position_for_column (line_table, 20);
    2109            3 :   richloc.add_fixit_remove (where);
    2110              : 
    2111            3 :   print_parseable_fixits (fc, &pp, &richloc, DIAGNOSTICS_COLUMN_UNIT_BYTE, 8);
    2112            3 :   ASSERT_STREQ ("fix-it:\"test.c\":{5:10-5:21}:\"\"\n",
    2113              :                 pp_formatted_text (&pp));
    2114            3 : }
    2115              : 
    2116              : /* Verify that print_parseable_fixits does the right thing if there
    2117              :    is an replacement fixit hint.  */
    2118              : 
    2119              : static void
    2120            3 : test_print_parseable_fixits_replace ()
    2121              : {
    2122            3 :   pretty_printer pp;
    2123            3 :   file_cache fc;
    2124            3 :   rich_location richloc (line_table, UNKNOWN_LOCATION);
    2125              : 
    2126            3 :   linemap_add (line_table, LC_ENTER, false, "test.c", 0);
    2127            3 :   linemap_line_start (line_table, 5, 100);
    2128            3 :   linemap_add (line_table, LC_LEAVE, false, nullptr, 0);
    2129            3 :   source_range where;
    2130            3 :   where.m_start = linemap_position_for_column (line_table, 10);
    2131            3 :   where.m_finish = linemap_position_for_column (line_table, 20);
    2132            3 :   richloc.add_fixit_replace (where, "replacement");
    2133              : 
    2134            3 :   print_parseable_fixits (fc, &pp, &richloc, DIAGNOSTICS_COLUMN_UNIT_BYTE, 8);
    2135            3 :   ASSERT_STREQ ("fix-it:\"test.c\":{5:10-5:21}:\"replacement\"\n",
    2136              :                 pp_formatted_text (&pp));
    2137            3 : }
    2138              : 
    2139              : /* Verify that print_parseable_fixits correctly handles
    2140              :    DIAGNOSTICS_COLUMN_UNIT_BYTE vs DIAGNOSTICS_COLUMN_UNIT_COLUMN.  */
    2141              : 
    2142              : static void
    2143            3 : test_print_parseable_fixits_bytes_vs_display_columns ()
    2144              : {
    2145            3 :   line_table_test ltt;
    2146            3 :   rich_location richloc (line_table, UNKNOWN_LOCATION);
    2147              : 
    2148              :   /* 1-based byte offsets:     12345677778888999900001234567.  */
    2149            3 :   const char *const content = "smile \xf0\x9f\x98\x82 colour\n";
    2150              :   /* 1-based display cols:     123456[......7-8.....]9012345.  */
    2151            3 :   const int tabstop = 8;
    2152              : 
    2153            3 :   temp_source_file tmp (SELFTEST_LOCATION, ".c", content);
    2154            3 :   file_cache fc;
    2155            3 :   const char *const fname = tmp.get_filename ();
    2156              : 
    2157            3 :   linemap_add (line_table, LC_ENTER, false, fname, 0);
    2158            3 :   linemap_line_start (line_table, 1, 100);
    2159            3 :   linemap_add (line_table, LC_LEAVE, false, nullptr, 0);
    2160            3 :   source_range where;
    2161            3 :   where.m_start = linemap_position_for_column (line_table, 12);
    2162            3 :   where.m_finish = linemap_position_for_column (line_table, 17);
    2163            3 :   richloc.add_fixit_replace (where, "color");
    2164              : 
    2165              :   /* Escape fname.  */
    2166            3 :   pretty_printer tmp_pp;
    2167            3 :   print_escaped_string (&tmp_pp, fname);
    2168            3 :   char *escaped_fname = xstrdup (pp_formatted_text (&tmp_pp));
    2169              : 
    2170            3 :   const int buf_len = strlen (escaped_fname) + 100;
    2171            3 :   char *const expected = XNEWVEC (char, buf_len);
    2172              : 
    2173            3 :   {
    2174            3 :     pretty_printer pp;
    2175            3 :     print_parseable_fixits (fc, &pp, &richloc,
    2176              :                             DIAGNOSTICS_COLUMN_UNIT_BYTE,
    2177              :                             tabstop);
    2178            3 :     snprintf (expected, buf_len,
    2179              :               "fix-it:%s:{1:12-1:18}:\"color\"\n", escaped_fname);
    2180            3 :     ASSERT_STREQ (expected, pp_formatted_text (&pp));
    2181            3 :   }
    2182            3 :   {
    2183            3 :     pretty_printer pp;
    2184            3 :     print_parseable_fixits (fc, &pp, &richloc,
    2185              :                             DIAGNOSTICS_COLUMN_UNIT_DISPLAY,
    2186              :                             tabstop);
    2187            3 :     snprintf (expected, buf_len,
    2188              :               "fix-it:%s:{1:10-1:16}:\"color\"\n", escaped_fname);
    2189            3 :     ASSERT_STREQ (expected, pp_formatted_text (&pp));
    2190            3 :   }
    2191              : 
    2192            3 :   XDELETEVEC (expected);
    2193            3 :   free (escaped_fname);
    2194            3 : }
    2195              : 
    2196              : /* Verify that
    2197              :      diagnostics::column_policy::get_location_text (..., SHOW_COLUMN, ...)
    2198              :    generates EXPECTED_LOC_TEXT, given FILENAME, LINE, COLUMN, with
    2199              :    colorization disabled.  */
    2200              : 
    2201              : static void
    2202           42 : assert_location_text (const char *expected_loc_text,
    2203              :                       const char *filename, int line, int column,
    2204              :                       bool show_column,
    2205              :                       int origin = 1,
    2206              :                       enum diagnostics_column_unit column_unit
    2207              :                         = DIAGNOSTICS_COLUMN_UNIT_BYTE)
    2208              : {
    2209           42 :   diagnostics::selftest::test_context dc;
    2210           42 :   dc.get_column_options ().m_column_unit = column_unit;
    2211           42 :   dc.get_column_options ().m_column_origin = origin;
    2212              : 
    2213           42 :   expanded_location xloc;
    2214           42 :   xloc.file = filename;
    2215           42 :   xloc.line = line;
    2216           42 :   xloc.column = column;
    2217           42 :   xloc.data = nullptr;
    2218           42 :   xloc.sysp = false;
    2219              : 
    2220           42 :   diagnostics::column_policy column_policy (dc);
    2221           42 :   label_text actual_loc_text
    2222           42 :     = column_policy.get_location_text (xloc, show_column, false);
    2223           42 :   ASSERT_STREQ (expected_loc_text, actual_loc_text.get ());
    2224           42 : }
    2225              : 
    2226              : /* Verify that get_location_text works as expected.  */
    2227              : 
    2228              : static void
    2229            3 : test_get_location_text ()
    2230              : {
    2231            3 :   const char *old_progname = progname;
    2232            3 :   progname = "PROGNAME";
    2233            3 :   assert_location_text ("PROGNAME:", nullptr, 0, 0, true);
    2234            3 :   char *built_in_colon = concat (special_fname_builtin (), ":", (char *) 0);
    2235            3 :   assert_location_text (built_in_colon, special_fname_builtin (),
    2236              :                         42, 10, true);
    2237            3 :   free (built_in_colon);
    2238            3 :   assert_location_text ("foo.c:42:10:", "foo.c", 42, 10, true);
    2239            3 :   assert_location_text ("foo.c:42:9:", "foo.c", 42, 10, true, 0);
    2240            3 :   assert_location_text ("foo.c:42:1010:", "foo.c", 42, 10, true, 1001);
    2241            9 :   for (int origin = 0; origin != 2; ++origin)
    2242            6 :     assert_location_text ("foo.c:42:", "foo.c", 42, 0, true, origin);
    2243            3 :   assert_location_text ("foo.c:", "foo.c", 0, 10, true);
    2244            3 :   assert_location_text ("foo.c:42:", "foo.c", 42, 10, false);
    2245            3 :   assert_location_text ("foo.c:", "foo.c", 0, 10, false);
    2246              : 
    2247            3 :   diagnostics::text_sink::maybe_line_and_column (INT_MAX, INT_MAX);
    2248            3 :   diagnostics::text_sink::maybe_line_and_column (INT_MIN, INT_MIN);
    2249              : 
    2250            3 :   {
    2251              :     /* In order to test display columns vs byte columns, we need to create a
    2252              :        file for location_get_source_line() to read.  */
    2253              : 
    2254            3 :     const char *const content = "smile \xf0\x9f\x98\x82\n";
    2255            3 :     const int line_bytes = strlen (content) - 1;
    2256            3 :     const int def_tabstop = 8;
    2257            3 :     const cpp_char_column_policy policy (def_tabstop, cpp_wcwidth);
    2258            3 :     const int display_width = cpp_display_width (content, line_bytes, policy);
    2259            3 :     ASSERT_EQ (line_bytes - 2, display_width);
    2260            3 :     temp_source_file tmp (SELFTEST_LOCATION, ".c", content);
    2261            3 :     const char *const fname = tmp.get_filename ();
    2262            3 :     const int buf_len = strlen (fname) + 16;
    2263            3 :     char *const expected = XNEWVEC (char, buf_len);
    2264              : 
    2265            3 :     snprintf (expected, buf_len, "%s:1:%d:", fname, line_bytes);
    2266            3 :     assert_location_text (expected, fname, 1, line_bytes, true,
    2267              :                           1, DIAGNOSTICS_COLUMN_UNIT_BYTE);
    2268              : 
    2269            3 :     snprintf (expected, buf_len, "%s:1:%d:", fname, line_bytes - 1);
    2270            3 :     assert_location_text (expected, fname, 1, line_bytes, true,
    2271              :                           0, DIAGNOSTICS_COLUMN_UNIT_BYTE);
    2272              : 
    2273            3 :     snprintf (expected, buf_len, "%s:1:%d:", fname, display_width);
    2274            3 :     assert_location_text (expected, fname, 1, line_bytes, true,
    2275              :                           1, DIAGNOSTICS_COLUMN_UNIT_DISPLAY);
    2276              : 
    2277            3 :     snprintf (expected, buf_len, "%s:1:%d:", fname, display_width - 1);
    2278            3 :     assert_location_text (expected, fname, 1, line_bytes, true,
    2279              :                           0, DIAGNOSTICS_COLUMN_UNIT_DISPLAY);
    2280              : 
    2281            3 :     XDELETEVEC (expected);
    2282            3 :   }
    2283              : 
    2284              : 
    2285            3 :   progname = old_progname;
    2286            3 : }
    2287              : 
    2288              : /* Selftest for num_digits.  */
    2289              : 
    2290              : static void
    2291            3 : test_num_digits ()
    2292              : {
    2293            3 :   ASSERT_EQ (1, num_digits (0));
    2294            3 :   ASSERT_EQ (1, num_digits (9));
    2295            3 :   ASSERT_EQ (2, num_digits (10));
    2296            3 :   ASSERT_EQ (2, num_digits (99));
    2297            3 :   ASSERT_EQ (3, num_digits (100));
    2298            3 :   ASSERT_EQ (3, num_digits (999));
    2299            3 :   ASSERT_EQ (4, num_digits (1000));
    2300            3 :   ASSERT_EQ (4, num_digits (9999));
    2301            3 :   ASSERT_EQ (5, num_digits (10000));
    2302            3 :   ASSERT_EQ (5, num_digits (99999));
    2303            3 :   ASSERT_EQ (6, num_digits (100000));
    2304            3 :   ASSERT_EQ (6, num_digits (999999));
    2305            3 :   ASSERT_EQ (7, num_digits (1000000));
    2306            3 :   ASSERT_EQ (7, num_digits (9999999));
    2307            3 :   ASSERT_EQ (8, num_digits (10000000));
    2308            3 :   ASSERT_EQ (8, num_digits (99999999));
    2309            3 :   ASSERT_EQ (20, num_digits (uint64_t (-1)));
    2310            3 : }
    2311              : 
    2312              : /* Run all of the selftests within this file.
    2313              : 
    2314              :    According to https://gcc.gnu.org/pipermail/gcc/2021-November/237703.html
    2315              :    there are some language-specific assumptions within these tests, so only
    2316              :    run them from C/C++.  */
    2317              : 
    2318              : void
    2319            3 : context_cc_tests ()
    2320              : {
    2321            3 :   test_print_escaped_string ();
    2322            3 :   test_print_parseable_fixits_none ();
    2323            3 :   test_print_parseable_fixits_insert ();
    2324            3 :   test_print_parseable_fixits_remove ();
    2325            3 :   test_print_parseable_fixits_replace ();
    2326            3 :   test_print_parseable_fixits_bytes_vs_display_columns ();
    2327            3 :   test_get_location_text ();
    2328            3 :   test_num_digits ();
    2329            3 : }
    2330              : 
    2331              : } // namespace diagnostics::selftest
    2332              : 
    2333              : #endif /* #if CHECKING_P */
    2334              : 
    2335              : } // namespace diagnostics
    2336              : 
    2337              : #if __GNUC__ >= 10
    2338              : #  pragma GCC diagnostic pop
    2339              : #endif
    2340              : 
    2341              : static void real_abort (void) ATTRIBUTE_NORETURN;
    2342              : 
    2343              : /* Really call the system 'abort'.  This has to go right at the end of
    2344              :    this file, so that there are no functions after it that call abort
    2345              :    and get the system abort instead of our macro.  */
    2346              : #undef abort
    2347              : static void
    2348            0 : real_abort (void)
    2349              : {
    2350            0 :   abort ();
    2351              : }
        

Generated by: LCOV version 2.4-beta

LCOV profile is generated on x86_64 machine using following configure options: configure --disable-bootstrap --enable-coverage=opt --enable-languages=c,c++,fortran,go,jit,lto,rust,m2 --enable-host-shared. GCC test suite is run with the built compiler.