Line data Source code
1 : /* Output colorization.
2 : Copyright (C) 2011-2026 Free Software Foundation, Inc.
3 :
4 : This program is free software; you can redistribute it and/or modify
5 : it under the terms of the GNU General Public License as published by
6 : the Free Software Foundation; either version 3, or (at your option)
7 : any later version.
8 :
9 : This program is distributed in the hope that it will be useful,
10 : but WITHOUT ANY WARRANTY; without even the implied warranty of
11 : MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 : GNU General Public License for more details.
13 :
14 : You should have received a copy of the GNU General Public License
15 : along with this program; if not, write to the Free Software
16 : Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA
17 : 02110-1301, USA. */
18 :
19 : #include "config.h"
20 : #define INCLUDE_VECTOR
21 : #include "system.h"
22 : #include "diagnostics/color.h"
23 : #include "diagnostics/url.h"
24 : #include "label-text.h"
25 :
26 : #ifdef __MINGW32__
27 : # define WIN32_LEAN_AND_MEAN
28 : # include <windows.h>
29 : #endif
30 :
31 : #include "color-macros.h"
32 : #include "selftest.h"
33 :
34 : /* The context and logic for choosing default --color screen attributes
35 : (foreground and background colors, etc.) are the following.
36 : -- There are eight basic colors available, each with its own
37 : nominal luminosity to the human eye and foreground/background
38 : codes (black [0 %, 30/40], blue [11 %, 34/44], red [30 %, 31/41],
39 : magenta [41 %, 35/45], green [59 %, 32/42], cyan [70 %, 36/46],
40 : yellow [89 %, 33/43], and white [100 %, 37/47]).
41 : -- Sometimes, white as a background is actually implemented using
42 : a shade of light gray, so that a foreground white can be visible
43 : on top of it (but most often not).
44 : -- Sometimes, black as a foreground is actually implemented using
45 : a shade of dark gray, so that it can be visible on top of a
46 : background black (but most often not).
47 : -- Sometimes, more colors are available, as extensions.
48 : -- Other attributes can be selected/deselected (bold [1/22],
49 : underline [4/24], standout/inverse [7/27], blink [5/25], and
50 : invisible/hidden [8/28]). They are sometimes implemented by
51 : using colors instead of what their names imply; e.g., bold is
52 : often achieved by using brighter colors. In practice, only bold
53 : is really available to us, underline sometimes being mapped by
54 : the terminal to some strange color choice, and standout best
55 : being left for use by downstream programs such as less(1).
56 : -- We cannot assume that any of the extensions or special features
57 : are available for the purpose of choosing defaults for everyone.
58 : -- The most prevalent default terminal backgrounds are pure black
59 : and pure white, and are not necessarily the same shades of
60 : those as if they were selected explicitly with SGR sequences.
61 : Some terminals use dark or light pictures as default background,
62 : but those are covered over by an explicit selection of background
63 : color with an SGR sequence; their users will appreciate their
64 : background pictures not be covered like this, if possible.
65 : -- Some uses of colors attributes is to make some output items
66 : more understated (e.g., context lines); this cannot be achieved
67 : by changing the background color.
68 : -- For these reasons, the GCC color defaults should strive not
69 : to change the background color from its default, unless it's
70 : for a short item that should be highlighted, not understated.
71 : -- The GCC foreground color defaults (without an explicitly set
72 : background) should provide enough contrast to be readable on any
73 : terminal with either a black (dark) or white (light) background.
74 : This only leaves red, magenta, green, and cyan (and their bold
75 : counterparts) and possibly bold blue. */
76 : /* Default colors. The user can overwrite them using environment
77 : variable GCC_COLORS. */
78 : struct color_default
79 : {
80 : const char *m_name;
81 : const char *m_val;
82 : };
83 :
84 : /* For GCC_COLORS. */
85 : static const color_default gcc_color_defaults[] =
86 : {
87 : { "error", SGR_SEQ (COLOR_BOLD COLOR_SEPARATOR COLOR_FG_RED) },
88 : { "warning", SGR_SEQ (COLOR_BOLD COLOR_SEPARATOR COLOR_FG_MAGENTA) },
89 : { "note", SGR_SEQ (COLOR_BOLD COLOR_SEPARATOR COLOR_FG_CYAN) },
90 : { "range1", SGR_SEQ (COLOR_FG_GREEN) },
91 : { "range2", SGR_SEQ (COLOR_FG_BLUE) },
92 : { "locus", SGR_SEQ (COLOR_BOLD) },
93 : { "quote", SGR_SEQ (COLOR_BOLD) },
94 : { "path", SGR_SEQ (COLOR_BOLD COLOR_SEPARATOR COLOR_FG_CYAN) },
95 : { "fnname", SGR_SEQ (COLOR_BOLD COLOR_SEPARATOR COLOR_FG_GREEN) },
96 : { "targs", SGR_SEQ (COLOR_FG_MAGENTA) },
97 : { "fixit-insert", SGR_SEQ (COLOR_FG_GREEN) },
98 : { "fixit-delete", SGR_SEQ (COLOR_FG_RED) },
99 : { "diff-filename", SGR_SEQ (COLOR_BOLD) },
100 : { "diff-hunk", SGR_SEQ (COLOR_FG_CYAN) },
101 : { "diff-delete", SGR_SEQ (COLOR_FG_RED) },
102 : { "diff-insert", SGR_SEQ (COLOR_FG_GREEN) },
103 : { "type-diff", SGR_SEQ (COLOR_BOLD COLOR_SEPARATOR COLOR_FG_GREEN) },
104 : { "valid", SGR_SEQ (COLOR_BOLD COLOR_SEPARATOR COLOR_FG_GREEN) },
105 : { "invalid", SGR_SEQ (COLOR_BOLD COLOR_SEPARATOR COLOR_FG_RED) },
106 : { "highlight-a", SGR_SEQ (COLOR_BOLD COLOR_SEPARATOR COLOR_FG_GREEN) },
107 : { "highlight-b", SGR_SEQ (COLOR_BOLD COLOR_SEPARATOR COLOR_FG_BLUE) },
108 :
109 : /* For debugging the analyzer. */
110 : { "bit_contents", SGR_SEQ (COLOR_BOLD COLOR_SEPARATOR COLOR_FG_MAGENTA) },
111 : { "bit_vector", SGR_SEQ (COLOR_BOLD COLOR_SEPARATOR COLOR_FG_CYAN) },
112 : { "region", SGR_SEQ (COLOR_BOLD COLOR_SEPARATOR COLOR_FG_GREEN) },
113 : { "scalar", SGR_SEQ (COLOR_BOLD COLOR_SEPARATOR COLOR_FG_RED) },
114 : { "svalue", SGR_SEQ (COLOR_BOLD COLOR_SEPARATOR COLOR_FG_YELLOW) }
115 : };
116 :
117 24 : class diagnostic_color_dict
118 : {
119 : public:
120 : diagnostic_color_dict (const color_default *default_values,
121 : size_t num_default_values);
122 :
123 : bool parse_envvar_value (const char *const envvar_value);
124 :
125 : const char *get_start_by_name (const char *name, size_t name_len) const;
126 32 : const char *get_start_by_name (const char *name) const
127 : {
128 32 : return get_start_by_name (name, strlen (name));
129 : }
130 :
131 : private:
132 15980908 : struct entry
133 : {
134 15980692 : entry (const color_default &d)
135 15980692 : : m_name (d.m_name),
136 15980692 : m_name_len (strlen (d.m_name)),
137 15980692 : m_val (label_text::borrow (d.m_val))
138 : {
139 : }
140 :
141 : const char *m_name;
142 : size_t m_name_len;
143 : label_text m_val;
144 : };
145 :
146 : const entry *get_entry_by_name (const char *name, size_t name_len) const;
147 : entry *get_entry_by_name (const char *name, size_t name_len);
148 :
149 : std::vector<entry> m_entries;
150 : };
151 :
152 : static diagnostic_color_dict *g_color_dict;
153 :
154 : const char *
155 102240275 : colorize_start (bool show_color, const char *name, size_t name_len)
156 : {
157 102240275 : if (!show_color)
158 : return "";
159 :
160 85921 : if (!g_color_dict)
161 : return "";
162 :
163 85921 : return g_color_dict->get_start_by_name (name, name_len);
164 : }
165 :
166 : /* Look for an entry named NAME of length NAME_LEN within this
167 : diagnostic_color_dict, or nullptr if there isn't one. */
168 :
169 : const diagnostic_color_dict::entry *
170 85953 : diagnostic_color_dict::get_entry_by_name (const char *name,
171 : size_t name_len) const
172 : {
173 1721654 : for (auto &iter : m_entries)
174 1721634 : if (iter.m_name_len == name_len
175 325645 : && memcmp (iter.m_name, name, name_len) == 0)
176 85953 : return &iter;
177 : return nullptr;
178 : }
179 :
180 : /* Non-const version of the above. */
181 :
182 : diagnostic_color_dict::entry *
183 12 : diagnostic_color_dict::get_entry_by_name (const char *name,
184 : size_t name_len)
185 : {
186 120 : for (auto &iter : m_entries)
187 116 : if (iter.m_name_len == name_len
188 12 : && memcmp (iter.m_name, name, name_len) == 0)
189 12 : return &iter;
190 : return nullptr;
191 : }
192 :
193 : /* Return the SGR codes to start a color entry named NAME of length
194 : NAME_LEN within this diagnostic_color_dict, or the empty string if
195 : there isn't one. */
196 :
197 : const char *
198 85953 : diagnostic_color_dict::get_start_by_name (const char *name,
199 : size_t name_len) const
200 : {
201 85953 : if (const entry *e = get_entry_by_name (name, name_len))
202 85933 : return e->m_val.get ();
203 :
204 : return "";
205 : }
206 :
207 : const char *
208 102067387 : colorize_stop (bool show_color)
209 : {
210 102067387 : return show_color ? SGR_RESET : "";
211 : }
212 :
213 : /* diagnostic_color_dict's ctor. Initialize it from the given array
214 : of color_default values. */
215 :
216 614646 : diagnostic_color_dict::
217 : diagnostic_color_dict (const color_default *default_values,
218 614646 : size_t num_default_values)
219 : {
220 614646 : m_entries.reserve (num_default_values);
221 17209984 : for (size_t idx = 0; idx < num_default_values; idx++)
222 15980692 : m_entries.push_back (entry (default_values[idx]));
223 614646 : }
224 :
225 : /* Parse a list of color definitions from an environment variable
226 : value (such as that of GCC_COLORS).
227 : No character escaping is needed or supported. */
228 :
229 : bool
230 509636 : diagnostic_color_dict::parse_envvar_value (const char *const envvar_value)
231 : {
232 : /* envvar not set: use the default colors. */
233 509636 : if (envvar_value == nullptr)
234 : return true;
235 :
236 : /* envvar set to empty string: disable colorization. */
237 52 : if (*envvar_value == '\0')
238 : return false;
239 :
240 : const char *q, *name, *val;
241 : size_t name_len = 0, val_len = 0;
242 :
243 : name = q = envvar_value;
244 : val = nullptr;
245 : /* From now on, be well-formed or you're gone. */
246 184 : for (;;)
247 184 : if (*q == ':' || *q == '\0')
248 : {
249 12 : if (val)
250 12 : val_len = q - val;
251 : else
252 0 : name_len = q - name;
253 : /* Empty name without val (empty cap)
254 : won't match and will be ignored. */
255 12 : entry *e = get_entry_by_name (name, name_len);
256 : /* If name unknown, go on for forward compatibility. */
257 12 : if (e && val)
258 : {
259 8 : char *b = XNEWVEC (char, val_len + sizeof (SGR_SEQ ("")));
260 8 : memcpy (b, SGR_START, strlen (SGR_START));
261 8 : memcpy (b + strlen (SGR_START), val, val_len);
262 8 : memcpy (b + strlen (SGR_START) + val_len, SGR_END,
263 : sizeof (SGR_END));
264 8 : e->m_val = label_text::take (b);
265 : }
266 12 : if (*q == '\0')
267 : return true;
268 8 : name = ++q;
269 8 : val = nullptr;
270 : }
271 172 : else if (*q == '=')
272 : {
273 12 : if (q == name || val)
274 : return true;
275 :
276 12 : name_len = q - name;
277 12 : val = ++q; /* Can be the empty string. */
278 : }
279 160 : else if (val == nullptr)
280 100 : q++; /* Accumulate name. */
281 60 : else if (*q == ';' || (*q >= '0' && *q <= '9'))
282 60 : q++; /* Accumulate val. Protect the terminal from being sent
283 : garbage. */
284 : else
285 : return true;
286 : }
287 :
288 : /* Parse GCC_COLORS. The default would look like:
289 : GCC_COLORS='error=01;31:warning=01;35:note=01;36:\
290 : range1=32:range2=34:locus=01:quote=01:path=01;36:\
291 : fixit-insert=32:fixit-delete=31:'\
292 : diff-filename=01:diff-hunk=32:diff-delete=31:diff-insert=32:\
293 : type-diff=01;32'. */
294 : static bool
295 509632 : parse_gcc_colors ()
296 : {
297 509632 : if (!g_color_dict)
298 : return false;
299 509632 : return g_color_dict->parse_envvar_value (getenv ("GCC_COLORS")); /* Plural! */
300 : }
301 :
302 : /* Return true if we should use color when in auto mode, false otherwise. */
303 : static bool
304 1234034 : should_colorize (void)
305 : {
306 : #ifdef __MINGW32__
307 : /* For consistency reasons, one should check the handle returned by
308 : _get_osfhandle(_fileno(stderr)) because the function
309 : pp_write_text_to_stream() in pretty-print.cc calls fputs() on
310 : that stream. However, the code below for non-Windows doesn't seem
311 : to care about it either... */
312 : HANDLE handle;
313 : DWORD mode;
314 : BOOL isconsole = false;
315 :
316 : handle = GetStdHandle (STD_ERROR_HANDLE);
317 :
318 : if ((handle != INVALID_HANDLE_VALUE) && (handle != nullptr))
319 : isconsole = GetConsoleMode (handle, &mode);
320 :
321 : #ifdef ENABLE_VIRTUAL_TERMINAL_PROCESSING
322 : if (isconsole)
323 : {
324 : /* Try to enable processing of VT100 escape sequences */
325 : mode |= ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING;
326 : SetConsoleMode (handle, mode);
327 : }
328 : #endif
329 :
330 : return isconsole;
331 : #else
332 1234034 : char const *t = getenv ("TERM");
333 : /* emacs M-x shell sets TERM="dumb". */
334 1234034 : return t && strcmp (t, "dumb") != 0 && isatty (STDERR_FILENO);
335 : #endif
336 : }
337 :
338 : bool
339 1468280 : colorize_init (diagnostic_color_rule_t rule)
340 : {
341 1468280 : if (!g_color_dict)
342 614634 : g_color_dict = new diagnostic_color_dict (gcc_color_defaults,
343 614634 : ARRAY_SIZE (gcc_color_defaults));
344 :
345 1468280 : switch (rule)
346 : {
347 : case DIAGNOSTICS_COLOR_NO:
348 : return false;
349 133 : case DIAGNOSTICS_COLOR_YES:
350 133 : return parse_gcc_colors ();
351 617017 : case DIAGNOSTICS_COLOR_AUTO:
352 617017 : if (should_colorize ())
353 509499 : return parse_gcc_colors ();
354 : else
355 : return false;
356 0 : default:
357 0 : gcc_unreachable ();
358 : }
359 : }
360 :
361 : /* Return URL_FORMAT_XXX which tells how we should emit urls
362 : when in always mode.
363 : We use GCC_URLS and if that is not defined TERM_URLS.
364 : If neither is defined the feature is enabled by default. */
365 :
366 : static diagnostic_url_format
367 0 : parse_env_vars_for_urls ()
368 : {
369 0 : const char *p;
370 :
371 0 : p = getenv ("GCC_URLS"); /* Plural! */
372 0 : if (p == nullptr)
373 0 : p = getenv ("TERM_URLS");
374 :
375 0 : if (p == nullptr)
376 : return URL_FORMAT_DEFAULT;
377 :
378 0 : if (*p == '\0')
379 : return URL_FORMAT_NONE;
380 :
381 0 : if (!strcmp (p, "no"))
382 : return URL_FORMAT_NONE;
383 :
384 0 : if (!strcmp (p, "st"))
385 0 : return URL_FORMAT_ST;
386 :
387 : if (!strcmp (p, "bel"))
388 : return URL_FORMAT_BEL;
389 :
390 : return URL_FORMAT_DEFAULT;
391 : }
392 :
393 : /* Return true if we should use urls when in auto mode, false otherwise. */
394 :
395 : static bool
396 617017 : auto_enable_urls ()
397 : {
398 617017 : const char *term, *colorterm;
399 :
400 : /* First check the terminal is capable of printing color escapes,
401 : if not URLs won't work either. */
402 617017 : if (!should_colorize ())
403 : return false;
404 :
405 : #ifdef __MINGW32__
406 : HANDLE handle;
407 : DWORD mode;
408 :
409 : handle = GetStdHandle (STD_ERROR_HANDLE);
410 : if ((handle == INVALID_HANDLE_VALUE) || (handle == nullptr))
411 : return false;
412 :
413 : /* If ansi escape sequences aren't supported by the console, then URLs will
414 : print mangled from mingw_ansi_fputs's console API translation. It wouldn't
415 : be useful even if this weren't the case. */
416 : if (GetConsoleMode (handle, &mode)
417 : #ifdef ENABLE_VIRTUAL_TERMINAL_PROCESSING
418 : && !(mode & ENABLE_VIRTUAL_TERMINAL_PROCESSING)
419 : #endif
420 : )
421 : return false;
422 : #endif
423 :
424 : /* xfce4-terminal is known to not implement URLs at this time.
425 : Recently new installations (0.8) will safely ignore the URL escape
426 : sequences, but a large number of legacy installations (0.6.3) print
427 : garbage when URLs are printed. Therefore we lose nothing by
428 : disabling this feature for that specific terminal type. */
429 509499 : colorterm = getenv ("COLORTERM");
430 509499 : if (colorterm && !strcmp (colorterm, "xfce4-terminal"))
431 : return false;
432 :
433 : /* Old versions of gnome-terminal where URL escapes cause screen
434 : corruptions set COLORTERM="gnome-terminal", recent versions
435 : with working URL support set this to "truecolor". */
436 0 : if (colorterm && !strcmp (colorterm, "gnome-terminal"))
437 : return false;
438 :
439 : /* Since the following checks are less specific than the ones
440 : above, let GCC_URLS and TERM_URLS override the decision. */
441 509499 : if (getenv ("GCC_URLS") || getenv ("TERM_URLS"))
442 : return true;
443 :
444 : /* In an ssh session the COLORTERM is not there, but TERM=xterm
445 : can be used as an indication of a incompatible terminal while
446 : TERM=xterm-256color appears to be a working terminal. */
447 509499 : term = getenv ("TERM");
448 509499 : if (!colorterm && term && !strcmp (term, "xterm"))
449 : return false;
450 :
451 : /* When logging in a linux over serial line, we see TERM=linux
452 : and no COLORTERM, it is unlikely that the URL escapes will
453 : work in that environment either. */
454 0 : if (!colorterm && term && !strcmp (term, "linux"))
455 0 : return false;
456 :
457 : return true;
458 : }
459 :
460 : /* Determine if URLs should be enabled, based on RULE,
461 : and, if so, which format to use.
462 : This reuses the logic for colorization. */
463 :
464 : diagnostic_url_format
465 1450909 : determine_url_format (diagnostic_url_rule_t rule)
466 : {
467 1450909 : switch (rule)
468 : {
469 : case DIAGNOSTICS_URL_NO:
470 : return URL_FORMAT_NONE;
471 0 : case DIAGNOSTICS_URL_YES:
472 0 : return parse_env_vars_for_urls ();
473 617017 : case DIAGNOSTICS_URL_AUTO:
474 617017 : if (auto_enable_urls ())
475 0 : return parse_env_vars_for_urls ();
476 : else
477 : return URL_FORMAT_NONE;
478 0 : default:
479 0 : gcc_unreachable ();
480 : }
481 : }
482 :
483 : #if CHECKING_P
484 :
485 : namespace diagnostics {
486 : namespace selftest {
487 :
488 : /* Test of an empty diagnostic_color_dict. */
489 :
490 : static void
491 4 : test_empty_color_dict ()
492 : {
493 4 : diagnostic_color_dict d (nullptr, 0);
494 4 : ASSERT_STREQ (d.get_start_by_name ("warning"), "");
495 4 : ASSERT_STREQ (d.get_start_by_name ("should-not-be-found"), "");
496 4 : }
497 :
498 : /* Test of a diagnostic_color_dict with GCC's defaults. */
499 :
500 : static void
501 4 : test_default_color_dict ()
502 : {
503 4 : diagnostic_color_dict d (gcc_color_defaults,
504 4 : ARRAY_SIZE (gcc_color_defaults));
505 4 : ASSERT_STREQ (d.get_start_by_name ("warning"),
506 : SGR_SEQ (COLOR_BOLD COLOR_SEPARATOR COLOR_FG_MAGENTA));
507 4 : ASSERT_STREQ (d.get_start_by_name ("should-not-be-found"), "");
508 4 : }
509 :
510 : /* Test of a diagnostic_color_dict with GCC's defaults plus overrides from
511 : an environment variable. */
512 :
513 : static void
514 4 : test_color_dict_envvar_parsing ()
515 : {
516 4 : diagnostic_color_dict d (gcc_color_defaults,
517 4 : ARRAY_SIZE (gcc_color_defaults));
518 :
519 4 : d.parse_envvar_value ("error=01;37:warning=01;42:unknown-value=01;36");
520 :
521 4 : ASSERT_STREQ (d.get_start_by_name ("error"),
522 : SGR_SEQ ("01;37"));
523 4 : ASSERT_STREQ (d.get_start_by_name ("warning"),
524 : SGR_SEQ ("01;42"));
525 4 : ASSERT_STREQ (d.get_start_by_name ("unknown-value"), "");
526 4 : ASSERT_STREQ (d.get_start_by_name ("should-not-be-found"), "");
527 4 : }
528 :
529 :
530 : /* Run all of the selftests within this file. */
531 :
532 : void
533 4 : color_cc_tests ()
534 : {
535 4 : test_empty_color_dict ();
536 4 : test_default_color_dict ();
537 4 : test_color_dict_envvar_parsing ();
538 4 : }
539 :
540 : } // namespace selftest
541 : } // namespace diagnostics
542 :
543 : #endif /* #if CHECKING_P */
|