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/FileManager.h"
12 #include "clang/Basic/SourceManager.h"
13 #include "clang/Basic/ConvertUTF.h"
14 #include "clang/Basic/DiagnosticOptions.h"
15 #include "clang/Lex/Lexer.h"
16 #include "llvm/Support/MemoryBuffer.h"
17 #include "llvm/Support/raw_ostream.h"
18 #include "llvm/Support/ErrorHandling.h"
19 #include "llvm/Support/Locale.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/ADT/StringExtras.h"
25 using namespace clang;
27 static const enum raw_ostream::Colors noteColor =
29 static const enum raw_ostream::Colors fixitColor =
31 static const enum raw_ostream::Colors caretColor =
33 static const enum raw_ostream::Colors warningColor =
35 static const enum raw_ostream::Colors templateColor =
37 static const enum raw_ostream::Colors errorColor = raw_ostream::RED;
38 static const enum raw_ostream::Colors fatalColor = raw_ostream::RED;
39 // Used for changing only the bold attribute.
40 static const enum raw_ostream::Colors savedColor =
41 raw_ostream::SAVEDCOLOR;
43 /// \brief Add highlights to differences in template strings.
44 static void applyTemplateHighlighting(raw_ostream &OS, StringRef Str,
45 bool &Normal, bool Bold) {
47 size_t Pos = Str.find(ToggleHighlight);
48 OS << Str.slice(0, Pos);
49 if (Pos == StringRef::npos)
52 Str = Str.substr(Pos + 1);
54 OS.changeColor(templateColor, true);
58 OS.changeColor(savedColor, true);
64 /// \brief Number of spaces to indent when word-wrapping.
65 const unsigned WordWrapIndentation = 6;
67 static int bytesSincePreviousTabOrLineBegin(StringRef SourceLine, size_t i) {
70 if (SourceLine[--i]=='\t')
77 /// \brief returns a printable representation of first item from input range
79 /// This function returns a printable representation of the next item in a line
80 /// of source. If the next byte begins a valid and printable character, that
81 /// character is returned along with 'true'.
83 /// Otherwise, if the next byte begins a valid, but unprintable character, a
84 /// printable, escaped representation of the character is returned, along with
85 /// 'false'. Otherwise a printable, escaped representation of the next byte
86 /// is returned along with 'false'.
88 /// \note The index is updated to be used with a subsequent call to
89 /// printableTextForNextCharacter.
91 /// \param SourceLine The line of source
92 /// \param i Pointer to byte index,
93 /// \param TabStop used to expand tabs
94 /// \return pair(printable text, 'true' iff original text was printable)
96 static std::pair<SmallString<16>, bool>
97 printableTextForNextCharacter(StringRef SourceLine, size_t *i,
99 assert(i && "i must not be null");
100 assert(*i<SourceLine.size() && "must point to a valid index");
102 if (SourceLine[*i]=='\t') {
103 assert(0 < TabStop && TabStop <= DiagnosticOptions::MaxTabStop &&
104 "Invalid -ftabstop value");
105 unsigned col = bytesSincePreviousTabOrLineBegin(SourceLine, *i);
106 unsigned NumSpaces = TabStop - col%TabStop;
107 assert(0 < NumSpaces && NumSpaces <= TabStop
108 && "Invalid computation of space amt");
111 SmallString<16> expandedTab;
112 expandedTab.assign(NumSpaces, ' ');
113 return std::make_pair(expandedTab, true);
116 unsigned char const *begin, *end;
117 begin = reinterpret_cast<unsigned char const *>(&*(SourceLine.begin() + *i));
118 end = begin + (SourceLine.size() - *i);
120 if (isLegalUTF8Sequence(begin, end)) {
123 unsigned char const *original_begin = begin;
124 unsigned char const *cp_end = begin+getNumBytesForUTF8(SourceLine[*i]);
126 ConversionResult res = ConvertUTF8toUTF32(&begin, cp_end, &cptr, cptr+1,
129 assert(conversionOK==res);
130 assert(0 < begin-original_begin
131 && "we must be further along in the string now");
132 *i += begin-original_begin;
134 if (!llvm::sys::locale::isPrint(c)) {
135 // If next character is valid UTF-8, but not printable
136 SmallString<16> expandedCP("<U+>");
138 expandedCP.insert(expandedCP.begin()+3, llvm::hexdigit(c%16));
141 while (expandedCP.size() < 8)
142 expandedCP.insert(expandedCP.begin()+3, llvm::hexdigit(0));
143 return std::make_pair(expandedCP, false);
146 // If next character is valid UTF-8, and printable
147 return std::make_pair(SmallString<16>(original_begin, cp_end), true);
151 // If next byte is not valid UTF-8 (and therefore not printable)
152 SmallString<16> expandedByte("<XX>");
153 unsigned char byte = SourceLine[*i];
154 expandedByte[1] = llvm::hexdigit(byte / 16);
155 expandedByte[2] = llvm::hexdigit(byte % 16);
157 return std::make_pair(expandedByte, false);
160 static void expandTabs(std::string &SourceLine, unsigned TabStop) {
161 size_t i = SourceLine.size();
164 if (SourceLine[i]!='\t')
167 std::pair<SmallString<16>,bool> res
168 = printableTextForNextCharacter(SourceLine, &tmp_i, TabStop);
169 SourceLine.replace(i, 1, res.first.c_str());
173 /// This function takes a raw source line and produces a mapping from the bytes
174 /// of the printable representation of the line to the columns those printable
175 /// characters will appear at (numbering the first column as 0).
177 /// If a byte 'i' corresponds to muliple columns (e.g. the byte contains a tab
178 /// character) then the array will map that byte to the first column the
179 /// tab appears at and the next value in the map will have been incremented
182 /// If a byte is the first in a sequence of bytes that together map to a single
183 /// entity in the output, then the array will map that byte to the appropriate
184 /// column while the subsequent bytes will be -1.
186 /// The last element in the array does not correspond to any byte in the input
187 /// and instead is the number of columns needed to display the source
189 /// example: (given a tabstop of 8)
191 /// "a \t \u3042" -> {0,1,2,8,9,-1,-1,11}
193 /// (\\u3042 is represented in UTF-8 by three bytes and takes two columns to
195 static void byteToColumn(StringRef SourceLine, unsigned TabStop,
196 SmallVectorImpl<int> &out) {
199 if (SourceLine.empty()) {
204 out.resize(SourceLine.size()+1, -1);
208 while (i<SourceLine.size()) {
210 std::pair<SmallString<16>,bool> res
211 = printableTextForNextCharacter(SourceLine, &i, TabStop);
212 columns += llvm::sys::locale::columnWidth(res.first);
214 out.back() = columns;
217 /// This function takes a raw source line and produces a mapping from columns
218 /// to the byte of the source line that produced the character displaying at
219 /// that column. This is the inverse of the mapping produced by byteToColumn()
221 /// The last element in the array is the number of bytes in the source string
223 /// example: (given a tabstop of 8)
225 /// "a \t \u3042" -> {0,1,2,-1,-1,-1,-1,-1,3,4,-1,7}
227 /// (\\u3042 is represented in UTF-8 by three bytes and takes two columns to
229 static void columnToByte(StringRef SourceLine, unsigned TabStop,
230 SmallVectorImpl<int> &out) {
233 if (SourceLine.empty()) {
240 while (i<SourceLine.size()) {
241 out.resize(columns+1, -1);
243 std::pair<SmallString<16>,bool> res
244 = printableTextForNextCharacter(SourceLine, &i, TabStop);
245 columns += llvm::sys::locale::columnWidth(res.first);
247 out.resize(columns+1, -1);
251 struct SourceColumnMap {
252 SourceColumnMap(StringRef SourceLine, unsigned TabStop)
253 : m_SourceLine(SourceLine) {
255 ::byteToColumn(SourceLine, TabStop, m_byteToColumn);
256 ::columnToByte(SourceLine, TabStop, m_columnToByte);
258 assert(m_byteToColumn.size()==SourceLine.size()+1);
259 assert(0 < m_byteToColumn.size() && 0 < m_columnToByte.size());
260 assert(m_byteToColumn.size()
261 == static_cast<unsigned>(m_columnToByte.back()+1));
262 assert(static_cast<unsigned>(m_byteToColumn.back()+1)
263 == m_columnToByte.size());
265 int columns() const { return m_byteToColumn.back(); }
266 int bytes() const { return m_columnToByte.back(); }
268 /// \brief Map a byte to the column which it is at the start of, or return -1
269 /// if it is not at the start of a column (for a UTF-8 trailing byte).
270 int byteToColumn(int n) const {
271 assert(0<=n && n<static_cast<int>(m_byteToColumn.size()));
272 return m_byteToColumn[n];
275 /// \brief Map a byte to the first column which contains it.
276 int byteToContainingColumn(int N) const {
277 assert(0 <= N && N < static_cast<int>(m_byteToColumn.size()));
278 while (m_byteToColumn[N] == -1)
280 return m_byteToColumn[N];
283 /// \brief Map a column to the byte which starts the column, or return -1 if
284 /// the column the second or subsequent column of an expanded tab or similar
285 /// multi-column entity.
286 int columnToByte(int n) const {
287 assert(0<=n && n<static_cast<int>(m_columnToByte.size()));
288 return m_columnToByte[n];
291 /// \brief Map from a byte index to the next byte which starts a column.
292 int startOfNextColumn(int N) const {
293 assert(0 <= N && N < static_cast<int>(m_columnToByte.size() - 1));
294 while (byteToColumn(++N) == -1) {}
298 /// \brief Map from a byte index to the previous byte which starts a column.
299 int startOfPreviousColumn(int N) const {
300 assert(0 < N && N < static_cast<int>(m_columnToByte.size()));
301 while (byteToColumn(--N) == -1) {}
305 StringRef getSourceLine() const {
310 const std::string m_SourceLine;
311 SmallVector<int,200> m_byteToColumn;
312 SmallVector<int,200> m_columnToByte;
315 // used in assert in selectInterestingSourceRegion()
317 struct char_out_of_range {
318 const char lower,upper;
319 char_out_of_range(char lower, char upper) :
320 lower(lower), upper(upper) {}
321 bool operator()(char c) { return c < lower || upper < c; }
325 /// \brief When the source code line we want to print is too long for
326 /// the terminal, select the "interesting" region.
327 static void selectInterestingSourceRegion(std::string &SourceLine,
328 std::string &CaretLine,
329 std::string &FixItInsertionLine,
331 const SourceColumnMap &map) {
332 unsigned MaxColumns = std::max<unsigned>(map.columns(),
333 std::max(CaretLine.size(),
334 FixItInsertionLine.size()));
335 // if the number of columns is less than the desired number we're done
336 if (MaxColumns <= Columns)
339 // no special characters allowed in CaretLine or FixItInsertionLine
340 assert(CaretLine.end() ==
341 std::find_if(CaretLine.begin(), CaretLine.end(),
342 char_out_of_range(' ','~')));
343 assert(FixItInsertionLine.end() ==
344 std::find_if(FixItInsertionLine.begin(), FixItInsertionLine.end(),
345 char_out_of_range(' ','~')));
347 // Find the slice that we need to display the full caret line
349 unsigned CaretStart = 0, CaretEnd = CaretLine.size();
350 for (; CaretStart != CaretEnd; ++CaretStart)
351 if (!isspace(static_cast<unsigned char>(CaretLine[CaretStart])))
354 for (; CaretEnd != CaretStart; --CaretEnd)
355 if (!isspace(static_cast<unsigned char>(CaretLine[CaretEnd - 1])))
358 // caret has already been inserted into CaretLine so the above whitespace
359 // check is guaranteed to include the caret
361 // If we have a fix-it line, make sure the slice includes all of the
362 // fix-it information.
363 if (!FixItInsertionLine.empty()) {
364 unsigned FixItStart = 0, FixItEnd = FixItInsertionLine.size();
365 for (; FixItStart != FixItEnd; ++FixItStart)
366 if (!isspace(static_cast<unsigned char>(FixItInsertionLine[FixItStart])))
369 for (; FixItEnd != FixItStart; --FixItEnd)
370 if (!isspace(static_cast<unsigned char>(FixItInsertionLine[FixItEnd - 1])))
373 CaretStart = std::min(FixItStart, CaretStart);
374 CaretEnd = std::max(FixItEnd, 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.
427 isspace(static_cast<unsigned char>(SourceLine[NewStart])))
428 NewStart = map.startOfPreviousColumn(NewStart);
430 // Skip over this bit of "interesting" text.
432 unsigned Prev = map.startOfPreviousColumn(NewStart);
433 if (isspace(static_cast<unsigned char>(SourceLine[Prev])))
438 assert(map.byteToColumn(NewStart) != -1);
439 unsigned NewColumns = map.byteToColumn(SourceEnd) -
440 map.byteToColumn(NewStart);
441 if (NewColumns <= TargetColumns) {
442 SourceStart = NewStart;
443 ExpandedRegion = true;
447 if (SourceEnd<SourceLine.size()) {
448 unsigned NewEnd = map.startOfNextColumn(SourceEnd);
450 // Skip over any whitespace we see here; we're looking for
451 // another bit of interesting text.
452 // FIXME: Detect non-ASCII whitespace characters too.
453 while (NewEnd < SourceLine.size() &&
454 isspace(static_cast<unsigned char>(SourceLine[NewEnd])))
455 NewEnd = map.startOfNextColumn(NewEnd);
457 // Skip over this bit of "interesting" text.
458 while (NewEnd < SourceLine.size() &&
459 !isspace(static_cast<unsigned char>(SourceLine[NewEnd])))
460 NewEnd = map.startOfNextColumn(NewEnd);
462 assert(map.byteToColumn(NewEnd) != -1);
463 unsigned NewColumns = map.byteToColumn(NewEnd) -
464 map.byteToColumn(SourceStart);
465 if (NewColumns <= TargetColumns) {
467 ExpandedRegion = true;
475 CaretStart = map.byteToColumn(SourceStart);
476 CaretEnd = map.byteToColumn(SourceEnd) + CaretColumnsOutsideSource;
478 // [CaretStart, CaretEnd) is the slice we want. Update the various
479 // output lines to show only this slice, with two-space padding
480 // before the lines so that it looks nicer.
482 assert(CaretStart!=(unsigned)-1 && CaretEnd!=(unsigned)-1 &&
483 SourceStart!=(unsigned)-1 && SourceEnd!=(unsigned)-1);
484 assert(SourceStart <= SourceEnd);
485 assert(CaretStart <= CaretEnd);
487 unsigned BackColumnsRemoved
488 = map.byteToColumn(SourceLine.size())-map.byteToColumn(SourceEnd);
489 unsigned FrontColumnsRemoved = CaretStart;
490 unsigned ColumnsKept = CaretEnd-CaretStart;
492 // We checked up front that the line needed truncation
493 assert(FrontColumnsRemoved+ColumnsKept+BackColumnsRemoved > Columns);
495 // The line needs some trunctiona, and we'd prefer to keep the front
496 // if possible, so remove the back
497 if (BackColumnsRemoved > strlen(back_ellipse))
498 SourceLine.replace(SourceEnd, std::string::npos, back_ellipse);
500 // If that's enough then we're done
501 if (FrontColumnsRemoved+ColumnsKept <= Columns)
504 // Otherwise remove the front as well
505 if (FrontColumnsRemoved > strlen(front_ellipse)) {
506 SourceLine.replace(0, SourceStart, front_ellipse);
507 CaretLine.replace(0, CaretStart, front_space);
508 if (!FixItInsertionLine.empty())
509 FixItInsertionLine.replace(0, CaretStart, front_space);
513 /// \brief Skip over whitespace in the string, starting at the given
516 /// \returns The index of the first non-whitespace character that is
517 /// greater than or equal to Idx or, if no such character exists,
518 /// returns the end of the string.
519 static unsigned skipWhitespace(unsigned Idx, StringRef Str, unsigned Length) {
520 while (Idx < Length && isspace(Str[Idx]))
525 /// \brief If the given character is the start of some kind of
526 /// balanced punctuation (e.g., quotes or parentheses), return the
527 /// character that will terminate the punctuation.
529 /// \returns The ending punctuation character, if any, or the NULL
530 /// character if the input character does not start any punctuation.
531 static inline char findMatchingPunctuation(char c) {
533 case '\'': return '\'';
534 case '`': return '\'';
535 case '"': return '"';
536 case '(': return ')';
537 case '[': return ']';
538 case '{': return '}';
545 /// \brief Find the end of the word starting at the given offset
548 /// \returns the index pointing one character past the end of the
550 static unsigned findEndOfWord(unsigned Start, StringRef Str,
551 unsigned Length, unsigned Column,
553 assert(Start < Str.size() && "Invalid start position!");
554 unsigned End = Start + 1;
556 // If we are already at the end of the string, take that as the word.
557 if (End == Str.size())
560 // Determine if the start of the string is actually opening
561 // punctuation, e.g., a quote or parentheses.
562 char EndPunct = findMatchingPunctuation(Str[Start]);
564 // This is a normal word. Just find the first space character.
565 while (End < Length && !isspace(Str[End]))
570 // We have the start of a balanced punctuation sequence (quotes,
571 // parentheses, etc.). Determine the full sequence is.
572 SmallString<16> PunctuationEndStack;
573 PunctuationEndStack.push_back(EndPunct);
574 while (End < Length && !PunctuationEndStack.empty()) {
575 if (Str[End] == PunctuationEndStack.back())
576 PunctuationEndStack.pop_back();
577 else if (char SubEndPunct = findMatchingPunctuation(Str[End]))
578 PunctuationEndStack.push_back(SubEndPunct);
583 // Find the first space character after the punctuation ended.
584 while (End < Length && !isspace(Str[End]))
587 unsigned PunctWordLength = End - Start;
588 if (// If the word fits on this line
589 Column + PunctWordLength <= Columns ||
590 // ... or the word is "short enough" to take up the next line
591 // without too much ugly white space
592 PunctWordLength < Columns/3)
593 return End; // Take the whole thing as a single "word".
595 // The whole quoted/parenthesized string is too long to print as a
596 // single "word". Instead, find the "word" that starts just after
597 // the punctuation and use that end-point instead. This will recurse
598 // until it finds something small enough to consider a word.
599 return findEndOfWord(Start + 1, Str, Length, Column + 1, Columns);
602 /// \brief Print the given string to a stream, word-wrapping it to
603 /// some number of columns in the process.
605 /// \param OS the stream to which the word-wrapping string will be
607 /// \param Str the string to word-wrap and output.
608 /// \param Columns the number of columns to word-wrap to.
609 /// \param Column the column number at which the first character of \p
610 /// Str will be printed. This will be non-zero when part of the first
611 /// line has already been printed.
612 /// \param Bold if the current text should be bold
613 /// \param Indentation the number of spaces to indent any lines beyond
615 /// \returns true if word-wrapping was required, or false if the
616 /// string fit on the first line.
617 static bool printWordWrapped(raw_ostream &OS, StringRef Str,
621 unsigned Indentation = WordWrapIndentation) {
622 const unsigned Length = std::min(Str.find('\n'), Str.size());
623 bool TextNormal = true;
625 // The string used to indent each line.
626 SmallString<16> IndentStr;
627 IndentStr.assign(Indentation, ' ');
628 bool Wrapped = false;
629 for (unsigned WordStart = 0, WordEnd; WordStart < Length;
630 WordStart = WordEnd) {
631 // Find the beginning of the next word.
632 WordStart = skipWhitespace(WordStart, Str, Length);
633 if (WordStart == Length)
636 // Find the end of this word.
637 WordEnd = findEndOfWord(WordStart, Str, Length, Column, Columns);
639 // Does this word fit on the current line?
640 unsigned WordLength = WordEnd - WordStart;
641 if (Column + WordLength < Columns) {
642 // This word fits on the current line; print it there.
647 applyTemplateHighlighting(OS, Str.substr(WordStart, WordLength),
649 Column += WordLength;
653 // This word does not fit on the current line, so wrap to the next
656 OS.write(&IndentStr[0], Indentation);
657 applyTemplateHighlighting(OS, Str.substr(WordStart, WordLength),
659 Column = Indentation + WordLength;
663 // Append any remaning text from the message with its existing formatting.
664 applyTemplateHighlighting(OS, Str.substr(Length), TextNormal, Bold);
666 assert(TextNormal && "Text highlighted at end of diagnostic message.");
671 TextDiagnostic::TextDiagnostic(raw_ostream &OS,
672 const LangOptions &LangOpts,
673 DiagnosticOptions *DiagOpts)
674 : DiagnosticRenderer(LangOpts, DiagOpts), OS(OS) {}
676 TextDiagnostic::~TextDiagnostic() {}
679 TextDiagnostic::emitDiagnosticMessage(SourceLocation Loc,
681 DiagnosticsEngine::Level Level,
683 ArrayRef<clang::CharSourceRange> Ranges,
684 const SourceManager *SM,
685 DiagOrStoredDiag D) {
686 uint64_t StartOfLocationInfo = OS.tell();
688 // Emit the location of this particular diagnostic.
690 emitDiagnosticLoc(Loc, PLoc, Level, Ranges, *SM);
692 if (DiagOpts->ShowColors)
695 printDiagnosticLevel(OS, Level, DiagOpts->ShowColors);
696 printDiagnosticMessage(OS, Level, Message,
697 OS.tell() - StartOfLocationInfo,
698 DiagOpts->MessageLength, DiagOpts->ShowColors);
702 TextDiagnostic::printDiagnosticLevel(raw_ostream &OS,
703 DiagnosticsEngine::Level Level,
706 // Print diagnostic category in bold and color
708 case DiagnosticsEngine::Ignored:
709 llvm_unreachable("Invalid diagnostic type");
710 case DiagnosticsEngine::Note: OS.changeColor(noteColor, 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::Warning: OS << "warning: "; break;
722 case DiagnosticsEngine::Error: OS << "error: "; break;
723 case DiagnosticsEngine::Fatal: OS << "fatal error: "; break;
731 TextDiagnostic::printDiagnosticMessage(raw_ostream &OS,
732 DiagnosticsEngine::Level Level,
734 unsigned CurrentColumn, unsigned Columns,
738 // Print warnings, errors and fatal errors in bold, no color
740 case DiagnosticsEngine::Warning:
741 case DiagnosticsEngine::Error:
742 case DiagnosticsEngine::Fatal:
743 OS.changeColor(savedColor, true);
746 default: break; //don't bold notes
751 printWordWrapped(OS, Message, Columns, CurrentColumn, Bold);
754 applyTemplateHighlighting(OS, Message, Normal, Bold);
755 assert(Normal && "Formatting should have returned to normal");
763 /// \brief Print out the file/line/column information and include trace.
765 /// This method handlen the emission of the diagnostic location information.
766 /// This includes extracting as much location information as is present for
767 /// the diagnostic and printing it, as well as any include stack or source
768 /// ranges necessary.
769 void TextDiagnostic::emitDiagnosticLoc(SourceLocation Loc, PresumedLoc PLoc,
770 DiagnosticsEngine::Level Level,
771 ArrayRef<CharSourceRange> Ranges,
772 const SourceManager &SM) {
773 if (PLoc.isInvalid()) {
774 // At least print the file name if available:
775 FileID FID = SM.getFileID(Loc);
776 if (!FID.isInvalid()) {
777 const FileEntry* FE = SM.getFileEntryForID(FID);
778 if (FE && FE->getName()) {
780 if (FE->getDevice() == 0 && FE->getInode() == 0
781 && FE->getFileMode() == 0) {
782 // in PCH is a guess, but a good one:
790 unsigned LineNo = PLoc.getLine();
792 if (!DiagOpts->ShowLocation)
795 if (DiagOpts->ShowColors)
796 OS.changeColor(savedColor, true);
798 OS << PLoc.getFilename();
799 switch (DiagOpts->getFormat()) {
800 case DiagnosticOptions::Clang: OS << ':' << LineNo; break;
801 case DiagnosticOptions::Msvc: OS << '(' << LineNo; break;
802 case DiagnosticOptions::Vi: OS << " +" << LineNo; break;
805 if (DiagOpts->ShowColumn)
806 // Compute the column number.
807 if (unsigned ColNo = PLoc.getColumn()) {
808 if (DiagOpts->getFormat() == DiagnosticOptions::Msvc) {
815 switch (DiagOpts->getFormat()) {
816 case DiagnosticOptions::Clang:
817 case DiagnosticOptions::Vi: OS << ':'; break;
818 case DiagnosticOptions::Msvc: OS << ") : "; break;
821 if (DiagOpts->ShowSourceRanges && !Ranges.empty()) {
823 SM.getFileID(SM.getExpansionLoc(Loc));
824 bool PrintedRange = false;
826 for (ArrayRef<CharSourceRange>::const_iterator RI = Ranges.begin(),
829 // Ignore invalid ranges.
830 if (!RI->isValid()) continue;
832 SourceLocation B = SM.getExpansionLoc(RI->getBegin());
833 SourceLocation E = SM.getExpansionLoc(RI->getEnd());
835 // If the End location and the start location are the same and are a
836 // macro location, then the range was something that came from a
837 // macro expansion or _Pragma. If this is an object-like macro, the
838 // best we can do is to highlight the range. If this is a
839 // function-like macro, we'd also like to highlight the arguments.
840 if (B == E && RI->getEnd().isMacroID())
841 E = SM.getExpansionRange(RI->getEnd()).second;
843 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(B);
844 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E);
846 // If the start or end of the range is in another file, just discard
848 if (BInfo.first != CaretFileID || EInfo.first != CaretFileID)
851 // Add in the length of the token, so that we cover multi-char
853 unsigned TokSize = 0;
854 if (RI->isTokenRange())
855 TokSize = Lexer::MeasureTokenLength(E, SM, LangOpts);
857 OS << '{' << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
858 << SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
859 << SM.getLineNumber(EInfo.first, EInfo.second) << ':'
860 << (SM.getColumnNumber(EInfo.first, EInfo.second)+TokSize)
871 void TextDiagnostic::emitBasicNote(StringRef Message) {
872 // FIXME: Emit this as a real note diagnostic.
873 // FIXME: Format an actual diagnostic rather than a hard coded string.
874 OS << "note: " << Message << "\n";
877 void TextDiagnostic::emitIncludeLocation(SourceLocation Loc,
879 const SourceManager &SM) {
880 if (DiagOpts->ShowLocation)
881 OS << "In file included from " << PLoc.getFilename() << ':'
882 << PLoc.getLine() << ":\n";
884 OS << "In included file:\n";
887 /// \brief Emit a code snippet and caret line.
889 /// This routine emits a single line's code snippet and caret line..
891 /// \param Loc The location for the caret.
892 /// \param Ranges The underlined ranges for this code snippet.
893 /// \param Hints The FixIt hints active for this diagnostic.
894 void TextDiagnostic::emitSnippetAndCaret(
895 SourceLocation Loc, DiagnosticsEngine::Level Level,
896 SmallVectorImpl<CharSourceRange>& Ranges,
897 ArrayRef<FixItHint> Hints,
898 const SourceManager &SM) {
899 assert(!Loc.isInvalid() && "must have a valid source location here");
900 assert(Loc.isFileID() && "must have a file location here");
902 // If caret diagnostics are enabled and we have location, we want to
903 // emit the caret. However, we only do this if the location moved
904 // from the last diagnostic, if the last diagnostic was a note that
905 // was part of a different warning or error diagnostic, or if the
906 // diagnostic has ranges. We don't want to emit the same caret
907 // multiple times if one loc has multiple diagnostics.
908 if (!DiagOpts->ShowCarets)
910 if (Loc == LastLoc && Ranges.empty() && Hints.empty() &&
911 (LastLevel != DiagnosticsEngine::Note || Level == LastLevel))
914 // Decompose the location into a FID/Offset pair.
915 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
916 FileID FID = LocInfo.first;
917 unsigned FileOffset = LocInfo.second;
919 // Get information about the buffer it points into.
920 bool Invalid = false;
921 const char *BufStart = SM.getBufferData(FID, &Invalid).data();
925 unsigned LineNo = SM.getLineNumber(FID, FileOffset);
926 unsigned ColNo = SM.getColumnNumber(FID, FileOffset);
928 // Rewind from the current position to the start of the line.
929 const char *TokPtr = BufStart+FileOffset;
930 const char *LineStart = TokPtr-ColNo+1; // Column # is 1-based.
933 // Compute the line end. Scan forward from the error position to the end of
935 const char *LineEnd = TokPtr;
936 while (*LineEnd != '\n' && *LineEnd != '\r' && *LineEnd != '\0')
939 // Copy the line of code into an std::string for ease of manipulation.
940 std::string SourceLine(LineStart, LineEnd);
942 // Create a line for the caret that is filled with spaces that is the same
943 // length as the line of source code.
944 std::string CaretLine(LineEnd-LineStart, ' ');
946 const SourceColumnMap sourceColMap(SourceLine, DiagOpts->TabStop);
948 // Highlight all of the characters covered by Ranges with ~ characters.
949 for (SmallVectorImpl<CharSourceRange>::iterator I = Ranges.begin(),
952 highlightRange(*I, LineNo, FID, sourceColMap, CaretLine, SM);
954 // Next, insert the caret itself.
955 ColNo = sourceColMap.byteToContainingColumn(ColNo-1);
956 if (CaretLine.size()<ColNo+1)
957 CaretLine.resize(ColNo+1, ' ');
958 CaretLine[ColNo] = '^';
960 std::string FixItInsertionLine = buildFixItInsertionLine(LineNo,
964 // If the source line is too long for our terminal, select only the
965 // "interesting" source region within that line.
966 unsigned Columns = DiagOpts->MessageLength;
968 selectInterestingSourceRegion(SourceLine, CaretLine, FixItInsertionLine,
969 Columns, sourceColMap);
971 // If we are in -fdiagnostics-print-source-range-info mode, we are trying
972 // to produce easily machine parsable output. Add a space before the
973 // source line and the caret to make it trivial to tell the main diagnostic
974 // line from what the user is intended to see.
975 if (DiagOpts->ShowSourceRanges) {
976 SourceLine = ' ' + SourceLine;
977 CaretLine = ' ' + CaretLine;
980 // Finally, remove any blank spaces from the end of CaretLine.
981 while (CaretLine[CaretLine.size()-1] == ' ')
982 CaretLine.erase(CaretLine.end()-1);
984 // Emit what we have computed.
985 emitSnippet(SourceLine);
987 if (DiagOpts->ShowColors)
988 OS.changeColor(caretColor, true);
989 OS << CaretLine << '\n';
990 if (DiagOpts->ShowColors)
993 if (!FixItInsertionLine.empty()) {
994 if (DiagOpts->ShowColors)
995 // Print fixit line in color
996 OS.changeColor(fixitColor, false);
997 if (DiagOpts->ShowSourceRanges)
999 OS << FixItInsertionLine << '\n';
1000 if (DiagOpts->ShowColors)
1004 // Print out any parseable fixit information requested by the options.
1005 emitParseableFixits(Hints, SM);
1008 void TextDiagnostic::emitSnippet(StringRef line) {
1014 std::string to_print;
1015 bool print_reversed = false;
1017 while (i<line.size()) {
1018 std::pair<SmallString<16>,bool> res
1019 = printableTextForNextCharacter(line, &i, DiagOpts->TabStop);
1020 bool was_printable = res.second;
1022 if (DiagOpts->ShowColors && was_printable == print_reversed) {
1027 if (DiagOpts->ShowColors)
1031 print_reversed = !was_printable;
1032 to_print += res.first.str();
1035 if (print_reversed && DiagOpts->ShowColors)
1038 if (print_reversed && DiagOpts->ShowColors)
1044 /// \brief Highlight a SourceRange (with ~'s) for any characters on LineNo.
1045 void TextDiagnostic::highlightRange(const CharSourceRange &R,
1046 unsigned LineNo, FileID FID,
1047 const SourceColumnMap &map,
1048 std::string &CaretLine,
1049 const SourceManager &SM) {
1050 if (!R.isValid()) return;
1052 SourceLocation Begin = R.getBegin();
1053 SourceLocation End = R.getEnd();
1055 unsigned StartLineNo = SM.getExpansionLineNumber(Begin);
1056 if (StartLineNo > LineNo || SM.getFileID(Begin) != FID)
1057 return; // No intersection.
1059 unsigned EndLineNo = SM.getExpansionLineNumber(End);
1060 if (EndLineNo < LineNo || SM.getFileID(End) != FID)
1061 return; // No intersection.
1063 // Compute the column number of the start.
1064 unsigned StartColNo = 0;
1065 if (StartLineNo == LineNo) {
1066 StartColNo = SM.getExpansionColumnNumber(Begin);
1067 if (StartColNo) --StartColNo; // Zero base the col #.
1070 // Compute the column number of the end.
1071 unsigned EndColNo = map.getSourceLine().size();
1072 if (EndLineNo == LineNo) {
1073 EndColNo = SM.getExpansionColumnNumber(End);
1075 --EndColNo; // Zero base the col #.
1077 // Add in the length of the token, so that we cover multi-char tokens if
1078 // this is a token range.
1079 if (R.isTokenRange())
1080 EndColNo += Lexer::MeasureTokenLength(End, SM, LangOpts);
1082 EndColNo = CaretLine.size();
1086 assert(StartColNo <= EndColNo && "Invalid range!");
1088 // Check that a token range does not highlight only whitespace.
1089 if (R.isTokenRange()) {
1090 // Pick the first non-whitespace column.
1091 while (StartColNo < map.getSourceLine().size() &&
1092 (map.getSourceLine()[StartColNo] == ' ' ||
1093 map.getSourceLine()[StartColNo] == '\t'))
1094 StartColNo = map.startOfNextColumn(StartColNo);
1096 // Pick the last non-whitespace column.
1097 if (EndColNo > map.getSourceLine().size())
1098 EndColNo = map.getSourceLine().size();
1099 while (EndColNo-1 &&
1100 (map.getSourceLine()[EndColNo-1] == ' ' ||
1101 map.getSourceLine()[EndColNo-1] == '\t'))
1102 EndColNo = map.startOfPreviousColumn(EndColNo);
1104 // If the start/end passed each other, then we are trying to highlight a
1105 // range that just exists in whitespace, which must be some sort of other
1107 assert(StartColNo <= EndColNo && "Trying to highlight whitespace??");
1110 assert(StartColNo <= map.getSourceLine().size() && "Invalid range!");
1111 assert(EndColNo <= map.getSourceLine().size() && "Invalid range!");
1113 // Fill the range with ~'s.
1114 StartColNo = map.byteToContainingColumn(StartColNo);
1115 EndColNo = map.byteToContainingColumn(EndColNo);
1117 assert(StartColNo <= EndColNo && "Invalid range!");
1118 if (CaretLine.size() < EndColNo)
1119 CaretLine.resize(EndColNo,' ');
1120 std::fill(CaretLine.begin()+StartColNo,CaretLine.begin()+EndColNo,'~');
1123 std::string TextDiagnostic::buildFixItInsertionLine(
1125 const SourceColumnMap &map,
1126 ArrayRef<FixItHint> Hints,
1127 const SourceManager &SM) {
1129 std::string FixItInsertionLine;
1130 if (Hints.empty() || !DiagOpts->ShowFixits)
1131 return FixItInsertionLine;
1132 unsigned PrevHintEndCol = 0;
1134 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1136 if (!I->CodeToInsert.empty()) {
1137 // We have an insertion hint. Determine whether the inserted
1138 // code contains no newlines and is on the same line as the caret.
1139 std::pair<FileID, unsigned> HintLocInfo
1140 = SM.getDecomposedExpansionLoc(I->RemoveRange.getBegin());
1141 if (LineNo == SM.getLineNumber(HintLocInfo.first, HintLocInfo.second) &&
1142 StringRef(I->CodeToInsert).find_first_of("\n\r") == StringRef::npos) {
1143 // Insert the new code into the line just below the code
1144 // that the user wrote.
1145 // Note: When modifying this function, be very careful about what is a
1146 // "column" (printed width, platform-dependent) and what is a
1147 // "byte offset" (SourceManager "column").
1148 unsigned HintByteOffset
1149 = SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second) - 1;
1151 // The hint must start inside the source or right at the end
1152 assert(HintByteOffset < static_cast<unsigned>(map.bytes())+1);
1153 unsigned HintCol = map.byteToContainingColumn(HintByteOffset);
1155 // If we inserted a long previous hint, push this one forwards, and add
1156 // an extra space to show that this is not part of the previous
1157 // completion. This is sort of the best we can do when two hints appear
1160 // Note that if this hint is located immediately after the previous
1161 // hint, no space will be added, since the location is more important.
1162 if (HintCol < PrevHintEndCol)
1163 HintCol = PrevHintEndCol + 1;
1165 // FIXME: This function handles multibyte characters in the source, but
1166 // not in the fixits. This assertion is intended to catch unintended
1167 // use of multibyte characters in fixits. If we decide to do this, we'll
1168 // have to track separate byte widths for the source and fixit lines.
1169 assert((size_t)llvm::sys::locale::columnWidth(I->CodeToInsert) ==
1170 I->CodeToInsert.size());
1172 // This relies on one byte per column in our fixit hints.
1173 // This should NOT use HintByteOffset, because the source might have
1174 // Unicode characters in earlier columns.
1175 unsigned LastColumnModified = HintCol + I->CodeToInsert.size();
1176 if (LastColumnModified > FixItInsertionLine.size())
1177 FixItInsertionLine.resize(LastColumnModified, ' ');
1179 std::copy(I->CodeToInsert.begin(), I->CodeToInsert.end(),
1180 FixItInsertionLine.begin() + HintCol);
1182 PrevHintEndCol = LastColumnModified;
1184 FixItInsertionLine.clear();
1190 expandTabs(FixItInsertionLine, DiagOpts->TabStop);
1192 return FixItInsertionLine;
1195 void TextDiagnostic::emitParseableFixits(ArrayRef<FixItHint> Hints,
1196 const SourceManager &SM) {
1197 if (!DiagOpts->ShowParseableFixits)
1200 // We follow FixItRewriter's example in not (yet) handling
1201 // fix-its in macros.
1202 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1204 if (I->RemoveRange.isInvalid() ||
1205 I->RemoveRange.getBegin().isMacroID() ||
1206 I->RemoveRange.getEnd().isMacroID())
1210 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1212 SourceLocation BLoc = I->RemoveRange.getBegin();
1213 SourceLocation ELoc = I->RemoveRange.getEnd();
1215 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(BLoc);
1216 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(ELoc);
1218 // Adjust for token ranges.
1219 if (I->RemoveRange.isTokenRange())
1220 EInfo.second += Lexer::MeasureTokenLength(ELoc, SM, LangOpts);
1222 // We specifically do not do word-wrapping or tab-expansion here,
1223 // because this is supposed to be easy to parse.
1224 PresumedLoc PLoc = SM.getPresumedLoc(BLoc);
1225 if (PLoc.isInvalid())
1229 OS.write_escaped(PLoc.getFilename());
1230 OS << "\":{" << SM.getLineNumber(BInfo.first, BInfo.second)
1231 << ':' << SM.getColumnNumber(BInfo.first, BInfo.second)
1232 << '-' << SM.getLineNumber(EInfo.first, EInfo.second)
1233 << ':' << SM.getColumnNumber(EInfo.first, EInfo.second)
1235 OS.write_escaped(I->CodeToInsert);