clang 20.0.0git
TextDiagnostic.cpp
Go to the documentation of this file.
1//===--- TextDiagnostic.cpp - Text Diagnostic Pretty-Printing -------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
14#include "clang/Lex/Lexer.h"
16#include "llvm/ADT/SmallString.h"
17#include "llvm/ADT/StringExtras.h"
18#include "llvm/Support/ConvertUTF.h"
19#include "llvm/Support/ErrorHandling.h"
20#include "llvm/Support/Locale.h"
21#include "llvm/Support/Path.h"
22#include "llvm/Support/raw_ostream.h"
23#include <algorithm>
24#include <optional>
25
26using namespace clang;
27
28static const enum raw_ostream::Colors noteColor = raw_ostream::CYAN;
29static const enum raw_ostream::Colors remarkColor =
30 raw_ostream::BLUE;
31static const enum raw_ostream::Colors fixitColor =
32 raw_ostream::GREEN;
33static const enum raw_ostream::Colors caretColor =
34 raw_ostream::GREEN;
35static const enum raw_ostream::Colors warningColor =
36 raw_ostream::MAGENTA;
37static const enum raw_ostream::Colors templateColor =
38 raw_ostream::CYAN;
39static const enum raw_ostream::Colors errorColor = raw_ostream::RED;
40static const enum raw_ostream::Colors fatalColor = raw_ostream::RED;
41// Used for changing only the bold attribute.
42static const enum raw_ostream::Colors savedColor =
43 raw_ostream::SAVEDCOLOR;
44
45// Magenta is taken for 'warning'. Red is already 'error' and 'cyan'
46// is already taken for 'note'. Green is already used to underline
47// source ranges. White and black are bad because of the usual
48// terminal backgrounds. Which leaves us only with TWO options.
49static constexpr raw_ostream::Colors CommentColor = raw_ostream::YELLOW;
50static constexpr raw_ostream::Colors LiteralColor = raw_ostream::GREEN;
51static constexpr raw_ostream::Colors KeywordColor = raw_ostream::BLUE;
52
53/// Add highlights to differences in template strings.
54static void applyTemplateHighlighting(raw_ostream &OS, StringRef Str,
55 bool &Normal, bool Bold) {
56 while (true) {
57 size_t Pos = Str.find(ToggleHighlight);
58 OS << Str.slice(0, Pos);
59 if (Pos == StringRef::npos)
60 break;
61
62 Str = Str.substr(Pos + 1);
63 if (Normal)
64 OS.changeColor(templateColor, true);
65 else {
66 OS.resetColor();
67 if (Bold)
68 OS.changeColor(savedColor, true);
69 }
70 Normal = !Normal;
71 }
72}
73
74/// Number of spaces to indent when word-wrapping.
75const unsigned WordWrapIndentation = 6;
76
77static int bytesSincePreviousTabOrLineBegin(StringRef SourceLine, size_t i) {
78 int bytes = 0;
79 while (0<i) {
80 if (SourceLine[--i]=='\t')
81 break;
82 ++bytes;
83 }
84 return bytes;
85}
86
87/// returns a printable representation of first item from input range
88///
89/// This function returns a printable representation of the next item in a line
90/// of source. If the next byte begins a valid and printable character, that
91/// character is returned along with 'true'.
92///
93/// Otherwise, if the next byte begins a valid, but unprintable character, a
94/// printable, escaped representation of the character is returned, along with
95/// 'false'. Otherwise a printable, escaped representation of the next byte
96/// is returned along with 'false'.
97///
98/// \note The index is updated to be used with a subsequent call to
99/// printableTextForNextCharacter.
100///
101/// \param SourceLine The line of source
102/// \param I Pointer to byte index,
103/// \param TabStop used to expand tabs
104/// \return pair(printable text, 'true' iff original text was printable)
105///
106static std::pair<SmallString<16>, bool>
107printableTextForNextCharacter(StringRef SourceLine, size_t *I,
108 unsigned TabStop) {
109 assert(I && "I must not be null");
110 assert(*I < SourceLine.size() && "must point to a valid index");
111
112 if (SourceLine[*I] == '\t') {
113 assert(0 < TabStop && TabStop <= DiagnosticOptions::MaxTabStop &&
114 "Invalid -ftabstop value");
115 unsigned Col = bytesSincePreviousTabOrLineBegin(SourceLine, *I);
116 unsigned NumSpaces = TabStop - (Col % TabStop);
117 assert(0 < NumSpaces && NumSpaces <= TabStop
118 && "Invalid computation of space amt");
119 ++(*I);
120
121 SmallString<16> ExpandedTab;
122 ExpandedTab.assign(NumSpaces, ' ');
123 return std::make_pair(ExpandedTab, true);
124 }
125
126 const unsigned char *Begin = SourceLine.bytes_begin() + *I;
127
128 // Fast path for the common ASCII case.
129 if (*Begin < 0x80 && llvm::sys::locale::isPrint(*Begin)) {
130 ++(*I);
131 return std::make_pair(SmallString<16>(Begin, Begin + 1), true);
132 }
133 unsigned CharSize = llvm::getNumBytesForUTF8(*Begin);
134 const unsigned char *End = Begin + CharSize;
135
136 // Convert it to UTF32 and check if it's printable.
137 if (End <= SourceLine.bytes_end() && llvm::isLegalUTF8Sequence(Begin, End)) {
138 llvm::UTF32 C;
139 llvm::UTF32 *CPtr = &C;
140
141 // Begin and end before conversion.
142 unsigned char const *OriginalBegin = Begin;
143 llvm::ConversionResult Res = llvm::ConvertUTF8toUTF32(
144 &Begin, End, &CPtr, CPtr + 1, llvm::strictConversion);
145 (void)Res;
146 assert(Res == llvm::conversionOK);
147 assert(OriginalBegin < Begin);
148 assert(unsigned(Begin - OriginalBegin) == CharSize);
149
150 (*I) += (Begin - OriginalBegin);
151
152 // Valid, multi-byte, printable UTF8 character.
153 if (llvm::sys::locale::isPrint(C))
154 return std::make_pair(SmallString<16>(OriginalBegin, End), true);
155
156 // Valid but not printable.
157 SmallString<16> Str("<U+>");
158 while (C) {
159 Str.insert(Str.begin() + 3, llvm::hexdigit(C % 16));
160 C /= 16;
161 }
162 while (Str.size() < 8)
163 Str.insert(Str.begin() + 3, llvm::hexdigit(0));
164 return std::make_pair(Str, false);
165 }
166
167 // Otherwise, not printable since it's not valid UTF8.
168 SmallString<16> ExpandedByte("<XX>");
169 unsigned char Byte = SourceLine[*I];
170 ExpandedByte[1] = llvm::hexdigit(Byte / 16);
171 ExpandedByte[2] = llvm::hexdigit(Byte % 16);
172 ++(*I);
173 return std::make_pair(ExpandedByte, false);
174}
175
176static void expandTabs(std::string &SourceLine, unsigned TabStop) {
177 size_t I = SourceLine.size();
178 while (I > 0) {
179 I--;
180 if (SourceLine[I] != '\t')
181 continue;
182 size_t TmpI = I;
183 auto [Str, Printable] =
184 printableTextForNextCharacter(SourceLine, &TmpI, TabStop);
185 SourceLine.replace(I, 1, Str.c_str());
186 }
187}
188
189/// \p BytesOut:
190/// A mapping from columns to the byte of the source line that produced the
191/// character displaying at that column. This is the inverse of \p ColumnsOut.
192///
193/// The last element in the array is the number of bytes in the source string.
194///
195/// example: (given a tabstop of 8)
196///
197/// "a \t \u3042" -> {0,1,2,-1,-1,-1,-1,-1,3,4,-1,7}
198///
199/// (\\u3042 is represented in UTF-8 by three bytes and takes two columns to
200/// display)
201///
202/// \p ColumnsOut:
203/// A mapping from the bytes
204/// of the printable representation of the line to the columns those printable
205/// characters will appear at (numbering the first column as 0).
206///
207/// If a byte 'i' corresponds to multiple columns (e.g. the byte contains a tab
208/// character) then the array will map that byte to the first column the
209/// tab appears at and the next value in the map will have been incremented
210/// more than once.
211///
212/// If a byte is the first in a sequence of bytes that together map to a single
213/// entity in the output, then the array will map that byte to the appropriate
214/// column while the subsequent bytes will be -1.
215///
216/// The last element in the array does not correspond to any byte in the input
217/// and instead is the number of columns needed to display the source
218///
219/// example: (given a tabstop of 8)
220///
221/// "a \t \u3042" -> {0,1,2,8,9,-1,-1,11}
222///
223/// (\\u3042 is represented in UTF-8 by three bytes and takes two columns to
224/// display)
225static void genColumnByteMapping(StringRef SourceLine, unsigned TabStop,
226 SmallVectorImpl<int> &BytesOut,
227 SmallVectorImpl<int> &ColumnsOut) {
228 assert(BytesOut.empty());
229 assert(ColumnsOut.empty());
230
231 if (SourceLine.empty()) {
232 BytesOut.resize(1u, 0);
233 ColumnsOut.resize(1u, 0);
234 return;
235 }
236
237 ColumnsOut.resize(SourceLine.size() + 1, -1);
238
239 int Columns = 0;
240 size_t I = 0;
241 while (I < SourceLine.size()) {
242 ColumnsOut[I] = Columns;
243 BytesOut.resize(Columns + 1, -1);
244 BytesOut.back() = I;
245 auto [Str, Printable] =
246 printableTextForNextCharacter(SourceLine, &I, TabStop);
247 Columns += llvm::sys::locale::columnWidth(Str);
248 }
249
250 ColumnsOut.back() = Columns;
251 BytesOut.resize(Columns + 1, -1);
252 BytesOut.back() = I;
253}
254
255namespace {
256struct SourceColumnMap {
257 SourceColumnMap(StringRef SourceLine, unsigned TabStop)
258 : m_SourceLine(SourceLine) {
259
260 genColumnByteMapping(SourceLine, TabStop, m_columnToByte, m_byteToColumn);
261
262 assert(m_byteToColumn.size()==SourceLine.size()+1);
263 assert(0 < m_byteToColumn.size() && 0 < m_columnToByte.size());
264 assert(m_byteToColumn.size()
265 == static_cast<unsigned>(m_columnToByte.back()+1));
266 assert(static_cast<unsigned>(m_byteToColumn.back()+1)
267 == m_columnToByte.size());
268 }
269 int columns() const { return m_byteToColumn.back(); }
270 int bytes() const { return m_columnToByte.back(); }
271
272 /// Map a byte to the column which it is at the start of, or return -1
273 /// if it is not at the start of a column (for a UTF-8 trailing byte).
274 int byteToColumn(int n) const {
275 assert(0<=n && n<static_cast<int>(m_byteToColumn.size()));
276 return m_byteToColumn[n];
277 }
278
279 /// Map a byte to the first column which contains it.
280 int byteToContainingColumn(int N) const {
281 assert(0 <= N && N < static_cast<int>(m_byteToColumn.size()));
282 while (m_byteToColumn[N] == -1)
283 --N;
284 return m_byteToColumn[N];
285 }
286
287 /// Map a column to the byte which starts the column, or return -1 if
288 /// the column the second or subsequent column of an expanded tab or similar
289 /// multi-column entity.
290 int columnToByte(int n) const {
291 assert(0<=n && n<static_cast<int>(m_columnToByte.size()));
292 return m_columnToByte[n];
293 }
294
295 /// Map from a byte index to the next byte which starts a column.
296 int startOfNextColumn(int N) const {
297 assert(0 <= N && N < static_cast<int>(m_byteToColumn.size() - 1));
298 while (byteToColumn(++N) == -1) {}
299 return N;
300 }
301
302 /// Map from a byte index to the previous byte which starts a column.
303 int startOfPreviousColumn(int N) const {
304 assert(0 < N && N < static_cast<int>(m_byteToColumn.size()));
305 while (byteToColumn(--N) == -1) {}
306 return N;
307 }
308
309 StringRef getSourceLine() const {
310 return m_SourceLine;
311 }
312
313private:
314 const std::string m_SourceLine;
315 SmallVector<int,200> m_byteToColumn;
316 SmallVector<int,200> m_columnToByte;
317};
318} // end anonymous namespace
319
320/// When the source code line we want to print is too long for
321/// the terminal, select the "interesting" region.
322static void selectInterestingSourceRegion(std::string &SourceLine,
323 std::string &CaretLine,
324 std::string &FixItInsertionLine,
325 unsigned Columns,
326 const SourceColumnMap &map) {
327 unsigned CaretColumns = CaretLine.size();
328 unsigned FixItColumns = llvm::sys::locale::columnWidth(FixItInsertionLine);
329 unsigned MaxColumns = std::max(static_cast<unsigned>(map.columns()),
330 std::max(CaretColumns, FixItColumns));
331 // if the number of columns is less than the desired number we're done
332 if (MaxColumns <= Columns)
333 return;
334
335 // No special characters are allowed in CaretLine.
336 assert(llvm::none_of(CaretLine, [](char c) { return c < ' ' || '~' < c; }));
337
338 // Find the slice that we need to display the full caret line
339 // correctly.
340 unsigned CaretStart = 0, CaretEnd = CaretLine.size();
341 for (; CaretStart != CaretEnd; ++CaretStart)
342 if (!isWhitespace(CaretLine[CaretStart]))
343 break;
344
345 for (; CaretEnd != CaretStart; --CaretEnd)
346 if (!isWhitespace(CaretLine[CaretEnd - 1]))
347 break;
348
349 // caret has already been inserted into CaretLine so the above whitespace
350 // check is guaranteed to include the caret
351
352 // If we have a fix-it line, make sure the slice includes all of the
353 // fix-it information.
354 if (!FixItInsertionLine.empty()) {
355 unsigned FixItStart = 0, FixItEnd = FixItInsertionLine.size();
356 for (; FixItStart != FixItEnd; ++FixItStart)
357 if (!isWhitespace(FixItInsertionLine[FixItStart]))
358 break;
359
360 for (; FixItEnd != FixItStart; --FixItEnd)
361 if (!isWhitespace(FixItInsertionLine[FixItEnd - 1]))
362 break;
363
364 // We can safely use the byte offset FixItStart as the column offset
365 // because the characters up until FixItStart are all ASCII whitespace
366 // characters.
367 unsigned FixItStartCol = FixItStart;
368 unsigned FixItEndCol
369 = llvm::sys::locale::columnWidth(FixItInsertionLine.substr(0, FixItEnd));
370
371 CaretStart = std::min(FixItStartCol, CaretStart);
372 CaretEnd = std::max(FixItEndCol, CaretEnd);
373 }
374
375 // CaretEnd may have been set at the middle of a character
376 // If it's not at a character's first column then advance it past the current
377 // character.
378 while (static_cast<int>(CaretEnd) < map.columns() &&
379 -1 == map.columnToByte(CaretEnd))
380 ++CaretEnd;
381
382 assert((static_cast<int>(CaretStart) > map.columns() ||
383 -1!=map.columnToByte(CaretStart)) &&
384 "CaretStart must not point to a column in the middle of a source"
385 " line character");
386 assert((static_cast<int>(CaretEnd) > map.columns() ||
387 -1!=map.columnToByte(CaretEnd)) &&
388 "CaretEnd must not point to a column in the middle of a source line"
389 " character");
390
391 // CaretLine[CaretStart, CaretEnd) contains all of the interesting
392 // parts of the caret line. While this slice is smaller than the
393 // number of columns we have, try to grow the slice to encompass
394 // more context.
395
396 unsigned SourceStart = map.columnToByte(std::min<unsigned>(CaretStart,
397 map.columns()));
398 unsigned SourceEnd = map.columnToByte(std::min<unsigned>(CaretEnd,
399 map.columns()));
400
401 unsigned CaretColumnsOutsideSource = CaretEnd-CaretStart
402 - (map.byteToColumn(SourceEnd)-map.byteToColumn(SourceStart));
403
404 char const *front_ellipse = " ...";
405 char const *front_space = " ";
406 char const *back_ellipse = "...";
407 unsigned ellipses_space = strlen(front_ellipse) + strlen(back_ellipse);
408
409 unsigned TargetColumns = Columns;
410 // Give us extra room for the ellipses
411 // and any of the caret line that extends past the source
412 if (TargetColumns > ellipses_space+CaretColumnsOutsideSource)
413 TargetColumns -= ellipses_space+CaretColumnsOutsideSource;
414
415 while (SourceStart>0 || SourceEnd<SourceLine.size()) {
416 bool ExpandedRegion = false;
417
418 if (SourceStart>0) {
419 unsigned NewStart = map.startOfPreviousColumn(SourceStart);
420
421 // Skip over any whitespace we see here; we're looking for
422 // another bit of interesting text.
423 // FIXME: Detect non-ASCII whitespace characters too.
424 while (NewStart && isWhitespace(SourceLine[NewStart]))
425 NewStart = map.startOfPreviousColumn(NewStart);
426
427 // Skip over this bit of "interesting" text.
428 while (NewStart) {
429 unsigned Prev = map.startOfPreviousColumn(NewStart);
430 if (isWhitespace(SourceLine[Prev]))
431 break;
432 NewStart = Prev;
433 }
434
435 assert(map.byteToColumn(NewStart) != -1);
436 unsigned NewColumns = map.byteToColumn(SourceEnd) -
437 map.byteToColumn(NewStart);
438 if (NewColumns <= TargetColumns) {
439 SourceStart = NewStart;
440 ExpandedRegion = true;
441 }
442 }
443
444 if (SourceEnd<SourceLine.size()) {
445 unsigned NewEnd = map.startOfNextColumn(SourceEnd);
446
447 // Skip over any whitespace we see here; we're looking for
448 // another bit of interesting text.
449 // FIXME: Detect non-ASCII whitespace characters too.
450 while (NewEnd < SourceLine.size() && isWhitespace(SourceLine[NewEnd]))
451 NewEnd = map.startOfNextColumn(NewEnd);
452
453 // Skip over this bit of "interesting" text.
454 while (NewEnd < SourceLine.size() && isWhitespace(SourceLine[NewEnd]))
455 NewEnd = map.startOfNextColumn(NewEnd);
456
457 assert(map.byteToColumn(NewEnd) != -1);
458 unsigned NewColumns = map.byteToColumn(NewEnd) -
459 map.byteToColumn(SourceStart);
460 if (NewColumns <= TargetColumns) {
461 SourceEnd = NewEnd;
462 ExpandedRegion = true;
463 }
464 }
465
466 if (!ExpandedRegion)
467 break;
468 }
469
470 CaretStart = map.byteToColumn(SourceStart);
471 CaretEnd = map.byteToColumn(SourceEnd) + CaretColumnsOutsideSource;
472
473 // [CaretStart, CaretEnd) is the slice we want. Update the various
474 // output lines to show only this slice.
475 assert(CaretStart!=(unsigned)-1 && CaretEnd!=(unsigned)-1 &&
476 SourceStart!=(unsigned)-1 && SourceEnd!=(unsigned)-1);
477 assert(SourceStart <= SourceEnd);
478 assert(CaretStart <= CaretEnd);
479
480 unsigned BackColumnsRemoved
481 = map.byteToColumn(SourceLine.size())-map.byteToColumn(SourceEnd);
482 unsigned FrontColumnsRemoved = CaretStart;
483 unsigned ColumnsKept = CaretEnd-CaretStart;
484
485 // We checked up front that the line needed truncation
486 assert(FrontColumnsRemoved+ColumnsKept+BackColumnsRemoved > Columns);
487
488 // The line needs some truncation, and we'd prefer to keep the front
489 // if possible, so remove the back
490 if (BackColumnsRemoved > strlen(back_ellipse))
491 SourceLine.replace(SourceEnd, std::string::npos, back_ellipse);
492
493 // If that's enough then we're done
494 if (FrontColumnsRemoved+ColumnsKept <= Columns)
495 return;
496
497 // Otherwise remove the front as well
498 if (FrontColumnsRemoved > strlen(front_ellipse)) {
499 SourceLine.replace(0, SourceStart, front_ellipse);
500 CaretLine.replace(0, CaretStart, front_space);
501 if (!FixItInsertionLine.empty())
502 FixItInsertionLine.replace(0, CaretStart, front_space);
503 }
504}
505
506/// Skip over whitespace in the string, starting at the given
507/// index.
508///
509/// \returns The index of the first non-whitespace character that is
510/// greater than or equal to Idx or, if no such character exists,
511/// returns the end of the string.
512static unsigned skipWhitespace(unsigned Idx, StringRef Str, unsigned Length) {
513 while (Idx < Length && isWhitespace(Str[Idx]))
514 ++Idx;
515 return Idx;
516}
517
518/// If the given character is the start of some kind of
519/// balanced punctuation (e.g., quotes or parentheses), return the
520/// character that will terminate the punctuation.
521///
522/// \returns The ending punctuation character, if any, or the NULL
523/// character if the input character does not start any punctuation.
524static inline char findMatchingPunctuation(char c) {
525 switch (c) {
526 case '\'': return '\'';
527 case '`': return '\'';
528 case '"': return '"';
529 case '(': return ')';
530 case '[': return ']';
531 case '{': return '}';
532 default: break;
533 }
534
535 return 0;
536}
537
538/// Find the end of the word starting at the given offset
539/// within a string.
540///
541/// \returns the index pointing one character past the end of the
542/// word.
543static unsigned findEndOfWord(unsigned Start, StringRef Str,
544 unsigned Length, unsigned Column,
545 unsigned Columns) {
546 assert(Start < Str.size() && "Invalid start position!");
547 unsigned End = Start + 1;
548
549 // If we are already at the end of the string, take that as the word.
550 if (End == Str.size())
551 return End;
552
553 // Determine if the start of the string is actually opening
554 // punctuation, e.g., a quote or parentheses.
555 char EndPunct = findMatchingPunctuation(Str[Start]);
556 if (!EndPunct) {
557 // This is a normal word. Just find the first space character.
558 while (End < Length && !isWhitespace(Str[End]))
559 ++End;
560 return End;
561 }
562
563 // We have the start of a balanced punctuation sequence (quotes,
564 // parentheses, etc.). Determine the full sequence is.
565 SmallString<16> PunctuationEndStack;
566 PunctuationEndStack.push_back(EndPunct);
567 while (End < Length && !PunctuationEndStack.empty()) {
568 if (Str[End] == PunctuationEndStack.back())
569 PunctuationEndStack.pop_back();
570 else if (char SubEndPunct = findMatchingPunctuation(Str[End]))
571 PunctuationEndStack.push_back(SubEndPunct);
572
573 ++End;
574 }
575
576 // Find the first space character after the punctuation ended.
577 while (End < Length && !isWhitespace(Str[End]))
578 ++End;
579
580 unsigned PunctWordLength = End - Start;
581 if (// If the word fits on this line
582 Column + PunctWordLength <= Columns ||
583 // ... or the word is "short enough" to take up the next line
584 // without too much ugly white space
585 PunctWordLength < Columns/3)
586 return End; // Take the whole thing as a single "word".
587
588 // The whole quoted/parenthesized string is too long to print as a
589 // single "word". Instead, find the "word" that starts just after
590 // the punctuation and use that end-point instead. This will recurse
591 // until it finds something small enough to consider a word.
592 return findEndOfWord(Start + 1, Str, Length, Column + 1, Columns);
593}
594
595/// Print the given string to a stream, word-wrapping it to
596/// some number of columns in the process.
597///
598/// \param OS the stream to which the word-wrapping string will be
599/// emitted.
600/// \param Str the string to word-wrap and output.
601/// \param Columns the number of columns to word-wrap to.
602/// \param Column the column number at which the first character of \p
603/// Str will be printed. This will be non-zero when part of the first
604/// line has already been printed.
605/// \param Bold if the current text should be bold
606/// \returns true if word-wrapping was required, or false if the
607/// string fit on the first line.
608static bool printWordWrapped(raw_ostream &OS, StringRef Str, unsigned Columns,
609 unsigned Column, bool Bold) {
610 const unsigned Length = std::min(Str.find('\n'), Str.size());
611 bool TextNormal = true;
612
613 bool Wrapped = false;
614 for (unsigned WordStart = 0, WordEnd; WordStart < Length;
615 WordStart = WordEnd) {
616 // Find the beginning of the next word.
617 WordStart = skipWhitespace(WordStart, Str, Length);
618 if (WordStart == Length)
619 break;
620
621 // Find the end of this word.
622 WordEnd = findEndOfWord(WordStart, Str, Length, Column, Columns);
623
624 // Does this word fit on the current line?
625 unsigned WordLength = WordEnd - WordStart;
626 if (Column + WordLength < Columns) {
627 // This word fits on the current line; print it there.
628 if (WordStart) {
629 OS << ' ';
630 Column += 1;
631 }
632 applyTemplateHighlighting(OS, Str.substr(WordStart, WordLength),
633 TextNormal, Bold);
634 Column += WordLength;
635 continue;
636 }
637
638 // This word does not fit on the current line, so wrap to the next
639 // line.
640 OS << '\n';
641 OS.indent(WordWrapIndentation);
642 applyTemplateHighlighting(OS, Str.substr(WordStart, WordLength),
643 TextNormal, Bold);
644 Column = WordWrapIndentation + WordLength;
645 Wrapped = true;
646 }
647
648 // Append any remaning text from the message with its existing formatting.
649 applyTemplateHighlighting(OS, Str.substr(Length), TextNormal, Bold);
650
651 assert(TextNormal && "Text highlighted at end of diagnostic message.");
652
653 return Wrapped;
654}
655
656TextDiagnostic::TextDiagnostic(raw_ostream &OS, const LangOptions &LangOpts,
657 DiagnosticOptions *DiagOpts,
658 const Preprocessor *PP)
659 : DiagnosticRenderer(LangOpts, DiagOpts), OS(OS), PP(PP) {}
660
662
665 StringRef Message, ArrayRef<clang::CharSourceRange> Ranges,
667 uint64_t StartOfLocationInfo = OS.tell();
668
669 // Emit the location of this particular diagnostic.
670 if (Loc.isValid())
671 emitDiagnosticLoc(Loc, PLoc, Level, Ranges);
672
673 if (DiagOpts->ShowColors)
674 OS.resetColor();
675
676 if (DiagOpts->ShowLevel)
677 printDiagnosticLevel(OS, Level, DiagOpts->ShowColors);
679 /*IsSupplemental*/ Level == DiagnosticsEngine::Note,
680 Message, OS.tell() - StartOfLocationInfo,
681 DiagOpts->MessageLength, DiagOpts->ShowColors);
682}
683
684/*static*/ void
687 bool ShowColors) {
688 if (ShowColors) {
689 // Print diagnostic category in bold and color
690 switch (Level) {
692 llvm_unreachable("Invalid diagnostic type");
693 case DiagnosticsEngine::Note: OS.changeColor(noteColor, true); break;
694 case DiagnosticsEngine::Remark: OS.changeColor(remarkColor, true); break;
695 case DiagnosticsEngine::Warning: OS.changeColor(warningColor, true); break;
696 case DiagnosticsEngine::Error: OS.changeColor(errorColor, true); break;
697 case DiagnosticsEngine::Fatal: OS.changeColor(fatalColor, true); break;
698 }
699 }
700
701 switch (Level) {
703 llvm_unreachable("Invalid diagnostic type");
704 case DiagnosticsEngine::Note: OS << "note: "; break;
705 case DiagnosticsEngine::Remark: OS << "remark: "; break;
706 case DiagnosticsEngine::Warning: OS << "warning: "; break;
707 case DiagnosticsEngine::Error: OS << "error: "; break;
708 case DiagnosticsEngine::Fatal: OS << "fatal error: "; break;
709 }
710
711 if (ShowColors)
712 OS.resetColor();
713}
714
715/*static*/
717 bool IsSupplemental,
718 StringRef Message,
719 unsigned CurrentColumn,
720 unsigned Columns, bool ShowColors) {
721 bool Bold = false;
722 if (ShowColors && !IsSupplemental) {
723 // Print primary diagnostic messages in bold and without color, to visually
724 // indicate the transition from continuation notes and other output.
725 OS.changeColor(savedColor, true);
726 Bold = true;
727 }
728
729 if (Columns)
730 printWordWrapped(OS, Message, Columns, CurrentColumn, Bold);
731 else {
732 bool Normal = true;
733 applyTemplateHighlighting(OS, Message, Normal, Bold);
734 assert(Normal && "Formatting should have returned to normal");
735 }
736
737 if (ShowColors)
738 OS.resetColor();
739 OS << '\n';
740}
741
742void TextDiagnostic::emitFilename(StringRef Filename, const SourceManager &SM) {
743#ifdef _WIN32
744 SmallString<4096> TmpFilename;
745#endif
746 if (DiagOpts->AbsolutePath) {
747 auto File = SM.getFileManager().getOptionalFileRef(Filename);
748 if (File) {
749 // We want to print a simplified absolute path, i. e. without "dots".
750 //
751 // The hardest part here are the paths like "<part1>/<link>/../<part2>".
752 // On Unix-like systems, we cannot just collapse "<link>/..", because
753 // paths are resolved sequentially, and, thereby, the path
754 // "<part1>/<part2>" may point to a different location. That is why
755 // we use FileManager::getCanonicalName(), which expands all indirections
756 // with llvm::sys::fs::real_path() and caches the result.
757 //
758 // On the other hand, it would be better to preserve as much of the
759 // original path as possible, because that helps a user to recognize it.
760 // real_path() expands all links, which sometimes too much. Luckily,
761 // on Windows we can just use llvm::sys::path::remove_dots(), because,
762 // on that system, both aforementioned paths point to the same place.
763#ifdef _WIN32
764 TmpFilename = File->getName();
765 llvm::sys::fs::make_absolute(TmpFilename);
766 llvm::sys::path::native(TmpFilename);
767 llvm::sys::path::remove_dots(TmpFilename, /* remove_dot_dot */ true);
768 Filename = StringRef(TmpFilename.data(), TmpFilename.size());
769#else
770 Filename = SM.getFileManager().getCanonicalName(*File);
771#endif
772 }
773 }
774
775 OS << Filename;
776}
777
778/// Print out the file/line/column information and include trace.
779///
780/// This method handles the emission of the diagnostic location information.
781/// This includes extracting as much location information as is present for
782/// the diagnostic and printing it, as well as any include stack or source
783/// ranges necessary.
787 if (PLoc.isInvalid()) {
788 // At least print the file name if available:
789 if (FileID FID = Loc.getFileID(); FID.isValid()) {
790 if (OptionalFileEntryRef FE = Loc.getFileEntryRef()) {
791 emitFilename(FE->getName(), Loc.getManager());
792 OS << ": ";
793 }
794 }
795 return;
796 }
797 unsigned LineNo = PLoc.getLine();
798
799 if (!DiagOpts->ShowLocation)
800 return;
801
802 if (DiagOpts->ShowColors)
803 OS.changeColor(