1 //===--- TextDiagnostic.cpp - Text Diagnostic Pretty-Printing -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "clang/Frontend/TextDiagnostic.h"
11 #include "clang/Basic/CharInfo.h"
12 #include "clang/Basic/DiagnosticOptions.h"
13 #include "clang/Basic/FileManager.h"
14 #include "clang/Basic/SourceManager.h"
15 #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"
25 using namespace clang;
27 static const enum raw_ostream::Colors noteColor =
29 static const enum raw_ostream::Colors remarkColor =
31 static const enum raw_ostream::Colors fixitColor =
33 static const enum raw_ostream::Colors caretColor =
35 static const enum raw_ostream::Colors warningColor =
37 static const enum raw_ostream::Colors templateColor =
39 static const enum raw_ostream::Colors errorColor = raw_ostream::RED;
40 static const enum raw_ostream::Colors fatalColor = raw_ostream::RED;
41 // Used for changing only the bold attribute.
42 static const enum raw_ostream::Colors savedColor =
43 raw_ostream::SAVEDCOLOR;
45 /// Add highlights to differences in template strings.
46 static void applyTemplateHighlighting(raw_ostream &OS, StringRef Str,
47 bool &Normal, bool Bold) {
49 size_t Pos = Str.find(ToggleHighlight);
50 OS << Str.slice(0, Pos);
51 if (Pos == StringRef::npos)
54 Str = Str.substr(Pos + 1);
56 OS.changeColor(templateColor, true);
60 OS.changeColor(savedColor, true);
66 /// Number of spaces to indent when word-wrapping.
67 const unsigned WordWrapIndentation = 6;
69 static int bytesSincePreviousTabOrLineBegin(StringRef SourceLine, size_t i) {
72 if (SourceLine[--i]=='\t')
79 /// returns a printable representation of first item from input range
81 /// This function returns a printable representation of the next item in a line
82 /// of source. If the next byte begins a valid and printable character, that
83 /// character is returned along with 'true'.
85 /// Otherwise, if the next byte begins a valid, but unprintable character, a
86 /// printable, escaped representation of the character is returned, along with
87 /// 'false'. Otherwise a printable, escaped representation of the next byte
88 /// is returned along with 'false'.
90 /// \note The index is updated to be used with a subsequent call to
91 /// printableTextForNextCharacter.
93 /// \param SourceLine The line of source
94 /// \param i Pointer to byte index,
95 /// \param TabStop used to expand tabs
96 /// \return pair(printable text, 'true' iff original text was printable)
98 static std::pair<SmallString<16>, bool>
99 printableTextForNextCharacter(StringRef SourceLine, size_t *i,
101 assert(i && "i must not be null");
102 assert(*i<SourceLine.size() && "must point to a valid index");
104 if (SourceLine[*i]=='\t') {
105 assert(0 < TabStop && TabStop <= DiagnosticOptions::MaxTabStop &&
106 "Invalid -ftabstop value");
107 unsigned col = bytesSincePreviousTabOrLineBegin(SourceLine, *i);
108 unsigned NumSpaces = TabStop - col%TabStop;
109 assert(0 < NumSpaces && NumSpaces <= TabStop
110 && "Invalid computation of space amt");
113 SmallString<16> expandedTab;
114 expandedTab.assign(NumSpaces, ' ');
115 return std::make_pair(expandedTab, true);
118 unsigned char const *begin, *end;
119 begin = reinterpret_cast<unsigned char const *>(&*(SourceLine.begin() + *i));
120 end = begin + (SourceLine.size() - *i);
122 if (llvm::isLegalUTF8Sequence(begin, end)) {
124 llvm::UTF32 *cptr = &c;
125 unsigned char const *original_begin = begin;
126 unsigned char const *cp_end =
127 begin + llvm::getNumBytesForUTF8(SourceLine[*i]);
129 llvm::ConversionResult res = llvm::ConvertUTF8toUTF32(
130 &begin, cp_end, &cptr, cptr + 1, llvm::strictConversion);
132 assert(llvm::conversionOK == res);
133 assert(0 < begin-original_begin
134 && "we must be further along in the string now");
135 *i += begin-original_begin;
137 if (!llvm::sys::locale::isPrint(c)) {
138 // If next character is valid UTF-8, but not printable
139 SmallString<16> expandedCP("<U+>");
141 expandedCP.insert(expandedCP.begin()+3, llvm::hexdigit(c%16));
144 while (expandedCP.size() < 8)
145 expandedCP.insert(expandedCP.begin()+3, llvm::hexdigit(0));
146 return std::make_pair(expandedCP, false);
149 // If next character is valid UTF-8, and printable
150 return std::make_pair(SmallString<16>(original_begin, cp_end), true);
154 // If next byte is not valid UTF-8 (and therefore not printable)
155 SmallString<16> expandedByte("<XX>");
156 unsigned char byte = SourceLine[*i];
157 expandedByte[1] = llvm::hexdigit(byte / 16);
158 expandedByte[2] = llvm::hexdigit(byte % 16);
160 return std::make_pair(expandedByte, false);
163 static void expandTabs(std::string &SourceLine, unsigned TabStop) {
164 size_t i = SourceLine.size();
167 if (SourceLine[i]!='\t')
170 std::pair<SmallString<16>,bool> res
171 = printableTextForNextCharacter(SourceLine, &tmp_i, TabStop);
172 SourceLine.replace(i, 1, res.first.c_str());
176 /// This function takes a raw source line and produces a mapping from the bytes
177 /// of the printable representation of the line to the columns those printable
178 /// characters will appear at (numbering the first column as 0).
180 /// If a byte 'i' corresponds to multiple columns (e.g. the byte contains a tab
181 /// character) then the array will map that byte to the first column the
182 /// tab appears at and the next value in the map will have been incremented
185 /// If a byte is the first in a sequence of bytes that together map to a single
186 /// entity in the output, then the array will map that byte to the appropriate
187 /// column while the subsequent bytes will be -1.
189 /// The last element in the array does not correspond to any byte in the input
190 /// and instead is the number of columns needed to display the source
192 /// example: (given a tabstop of 8)
194 /// "a \t \u3042" -> {0,1,2,8,9,-1,-1,11}
196 /// (\\u3042 is represented in UTF-8 by three bytes and takes two columns to
198 static void byteToColumn(StringRef SourceLine, unsigned TabStop,
199 SmallVectorImpl<int> &out) {
202 if (SourceLine.empty()) {
207 out.resize(SourceLine.size()+1, -1);
211 while (i<SourceLine.size()) {
213 std::pair<SmallString<16>,bool> res
214 = printableTextForNextCharacter(SourceLine, &i, TabStop);
215 columns += llvm::sys::locale::columnWidth(res.first);
217 out.back() = columns;
220 /// This function takes a raw source line and produces a mapping from columns
221 /// to the byte of the source line that produced the character displaying at
222 /// that column. This is the inverse of the mapping produced by byteToColumn()
224 /// The last element in the array is the number of bytes in the source string
226 /// example: (given a tabstop of 8)
228 /// "a \t \u3042" -> {0,1,2,-1,-1,-1,-1,-1,3,4,-1,7}
230 /// (\\u3042 is represented in UTF-8 by three bytes and takes two columns to
232 static void columnToByte(StringRef SourceLine, unsigned TabStop,
233 SmallVectorImpl<int> &out) {
236 if (SourceLine.empty()) {
243 while (i<SourceLine.size()) {
244 out.resize(columns+1, -1);
246 std::pair<SmallString<16>,bool> res
247 = printableTextForNextCharacter(SourceLine, &i, TabStop);
248 columns += llvm::sys::locale::columnWidth(res.first);
250 out.resize(columns+1, -1);
255 struct SourceColumnMap {
256 SourceColumnMap(StringRef SourceLine, unsigned TabStop)
257 : m_SourceLine(SourceLine) {
259 ::byteToColumn(SourceLine, TabStop, m_byteToColumn);
260 ::columnToByte(SourceLine, TabStop, m_columnToByte);
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());
269 int columns() const { return m_byteToColumn.back(); }
270 int bytes() const { return m_columnToByte.back(); }
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];
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)
284 return m_byteToColumn[N];
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];
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) {}
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) {}
309 StringRef getSourceLine() const {
314 const std::string m_SourceLine;
315 SmallVector<int,200> m_byteToColumn;
316 SmallVector<int,200> m_columnToByte;
318 } // end anonymous namespace
320 /// When the source code line we want to print is too long for
321 /// the terminal, select the "interesting" region.
322 static void selectInterestingSourceRegion(std::string &SourceLine,
323 std::string &CaretLine,
324 std::string &FixItInsertionLine,
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)
335 // No special characters are allowed in CaretLine.
336 assert(CaretLine.end() ==
337 std::find_if(CaretLine.begin(), CaretLine.end(),
338 [](char c) { return c < ' ' || '~' < c; }));
340 // Find the slice that we need to display the full caret line
342 unsigned CaretStart = 0, CaretEnd = CaretLine.size();
343 for (; CaretStart != CaretEnd; ++CaretStart)
344 if (!isWhitespace(CaretLine[CaretStart]))
347 for (; CaretEnd != CaretStart; --CaretEnd)
348 if (!isWhitespace(CaretLine[CaretEnd - 1]))
351 // caret has already been inserted into CaretLine so the above whitespace
352 // check is guaranteed to include the caret
354 // If we have a fix-it line, make sure the slice includes all of the
355 // fix-it information.
356 if (!FixItInsertionLine.empty()) {
357 unsigned FixItStart = 0, FixItEnd = FixItInsertionLine.size();
358 for (; FixItStart != FixItEnd; ++FixItStart)
359 if (!isWhitespace(FixItInsertionLine[FixItStart]))
362 for (; FixItEnd != FixItStart; --FixItEnd)
363 if (!isWhitespace(FixItInsertionLine[FixItEnd - 1]))
366 // We can safely use the byte offset FixItStart as the column offset
367 // because the characters up until FixItStart are all ASCII whitespace
369 unsigned FixItStartCol = FixItStart;
371 = llvm::sys::locale::columnWidth(FixItInsertionLine.substr(0, FixItEnd));
373 CaretStart = std::min(FixItStartCol, CaretStart);
374 CaretEnd = std::max(FixItEndCol, CaretEnd);
377 // CaretEnd may have been set at the middle of a character
378 // If it's not at a character's first column then advance it past the current
380 while (static_cast<int>(CaretEnd) < map.columns() &&
381 -1 == map.columnToByte(CaretEnd))
384 assert((static_cast<int>(CaretStart) > map.columns() ||
385 -1!=map.columnToByte(CaretStart)) &&
386 "CaretStart must not point to a column in the middle of a source"
388 assert((static_cast<int>(CaretEnd) > map.columns() ||
389 -1!=map.columnToByte(CaretEnd)) &&
390 "CaretEnd must not point to a column in the middle of a source line"
393 // CaretLine[CaretStart, CaretEnd) contains all of the interesting
394 // parts of the caret line. While this slice is smaller than the
395 // number of columns we have, try to grow the slice to encompass
398 unsigned SourceStart = map.columnToByte(std::min<unsigned>(CaretStart,
400 unsigned SourceEnd = map.columnToByte(std::min<unsigned>(CaretEnd,
403 unsigned CaretColumnsOutsideSource = CaretEnd-CaretStart
404 - (map.byteToColumn(SourceEnd)-map.byteToColumn(SourceStart));
406 char const *front_ellipse = " ...";
407 char const *front_space = " ";
408 char const *back_ellipse = "...";
409 unsigned ellipses_space = strlen(front_ellipse) + strlen(back_ellipse);
411 unsigned TargetColumns = Columns;
412 // Give us extra room for the ellipses
413 // and any of the caret line that extends past the source
414 if (TargetColumns > ellipses_space+CaretColumnsOutsideSource)
415 TargetColumns -= ellipses_space+CaretColumnsOutsideSource;
417 while (SourceStart>0 || SourceEnd<SourceLine.size()) {
418 bool ExpandedRegion = false;
421 unsigned NewStart = map.startOfPreviousColumn(SourceStart);
423 // Skip over any whitespace we see here; we're looking for
424 // another bit of interesting text.
425 // FIXME: Detect non-ASCII whitespace characters too.
426 while (NewStart && isWhitespace(SourceLine[NewStart]))
427 NewStart = map.startOfPreviousColumn(NewStart);
429 // Skip over this bit of "interesting" text.
431 unsigned Prev = map.startOfPreviousColumn(NewStart);
432 if (isWhitespace(SourceLine[Prev]))
437 assert(map.byteToColumn(NewStart) != -1);
438 unsigned NewColumns = map.byteToColumn(SourceEnd) -
439 map.byteToColumn(NewStart);
440 if (NewColumns <= TargetColumns) {
441 SourceStart = NewStart;
442 ExpandedRegion = true;
446 if (SourceEnd<SourceLine.size()) {
447 unsigned NewEnd = map.startOfNextColumn(SourceEnd);
449 // Skip over any whitespace we see here; we're looking for
450 // another bit of interesting text.
451 // FIXME: Detect non-ASCII whitespace characters too.
452 while (NewEnd < SourceLine.size() && isWhitespace(SourceLine[NewEnd]))
453 NewEnd = map.startOfNextColumn(NewEnd);
455 // Skip over this bit of "interesting" text.
456 while (NewEnd < SourceLine.size() && isWhitespace(SourceLine[NewEnd]))
457 NewEnd = map.startOfNextColumn(NewEnd);
459 assert(map.byteToColumn(NewEnd) != -1);
460 unsigned NewColumns = map.byteToColumn(NewEnd) -
461 map.byteToColumn(SourceStart);
462 if (NewColumns <= TargetColumns) {
464 ExpandedRegion = true;
472 CaretStart = map.byteToColumn(SourceStart);
473 CaretEnd = map.byteToColumn(SourceEnd) + CaretColumnsOutsideSource;
475 // [CaretStart, CaretEnd) is the slice we want. Update the various
476 // output lines to show only this slice, with two-space padding
477 // before the lines so that it looks nicer.
479 assert(CaretStart!=(unsigned)-1 && CaretEnd!=(unsigned)-1 &&
480 SourceStart!=(unsigned)-1 && SourceEnd!=(unsigned)-1);
481 assert(SourceStart <= SourceEnd);
482 assert(CaretStart <= CaretEnd);
484 unsigned BackColumnsRemoved
485 = map.byteToColumn(SourceLine.size())-map.byteToColumn(SourceEnd);
486 unsigned FrontColumnsRemoved = CaretStart;
487 unsigned ColumnsKept = CaretEnd-CaretStart;
489 // We checked up front that the line needed truncation
490 assert(FrontColumnsRemoved+ColumnsKept+BackColumnsRemoved > Columns);
492 // The line needs some truncation, and we'd prefer to keep the front
493 // if possible, so remove the back
494 if (BackColumnsRemoved > strlen(back_ellipse))
495 SourceLine.replace(SourceEnd, std::string::npos, back_ellipse);
497 // If that's enough then we're done
498 if (FrontColumnsRemoved+ColumnsKept <= Columns)
501 // Otherwise remove the front as well
502 if (FrontColumnsRemoved > strlen(front_ellipse)) {
503 SourceLine.replace(0, SourceStart, front_ellipse);
504 CaretLine.replace(0, CaretStart, front_space);
505 if (!FixItInsertionLine.empty())
506 FixItInsertionLine.replace(0, CaretStart, front_space);
510 /// Skip over whitespace in the string, starting at the given
513 /// \returns The index of the first non-whitespace character that is
514 /// greater than or equal to Idx or, if no such character exists,
515 /// returns the end of the string.
516 static unsigned skipWhitespace(unsigned Idx, StringRef Str, unsigned Length) {
517 while (Idx < Length && isWhitespace(Str[Idx]))
522 /// If the given character is the start of some kind of
523 /// balanced punctuation (e.g., quotes or parentheses), return the
524 /// character that will terminate the punctuation.
526 /// \returns The ending punctuation character, if any, or the NULL
527 /// character if the input character does not start any punctuation.
528 static inline char findMatchingPunctuation(char c) {
530 case '\'': return '\'';
531 case '`': return '\'';
532 case '"': return '"';
533 case '(': return ')';
534 case '[': return ']';
535 case '{': return '}';
542 /// Find the end of the word starting at the given offset
545 /// \returns the index pointing one character past the end of the
547 static unsigned findEndOfWord(unsigned Start, StringRef Str,
548 unsigned Length, unsigned Column,
550 assert(Start < Str.size() && "Invalid start position!");
551 unsigned End = Start + 1;
553 // If we are already at the end of the string, take that as the word.
554 if (End == Str.size())
557 // Determine if the start of the string is actually opening
558 // punctuation, e.g., a quote or parentheses.
559 char EndPunct = findMatchingPunctuation(Str[Start]);
561 // This is a normal word. Just find the first space character.
562 while (End < Length && !isWhitespace(Str[End]))
567 // We have the start of a balanced punctuation sequence (quotes,
568 // parentheses, etc.). Determine the full sequence is.
569 SmallString<16> PunctuationEndStack;
570 PunctuationEndStack.push_back(EndPunct);
571 while (End < Length && !PunctuationEndStack.empty()) {
572 if (Str[End] == PunctuationEndStack.back())
573 PunctuationEndStack.pop_back();
574 else if (char SubEndPunct = findMatchingPunctuation(Str[End]))
575 PunctuationEndStack.push_back(SubEndPunct);
580 // Find the first space character after the punctuation ended.
581 while (End < Length && !isWhitespace(Str[End]))
584 unsigned PunctWordLength = End - Start;
585 if (// If the word fits on this line
586 Column + PunctWordLength <= Columns ||
587 // ... or the word is "short enough" to take up the next line
588 // without too much ugly white space
589 PunctWordLength < Columns/3)
590 return End; // Take the whole thing as a single "word".
592 // The whole quoted/parenthesized string is too long to print as a
593 // single "word". Instead, find the "word" that starts just after
594 // the punctuation and use that end-point instead. This will recurse
595 // until it finds something small enough to consider a word.
596 return findEndOfWord(Start + 1, Str, Length, Column + 1, Columns);
599 /// Print the given string to a stream, word-wrapping it to
600 /// some number of columns in the process.
602 /// \param OS the stream to which the word-wrapping string will be
604 /// \param Str the string to word-wrap and output.
605 /// \param Columns the number of columns to word-wrap to.
606 /// \param Column the column number at which the first character of \p
607 /// Str will be printed. This will be non-zero when part of the first
608 /// line has already been printed.
609 /// \param Bold if the current text should be bold
610 /// \param Indentation the number of spaces to indent any lines beyond
612 /// \returns true if word-wrapping was required, or false if the
613 /// string fit on the first line.
614 static bool printWordWrapped(raw_ostream &OS, StringRef Str,
618 unsigned Indentation = WordWrapIndentation) {
619 const unsigned Length = std::min(Str.find('\n'), Str.size());
620 bool TextNormal = true;
622 // The string used to indent each line.
623 SmallString<16> IndentStr;
624 IndentStr.assign(Indentation, ' ');
625 bool Wrapped = false;
626 for (unsigned WordStart = 0, WordEnd; WordStart < Length;
627 WordStart = WordEnd) {
628 // Find the beginning of the next word.
629 WordStart = skipWhitespace(WordStart, Str, Length);
630 if (WordStart == Length)
633 // Find the end of this word.
634 WordEnd = findEndOfWord(WordStart, Str, Length, Column, Columns);
636 // Does this word fit on the current line?
637 unsigned WordLength = WordEnd - WordStart;
638 if (Column + WordLength < Columns) {
639 // This word fits on the current line; print it there.
644 applyTemplateHighlighting(OS, Str.substr(WordStart, WordLength),
646 Column += WordLength;
650 // This word does not fit on the current line, so wrap to the next
653 OS.write(&IndentStr[0], Indentation);
654 applyTemplateHighlighting(OS, Str.substr(WordStart, WordLength),
656 Column = Indentation + WordLength;
660 // Append any remaning text from the message with its existing formatting.
661 applyTemplateHighlighting(OS, Str.substr(Length), TextNormal, Bold);
663 assert(TextNormal && "Text highlighted at end of diagnostic message.");
668 TextDiagnostic::TextDiagnostic(raw_ostream &OS,
669 const LangOptions &LangOpts,
670 DiagnosticOptions *DiagOpts)
671 : DiagnosticRenderer(LangOpts, DiagOpts), OS(OS) {}
673 TextDiagnostic::~TextDiagnostic() {}
675 void TextDiagnostic::emitDiagnosticMessage(
676 FullSourceLoc Loc, PresumedLoc PLoc, DiagnosticsEngine::Level Level,
677 StringRef Message, ArrayRef<clang::CharSourceRange> Ranges,
678 DiagOrStoredDiag D) {
679 uint64_t StartOfLocationInfo = OS.tell();
681 // Emit the location of this particular diagnostic.
683 emitDiagnosticLoc(Loc, PLoc, Level, Ranges);
685 if (DiagOpts->ShowColors)
688 printDiagnosticLevel(OS, Level, DiagOpts->ShowColors,
689 DiagOpts->CLFallbackMode);
690 printDiagnosticMessage(OS,
691 /*IsSupplemental*/ Level == DiagnosticsEngine::Note,
692 Message, OS.tell() - StartOfLocationInfo,
693 DiagOpts->MessageLength, DiagOpts->ShowColors);
697 TextDiagnostic::printDiagnosticLevel(raw_ostream &OS,
698 DiagnosticsEngine::Level Level,
700 bool CLFallbackMode) {
702 // Print diagnostic category in bold and color
704 case DiagnosticsEngine::Ignored:
705 llvm_unreachable("Invalid diagnostic type");
706 case DiagnosticsEngine::Note: OS.changeColor(noteColor, true); break;
707 case DiagnosticsEngine::Remark: OS.changeColor(remarkColor, true); break;
708 case DiagnosticsEngine::Warning: OS.changeColor(warningColor, true); break;
709 case DiagnosticsEngine::Error: OS.changeColor(errorColor, true); break;
710 case DiagnosticsEngine::Fatal: OS.changeColor(fatalColor, true); break;
715 case DiagnosticsEngine::Ignored:
716 llvm_unreachable("Invalid diagnostic type");
717 case DiagnosticsEngine::Note: OS << "note"; break;
718 case DiagnosticsEngine::Remark: OS << "remark"; break;
719 case DiagnosticsEngine::Warning: OS << "warning"; break;
720 case DiagnosticsEngine::Error: OS << "error"; break;
721 case DiagnosticsEngine::Fatal: OS << "fatal error"; break;
724 // In clang-cl /fallback mode, print diagnostics as "error(clang):". This
725 // makes it more clear whether a message is coming from clang or cl.exe,
726 // and it prevents MSBuild from concluding that the build failed just because
727 // there is an "error:" in the output.
738 void TextDiagnostic::printDiagnosticMessage(raw_ostream &OS,
741 unsigned CurrentColumn,
742 unsigned Columns, bool ShowColors) {
744 if (ShowColors && !IsSupplemental) {
745 // Print primary diagnostic messages in bold and without color, to visually
746 // indicate the transition from continuation notes and other output.
747 OS.changeColor(savedColor, true);
752 printWordWrapped(OS, Message, Columns, CurrentColumn, Bold);
755 applyTemplateHighlighting(OS, Message, Normal, Bold);
756 assert(Normal && "Formatting should have returned to normal");
764 void TextDiagnostic::emitFilename(StringRef Filename, const SourceManager &SM) {
765 SmallVector<char, 128> AbsoluteFilename;
766 if (DiagOpts->AbsolutePath) {
767 const DirectoryEntry *Dir = SM.getFileManager().getDirectory(
768 llvm::sys::path::parent_path(Filename));
770 StringRef DirName = SM.getFileManager().getCanonicalName(Dir);
771 llvm::sys::path::append(AbsoluteFilename, DirName,
772 llvm::sys::path::filename(Filename));
773 Filename = StringRef(AbsoluteFilename.data(), AbsoluteFilename.size());
780 /// Print out the file/line/column information and include trace.
782 /// This method handlen the emission of the diagnostic location information.
783 /// This includes extracting as much location information as is present for
784 /// the diagnostic and printing it, as well as any include stack or source
785 /// ranges necessary.
786 void TextDiagnostic::emitDiagnosticLoc(FullSourceLoc Loc, PresumedLoc PLoc,
787 DiagnosticsEngine::Level Level,
788 ArrayRef<CharSourceRange> Ranges) {
789 if (PLoc.isInvalid()) {
790 // At least print the file name if available:
791 FileID FID = Loc.getFileID();
793 const FileEntry *FE = Loc.getFileEntry();
794 if (FE && FE->isValid()) {
795 emitFilename(FE->getName(), Loc.getManager());
803 unsigned LineNo = PLoc.getLine();
805 if (!DiagOpts->ShowLocation)
808 if (DiagOpts->ShowColors)
809 OS.changeColor(savedColor, true);
811 emitFilename(PLoc.getFilename(), Loc.getManager());
812 switch (DiagOpts->getFormat()) {
813 case DiagnosticOptions::Clang: OS << ':' << LineNo; break;
814 case DiagnosticOptions::MSVC: OS << '(' << LineNo; break;
815 case DiagnosticOptions::Vi: OS << " +" << LineNo; break;
818 if (DiagOpts->ShowColumn)
819 // Compute the column number.
820 if (unsigned ColNo = PLoc.getColumn()) {
821 if (DiagOpts->getFormat() == DiagnosticOptions::MSVC) {
823 // Visual Studio 2010 or earlier expects column number to be off by one
824 if (LangOpts.MSCompatibilityVersion &&
825 !LangOpts.isCompatibleWithMSVC(LangOptions::MSVC2012))
831 switch (DiagOpts->getFormat()) {
832 case DiagnosticOptions::Clang:
833 case DiagnosticOptions::Vi: OS << ':'; break;
834 case DiagnosticOptions::MSVC:
835 // MSVC2013 and before print 'file(4) : error'. MSVC2015 gets rid of the
836 // space and prints 'file(4): error'.
838 if (LangOpts.MSCompatibilityVersion &&
839 !LangOpts.isCompatibleWithMSVC(LangOptions::MSVC2015))
845 if (DiagOpts->ShowSourceRanges && !Ranges.empty()) {
846 FileID CaretFileID = Loc.getExpansionLoc().getFileID();
847 bool PrintedRange = false;
849 for (ArrayRef<CharSourceRange>::const_iterator RI = Ranges.begin(),
852 // Ignore invalid ranges.
853 if (!RI->isValid()) continue;
855 auto &SM = Loc.getManager();
856 SourceLocation B = SM.getExpansionLoc(RI->getBegin());
857 CharSourceRange ERange = SM.getExpansionRange(RI->getEnd());
858 SourceLocation E = ERange.getEnd();
859 bool IsTokenRange = ERange.isTokenRange();
861 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(B);
862 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E);
864 // If the start or end of the range is in another file, just discard
866 if (BInfo.first != CaretFileID || EInfo.first != CaretFileID)
869 // Add in the length of the token, so that we cover multi-char
871 unsigned TokSize = 0;
873 TokSize = Lexer::MeasureTokenLength(E, SM, LangOpts);
875 FullSourceLoc BF(B, SM), EF(E, SM);
877 << BF.getLineNumber() << ':' << BF.getColumnNumber() << '-'
878 << EF.getLineNumber() << ':' << (EF.getColumnNumber() + TokSize)
889 void TextDiagnostic::emitIncludeLocation(FullSourceLoc Loc, PresumedLoc PLoc) {
890 if (DiagOpts->ShowLocation && PLoc.isValid())
891 OS << "In file included from " << PLoc.getFilename() << ':'
892 << PLoc.getLine() << ":\n";
894 OS << "In included file:\n";
897 void TextDiagnostic::emitImportLocation(FullSourceLoc Loc, PresumedLoc PLoc,
898 StringRef ModuleName) {
899 if (DiagOpts->ShowLocation && PLoc.isValid())
900 OS << "In module '" << ModuleName << "' imported from "
901 << PLoc.getFilename() << ':' << PLoc.getLine() << ":\n";
903 OS << "In module '" << ModuleName << "':\n";
906 void TextDiagnostic::emitBuildingModuleLocation(FullSourceLoc Loc,
908 StringRef ModuleName) {
909 if (DiagOpts->ShowLocation && PLoc.isValid())
910 OS << "While building module '" << ModuleName << "' imported from "
911 << PLoc.getFilename() << ':' << PLoc.getLine() << ":\n";
913 OS << "While building module '" << ModuleName << "':\n";
916 /// Find the suitable set of lines to show to include a set of ranges.
917 static llvm::Optional<std::pair<unsigned, unsigned>>
918 findLinesForRange(const CharSourceRange &R, FileID FID,
919 const SourceManager &SM) {
920 if (!R.isValid()) return None;
922 SourceLocation Begin = R.getBegin();
923 SourceLocation End = R.getEnd();
924 if (SM.getFileID(Begin) != FID || SM.getFileID(End) != FID)
927 return std::make_pair(SM.getExpansionLineNumber(Begin),
928 SM.getExpansionLineNumber(End));
931 /// Add as much of range B into range A as possible without exceeding a maximum
932 /// size of MaxRange. Ranges are inclusive.
933 static std::pair<unsigned, unsigned>
934 maybeAddRange(std::pair<unsigned, unsigned> A, std::pair<unsigned, unsigned> B,
936 // If A is already the maximum size, we're done.
937 unsigned Slack = MaxRange - (A.second - A.first + 1);
941 // Easy case: merge succeeds within MaxRange.
942 unsigned Min = std::min(A.first, B.first);
943 unsigned Max = std::max(A.second, B.second);
944 if (Max - Min + 1 <= MaxRange)
947 // If we can't reach B from A within MaxRange, there's nothing to do.
948 // Don't add lines to the range that contain nothing interesting.
949 if ((B.first > A.first && B.first - A.first + 1 > MaxRange) ||
950 (B.second < A.second && A.second - B.second + 1 > MaxRange))
953 // Otherwise, expand A towards B to produce a range of size MaxRange. We
954 // attempt to expand by the same amount in both directions if B strictly
957 // Expand downwards by up to half the available amount, then upwards as
958 // much as possible, then downwards as much as possible.
959 A.second = std::min(A.second + (Slack + 1) / 2, Max);
960 Slack = MaxRange - (A.second - A.first + 1);
961 A.first = std::max(Min + Slack, A.first) - Slack;
962 A.second = std::min(A.first + MaxRange - 1, Max);
966 /// Highlight a SourceRange (with ~'s) for any characters on LineNo.
967 static void highlightRange(const CharSourceRange &R,
968 unsigned LineNo, FileID FID,
969 const SourceColumnMap &map,
970 std::string &CaretLine,
971 const SourceManager &SM,
972 const LangOptions &LangOpts) {
973 if (!R.isValid()) return;
975 SourceLocation Begin = R.getBegin();
976 SourceLocation End = R.getEnd();
978 unsigned StartLineNo = SM.getExpansionLineNumber(Begin);
979 if (StartLineNo > LineNo || SM.getFileID(Begin) != FID)
980 return; // No intersection.
982 unsigned EndLineNo = SM.getExpansionLineNumber(End);
983 if (EndLineNo < LineNo || SM.getFileID(End) != FID)
984 return; // No intersection.
986 // Compute the column number of the start.
987 unsigned StartColNo = 0;
988 if (StartLineNo == LineNo) {
989 StartColNo = SM.getExpansionColumnNumber(Begin);
990 if (StartColNo) --StartColNo; // Zero base the col #.
993 // Compute the column number of the end.
994 unsigned EndColNo = map.getSourceLine().size();
995 if (EndLineNo == LineNo) {
996 EndColNo = SM.getExpansionColumnNumber(End);
998 --EndColNo; // Zero base the col #.
1000 // Add in the length of the token, so that we cover multi-char tokens if
1001 // this is a token range.
1002 if (R.isTokenRange())
1003 EndColNo += Lexer::MeasureTokenLength(End, SM, LangOpts);
1005 EndColNo = CaretLine.size();
1009 assert(StartColNo <= EndColNo && "Invalid range!");
1011 // Check that a token range does not highlight only whitespace.
1012 if (R.isTokenRange()) {
1013 // Pick the first non-whitespace column.
1014 while (StartColNo < map.getSourceLine().size() &&
1015 (map.getSourceLine()[StartColNo] == ' ' ||
1016 map.getSourceLine()[StartColNo] == '\t'))
1017 StartColNo = map.startOfNextColumn(StartColNo);
1019 // Pick the last non-whitespace column.
1020 if (EndColNo > map.getSourceLine().size())
1021 EndColNo = map.getSourceLine().size();
1023 (map.getSourceLine()[EndColNo-1] == ' ' ||
1024 map.getSourceLine()[EndColNo-1] == '\t'))
1025 EndColNo = map.startOfPreviousColumn(EndColNo);
1027 // If the start/end passed each other, then we are trying to highlight a
1028 // range that just exists in whitespace. That most likely means we have
1029 // a multi-line highlighting range that covers a blank line.
1030 if (StartColNo > EndColNo) {
1031 assert(StartLineNo != EndLineNo && "trying to highlight whitespace");
1032 StartColNo = EndColNo;
1036 assert(StartColNo <= map.getSourceLine().size() && "Invalid range!");
1037 assert(EndColNo <= map.getSourceLine().size() && "Invalid range!");
1039 // Fill the range with ~'s.
1040 StartColNo = map.byteToContainingColumn(StartColNo);
1041 EndColNo = map.byteToContainingColumn(EndColNo);
1043 assert(StartColNo <= EndColNo && "Invalid range!");
1044 if (CaretLine.size() < EndColNo)
1045 CaretLine.resize(EndColNo,' ');
1046 std::fill(CaretLine.begin()+StartColNo,CaretLine.begin()+EndColNo,'~');
1049 static std::string buildFixItInsertionLine(FileID FID,
1051 const SourceColumnMap &map,
1052 ArrayRef<FixItHint> Hints,
1053 const SourceManager &SM,
1054 const DiagnosticOptions *DiagOpts) {
1055 std::string FixItInsertionLine;
1056 if (Hints.empty() || !DiagOpts->ShowFixits)
1057 return FixItInsertionLine;
1058 unsigned PrevHintEndCol = 0;
1060 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1062 if (!I->CodeToInsert.empty()) {
1063 // We have an insertion hint. Determine whether the inserted
1064 // code contains no newlines and is on the same line as the caret.
1065 std::pair<FileID, unsigned> HintLocInfo
1066 = SM.getDecomposedExpansionLoc(I->RemoveRange.getBegin());
1067 if (FID == HintLocInfo.first &&
1068 LineNo == SM.getLineNumber(HintLocInfo.first, HintLocInfo.second) &&
1069 StringRef(I->CodeToInsert).find_first_of("\n\r") == StringRef::npos) {
1070 // Insert the new code into the line just below the code
1071 // that the user wrote.
1072 // Note: When modifying this function, be very careful about what is a
1073 // "column" (printed width, platform-dependent) and what is a
1074 // "byte offset" (SourceManager "column").
1075 unsigned HintByteOffset
1076 = SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second) - 1;
1078 // The hint must start inside the source or right at the end
1079 assert(HintByteOffset < static_cast<unsigned>(map.bytes())+1);
1080 unsigned HintCol = map.byteToContainingColumn(HintByteOffset);
1082 // If we inserted a long previous hint, push this one forwards, and add
1083 // an extra space to show that this is not part of the previous
1084 // completion. This is sort of the best we can do when two hints appear
1087 // Note that if this hint is located immediately after the previous
1088 // hint, no space will be added, since the location is more important.
1089 if (HintCol < PrevHintEndCol)
1090 HintCol = PrevHintEndCol + 1;
1092 // This should NOT use HintByteOffset, because the source might have
1093 // Unicode characters in earlier columns.
1094 unsigned NewFixItLineSize = FixItInsertionLine.size() +
1095 (HintCol - PrevHintEndCol) + I->CodeToInsert.size();
1096 if (NewFixItLineSize > FixItInsertionLine.size())
1097 FixItInsertionLine.resize(NewFixItLineSize, ' ');
1099 std::copy(I->CodeToInsert.begin(), I->CodeToInsert.end(),
1100 FixItInsertionLine.end() - I->CodeToInsert.size());
1103 HintCol + llvm::sys::locale::columnWidth(I->CodeToInsert);
1108 expandTabs(FixItInsertionLine, DiagOpts->TabStop);
1110 return FixItInsertionLine;
1113 /// Emit a code snippet and caret line.
1115 /// This routine emits a single line's code snippet and caret line..
1117 /// \param Loc The location for the caret.
1118 /// \param Ranges The underlined ranges for this code snippet.
1119 /// \param Hints The FixIt hints active for this diagnostic.
1120 void TextDiagnostic::emitSnippetAndCaret(
1121 FullSourceLoc Loc, DiagnosticsEngine::Level Level,
1122 SmallVectorImpl<CharSourceRange> &Ranges, ArrayRef<FixItHint> Hints) {
1123 assert(Loc.isValid() && "must have a valid source location here");
1124 assert(Loc.isFileID() && "must have a file location here");
1126 // If caret diagnostics are enabled and we have location, we want to
1127 // emit the caret. However, we only do this if the location moved
1128 // from the last diagnostic, if the last diagnostic was a note that
1129 // was part of a different warning or error diagnostic, or if the
1130 // diagnostic has ranges. We don't want to emit the same caret
1131 // multiple times if one loc has multiple diagnostics.
1132 if (!DiagOpts->ShowCarets)
1134 if (Loc == LastLoc && Ranges.empty() && Hints.empty() &&
1135 (LastLevel != DiagnosticsEngine::Note || Level == LastLevel))
1138 // Decompose the location into a FID/Offset pair.
1139 std::pair<FileID, unsigned> LocInfo = Loc.getDecomposedLoc();
1140 FileID FID = LocInfo.first;
1141 const SourceManager &SM = Loc.getManager();
1143 // Get information about the buffer it points into.
1144 bool Invalid = false;
1145 StringRef BufData = Loc.getBufferData(&Invalid);
1149 unsigned CaretLineNo = Loc.getLineNumber();
1150 unsigned CaretColNo = Loc.getColumnNumber();
1152 // Arbitrarily stop showing snippets when the line is too long.
1153 static const size_t MaxLineLengthToPrint = 4096;
1154 if (CaretColNo > MaxLineLengthToPrint)
1157 // Find the set of lines to include.
1158 const unsigned MaxLines = DiagOpts->SnippetLineLimit;
1159 std::pair<unsigned, unsigned> Lines = {CaretLineNo, CaretLineNo};
1160 for (SmallVectorImpl<CharSourceRange>::iterator I = Ranges.begin(),
1163 if (auto OptionalRange = findLinesForRange(*I, FID, SM))
1164 Lines = maybeAddRange(Lines, *OptionalRange, MaxLines);
1166 for (unsigned LineNo = Lines.first; LineNo != Lines.second + 1; ++LineNo) {
1167 const char *BufStart = BufData.data();
1168 const char *BufEnd = BufStart + BufData.size();
1170 // Rewind from the current position to the start of the line.
1171 const char *LineStart =
1173 SM.getDecomposedLoc(SM.translateLineCol(FID, LineNo, 1)).second;
1174 if (LineStart == BufEnd)
1177 // Compute the line end.
1178 const char *LineEnd = LineStart;
1179 while (*LineEnd != '\n' && *LineEnd != '\r' && LineEnd != BufEnd)
1182 // Arbitrarily stop showing snippets when the line is too long.
1183 // FIXME: Don't print any lines in this case.
1184 if (size_t(LineEnd - LineStart) > MaxLineLengthToPrint)
1187 // Trim trailing null-bytes.
1188 StringRef Line(LineStart, LineEnd - LineStart);
1189 while (!Line.empty() && Line.back() == '\0' &&
1190 (LineNo != CaretLineNo || Line.size() > CaretColNo))
1191 Line = Line.drop_back();
1193 // Copy the line of code into an std::string for ease of manipulation.
1194 std::string SourceLine(Line.begin(), Line.end());
1196 // Build the byte to column map.
1197 const SourceColumnMap sourceColMap(SourceLine, DiagOpts->TabStop);
1199 // Create a line for the caret that is filled with spaces that is the same
1200 // number of columns as the line of source code.
1201 std::string CaretLine(sourceColMap.columns(), ' ');
1203 // Highlight all of the characters covered by Ranges with ~ characters.
1204 for (SmallVectorImpl<CharSourceRange>::iterator I = Ranges.begin(),
1207 highlightRange(*I, LineNo, FID, sourceColMap, CaretLine, SM, LangOpts);
1209 // Next, insert the caret itself.
1210 if (CaretLineNo == LineNo) {
1211 CaretColNo = sourceColMap.byteToContainingColumn(CaretColNo - 1);
1212 if (CaretLine.size() < CaretColNo + 1)
1213 CaretLine.resize(CaretColNo + 1, ' ');
1214 CaretLine[CaretColNo] = '^';
1217 std::string FixItInsertionLine = buildFixItInsertionLine(
1218 FID, LineNo, sourceColMap, Hints, SM, DiagOpts.get());
1220 // If the source line is too long for our terminal, select only the
1221 // "interesting" source region within that line.
1222 unsigned Columns = DiagOpts->MessageLength;
1224 selectInterestingSourceRegion(SourceLine, CaretLine, FixItInsertionLine,
1225 Columns, sourceColMap);
1227 // If we are in -fdiagnostics-print-source-range-info mode, we are trying
1228 // to produce easily machine parsable output. Add a space before the
1229 // source line and the caret to make it trivial to tell the main diagnostic
1230 // line from what the user is intended to see.
1231 if (DiagOpts->ShowSourceRanges) {
1232 SourceLine = ' ' + SourceLine;
1233 CaretLine = ' ' + CaretLine;
1236 // Finally, remove any blank spaces from the end of CaretLine.
1237 while (!CaretLine.empty() && CaretLine[CaretLine.size() - 1] == ' ')
1238 CaretLine.erase(CaretLine.end() - 1);
1240 // Emit what we have computed.
1241 emitSnippet(SourceLine);
1243 if (!CaretLine.empty()) {
1244 if (DiagOpts->ShowColors)
1245 OS.changeColor(caretColor, true);
1246 OS << CaretLine << '\n';
1247 if (DiagOpts->ShowColors)
1251 if (!FixItInsertionLine.empty()) {
1252 if (DiagOpts->ShowColors)
1253 // Print fixit line in color
1254 OS.changeColor(fixitColor, false);
1255 if (DiagOpts->ShowSourceRanges)
1257 OS << FixItInsertionLine << '\n';
1258 if (DiagOpts->ShowColors)
1263 // Print out any parseable fixit information requested by the options.
1264 emitParseableFixits(Hints, SM);
1267 void TextDiagnostic::emitSnippet(StringRef line) {
1273 std::string to_print;
1274 bool print_reversed = false;
1276 while (i<line.size()) {
1277 std::pair<SmallString<16>,bool> res
1278 = printableTextForNextCharacter(line, &i, DiagOpts->TabStop);
1279 bool was_printable = res.second;
1281 if (DiagOpts->ShowColors && was_printable == print_reversed) {
1286 if (DiagOpts->ShowColors)
1290 print_reversed = !was_printable;
1291 to_print += res.first.str();
1294 if (print_reversed && DiagOpts->ShowColors)
1297 if (print_reversed && DiagOpts->ShowColors)
1303 void TextDiagnostic::emitParseableFixits(ArrayRef<FixItHint> Hints,
1304 const SourceManager &SM) {
1305 if (!DiagOpts->ShowParseableFixits)
1308 // We follow FixItRewriter's example in not (yet) handling
1309 // fix-its in macros.
1310 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1312 if (I->RemoveRange.isInvalid() ||
1313 I->RemoveRange.getBegin().isMacroID() ||
1314 I->RemoveRange.getEnd().isMacroID())
1318 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1320 SourceLocation BLoc = I->RemoveRange.getBegin();
1321 SourceLocation ELoc = I->RemoveRange.getEnd();
1323 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(BLoc);
1324 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(ELoc);
1326 // Adjust for token ranges.
1327 if (I->RemoveRange.isTokenRange())
1328 EInfo.second += Lexer::MeasureTokenLength(ELoc, SM, LangOpts);
1330 // We specifically do not do word-wrapping or tab-expansion here,
1331 // because this is supposed to be easy to parse.
1332 PresumedLoc PLoc = SM.getPresumedLoc(BLoc);
1333 if (PLoc.isInvalid())
1337 OS.write_escaped(PLoc.getFilename());
1338 OS << "\":{" << SM.getLineNumber(BInfo.first, BInfo.second)
1339 << ':' << SM.getColumnNumber(BInfo.first, BInfo.second)
1340 << '-' << SM.getLineNumber(EInfo.first, EInfo.second)
1341 << ':' << SM.getColumnNumber(EInfo.first, EInfo.second)
1343 OS.write_escaped(I->CodeToInsert);