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/MemoryBuffer.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 /// \brief 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 /// \brief 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 /// \brief 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 (isLegalUTF8Sequence(begin, end)) {
125 unsigned char const *original_begin = begin;
126 unsigned char const *cp_end = begin+getNumBytesForUTF8(SourceLine[*i]);
128 ConversionResult res = ConvertUTF8toUTF32(&begin, cp_end, &cptr, cptr+1,
131 assert(conversionOK==res);
132 assert(0 < begin-original_begin
133 && "we must be further along in the string now");
134 *i += begin-original_begin;
136 if (!llvm::sys::locale::isPrint(c)) {
137 // If next character is valid UTF-8, but not printable
138 SmallString<16> expandedCP("<U+>");
140 expandedCP.insert(expandedCP.begin()+3, llvm::hexdigit(c%16));
143 while (expandedCP.size() < 8)
144 expandedCP.insert(expandedCP.begin()+3, llvm::hexdigit(0));
145 return std::make_pair(expandedCP, false);
148 // If next character is valid UTF-8, and printable
149 return std::make_pair(SmallString<16>(original_begin, cp_end), true);
153 // If next byte is not valid UTF-8 (and therefore not printable)
154 SmallString<16> expandedByte("<XX>");
155 unsigned char byte = SourceLine[*i];
156 expandedByte[1] = llvm::hexdigit(byte / 16);
157 expandedByte[2] = llvm::hexdigit(byte % 16);
159 return std::make_pair(expandedByte, false);
162 static void expandTabs(std::string &SourceLine, unsigned TabStop) {
163 size_t i = SourceLine.size();
166 if (SourceLine[i]!='\t')
169 std::pair<SmallString<16>,bool> res
170 = printableTextForNextCharacter(SourceLine, &tmp_i, TabStop);
171 SourceLine.replace(i, 1, res.first.c_str());
175 /// This function takes a raw source line and produces a mapping from the bytes
176 /// of the printable representation of the line to the columns those printable
177 /// characters will appear at (numbering the first column as 0).
179 /// If a byte 'i' corresponds to multiple columns (e.g. the byte contains a tab
180 /// character) then the array will map that byte to the first column the
181 /// tab appears at and the next value in the map will have been incremented
184 /// If a byte is the first in a sequence of bytes that together map to a single
185 /// entity in the output, then the array will map that byte to the appropriate
186 /// column while the subsequent bytes will be -1.
188 /// The last element in the array does not correspond to any byte in the input
189 /// and instead is the number of columns needed to display the source
191 /// example: (given a tabstop of 8)
193 /// "a \t \u3042" -> {0,1,2,8,9,-1,-1,11}
195 /// (\\u3042 is represented in UTF-8 by three bytes and takes two columns to
197 static void byteToColumn(StringRef SourceLine, unsigned TabStop,
198 SmallVectorImpl<int> &out) {
201 if (SourceLine.empty()) {
206 out.resize(SourceLine.size()+1, -1);
210 while (i<SourceLine.size()) {
212 std::pair<SmallString<16>,bool> res
213 = printableTextForNextCharacter(SourceLine, &i, TabStop);
214 columns += llvm::sys::locale::columnWidth(res.first);
216 out.back() = columns;
219 /// This function takes a raw source line and produces a mapping from columns
220 /// to the byte of the source line that produced the character displaying at
221 /// that column. This is the inverse of the mapping produced by byteToColumn()
223 /// The last element in the array is the number of bytes in the source string
225 /// example: (given a tabstop of 8)
227 /// "a \t \u3042" -> {0,1,2,-1,-1,-1,-1,-1,3,4,-1,7}
229 /// (\\u3042 is represented in UTF-8 by three bytes and takes two columns to
231 static void columnToByte(StringRef SourceLine, unsigned TabStop,
232 SmallVectorImpl<int> &out) {
235 if (SourceLine.empty()) {
242 while (i<SourceLine.size()) {
243 out.resize(columns+1, -1);
245 std::pair<SmallString<16>,bool> res
246 = printableTextForNextCharacter(SourceLine, &i, TabStop);
247 columns += llvm::sys::locale::columnWidth(res.first);
249 out.resize(columns+1, -1);
254 struct SourceColumnMap {
255 SourceColumnMap(StringRef SourceLine, unsigned TabStop)
256 : m_SourceLine(SourceLine) {
258 ::byteToColumn(SourceLine, TabStop, m_byteToColumn);
259 ::columnToByte(SourceLine, TabStop, m_columnToByte);
261 assert(m_byteToColumn.size()==SourceLine.size()+1);
262 assert(0 < m_byteToColumn.size() && 0 < m_columnToByte.size());
263 assert(m_byteToColumn.size()
264 == static_cast<unsigned>(m_columnToByte.back()+1));
265 assert(static_cast<unsigned>(m_byteToColumn.back()+1)
266 == m_columnToByte.size());
268 int columns() const { return m_byteToColumn.back(); }
269 int bytes() const { return m_columnToByte.back(); }
271 /// \brief Map a byte to the column which it is at the start of, or return -1
272 /// if it is not at the start of a column (for a UTF-8 trailing byte).
273 int byteToColumn(int n) const {
274 assert(0<=n && n<static_cast<int>(m_byteToColumn.size()));
275 return m_byteToColumn[n];
278 /// \brief Map a byte to the first column which contains it.
279 int byteToContainingColumn(int N) const {
280 assert(0 <= N && N < static_cast<int>(m_byteToColumn.size()));
281 while (m_byteToColumn[N] == -1)
283 return m_byteToColumn[N];
286 /// \brief Map a column to the byte which starts the column, or return -1 if
287 /// the column the second or subsequent column of an expanded tab or similar
288 /// multi-column entity.
289 int columnToByte(int n) const {
290 assert(0<=n && n<static_cast<int>(m_columnToByte.size()));
291 return m_columnToByte[n];
294 /// \brief Map from a byte index to the next byte which starts a column.
295 int startOfNextColumn(int N) const {
296 assert(0 <= N && N < static_cast<int>(m_byteToColumn.size() - 1));
297 while (byteToColumn(++N) == -1) {}
301 /// \brief Map from a byte index to the previous byte which starts a column.
302 int startOfPreviousColumn(int N) const {
303 assert(0 < N && N < static_cast<int>(m_byteToColumn.size()));
304 while (byteToColumn(--N) == -1) {}
308 StringRef getSourceLine() const {
313 const std::string m_SourceLine;
314 SmallVector<int,200> m_byteToColumn;
315 SmallVector<int,200> m_columnToByte;
317 } // end anonymous namespace
319 /// \brief When the source code line we want to print is too long for
320 /// the terminal, select the "interesting" region.
321 static void selectInterestingSourceRegion(std::string &SourceLine,
322 std::string &CaretLine,
323 std::string &FixItInsertionLine,
325 const SourceColumnMap &map) {
326 unsigned CaretColumns = CaretLine.size();
327 unsigned FixItColumns = llvm::sys::locale::columnWidth(FixItInsertionLine);
328 unsigned MaxColumns = std::max(static_cast<unsigned>(map.columns()),
329 std::max(CaretColumns, FixItColumns));
330 // if the number of columns is less than the desired number we're done
331 if (MaxColumns <= Columns)
334 // No special characters are allowed in CaretLine.
335 assert(CaretLine.end() ==
336 std::find_if(CaretLine.begin(), CaretLine.end(),
337 [](char c) { return c < ' ' || '~' < c; }));
339 // Find the slice that we need to display the full caret line
341 unsigned CaretStart = 0, CaretEnd = CaretLine.size();
342 for (; CaretStart != CaretEnd; ++CaretStart)
343 if (!isWhitespace(CaretLine[CaretStart]))
346 for (; CaretEnd != CaretStart; --CaretEnd)
347 if (!isWhitespace(CaretLine[CaretEnd - 1]))
350 // caret has already been inserted into CaretLine so the above whitespace
351 // check is guaranteed to include the caret
353 // If we have a fix-it line, make sure the slice includes all of the
354 // fix-it information.
355 if (!FixItInsertionLine.empty()) {
356 unsigned FixItStart = 0, FixItEnd = FixItInsertionLine.size();
357 for (; FixItStart != FixItEnd; ++FixItStart)
358 if (!isWhitespace(FixItInsertionLine[FixItStart]))
361 for (; FixItEnd != FixItStart; --FixItEnd)
362 if (!isWhitespace(FixItInsertionLine[FixItEnd - 1]))
365 // We can safely use the byte offset FixItStart as the column offset
366 // because the characters up until FixItStart are all ASCII whitespace
368 unsigned FixItStartCol = FixItStart;
370 = llvm::sys::locale::columnWidth(FixItInsertionLine.substr(0, FixItEnd));
372 CaretStart = std::min(FixItStartCol, CaretStart);
373 CaretEnd = std::max(FixItEndCol, CaretEnd);
376 // CaretEnd may have been set at the middle of a character
377 // If it's not at a character's first column then advance it past the current
379 while (static_cast<int>(CaretEnd) < map.columns() &&
380 -1 == map.columnToByte(CaretEnd))
383 assert((static_cast<int>(CaretStart) > map.columns() ||
384 -1!=map.columnToByte(CaretStart)) &&
385 "CaretStart must not point to a column in the middle of a source"
387 assert((static_cast<int>(CaretEnd) > map.columns() ||
388 -1!=map.columnToByte(CaretEnd)) &&
389 "CaretEnd must not point to a column in the middle of a source line"
392 // CaretLine[CaretStart, CaretEnd) contains all of the interesting
393 // parts of the caret line. While this slice is smaller than the
394 // number of columns we have, try to grow the slice to encompass
397 unsigned SourceStart = map.columnToByte(std::min<unsigned>(CaretStart,
399 unsigned SourceEnd = map.columnToByte(std::min<unsigned>(CaretEnd,
402 unsigned CaretColumnsOutsideSource = CaretEnd-CaretStart
403 - (map.byteToColumn(SourceEnd)-map.byteToColumn(SourceStart));
405 char const *front_ellipse = " ...";
406 char const *front_space = " ";
407 char const *back_ellipse = "...";
408 unsigned ellipses_space = strlen(front_ellipse) + strlen(back_ellipse);
410 unsigned TargetColumns = Columns;
411 // Give us extra room for the ellipses
412 // and any of the caret line that extends past the source
413 if (TargetColumns > ellipses_space+CaretColumnsOutsideSource)
414 TargetColumns -= ellipses_space+CaretColumnsOutsideSource;
416 while (SourceStart>0 || SourceEnd<SourceLine.size()) {
417 bool ExpandedRegion = false;
420 unsigned NewStart = map.startOfPreviousColumn(SourceStart);
422 // Skip over any whitespace we see here; we're looking for
423 // another bit of interesting text.
424 // FIXME: Detect non-ASCII whitespace characters too.
425 while (NewStart && isWhitespace(SourceLine[NewStart]))
426 NewStart = map.startOfPreviousColumn(NewStart);
428 // Skip over this bit of "interesting" text.
430 unsigned Prev = map.startOfPreviousColumn(NewStart);
431 if (isWhitespace(SourceLine[Prev]))
436 assert(map.byteToColumn(NewStart) != -1);
437 unsigned NewColumns = map.byteToColumn(SourceEnd) -
438 map.byteToColumn(NewStart);
439 if (NewColumns <= TargetColumns) {
440 SourceStart = NewStart;
441 ExpandedRegion = true;
445 if (SourceEnd<SourceLine.size()) {
446 unsigned NewEnd = map.startOfNextColumn(SourceEnd);
448 // Skip over any whitespace we see here; we're looking for
449 // another bit of interesting text.
450 // FIXME: Detect non-ASCII whitespace characters too.
451 while (NewEnd < SourceLine.size() && isWhitespace(SourceLine[NewEnd]))
452 NewEnd = map.startOfNextColumn(NewEnd);
454 // Skip over this bit of "interesting" text.
455 while (NewEnd < SourceLine.size() && isWhitespace(SourceLine[NewEnd]))
456 NewEnd = map.startOfNextColumn(NewEnd);
458 assert(map.byteToColumn(NewEnd) != -1);
459 unsigned NewColumns = map.byteToColumn(NewEnd) -
460 map.byteToColumn(SourceStart);
461 if (NewColumns <= TargetColumns) {
463 ExpandedRegion = true;
471 CaretStart = map.byteToColumn(SourceStart);
472 CaretEnd = map.byteToColumn(SourceEnd) + CaretColumnsOutsideSource;
474 // [CaretStart, CaretEnd) is the slice we want. Update the various
475 // output lines to show only this slice, with two-space padding
476 // before the lines so that it looks nicer.
478 assert(CaretStart!=(unsigned)-1 && CaretEnd!=(unsigned)-1 &&
479 SourceStart!=(unsigned)-1 && SourceEnd!=(unsigned)-1);
480 assert(SourceStart <= SourceEnd);
481 assert(CaretStart <= CaretEnd);
483 unsigned BackColumnsRemoved
484 = map.byteToColumn(SourceLine.size())-map.byteToColumn(SourceEnd);
485 unsigned FrontColumnsRemoved = CaretStart;
486 unsigned ColumnsKept = CaretEnd-CaretStart;
488 // We checked up front that the line needed truncation
489 assert(FrontColumnsRemoved+ColumnsKept+BackColumnsRemoved > Columns);
491 // The line needs some truncation, and we'd prefer to keep the front
492 // if possible, so remove the back
493 if (BackColumnsRemoved > strlen(back_ellipse))
494 SourceLine.replace(SourceEnd, std::string::npos, back_ellipse);
496 // If that's enough then we're done
497 if (FrontColumnsRemoved+ColumnsKept <= Columns)
500 // Otherwise remove the front as well
501 if (FrontColumnsRemoved > strlen(front_ellipse)) {
502 SourceLine.replace(0, SourceStart, front_ellipse);
503 CaretLine.replace(0, CaretStart, front_space);
504 if (!FixItInsertionLine.empty())
505 FixItInsertionLine.replace(0, CaretStart, front_space);
509 /// \brief Skip over whitespace in the string, starting at the given
512 /// \returns The index of the first non-whitespace character that is
513 /// greater than or equal to Idx or, if no such character exists,
514 /// returns the end of the string.
515 static unsigned skipWhitespace(unsigned Idx, StringRef Str, unsigned Length) {
516 while (Idx < Length && isWhitespace(Str[Idx]))
521 /// \brief If the given character is the start of some kind of
522 /// balanced punctuation (e.g., quotes or parentheses), return the
523 /// character that will terminate the punctuation.
525 /// \returns The ending punctuation character, if any, or the NULL
526 /// character if the input character does not start any punctuation.
527 static inline char findMatchingPunctuation(char c) {
529 case '\'': return '\'';
530 case '`': return '\'';
531 case '"': return '"';
532 case '(': return ')';
533 case '[': return ']';
534 case '{': return '}';
541 /// \brief Find the end of the word starting at the given offset
544 /// \returns the index pointing one character past the end of the
546 static unsigned findEndOfWord(unsigned Start, StringRef Str,
547 unsigned Length, unsigned Column,
549 assert(Start < Str.size() && "Invalid start position!");
550 unsigned End = Start + 1;
552 // If we are already at the end of the string, take that as the word.
553 if (End == Str.size())
556 // Determine if the start of the string is actually opening
557 // punctuation, e.g., a quote or parentheses.
558 char EndPunct = findMatchingPunctuation(Str[Start]);
560 // This is a normal word. Just find the first space character.
561 while (End < Length && !isWhitespace(Str[End]))
566 // We have the start of a balanced punctuation sequence (quotes,
567 // parentheses, etc.). Determine the full sequence is.
568 SmallString<16> PunctuationEndStack;
569 PunctuationEndStack.push_back(EndPunct);
570 while (End < Length && !PunctuationEndStack.empty()) {
571 if (Str[End] == PunctuationEndStack.back())
572 PunctuationEndStack.pop_back();
573 else if (char SubEndPunct = findMatchingPunctuation(Str[End]))
574 PunctuationEndStack.push_back(SubEndPunct);
579 // Find the first space character after the punctuation ended.
580 while (End < Length && !isWhitespace(Str[End]))
583 unsigned PunctWordLength = End - Start;
584 if (// If the word fits on this line
585 Column + PunctWordLength <= Columns ||
586 // ... or the word is "short enough" to take up the next line
587 // without too much ugly white space
588 PunctWordLength < Columns/3)
589 return End; // Take the whole thing as a single "word".
591 // The whole quoted/parenthesized string is too long to print as a
592 // single "word". Instead, find the "word" that starts just after
593 // the punctuation and use that end-point instead. This will recurse
594 // until it finds something small enough to consider a word.
595 return findEndOfWord(Start + 1, Str, Length, Column + 1, Columns);
598 /// \brief Print the given string to a stream, word-wrapping it to
599 /// some number of columns in the process.
601 /// \param OS the stream to which the word-wrapping string will be
603 /// \param Str the string to word-wrap and output.
604 /// \param Columns the number of columns to word-wrap to.
605 /// \param Column the column number at which the first character of \p
606 /// Str will be printed. This will be non-zero when part of the first
607 /// line has already been printed.
608 /// \param Bold if the current text should be bold
609 /// \param Indentation the number of spaces to indent any lines beyond
611 /// \returns true if word-wrapping was required, or false if the
612 /// string fit on the first line.
613 static bool printWordWrapped(raw_ostream &OS, StringRef Str,
617 unsigned Indentation = WordWrapIndentation) {
618 const unsigned Length = std::min(Str.find('\n'), Str.size());
619 bool TextNormal = true;
621 // The string used to indent each line.
622 SmallString<16> IndentStr;
623 IndentStr.assign(Indentation, ' ');
624 bool Wrapped = false;
625 for (unsigned WordStart = 0, WordEnd; WordStart < Length;
626 WordStart = WordEnd) {
627 // Find the beginning of the next word.
628 WordStart = skipWhitespace(WordStart, Str, Length);
629 if (WordStart == Length)
632 // Find the end of this word.
633 WordEnd = findEndOfWord(WordStart, Str, Length, Column, Columns);
635 // Does this word fit on the current line?
636 unsigned WordLength = WordEnd - WordStart;
637 if (Column + WordLength < Columns) {
638 // This word fits on the current line; print it there.
643 applyTemplateHighlighting(OS, Str.substr(WordStart, WordLength),
645 Column += WordLength;
649 // This word does not fit on the current line, so wrap to the next
652 OS.write(&IndentStr[0], Indentation);
653 applyTemplateHighlighting(OS, Str.substr(WordStart, WordLength),
655 Column = Indentation + WordLength;
659 // Append any remaning text from the message with its existing formatting.
660 applyTemplateHighlighting(OS, Str.substr(Length), TextNormal, Bold);
662 assert(TextNormal && "Text highlighted at end of diagnostic message.");
667 TextDiagnostic::TextDiagnostic(raw_ostream &OS,
668 const LangOptions &LangOpts,
669 DiagnosticOptions *DiagOpts)
670 : DiagnosticRenderer(LangOpts, DiagOpts), OS(OS) {}
672 TextDiagnostic::~TextDiagnostic() {}
675 TextDiagnostic::emitDiagnosticMessage(SourceLocation Loc,
677 DiagnosticsEngine::Level Level,
679 ArrayRef<clang::CharSourceRange> Ranges,
680 const SourceManager *SM,
681 DiagOrStoredDiag D) {
682 uint64_t StartOfLocationInfo = OS.tell();
684 // Emit the location of this particular diagnostic.
686 emitDiagnosticLoc(Loc, PLoc, Level, Ranges, *SM);
688 if (DiagOpts->ShowColors)
691 printDiagnosticLevel(OS, Level, DiagOpts->ShowColors,
692 DiagOpts->CLFallbackMode);
693 printDiagnosticMessage(OS,
694 /*IsSupplemental*/ Level == DiagnosticsEngine::Note,
695 Message, OS.tell() - StartOfLocationInfo,
696 DiagOpts->MessageLength, DiagOpts->ShowColors);
700 TextDiagnostic::printDiagnosticLevel(raw_ostream &OS,
701 DiagnosticsEngine::Level Level,
703 bool CLFallbackMode) {
705 // Print diagnostic category in bold and color
707 case DiagnosticsEngine::Ignored:
708 llvm_unreachable("Invalid diagnostic type");
709 case DiagnosticsEngine::Note: OS.changeColor(noteColor, true); break;
710 case DiagnosticsEngine::Remark: OS.changeColor(remarkColor, true); break;
711 case DiagnosticsEngine::Warning: OS.changeColor(warningColor, true); break;
712 case DiagnosticsEngine::Error: OS.changeColor(errorColor, true); break;
713 case DiagnosticsEngine::Fatal: OS.changeColor(fatalColor, true); break;
718 case DiagnosticsEngine::Ignored:
719 llvm_unreachable("Invalid diagnostic type");
720 case DiagnosticsEngine::Note: OS << "note"; break;
721 case DiagnosticsEngine::Remark: OS << "remark"; break;
722 case DiagnosticsEngine::Warning: OS << "warning"; break;
723 case DiagnosticsEngine::Error: OS << "error"; break;
724 case DiagnosticsEngine::Fatal: OS << "fatal error"; break;
727 // In clang-cl /fallback mode, print diagnostics as "error(clang):". This
728 // makes it more clear whether a message is coming from clang or cl.exe,
729 // and it prevents MSBuild from concluding that the build failed just because
730 // there is an "error:" in the output.
741 void TextDiagnostic::printDiagnosticMessage(raw_ostream &OS,
744 unsigned CurrentColumn,
745 unsigned Columns, bool ShowColors) {
747 if (ShowColors && !IsSupplemental) {
748 // Print primary diagnostic messages in bold and without color, to visually
749 // indicate the transition from continuation notes and other output.
750 OS.changeColor(savedColor, true);
755 printWordWrapped(OS, Message, Columns, CurrentColumn, Bold);
758 applyTemplateHighlighting(OS, Message, Normal, Bold);
759 assert(Normal && "Formatting should have returned to normal");
767 /// \brief Print out the file/line/column information and include trace.
769 /// This method handlen the emission of the diagnostic location information.
770 /// This includes extracting as much location information as is present for
771 /// the diagnostic and printing it, as well as any include stack or source
772 /// ranges necessary.
773 void TextDiagnostic::emitDiagnosticLoc(SourceLocation Loc, PresumedLoc PLoc,
774 DiagnosticsEngine::Level Level,
775 ArrayRef<CharSourceRange> Ranges,
776 const SourceManager &SM) {
777 if (PLoc.isInvalid()) {
778 // At least print the file name if available:
779 FileID FID = SM.getFileID(Loc);
781 const FileEntry* FE = SM.getFileEntryForID(FID);
782 if (FE && FE->isValid()) {
791 unsigned LineNo = PLoc.getLine();
793 if (!DiagOpts->ShowLocation)
796 if (DiagOpts->ShowColors)
797 OS.changeColor(savedColor, true);
799 OS << PLoc.getFilename();
800 switch (DiagOpts->getFormat()) {
801 case DiagnosticOptions::Clang: OS << ':' << LineNo; break;
802 case DiagnosticOptions::MSVC: OS << '(' << LineNo; break;
803 case DiagnosticOptions::Vi: OS << " +" << LineNo; break;
806 if (DiagOpts->ShowColumn)
807 // Compute the column number.
808 if (unsigned ColNo = PLoc.getColumn()) {
809 if (DiagOpts->getFormat() == DiagnosticOptions::MSVC) {
811 // Visual Studio 2010 or earlier expects column number to be off by one
812 if (LangOpts.MSCompatibilityVersion &&
813 !LangOpts.isCompatibleWithMSVC(LangOptions::MSVC2012))
819 switch (DiagOpts->getFormat()) {
820 case DiagnosticOptions::Clang:
821 case DiagnosticOptions::Vi: OS << ':'; break;
822 case DiagnosticOptions::MSVC:
823 // MSVC2013 and before print 'file(4) : error'. MSVC2015 gets rid of the
824 // space and prints 'file(4): error'.
826 if (LangOpts.MSCompatibilityVersion &&
827 !LangOpts.isCompatibleWithMSVC(LangOptions::MSVC2015))
833 if (DiagOpts->ShowSourceRanges && !Ranges.empty()) {
835 SM.getFileID(SM.getExpansionLoc(Loc));
836 bool PrintedRange = false;
838 for (ArrayRef<CharSourceRange>::const_iterator RI = Ranges.begin(),
841 // Ignore invalid ranges.
842 if (!RI->isValid()) continue;
844 SourceLocation B = SM.getExpansionLoc(RI->getBegin());
845 SourceLocation E = SM.getExpansionLoc(RI->getEnd());
847 // If the End location and the start location are the same and are a
848 // macro location, then the range was something that came from a
849 // macro expansion or _Pragma. If this is an object-like macro, the
850 // best we can do is to highlight the range. If this is a
851 // function-like macro, we'd also like to highlight the arguments.
852 if (B == E && RI->getEnd().isMacroID())
853 E = SM.getExpansionRange(RI->getEnd()).second;
855 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(B);
856 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E);
858 // If the start or end of the range is in another file, just discard
860 if (BInfo.first != CaretFileID || EInfo.first != CaretFileID)
863 // Add in the length of the token, so that we cover multi-char
865 unsigned TokSize = 0;
866 if (RI->isTokenRange())
867 TokSize = Lexer::MeasureTokenLength(E, SM, LangOpts);
869 OS << '{' << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
870 << SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
871 << SM.getLineNumber(EInfo.first, EInfo.second) << ':'
872 << (SM.getColumnNumber(EInfo.first, EInfo.second)+TokSize)
883 void TextDiagnostic::emitIncludeLocation(SourceLocation Loc,
885 const SourceManager &SM) {
886 if (DiagOpts->ShowLocation && PLoc.isValid())
887 OS << "In file included from " << PLoc.getFilename() << ':'
888 << PLoc.getLine() << ":\n";
890 OS << "In included file:\n";
893 void TextDiagnostic::emitImportLocation(SourceLocation Loc, PresumedLoc PLoc,
894 StringRef ModuleName,
895 const SourceManager &SM) {
896 if (DiagOpts->ShowLocation && PLoc.isValid())
897 OS << "In module '" << ModuleName << "' imported from "
898 << PLoc.getFilename() << ':' << PLoc.getLine() << ":\n";
900 OS << "In module '" << ModuleName << "':\n";
903 void TextDiagnostic::emitBuildingModuleLocation(SourceLocation Loc,
905 StringRef ModuleName,
906 const SourceManager &SM) {
907 if (DiagOpts->ShowLocation && PLoc.isValid())
908 OS << "While building module '" << ModuleName << "' imported from "
909 << PLoc.getFilename() << ':' << PLoc.getLine() << ":\n";
911 OS << "While building module '" << ModuleName << "':\n";
914 /// \brief Highlight a SourceRange (with ~'s) for any characters on LineNo.
915 static void highlightRange(const CharSourceRange &R,
916 unsigned LineNo, FileID FID,
917 const SourceColumnMap &map,
918 std::string &CaretLine,
919 const SourceManager &SM,
920 const LangOptions &LangOpts) {
921 if (!R.isValid()) return;
923 SourceLocation Begin = R.getBegin();
924 SourceLocation End = R.getEnd();
926 unsigned StartLineNo = SM.getExpansionLineNumber(Begin);
927 if (StartLineNo > LineNo || SM.getFileID(Begin) != FID)
928 return; // No intersection.
930 unsigned EndLineNo = SM.getExpansionLineNumber(End);
931 if (EndLineNo < LineNo || SM.getFileID(End) != FID)
932 return; // No intersection.
934 // Compute the column number of the start.
935 unsigned StartColNo = 0;
936 if (StartLineNo == LineNo) {
937 StartColNo = SM.getExpansionColumnNumber(Begin);
938 if (StartColNo) --StartColNo; // Zero base the col #.
941 // Compute the column number of the end.
942 unsigned EndColNo = map.getSourceLine().size();
943 if (EndLineNo == LineNo) {
944 EndColNo = SM.getExpansionColumnNumber(End);
946 --EndColNo; // Zero base the col #.
948 // Add in the length of the token, so that we cover multi-char tokens if
949 // this is a token range.
950 if (R.isTokenRange())
951 EndColNo += Lexer::MeasureTokenLength(End, SM, LangOpts);
953 EndColNo = CaretLine.size();
957 assert(StartColNo <= EndColNo && "Invalid range!");
959 // Check that a token range does not highlight only whitespace.
960 if (R.isTokenRange()) {
961 // Pick the first non-whitespace column.
962 while (StartColNo < map.getSourceLine().size() &&
963 (map.getSourceLine()[StartColNo] == ' ' ||
964 map.getSourceLine()[StartColNo] == '\t'))
965 StartColNo = map.startOfNextColumn(StartColNo);
967 // Pick the last non-whitespace column.
968 if (EndColNo > map.getSourceLine().size())
969 EndColNo = map.getSourceLine().size();
971 (map.getSourceLine()[EndColNo-1] == ' ' ||
972 map.getSourceLine()[EndColNo-1] == '\t'))
973 EndColNo = map.startOfPreviousColumn(EndColNo);
975 // If the start/end passed each other, then we are trying to highlight a
976 // range that just exists in whitespace, which must be some sort of other
978 assert(StartColNo <= EndColNo && "Trying to highlight whitespace??");
981 assert(StartColNo <= map.getSourceLine().size() && "Invalid range!");
982 assert(EndColNo <= map.getSourceLine().size() && "Invalid range!");
984 // Fill the range with ~'s.
985 StartColNo = map.byteToContainingColumn(StartColNo);
986 EndColNo = map.byteToContainingColumn(EndColNo);
988 assert(StartColNo <= EndColNo && "Invalid range!");
989 if (CaretLine.size() < EndColNo)
990 CaretLine.resize(EndColNo,' ');
991 std::fill(CaretLine.begin()+StartColNo,CaretLine.begin()+EndColNo,'~');
994 static std::string buildFixItInsertionLine(unsigned LineNo,
995 const SourceColumnMap &map,
996 ArrayRef<FixItHint> Hints,
997 const SourceManager &SM,
998 const DiagnosticOptions *DiagOpts) {
999 std::string FixItInsertionLine;
1000 if (Hints.empty() || !DiagOpts->ShowFixits)
1001 return FixItInsertionLine;
1002 unsigned PrevHintEndCol = 0;
1004 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1006 if (!I->CodeToInsert.empty()) {
1007 // We have an insertion hint. Determine whether the inserted
1008 // code contains no newlines and is on the same line as the caret.
1009 std::pair<FileID, unsigned> HintLocInfo
1010 = SM.getDecomposedExpansionLoc(I->RemoveRange.getBegin());
1011 if (LineNo == SM.getLineNumber(HintLocInfo.first, HintLocInfo.second) &&
1012 StringRef(I->CodeToInsert).find_first_of("\n\r") == StringRef::npos) {
1013 // Insert the new code into the line just below the code
1014 // that the user wrote.
1015 // Note: When modifying this function, be very careful about what is a
1016 // "column" (printed width, platform-dependent) and what is a
1017 // "byte offset" (SourceManager "column").
1018 unsigned HintByteOffset
1019 = SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second) - 1;
1021 // The hint must start inside the source or right at the end
1022 assert(HintByteOffset < static_cast<unsigned>(map.bytes())+1);
1023 unsigned HintCol = map.byteToContainingColumn(HintByteOffset);
1025 // If we inserted a long previous hint, push this one forwards, and add
1026 // an extra space to show that this is not part of the previous
1027 // completion. This is sort of the best we can do when two hints appear
1030 // Note that if this hint is located immediately after the previous
1031 // hint, no space will be added, since the location is more important.
1032 if (HintCol < PrevHintEndCol)
1033 HintCol = PrevHintEndCol + 1;
1035 // This should NOT use HintByteOffset, because the source might have
1036 // Unicode characters in earlier columns.
1037 unsigned NewFixItLineSize = FixItInsertionLine.size() +
1038 (HintCol - PrevHintEndCol) + I->CodeToInsert.size();
1039 if (NewFixItLineSize > FixItInsertionLine.size())
1040 FixItInsertionLine.resize(NewFixItLineSize, ' ');
1042 std::copy(I->CodeToInsert.begin(), I->CodeToInsert.end(),
1043 FixItInsertionLine.end() - I->CodeToInsert.size());
1046 HintCol + llvm::sys::locale::columnWidth(I->CodeToInsert);
1048 FixItInsertionLine.clear();
1054 expandTabs(FixItInsertionLine, DiagOpts->TabStop);
1056 return FixItInsertionLine;
1059 /// \brief Emit a code snippet and caret line.
1061 /// This routine emits a single line's code snippet and caret line..
1063 /// \param Loc The location for the caret.
1064 /// \param Ranges The underlined ranges for this code snippet.
1065 /// \param Hints The FixIt hints active for this diagnostic.
1066 void TextDiagnostic::emitSnippetAndCaret(
1067 SourceLocation Loc, DiagnosticsEngine::Level Level,
1068 SmallVectorImpl<CharSourceRange>& Ranges,
1069 ArrayRef<FixItHint> Hints,
1070 const SourceManager &SM) {
1071 assert(Loc.isValid() && "must have a valid source location here");
1072 assert(Loc.isFileID() && "must have a file location here");
1074 // If caret diagnostics are enabled and we have location, we want to
1075 // emit the caret. However, we only do this if the location moved
1076 // from the last diagnostic, if the last diagnostic was a note that
1077 // was part of a different warning or error diagnostic, or if the
1078 // diagnostic has ranges. We don't want to emit the same caret
1079 // multiple times if one loc has multiple diagnostics.
1080 if (!DiagOpts->ShowCarets)
1082 if (Loc == LastLoc && Ranges.empty() && Hints.empty() &&
1083 (LastLevel != DiagnosticsEngine::Note || Level == LastLevel))
1086 // Decompose the location into a FID/Offset pair.
1087 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1088 FileID FID = LocInfo.first;
1089 unsigned FileOffset = LocInfo.second;
1091 // Get information about the buffer it points into.
1092 bool Invalid = false;
1093 StringRef BufData = SM.getBufferData(FID, &Invalid);
1097 const char *BufStart = BufData.data();
1098 const char *BufEnd = BufStart + BufData.size();
1100 unsigned LineNo = SM.getLineNumber(FID, FileOffset);
1101 unsigned ColNo = SM.getColumnNumber(FID, FileOffset);
1103 // Arbitrarily stop showing snippets when the line is too long.
1104 static const size_t MaxLineLengthToPrint = 4096;
1105 if (ColNo > MaxLineLengthToPrint)
1108 // Rewind from the current position to the start of the line.
1109 const char *TokPtr = BufStart+FileOffset;
1110 const char *LineStart = TokPtr-ColNo+1; // Column # is 1-based.
1112 // Compute the line end. Scan forward from the error position to the end of
1114 const char *LineEnd = TokPtr;
1115 while (*LineEnd != '\n' && *LineEnd != '\r' && LineEnd != BufEnd)
1118 // Arbitrarily stop showing snippets when the line is too long.
1119 if (size_t(LineEnd - LineStart) > MaxLineLengthToPrint)
1122 // Trim trailing null-bytes.
1123 StringRef Line(LineStart, LineEnd - LineStart);
1124 while (Line.size() > ColNo && Line.back() == '\0')
1125 Line = Line.drop_back();
1127 // Copy the line of code into an std::string for ease of manipulation.
1128 std::string SourceLine(Line.begin(), Line.end());
1130 // Build the byte to column map.
1131 const SourceColumnMap sourceColMap(SourceLine, DiagOpts->TabStop);
1133 // Create a line for the caret that is filled with spaces that is the same
1134 // number of columns as the line of source code.
1135 std::string CaretLine(sourceColMap.columns(), ' ');
1137 // Highlight all of the characters covered by Ranges with ~ characters.
1138 for (SmallVectorImpl<CharSourceRange>::iterator I = Ranges.begin(),
1141 highlightRange(*I, LineNo, FID, sourceColMap, CaretLine, SM, LangOpts);
1143 // Next, insert the caret itself.
1144 ColNo = sourceColMap.byteToContainingColumn(ColNo-1);
1145 if (CaretLine.size()<ColNo+1)
1146 CaretLine.resize(ColNo+1, ' ');
1147 CaretLine[ColNo] = '^';
1149 std::string FixItInsertionLine = buildFixItInsertionLine(LineNo,
1154 // If the source line is too long for our terminal, select only the
1155 // "interesting" source region within that line.
1156 unsigned Columns = DiagOpts->MessageLength;
1158 selectInterestingSourceRegion(SourceLine, CaretLine, FixItInsertionLine,
1159 Columns, sourceColMap);
1161 // If we are in -fdiagnostics-print-source-range-info mode, we are trying
1162 // to produce easily machine parsable output. Add a space before the
1163 // source line and the caret to make it trivial to tell the main diagnostic
1164 // line from what the user is intended to see.
1165 if (DiagOpts->ShowSourceRanges) {
1166 SourceLine = ' ' + SourceLine;
1167 CaretLine = ' ' + CaretLine;
1170 // Finally, remove any blank spaces from the end of CaretLine.
1171 while (CaretLine[CaretLine.size()-1] == ' ')
1172 CaretLine.erase(CaretLine.end()-1);
1174 // Emit what we have computed.
1175 emitSnippet(SourceLine);
1177 if (DiagOpts->ShowColors)
1178 OS.changeColor(caretColor, true);
1179 OS << CaretLine << '\n';
1180 if (DiagOpts->ShowColors)
1183 if (!FixItInsertionLine.empty()) {
1184 if (DiagOpts->ShowColors)
1185 // Print fixit line in color
1186 OS.changeColor(fixitColor, false);
1187 if (DiagOpts->ShowSourceRanges)
1189 OS << FixItInsertionLine << '\n';
1190 if (DiagOpts->ShowColors)
1194 // Print out any parseable fixit information requested by the options.
1195 emitParseableFixits(Hints, SM);
1198 void TextDiagnostic::emitSnippet(StringRef line) {
1204 std::string to_print;
1205 bool print_reversed = false;
1207 while (i<line.size()) {
1208 std::pair<SmallString<16>,bool> res
1209 = printableTextForNextCharacter(line, &i, DiagOpts->TabStop);
1210 bool was_printable = res.second;
1212 if (DiagOpts->ShowColors && was_printable == print_reversed) {
1217 if (DiagOpts->ShowColors)
1221 print_reversed = !was_printable;
1222 to_print += res.first.str();
1225 if (print_reversed && DiagOpts->ShowColors)
1228 if (print_reversed && DiagOpts->ShowColors)
1234 void TextDiagnostic::emitParseableFixits(ArrayRef<FixItHint> Hints,
1235 const SourceManager &SM) {
1236 if (!DiagOpts->ShowParseableFixits)
1239 // We follow FixItRewriter's example in not (yet) handling
1240 // fix-its in macros.
1241 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1243 if (I->RemoveRange.isInvalid() ||
1244 I->RemoveRange.getBegin().isMacroID() ||
1245 I->RemoveRange.getEnd().isMacroID())
1249 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1251 SourceLocation BLoc = I->RemoveRange.getBegin();
1252 SourceLocation ELoc = I->RemoveRange.getEnd();
1254 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(BLoc);
1255 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(ELoc);
1257 // Adjust for token ranges.
1258 if (I->RemoveRange.isTokenRange())
1259 EInfo.second += Lexer::MeasureTokenLength(ELoc, SM, LangOpts);
1261 // We specifically do not do word-wrapping or tab-expansion here,
1262 // because this is supposed to be easy to parse.
1263 PresumedLoc PLoc = SM.getPresumedLoc(BLoc);
1264 if (PLoc.isInvalid())
1268 OS.write_escaped(PLoc.getFilename());
1269 OS << "\":{" << SM.getLineNumber(BInfo.first, BInfo.second)
1270 << ':' << SM.getColumnNumber(BInfo.first, BInfo.second)
1271 << '-' << SM.getLineNumber(EInfo.first, EInfo.second)
1272 << ':' << SM.getColumnNumber(EInfo.first, EInfo.second)
1274 OS.write_escaped(I->CodeToInsert);