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/FileManager.h"
16 #include "clang/Basic/SourceManager.h"
17 #include "clang/Frontend/DiagnosticOptions.h"
18 #include "clang/Lex/Lexer.h"
19 #include "llvm/Support/MemoryBuffer.h"
20 #include "llvm/Support/raw_ostream.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include <algorithm>
24 using namespace clang;
25 
26 static const enum raw_ostream::Colors noteColor =
27   raw_ostream::BLACK;
28 static const enum raw_ostream::Colors fixitColor =
29   raw_ostream::GREEN;
30 static const enum raw_ostream::Colors caretColor =
31   raw_ostream::GREEN;
32 static const enum raw_ostream::Colors warningColor =
33   raw_ostream::MAGENTA;
34 static const enum raw_ostream::Colors errorColor = raw_ostream::RED;
35 static const enum raw_ostream::Colors fatalColor = raw_ostream::RED;
36 // Used for changing only the bold attribute.
37 static const enum raw_ostream::Colors savedColor =
38   raw_ostream::SAVEDCOLOR;
39 
40 /// \brief Number of spaces to indent when word-wrapping.
41 const unsigned WordWrapIndentation = 6;
42 
43 TextDiagnosticPrinter::TextDiagnosticPrinter(raw_ostream &os,
44                                              const DiagnosticOptions &diags,
45                                              bool _OwnsOutputStream)
46   : OS(os), LangOpts(0), DiagOpts(&diags),
47     LastCaretDiagnosticWasNote(0),
48     OwnsOutputStream(_OwnsOutputStream) {
49 }
50 
51 TextDiagnosticPrinter::~TextDiagnosticPrinter() {
52   if (OwnsOutputStream)
53     delete &OS;
54 }
55 
56 /// \brief Helper to recursivly walk up the include stack and print each layer
57 /// on the way back down.
58 static void PrintIncludeStackRecursively(raw_ostream &OS,
59                                          const SourceManager &SM,
60                                          SourceLocation Loc,
61                                          bool ShowLocation) {
62   if (Loc.isInvalid())
63     return;
64 
65   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
66   if (PLoc.isInvalid())
67     return;
68 
69   // Print out the other include frames first.
70   PrintIncludeStackRecursively(OS, SM, PLoc.getIncludeLoc(), ShowLocation);
71 
72   if (ShowLocation)
73     OS << "In file included from " << PLoc.getFilename()
74        << ':' << PLoc.getLine() << ":\n";
75   else
76     OS << "In included file:\n";
77 }
78 
79 /// \brief Prints an include stack when appropriate for a particular diagnostic
80 /// level and location.
81 ///
82 /// This routine handles all the logic of suppressing particular include stacks
83 /// (such as those for notes) and duplicate include stacks when repeated
84 /// warnings occur within the same file. It also handles the logic of
85 /// customizing the formatting and display of the include stack.
86 ///
87 /// \param Level The diagnostic level of the message this stack pertains to.
88 /// \param Loc   The include location of the current file (not the diagnostic
89 ///              location).
90 void TextDiagnosticPrinter::PrintIncludeStack(Diagnostic::Level Level,
91                                               SourceLocation Loc,
92                                               const SourceManager &SM) {
93   // Skip redundant include stacks altogether.
94   if (LastWarningLoc == Loc)
95     return;
96   LastWarningLoc = Loc;
97 
98   if (!DiagOpts->ShowNoteIncludeStack && Level == Diagnostic::Note)
99     return;
100 
101   PrintIncludeStackRecursively(OS, SM, Loc, DiagOpts->ShowLocation);
102 }
103 
104 /// \brief When the source code line we want to print is too long for
105 /// the terminal, select the "interesting" region.
106 static void SelectInterestingSourceRegion(std::string &SourceLine,
107                                           std::string &CaretLine,
108                                           std::string &FixItInsertionLine,
109                                           unsigned EndOfCaretToken,
110                                           unsigned Columns) {
111   unsigned MaxSize = std::max(SourceLine.size(),
112                               std::max(CaretLine.size(),
113                                        FixItInsertionLine.size()));
114   if (MaxSize > SourceLine.size())
115     SourceLine.resize(MaxSize, ' ');
116   if (MaxSize > CaretLine.size())
117     CaretLine.resize(MaxSize, ' ');
118   if (!FixItInsertionLine.empty() && MaxSize > FixItInsertionLine.size())
119     FixItInsertionLine.resize(MaxSize, ' ');
120 
121   // Find the slice that we need to display the full caret line
122   // correctly.
123   unsigned CaretStart = 0, CaretEnd = CaretLine.size();
124   for (; CaretStart != CaretEnd; ++CaretStart)
125     if (!isspace(CaretLine[CaretStart]))
126       break;
127 
128   for (; CaretEnd != CaretStart; --CaretEnd)
129     if (!isspace(CaretLine[CaretEnd - 1]))
130       break;
131 
132   // Make sure we don't chop the string shorter than the caret token
133   // itself.
134   if (CaretEnd < EndOfCaretToken)
135     CaretEnd = EndOfCaretToken;
136 
137   // If we have a fix-it line, make sure the slice includes all of the
138   // fix-it information.
139   if (!FixItInsertionLine.empty()) {
140     unsigned FixItStart = 0, FixItEnd = FixItInsertionLine.size();
141     for (; FixItStart != FixItEnd; ++FixItStart)
142       if (!isspace(FixItInsertionLine[FixItStart]))
143         break;
144 
145     for (; FixItEnd != FixItStart; --FixItEnd)
146       if (!isspace(FixItInsertionLine[FixItEnd - 1]))
147         break;
148 
149     if (FixItStart < CaretStart)
150       CaretStart = FixItStart;
151     if (FixItEnd > CaretEnd)
152       CaretEnd = FixItEnd;
153   }
154 
155   // CaretLine[CaretStart, CaretEnd) contains all of the interesting
156   // parts of the caret line. While this slice is smaller than the
157   // number of columns we have, try to grow the slice to encompass
158   // more context.
159 
160   // If the end of the interesting region comes before we run out of
161   // space in the terminal, start at the beginning of the line.
162   if (Columns > 3 && CaretEnd < Columns - 3)
163     CaretStart = 0;
164 
165   unsigned TargetColumns = Columns;
166   if (TargetColumns > 8)
167     TargetColumns -= 8; // Give us extra room for the ellipses.
168   unsigned SourceLength = SourceLine.size();
169   while ((CaretEnd - CaretStart) < TargetColumns) {
170     bool ExpandedRegion = false;
171     // Move the start of the interesting region left until we've
172     // pulled in something else interesting.
173     if (CaretStart == 1)
174       CaretStart = 0;
175     else if (CaretStart > 1) {
176       unsigned NewStart = CaretStart - 1;
177 
178       // Skip over any whitespace we see here; we're looking for
179       // another bit of interesting text.
180       while (NewStart && isspace(SourceLine[NewStart]))
181         --NewStart;
182 
183       // Skip over this bit of "interesting" text.
184       while (NewStart && !isspace(SourceLine[NewStart]))
185         --NewStart;
186 
187       // Move up to the non-whitespace character we just saw.
188       if (NewStart)
189         ++NewStart;
190 
191       // If we're still within our limit, update the starting
192       // position within the source/caret line.
193       if (CaretEnd - NewStart <= TargetColumns) {
194         CaretStart = NewStart;
195         ExpandedRegion = true;
196       }
197     }
198 
199     // Move the end of the interesting region right until we've
200     // pulled in something else interesting.
201     if (CaretEnd != SourceLength) {
202       assert(CaretEnd < SourceLength && "Unexpected caret position!");
203       unsigned NewEnd = CaretEnd;
204 
205       // Skip over any whitespace we see here; we're looking for
206       // another bit of interesting text.
207       while (NewEnd != SourceLength && isspace(SourceLine[NewEnd - 1]))
208         ++NewEnd;
209 
210       // Skip over this bit of "interesting" text.
211       while (NewEnd != SourceLength && !isspace(SourceLine[NewEnd - 1]))
212         ++NewEnd;
213 
214       if (NewEnd - CaretStart <= TargetColumns) {
215         CaretEnd = NewEnd;
216         ExpandedRegion = true;
217       }
218     }
219 
220     if (!ExpandedRegion)
221       break;
222   }
223 
224   // [CaretStart, CaretEnd) is the slice we want. Update the various
225   // output lines to show only this slice, with two-space padding
226   // before the lines so that it looks nicer.
227   if (CaretEnd < SourceLine.size())
228     SourceLine.replace(CaretEnd, std::string::npos, "...");
229   if (CaretEnd < CaretLine.size())
230     CaretLine.erase(CaretEnd, std::string::npos);
231   if (FixItInsertionLine.size() > CaretEnd)
232     FixItInsertionLine.erase(CaretEnd, std::string::npos);
233 
234   if (CaretStart > 2) {
235     SourceLine.replace(0, CaretStart, "  ...");
236     CaretLine.replace(0, CaretStart, "     ");
237     if (FixItInsertionLine.size() >= CaretStart)
238       FixItInsertionLine.replace(0, CaretStart, "     ");
239   }
240 }
241 
242 /// Look through spelling locations for a macro argument expansion, and
243 /// if found skip to it so that we can trace the argument rather than the macros
244 /// in which that argument is used. If no macro argument expansion is found,
245 /// don't skip anything and return the starting location.
246 static SourceLocation skipToMacroArgExpansion(const SourceManager &SM,
247                                                   SourceLocation StartLoc) {
248   for (SourceLocation L = StartLoc; L.isMacroID();
249        L = SM.getImmediateSpellingLoc(L)) {
250     if (SM.isMacroArgExpansion(L))
251       return L;
252   }
253 
254   // Otherwise just return initial location, there's nothing to skip.
255   return StartLoc;
256 }
257 
258 /// Gets the location of the immediate macro caller, one level up the stack
259 /// toward the initial macro typed into the source.
260 static SourceLocation getImmediateMacroCallerLoc(const SourceManager &SM,
261                                                  SourceLocation Loc) {
262   if (!Loc.isMacroID()) return Loc;
263 
264   // When we have the location of (part of) an expanded parameter, its spelling
265   // location points to the argument as typed into the macro call, and
266   // therefore is used to locate the macro caller.
267   if (SM.isMacroArgExpansion(Loc))
268     return SM.getImmediateSpellingLoc(Loc);
269 
270   // Otherwise, the caller of the macro is located where this macro is
271   // expanded (while the spelling is part of the macro definition).
272   return SM.getImmediateExpansionRange(Loc).first;
273 }
274 
275 /// Gets the location of the immediate macro callee, one level down the stack
276 /// toward the leaf macro.
277 static SourceLocation getImmediateMacroCalleeLoc(const SourceManager &SM,
278                                                  SourceLocation Loc) {
279   if (!Loc.isMacroID()) return Loc;
280 
281   // When we have the location of (part of) an expanded parameter, its
282   // expansion location points to the unexpanded paramater reference within
283   // the macro definition (or callee).
284   if (SM.isMacroArgExpansion(Loc))
285     return SM.getImmediateExpansionRange(Loc).first;
286 
287   // Otherwise, the callee of the macro is located where this location was
288   // spelled inside the macro definition.
289   return SM.getImmediateSpellingLoc(Loc);
290 }
291 
292 namespace {
293 
294 /// \brief Class to encapsulate the logic for printing a caret diagnostic
295 /// message.
296 ///
297 /// This class provides an interface for building and emitting a caret
298 /// diagnostic, including all of the macro backtrace caret diagnostics, FixIt
299 /// Hints, and code snippets. In the presence of macros this turns into
300 /// a recursive process and so the class provides common state across the
301 /// emission of a particular diagnostic, while each invocation of \see Emit()
302 /// walks down the macro stack.
303 ///
304 /// This logic assumes that the core diagnostic location and text has already
305 /// been emitted and focuses on emitting the pretty caret display and macro
306 /// backtrace following that.
307 ///
308 /// FIXME: Hoist helper routines specific to caret diagnostics into class
309 /// methods to reduce paramater passing churn.
310 class CaretDiagnostic {
311   TextDiagnosticPrinter &Printer;
312   raw_ostream &OS;
313   const SourceManager &SM;
314   const LangOptions &LangOpts;
315   const DiagnosticOptions &DiagOpts;
316   const unsigned Columns, MacroSkipStart, MacroSkipEnd;
317 
318 public:
319   CaretDiagnostic(TextDiagnosticPrinter &Printer,
320                   raw_ostream &OS,
321                   const SourceManager &SM,
322                   const LangOptions &LangOpts,
323                   const DiagnosticOptions &DiagOpts,
324                   unsigned Columns,
325                   unsigned MacroSkipStart,
326                   unsigned MacroSkipEnd)
327     : Printer(Printer), OS(OS), SM(SM), LangOpts(LangOpts), DiagOpts(DiagOpts),
328       Columns(Columns), MacroSkipStart(MacroSkipStart),
329       MacroSkipEnd(MacroSkipEnd) {
330   }
331 
332   /// \brief Emit the caret diagnostic text.
333   ///
334   /// Walks up the macro expansion stack printing the code snippet, caret,
335   /// underlines and FixItHint display as appropriate at each level. Walk is
336   /// accomplished by calling itself recursively.
337   ///
338   /// FIXME: Break up massive function into logical units.
339   ///
340   /// \param Loc The location for this caret.
341   /// \param Ranges The underlined ranges for this code snippet.
342   /// \param Hints The FixIt hints active for this diagnostic.
343   /// \param OnMacroInst The current depth of the macro expansion stack.
344   void Emit(SourceLocation Loc,
345             SmallVectorImpl<CharSourceRange>& Ranges,
346             ArrayRef<FixItHint> Hints,
347             unsigned OnMacroInst = 0) {
348     assert(!Loc.isInvalid() && "must have a valid source location here");
349 
350     // If this is a macro ID, first emit information about where this was
351     // expanded (recursively) then emit information about where the token was
352     // spelled from.
353     if (!Loc.isFileID()) {
354       // Whether to suppress printing this macro expansion.
355       bool Suppressed
356         = OnMacroInst >= MacroSkipStart && OnMacroInst < MacroSkipEnd;
357 
358       // When processing macros, skip over the expansions leading up to
359       // a macro argument, and trace the argument's expansion stack instead.
360       Loc = skipToMacroArgExpansion(SM, Loc);
361 
362       SourceLocation OneLevelUp = getImmediateMacroCallerLoc(SM, Loc);
363 
364       // FIXME: Map ranges?
365       Emit(OneLevelUp, Ranges, Hints, OnMacroInst + 1);
366 
367       // Map the location.
368       Loc = getImmediateMacroCalleeLoc(SM, Loc);
369 
370       // Map the ranges.
371       for (SmallVectorImpl<CharSourceRange>::iterator I = Ranges.begin(),
372                                                       E = Ranges.end();
373            I != E; ++I) {
374         SourceLocation Start = I->getBegin(), End = I->getEnd();
375         if (Start.isMacroID())
376           I->setBegin(getImmediateMacroCalleeLoc(SM, Start));
377         if (End.isMacroID())
378           I->setEnd(getImmediateMacroCalleeLoc(SM, End));
379       }
380 
381       if (!Suppressed) {
382         // Don't print recursive expansion notes from an expansion note.
383         Loc = SM.getSpellingLoc(Loc);
384 
385         // Get the pretty name, according to #line directives etc.
386         PresumedLoc PLoc = SM.getPresumedLoc(Loc);
387         if (PLoc.isInvalid())
388           return;
389 
390         // If this diagnostic is not in the main file, print out the
391         // "included from" lines.
392         Printer.PrintIncludeStack(Diagnostic::Note, PLoc.getIncludeLoc(), SM);
393 
394         if (DiagOpts.ShowLocation) {
395           // Emit the file/line/column that this expansion came from.
396           OS << PLoc.getFilename() << ':' << PLoc.getLine() << ':';
397           if (DiagOpts.ShowColumn)
398             OS << PLoc.getColumn() << ':';
399           OS << ' ';
400         }
401         OS << "note: expanded from:\n";
402 
403         Emit(Loc, Ranges, ArrayRef<FixItHint>(), OnMacroInst + 1);
404         return;
405       }
406 
407       if (OnMacroInst == MacroSkipStart) {
408         // Tell the user that we've skipped contexts.
409         OS << "note: (skipping " << (MacroSkipEnd - MacroSkipStart)
410         << " expansions in backtrace; use -fmacro-backtrace-limit=0 to see "
411         "all)\n";
412       }
413 
414       return;
415     }
416 
417     // Decompose the location into a FID/Offset pair.
418     std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
419     FileID FID = LocInfo.first;
420     unsigned FileOffset = LocInfo.second;
421 
422     // Get information about the buffer it points into.
423     bool Invalid = false;
424     const char *BufStart = SM.getBufferData(FID, &Invalid).data();
425     if (Invalid)
426       return;
427 
428     unsigned LineNo = SM.getLineNumber(FID, FileOffset);
429     unsigned ColNo = SM.getColumnNumber(FID, FileOffset);
430     unsigned CaretEndColNo
431       = ColNo + Lexer::MeasureTokenLength(Loc, SM, LangOpts);
432 
433     // Rewind from the current position to the start of the line.
434     const char *TokPtr = BufStart+FileOffset;
435     const char *LineStart = TokPtr-ColNo+1; // Column # is 1-based.
436 
437 
438     // Compute the line end.  Scan forward from the error position to the end of
439     // the line.
440     const char *LineEnd = TokPtr;
441     while (*LineEnd != '\n' && *LineEnd != '\r' && *LineEnd != '\0')
442       ++LineEnd;
443 
444     // FIXME: This shouldn't be necessary, but the CaretEndColNo can extend past
445     // the source line length as currently being computed. See
446     // test/Misc/message-length.c.
447     CaretEndColNo = std::min(CaretEndColNo, unsigned(LineEnd - LineStart));
448 
449     // Copy the line of code into an std::string for ease of manipulation.
450     std::string SourceLine(LineStart, LineEnd);
451 
452     // Create a line for the caret that is filled with spaces that is the same
453     // length as the line of source code.
454     std::string CaretLine(LineEnd-LineStart, ' ');
455 
456     // Highlight all of the characters covered by Ranges with ~ characters.
457     for (SmallVectorImpl<CharSourceRange>::iterator I = Ranges.begin(),
458                                                     E = Ranges.end();
459          I != E; ++I)
460       HighlightRange(*I, LineNo, FID, SourceLine, CaretLine);
461 
462     // Next, insert the caret itself.
463     if (ColNo-1 < CaretLine.size())
464       CaretLine[ColNo-1] = '^';
465     else
466       CaretLine.push_back('^');
467 
468     ExpandTabs(SourceLine, CaretLine);
469 
470     // If we are in -fdiagnostics-print-source-range-info mode, we are trying
471     // to produce easily machine parsable output.  Add a space before the
472     // source line and the caret to make it trivial to tell the main diagnostic
473     // line from what the user is intended to see.
474     if (DiagOpts.ShowSourceRanges) {
475       SourceLine = ' ' + SourceLine;
476       CaretLine = ' ' + CaretLine;
477     }
478 
479     std::string FixItInsertionLine = BuildFixItInsertionLine(LineNo,
480                                                              LineStart, LineEnd,
481                                                              Hints);
482 
483     // If the source line is too long for our terminal, select only the
484     // "interesting" source region within that line.
485     if (Columns && SourceLine.size() > Columns)
486       SelectInterestingSourceRegion(SourceLine, CaretLine, FixItInsertionLine,
487                                     CaretEndColNo, Columns);
488 
489     // Finally, remove any blank spaces from the end of CaretLine.
490     while (CaretLine[CaretLine.size()-1] == ' ')
491       CaretLine.erase(CaretLine.end()-1);
492 
493     // Emit what we have computed.
494     OS << SourceLine << '\n';
495 
496     if (DiagOpts.ShowColors)
497       OS.changeColor(caretColor, true);
498     OS << CaretLine << '\n';
499     if (DiagOpts.ShowColors)
500       OS.resetColor();
501 
502     if (!FixItInsertionLine.empty()) {
503       if (DiagOpts.ShowColors)
504         // Print fixit line in color
505         OS.changeColor(fixitColor, false);
506       if (DiagOpts.ShowSourceRanges)
507         OS << ' ';
508       OS << FixItInsertionLine << '\n';
509       if (DiagOpts.ShowColors)
510         OS.resetColor();
511     }
512 
513     // Print out any parseable fixit information requested by the options.
514     EmitParseableFixits(Hints);
515   }
516 
517 private:
518   /// \brief Highlight a SourceRange (with ~'s) for any characters on LineNo.
519   void HighlightRange(const CharSourceRange &R,
520                       unsigned LineNo, FileID FID,
521                       const std::string &SourceLine,
522                       std::string &CaretLine) {
523     assert(CaretLine.size() == SourceLine.size() &&
524            "Expect a correspondence between source and caret line!");
525     if (!R.isValid()) return;
526 
527     SourceLocation Begin = SM.getExpansionLoc(R.getBegin());
528     SourceLocation End = SM.getExpansionLoc(R.getEnd());
529 
530     // If the End location and the start location are the same and are a macro
531     // location, then the range was something that came from a macro expansion
532     // or _Pragma.  If this is an object-like macro, the best we can do is to
533     // highlight the range.  If this is a function-like macro, we'd also like to
534     // highlight the arguments.
535     if (Begin == End && R.getEnd().isMacroID())
536       End = SM.getExpansionRange(R.getEnd()).second;
537 
538     unsigned StartLineNo = SM.getExpansionLineNumber(Begin);
539     if (StartLineNo > LineNo || SM.getFileID(Begin) != FID)
540       return;  // No intersection.
541 
542     unsigned EndLineNo = SM.getExpansionLineNumber(End);
543     if (EndLineNo < LineNo || SM.getFileID(End) != FID)
544       return;  // No intersection.
545 
546     // Compute the column number of the start.
547     unsigned StartColNo = 0;
548     if (StartLineNo == LineNo) {
549       StartColNo = SM.getExpansionColumnNumber(Begin);
550       if (StartColNo) --StartColNo;  // Zero base the col #.
551     }
552 
553     // Compute the column number of the end.
554     unsigned EndColNo = CaretLine.size();
555     if (EndLineNo == LineNo) {
556       EndColNo = SM.getExpansionColumnNumber(End);
557       if (EndColNo) {
558         --EndColNo;  // Zero base the col #.
559 
560         // Add in the length of the token, so that we cover multi-char tokens if
561         // this is a token range.
562         if (R.isTokenRange())
563           EndColNo += Lexer::MeasureTokenLength(End, SM, LangOpts);
564       } else {
565         EndColNo = CaretLine.size();
566       }
567     }
568 
569     assert(StartColNo <= EndColNo && "Invalid range!");
570 
571     // Check that a token range does not highlight only whitespace.
572     if (R.isTokenRange()) {
573       // Pick the first non-whitespace column.
574       while (StartColNo < SourceLine.size() &&
575              (SourceLine[StartColNo] == ' ' || SourceLine[StartColNo] == '\t'))
576         ++StartColNo;
577 
578       // Pick the last non-whitespace column.
579       if (EndColNo > SourceLine.size())
580         EndColNo = SourceLine.size();
581       while (EndColNo-1 &&
582              (SourceLine[EndColNo-1] == ' ' || SourceLine[EndColNo-1] == '\t'))
583         --EndColNo;
584 
585       // If the start/end passed each other, then we are trying to highlight a
586       // range that just exists in whitespace, which must be some sort of other
587       // bug.
588       assert(StartColNo <= EndColNo && "Trying to highlight whitespace??");
589     }
590 
591     // Fill the range with ~'s.
592     for (unsigned i = StartColNo; i < EndColNo; ++i)
593       CaretLine[i] = '~';
594   }
595 
596   std::string BuildFixItInsertionLine(unsigned LineNo,
597                                       const char *LineStart,
598                                       const char *LineEnd,
599                                       ArrayRef<FixItHint> Hints) {
600     std::string FixItInsertionLine;
601     if (Hints.empty() || !DiagOpts.ShowFixits)
602       return FixItInsertionLine;
603 
604     for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
605          I != E; ++I) {
606       if (!I->CodeToInsert.empty()) {
607         // We have an insertion hint. Determine whether the inserted
608         // code is on the same line as the caret.
609         std::pair<FileID, unsigned> HintLocInfo
610           = SM.getDecomposedExpansionLoc(I->RemoveRange.getBegin());
611         if (LineNo == SM.getLineNumber(HintLocInfo.first, HintLocInfo.second)) {
612           // Insert the new code into the line just below the code
613           // that the user wrote.
614           unsigned HintColNo
615             = SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second);
616           unsigned LastColumnModified
617             = HintColNo - 1 + I->CodeToInsert.size();
618           if (LastColumnModified > FixItInsertionLine.size())
619             FixItInsertionLine.resize(LastColumnModified, ' ');
620           std::copy(I->CodeToInsert.begin(), I->CodeToInsert.end(),
621                     FixItInsertionLine.begin() + HintColNo - 1);
622         } else {
623           FixItInsertionLine.clear();
624           break;
625         }
626       }
627     }
628 
629     if (FixItInsertionLine.empty())
630       return FixItInsertionLine;
631 
632     // Now that we have the entire fixit line, expand the tabs in it.
633     // Since we don't want to insert spaces in the middle of a word,
634     // find each word and the column it should line up with and insert
635     // spaces until they match.
636     unsigned FixItPos = 0;
637     unsigned LinePos = 0;
638     unsigned TabExpandedCol = 0;
639     unsigned LineLength = LineEnd - LineStart;
640 
641     while (FixItPos < FixItInsertionLine.size() && LinePos < LineLength) {
642       // Find the next word in the FixIt line.
643       while (FixItPos < FixItInsertionLine.size() &&
644              FixItInsertionLine[FixItPos] == ' ')
645         ++FixItPos;
646       unsigned CharDistance = FixItPos - TabExpandedCol;
647 
648       // Walk forward in the source line, keeping track of
649       // the tab-expanded column.
650       for (unsigned I = 0; I < CharDistance; ++I, ++LinePos)
651         if (LinePos >= LineLength || LineStart[LinePos] != '\t')
652           ++TabExpandedCol;
653         else
654           TabExpandedCol =
655             (TabExpandedCol/DiagOpts.TabStop + 1) * DiagOpts.TabStop;
656 
657       // Adjust the fixit line to match this column.
658       FixItInsertionLine.insert(FixItPos, TabExpandedCol-FixItPos, ' ');
659       FixItPos = TabExpandedCol;
660 
661       // Walk to the end of the word.
662       while (FixItPos < FixItInsertionLine.size() &&
663              FixItInsertionLine[FixItPos] != ' ')
664         ++FixItPos;
665     }
666 
667     return FixItInsertionLine;
668   }
669 
670   void ExpandTabs(std::string &SourceLine, std::string &CaretLine) {
671     // Scan the source line, looking for tabs.  If we find any, manually expand
672     // them to spaces and update the CaretLine to match.
673     for (unsigned i = 0; i != SourceLine.size(); ++i) {
674       if (SourceLine[i] != '\t') continue;
675 
676       // Replace this tab with at least one space.
677       SourceLine[i] = ' ';
678 
679       // Compute the number of spaces we need to insert.
680       unsigned TabStop = DiagOpts.TabStop;
681       assert(0 < TabStop && TabStop <= DiagnosticOptions::MaxTabStop &&
682              "Invalid -ftabstop value");
683       unsigned NumSpaces = ((i+TabStop)/TabStop * TabStop) - (i+1);
684       assert(NumSpaces < TabStop && "Invalid computation of space amt");
685 
686       // Insert spaces into the SourceLine.
687       SourceLine.insert(i+1, NumSpaces, ' ');
688 
689       // Insert spaces or ~'s into CaretLine.
690       CaretLine.insert(i+1, NumSpaces, CaretLine[i] == '~' ? '~' : ' ');
691     }
692   }
693 
694   void EmitParseableFixits(ArrayRef<FixItHint> Hints) {
695     if (!DiagOpts.ShowParseableFixits)
696       return;
697 
698     // We follow FixItRewriter's example in not (yet) handling
699     // fix-its in macros.
700     for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
701          I != E; ++I) {
702       if (I->RemoveRange.isInvalid() ||
703           I->RemoveRange.getBegin().isMacroID() ||
704           I->RemoveRange.getEnd().isMacroID())
705         return;
706     }
707 
708     for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
709          I != E; ++I) {
710       SourceLocation BLoc = I->RemoveRange.getBegin();
711       SourceLocation ELoc = I->RemoveRange.getEnd();
712 
713       std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(BLoc);
714       std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(ELoc);
715 
716       // Adjust for token ranges.
717       if (I->RemoveRange.isTokenRange())
718         EInfo.second += Lexer::MeasureTokenLength(ELoc, SM, LangOpts);
719 
720       // We specifically do not do word-wrapping or tab-expansion here,
721       // because this is supposed to be easy to parse.
722       PresumedLoc PLoc = SM.getPresumedLoc(BLoc);
723       if (PLoc.isInvalid())
724         break;
725 
726       OS << "fix-it:\"";
727       OS.write_escaped(PLoc.getFilename());
728       OS << "\":{" << SM.getLineNumber(BInfo.first, BInfo.second)
729         << ':' << SM.getColumnNumber(BInfo.first, BInfo.second)
730         << '-' << SM.getLineNumber(EInfo.first, EInfo.second)
731         << ':' << SM.getColumnNumber(EInfo.first, EInfo.second)
732         << "}:\"";
733       OS.write_escaped(I->CodeToInsert);
734       OS << "\"\n";
735     }
736   }
737 };
738 
739 } // end namespace
740 
741 void TextDiagnosticPrinter::EmitCaretDiagnostic(
742     SourceLocation Loc,
743     SmallVectorImpl<CharSourceRange>& Ranges,
744     const SourceManager &SM,
745     ArrayRef<FixItHint> Hints,
746     unsigned Columns,
747     unsigned MacroSkipStart,
748     unsigned MacroSkipEnd) {
749   assert(LangOpts && "Unexpected diagnostic outside source file processing");
750   assert(DiagOpts && "Unexpected diagnostic without options set");
751   // FIXME: Remove this method and have clients directly build and call Emit on
752   // the CaretDiagnostic object.
753   CaretDiagnostic CaretDiag(*this, OS, SM, *LangOpts, *DiagOpts,
754                             Columns, MacroSkipStart, MacroSkipEnd);
755   CaretDiag.Emit(Loc, Ranges, Hints);
756 }
757 
758 /// \brief Skip over whitespace in the string, starting at the given
759 /// index.
760 ///
761 /// \returns The index of the first non-whitespace character that is
762 /// greater than or equal to Idx or, if no such character exists,
763 /// returns the end of the string.
764 static unsigned skipWhitespace(unsigned Idx,
765                                const SmallVectorImpl<char> &Str,
766                                unsigned Length) {
767   while (Idx < Length && isspace(Str[Idx]))
768     ++Idx;
769   return Idx;
770 }
771 
772 /// \brief If the given character is the start of some kind of
773 /// balanced punctuation (e.g., quotes or parentheses), return the
774 /// character that will terminate the punctuation.
775 ///
776 /// \returns The ending punctuation character, if any, or the NULL
777 /// character if the input character does not start any punctuation.
778 static inline char findMatchingPunctuation(char c) {
779   switch (c) {
780   case '\'': return '\'';
781   case '`': return '\'';
782   case '"':  return '"';
783   case '(':  return ')';
784   case '[': return ']';
785   case '{': return '}';
786   default: break;
787   }
788 
789   return 0;
790 }
791 
792 /// \brief Find the end of the word starting at the given offset
793 /// within a string.
794 ///
795 /// \returns the index pointing one character past the end of the
796 /// word.
797 static unsigned findEndOfWord(unsigned Start,
798                               const SmallVectorImpl<char> &Str,
799                               unsigned Length, unsigned Column,
800                               unsigned Columns) {
801   assert(Start < Str.size() && "Invalid start position!");
802   unsigned End = Start + 1;
803 
804   // If we are already at the end of the string, take that as the word.
805   if (End == Str.size())
806     return End;
807 
808   // Determine if the start of the string is actually opening
809   // punctuation, e.g., a quote or parentheses.
810   char EndPunct = findMatchingPunctuation(Str[Start]);
811   if (!EndPunct) {
812     // This is a normal word. Just find the first space character.
813     while (End < Length && !isspace(Str[End]))
814       ++End;
815     return End;
816   }
817 
818   // We have the start of a balanced punctuation sequence (quotes,
819   // parentheses, etc.). Determine the full sequence is.
820   llvm::SmallString<16> PunctuationEndStack;
821   PunctuationEndStack.push_back(EndPunct);
822   while (End < Length && !PunctuationEndStack.empty()) {
823     if (Str[End] == PunctuationEndStack.back())
824       PunctuationEndStack.pop_back();
825     else if (char SubEndPunct = findMatchingPunctuation(Str[End]))
826       PunctuationEndStack.push_back(SubEndPunct);
827 
828     ++End;
829   }
830 
831   // Find the first space character after the punctuation ended.
832   while (End < Length && !isspace(Str[End]))
833     ++End;
834 
835   unsigned PunctWordLength = End - Start;
836   if (// If the word fits on this line
837       Column + PunctWordLength <= Columns ||
838       // ... or the word is "short enough" to take up the next line
839       // without too much ugly white space
840       PunctWordLength < Columns/3)
841     return End; // Take the whole thing as a single "word".
842 
843   // The whole quoted/parenthesized string is too long to print as a
844   // single "word". Instead, find the "word" that starts just after
845   // the punctuation and use that end-point instead. This will recurse
846   // until it finds something small enough to consider a word.
847   return findEndOfWord(Start + 1, Str, Length, Column + 1, Columns);
848 }
849 
850 /// \brief Print the given string to a stream, word-wrapping it to
851 /// some number of columns in the process.
852 ///
853 /// \brief OS the stream to which the word-wrapping string will be
854 /// emitted.
855 ///
856 /// \brief Str the string to word-wrap and output.
857 ///
858 /// \brief Columns the number of columns to word-wrap to.
859 ///
860 /// \brief Column the column number at which the first character of \p
861 /// Str will be printed. This will be non-zero when part of the first
862 /// line has already been printed.
863 ///
864 /// \brief Indentation the number of spaces to indent any lines beyond
865 /// the first line.
866 ///
867 /// \returns true if word-wrapping was required, or false if the
868 /// string fit on the first line.
869 static bool PrintWordWrapped(raw_ostream &OS,
870                              const SmallVectorImpl<char> &Str,
871                              unsigned Columns,
872                              unsigned Column = 0,
873                              unsigned Indentation = WordWrapIndentation) {
874   unsigned Length = Str.size();
875 
876   // If there is a newline in this message somewhere, find that
877   // newline and split the message into the part before the newline
878   // (which will be word-wrapped) and the part from the newline one
879   // (which will be emitted unchanged).
880   for (unsigned I = 0; I != Length; ++I)
881     if (Str[I] == '\n') {
882       Length = I;
883       break;
884     }
885 
886   // The string used to indent each line.
887   llvm::SmallString<16> IndentStr;
888   IndentStr.assign(Indentation, ' ');
889   bool Wrapped = false;
890   for (unsigned WordStart = 0, WordEnd; WordStart < Length;
891        WordStart = WordEnd) {
892     // Find the beginning of the next word.
893     WordStart = skipWhitespace(WordStart, Str, Length);
894     if (WordStart == Length)
895       break;
896 
897     // Find the end of this word.
898     WordEnd = findEndOfWord(WordStart, Str, Length, Column, Columns);
899 
900     // Does this word fit on the current line?
901     unsigned WordLength = WordEnd - WordStart;
902     if (Column + WordLength < Columns) {
903       // This word fits on the current line; print it there.
904       if (WordStart) {
905         OS << ' ';
906         Column += 1;
907       }
908       OS.write(&Str[WordStart], WordLength);
909       Column += WordLength;
910       continue;
911     }
912 
913     // This word does not fit on the current line, so wrap to the next
914     // line.
915     OS << '\n';
916     OS.write(&IndentStr[0], Indentation);
917     OS.write(&Str[WordStart], WordLength);
918     Column = Indentation + WordLength;
919     Wrapped = true;
920   }
921 
922   if (Length == Str.size())
923     return Wrapped; // We're done.
924 
925   // There is a newline in the message, followed by something that
926   // will not be word-wrapped. Print that.
927   OS.write(&Str[Length], Str.size() - Length);
928   return true;
929 }
930 
931 /// Get the presumed location of a diagnostic message. This computes the
932 /// presumed location for the top of any macro backtrace when present.
933 static PresumedLoc getDiagnosticPresumedLoc(const SourceManager &SM,
934                                             SourceLocation Loc) {
935   // This is a condensed form of the algorithm used by EmitCaretDiagnostic to
936   // walk to the top of the macro call stack.
937   while (Loc.isMacroID()) {
938     Loc = skipToMacroArgExpansion(SM, Loc);
939     Loc = getImmediateMacroCallerLoc(SM, Loc);
940   }
941 
942   return SM.getPresumedLoc(Loc);
943 }
944 
945 /// \brief Print out the file/line/column information and include trace.
946 ///
947 /// This method handlen the emission of the diagnostic location information.
948 /// This includes extracting as much location information as is present for the
949 /// diagnostic and printing it, as well as any include stack or source ranges
950 /// necessary.
951 void TextDiagnosticPrinter::EmitDiagnosticLoc(Diagnostic::Level Level,
952                                               const DiagnosticInfo &Info,
953                                               const SourceManager &SM,
954                                               PresumedLoc PLoc) {
955   if (PLoc.isInvalid()) {
956     // At least print the file name if available:
957     FileID FID = SM.getFileID(Info.getLocation());
958     if (!FID.isInvalid()) {
959       const FileEntry* FE = SM.getFileEntryForID(FID);
960       if (FE && FE->getName()) {
961         OS << FE->getName();
962         if (FE->getDevice() == 0 && FE->getInode() == 0
963             && FE->getFileMode() == 0) {
964           // in PCH is a guess, but a good one:
965           OS << " (in PCH)";
966         }
967         OS << ": ";
968       }
969     }
970     return;
971   }
972   unsigned LineNo = PLoc.getLine();
973 
974   if (!DiagOpts->ShowLocation)
975     return;
976 
977   if (DiagOpts->ShowColors)
978     OS.changeColor(savedColor, true);
979 
980   OS << PLoc.getFilename();
981   switch (DiagOpts->Format) {
982   case DiagnosticOptions::Clang: OS << ':'  << LineNo; break;
983   case DiagnosticOptions::Msvc:  OS << '('  << LineNo; break;
984   case DiagnosticOptions::Vi:    OS << " +" << LineNo; break;
985   }
986 
987   if (DiagOpts->ShowColumn)
988     // Compute the column number.
989     if (unsigned ColNo = PLoc.getColumn()) {
990       if (DiagOpts->Format == DiagnosticOptions::Msvc) {
991         OS << ',';
992         ColNo--;
993       } else
994         OS << ':';
995       OS << ColNo;
996     }
997   switch (DiagOpts->Format) {
998   case DiagnosticOptions::Clang:
999   case DiagnosticOptions::Vi:    OS << ':';    break;
1000   case DiagnosticOptions::Msvc:  OS << ") : "; break;
1001   }
1002 
1003   if (DiagOpts->ShowSourceRanges && Info.getNumRanges()) {
1004     FileID CaretFileID =
1005       SM.getFileID(SM.getExpansionLoc(Info.getLocation()));
1006     bool PrintedRange = false;
1007 
1008     for (unsigned i = 0, e = Info.getNumRanges(); i != e; ++i) {
1009       // Ignore invalid ranges.
1010       if (!Info.getRange(i).isValid()) continue;
1011 
1012       SourceLocation B = Info.getRange(i).getBegin();
1013       SourceLocation E = Info.getRange(i).getEnd();
1014       B = SM.getExpansionLoc(B);
1015       E = SM.getExpansionLoc(E);
1016 
1017       // If the End location and the start location are the same and are a
1018       // macro location, then the range was something that came from a
1019       // macro expansion or _Pragma.  If this is an object-like macro, the
1020       // best we can do is to highlight the range.  If this is a
1021       // function-like macro, we'd also like to highlight the arguments.
1022       if (B == E && Info.getRange(i).getEnd().isMacroID())
1023         E = SM.getExpansionRange(Info.getRange(i).getEnd()).second;
1024 
1025       std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(B);
1026       std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E);
1027 
1028       // If the start or end of the range is in another file, just discard
1029       // it.
1030       if (BInfo.first != CaretFileID || EInfo.first != CaretFileID)
1031         continue;
1032 
1033       // Add in the length of the token, so that we cover multi-char
1034       // tokens.
1035       unsigned TokSize = 0;
1036       if (Info.getRange(i).isTokenRange())
1037         TokSize = Lexer::MeasureTokenLength(E, SM, *LangOpts);
1038 
1039       OS << '{' << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
1040         << SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
1041         << SM.getLineNumber(EInfo.first, EInfo.second) << ':'
1042         << (SM.getColumnNumber(EInfo.first, EInfo.second)+TokSize)
1043         << '}';
1044       PrintedRange = true;
1045     }
1046 
1047     if (PrintedRange)
1048       OS << ':';
1049   }
1050   OS << ' ';
1051 }
1052 
1053 void TextDiagnosticPrinter::HandleDiagnostic(Diagnostic::Level Level,
1054                                              const DiagnosticInfo &Info) {
1055   // Default implementation (Warnings/errors count).
1056   DiagnosticClient::HandleDiagnostic(Level, Info);
1057 
1058   // Keeps track of the the starting position of the location
1059   // information (e.g., "foo.c:10:4:") that precedes the error
1060   // message. We use this information to determine how long the
1061   // file+line+column number prefix is.
1062   uint64_t StartOfLocationInfo = OS.tell();
1063 
1064   if (!Prefix.empty())
1065     OS << Prefix << ": ";
1066 
1067   if (Info.getLocation().isValid()) {
1068     const SourceManager &SM = Info.getSourceManager();
1069     PresumedLoc PLoc = getDiagnosticPresumedLoc(SM, Info.getLocation());
1070 
1071     // First, if this diagnostic is not in the main file, print out the
1072     // "included from" lines.
1073     PrintIncludeStack(Level, PLoc.getIncludeLoc(), SM);
1074     StartOfLocationInfo = OS.tell();
1075 
1076     // Next emit the location of this particular diagnostic.
1077     EmitDiagnosticLoc(Level, Info, SM, PLoc);
1078 
1079     if (DiagOpts->ShowColors)
1080       OS.resetColor();
1081   }
1082 
1083   if (DiagOpts->ShowColors) {
1084     // Print diagnostic category in bold and color
1085     switch (Level) {
1086     case Diagnostic::Ignored: assert(0 && "Invalid diagnostic type");
1087     case Diagnostic::Note:    OS.changeColor(noteColor, true); break;
1088     case Diagnostic::Warning: OS.changeColor(warningColor, true); break;
1089     case Diagnostic::Error:   OS.changeColor(errorColor, true); break;
1090     case Diagnostic::Fatal:   OS.changeColor(fatalColor, true); break;
1091     }
1092   }
1093 
1094   switch (Level) {
1095   case Diagnostic::Ignored: assert(0 && "Invalid diagnostic type");
1096   case Diagnostic::Note:    OS << "note: "; break;
1097   case Diagnostic::Warning: OS << "warning: "; break;
1098   case Diagnostic::Error:   OS << "error: "; break;
1099   case Diagnostic::Fatal:   OS << "fatal error: "; break;
1100   }
1101 
1102   if (DiagOpts->ShowColors)
1103     OS.resetColor();
1104 
1105   llvm::SmallString<100> OutStr;
1106   Info.FormatDiagnostic(OutStr);
1107 
1108   if (DiagOpts->ShowNames &&
1109       !DiagnosticIDs::isBuiltinNote(Info.getID())) {
1110     OutStr += " [";
1111     OutStr += DiagnosticIDs::getName(Info.getID());
1112     OutStr += "]";
1113   }
1114 
1115   std::string OptionName;
1116   if (DiagOpts->ShowOptionNames) {
1117     // Was this a warning mapped to an error using -Werror or pragma?
1118     if (Level == Diagnostic::Error &&
1119         DiagnosticIDs::isBuiltinWarningOrExtension(Info.getID())) {
1120       diag::Mapping mapping = diag::MAP_IGNORE;
1121       Info.getDiags()->getDiagnosticLevel(Info.getID(), Info.getLocation(),
1122                                           &mapping);
1123       if (mapping == diag::MAP_WARNING)
1124         OptionName += "-Werror";
1125     }
1126 
1127     StringRef Opt = DiagnosticIDs::getWarningOptionForDiag(Info.getID());
1128     if (!Opt.empty()) {
1129       if (!OptionName.empty())
1130         OptionName += ',';
1131       OptionName += "-W";
1132       OptionName += Opt;
1133     } else if (Info.getID() == diag::fatal_too_many_errors) {
1134       OptionName = "-ferror-limit=";
1135     } else {
1136       // If the diagnostic is an extension diagnostic and not enabled by default
1137       // then it must have been turned on with -pedantic.
1138       bool EnabledByDefault;
1139       if (DiagnosticIDs::isBuiltinExtensionDiag(Info.getID(),
1140                                                 EnabledByDefault) &&
1141           !EnabledByDefault)
1142         OptionName = "-pedantic";
1143     }
1144   }
1145 
1146   // If the user wants to see category information, include it too.
1147   unsigned DiagCategory = 0;
1148   if (DiagOpts->ShowCategories)
1149     DiagCategory = DiagnosticIDs::getCategoryNumberForDiag(Info.getID());
1150 
1151   // If there is any categorization information, include it.
1152   if (!OptionName.empty() || DiagCategory != 0) {
1153     bool NeedsComma = false;
1154     OutStr += " [";
1155 
1156     if (!OptionName.empty()) {
1157       OutStr += OptionName;
1158       NeedsComma = true;
1159     }
1160 
1161     if (DiagCategory) {
1162       if (NeedsComma) OutStr += ',';
1163       if (DiagOpts->ShowCategories == 1)
1164         OutStr += llvm::utostr(DiagCategory);
1165       else {
1166         assert(DiagOpts->ShowCategories == 2 && "Invalid ShowCategories value");
1167         OutStr += DiagnosticIDs::getCategoryNameFromID(DiagCategory);
1168       }
1169     }
1170 
1171     OutStr += "]";
1172   }
1173 
1174 
1175   if (DiagOpts->ShowColors) {
1176     // Print warnings, errors and fatal errors in bold, no color
1177     switch (Level) {
1178     case Diagnostic::Warning: OS.changeColor(savedColor, true); break;
1179     case Diagnostic::Error:   OS.changeColor(savedColor, true); break;
1180     case Diagnostic::Fatal:   OS.changeColor(savedColor, true); break;
1181     default: break; //don't bold notes
1182     }
1183   }
1184 
1185   if (DiagOpts->MessageLength) {
1186     // We will be word-wrapping the error message, so compute the
1187     // column number where we currently are (after printing the
1188     // location information).
1189     unsigned Column = OS.tell() - StartOfLocationInfo;
1190     PrintWordWrapped(OS, OutStr, DiagOpts->MessageLength, Column);
1191   } else {
1192     OS.write(OutStr.begin(), OutStr.size());
1193   }
1194   OS << '\n';
1195   if (DiagOpts->ShowColors)
1196     OS.resetColor();
1197 
1198   // If caret diagnostics are enabled and we have location, we want to
1199   // emit the caret.  However, we only do this if the location moved
1200   // from the last diagnostic, if the last diagnostic was a note that
1201   // was part of a different warning or error diagnostic, or if the
1202   // diagnostic has ranges.  We don't want to emit the same caret
1203   // multiple times if one loc has multiple diagnostics.
1204   if (DiagOpts->ShowCarets && Info.getLocation().isValid() &&
1205       ((LastLoc != Info.getLocation()) || Info.getNumRanges() ||
1206        (LastCaretDiagnosticWasNote && Level != Diagnostic::Note) ||
1207        Info.getNumFixItHints())) {
1208     // Cache the LastLoc, it allows us to omit duplicate source/caret spewage.
1209     LastLoc = FullSourceLoc(Info.getLocation(), Info.getSourceManager());
1210     LastCaretDiagnosticWasNote = (Level == Diagnostic::Note);
1211 
1212     // Get the ranges into a local array we can hack on.
1213     SmallVector<CharSourceRange, 20> Ranges;
1214     Ranges.reserve(Info.getNumRanges());
1215     for (unsigned i = 0, e = Info.getNumRanges(); i != e; ++i)
1216       Ranges.push_back(Info.getRange(i));
1217 
1218     for (unsigned i = 0, e = Info.getNumFixItHints(); i != e; ++i) {
1219       const FixItHint &Hint = Info.getFixItHint(i);
1220       if (Hint.RemoveRange.isValid())
1221         Ranges.push_back(Hint.RemoveRange);
1222     }
1223 
1224     const SourceManager &SM = LastLoc.getManager();
1225     unsigned MacroInstSkipStart = 0, MacroInstSkipEnd = 0;
1226     if (DiagOpts && DiagOpts->MacroBacktraceLimit && !LastLoc.isFileID()) {
1227       // Compute the length of the macro-expansion backtrace, so that we
1228       // can establish which steps in the macro backtrace we'll skip.
1229       SourceLocation Loc = LastLoc;
1230       unsigned Depth = 0;
1231       do {
1232         ++Depth;
1233         Loc = skipToMacroArgExpansion(SM, Loc);
1234         Loc = getImmediateMacroCallerLoc(SM, Loc);
1235       } while (!Loc.isFileID());
1236 
1237       if (Depth > DiagOpts->MacroBacktraceLimit) {
1238         MacroInstSkipStart = DiagOpts->MacroBacktraceLimit / 2 +
1239                              DiagOpts->MacroBacktraceLimit % 2;
1240         MacroInstSkipEnd = Depth - DiagOpts->MacroBacktraceLimit / 2;
1241       }
1242     }
1243 
1244     EmitCaretDiagnostic(LastLoc, Ranges, LastLoc.getManager(),
1245                         llvm::makeArrayRef(Info.getFixItHints(),
1246                                            Info.getNumFixItHints()),
1247                         DiagOpts->MessageLength,
1248                         MacroInstSkipStart, MacroInstSkipEnd);
1249   }
1250 
1251   OS.flush();
1252 }
1253