xref: /dragonfly/contrib/gcc-8.0/gcc/diagnostic.c (revision dda92f98)
1 /* Language-independent diagnostic subroutines for the GNU Compiler Collection
2    Copyright (C) 1999-2018 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 #include "system.h"
27 #include "coretypes.h"
28 #include "version.h"
29 #include "demangle.h"
30 #include "intl.h"
31 #include "backtrace.h"
32 #include "diagnostic.h"
33 #include "diagnostic-color.h"
34 #include "edit-context.h"
35 #include "selftest.h"
36 #include "selftest-diagnostic.h"
37 
38 #ifdef HAVE_TERMIOS_H
39 # include <termios.h>
40 #endif
41 
42 #ifdef GWINSZ_IN_SYS_IOCTL
43 # include <sys/ioctl.h>
44 #endif
45 
46 #define pedantic_warning_kind(DC)			\
47   ((DC)->pedantic_errors ? DK_ERROR : DK_WARNING)
48 #define permissive_error_kind(DC) ((DC)->permissive ? DK_WARNING : DK_ERROR)
49 #define permissive_error_option(DC) ((DC)->opt_permissive)
50 
51 /* Prototypes.  */
52 static bool diagnostic_impl (rich_location *, int, const char *,
53 			     va_list *, diagnostic_t) ATTRIBUTE_GCC_DIAG(3,0);
54 static bool diagnostic_n_impl (rich_location *, int, unsigned HOST_WIDE_INT,
55 			       const char *, const char *, va_list *,
56 			       diagnostic_t) ATTRIBUTE_GCC_DIAG(5,0);
57 
58 static void error_recursion (diagnostic_context *) ATTRIBUTE_NORETURN;
59 static void real_abort (void) ATTRIBUTE_NORETURN;
60 
61 /* Name of program invoked, sans directories.  */
62 
63 const char *progname;
64 
65 /* A diagnostic_context surrogate for stderr.  */
66 static diagnostic_context global_diagnostic_context;
67 diagnostic_context *global_dc = &global_diagnostic_context;
68 
69 /* Return a malloc'd string containing MSG formatted a la printf.  The
70    caller is responsible for freeing the memory.  */
71 char *
72 build_message_string (const char *msg, ...)
73 {
74   char *str;
75   va_list ap;
76 
77   va_start (ap, msg);
78   str = xvasprintf (msg, ap);
79   va_end (ap);
80 
81   return str;
82 }
83 
84 /* Same as diagnostic_build_prefix, but only the source FILE is given.  */
85 char *
86 file_name_as_prefix (diagnostic_context *context, const char *f)
87 {
88   const char *locus_cs
89     = colorize_start (pp_show_color (context->printer), "locus");
90   const char *locus_ce = colorize_stop (pp_show_color (context->printer));
91   return build_message_string ("%s%s:%s ", locus_cs, f, locus_ce);
92 }
93 
94 
95 
96 /* Return the value of the getenv("COLUMNS") as an integer. If the
97    value is not set to a positive integer, use ioctl to get the
98    terminal width. If it fails, return INT_MAX.  */
99 int
100 get_terminal_width (void)
101 {
102   const char * s = getenv ("COLUMNS");
103   if (s != NULL) {
104     int n = atoi (s);
105     if (n > 0)
106       return n;
107   }
108 
109 #ifdef TIOCGWINSZ
110   struct winsize w;
111   w.ws_col = 0;
112   if (ioctl (0, TIOCGWINSZ, &w) == 0 && w.ws_col > 0)
113     return w.ws_col;
114 #endif
115 
116   return INT_MAX;
117 }
118 
119 /* Set caret_max_width to value.  */
120 void
121 diagnostic_set_caret_max_width (diagnostic_context *context, int value)
122 {
123   /* One minus to account for the leading empty space.  */
124   value = value ? value - 1
125     : (isatty (fileno (pp_buffer (context->printer)->stream))
126        ? get_terminal_width () - 1: INT_MAX);
127 
128   if (value <= 0)
129     value = INT_MAX;
130 
131   context->caret_max_width = value;
132 }
133 
134 /* Initialize the diagnostic message outputting machinery.  */
135 void
136 diagnostic_initialize (diagnostic_context *context, int n_opts)
137 {
138   int i;
139 
140   /* Allocate a basic pretty-printer.  Clients will replace this a
141      much more elaborated pretty-printer if they wish.  */
142   context->printer = XNEW (pretty_printer);
143   new (context->printer) pretty_printer ();
144 
145   memset (context->diagnostic_count, 0, sizeof context->diagnostic_count);
146   context->warning_as_error_requested = false;
147   context->n_opts = n_opts;
148   context->classify_diagnostic = XNEWVEC (diagnostic_t, n_opts);
149   for (i = 0; i < n_opts; i++)
150     context->classify_diagnostic[i] = DK_UNSPECIFIED;
151   context->show_caret = false;
152   diagnostic_set_caret_max_width (context, pp_line_cutoff (context->printer));
153   for (i = 0; i < rich_location::STATICALLY_ALLOCATED_RANGES; i++)
154     context->caret_chars[i] = '^';
155   context->show_option_requested = false;
156   context->abort_on_error = false;
157   context->show_column = false;
158   context->pedantic_errors = false;
159   context->permissive = false;
160   context->opt_permissive = 0;
161   context->fatal_errors = false;
162   context->dc_inhibit_warnings = false;
163   context->dc_warn_system_headers = false;
164   context->max_errors = 0;
165   context->internal_error = NULL;
166   diagnostic_starter (context) = default_diagnostic_starter;
167   context->start_span = default_diagnostic_start_span_fn;
168   diagnostic_finalizer (context) = default_diagnostic_finalizer;
169   context->option_enabled = NULL;
170   context->option_state = NULL;
171   context->option_name = NULL;
172   context->last_location = UNKNOWN_LOCATION;
173   context->last_module = 0;
174   context->x_data = NULL;
175   context->lock = 0;
176   context->inhibit_notes_p = false;
177   context->colorize_source_p = false;
178   context->show_ruler_p = false;
179   context->parseable_fixits_p = false;
180   context->edit_context_ptr = NULL;
181 }
182 
183 /* Maybe initialize the color support. We require clients to do this
184    explicitly, since most clients don't want color.  When called
185    without a VALUE, it initializes with DIAGNOSTICS_COLOR_DEFAULT.  */
186 
187 void
188 diagnostic_color_init (diagnostic_context *context, int value /*= -1 */)
189 {
190   /* value == -1 is the default value.  */
191   if (value < 0)
192     {
193       /* If DIAGNOSTICS_COLOR_DEFAULT is -1, default to
194 	 -fdiagnostics-color=auto if GCC_COLORS is in the environment,
195 	 otherwise default to -fdiagnostics-color=never, for other
196 	 values default to that
197 	 -fdiagnostics-color={never,auto,always}.  */
198       if (DIAGNOSTICS_COLOR_DEFAULT == -1)
199 	{
200 	  if (!getenv ("GCC_COLORS"))
201 	    return;
202 	  value = DIAGNOSTICS_COLOR_AUTO;
203 	}
204       else
205 	value = DIAGNOSTICS_COLOR_DEFAULT;
206     }
207   pp_show_color (context->printer)
208     = colorize_init ((diagnostic_color_rule_t) value);
209 }
210 
211 /* Do any cleaning up required after the last diagnostic is emitted.  */
212 
213 void
214 diagnostic_finish (diagnostic_context *context)
215 {
216   /* Some of the errors may actually have been warnings.  */
217   if (diagnostic_kind_count (context, DK_WERROR))
218     {
219       /* -Werror was given.  */
220       if (context->warning_as_error_requested)
221 	pp_verbatim (context->printer,
222 		     _("%s: all warnings being treated as errors"),
223 		     progname);
224       /* At least one -Werror= was given.  */
225       else
226 	pp_verbatim (context->printer,
227 		     _("%s: some warnings being treated as errors"),
228 		     progname);
229       pp_newline_and_flush (context->printer);
230     }
231 
232   diagnostic_file_cache_fini ();
233 
234   XDELETEVEC (context->classify_diagnostic);
235   context->classify_diagnostic = NULL;
236 
237   /* diagnostic_initialize allocates context->printer using XNEW
238      and placement-new.  */
239   context->printer->~pretty_printer ();
240   XDELETE (context->printer);
241   context->printer = NULL;
242 
243   if (context->edit_context_ptr)
244     {
245       delete context->edit_context_ptr;
246       context->edit_context_ptr = NULL;
247     }
248 }
249 
250 /* Initialize DIAGNOSTIC, where the message MSG has already been
251    translated.  */
252 void
253 diagnostic_set_info_translated (diagnostic_info *diagnostic, const char *msg,
254 				va_list *args, rich_location *richloc,
255 				diagnostic_t kind)
256 {
257   gcc_assert (richloc);
258   diagnostic->message.err_no = errno;
259   diagnostic->message.args_ptr = args;
260   diagnostic->message.format_spec = msg;
261   diagnostic->message.m_richloc = richloc;
262   diagnostic->richloc = richloc;
263   diagnostic->kind = kind;
264   diagnostic->option_index = 0;
265 }
266 
267 /* Initialize DIAGNOSTIC, where the message GMSGID has not yet been
268    translated.  */
269 void
270 diagnostic_set_info (diagnostic_info *diagnostic, const char *gmsgid,
271 		     va_list *args, rich_location *richloc,
272 		     diagnostic_t kind)
273 {
274   gcc_assert (richloc);
275   diagnostic_set_info_translated (diagnostic, _(gmsgid), args, richloc, kind);
276 }
277 
278 static const char *const diagnostic_kind_color[] = {
279 #define DEFINE_DIAGNOSTIC_KIND(K, T, C) (C),
280 #include "diagnostic.def"
281 #undef DEFINE_DIAGNOSTIC_KIND
282   NULL
283 };
284 
285 /* Get a color name for diagnostics of type KIND
286    Result could be NULL.  */
287 
288 const char *
289 diagnostic_get_color_for_kind (diagnostic_t kind)
290 {
291   return diagnostic_kind_color[kind];
292 }
293 
294 /* Return a formatted line and column ':%line:%column'.  Elided if
295    zero.  The result is a statically allocated buffer.  */
296 
297 static const char *
298 maybe_line_and_column (int line, int col)
299 {
300   static char result[32];
301 
302   if (line)
303     {
304       size_t l = snprintf (result, sizeof (result),
305 			   col ? ":%d:%d" : ":%d", line, col);
306       gcc_checking_assert (l < sizeof (result));
307     }
308   else
309     result[0] = 0;
310   return result;
311 }
312 
313 /* Return a malloc'd string describing a location e.g. "foo.c:42:10".
314    The caller is responsible for freeing the memory.  */
315 
316 static char *
317 diagnostic_get_location_text (diagnostic_context *context,
318 			      expanded_location s)
319 {
320   pretty_printer *pp = context->printer;
321   const char *locus_cs = colorize_start (pp_show_color (pp), "locus");
322   const char *locus_ce = colorize_stop (pp_show_color (pp));
323   const char *file = s.file ? s.file : progname;
324   int line = strcmp (file, N_("<built-in>")) ? s.line : 0;
325   int col = context->show_column ? s.column : 0;
326 
327   const char *line_col = maybe_line_and_column (line, col);
328   return build_message_string ("%s%s%s:%s", locus_cs, file,
329 			       line_col, locus_ce);
330 }
331 
332 /* Return a malloc'd string describing a location and the severity of the
333    diagnostic, e.g. "foo.c:42:10: error: ".  The caller is responsible for
334    freeing the memory.  */
335 char *
336 diagnostic_build_prefix (diagnostic_context *context,
337 			 const diagnostic_info *diagnostic)
338 {
339   static const char *const diagnostic_kind_text[] = {
340 #define DEFINE_DIAGNOSTIC_KIND(K, T, C) (T),
341 #include "diagnostic.def"
342 #undef DEFINE_DIAGNOSTIC_KIND
343     "must-not-happen"
344   };
345   gcc_assert (diagnostic->kind < DK_LAST_DIAGNOSTIC_KIND);
346 
347   const char *text = _(diagnostic_kind_text[diagnostic->kind]);
348   const char *text_cs = "", *text_ce = "";
349   pretty_printer *pp = context->printer;
350 
351   if (diagnostic_kind_color[diagnostic->kind])
352     {
353       text_cs = colorize_start (pp_show_color (pp),
354 				diagnostic_kind_color[diagnostic->kind]);
355       text_ce = colorize_stop (pp_show_color (pp));
356     }
357 
358   expanded_location s = diagnostic_expand_location (diagnostic);
359   char *location_text = diagnostic_get_location_text (context, s);
360 
361   char *result = build_message_string ("%s %s%s%s", location_text,
362 				       text_cs, text, text_ce);
363   free (location_text);
364   return result;
365 }
366 
367 /* Functions at which to stop the backtrace print.  It's not
368    particularly helpful to print the callers of these functions.  */
369 
370 static const char * const bt_stop[] =
371 {
372   "main",
373   "toplev::main",
374   "execute_one_pass",
375   "compile_file",
376 };
377 
378 /* A callback function passed to the backtrace_full function.  */
379 
380 static int
381 bt_callback (void *data, uintptr_t pc, const char *filename, int lineno,
382 	     const char *function)
383 {
384   int *pcount = (int *) data;
385 
386   /* If we don't have any useful information, don't print
387      anything.  */
388   if (filename == NULL && function == NULL)
389     return 0;
390 
391   /* Skip functions in diagnostic.c.  */
392   if (*pcount == 0
393       && filename != NULL
394       && strcmp (lbasename (filename), "diagnostic.c") == 0)
395     return 0;
396 
397   /* Print up to 20 functions.  We could make this a --param, but
398      since this is only for debugging just use a constant for now.  */
399   if (*pcount >= 20)
400     {
401       /* Returning a non-zero value stops the backtrace.  */
402       return 1;
403     }
404   ++*pcount;
405 
406   char *alc = NULL;
407   if (function != NULL)
408     {
409       char *str = cplus_demangle_v3 (function,
410 				     (DMGL_VERBOSE | DMGL_ANSI
411 				      | DMGL_GNU_V3 | DMGL_PARAMS));
412       if (str != NULL)
413 	{
414 	  alc = str;
415 	  function = str;
416 	}
417 
418       for (size_t i = 0; i < ARRAY_SIZE (bt_stop); ++i)
419 	{
420 	  size_t len = strlen (bt_stop[i]);
421 	  if (strncmp (function, bt_stop[i], len) == 0
422 	      && (function[len] == '\0' || function[len] == '('))
423 	    {
424 	      if (alc != NULL)
425 		free (alc);
426 	      /* Returning a non-zero value stops the backtrace.  */
427 	      return 1;
428 	    }
429 	}
430     }
431 
432   fprintf (stderr, "0x%lx %s\n\t%s:%d\n",
433 	   (unsigned long) pc,
434 	   function == NULL ? "???" : function,
435 	   filename == NULL ? "???" : filename,
436 	   lineno);
437 
438   if (alc != NULL)
439     free (alc);
440 
441   return 0;
442 }
443 
444 /* A callback function passed to the backtrace_full function.  This is
445    called if backtrace_full has an error.  */
446 
447 static void
448 bt_err_callback (void *data ATTRIBUTE_UNUSED, const char *msg, int errnum)
449 {
450   if (errnum < 0)
451     {
452       /* This means that no debug info was available.  Just quietly
453 	 skip printing backtrace info.  */
454       return;
455     }
456   fprintf (stderr, "%s%s%s\n", msg, errnum == 0 ? "" : ": ",
457 	   errnum == 0 ? "" : xstrerror (errnum));
458 }
459 
460 /* Check if we've met the maximum error limit, and if so fatally exit
461    with a message.  CONTEXT is the context to check, and FLUSH
462    indicates whether a diagnostic_finish call is needed.  */
463 
464 void
465 diagnostic_check_max_errors (diagnostic_context *context, bool flush)
466 {
467   if (!context->max_errors)
468     return;
469 
470   int count = (diagnostic_kind_count (context, DK_ERROR)
471 	       + diagnostic_kind_count (context, DK_SORRY)
472 	       + diagnostic_kind_count (context, DK_WERROR));
473 
474   if (count >= context->max_errors)
475     {
476       fnotice (stderr,
477 	       "compilation terminated due to -fmax-errors=%u.\n",
478 	       context->max_errors);
479       if (flush)
480 	diagnostic_finish (context);
481       exit (FATAL_EXIT_CODE);
482     }
483 }
484 
485 /* Take any action which is expected to happen after the diagnostic
486    is written out.  This function does not always return.  */
487 void
488 diagnostic_action_after_output (diagnostic_context *context,
489 				diagnostic_t diag_kind)
490 {
491   switch (diag_kind)
492     {
493     case DK_DEBUG:
494     case DK_NOTE:
495     case DK_ANACHRONISM:
496     case DK_WARNING:
497       break;
498 
499     case DK_ERROR:
500     case DK_SORRY:
501       if (context->abort_on_error)
502 	real_abort ();
503       if (context->fatal_errors)
504 	{
505 	  fnotice (stderr, "compilation terminated due to -Wfatal-errors.\n");
506 	  diagnostic_finish (context);
507 	  exit (FATAL_EXIT_CODE);
508 	}
509       break;
510 
511     case DK_ICE:
512     case DK_ICE_NOBT:
513       {
514 	struct backtrace_state *state = NULL;
515 	if (diag_kind == DK_ICE)
516 	  state = backtrace_create_state (NULL, 0, bt_err_callback, NULL);
517 	int count = 0;
518 	if (state != NULL)
519 	  backtrace_full (state, 2, bt_callback, bt_err_callback,
520 			  (void *) &count);
521 
522 	if (context->abort_on_error)
523 	  real_abort ();
524 
525 	fnotice (stderr, "Please submit a full bug report,\n"
526 		 "with preprocessed source if appropriate.\n");
527 	if (count > 0)
528 	  fnotice (stderr,
529 		   ("Please include the complete backtrace "
530 		    "with any bug report.\n"));
531 	fnotice (stderr, "See %s for instructions.\n", bug_report_url);
532 
533 	exit (ICE_EXIT_CODE);
534       }
535 
536     case DK_FATAL:
537       if (context->abort_on_error)
538 	real_abort ();
539       diagnostic_finish (context);
540       fnotice (stderr, "compilation terminated.\n");
541       exit (FATAL_EXIT_CODE);
542 
543     default:
544       gcc_unreachable ();
545     }
546 }
547 
548 /* True if the last module or file in which a diagnostic was reported is
549    different from the current one.  */
550 
551 static bool
552 last_module_changed_p (diagnostic_context *context,
553 		       const line_map_ordinary *map)
554 {
555   return context->last_module != map;
556 }
557 
558 /* Remember the current module or file as being the last one in which we
559    report a diagnostic.  */
560 
561 static void
562 set_last_module (diagnostic_context *context, const line_map_ordinary *map)
563 {
564   context->last_module = map;
565 }
566 
567 void
568 diagnostic_report_current_module (diagnostic_context *context, location_t where)
569 {
570   const line_map_ordinary *map = NULL;
571 
572   if (pp_needs_newline (context->printer))
573     {
574       pp_newline (context->printer);
575       pp_needs_newline (context->printer) = false;
576     }
577 
578   if (where <= BUILTINS_LOCATION)
579     return;
580 
581   linemap_resolve_location (line_table, where,
582 			    LRK_MACRO_DEFINITION_LOCATION,
583 			    &map);
584 
585   if (map && last_module_changed_p (context, map))
586     {
587       set_last_module (context, map);
588       if (! MAIN_FILE_P (map))
589 	{
590 	  map = INCLUDED_FROM (line_table, map);
591 	  const char *line_col
592 	    = maybe_line_and_column (LAST_SOURCE_LINE (map),
593 				     context->show_column
594 				     ? LAST_SOURCE_COLUMN (map) : 0);
595 	  pp_verbatim (context->printer,
596 		       "In file included from %r%s%s%R", "locus",
597 		       LINEMAP_FILE (map), line_col);
598 	  while (! MAIN_FILE_P (map))
599 	    {
600 	      map = INCLUDED_FROM (line_table, map);
601 	      line_col = maybe_line_and_column (LAST_SOURCE_LINE (map), 0);
602 	      pp_verbatim (context->printer,
603 			   ",\n                 from %r%s%s%R", "locus",
604 			   LINEMAP_FILE (map), line_col);
605 	    }
606 	  pp_verbatim (context->printer, ":");
607 	  pp_newline (context->printer);
608 	}
609     }
610 }
611 
612 void
613 default_diagnostic_starter (diagnostic_context *context,
614 			    diagnostic_info *diagnostic)
615 {
616   diagnostic_report_current_module (context, diagnostic_location (diagnostic));
617   pp_set_prefix (context->printer, diagnostic_build_prefix (context,
618 							    diagnostic));
619 }
620 
621 void
622 default_diagnostic_start_span_fn (diagnostic_context *context,
623 				  expanded_location exploc)
624 {
625   pp_set_prefix (context->printer,
626 		 diagnostic_get_location_text (context, exploc));
627   pp_string (context->printer, "");
628   pp_newline (context->printer);
629 }
630 
631 void
632 default_diagnostic_finalizer (diagnostic_context *context,
633 			      diagnostic_info *diagnostic)
634 {
635   diagnostic_show_locus (context, diagnostic->richloc, diagnostic->kind);
636   pp_destroy_prefix (context->printer);
637   pp_flush (context->printer);
638 }
639 
640 /* Interface to specify diagnostic kind overrides.  Returns the
641    previous setting, or DK_UNSPECIFIED if the parameters are out of
642    range.  If OPTION_INDEX is zero, the new setting is for all the
643    diagnostics.  */
644 diagnostic_t
645 diagnostic_classify_diagnostic (diagnostic_context *context,
646 				int option_index,
647 				diagnostic_t new_kind,
648 				location_t where)
649 {
650   diagnostic_t old_kind;
651 
652   if (option_index < 0
653       || option_index >= context->n_opts
654       || new_kind >= DK_LAST_DIAGNOSTIC_KIND)
655     return DK_UNSPECIFIED;
656 
657   old_kind = context->classify_diagnostic[option_index];
658 
659   /* Handle pragmas separately, since we need to keep track of *where*
660      the pragmas were.  */
661   if (where != UNKNOWN_LOCATION)
662     {
663       int i;
664 
665       /* Record the command-line status, so we can reset it back on DK_POP. */
666       if (old_kind == DK_UNSPECIFIED)
667 	{
668 	  old_kind = !context->option_enabled (option_index,
669 					       context->option_state)
670 	    ? DK_IGNORED : (context->warning_as_error_requested
671 			    ? DK_ERROR : DK_WARNING);
672 	  context->classify_diagnostic[option_index] = old_kind;
673 	}
674 
675       for (i = context->n_classification_history - 1; i >= 0; i --)
676 	if (context->classification_history[i].option == option_index)
677 	  {
678 	    old_kind = context->classification_history[i].kind;
679 	    break;
680 	  }
681 
682       i = context->n_classification_history;
683       context->classification_history =
684 	(diagnostic_classification_change_t *) xrealloc (context->classification_history, (i + 1)
685 							 * sizeof (diagnostic_classification_change_t));
686       context->classification_history[i].location = where;
687       context->classification_history[i].option = option_index;
688       context->classification_history[i].kind = new_kind;
689       context->n_classification_history ++;
690     }
691   else
692     context->classify_diagnostic[option_index] = new_kind;
693 
694   return old_kind;
695 }
696 
697 /* Save all diagnostic classifications in a stack.  */
698 void
699 diagnostic_push_diagnostics (diagnostic_context *context, location_t where ATTRIBUTE_UNUSED)
700 {
701   context->push_list = (int *) xrealloc (context->push_list, (context->n_push + 1) * sizeof (int));
702   context->push_list[context->n_push ++] = context->n_classification_history;
703 }
704 
705 /* Restore the topmost classification set off the stack.  If the stack
706    is empty, revert to the state based on command line parameters.  */
707 void
708 diagnostic_pop_diagnostics (diagnostic_context *context, location_t where)
709 {
710   int jump_to;
711   int i;
712 
713   if (context->n_push)
714     jump_to = context->push_list [-- context->n_push];
715   else
716     jump_to = 0;
717 
718   i = context->n_classification_history;
719   context->classification_history =
720     (diagnostic_classification_change_t *) xrealloc (context->classification_history, (i + 1)
721 						     * sizeof (diagnostic_classification_change_t));
722   context->classification_history[i].location = where;
723   context->classification_history[i].option = jump_to;
724   context->classification_history[i].kind = DK_POP;
725   context->n_classification_history ++;
726 }
727 
728 /* Helper function for print_parseable_fixits.  Print TEXT to PP, obeying the
729    escaping rules for -fdiagnostics-parseable-fixits.  */
730 
731 static void
732 print_escaped_string (pretty_printer *pp, const char *text)
733 {
734   gcc_assert (pp);
735   gcc_assert (text);
736 
737   pp_character (pp, '"');
738   for (const char *ch = text; *ch; ch++)
739     {
740       switch (*ch)
741 	{
742 	case '\\':
743 	  /* Escape backslash as two backslashes.  */
744 	  pp_string (pp, "\\\\");
745 	  break;
746 	case '\t':
747 	  /* Escape tab as "\t".  */
748 	  pp_string (pp, "\\t");
749 	  break;
750 	case '\n':
751 	  /* Escape newline as "\n".  */
752 	  pp_string (pp, "\\n");
753 	  break;
754 	case '"':
755 	  /* Escape doublequotes as \".  */
756 	  pp_string (pp, "\\\"");
757 	  break;
758 	default:
759 	  if (ISPRINT (*ch))
760 	    pp_character (pp, *ch);
761 	  else
762 	    /* Use octal for non-printable chars.  */
763 	    {
764 	      unsigned char c = (*ch & 0xff);
765 	      pp_printf (pp, "\\%o%o%o", (c / 64), (c / 8) & 007, c & 007);
766 	    }
767 	  break;
768 	}
769     }
770   pp_character (pp, '"');
771 }
772 
773 /* Implementation of -fdiagnostics-parseable-fixits.  Print a
774    machine-parseable version of all fixits in RICHLOC to PP.  */
775 
776 static void
777 print_parseable_fixits (pretty_printer *pp, rich_location *richloc)
778 {
779   gcc_assert (pp);
780   gcc_assert (richloc);
781 
782   for (unsigned i = 0; i < richloc->get_num_fixit_hints (); i++)
783     {
784       const fixit_hint *hint = richloc->get_fixit_hint (i);
785       source_location start_loc = hint->get_start_loc ();
786       expanded_location start_exploc = expand_location (start_loc);
787       pp_string (pp, "fix-it:");
788       print_escaped_string (pp, start_exploc.file);
789       /* For compatibility with clang, print as a half-open range.  */
790       source_location next_loc = hint->get_next_loc ();
791       expanded_location next_exploc = expand_location (next_loc);
792       pp_printf (pp, ":{%i:%i-%i:%i}:",
793 		 start_exploc.line, start_exploc.column,
794 		 next_exploc.line, next_exploc.column);
795       print_escaped_string (pp, hint->get_string ());
796       pp_newline (pp);
797     }
798 }
799 
800 /* Update the diag_class of DIAGNOSTIC based on its location
801    relative to any
802      #pragma GCC diagnostic
803    directives recorded within CONTEXT.
804 
805    Return the new diag_class of DIAGNOSTIC if it was updated, or
806    DK_UNSPECIFIED otherwise.  */
807 
808 static diagnostic_t
809 update_effective_level_from_pragmas (diagnostic_context *context,
810 				     diagnostic_info *diagnostic)
811 {
812   diagnostic_t diag_class = DK_UNSPECIFIED;
813 
814   if (context->n_classification_history > 0)
815     {
816       location_t location = diagnostic_location (diagnostic);
817 
818       /* FIXME: Stupid search.  Optimize later. */
819       for (int i = context->n_classification_history - 1; i >= 0; i --)
820 	{
821 	  if (linemap_location_before_p
822 	      (line_table,
823 	       context->classification_history[i].location,
824 	       location))
825 	    {
826 	      if (context->classification_history[i].kind == (int) DK_POP)
827 		{
828 		  i = context->classification_history[i].option;
829 		  continue;
830 		}
831 	      int option = context->classification_history[i].option;
832 	      /* The option 0 is for all the diagnostics.  */
833 	      if (option == 0 || option == diagnostic->option_index)
834 		{
835 		  diag_class = context->classification_history[i].kind;
836 		  if (diag_class != DK_UNSPECIFIED)
837 		    diagnostic->kind = diag_class;
838 		  break;
839 		}
840 	    }
841 	}
842     }
843 
844   return diag_class;
845 }
846 
847 /* Print any metadata about the option used to control DIAGNOSTIC to CONTEXT's
848    printer, e.g. " [-Werror=uninitialized]".
849    Subroutine of diagnostic_report_diagnostic.  */
850 
851 static void
852 print_option_information (diagnostic_context *context,
853 			  const diagnostic_info *diagnostic,
854 			  diagnostic_t orig_diag_kind)
855 {
856   char *option_text;
857 
858   option_text = context->option_name (context, diagnostic->option_index,
859 				      orig_diag_kind, diagnostic->kind);
860 
861   if (option_text)
862     {
863       pretty_printer *pp = context->printer;
864       pp_string (pp, " [");
865       pp_string (pp, colorize_start (pp_show_color (pp),
866 				     diagnostic_kind_color[diagnostic->kind]));
867       pp_string (pp, option_text);
868       pp_string (pp, colorize_stop (pp_show_color (pp)));
869       pp_character (pp, ']');
870       free (option_text);
871     }
872 }
873 
874 /* Report a diagnostic message (an error or a warning) as specified by
875    DC.  This function is *the* subroutine in terms of which front-ends
876    should implement their specific diagnostic handling modules.  The
877    front-end independent format specifiers are exactly those described
878    in the documentation of output_format.
879    Return true if a diagnostic was printed, false otherwise.  */
880 
881 bool
882 diagnostic_report_diagnostic (diagnostic_context *context,
883 			      diagnostic_info *diagnostic)
884 {
885   location_t location = diagnostic_location (diagnostic);
886   diagnostic_t orig_diag_kind = diagnostic->kind;
887 
888   /* Give preference to being able to inhibit warnings, before they
889      get reclassified to something else.  */
890   if ((diagnostic->kind == DK_WARNING || diagnostic->kind == DK_PEDWARN)
891       && !diagnostic_report_warnings_p (context, location))
892     return false;
893 
894   if (diagnostic->kind == DK_PEDWARN)
895     {
896       diagnostic->kind = pedantic_warning_kind (context);
897       /* We do this to avoid giving the message for -pedantic-errors.  */
898       orig_diag_kind = diagnostic->kind;
899     }
900 
901   if (diagnostic->kind == DK_NOTE && context->inhibit_notes_p)
902     return false;
903 
904   if (context->lock > 0)
905     {
906       /* If we're reporting an ICE in the middle of some other error,
907 	 try to flush out the previous error, then let this one
908 	 through.  Don't do this more than once.  */
909       if ((diagnostic->kind == DK_ICE || diagnostic->kind == DK_ICE_NOBT)
910 	  && context->lock == 1)
911 	pp_newline_and_flush (context->printer);
912       else
913 	error_recursion (context);
914     }
915 
916   /* If the user requested that warnings be treated as errors, so be
917      it.  Note that we do this before the next block so that
918      individual warnings can be overridden back to warnings with
919      -Wno-error=*.  */
920   if (context->warning_as_error_requested
921       && diagnostic->kind == DK_WARNING)
922     diagnostic->kind = DK_ERROR;
923 
924   if (diagnostic->option_index
925       && diagnostic->option_index != permissive_error_option (context))
926     {
927       /* This tests if the user provided the appropriate -Wfoo or
928 	 -Wno-foo option.  */
929       if (! context->option_enabled (diagnostic->option_index,
930 				     context->option_state))
931 	return false;
932 
933       /* This tests for #pragma diagnostic changes.  */
934       diagnostic_t diag_class
935 	= update_effective_level_from_pragmas (context, diagnostic);
936 
937       /* This tests if the user provided the appropriate -Werror=foo
938 	 option.  */
939       if (diag_class == DK_UNSPECIFIED
940 	  && (context->classify_diagnostic[diagnostic->option_index]
941 	      != DK_UNSPECIFIED))
942 	diagnostic->kind
943 	  = context->classify_diagnostic[diagnostic->option_index];
944 
945       /* This allows for future extensions, like temporarily disabling
946 	 warnings for ranges of source code.  */
947       if (diagnostic->kind == DK_IGNORED)
948 	return false;
949     }
950 
951   if (diagnostic->kind != DK_NOTE)
952     diagnostic_check_max_errors (context);
953 
954   context->lock++;
955 
956   if (diagnostic->kind == DK_ICE || diagnostic->kind == DK_ICE_NOBT)
957     {
958       /* When not checking, ICEs are converted to fatal errors when an
959 	 error has already occurred.  This is counteracted by
960 	 abort_on_error.  */
961       if (!CHECKING_P
962 	  && (diagnostic_kind_count (context, DK_ERROR) > 0
963 	      || diagnostic_kind_count (context, DK_SORRY) > 0)
964 	  && !context->abort_on_error)
965 	{
966 	  expanded_location s
967 	    = expand_location (diagnostic_location (diagnostic));
968 	  fnotice (stderr, "%s:%d: confused by earlier errors, bailing out\n",
969 		   s.file, s.line);
970 	  exit (ICE_EXIT_CODE);
971 	}
972       if (context->internal_error)
973 	(*context->internal_error) (context,
974 				    diagnostic->message.format_spec,
975 				    diagnostic->message.args_ptr);
976     }
977   if (diagnostic->kind == DK_ERROR && orig_diag_kind == DK_WARNING)
978     ++diagnostic_kind_count (context, DK_WERROR);
979   else
980     ++diagnostic_kind_count (context, diagnostic->kind);
981 
982   diagnostic->message.x_data = &diagnostic->x_data;
983   diagnostic->x_data = NULL;
984   pp_format (context->printer, &diagnostic->message);
985   (*diagnostic_starter (context)) (context, diagnostic);
986   pp_output_formatted_text (context->printer);
987   if (context->show_option_requested)
988     print_option_information (context, diagnostic, orig_diag_kind);
989   (*diagnostic_finalizer (context)) (context, diagnostic);
990   if (context->parseable_fixits_p)
991     {
992       print_parseable_fixits (context->printer, diagnostic->richloc);
993       pp_flush (context->printer);
994     }
995   diagnostic_action_after_output (context, diagnostic->kind);
996   diagnostic->x_data = NULL;
997 
998   if (context->edit_context_ptr)
999     if (diagnostic->richloc->fixits_can_be_auto_applied_p ())
1000       context->edit_context_ptr->add_fixits (diagnostic->richloc);
1001 
1002   context->lock--;
1003 
1004   return true;
1005 }
1006 
1007 /* Given a partial pathname as input, return another pathname that
1008    shares no directory elements with the pathname of __FILE__.  This
1009    is used by fancy_abort() to print `Internal compiler error in expr.c'
1010    instead of `Internal compiler error in ../../GCC/gcc/expr.c'.  */
1011 
1012 const char *
1013 trim_filename (const char *name)
1014 {
1015   static const char this_file[] = __FILE__;
1016   const char *p = name, *q = this_file;
1017 
1018   /* First skip any "../" in each filename.  This allows us to give a proper
1019      reference to a file in a subdirectory.  */
1020   while (p[0] == '.' && p[1] == '.' && IS_DIR_SEPARATOR (p[2]))
1021     p += 3;
1022 
1023   while (q[0] == '.' && q[1] == '.' && IS_DIR_SEPARATOR (q[2]))
1024     q += 3;
1025 
1026   /* Now skip any parts the two filenames have in common.  */
1027   while (*p == *q && *p != 0 && *q != 0)
1028     p++, q++;
1029 
1030   /* Now go backwards until the previous directory separator.  */
1031   while (p > name && !IS_DIR_SEPARATOR (p[-1]))
1032     p--;
1033 
1034   return p;
1035 }
1036 
1037 /* Standard error reporting routines in increasing order of severity.
1038    All of these take arguments like printf.  */
1039 
1040 /* Text to be emitted verbatim to the error message stream; this
1041    produces no prefix and disables line-wrapping.  Use rarely.  */
1042 void
1043 verbatim (const char *gmsgid, ...)
1044 {
1045   text_info text;
1046   va_list ap;
1047 
1048   va_start (ap, gmsgid);
1049   text.err_no = errno;
1050   text.args_ptr = &ap;
1051   text.format_spec = _(gmsgid);
1052   text.x_data = NULL;
1053   pp_format_verbatim (global_dc->printer, &text);
1054   pp_newline_and_flush (global_dc->printer);
1055   va_end (ap);
1056 }
1057 
1058 /* Add a note with text GMSGID and with LOCATION to the diagnostic CONTEXT.  */
1059 void
1060 diagnostic_append_note (diagnostic_context *context,
1061                         location_t location,
1062                         const char * gmsgid, ...)
1063 {
1064   diagnostic_info diagnostic;
1065   va_list ap;
1066   rich_location richloc (line_table, location);
1067 
1068   va_start (ap, gmsgid);
1069   diagnostic_set_info (&diagnostic, gmsgid, &ap, &richloc, DK_NOTE);
1070   if (context->inhibit_notes_p)
1071     {
1072       va_end (ap);
1073       return;
1074     }
1075   char *saved_prefix = pp_take_prefix (context->printer);
1076   pp_set_prefix (context->printer,
1077                  diagnostic_build_prefix (context, &diagnostic));
1078   pp_format (context->printer, &diagnostic.message);
1079   pp_output_formatted_text (context->printer);
1080   pp_destroy_prefix (context->printer);
1081   pp_set_prefix (context->printer, saved_prefix);
1082   diagnostic_show_locus (context, &richloc, DK_NOTE);
1083   va_end (ap);
1084 }
1085 
1086 /* Implement emit_diagnostic, inform, warning, warning_at, pedwarn,
1087    permerror, error, error_at, error_at, sorry, fatal_error, internal_error,
1088    and internal_error_no_backtrace, as documented and defined below.  */
1089 static bool
1090 diagnostic_impl (rich_location *richloc, int opt,
1091 		 const char *gmsgid,
1092 		 va_list *ap, diagnostic_t kind)
1093 {
1094   diagnostic_info diagnostic;
1095   if (kind == DK_PERMERROR)
1096     {
1097       diagnostic_set_info (&diagnostic, gmsgid, ap, richloc,
1098 			   permissive_error_kind (global_dc));
1099       diagnostic.option_index = permissive_error_option (global_dc);
1100     }
1101   else
1102     {
1103       diagnostic_set_info (&diagnostic, gmsgid, ap, richloc, kind);
1104       if (kind == DK_WARNING || kind == DK_PEDWARN)
1105 	diagnostic.option_index = opt;
1106     }
1107   return diagnostic_report_diagnostic (global_dc, &diagnostic);
1108 }
1109 
1110 /* Implement inform_n, warning_n, and error_n, as documented and
1111    defined below.  */
1112 static bool
1113 diagnostic_n_impl (rich_location *richloc, int opt, unsigned HOST_WIDE_INT n,
1114 		   const char *singular_gmsgid,
1115 		   const char *plural_gmsgid,
1116 		   va_list *ap, diagnostic_t kind)
1117 {
1118   diagnostic_info diagnostic;
1119   unsigned long gtn;
1120 
1121   if (sizeof n <= sizeof gtn)
1122     gtn = n;
1123   else
1124     /* Use the largest number ngettext can handle, otherwise
1125        preserve the six least significant decimal digits for
1126        languages where the plural form depends on them.  */
1127     gtn = n <= ULONG_MAX ? n : n % 1000000LU + 1000000LU;
1128 
1129   const char *text = ngettext (singular_gmsgid, plural_gmsgid, gtn);
1130   diagnostic_set_info_translated (&diagnostic, text, ap, richloc, kind);
1131   if (kind == DK_WARNING)
1132     diagnostic.option_index = opt;
1133   return diagnostic_report_diagnostic (global_dc, &diagnostic);
1134 }
1135 
1136 /* Wrapper around diagnostic_impl taking a variable argument list.  */
1137 
1138 bool
1139 emit_diagnostic (diagnostic_t kind, location_t location, int opt,
1140 		 const char *gmsgid, ...)
1141 {
1142   va_list ap;
1143   va_start (ap, gmsgid);
1144   rich_location richloc (line_table, location);
1145   bool ret = diagnostic_impl (&richloc, opt, gmsgid, &ap, kind);
1146   va_end (ap);
1147   return ret;
1148 }
1149 
1150 /* Wrapper around diagnostic_impl taking a va_list parameter.  */
1151 
1152 bool
1153 emit_diagnostic_valist (diagnostic_t kind, location_t location, int opt,
1154 			const char *gmsgid, va_list *ap)
1155 {
1156   rich_location richloc (line_table, location);
1157   return diagnostic_impl (&richloc, opt, gmsgid, ap, kind);
1158 }
1159 
1160 /* An informative note at LOCATION.  Use this for additional details on an error
1161    message.  */
1162 void
1163 inform (location_t location, const char *gmsgid, ...)
1164 {
1165   va_list ap;
1166   va_start (ap, gmsgid);
1167   rich_location richloc (line_table, location);
1168   diagnostic_impl (&richloc, -1, gmsgid, &ap, DK_NOTE);
1169   va_end (ap);
1170 }
1171 
1172 /* Same as "inform" above, but at RICHLOC.  */
1173 void
1174 inform (rich_location *richloc, const char *gmsgid, ...)
1175 {
1176   gcc_assert (richloc);
1177 
1178   va_list ap;
1179   va_start (ap, gmsgid);
1180   diagnostic_impl (richloc, -1, gmsgid, &ap, DK_NOTE);
1181   va_end (ap);
1182 }
1183 
1184 /* An informative note at LOCATION.  Use this for additional details on an
1185    error message.  */
1186 void
1187 inform_n (location_t location, unsigned HOST_WIDE_INT n,
1188 	  const char *singular_gmsgid, const char *plural_gmsgid, ...)
1189 {
1190   va_list ap;
1191   va_start (ap, plural_gmsgid);
1192   rich_location richloc (line_table, location);
1193   diagnostic_n_impl (&richloc, -1, n, singular_gmsgid, plural_gmsgid,
1194 		     &ap, DK_NOTE);
1195   va_end (ap);
1196 }
1197 
1198 /* A warning at INPUT_LOCATION.  Use this for code which is correct according
1199    to the relevant language specification but is likely to be buggy anyway.
1200    Returns true if the warning was printed, false if it was inhibited.  */
1201 bool
1202 warning (int opt, const char *gmsgid, ...)
1203 {
1204   va_list ap;
1205   va_start (ap, gmsgid);
1206   rich_location richloc (line_table, input_location);
1207   bool ret = diagnostic_impl (&richloc, opt, gmsgid, &ap, DK_WARNING);
1208   va_end (ap);
1209   return ret;
1210 }
1211 
1212 /* A warning at LOCATION.  Use this for code which is correct according to the
1213    relevant language specification but is likely to be buggy anyway.
1214    Returns true if the warning was printed, false if it was inhibited.  */
1215 
1216 bool
1217 warning_at (location_t location, int opt, const char *gmsgid, ...)
1218 {
1219   va_list ap;
1220   va_start (ap, gmsgid);
1221   rich_location richloc (line_table, location);
1222   bool ret = diagnostic_impl (&richloc, opt, gmsgid, &ap, DK_WARNING);
1223   va_end (ap);
1224   return ret;
1225 }
1226 
1227 /* Same as "warning at" above, but using RICHLOC.  */
1228 
1229 bool
1230 warning_at (rich_location *richloc, int opt, const char *gmsgid, ...)
1231 {
1232   gcc_assert (richloc);
1233 
1234   va_list ap;
1235   va_start (ap, gmsgid);
1236   bool ret = diagnostic_impl (richloc, opt, gmsgid, &ap, DK_WARNING);
1237   va_end (ap);
1238   return ret;
1239 }
1240 
1241 /* Same as warning_n plural variant below, but using RICHLOC.  */
1242 
1243 bool
1244 warning_n (rich_location *richloc, int opt, unsigned HOST_WIDE_INT n,
1245 	   const char *singular_gmsgid, const char *plural_gmsgid, ...)
1246 {
1247   gcc_assert (richloc);
1248 
1249   va_list ap;
1250   va_start (ap, plural_gmsgid);
1251   bool ret = diagnostic_n_impl (richloc, opt, n,
1252 				singular_gmsgid, plural_gmsgid,
1253 				&ap, DK_WARNING);
1254   va_end (ap);
1255   return ret;
1256 }
1257 
1258 /* A warning at LOCATION.  Use this for code which is correct according to the
1259    relevant language specification but is likely to be buggy anyway.
1260    Returns true if the warning was printed, false if it was inhibited.  */
1261 
1262 bool
1263 warning_n (location_t location, int opt, unsigned HOST_WIDE_INT n,
1264 	   const char *singular_gmsgid, const char *plural_gmsgid, ...)
1265 {
1266   va_list ap;
1267   va_start (ap, plural_gmsgid);
1268   rich_location richloc (line_table, location);
1269   bool ret = diagnostic_n_impl (&richloc, opt, n,
1270 				singular_gmsgid, plural_gmsgid,
1271 				&ap, DK_WARNING);
1272   va_end (ap);
1273   return ret;
1274 }
1275 
1276 /* A "pedantic" warning at LOCATION: issues a warning unless
1277    -pedantic-errors was given on the command line, in which case it
1278    issues an error.  Use this for diagnostics required by the relevant
1279    language standard, if you have chosen not to make them errors.
1280 
1281    Note that these diagnostics are issued independent of the setting
1282    of the -Wpedantic command-line switch.  To get a warning enabled
1283    only with that switch, use either "if (pedantic) pedwarn
1284    (OPT_Wpedantic,...)" or just "pedwarn (OPT_Wpedantic,..)".  To get a
1285    pedwarn independently of the -Wpedantic switch use "pedwarn (0,...)".
1286 
1287    Returns true if the warning was printed, false if it was inhibited.  */
1288 
1289 bool
1290 pedwarn (location_t location, int opt, const char *gmsgid, ...)
1291 {
1292   va_list ap;
1293   va_start (ap, gmsgid);
1294   rich_location richloc (line_table, location);
1295   bool ret = diagnostic_impl (&richloc, opt, gmsgid, &ap, DK_PEDWARN);
1296   va_end (ap);
1297   return ret;
1298 }
1299 
1300 /* Same as pedwarn above, but using RICHLOC.  */
1301 
1302 bool
1303 pedwarn (rich_location *richloc, int opt, const char *gmsgid, ...)
1304 {
1305   gcc_assert (richloc);
1306 
1307   va_list ap;
1308   va_start (ap, gmsgid);
1309   bool ret = diagnostic_impl (richloc, opt, gmsgid, &ap, DK_PEDWARN);
1310   va_end (ap);
1311   return ret;
1312 }
1313 
1314 /* A "permissive" error at LOCATION: issues an error unless
1315    -fpermissive was given on the command line, in which case it issues
1316    a warning.  Use this for things that really should be errors but we
1317    want to support legacy code.
1318 
1319    Returns true if the warning was printed, false if it was inhibited.  */
1320 
1321 bool
1322 permerror (location_t location, const char *gmsgid, ...)
1323 {
1324   va_list ap;
1325   va_start (ap, gmsgid);
1326   rich_location richloc (line_table, location);
1327   bool ret = diagnostic_impl (&richloc, -1, gmsgid, &ap, DK_PERMERROR);
1328   va_end (ap);
1329   return ret;
1330 }
1331 
1332 /* Same as "permerror" above, but at RICHLOC.  */
1333 
1334 bool
1335 permerror (rich_location *richloc, const char *gmsgid, ...)
1336 {
1337   gcc_assert (richloc);
1338 
1339   va_list ap;
1340   va_start (ap, gmsgid);
1341   bool ret = diagnostic_impl (richloc, -1, gmsgid, &ap, DK_PERMERROR);
1342   va_end (ap);
1343   return ret;
1344 }
1345 
1346 /* A hard error: the code is definitely ill-formed, and an object file
1347    will not be produced.  */
1348 void
1349 error (const char *gmsgid, ...)
1350 {
1351   va_list ap;
1352   va_start (ap, gmsgid);
1353   rich_location richloc (line_table, input_location);
1354   diagnostic_impl (&richloc, -1, gmsgid, &ap, DK_ERROR);
1355   va_end (ap);
1356 }
1357 
1358 /* A hard error: the code is definitely ill-formed, and an object file
1359    will not be produced.  */
1360 void
1361 error_n (location_t location, unsigned HOST_WIDE_INT n,
1362 	 const char *singular_gmsgid, const char *plural_gmsgid, ...)
1363 {
1364   va_list ap;
1365   va_start (ap, plural_gmsgid);
1366   rich_location richloc (line_table, location);
1367   diagnostic_n_impl (&richloc, -1, n, singular_gmsgid, plural_gmsgid,
1368 		     &ap, DK_ERROR);
1369   va_end (ap);
1370 }
1371 
1372 /* Same as above, but use location LOC instead of input_location.  */
1373 void
1374 error_at (location_t loc, const char *gmsgid, ...)
1375 {
1376   va_list ap;
1377   va_start (ap, gmsgid);
1378   rich_location richloc (line_table, loc);
1379   diagnostic_impl (&richloc, -1, gmsgid, &ap, DK_ERROR);
1380   va_end (ap);
1381 }
1382 
1383 /* Same as above, but use RICH_LOC.  */
1384 
1385 void
1386 error_at (rich_location *richloc, const char *gmsgid, ...)
1387 {
1388   gcc_assert (richloc);
1389 
1390   va_list ap;
1391   va_start (ap, gmsgid);
1392   diagnostic_impl (richloc, -1, gmsgid, &ap, DK_ERROR);
1393   va_end (ap);
1394 }
1395 
1396 /* "Sorry, not implemented."  Use for a language feature which is
1397    required by the relevant specification but not implemented by GCC.
1398    An object file will not be produced.  */
1399 void
1400 sorry (const char *gmsgid, ...)
1401 {
1402   va_list ap;
1403   va_start (ap, gmsgid);
1404   rich_location richloc (line_table, input_location);
1405   diagnostic_impl (&richloc, -1, gmsgid, &ap, DK_SORRY);
1406   va_end (ap);
1407 }
1408 
1409 /* Return true if an error or a "sorry" has been seen.  Various
1410    processing is disabled after errors.  */
1411 bool
1412 seen_error (void)
1413 {
1414   return errorcount || sorrycount;
1415 }
1416 
1417 /* An error which is severe enough that we make no attempt to
1418    continue.  Do not use this for internal consistency checks; that's
1419    internal_error.  Use of this function should be rare.  */
1420 void
1421 fatal_error (location_t loc, const char *gmsgid, ...)
1422 {
1423   va_list ap;
1424   va_start (ap, gmsgid);
1425   rich_location richloc (line_table, loc);
1426   diagnostic_impl (&richloc, -1, gmsgid, &ap, DK_FATAL);
1427   va_end (ap);
1428 
1429   gcc_unreachable ();
1430 }
1431 
1432 /* An internal consistency check has failed.  We make no attempt to
1433    continue.  Note that unless there is debugging value to be had from
1434    a more specific message, or some other good reason, you should use
1435    abort () instead of calling this function directly.  */
1436 void
1437 internal_error (const char *gmsgid, ...)
1438 {
1439   va_list ap;
1440   va_start (ap, gmsgid);
1441   rich_location richloc (line_table, input_location);
1442   diagnostic_impl (&richloc, -1, gmsgid, &ap, DK_ICE);
1443   va_end (ap);
1444 
1445   gcc_unreachable ();
1446 }
1447 
1448 /* Like internal_error, but no backtrace will be printed.  Used when
1449    the internal error does not happen at the current location, but happened
1450    somewhere else.  */
1451 void
1452 internal_error_no_backtrace (const char *gmsgid, ...)
1453 {
1454   va_list ap;
1455   va_start (ap, gmsgid);
1456   rich_location richloc (line_table, input_location);
1457   diagnostic_impl (&richloc, -1, gmsgid, &ap, DK_ICE_NOBT);
1458   va_end (ap);
1459 
1460   gcc_unreachable ();
1461 }
1462 
1463 /* Special case error functions.  Most are implemented in terms of the
1464    above, or should be.  */
1465 
1466 /* Print a diagnostic MSGID on FILE.  This is just fprintf, except it
1467    runs its second argument through gettext.  */
1468 void
1469 fnotice (FILE *file, const char *cmsgid, ...)
1470 {
1471   va_list ap;
1472 
1473   va_start (ap, cmsgid);
1474   vfprintf (file, _(cmsgid), ap);
1475   va_end (ap);
1476 }
1477 
1478 /* Inform the user that an error occurred while trying to report some
1479    other error.  This indicates catastrophic internal inconsistencies,
1480    so give up now.  But do try to flush out the previous error.
1481    This mustn't use internal_error, that will cause infinite recursion.  */
1482 
1483 static void
1484 error_recursion (diagnostic_context *context)
1485 {
1486   if (context->lock < 3)
1487     pp_newline_and_flush (context->printer);
1488 
1489   fnotice (stderr,
1490 	   "Internal compiler error: Error reporting routines re-entered.\n");
1491 
1492   /* Call diagnostic_action_after_output to get the "please submit a bug
1493      report" message.  */
1494   diagnostic_action_after_output (context, DK_ICE);
1495 
1496   /* Do not use gcc_unreachable here; that goes through internal_error
1497      and therefore would cause infinite recursion.  */
1498   real_abort ();
1499 }
1500 
1501 /* Report an internal compiler error in a friendly manner.  This is
1502    the function that gets called upon use of abort() in the source
1503    code generally, thanks to a special macro.  */
1504 
1505 void
1506 fancy_abort (const char *file, int line, const char *function)
1507 {
1508   internal_error ("in %s, at %s:%d", function, trim_filename (file), line);
1509 }
1510 
1511 /* Really call the system 'abort'.  This has to go right at the end of
1512    this file, so that there are no functions after it that call abort
1513    and get the system abort instead of our macro.  */
1514 #undef abort
1515 static void
1516 real_abort (void)
1517 {
1518   abort ();
1519 }
1520 
1521 #if CHECKING_P
1522 
1523 namespace selftest {
1524 
1525 /* Helper function for test_print_escaped_string.  */
1526 
1527 static void
1528 assert_print_escaped_string (const location &loc, const char *expected_output,
1529 			     const char *input)
1530 {
1531   pretty_printer pp;
1532   print_escaped_string (&pp, input);
1533   ASSERT_STREQ_AT (loc, expected_output, pp_formatted_text (&pp));
1534 }
1535 
1536 #define ASSERT_PRINT_ESCAPED_STRING_STREQ(EXPECTED_OUTPUT, INPUT) \
1537     assert_print_escaped_string (SELFTEST_LOCATION, EXPECTED_OUTPUT, INPUT)
1538 
1539 /* Tests of print_escaped_string.  */
1540 
1541 static void
1542 test_print_escaped_string ()
1543 {
1544   /* Empty string.  */
1545   ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"\"", "");
1546 
1547   /* Non-empty string.  */
1548   ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"hello world\"", "hello world");
1549 
1550   /* Various things that need to be escaped:  */
1551   /* Backslash.  */
1552   ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"before\\\\after\"",
1553 				     "before\\after");
1554   /* Tab.  */
1555   ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"before\\tafter\"",
1556 				     "before\tafter");
1557   /* Newline.  */
1558   ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"before\\nafter\"",
1559 				     "before\nafter");
1560   /* Double quote.  */
1561   ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"before\\\"after\"",
1562 				     "before\"after");
1563 
1564   /* Non-printable characters: BEL: '\a': 0x07 */
1565   ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"before\\007after\"",
1566 				     "before\aafter");
1567   /* Non-printable characters: vertical tab: '\v': 0x0b */
1568   ASSERT_PRINT_ESCAPED_STRING_STREQ ("\"before\\013after\"",
1569 				     "before\vafter");
1570 }
1571 
1572 /* Tests of print_parseable_fixits.  */
1573 
1574 /* Verify that print_parseable_fixits emits the empty string if there
1575    are no fixits.  */
1576 
1577 static void
1578 test_print_parseable_fixits_none ()
1579 {
1580   pretty_printer pp;
1581   rich_location richloc (line_table, UNKNOWN_LOCATION);
1582 
1583   print_parseable_fixits (&pp, &richloc);
1584   ASSERT_STREQ ("", pp_formatted_text (&pp));
1585 }
1586 
1587 /* Verify that print_parseable_fixits does the right thing if there
1588    is an insertion fixit hint.  */
1589 
1590 static void
1591 test_print_parseable_fixits_insert ()
1592 {
1593   pretty_printer pp;
1594   rich_location richloc (line_table, UNKNOWN_LOCATION);
1595 
1596   linemap_add (line_table, LC_ENTER, false, "test.c", 0);
1597   linemap_line_start (line_table, 5, 100);
1598   linemap_add (line_table, LC_LEAVE, false, NULL, 0);
1599   location_t where = linemap_position_for_column (line_table, 10);
1600   richloc.add_fixit_insert_before (where, "added content");
1601 
1602   print_parseable_fixits (&pp, &richloc);
1603   ASSERT_STREQ ("fix-it:\"test.c\":{5:10-5:10}:\"added content\"\n",
1604 		pp_formatted_text (&pp));
1605 }
1606 
1607 /* Verify that print_parseable_fixits does the right thing if there
1608    is an removal fixit hint.  */
1609 
1610 static void
1611 test_print_parseable_fixits_remove ()
1612 {
1613   pretty_printer pp;
1614   rich_location richloc (line_table, UNKNOWN_LOCATION);
1615 
1616   linemap_add (line_table, LC_ENTER, false, "test.c", 0);
1617   linemap_line_start (line_table, 5, 100);
1618   linemap_add (line_table, LC_LEAVE, false, NULL, 0);
1619   source_range where;
1620   where.m_start = linemap_position_for_column (line_table, 10);
1621   where.m_finish = linemap_position_for_column (line_table, 20);
1622   richloc.add_fixit_remove (where);
1623 
1624   print_parseable_fixits (&pp, &richloc);
1625   ASSERT_STREQ ("fix-it:\"test.c\":{5:10-5:21}:\"\"\n",
1626 		pp_formatted_text (&pp));
1627 }
1628 
1629 /* Verify that print_parseable_fixits does the right thing if there
1630    is an replacement fixit hint.  */
1631 
1632 static void
1633 test_print_parseable_fixits_replace ()
1634 {
1635   pretty_printer pp;
1636   rich_location richloc (line_table, UNKNOWN_LOCATION);
1637 
1638   linemap_add (line_table, LC_ENTER, false, "test.c", 0);
1639   linemap_line_start (line_table, 5, 100);
1640   linemap_add (line_table, LC_LEAVE, false, NULL, 0);
1641   source_range where;
1642   where.m_start = linemap_position_for_column (line_table, 10);
1643   where.m_finish = linemap_position_for_column (line_table, 20);
1644   richloc.add_fixit_replace (where, "replacement");
1645 
1646   print_parseable_fixits (&pp, &richloc);
1647   ASSERT_STREQ ("fix-it:\"test.c\":{5:10-5:21}:\"replacement\"\n",
1648 		pp_formatted_text (&pp));
1649 }
1650 
1651 /* Verify that
1652      diagnostic_get_location_text (..., SHOW_COLUMN)
1653    generates EXPECTED_LOC_TEXT, given FILENAME, LINE, COLUMN, with
1654    colorization disabled.  */
1655 
1656 static void
1657 assert_location_text (const char *expected_loc_text,
1658 		      const char *filename, int line, int column,
1659 		      bool show_column)
1660 {
1661   test_diagnostic_context dc;
1662   dc.show_column = show_column;
1663 
1664   expanded_location xloc;
1665   xloc.file = filename;
1666   xloc.line = line;
1667   xloc.column = column;
1668   xloc.data = NULL;
1669   xloc.sysp = false;
1670 
1671   char *actual_loc_text = diagnostic_get_location_text (&dc, xloc);
1672   ASSERT_STREQ (expected_loc_text, actual_loc_text);
1673   free (actual_loc_text);
1674 }
1675 
1676 /* Verify that diagnostic_get_location_text works as expected.  */
1677 
1678 static void
1679 test_diagnostic_get_location_text ()
1680 {
1681   const char *old_progname = progname;
1682   progname = "PROGNAME";
1683   assert_location_text ("PROGNAME:", NULL, 0, 0, true);
1684   assert_location_text ("<built-in>:", "<built-in>", 42, 10, true);
1685   assert_location_text ("foo.c:42:10:", "foo.c", 42, 10, true);
1686   assert_location_text ("foo.c:42:", "foo.c", 42, 0, true);
1687   assert_location_text ("foo.c:", "foo.c", 0, 10, true);
1688   assert_location_text ("foo.c:42:", "foo.c", 42, 10, false);
1689   assert_location_text ("foo.c:", "foo.c", 0, 10, false);
1690 
1691   maybe_line_and_column (INT_MAX, INT_MAX);
1692   maybe_line_and_column (INT_MIN, INT_MIN);
1693 
1694   progname = old_progname;
1695 }
1696 
1697 /* Run all of the selftests within this file.  */
1698 
1699 void
1700 diagnostic_c_tests ()
1701 {
1702   test_print_escaped_string ();
1703   test_print_parseable_fixits_none ();
1704   test_print_parseable_fixits_insert ();
1705   test_print_parseable_fixits_remove ();
1706   test_print_parseable_fixits_replace ();
1707   test_diagnostic_get_location_text ();
1708 }
1709 
1710 } // namespace selftest
1711 
1712 #endif /* #if CHECKING_P */
1713