1 //===--- TextDiagnosticPrinter.cpp - Diagnostic Printer -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This diagnostic client prints out their diagnostic messages.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Frontend/TextDiagnosticPrinter.h"
15 #include "clang/Basic/SourceManager.h"
16 #include "clang/Lex/Lexer.h"
17 #include "llvm/Support/MemoryBuffer.h"
18 #include "llvm/Support/raw_ostream.h"
19 #include "llvm/ADT/SmallString.h"
20 #include <algorithm>
21 using namespace clang;
22 
23 static const enum llvm::raw_ostream::Colors noteColor =
24   llvm::raw_ostream::BLACK;
25 static const enum llvm::raw_ostream::Colors fixitColor =
26   llvm::raw_ostream::GREEN;
27 static const enum llvm::raw_ostream::Colors caretColor =
28   llvm::raw_ostream::GREEN;
29 static const enum llvm::raw_ostream::Colors warningColor =
30   llvm::raw_ostream::MAGENTA;
31 static const enum llvm::raw_ostream::Colors errorColor = llvm::raw_ostream::RED;
32 static const enum llvm::raw_ostream::Colors fatalColor = llvm::raw_ostream::RED;
33 // used for changing only the bold attribute
34 static const enum llvm::raw_ostream::Colors savedColor =
35   llvm::raw_ostream::SAVEDCOLOR;
36 
37 /// \brief Number of spaces to indent when word-wrapping.
38 const unsigned WordWrapIndentation = 6;
39 
40 void TextDiagnosticPrinter::
41 PrintIncludeStack(SourceLocation Loc, const SourceManager &SM) {
42   if (Loc.isInvalid()) return;
43 
44   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
45 
46   // Print out the other include frames first.
47   PrintIncludeStack(PLoc.getIncludeLoc(), SM);
48 
49   if (ShowLocation)
50     OS << "In file included from " << PLoc.getFilename()
51        << ':' << PLoc.getLine() << ":\n";
52   else
53     OS << "In included file:\n";
54 }
55 
56 /// HighlightRange - Given a SourceRange and a line number, highlight (with ~'s)
57 /// any characters in LineNo that intersect the SourceRange.
58 void TextDiagnosticPrinter::HighlightRange(const SourceRange &R,
59                                            const SourceManager &SM,
60                                            unsigned LineNo, FileID FID,
61                                            std::string &CaretLine,
62                                            const std::string &SourceLine) {
63   assert(CaretLine.size() == SourceLine.size() &&
64          "Expect a correspondence between source and caret line!");
65   if (!R.isValid()) return;
66 
67   SourceLocation Begin = SM.getInstantiationLoc(R.getBegin());
68   SourceLocation End = SM.getInstantiationLoc(R.getEnd());
69 
70   // If the End location and the start location are the same and are a macro
71   // location, then the range was something that came from a macro expansion
72   // or _Pragma.  If this is an object-like macro, the best we can do is to
73   // highlight the range.  If this is a function-like macro, we'd also like to
74   // highlight the arguments.
75   if (Begin == End && R.getEnd().isMacroID())
76     End = SM.getInstantiationRange(R.getEnd()).second;
77 
78   unsigned StartLineNo = SM.getInstantiationLineNumber(Begin);
79   if (StartLineNo > LineNo || SM.getFileID(Begin) != FID)
80     return;  // No intersection.
81 
82   unsigned EndLineNo = SM.getInstantiationLineNumber(End);
83   if (EndLineNo < LineNo || SM.getFileID(End) != FID)
84     return;  // No intersection.
85 
86   // Compute the column number of the start.
87   unsigned StartColNo = 0;
88   if (StartLineNo == LineNo) {
89     StartColNo = SM.getInstantiationColumnNumber(Begin);
90     if (StartColNo) --StartColNo;  // Zero base the col #.
91   }
92 
93   // Pick the first non-whitespace column.
94   while (StartColNo < SourceLine.size() &&
95          (SourceLine[StartColNo] == ' ' || SourceLine[StartColNo] == '\t'))
96     ++StartColNo;
97 
98   // Compute the column number of the end.
99   unsigned EndColNo = CaretLine.size();
100   if (EndLineNo == LineNo) {
101     EndColNo = SM.getInstantiationColumnNumber(End);
102     if (EndColNo) {
103       --EndColNo;  // Zero base the col #.
104 
105       // Add in the length of the token, so that we cover multi-char tokens.
106       EndColNo += Lexer::MeasureTokenLength(End, SM, *LangOpts);
107     } else {
108       EndColNo = CaretLine.size();
109     }
110   }
111 
112   // Pick the last non-whitespace column.
113   if (EndColNo <= SourceLine.size())
114     while (EndColNo-1 &&
115            (SourceLine[EndColNo-1] == ' ' || SourceLine[EndColNo-1] == '\t'))
116       --EndColNo;
117   else
118     EndColNo = SourceLine.size();
119 
120   // Fill the range with ~'s.
121   assert(StartColNo <= EndColNo && "Invalid range!");
122   for (unsigned i = StartColNo; i < EndColNo; ++i)
123     CaretLine[i] = '~';
124 }
125 
126 /// \brief When the source code line we want to print is too long for
127 /// the terminal, select the "interesting" region.
128 static void SelectInterestingSourceRegion(std::string &SourceLine,
129                                           std::string &CaretLine,
130                                           std::string &FixItInsertionLine,
131                                           unsigned EndOfCaretToken,
132                                           unsigned Columns) {
133   if (CaretLine.size() > SourceLine.size())
134     SourceLine.resize(CaretLine.size(), ' ');
135 
136   // Find the slice that we need to display the full caret line
137   // correctly.
138   unsigned CaretStart = 0, CaretEnd = CaretLine.size();
139   for (; CaretStart != CaretEnd; ++CaretStart)
140     if (!isspace(CaretLine[CaretStart]))
141       break;
142 
143   for (; CaretEnd != CaretStart; --CaretEnd)
144     if (!isspace(CaretLine[CaretEnd - 1]))
145       break;
146 
147   // Make sure we don't chop the string shorter than the caret token
148   // itself.
149   if (CaretEnd < EndOfCaretToken)
150     CaretEnd = EndOfCaretToken;
151 
152   // If we have a fix-it line, make sure the slice includes all of the
153   // fix-it information.
154   if (!FixItInsertionLine.empty()) {
155     unsigned FixItStart = 0, FixItEnd = FixItInsertionLine.size();
156     for (; FixItStart != FixItEnd; ++FixItStart)
157       if (!isspace(FixItInsertionLine[FixItStart]))
158         break;
159 
160     for (; FixItEnd != FixItStart; --FixItEnd)
161       if (!isspace(FixItInsertionLine[FixItEnd - 1]))
162         break;
163 
164     if (FixItStart < CaretStart)
165       CaretStart = FixItStart;
166     if (FixItEnd > CaretEnd)
167       CaretEnd = FixItEnd;
168   }
169 
170   // CaretLine[CaretStart, CaretEnd) contains all of the interesting
171   // parts of the caret line. While this slice is smaller than the
172   // number of columns we have, try to grow the slice to encompass
173   // more context.
174 
175   // If the end of the interesting region comes before we run out of
176   // space in the terminal, start at the beginning of the line.
177   if (Columns > 3 && CaretEnd < Columns - 3)
178     CaretStart = 0;
179 
180   unsigned TargetColumns = Columns;
181   if (TargetColumns > 8)
182     TargetColumns -= 8; // Give us extra room for the ellipses.
183   unsigned SourceLength = SourceLine.size();
184   while ((CaretEnd - CaretStart) < TargetColumns) {
185     bool ExpandedRegion = false;
186     // Move the start of the interesting region left until we've
187     // pulled in something else interesting.
188     if (CaretStart == 1)
189       CaretStart = 0;
190     else if (CaretStart > 1) {
191       unsigned NewStart = CaretStart - 1;
192 
193       // Skip over any whitespace we see here; we're looking for
194       // another bit of interesting text.
195       while (NewStart && isspace(SourceLine[NewStart]))
196         --NewStart;
197 
198       // Skip over this bit of "interesting" text.
199       while (NewStart && !isspace(SourceLine[NewStart]))
200         --NewStart;
201 
202       // Move up to the non-whitespace character we just saw.
203       if (NewStart)
204         ++NewStart;
205 
206       // If we're still within our limit, update the starting
207       // position within the source/caret line.
208       if (CaretEnd - NewStart <= TargetColumns) {
209         CaretStart = NewStart;
210         ExpandedRegion = true;
211       }
212     }
213 
214     // Move the end of the interesting region right until we've
215     // pulled in something else interesting.
216     if (CaretEnd != SourceLength) {
217       unsigned NewEnd = CaretEnd;
218 
219       // Skip over any whitespace we see here; we're looking for
220       // another bit of interesting text.
221       while (NewEnd != SourceLength && isspace(SourceLine[NewEnd - 1]))
222         ++NewEnd;
223 
224       // Skip over this bit of "interesting" text.
225       while (NewEnd != SourceLength && !isspace(SourceLine[NewEnd - 1]))
226         ++NewEnd;
227 
228       if (NewEnd - CaretStart <= TargetColumns) {
229         CaretEnd = NewEnd;
230         ExpandedRegion = true;
231       }
232     }
233 
234     if (!ExpandedRegion)
235       break;
236   }
237 
238   // [CaretStart, CaretEnd) is the slice we want. Update the various
239   // output lines to show only this slice, with two-space padding
240   // before the lines so that it looks nicer.
241   if (CaretEnd < SourceLine.size())
242     SourceLine.replace(CaretEnd, std::string::npos, "...");
243   if (CaretEnd < CaretLine.size())
244     CaretLine.erase(CaretEnd, std::string::npos);
245   if (FixItInsertionLine.size() > CaretEnd)
246     FixItInsertionLine.erase(CaretEnd, std::string::npos);
247 
248   if (CaretStart > 2) {
249     SourceLine.replace(0, CaretStart, "  ...");
250     CaretLine.replace(0, CaretStart, "     ");
251     if (FixItInsertionLine.size() >= CaretStart)
252       FixItInsertionLine.replace(0, CaretStart, "     ");
253   }
254 }
255 
256 void TextDiagnosticPrinter::EmitCaretDiagnostic(SourceLocation Loc,
257                                                 SourceRange *Ranges,
258                                                 unsigned NumRanges,
259                                                 SourceManager &SM,
260                                           const CodeModificationHint *Hints,
261                                                 unsigned NumHints,
262                                                 unsigned Columns) {
263   assert(!Loc.isInvalid() && "must have a valid source location here");
264 
265   // If this is a macro ID, first emit information about where this was
266   // instantiated (recursively) then emit information about where. the token was
267   // spelled from.
268   if (!Loc.isFileID()) {
269     SourceLocation OneLevelUp = SM.getImmediateInstantiationRange(Loc).first;
270     // FIXME: Map ranges?
271     EmitCaretDiagnostic(OneLevelUp, Ranges, NumRanges, SM, 0, 0, Columns);
272 
273     Loc = SM.getImmediateSpellingLoc(Loc);
274 
275     // Map the ranges.
276     for (unsigned i = 0; i != NumRanges; ++i) {
277       SourceLocation S = Ranges[i].getBegin(), E = Ranges[i].getEnd();
278       if (S.isMacroID()) S = SM.getImmediateSpellingLoc(S);
279       if (E.isMacroID()) E = SM.getImmediateSpellingLoc(E);
280       Ranges[i] = SourceRange(S, E);
281     }
282 
283     if (ShowLocation) {
284       std::pair<FileID, unsigned> IInfo = SM.getDecomposedInstantiationLoc(Loc);
285 
286       // Emit the file/line/column that this expansion came from.
287       OS << SM.getBuffer(IInfo.first)->getBufferIdentifier() << ':'
288          << SM.getLineNumber(IInfo.first, IInfo.second) << ':';
289       if (ShowColumn)
290         OS << SM.getColumnNumber(IInfo.first, IInfo.second) << ':';
291       OS << ' ';
292     }
293     OS << "note: instantiated from:\n";
294 
295     EmitCaretDiagnostic(Loc, Ranges, NumRanges, SM, Hints, NumHints, Columns);
296     return;
297   }
298 
299   // Decompose the location into a FID/Offset pair.
300   std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
301   FileID FID = LocInfo.first;
302   unsigned FileOffset = LocInfo.second;
303 
304   // Get information about the buffer it points into.
305   std::pair<const char*, const char*> BufferInfo = SM.getBufferData(FID);
306   const char *BufStart = BufferInfo.first;
307 
308   unsigned ColNo = SM.getColumnNumber(FID, FileOffset);
309   unsigned CaretEndColNo
310     = ColNo + Lexer::MeasureTokenLength(Loc, SM, *LangOpts);
311 
312   // Rewind from the current position to the start of the line.
313   const char *TokPtr = BufStart+FileOffset;
314   const char *LineStart = TokPtr-ColNo+1; // Column # is 1-based.
315 
316 
317   // Compute the line end.  Scan forward from the error position to the end of
318   // the line.
319   const char *LineEnd = TokPtr;
320   while (*LineEnd != '\n' && *LineEnd != '\r' && *LineEnd != '\0')
321     ++LineEnd;
322 
323   // Copy the line of code into an std::string for ease of manipulation.
324   std::string SourceLine(LineStart, LineEnd);
325 
326   // Create a line for the caret that is filled with spaces that is the same
327   // length as the line of source code.
328   std::string CaretLine(LineEnd-LineStart, ' ');
329 
330   // Highlight all of the characters covered by Ranges with ~ characters.
331   if (NumRanges) {
332     unsigned LineNo = SM.getLineNumber(FID, FileOffset);
333 
334     for (unsigned i = 0, e = NumRanges; i != e; ++i)
335       HighlightRange(Ranges[i], SM, LineNo, FID, CaretLine, SourceLine);
336   }
337 
338   // Next, insert the caret itself.
339   if (ColNo-1 < CaretLine.size())
340     CaretLine[ColNo-1] = '^';
341   else
342     CaretLine.push_back('^');
343 
344   // Scan the source line, looking for tabs.  If we find any, manually expand
345   // them to 8 characters and update the CaretLine to match.
346   for (unsigned i = 0; i != SourceLine.size(); ++i) {
347     if (SourceLine[i] != '\t') continue;
348 
349     // Replace this tab with at least one space.
350     SourceLine[i] = ' ';
351 
352     // Compute the number of spaces we need to insert.
353     unsigned NumSpaces = ((i+8)&~7) - (i+1);
354     assert(NumSpaces < 8 && "Invalid computation of space amt");
355 
356     // Insert spaces into the SourceLine.
357     SourceLine.insert(i+1, NumSpaces, ' ');
358 
359     // Insert spaces or ~'s into CaretLine.
360     CaretLine.insert(i+1, NumSpaces, CaretLine[i] == '~' ? '~' : ' ');
361   }
362 
363   // If we are in -fdiagnostics-print-source-range-info mode, we are trying to
364   // produce easily machine parsable output.  Add a space before the source line
365   // and the caret to make it trivial to tell the main diagnostic line from what
366   // the user is intended to see.
367   if (PrintRangeInfo) {
368     SourceLine = ' ' + SourceLine;
369     CaretLine = ' ' + CaretLine;
370   }
371 
372   std::string FixItInsertionLine;
373   if (NumHints && PrintFixItInfo) {
374     for (const CodeModificationHint *Hint = Hints, *LastHint = Hints + NumHints;
375          Hint != LastHint; ++Hint) {
376       if (Hint->InsertionLoc.isValid()) {
377         // We have an insertion hint. Determine whether the inserted
378         // code is on the same line as the caret.
379         std::pair<FileID, unsigned> HintLocInfo
380           = SM.getDecomposedInstantiationLoc(Hint->InsertionLoc);
381         if (SM.getLineNumber(HintLocInfo.first, HintLocInfo.second) ==
382               SM.getLineNumber(FID, FileOffset)) {
383           // Insert the new code into the line just below the code
384           // that the user wrote.
385           unsigned HintColNo
386             = SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second);
387           unsigned LastColumnModified
388             = HintColNo - 1 + Hint->CodeToInsert.size();
389           if (LastColumnModified > FixItInsertionLine.size())
390             FixItInsertionLine.resize(LastColumnModified, ' ');
391           std::copy(Hint->CodeToInsert.begin(), Hint->CodeToInsert.end(),
392                     FixItInsertionLine.begin() + HintColNo - 1);
393         } else {
394           FixItInsertionLine.clear();
395           break;
396         }
397       }
398     }
399   }
400 
401   // If the source line is too long for our terminal, select only the
402   // "interesting" source region within that line.
403   if (Columns && SourceLine.size() > Columns)
404     SelectInterestingSourceRegion(SourceLine, CaretLine, FixItInsertionLine,
405                                   CaretEndColNo, Columns);
406 
407   // Finally, remove any blank spaces from the end of CaretLine.
408   while (CaretLine[CaretLine.size()-1] == ' ')
409     CaretLine.erase(CaretLine.end()-1);
410 
411   // Emit what we have computed.
412   OS << SourceLine << '\n';
413 
414   if (UseColors)
415     OS.changeColor(caretColor, true);
416   OS << CaretLine << '\n';
417   if (UseColors)
418     OS.resetColor();
419 
420   if (!FixItInsertionLine.empty()) {
421     if (UseColors)
422       // Print fixit line in color
423       OS.changeColor(fixitColor, false);
424     if (PrintRangeInfo)
425       OS << ' ';
426     OS << FixItInsertionLine << '\n';
427     if (UseColors)
428       OS.resetColor();
429   }
430 }
431 
432 /// \brief Skip over whitespace in the string, starting at the given
433 /// index.
434 ///
435 /// \returns The index of the first non-whitespace character that is
436 /// greater than or equal to Idx or, if no such character exists,
437 /// returns the end of the string.
438 static unsigned skipWhitespace(unsigned Idx,
439 			       const llvm::SmallVectorImpl<char> &Str,
440                                unsigned Length) {
441   while (Idx < Length && isspace(Str[Idx]))
442     ++Idx;
443   return Idx;
444 }
445 
446 /// \brief If the given character is the start of some kind of
447 /// balanced punctuation (e.g., quotes or parentheses), return the
448 /// character that will terminate the punctuation.
449 ///
450 /// \returns The ending punctuation character, if any, or the NULL
451 /// character if the input character does not start any punctuation.
452 static inline char findMatchingPunctuation(char c) {
453   switch (c) {
454   case '\'': return '\'';
455   case '`': return '\'';
456   case '"':  return '"';
457   case '(':  return ')';
458   case '[': return ']';
459   case '{': return '}';
460   default: break;
461   }
462 
463   return 0;
464 }
465 
466 /// \brief Find the end of the word starting at the given offset
467 /// within a string.
468 ///
469 /// \returns the index pointing one character past the end of the
470 /// word.
471 unsigned findEndOfWord(unsigned Start,
472                        const llvm::SmallVectorImpl<char> &Str,
473                        unsigned Length, unsigned Column,
474                        unsigned Columns) {
475   unsigned End = Start + 1;
476 
477   // Determine if the start of the string is actually opening
478   // punctuation, e.g., a quote or parentheses.
479   char EndPunct = findMatchingPunctuation(Str[Start]);
480   if (!EndPunct) {
481     // This is a normal word. Just find the first space character.
482     while (End < Length && !isspace(Str[End]))
483       ++End;
484     return End;
485   }
486 
487   // We have the start of a balanced punctuation sequence (quotes,
488   // parentheses, etc.). Determine the full sequence is.
489   llvm::SmallVector<char, 16> PunctuationEndStack;
490   PunctuationEndStack.push_back(EndPunct);
491   while (End < Length && !PunctuationEndStack.empty()) {
492     if (Str[End] == PunctuationEndStack.back())
493       PunctuationEndStack.pop_back();
494     else if (char SubEndPunct = findMatchingPunctuation(Str[End]))
495       PunctuationEndStack.push_back(SubEndPunct);
496 
497     ++End;
498   }
499 
500   // Find the first space character after the punctuation ended.
501   while (End < Length && !isspace(Str[End]))
502     ++End;
503 
504   unsigned PunctWordLength = End - Start;
505   if (// If the word fits on this line
506       Column + PunctWordLength <= Columns ||
507       // ... or the word is "short enough" to take up the next line
508       // without too much ugly white space
509       PunctWordLength < Columns/3)
510     return End; // Take the whole thing as a single "word".
511 
512   // The whole quoted/parenthesized string is too long to print as a
513   // single "word". Instead, find the "word" that starts just after
514   // the punctuation and use that end-point instead. This will recurse
515   // until it finds something small enough to consider a word.
516   return findEndOfWord(Start + 1, Str, Length, Column + 1, Columns);
517 }
518 
519 /// \brief Print the given string to a stream, word-wrapping it to
520 /// some number of columns in the process.
521 ///
522 /// \brief OS the stream to which the word-wrapping string will be
523 /// emitted.
524 ///
525 /// \brief Str the string to word-wrap and output.
526 ///
527 /// \brief Columns the number of columns to word-wrap to.
528 ///
529 /// \brief Column the column number at which the first character of \p
530 /// Str will be printed. This will be non-zero when part of the first
531 /// line has already been printed.
532 ///
533 /// \brief Indentation the number of spaces to indent any lines beyond
534 /// the first line.
535 ///
536 /// \returns true if word-wrapping was required, or false if the
537 /// string fit on the first line.
538 static bool PrintWordWrapped(llvm::raw_ostream &OS,
539 			     const llvm::SmallVectorImpl<char> &Str,
540                              unsigned Columns,
541                              unsigned Column = 0,
542                              unsigned Indentation = WordWrapIndentation) {
543   unsigned Length = Str.size();
544 
545   // If there is a newline in this message somewhere, find that
546   // newline and split the message into the part before the newline
547   // (which will be word-wrapped) and the part from the newline one
548   // (which will be emitted unchanged).
549   for (unsigned I = 0; I != Length; ++I)
550     if (Str[I] == '\n') {
551       Length = I;
552       break;
553     }
554 
555   // The string used to indent each line.
556   llvm::SmallString<16> IndentStr;
557   IndentStr.assign(Indentation, ' ');
558   bool Wrapped = false;
559   for (unsigned WordStart = 0, WordEnd; WordStart < Length;
560        WordStart = WordEnd) {
561     // Find the beginning of the next word.
562     WordStart = skipWhitespace(WordStart, Str, Length);
563     if (WordStart == Length)
564       break;
565 
566     // Find the end of this word.
567     WordEnd = findEndOfWord(WordStart, Str, Length, Column, Columns);
568 
569     // Does this word fit on the current line?
570     unsigned WordLength = WordEnd - WordStart;
571     if (Column + WordLength < Columns) {
572       // This word fits on the current line; print it there.
573       if (WordStart) {
574         OS << ' ';
575         Column += 1;
576       }
577       OS.write(&Str[WordStart], WordLength);
578       Column += WordLength;
579       continue;
580     }
581 
582     // This word does not fit on the current line, so wrap to the next
583     // line.
584     OS << '\n';
585     OS.write(&IndentStr[0], Indentation);
586     OS.write(&Str[WordStart], WordLength);
587     Column = Indentation + WordLength;
588     Wrapped = true;
589   }
590 
591   if (Length == Str.size())
592     return Wrapped; // We're done.
593 
594   // There is a newline in the message, followed by something that
595   // will not be word-wrapped. Print that.
596   OS.write(&Str[Length], Str.size() - Length);
597   return true;
598 }
599 
600 void TextDiagnosticPrinter::HandleDiagnostic(Diagnostic::Level Level,
601                                              const DiagnosticInfo &Info) {
602   // Keeps track of the the starting position of the location
603   // information (e.g., "foo.c:10:4:") that precedes the error
604   // message. We use this information to determine how long the
605   // file+line+column number prefix is.
606   uint64_t StartOfLocationInfo = OS.tell();
607 
608   // If the location is specified, print out a file/line/col and include trace
609   // if enabled.
610   if (Info.getLocation().isValid()) {
611     const SourceManager &SM = Info.getLocation().getManager();
612     PresumedLoc PLoc = SM.getPresumedLoc(Info.getLocation());
613     unsigned LineNo = PLoc.getLine();
614 
615     // First, if this diagnostic is not in the main file, print out the
616     // "included from" lines.
617     if (LastWarningLoc != PLoc.getIncludeLoc()) {
618       LastWarningLoc = PLoc.getIncludeLoc();
619       PrintIncludeStack(LastWarningLoc, SM);
620       StartOfLocationInfo = OS.tell();
621     }
622 
623     // Compute the column number.
624     if (ShowLocation) {
625       if (UseColors)
626         OS.changeColor(savedColor, true);
627       OS << PLoc.getFilename() << ':' << LineNo << ':';
628       if (ShowColumn)
629         if (unsigned ColNo = PLoc.getColumn())
630           OS << ColNo << ':';
631 
632       if (PrintRangeInfo && Info.getNumRanges()) {
633         FileID CaretFileID =
634           SM.getFileID(SM.getInstantiationLoc(Info.getLocation()));
635         bool PrintedRange = false;
636 
637         for (unsigned i = 0, e = Info.getNumRanges(); i != e; ++i) {
638           // Ignore invalid ranges.
639           if (!Info.getRange(i).isValid()) continue;
640 
641           SourceLocation B = Info.getRange(i).getBegin();
642           SourceLocation E = Info.getRange(i).getEnd();
643           std::pair<FileID, unsigned> BInfo=SM.getDecomposedInstantiationLoc(B);
644 
645           E = SM.getInstantiationLoc(E);
646           std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E);
647 
648           // If the start or end of the range is in another file, just discard
649           // it.
650           if (BInfo.first != CaretFileID || EInfo.first != CaretFileID)
651             continue;
652 
653           // Add in the length of the token, so that we cover multi-char tokens.
654           unsigned TokSize = Lexer::MeasureTokenLength(E, SM, *LangOpts);
655 
656           OS << '{' << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
657              << SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
658              << SM.getLineNumber(EInfo.first, EInfo.second) << ':'
659              << (SM.getColumnNumber(EInfo.first, EInfo.second)+TokSize) << '}';
660           PrintedRange = true;
661         }
662 
663         if (PrintedRange)
664           OS << ':';
665       }
666       OS << ' ';
667       if (UseColors)
668         OS.resetColor();
669     }
670   }
671 
672   if (UseColors) {
673     // Print diagnostic category in bold and color
674     switch (Level) {
675     case Diagnostic::Ignored: assert(0 && "Invalid diagnostic type");
676     case Diagnostic::Note:    OS.changeColor(noteColor, true); break;
677     case Diagnostic::Warning: OS.changeColor(warningColor, true); break;
678     case Diagnostic::Error:   OS.changeColor(errorColor, true); break;
679     case Diagnostic::Fatal:   OS.changeColor(fatalColor, true); break;
680     }
681   }
682 
683   switch (Level) {
684   case Diagnostic::Ignored: assert(0 && "Invalid diagnostic type");
685   case Diagnostic::Note:    OS << "note: "; break;
686   case Diagnostic::Warning: OS << "warning: "; break;
687   case Diagnostic::Error:   OS << "error: "; break;
688   case Diagnostic::Fatal:   OS << "fatal error: "; break;
689   }
690 
691   if (UseColors)
692     OS.resetColor();
693 
694   llvm::SmallString<100> OutStr;
695   Info.FormatDiagnostic(OutStr);
696 
697   if (PrintDiagnosticOption)
698     if (const char *Opt = Diagnostic::getWarningOptionForDiag(Info.getID())) {
699       OutStr += " [-W";
700       OutStr += Opt;
701       OutStr += ']';
702     }
703 
704   if (UseColors) {
705     // Print warnings, errors and fatal errors in bold, no color
706     switch (Level) {
707     case Diagnostic::Warning: OS.changeColor(savedColor, true); break;
708     case Diagnostic::Error:   OS.changeColor(savedColor, true); break;
709     case Diagnostic::Fatal:   OS.changeColor(savedColor, true); break;
710     default: break; //don't bold notes
711     }
712   }
713 
714   if (MessageLength) {
715     // We will be word-wrapping the error message, so compute the
716     // column number where we currently are (after printing the
717     // location information).
718     unsigned Column = OS.tell() - StartOfLocationInfo;
719     PrintWordWrapped(OS, OutStr, MessageLength, Column);
720   } else {
721     OS.write(OutStr.begin(), OutStr.size());
722   }
723   OS << '\n';
724   if (UseColors)
725     OS.resetColor();
726 
727   // If caret diagnostics are enabled and we have location, we want to
728   // emit the caret.  However, we only do this if the location moved
729   // from the last diagnostic, if the last diagnostic was a note that
730   // was part of a different warning or error diagnostic, or if the
731   // diagnostic has ranges.  We don't want to emit the same caret
732   // multiple times if one loc has multiple diagnostics.
733   if (CaretDiagnostics && Info.getLocation().isValid() &&
734       ((LastLoc != Info.getLocation()) || Info.getNumRanges() ||
735        (LastCaretDiagnosticWasNote && Level != Diagnostic::Note) ||
736        Info.getNumCodeModificationHints())) {
737     // Cache the LastLoc, it allows us to omit duplicate source/caret spewage.
738     LastLoc = Info.getLocation();
739     LastCaretDiagnosticWasNote = (Level == Diagnostic::Note);
740 
741     // Get the ranges into a local array we can hack on.
742     SourceRange Ranges[20];
743     unsigned NumRanges = Info.getNumRanges();
744     assert(NumRanges < 20 && "Out of space");
745     for (unsigned i = 0; i != NumRanges; ++i)
746       Ranges[i] = Info.getRange(i);
747 
748     unsigned NumHints = Info.getNumCodeModificationHints();
749     for (unsigned idx = 0; idx < NumHints; ++idx) {
750       const CodeModificationHint &Hint = Info.getCodeModificationHint(idx);
751       if (Hint.RemoveRange.isValid()) {
752         assert(NumRanges < 20 && "Out of space");
753         Ranges[NumRanges++] = Hint.RemoveRange;
754       }
755     }
756 
757     EmitCaretDiagnostic(LastLoc, Ranges, NumRanges, LastLoc.getManager(),
758                         Info.getCodeModificationHints(),
759                         Info.getNumCodeModificationHints(),
760                         MessageLength);
761   }
762 
763   OS.flush();
764 }
765