gcc/testsuite/ChangeLog:
[platform/upstream/linaro-gcc.git] / gcc / pretty-print.c
1 /* Various declarations for language-independent pretty-print subroutines.
2    Copyright (C) 2003-2014 Free Software Foundation, Inc.
3    Contributed by Gabriel Dos Reis <gdr@integrable-solutions.net>
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 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "intl.h"
25 #include "pretty-print.h"
26 #include "diagnostic-color.h"
27
28 #include <new>                    // For placement-new.
29
30 #if HAVE_ICONV
31 #include <iconv.h>
32 #endif
33
34 // Default construct an output buffer.
35
36 output_buffer::output_buffer ()
37   : formatted_obstack (),
38     chunk_obstack (),
39     obstack (&formatted_obstack),
40     cur_chunk_array (),
41     stream (stderr),
42     line_length (),
43     digit_buffer (),
44     flush_p (true)
45 {
46   obstack_init (&formatted_obstack);
47   obstack_init (&chunk_obstack);
48 }
49
50 // Release resources owned by an output buffer at the end of lifetime.
51
52 output_buffer::~output_buffer ()
53 {
54   obstack_free (&chunk_obstack, NULL);
55   obstack_free (&formatted_obstack, NULL);
56 }
57
58 /* A pointer to the formatted diagnostic message.  */
59 #define pp_formatted_text_data(PP) \
60    ((const char *) obstack_base (pp_buffer (PP)->obstack))
61
62 /* Format an integer given by va_arg (ARG, type-specifier T) where
63    type-specifier is a precision modifier as indicated by PREC.  F is
64    a string used to construct the appropriate format-specifier.  */
65 #define pp_integer_with_precision(PP, ARG, PREC, T, F)       \
66   do                                                         \
67     switch (PREC)                                            \
68       {                                                      \
69       case 0:                                                \
70         pp_scalar (PP, "%" F, va_arg (ARG, T));              \
71         break;                                               \
72                                                              \
73       case 1:                                                \
74         pp_scalar (PP, "%l" F, va_arg (ARG, long T));        \
75         break;                                               \
76                                                              \
77       case 2:                                                \
78         pp_scalar (PP, "%" HOST_LONG_LONG_FORMAT F, va_arg (ARG, long long T));  \
79         break;                                               \
80                                                              \
81       default:                                               \
82         break;                                               \
83       }                                                      \
84   while (0)
85
86
87 /* Subroutine of pp_set_maximum_length.  Set up PRETTY-PRINTER's
88    internal maximum characters per line.  */
89 static void
90 pp_set_real_maximum_length (pretty_printer *pp)
91 {
92   /* If we're told not to wrap lines then do the obvious thing.  In case
93      we'll emit prefix only once per message, it is appropriate
94      not to increase unnecessarily the line-length cut-off.  */
95   if (!pp_is_wrapping_line (pp)
96       || pp_prefixing_rule (pp) == DIAGNOSTICS_SHOW_PREFIX_ONCE
97       || pp_prefixing_rule (pp) == DIAGNOSTICS_SHOW_PREFIX_NEVER)
98     pp->maximum_length = pp_line_cutoff (pp);
99   else
100     {
101       int prefix_length = pp->prefix ? strlen (pp->prefix) : 0;
102       /* If the prefix is ridiculously too long, output at least
103          32 characters.  */
104       if (pp_line_cutoff (pp) - prefix_length < 32)
105         pp->maximum_length = pp_line_cutoff (pp) + 32;
106       else
107         pp->maximum_length = pp_line_cutoff (pp);
108     }
109 }
110
111 /* Clear PRETTY-PRINTER's output state.  */
112 static inline void
113 pp_clear_state (pretty_printer *pp)
114 {
115   pp->emitted_prefix = false;
116   pp_indentation (pp) = 0;
117 }
118
119 /* Flush the formatted text of PRETTY-PRINTER onto the attached stream.  */
120 void
121 pp_write_text_to_stream (pretty_printer *pp)
122 {
123   const char *text = pp_formatted_text (pp);
124   fputs (text, pp_buffer (pp)->stream);
125   pp_clear_output_area (pp);
126 }
127
128 /* As pp_write_text_to_stream, but for GraphViz label output.
129
130    Flush the formatted text of pretty-printer PP onto the attached stream.
131    Replace characters in PPF that have special meaning in a GraphViz .dot
132    file.
133    
134    This routine is not very fast, but it doesn't have to be as this is only
135    be used by routines dumping intermediate representations in graph form.  */
136
137 void
138 pp_write_text_as_dot_label_to_stream (pretty_printer *pp, bool for_record)
139 {
140   const char *text = pp_formatted_text (pp);
141   const char *p = text;
142   FILE *fp = pp_buffer (pp)->stream;
143
144   while (*p)
145     {
146       switch (*p)
147         {
148         /* Print newlines as a left-aligned newline.  */
149         case '\n':
150           fputs ("\\l\\\n", fp);
151           break;
152
153         /* A pipe is only special for record-shape nodes.  */
154         case '|':
155           if (for_record)
156             fputc ('\\', fp);
157           fputc (*p, fp);
158           break;
159
160         /* The following characters always have to be escaped
161            for use in labels.  */
162         case '{':
163         case '}':
164         case '<':
165         case '>':
166         case '"':
167         case ' ':
168           fputc ('\\', fp);
169           /* fall through */
170         default:
171           fputc (*p, fp);
172           break;
173         }
174       p++;
175     }
176
177   pp_clear_output_area (pp);
178 }
179
180 /* Wrap a text delimited by START and END into PRETTY-PRINTER.  */
181 static void
182 pp_wrap_text (pretty_printer *pp, const char *start, const char *end)
183 {
184   bool wrapping_line = pp_is_wrapping_line (pp);
185
186   while (start != end)
187     {
188       /* Dump anything bordered by whitespaces.  */
189       {
190         const char *p = start;
191         while (p != end && !ISBLANK (*p) && *p != '\n')
192           ++p;
193         if (wrapping_line
194             && p - start >= pp_remaining_character_count_for_line (pp))
195           pp_newline (pp);
196         pp_append_text (pp, start, p);
197         start = p;
198       }
199
200       if (start != end && ISBLANK (*start))
201         {
202           pp_space (pp);
203           ++start;
204         }
205       if (start != end && *start == '\n')
206         {
207           pp_newline (pp);
208           ++start;
209         }
210     }
211 }
212
213 /* Same as pp_wrap_text but wrap text only when in line-wrapping mode.  */
214 static inline void
215 pp_maybe_wrap_text (pretty_printer *pp, const char *start, const char *end)
216 {
217   if (pp_is_wrapping_line (pp))
218     pp_wrap_text (pp, start, end);
219   else
220     pp_append_text (pp, start, end);
221 }
222
223 /* Append to the output area of PRETTY-PRINTER a string specified by its
224    STARTing character and LENGTH.  */
225 static inline void
226 pp_append_r (pretty_printer *pp, const char *start, int length)
227 {
228   obstack_grow (pp_buffer (pp)->obstack, start, length);
229   pp_buffer (pp)->line_length += length;
230 }
231
232 /* Insert enough spaces into the output area of PRETTY-PRINTER to bring
233    the column position to the current indentation level, assuming that a
234    newline has just been written to the buffer.  */
235 void
236 pp_indent (pretty_printer *pp)
237 {
238   int n = pp_indentation (pp);
239   int i;
240
241   for (i = 0; i < n; ++i)
242     pp_space (pp);
243 }
244
245 /* The following format specifiers are recognized as being client independent:
246    %d, %i: (signed) integer in base ten.
247    %u: unsigned integer in base ten.
248    %o: unsigned integer in base eight.
249    %x: unsigned integer in base sixteen.
250    %ld, %li, %lo, %lu, %lx: long versions of the above.
251    %lld, %lli, %llo, %llu, %llx: long long versions.
252    %wd, %wi, %wo, %wu, %wx: HOST_WIDE_INT versions.
253    %c: character.
254    %s: string.
255    %p: pointer.
256    %r: if pp_show_color(pp), switch to color identified by const char *.
257    %R: if pp_show_color(pp), reset color.
258    %m: strerror(text->err_no) - does not consume a value from args_ptr.
259    %%: '%'.
260    %<: opening quote.
261    %>: closing quote.
262    %': apostrophe (should only be used in untranslated messages;
263        translations should use appropriate punctuation directly).
264    %.*s: a substring the length of which is specified by an argument
265          integer.
266    %Ns: likewise, but length specified as constant in the format string.
267    Flag 'q': quote formatted text (must come immediately after '%').
268
269    Arguments can be used sequentially, or through %N$ resp. *N$
270    notation Nth argument after the format string.  If %N$ / *N$
271    notation is used, it must be used for all arguments, except %m, %%,
272    %<, %> and %', which may not have a number, as they do not consume
273    an argument.  When %M$.*N$s is used, M must be N + 1.  (This may
274    also be written %M$.*s, provided N is not otherwise used.)  The
275    format string must have conversion specifiers with argument numbers
276    1 up to highest argument; each argument may only be used once.
277    A format string can have at most 30 arguments.  */
278
279 /* Formatting phases 1 and 2: render TEXT->format_spec plus
280    TEXT->args_ptr into a series of chunks in pp_buffer (PP)->args[].
281    Phase 3 is in pp_format_text.  */
282
283 void
284 pp_format (pretty_printer *pp, text_info *text)
285 {
286   output_buffer *buffer = pp_buffer (pp);
287   const char *p;
288   const char **args;
289   struct chunk_info *new_chunk_array;
290
291   unsigned int curarg = 0, chunk = 0, argno;
292   pp_wrapping_mode_t old_wrapping_mode;
293   bool any_unnumbered = false, any_numbered = false;
294   const char **formatters[PP_NL_ARGMAX];
295
296   /* Allocate a new chunk structure.  */
297   new_chunk_array = XOBNEW (&buffer->chunk_obstack, struct chunk_info);
298   new_chunk_array->prev = buffer->cur_chunk_array;
299   buffer->cur_chunk_array = new_chunk_array;
300   args = new_chunk_array->args;
301
302   /* Formatting phase 1: split up TEXT->format_spec into chunks in
303      pp_buffer (PP)->args[].  Even-numbered chunks are to be output
304      verbatim, odd-numbered chunks are format specifiers.
305      %m, %%, %<, %>, and %' are replaced with the appropriate text at
306      this point.  */
307
308   memset (formatters, 0, sizeof formatters);
309
310   for (p = text->format_spec; *p; )
311     {
312       while (*p != '\0' && *p != '%')
313         {
314           obstack_1grow (&buffer->chunk_obstack, *p);
315           p++;
316         }
317
318       if (*p == '\0')
319         break;
320
321       switch (*++p)
322         {
323         case '\0':
324           gcc_unreachable ();
325
326         case '%':
327           obstack_1grow (&buffer->chunk_obstack, '%');
328           p++;
329           continue;
330
331         case '<':
332           {
333             obstack_grow (&buffer->chunk_obstack,
334                           open_quote, strlen (open_quote));
335             const char *colorstr
336               = colorize_start (pp_show_color (pp), "quote");
337             obstack_grow (&buffer->chunk_obstack, colorstr, strlen (colorstr));
338             p++;
339             continue;
340           }
341
342         case '>':
343           {
344             const char *colorstr = colorize_stop (pp_show_color (pp));
345             obstack_grow (&buffer->chunk_obstack, colorstr, strlen (colorstr));
346           }
347           /* FALLTHRU */
348         case '\'':
349           obstack_grow (&buffer->chunk_obstack,
350                         close_quote, strlen (close_quote));
351           p++;
352           continue;
353
354         case 'R':
355           {
356             const char *colorstr = colorize_stop (pp_show_color (pp));
357             obstack_grow (&buffer->chunk_obstack, colorstr,
358                           strlen (colorstr));
359             p++;
360             continue;
361           }
362
363         case 'm':
364           {
365             const char *errstr = xstrerror (text->err_no);
366             obstack_grow (&buffer->chunk_obstack, errstr, strlen (errstr));
367           }
368           p++;
369           continue;
370
371         default:
372           /* Handled in phase 2.  Terminate the plain chunk here.  */
373           obstack_1grow (&buffer->chunk_obstack, '\0');
374           gcc_assert (chunk < PP_NL_ARGMAX * 2);
375           args[chunk++] = XOBFINISH (&buffer->chunk_obstack, const char *);
376           break;
377         }
378
379       if (ISDIGIT (*p))
380         {
381           char *end;
382           argno = strtoul (p, &end, 10) - 1;
383           p = end;
384           gcc_assert (*p == '$');
385           p++;
386
387           any_numbered = true;
388           gcc_assert (!any_unnumbered);
389         }
390       else
391         {
392           argno = curarg++;
393           any_unnumbered = true;
394           gcc_assert (!any_numbered);
395         }
396       gcc_assert (argno < PP_NL_ARGMAX);
397       gcc_assert (!formatters[argno]);
398       formatters[argno] = &args[chunk];
399       do
400         {
401           obstack_1grow (&buffer->chunk_obstack, *p);
402           p++;
403         }
404       while (strchr ("qwl+#", p[-1]));
405
406       if (p[-1] == '.')
407         {
408           /* We handle '%.Ns' and '%.*s' or '%M$.*N$s'
409              (where M == N + 1).  */
410           if (ISDIGIT (*p))
411             {
412               do
413                 {
414                   obstack_1grow (&buffer->chunk_obstack, *p);
415                   p++;
416                 }
417               while (ISDIGIT (p[-1]));
418               gcc_assert (p[-1] == 's');
419             }
420           else
421             {
422               gcc_assert (*p == '*');
423               obstack_1grow (&buffer->chunk_obstack, '*');
424               p++;
425
426               if (ISDIGIT (*p))
427                 {
428                   char *end;
429                   unsigned int argno2 = strtoul (p, &end, 10) - 1;
430                   p = end;
431                   gcc_assert (argno2 == argno - 1);
432                   gcc_assert (!any_unnumbered);
433                   gcc_assert (*p == '$');
434
435                   p++;
436                   formatters[argno2] = formatters[argno];
437                 }
438               else
439                 {
440                   gcc_assert (!any_numbered);
441                   formatters[argno+1] = formatters[argno];
442                   curarg++;
443                 }
444               gcc_assert (*p == 's');
445               obstack_1grow (&buffer->chunk_obstack, 's');
446               p++;
447             }
448         }
449       if (*p == '\0')
450         break;
451
452       obstack_1grow (&buffer->chunk_obstack, '\0');
453       gcc_assert (chunk < PP_NL_ARGMAX * 2);
454       args[chunk++] = XOBFINISH (&buffer->chunk_obstack, const char *);
455     }
456
457   obstack_1grow (&buffer->chunk_obstack, '\0');
458   gcc_assert (chunk < PP_NL_ARGMAX * 2);
459   args[chunk++] = XOBFINISH (&buffer->chunk_obstack, const char *);
460   args[chunk] = 0;
461
462   /* Set output to the argument obstack, and switch line-wrapping and
463      prefixing off.  */
464   buffer->obstack = &buffer->chunk_obstack;
465   old_wrapping_mode = pp_set_verbatim_wrapping (pp);
466
467   /* Second phase.  Replace each formatter with the formatted text it
468      corresponds to.  */
469
470   for (argno = 0; formatters[argno]; argno++)
471     {
472       int precision = 0;
473       bool wide = false;
474       bool plus = false;
475       bool hash = false;
476       bool quote = false;
477
478       /* We do not attempt to enforce any ordering on the modifier
479          characters.  */
480
481       for (p = *formatters[argno];; p++)
482         {
483           switch (*p)
484             {
485             case 'q':
486               gcc_assert (!quote);
487               quote = true;
488               continue;
489
490             case '+':
491               gcc_assert (!plus);
492               plus = true;
493               continue;
494
495             case '#':
496               gcc_assert (!hash);
497               hash = true;
498               continue;
499
500             case 'w':
501               gcc_assert (!wide);
502               wide = true;
503               continue;
504
505             case 'l':
506               /* We don't support precision beyond that of "long long".  */
507               gcc_assert (precision < 2);
508               precision++;
509               continue;
510             }
511           break;
512         }
513
514       gcc_assert (!wide || precision == 0);
515
516       if (quote)
517         {
518           pp_string (pp, open_quote);
519           pp_string (pp, colorize_start (pp_show_color (pp), "quote"));
520         }
521
522       switch (*p)
523         {
524         case 'r':
525           pp_string (pp, colorize_start (pp_show_color (pp),
526                                          va_arg (*text->args_ptr,
527                                                  const char *)));
528           break;
529
530         case 'c':
531           pp_character (pp, va_arg (*text->args_ptr, int));
532           break;
533
534         case 'd':
535         case 'i':
536           if (wide)
537             pp_wide_integer (pp, va_arg (*text->args_ptr, HOST_WIDE_INT));
538           else
539             pp_integer_with_precision
540               (pp, *text->args_ptr, precision, int, "d");
541           break;
542
543         case 'o':
544           if (wide)
545             pp_scalar (pp, "%" HOST_WIDE_INT_PRINT "o",
546                        va_arg (*text->args_ptr, unsigned HOST_WIDE_INT));
547           else
548             pp_integer_with_precision
549               (pp, *text->args_ptr, precision, unsigned, "o");
550           break;
551
552         case 's':
553           pp_string (pp, va_arg (*text->args_ptr, const char *));
554           break;
555
556         case 'p':
557           pp_pointer (pp, va_arg (*text->args_ptr, void *));
558           break;
559
560         case 'u':
561           if (wide)
562             pp_scalar (pp, HOST_WIDE_INT_PRINT_UNSIGNED,
563                        va_arg (*text->args_ptr, unsigned HOST_WIDE_INT));
564           else
565             pp_integer_with_precision
566               (pp, *text->args_ptr, precision, unsigned, "u");
567           break;
568
569         case 'x':
570           if (wide)
571             pp_scalar (pp, HOST_WIDE_INT_PRINT_HEX,
572                        va_arg (*text->args_ptr, unsigned HOST_WIDE_INT));
573           else
574             pp_integer_with_precision
575               (pp, *text->args_ptr, precision, unsigned, "x");
576           break;
577
578         case '.':
579           {
580             int n;
581             const char *s;
582
583             /* We handle '%.Ns' and '%.*s' or '%M$.*N$s'
584                (where M == N + 1).  The format string should be verified
585                already from the first phase.  */
586             p++;
587             if (ISDIGIT (*p))
588               {
589                 char *end;
590                 n = strtoul (p, &end, 10);
591                 p = end;
592                 gcc_assert (*p == 's');
593               }
594             else
595               {
596                 gcc_assert (*p == '*');
597                 p++;
598                 gcc_assert (*p == 's');
599                 n = va_arg (*text->args_ptr, int);
600
601                 /* This consumes a second entry in the formatters array.  */
602                 gcc_assert (formatters[argno] == formatters[argno+1]);
603                 argno++;
604               }
605
606             s = va_arg (*text->args_ptr, const char *);
607             pp_append_text (pp, s, s + n);
608           }
609           break;
610
611         default:
612           {
613             bool ok;
614
615             gcc_assert (pp_format_decoder (pp));
616             ok = pp_format_decoder (pp) (pp, text, p,
617                                          precision, wide, plus, hash);
618             gcc_assert (ok);
619           }
620         }
621
622       if (quote)
623         {
624           pp_string (pp, colorize_stop (pp_show_color (pp)));
625           pp_string (pp, close_quote);
626         }
627
628       obstack_1grow (&buffer->chunk_obstack, '\0');
629       *formatters[argno] = XOBFINISH (&buffer->chunk_obstack, const char *);
630     }
631
632 #ifdef ENABLE_CHECKING
633   for (; argno < PP_NL_ARGMAX; argno++)
634     gcc_assert (!formatters[argno]);
635 #endif
636
637   /* Revert to normal obstack and wrapping mode.  */
638   buffer->obstack = &buffer->formatted_obstack;
639   buffer->line_length = 0;
640   pp_wrapping_mode (pp) = old_wrapping_mode;
641   pp_clear_state (pp);
642 }
643
644 /* Format of a message pointed to by TEXT.  */
645 void
646 pp_output_formatted_text (pretty_printer *pp)
647 {
648   unsigned int chunk;
649   output_buffer *buffer = pp_buffer (pp);
650   struct chunk_info *chunk_array = buffer->cur_chunk_array;
651   const char **args = chunk_array->args;
652
653   gcc_assert (buffer->obstack == &buffer->formatted_obstack);
654   gcc_assert (buffer->line_length == 0);
655
656   /* This is a third phase, first 2 phases done in pp_format_args.
657      Now we actually print it.  */
658   for (chunk = 0; args[chunk]; chunk++)
659     pp_string (pp, args[chunk]);
660
661   /* Deallocate the chunk structure and everything after it (i.e. the
662      associated series of formatted strings).  */
663   buffer->cur_chunk_array = chunk_array->prev;
664   obstack_free (&buffer->chunk_obstack, chunk_array);
665 }
666
667 /* Helper subroutine of output_verbatim and verbatim. Do the appropriate
668    settings needed by BUFFER for a verbatim formatting.  */
669 void
670 pp_format_verbatim (pretty_printer *pp, text_info *text)
671 {
672   /* Set verbatim mode.  */
673   pp_wrapping_mode_t oldmode = pp_set_verbatim_wrapping (pp);
674
675   /* Do the actual formatting.  */
676   pp_format (pp, text);
677   pp_output_formatted_text (pp);
678
679   /* Restore previous settings.  */
680   pp_wrapping_mode (pp) = oldmode;
681 }
682
683 /* Flush the content of BUFFER onto the attached stream.  This
684    function does nothing unless pp->output_buffer->flush_p.  */
685 void
686 pp_flush (pretty_printer *pp)
687 {
688   pp_clear_state (pp);
689   if (!pp->buffer->flush_p)
690     return;
691   pp_write_text_to_stream (pp);
692   fflush (pp_buffer (pp)->stream);
693 }
694
695 /* Flush the content of BUFFER onto the attached stream independently
696    of the value of pp->output_buffer->flush_p.  */
697 void
698 pp_really_flush (pretty_printer *pp)
699 {
700   pp_clear_state (pp);
701   pp_write_text_to_stream (pp);
702   fflush (pp_buffer (pp)->stream);
703 }
704
705 /* Sets the number of maximum characters per line PRETTY-PRINTER can
706    output in line-wrapping mode.  A LENGTH value 0 suppresses
707    line-wrapping.  */
708 void
709 pp_set_line_maximum_length (pretty_printer *pp, int length)
710 {
711   pp_line_cutoff (pp) = length;
712   pp_set_real_maximum_length (pp);
713 }
714
715 /* Clear PRETTY-PRINTER output area text info.  */
716 void
717 pp_clear_output_area (pretty_printer *pp)
718 {
719   obstack_free (pp_buffer (pp)->obstack,
720                 obstack_base (pp_buffer (pp)->obstack));
721   pp_buffer (pp)->line_length = 0;
722 }
723
724 /* Set PREFIX for PRETTY-PRINTER.  */
725 void
726 pp_set_prefix (pretty_printer *pp, const char *prefix)
727 {
728   pp->prefix = prefix;
729   pp_set_real_maximum_length (pp);
730   pp->emitted_prefix = false;
731   pp_indentation (pp) = 0;
732 }
733
734 /* Free PRETTY-PRINTER's prefix, a previously malloc()'d string.  */
735 void
736 pp_destroy_prefix (pretty_printer *pp)
737 {
738   if (pp->prefix != NULL)
739     {
740       free (CONST_CAST (char *, pp->prefix));
741       pp->prefix = NULL;
742     }
743 }
744
745 /* Write out PRETTY-PRINTER's prefix.  */
746 void
747 pp_emit_prefix (pretty_printer *pp)
748 {
749   if (pp->prefix != NULL)
750     {
751       switch (pp_prefixing_rule (pp))
752         {
753         default:
754         case DIAGNOSTICS_SHOW_PREFIX_NEVER:
755           break;
756
757         case DIAGNOSTICS_SHOW_PREFIX_ONCE:
758           if (pp->emitted_prefix)
759             {
760               pp_indent (pp);
761               break;
762             }
763           pp_indentation (pp) += 3;
764           /* Fall through.  */
765
766         case DIAGNOSTICS_SHOW_PREFIX_EVERY_LINE:
767           {
768             int prefix_length = strlen (pp->prefix);
769             pp_append_r (pp, pp->prefix, prefix_length);
770             pp->emitted_prefix = true;
771           }
772           break;
773         }
774     }
775 }
776
777 /* Construct a PRETTY-PRINTER with PREFIX and of MAXIMUM_LENGTH
778    characters per line.  */
779
780 pretty_printer::pretty_printer (const char *p, int l)
781   : buffer (new (XCNEW (output_buffer)) output_buffer ()),
782     prefix (),
783     padding (pp_none),
784     maximum_length (),
785     indent_skip (),
786     wrapping (),
787     format_decoder (),
788     emitted_prefix (),
789     need_newline (),
790     translate_identifiers (true),
791     show_color ()
792 {
793   pp_line_cutoff (this) = l;
794   /* By default, we emit prefixes once per message.  */
795   pp_prefixing_rule (this) = DIAGNOSTICS_SHOW_PREFIX_ONCE;
796   pp_set_prefix (this, p);
797 }
798
799 pretty_printer::~pretty_printer ()
800 {
801   buffer->~output_buffer ();
802   XDELETE (buffer);
803 }
804
805 /* Append a string delimited by START and END to the output area of
806    PRETTY-PRINTER.  No line wrapping is done.  However, if beginning a
807    new line then emit PRETTY-PRINTER's prefix and skip any leading
808    whitespace if appropriate.  The caller must ensure that it is
809    safe to do so.  */
810 void
811 pp_append_text (pretty_printer *pp, const char *start, const char *end)
812 {
813   /* Emit prefix and skip whitespace if we're starting a new line.  */
814   if (pp_buffer (pp)->line_length == 0)
815     {
816       pp_emit_prefix (pp);
817       if (pp_is_wrapping_line (pp))
818         while (start != end && *start == ' ')
819           ++start;
820     }
821   pp_append_r (pp, start, end - start);
822 }
823
824 /* Finishes constructing a NULL-terminated character string representing
825    the PRETTY-PRINTED text.  */
826 const char *
827 pp_formatted_text (pretty_printer *pp)
828 {
829   obstack_1grow (pp_buffer (pp)->obstack, '\0');
830   return pp_formatted_text_data (pp);
831 }
832
833 /*  Return a pointer to the last character emitted in PRETTY-PRINTER's
834     output area.  A NULL pointer means no character available.  */
835 const char *
836 pp_last_position_in_text (const pretty_printer *pp)
837 {
838   const char *p = NULL;
839   struct obstack *text = pp_buffer (pp)->obstack;
840
841   if (obstack_base (text) != obstack_next_free (text))
842     p = ((const char *) obstack_next_free (text)) - 1;
843   return p;
844 }
845
846 /* Return the amount of characters PRETTY-PRINTER can accept to
847    make a full line.  Meaningful only in line-wrapping mode.  */
848 int
849 pp_remaining_character_count_for_line (pretty_printer *pp)
850 {
851   return pp->maximum_length - pp_buffer (pp)->line_length;
852 }
853
854
855 /* Format a message into BUFFER a la printf.  */
856 void
857 pp_printf (pretty_printer *pp, const char *msg, ...)
858 {
859   text_info text;
860   va_list ap;
861
862   va_start (ap, msg);
863   text.err_no = errno;
864   text.args_ptr = &ap;
865   text.format_spec = msg;
866   text.locus = NULL;
867   pp_format (pp, &text);
868   pp_output_formatted_text (pp);
869   va_end (ap);
870 }
871
872
873 /* Output MESSAGE verbatim into BUFFER.  */
874 void
875 pp_verbatim (pretty_printer *pp, const char *msg, ...)
876 {
877   text_info text;
878   va_list ap;
879
880   va_start (ap, msg);
881   text.err_no = errno;
882   text.args_ptr = &ap;
883   text.format_spec = msg;
884   text.locus = NULL;
885   pp_format_verbatim (pp, &text);
886   va_end (ap);
887 }
888
889
890
891 /* Have PRETTY-PRINTER start a new line.  */
892 void
893 pp_newline (pretty_printer *pp)
894 {
895   obstack_1grow (pp_buffer (pp)->obstack, '\n');
896   pp_needs_newline (pp) = false;
897   pp_buffer (pp)->line_length = 0;
898 }
899
900 /* Have PRETTY-PRINTER add a CHARACTER.  */
901 void
902 pp_character (pretty_printer *pp, int c)
903 {
904   if (pp_is_wrapping_line (pp)
905       && pp_remaining_character_count_for_line (pp) <= 0)
906     {
907       pp_newline (pp);
908       if (ISSPACE (c))
909         return;
910     }
911   obstack_1grow (pp_buffer (pp)->obstack, c);
912   ++pp_buffer (pp)->line_length;
913 }
914
915 /* Append a STRING to the output area of PRETTY-PRINTER; the STRING may
916    be line-wrapped if in appropriate mode.  */
917 void
918 pp_string (pretty_printer *pp, const char *str)
919 {
920   pp_maybe_wrap_text (pp, str, str + (str ? strlen (str) : 0));
921 }
922
923 /* Maybe print out a whitespace if needed.  */
924
925 void
926 pp_maybe_space (pretty_printer *pp)
927 {
928   if (pp->padding != pp_none)
929     {
930       pp_space (pp);
931       pp->padding = pp_none;
932     }
933 }
934
935 // Add a newline to the pretty printer PP and flush formatted text.
936
937 void
938 pp_newline_and_flush (pretty_printer *pp)
939 {
940   pp_newline (pp);
941   pp_flush (pp);
942   pp_needs_newline (pp) = false;
943 }
944
945 // Add a newline to the pretty printer PP, followed by indentation.
946
947 void
948 pp_newline_and_indent (pretty_printer *pp, int n)
949 {
950   pp_indentation (pp) += n;
951   pp_newline (pp);
952   pp_indent (pp);
953   pp_needs_newline (pp) = false;
954 }
955
956 // Add separator C, followed by a single whitespace.
957
958 void
959 pp_separate_with (pretty_printer *pp, char c)
960 {
961   pp_character (pp, c);
962   pp_space (pp);
963 }
964
965 \f
966 /* The string starting at P has LEN (at least 1) bytes left; if they
967    start with a valid UTF-8 sequence, return the length of that
968    sequence and set *VALUE to the value of that sequence, and
969    otherwise return 0 and set *VALUE to (unsigned int) -1.  */
970
971 static int
972 decode_utf8_char (const unsigned char *p, size_t len, unsigned int *value)
973 {
974   unsigned int t = *p;
975
976   if (len == 0)
977     abort ();
978   if (t & 0x80)
979     {
980       size_t utf8_len = 0;
981       unsigned int ch;
982       size_t i;
983       for (t = *p; t & 0x80; t <<= 1)
984         utf8_len++;
985
986       if (utf8_len > len || utf8_len < 2 || utf8_len > 6)
987         {
988           *value = (unsigned int) -1;
989           return 0;
990         }
991       ch = *p & ((1 << (7 - utf8_len)) - 1);
992       for (i = 1; i < utf8_len; i++)
993         {
994           unsigned int u = p[i];
995           if ((u & 0xC0) != 0x80)
996             {
997               *value = (unsigned int) -1;
998               return 0;
999             }
1000           ch = (ch << 6) | (u & 0x3F);
1001         }
1002       if (   (ch <=      0x7F && utf8_len > 1)
1003           || (ch <=     0x7FF && utf8_len > 2)
1004           || (ch <=    0xFFFF && utf8_len > 3)
1005           || (ch <=  0x1FFFFF && utf8_len > 4)
1006           || (ch <= 0x3FFFFFF && utf8_len > 5)
1007           || (ch >= 0xD800 && ch <= 0xDFFF))
1008         {
1009           *value = (unsigned int) -1;
1010           return 0;
1011         }
1012       *value = ch;
1013       return utf8_len;
1014     }
1015   else
1016     {
1017       *value = t;
1018       return 1;
1019     }
1020 }
1021
1022 /* Allocator for identifier_to_locale and corresponding function to
1023    free memory.  */
1024
1025 void *(*identifier_to_locale_alloc) (size_t) = xmalloc;
1026 void (*identifier_to_locale_free) (void *) = free;
1027
1028 /* Given IDENT, an identifier in the internal encoding, return a
1029    version of IDENT suitable for diagnostics in the locale character
1030    set: either IDENT itself, or a string, allocated using
1031    identifier_to_locale_alloc, converted to the locale character set
1032    and using escape sequences if not representable in the locale
1033    character set or containing control characters or invalid byte
1034    sequences.  Existing backslashes in IDENT are not doubled, so the
1035    result may not uniquely specify the contents of an arbitrary byte
1036    sequence identifier.  */
1037
1038 const char *
1039 identifier_to_locale (const char *ident)
1040 {
1041   const unsigned char *uid = (const unsigned char *) ident;
1042   size_t idlen = strlen (ident);
1043   bool valid_printable_utf8 = true;
1044   bool all_ascii = true;
1045   size_t i;
1046
1047   for (i = 0; i < idlen;)
1048     {
1049       unsigned int c;
1050       size_t utf8_len = decode_utf8_char (&uid[i], idlen - i, &c);
1051       if (utf8_len == 0 || c <= 0x1F || (c >= 0x7F && c <= 0x9F))
1052         {
1053           valid_printable_utf8 = false;
1054           break;
1055         }
1056       if (utf8_len > 1)
1057         all_ascii = false;
1058       i += utf8_len;
1059     }
1060
1061   /* If IDENT contains invalid UTF-8 sequences (which may occur with
1062      attributes putting arbitrary byte sequences in identifiers), or
1063      control characters, we use octal escape sequences for all bytes
1064      outside printable ASCII.  */
1065   if (!valid_printable_utf8)
1066     {
1067       char *ret = (char *) identifier_to_locale_alloc (4 * idlen + 1);
1068       char *p = ret;
1069       for (i = 0; i < idlen; i++)
1070         {
1071           if (uid[i] > 0x1F && uid[i] < 0x7F)
1072             *p++ = uid[i];
1073           else
1074             {
1075               sprintf (p, "\\%03o", uid[i]);
1076               p += 4;
1077             }
1078         }
1079       *p = 0;
1080       return ret;
1081     }
1082
1083   /* Otherwise, if it is valid printable ASCII, or printable UTF-8
1084      with the locale character set being UTF-8, IDENT is used.  */
1085   if (all_ascii || locale_utf8)
1086     return ident;
1087
1088   /* Otherwise IDENT is converted to the locale character set if
1089      possible.  */
1090 #if defined ENABLE_NLS && defined HAVE_LANGINFO_CODESET && HAVE_ICONV
1091   if (locale_encoding != NULL)
1092     {
1093       iconv_t cd = iconv_open (locale_encoding, "UTF-8");
1094       bool conversion_ok = true;
1095       char *ret = NULL;
1096       if (cd != (iconv_t) -1)
1097         {
1098           size_t ret_alloc = 4 * idlen + 1;
1099           for (;;)
1100             {
1101               /* Repeat the whole conversion process as needed with
1102                  larger buffers so non-reversible transformations can
1103                  always be detected.  */
1104               ICONV_CONST char *inbuf = CONST_CAST (char *, ident);
1105               char *outbuf;
1106               size_t inbytesleft = idlen;
1107               size_t outbytesleft = ret_alloc - 1;
1108               size_t iconv_ret;
1109
1110               ret = (char *) identifier_to_locale_alloc (ret_alloc);
1111               outbuf = ret;
1112
1113               if (iconv (cd, 0, 0, 0, 0) == (size_t) -1)
1114                 {
1115                   conversion_ok = false;
1116                   break;
1117                 }
1118
1119               iconv_ret = iconv (cd, &inbuf, &inbytesleft,
1120                                  &outbuf, &outbytesleft);
1121               if (iconv_ret == (size_t) -1 || inbytesleft != 0)
1122                 {
1123                   if (errno == E2BIG)
1124                     {
1125                       ret_alloc *= 2;
1126                       identifier_to_locale_free (ret);
1127                       ret = NULL;
1128                       continue;
1129                     }
1130                   else
1131                     {
1132                       conversion_ok = false;
1133                       break;
1134                     }
1135                 }
1136               else if (iconv_ret != 0)
1137                 {
1138                   conversion_ok = false;
1139                   break;
1140                 }
1141               /* Return to initial shift state.  */
1142               if (iconv (cd, 0, 0, &outbuf, &outbytesleft) == (size_t) -1)
1143                 {
1144                   if (errno == E2BIG)
1145                     {
1146                       ret_alloc *= 2;
1147                       identifier_to_locale_free (ret);
1148                       ret = NULL;
1149                       continue;
1150                     }
1151                   else
1152                     {
1153                       conversion_ok = false;
1154                       break;
1155                     }
1156                 }
1157               *outbuf = 0;
1158               break;
1159             }
1160           iconv_close (cd);
1161           if (conversion_ok)
1162             return ret;
1163         }
1164     }
1165 #endif
1166
1167   /* Otherwise, convert non-ASCII characters in IDENT to UCNs.  */
1168   {
1169     char *ret = (char *) identifier_to_locale_alloc (10 * idlen + 1);
1170     char *p = ret;
1171     for (i = 0; i < idlen;)
1172       {
1173         unsigned int c;
1174         size_t utf8_len = decode_utf8_char (&uid[i], idlen - i, &c);
1175         if (utf8_len == 1)
1176           *p++ = uid[i];
1177         else
1178           {
1179             sprintf (p, "\\U%08x", c);
1180             p += 10;
1181           }
1182         i += utf8_len;
1183       }
1184     *p = 0;
1185     return ret;
1186   }
1187 }