1 //===--- TextDiagnostic.cpp - Text Diagnostic Pretty-Printing -------------===//
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 #include "clang/Frontend/TextDiagnostic.h"
11 #include "clang/Basic/FileManager.h"
12 #include "clang/Basic/SourceManager.h"
13 #include "clang/Frontend/DiagnosticOptions.h"
14 #include "clang/Lex/Lexer.h"
15 #include "llvm/Support/MemoryBuffer.h"
16 #include "llvm/Support/raw_ostream.h"
17 #include "llvm/Support/ErrorHandling.h"
18 #include "llvm/ADT/SmallString.h"
19 #include <algorithm>
20 using namespace clang;
21 
22 static const enum raw_ostream::Colors noteColor =
23   raw_ostream::BLACK;
24 static const enum raw_ostream::Colors fixitColor =
25   raw_ostream::GREEN;
26 static const enum raw_ostream::Colors caretColor =
27   raw_ostream::GREEN;
28 static const enum raw_ostream::Colors warningColor =
29   raw_ostream::MAGENTA;
30 static const enum raw_ostream::Colors errorColor = raw_ostream::RED;
31 static const enum raw_ostream::Colors fatalColor = raw_ostream::RED;
32 // Used for changing only the bold attribute.
33 static const enum raw_ostream::Colors savedColor =
34   raw_ostream::SAVEDCOLOR;
35 
36 /// \brief Number of spaces to indent when word-wrapping.
37 const unsigned WordWrapIndentation = 6;
38 
39 /// \brief When the source code line we want to print is too long for
40 /// the terminal, select the "interesting" region.
41 static void selectInterestingSourceRegion(std::string &SourceLine,
42                                           std::string &CaretLine,
43                                           std::string &FixItInsertionLine,
44                                           unsigned EndOfCaretToken,
45                                           unsigned Columns) {
46   unsigned MaxSize = std::max(SourceLine.size(),
47                               std::max(CaretLine.size(),
48                                        FixItInsertionLine.size()));
49   if (MaxSize > SourceLine.size())
50     SourceLine.resize(MaxSize, ' ');
51   if (MaxSize > CaretLine.size())
52     CaretLine.resize(MaxSize, ' ');
53   if (!FixItInsertionLine.empty() && MaxSize > FixItInsertionLine.size())
54     FixItInsertionLine.resize(MaxSize, ' ');
55 
56   // Find the slice that we need to display the full caret line
57   // correctly.
58   unsigned CaretStart = 0, CaretEnd = CaretLine.size();
59   for (; CaretStart != CaretEnd; ++CaretStart)
60     if (!isspace(CaretLine[CaretStart]))
61       break;
62 
63   for (; CaretEnd != CaretStart; --CaretEnd)
64     if (!isspace(CaretLine[CaretEnd - 1]))
65       break;
66 
67   // Make sure we don't chop the string shorter than the caret token
68   // itself.
69   if (CaretEnd < EndOfCaretToken)
70     CaretEnd = EndOfCaretToken;
71 
72   // If we have a fix-it line, make sure the slice includes all of the
73   // fix-it information.
74   if (!FixItInsertionLine.empty()) {
75     unsigned FixItStart = 0, FixItEnd = FixItInsertionLine.size();
76     for (; FixItStart != FixItEnd; ++FixItStart)
77       if (!isspace(FixItInsertionLine[FixItStart]))
78         break;
79 
80     for (; FixItEnd != FixItStart; --FixItEnd)
81       if (!isspace(FixItInsertionLine[FixItEnd - 1]))
82         break;
83 
84     if (FixItStart < CaretStart)
85       CaretStart = FixItStart;
86     if (FixItEnd > CaretEnd)
87       CaretEnd = FixItEnd;
88   }
89 
90   // CaretLine[CaretStart, CaretEnd) contains all of the interesting
91   // parts of the caret line. While this slice is smaller than the
92   // number of columns we have, try to grow the slice to encompass
93   // more context.
94 
95   // If the end of the interesting region comes before we run out of
96   // space in the terminal, start at the beginning of the line.
97   if (Columns > 3 && CaretEnd < Columns - 3)
98     CaretStart = 0;
99 
100   unsigned TargetColumns = Columns;
101   if (TargetColumns > 8)
102     TargetColumns -= 8; // Give us extra room for the ellipses.
103   unsigned SourceLength = SourceLine.size();
104   while ((CaretEnd - CaretStart) < TargetColumns) {
105     bool ExpandedRegion = false;
106     // Move the start of the interesting region left until we've
107     // pulled in something else interesting.
108     if (CaretStart == 1)
109       CaretStart = 0;
110     else if (CaretStart > 1) {
111       unsigned NewStart = CaretStart - 1;
112 
113       // Skip over any whitespace we see here; we're looking for
114       // another bit of interesting text.
115       while (NewStart && isspace(SourceLine[NewStart]))
116         --NewStart;
117 
118       // Skip over this bit of "interesting" text.
119       while (NewStart && !isspace(SourceLine[NewStart]))
120         --NewStart;
121 
122       // Move up to the non-whitespace character we just saw.
123       if (NewStart)
124         ++NewStart;
125 
126       // If we're still within our limit, update the starting
127       // position within the source/caret line.
128       if (CaretEnd - NewStart <= TargetColumns) {
129         CaretStart = NewStart;
130         ExpandedRegion = true;
131       }
132     }
133 
134     // Move the end of the interesting region right until we've
135     // pulled in something else interesting.
136     if (CaretEnd != SourceLength) {
137       assert(CaretEnd < SourceLength && "Unexpected caret position!");
138       unsigned NewEnd = CaretEnd;
139 
140       // Skip over any whitespace we see here; we're looking for
141       // another bit of interesting text.
142       while (NewEnd != SourceLength && isspace(SourceLine[NewEnd - 1]))
143         ++NewEnd;
144 
145       // Skip over this bit of "interesting" text.
146       while (NewEnd != SourceLength && !isspace(SourceLine[NewEnd - 1]))
147         ++NewEnd;
148 
149       if (NewEnd - CaretStart <= TargetColumns) {
150         CaretEnd = NewEnd;
151         ExpandedRegion = true;
152       }
153     }
154 
155     if (!ExpandedRegion)
156       break;
157   }
158 
159   // [CaretStart, CaretEnd) is the slice we want. Update the various
160   // output lines to show only this slice, with two-space padding
161   // before the lines so that it looks nicer.
162   if (CaretEnd < SourceLine.size())
163     SourceLine.replace(CaretEnd, std::string::npos, "...");
164   if (CaretEnd < CaretLine.size())
165     CaretLine.erase(CaretEnd, std::string::npos);
166   if (FixItInsertionLine.size() > CaretEnd)
167     FixItInsertionLine.erase(CaretEnd, std::string::npos);
168 
169   if (CaretStart > 2) {
170     SourceLine.replace(0, CaretStart, "  ...");
171     CaretLine.replace(0, CaretStart, "     ");
172     if (FixItInsertionLine.size() >= CaretStart)
173       FixItInsertionLine.replace(0, CaretStart, "     ");
174   }
175 }
176 
177 /// \brief Skip over whitespace in the string, starting at the given
178 /// index.
179 ///
180 /// \returns The index of the first non-whitespace character that is
181 /// greater than or equal to Idx or, if no such character exists,
182 /// returns the end of the string.
183 static unsigned skipWhitespace(unsigned Idx, StringRef Str, unsigned Length) {
184   while (Idx < Length && isspace(Str[Idx]))
185     ++Idx;
186   return Idx;
187 }
188 
189 /// \brief If the given character is the start of some kind of
190 /// balanced punctuation (e.g., quotes or parentheses), return the
191 /// character that will terminate the punctuation.
192 ///
193 /// \returns The ending punctuation character, if any, or the NULL
194 /// character if the input character does not start any punctuation.
195 static inline char findMatchingPunctuation(char c) {
196   switch (c) {
197   case '\'': return '\'';
198   case '`': return '\'';
199   case '"':  return '"';
200   case '(':  return ')';
201   case '[': return ']';
202   case '{': return '}';
203   default: break;
204   }
205 
206   return 0;
207 }
208 
209 /// \brief Find the end of the word starting at the given offset
210 /// within a string.
211 ///
212 /// \returns the index pointing one character past the end of the
213 /// word.
214 static unsigned findEndOfWord(unsigned Start, StringRef Str,
215                               unsigned Length, unsigned Column,
216                               unsigned Columns) {
217   assert(Start < Str.size() && "Invalid start position!");
218   unsigned End = Start + 1;
219 
220   // If we are already at the end of the string, take that as the word.
221   if (End == Str.size())
222     return End;
223 
224   // Determine if the start of the string is actually opening
225   // punctuation, e.g., a quote or parentheses.
226   char EndPunct = findMatchingPunctuation(Str[Start]);
227   if (!EndPunct) {
228     // This is a normal word. Just find the first space character.
229     while (End < Length && !isspace(Str[End]))
230       ++End;
231     return End;
232   }
233 
234   // We have the start of a balanced punctuation sequence (quotes,
235   // parentheses, etc.). Determine the full sequence is.
236   llvm::SmallString<16> PunctuationEndStack;
237   PunctuationEndStack.push_back(EndPunct);
238   while (End < Length && !PunctuationEndStack.empty()) {
239     if (Str[End] == PunctuationEndStack.back())
240       PunctuationEndStack.pop_back();
241     else if (char SubEndPunct = findMatchingPunctuation(Str[End]))
242       PunctuationEndStack.push_back(SubEndPunct);
243 
244     ++End;
245   }
246 
247   // Find the first space character after the punctuation ended.
248   while (End < Length && !isspace(Str[End]))
249     ++End;
250 
251   unsigned PunctWordLength = End - Start;
252   if (// If the word fits on this line
253       Column + PunctWordLength <= Columns ||
254       // ... or the word is "short enough" to take up the next line
255       // without too much ugly white space
256       PunctWordLength < Columns/3)
257     return End; // Take the whole thing as a single "word".
258 
259   // The whole quoted/parenthesized string is too long to print as a
260   // single "word". Instead, find the "word" that starts just after
261   // the punctuation and use that end-point instead. This will recurse
262   // until it finds something small enough to consider a word.
263   return findEndOfWord(Start + 1, Str, Length, Column + 1, Columns);
264 }
265 
266 /// \brief Print the given string to a stream, word-wrapping it to
267 /// some number of columns in the process.
268 ///
269 /// \param OS the stream to which the word-wrapping string will be
270 /// emitted.
271 /// \param Str the string to word-wrap and output.
272 /// \param Columns the number of columns to word-wrap to.
273 /// \param Column the column number at which the first character of \p
274 /// Str will be printed. This will be non-zero when part of the first
275 /// line has already been printed.
276 /// \param Indentation the number of spaces to indent any lines beyond
277 /// the first line.
278 /// \returns true if word-wrapping was required, or false if the
279 /// string fit on the first line.
280 static bool printWordWrapped(raw_ostream &OS, StringRef Str,
281                              unsigned Columns,
282                              unsigned Column = 0,
283                              unsigned Indentation = WordWrapIndentation) {
284   const unsigned Length = std::min(Str.find('\n'), Str.size());
285 
286   // The string used to indent each line.
287   llvm::SmallString<16> IndentStr;
288   IndentStr.assign(Indentation, ' ');
289   bool Wrapped = false;
290   for (unsigned WordStart = 0, WordEnd; WordStart < Length;
291        WordStart = WordEnd) {
292     // Find the beginning of the next word.
293     WordStart = skipWhitespace(WordStart, Str, Length);
294     if (WordStart == Length)
295       break;
296 
297     // Find the end of this word.
298     WordEnd = findEndOfWord(WordStart, Str, Length, Column, Columns);
299 
300     // Does this word fit on the current line?
301     unsigned WordLength = WordEnd - WordStart;
302     if (Column + WordLength < Columns) {
303       // This word fits on the current line; print it there.
304       if (WordStart) {
305         OS << ' ';
306         Column += 1;
307       }
308       OS << Str.substr(WordStart, WordLength);
309       Column += WordLength;
310       continue;
311     }
312 
313     // This word does not fit on the current line, so wrap to the next
314     // line.
315     OS << '\n';
316     OS.write(&IndentStr[0], Indentation);
317     OS << Str.substr(WordStart, WordLength);
318     Column = Indentation + WordLength;
319     Wrapped = true;
320   }
321 
322   // Append any remaning text from the message with its existing formatting.
323   OS << Str.substr(Length);
324 
325   return Wrapped;
326 }
327 
328 TextDiagnostic::TextDiagnostic(raw_ostream &OS,
329                                const SourceManager &SM,
330                                const LangOptions &LangOpts,
331                                const DiagnosticOptions &DiagOpts)
332   : DiagnosticRenderer(SM, LangOpts, DiagOpts), OS(OS) {}
333 
334 TextDiagnostic::~TextDiagnostic() {}
335 
336 void
337 TextDiagnostic::emitDiagnosticMessage(SourceLocation Loc,
338                                       PresumedLoc PLoc,
339                                       DiagnosticsEngine::Level Level,
340                                       StringRef Message,
341                                       ArrayRef<clang::CharSourceRange> Ranges,
342                                       const Diagnostic *Info) {
343   uint64_t StartOfLocationInfo = OS.tell();
344 
345   // Emit the location of this particular diagnostic.
346   emitDiagnosticLoc(Loc, PLoc, Level, Ranges);
347 
348   if (DiagOpts.ShowColors)
349     OS.resetColor();
350 
351   printDiagnosticLevel(OS, Level, DiagOpts.ShowColors);
352   printDiagnosticMessage(OS, Level, Message,
353                          OS.tell() - StartOfLocationInfo,
354                          DiagOpts.MessageLength, DiagOpts.ShowColors);
355 }
356 
357 /*static*/ void
358 TextDiagnostic::printDiagnosticLevel(raw_ostream &OS,
359                                      DiagnosticsEngine::Level Level,
360                                      bool ShowColors) {
361   if (ShowColors) {
362     // Print diagnostic category in bold and color
363     switch (Level) {
364     case DiagnosticsEngine::Ignored:
365       llvm_unreachable("Invalid diagnostic type");
366     case DiagnosticsEngine::Note:    OS.changeColor(noteColor, true); break;
367     case DiagnosticsEngine::Warning: OS.changeColor(warningColor, true); break;
368     case DiagnosticsEngine::Error:   OS.changeColor(errorColor, true); break;
369     case DiagnosticsEngine::Fatal:   OS.changeColor(fatalColor, true); break;
370     }
371   }
372 
373   switch (Level) {
374   case DiagnosticsEngine::Ignored:
375     llvm_unreachable("Invalid diagnostic type");
376   case DiagnosticsEngine::Note:    OS << "note: "; break;
377   case DiagnosticsEngine::Warning: OS << "warning: "; break;
378   case DiagnosticsEngine::Error:   OS << "error: "; break;
379   case DiagnosticsEngine::Fatal:   OS << "fatal error: "; break;
380   }
381 
382   if (ShowColors)
383     OS.resetColor();
384 }
385 
386 /*static*/ void
387 TextDiagnostic::printDiagnosticMessage(raw_ostream &OS,
388                                        DiagnosticsEngine::Level Level,
389                                        StringRef Message,
390                                        unsigned CurrentColumn, unsigned Columns,
391                                        bool ShowColors) {
392   if (ShowColors) {
393     // Print warnings, errors and fatal errors in bold, no color
394     switch (Level) {
395     case DiagnosticsEngine::Warning: OS.changeColor(savedColor, true); break;
396     case DiagnosticsEngine::Error:   OS.changeColor(savedColor, true); break;
397     case DiagnosticsEngine::Fatal:   OS.changeColor(savedColor, true); break;
398     default: break; //don't bold notes
399     }
400   }
401 
402   if (Columns)
403     printWordWrapped(OS, Message, Columns, CurrentColumn);
404   else
405     OS << Message;
406 
407   if (ShowColors)
408     OS.resetColor();
409   OS << '\n';
410 }
411 
412 /// \brief Print out the file/line/column information and include trace.
413 ///
414 /// This method handlen the emission of the diagnostic location information.
415 /// This includes extracting as much location information as is present for
416 /// the diagnostic and printing it, as well as any include stack or source
417 /// ranges necessary.
418 void TextDiagnostic::emitDiagnosticLoc(SourceLocation Loc, PresumedLoc PLoc,
419                                        DiagnosticsEngine::Level Level,
420                                        ArrayRef<CharSourceRange> Ranges) {
421   if (PLoc.isInvalid()) {
422     // At least print the file name if available:
423     FileID FID = SM.getFileID(Loc);
424     if (!FID.isInvalid()) {
425       const FileEntry* FE = SM.getFileEntryForID(FID);
426       if (FE && FE->getName()) {
427         OS << FE->getName();
428         if (FE->getDevice() == 0 && FE->getInode() == 0
429             && FE->getFileMode() == 0) {
430           // in PCH is a guess, but a good one:
431           OS << " (in PCH)";
432         }
433         OS << ": ";
434       }
435     }
436     return;
437   }
438   unsigned LineNo = PLoc.getLine();
439 
440   if (!DiagOpts.ShowLocation)
441     return;
442 
443   if (DiagOpts.ShowColors)
444     OS.changeColor(savedColor, true);
445 
446   OS << PLoc.getFilename();
447   switch (DiagOpts.Format) {
448   case DiagnosticOptions::Clang: OS << ':'  << LineNo; break;
449   case DiagnosticOptions::Msvc:  OS << '('  << LineNo; break;
450   case DiagnosticOptions::Vi:    OS << " +" << LineNo; break;
451   }
452 
453   if (DiagOpts.ShowColumn)
454     // Compute the column number.
455     if (unsigned ColNo = PLoc.getColumn()) {
456       if (DiagOpts.Format == DiagnosticOptions::Msvc) {
457         OS << ',';
458         ColNo--;
459       } else
460         OS << ':';
461       OS << ColNo;
462     }
463   switch (DiagOpts.Format) {
464   case DiagnosticOptions::Clang:
465   case DiagnosticOptions::Vi:    OS << ':';    break;
466   case DiagnosticOptions::Msvc:  OS << ") : "; break;
467   }
468 
469   if (DiagOpts.ShowSourceRanges && !Ranges.empty()) {
470     FileID CaretFileID =
471       SM.getFileID(SM.getExpansionLoc(Loc));
472     bool PrintedRange = false;
473 
474     for (ArrayRef<CharSourceRange>::const_iterator RI = Ranges.begin(),
475          RE = Ranges.end();
476          RI != RE; ++RI) {
477       // Ignore invalid ranges.
478       if (!RI->isValid()) continue;
479 
480       SourceLocation B = SM.getExpansionLoc(RI->getBegin());
481       SourceLocation E = SM.getExpansionLoc(RI->getEnd());
482 
483       // If the End location and the start location are the same and are a
484       // macro location, then the range was something that came from a
485       // macro expansion or _Pragma.  If this is an object-like macro, the
486       // best we can do is to highlight the range.  If this is a
487       // function-like macro, we'd also like to highlight the arguments.
488       if (B == E && RI->getEnd().isMacroID())
489         E = SM.getExpansionRange(RI->getEnd()).second;
490 
491       std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(B);
492       std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E);
493 
494       // If the start or end of the range is in another file, just discard
495       // it.
496       if (BInfo.first != CaretFileID || EInfo.first != CaretFileID)
497         continue;
498 
499       // Add in the length of the token, so that we cover multi-char
500       // tokens.
501       unsigned TokSize = 0;
502       if (RI->isTokenRange())
503         TokSize = Lexer::MeasureTokenLength(E, SM, LangOpts);
504 
505       OS << '{' << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
506         << SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
507         << SM.getLineNumber(EInfo.first, EInfo.second) << ':'
508         << (SM.getColumnNumber(EInfo.first, EInfo.second)+TokSize)
509         << '}';
510       PrintedRange = true;
511     }
512 
513     if (PrintedRange)
514       OS << ':';
515   }
516   OS << ' ';
517 }
518 
519 void TextDiagnostic::emitBasicNote(StringRef Message) {
520   // FIXME: Emit this as a real note diagnostic.
521   // FIXME: Format an actual diagnostic rather than a hard coded string.
522   OS << "note: " << Message << "\n";
523 }
524 
525 void TextDiagnostic::emitIncludeLocation(SourceLocation Loc,
526                                          PresumedLoc PLoc) {
527   if (DiagOpts.ShowLocation)
528     OS << "In file included from " << PLoc.getFilename() << ':'
529        << PLoc.getLine() << ":\n";
530   else
531     OS << "In included file:\n";
532 }
533 
534 /// \brief Emit a code snippet and caret line.
535 ///
536 /// This routine emits a single line's code snippet and caret line..
537 ///
538 /// \param Loc The location for the caret.
539 /// \param Ranges The underlined ranges for this code snippet.
540 /// \param Hints The FixIt hints active for this diagnostic.
541 void TextDiagnostic::emitSnippetAndCaret(
542     SourceLocation Loc, DiagnosticsEngine::Level Level,
543     SmallVectorImpl<CharSourceRange>& Ranges,
544     ArrayRef<FixItHint> Hints) {
545   assert(!Loc.isInvalid() && "must have a valid source location here");
546   assert(Loc.isFileID() && "must have a file location here");
547 
548   // If caret diagnostics are enabled and we have location, we want to
549   // emit the caret.  However, we only do this if the location moved
550   // from the last diagnostic, if the last diagnostic was a note that
551   // was part of a different warning or error diagnostic, or if the
552   // diagnostic has ranges.  We don't want to emit the same caret
553   // multiple times if one loc has multiple diagnostics.
554   if (!DiagOpts.ShowCarets)
555     return;
556   if (Loc == LastLoc && Ranges.empty() && Hints.empty() &&
557       (LastLevel != DiagnosticsEngine::Note || Level == LastLevel))
558     return;
559 
560   // Decompose the location into a FID/Offset pair.
561   std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
562   FileID FID = LocInfo.first;
563   unsigned FileOffset = LocInfo.second;
564 
565   // Get information about the buffer it points into.
566   bool Invalid = false;
567   const char *BufStart = SM.getBufferData(FID, &Invalid).data();
568   if (Invalid)
569     return;
570 
571   unsigned LineNo = SM.getLineNumber(FID, FileOffset);
572   unsigned ColNo = SM.getColumnNumber(FID, FileOffset);
573   unsigned CaretEndColNo
574     = ColNo + Lexer::MeasureTokenLength(Loc, SM, LangOpts);
575 
576   // Rewind from the current position to the start of the line.
577   const char *TokPtr = BufStart+FileOffset;
578   const char *LineStart = TokPtr-ColNo+1; // Column # is 1-based.
579 
580 
581   // Compute the line end.  Scan forward from the error position to the end of
582   // the line.
583   const char *LineEnd = TokPtr;
584   while (*LineEnd != '\n' && *LineEnd != '\r' && *LineEnd != '\0')
585     ++LineEnd;
586 
587   // FIXME: This shouldn't be necessary, but the CaretEndColNo can extend past
588   // the source line length as currently being computed. See
589   // test/Misc/message-length.c.
590   CaretEndColNo = std::min(CaretEndColNo, unsigned(LineEnd - LineStart));
591 
592   // Copy the line of code into an std::string for ease of manipulation.
593   std::string SourceLine(LineStart, LineEnd);
594 
595   // Create a line for the caret that is filled with spaces that is the same
596   // length as the line of source code.
597   std::string CaretLine(LineEnd-LineStart, ' ');
598 
599   // Highlight all of the characters covered by Ranges with ~ characters.
600   for (SmallVectorImpl<CharSourceRange>::iterator I = Ranges.begin(),
601                                                   E = Ranges.end();
602        I != E; ++I)
603     highlightRange(*I, LineNo, FID, SourceLine, CaretLine);
604 
605   // Next, insert the caret itself.
606   if (ColNo-1 < CaretLine.size())
607     CaretLine[ColNo-1] = '^';
608   else
609     CaretLine.push_back('^');
610 
611   expandTabs(SourceLine, CaretLine);
612 
613   // If we are in -fdiagnostics-print-source-range-info mode, we are trying
614   // to produce easily machine parsable output.  Add a space before the
615   // source line and the caret to make it trivial to tell the main diagnostic
616   // line from what the user is intended to see.
617   if (DiagOpts.ShowSourceRanges) {
618     SourceLine = ' ' + SourceLine;
619     CaretLine = ' ' + CaretLine;
620   }
621 
622   std::string FixItInsertionLine = buildFixItInsertionLine(LineNo,
623                                                            LineStart, LineEnd,
624                                                            Hints);
625 
626   // If the source line is too long for our terminal, select only the
627   // "interesting" source region within that line.
628   unsigned Columns = DiagOpts.MessageLength;
629   if (Columns && SourceLine.size() > Columns)
630     selectInterestingSourceRegion(SourceLine, CaretLine, FixItInsertionLine,
631                                   CaretEndColNo, Columns);
632 
633   // Finally, remove any blank spaces from the end of CaretLine.
634   while (CaretLine[CaretLine.size()-1] == ' ')
635     CaretLine.erase(CaretLine.end()-1);
636 
637   // Emit what we have computed.
638   OS << SourceLine << '\n';
639 
640   if (DiagOpts.ShowColors)
641     OS.changeColor(caretColor, true);
642   OS << CaretLine << '\n';
643   if (DiagOpts.ShowColors)
644     OS.resetColor();
645 
646   if (!FixItInsertionLine.empty()) {
647     if (DiagOpts.ShowColors)
648       // Print fixit line in color
649       OS.changeColor(fixitColor, false);
650     if (DiagOpts.ShowSourceRanges)
651       OS << ' ';
652     OS << FixItInsertionLine << '\n';
653     if (DiagOpts.ShowColors)
654       OS.resetColor();
655   }
656 
657   // Print out any parseable fixit information requested by the options.
658   emitParseableFixits(Hints);
659 }
660 
661 /// \brief Highlight a SourceRange (with ~'s) for any characters on LineNo.
662 void TextDiagnostic::highlightRange(const CharSourceRange &R,
663                                     unsigned LineNo, FileID FID,
664                                     const std::string &SourceLine,
665                                     std::string &CaretLine) {
666   assert(CaretLine.size() == SourceLine.size() &&
667          "Expect a correspondence between source and caret line!");
668   if (!R.isValid()) return;
669 
670   SourceLocation Begin = SM.getExpansionLoc(R.getBegin());
671   SourceLocation End = SM.getExpansionLoc(R.getEnd());
672 
673   // If the End location and the start location are the same and are a macro
674   // location, then the range was something that came from a macro expansion
675   // or _Pragma.  If this is an object-like macro, the best we can do is to
676   // highlight the range.  If this is a function-like macro, we'd also like to
677   // highlight the arguments.
678   if (Begin == End && R.getEnd().isMacroID())
679     End = SM.getExpansionRange(R.getEnd()).second;
680 
681   unsigned StartLineNo = SM.getExpansionLineNumber(Begin);
682   if (StartLineNo > LineNo || SM.getFileID(Begin) != FID)
683     return;  // No intersection.
684 
685   unsigned EndLineNo = SM.getExpansionLineNumber(End);
686   if (EndLineNo < LineNo || SM.getFileID(End) != FID)
687     return;  // No intersection.
688 
689   // Compute the column number of the start.
690   unsigned StartColNo = 0;
691   if (StartLineNo == LineNo) {
692     StartColNo = SM.getExpansionColumnNumber(Begin);
693     if (StartColNo) --StartColNo;  // Zero base the col #.
694   }
695 
696   // Compute the column number of the end.
697   unsigned EndColNo = CaretLine.size();
698   if (EndLineNo == LineNo) {
699     EndColNo = SM.getExpansionColumnNumber(End);
700     if (EndColNo) {
701       --EndColNo;  // Zero base the col #.
702 
703       // Add in the length of the token, so that we cover multi-char tokens if
704       // this is a token range.
705       if (R.isTokenRange())
706         EndColNo += Lexer::MeasureTokenLength(End, SM, LangOpts);
707     } else {
708       EndColNo = CaretLine.size();
709     }
710   }
711 
712   assert(StartColNo <= EndColNo && "Invalid range!");
713 
714   // Check that a token range does not highlight only whitespace.
715   if (R.isTokenRange()) {
716     // Pick the first non-whitespace column.
717     while (StartColNo < SourceLine.size() &&
718            (SourceLine[StartColNo] == ' ' || SourceLine[StartColNo] == '\t'))
719       ++StartColNo;
720 
721     // Pick the last non-whitespace column.
722     if (EndColNo > SourceLine.size())
723       EndColNo = SourceLine.size();
724     while (EndColNo-1 &&
725            (SourceLine[EndColNo-1] == ' ' || SourceLine[EndColNo-1] == '\t'))
726       --EndColNo;
727 
728     // If the start/end passed each other, then we are trying to highlight a
729     // range that just exists in whitespace, which must be some sort of other
730     // bug.
731     assert(StartColNo <= EndColNo && "Trying to highlight whitespace??");
732   }
733 
734   // Fill the range with ~'s.
735   for (unsigned i = StartColNo; i < EndColNo; ++i)
736     CaretLine[i] = '~';
737 }
738 
739 std::string TextDiagnostic::buildFixItInsertionLine(unsigned LineNo,
740                                                     const char *LineStart,
741                                                     const char *LineEnd,
742                                                     ArrayRef<FixItHint> Hints) {
743   std::string FixItInsertionLine;
744   if (Hints.empty() || !DiagOpts.ShowFixits)
745     return FixItInsertionLine;
746 
747   for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
748        I != E; ++I) {
749     if (!I->CodeToInsert.empty()) {
750       // We have an insertion hint. Determine whether the inserted
751       // code is on the same line as the caret.
752       std::pair<FileID, unsigned> HintLocInfo
753         = SM.getDecomposedExpansionLoc(I->RemoveRange.getBegin());
754       if (LineNo == SM.getLineNumber(HintLocInfo.first, HintLocInfo.second)) {
755         // Insert the new code into the line just below the code
756         // that the user wrote.
757         unsigned HintColNo
758           = SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second);
759         unsigned LastColumnModified
760           = HintColNo - 1 + I->CodeToInsert.size();
761         if (LastColumnModified > FixItInsertionLine.size())
762           FixItInsertionLine.resize(LastColumnModified, ' ');
763         std::copy(I->CodeToInsert.begin(), I->CodeToInsert.end(),
764                   FixItInsertionLine.begin() + HintColNo - 1);
765       } else {
766         FixItInsertionLine.clear();
767         break;
768       }
769     }
770   }
771 
772   if (FixItInsertionLine.empty())
773     return FixItInsertionLine;
774 
775   // Now that we have the entire fixit line, expand the tabs in it.
776   // Since we don't want to insert spaces in the middle of a word,
777   // find each word and the column it should line up with and insert
778   // spaces until they match.
779   unsigned FixItPos = 0;
780   unsigned LinePos = 0;
781   unsigned TabExpandedCol = 0;
782   unsigned LineLength = LineEnd - LineStart;
783 
784   while (FixItPos < FixItInsertionLine.size() && LinePos < LineLength) {
785     // Find the next word in the FixIt line.
786     while (FixItPos < FixItInsertionLine.size() &&
787            FixItInsertionLine[FixItPos] == ' ')
788       ++FixItPos;
789     unsigned CharDistance = FixItPos - TabExpandedCol;
790 
791     // Walk forward in the source line, keeping track of
792     // the tab-expanded column.
793     for (unsigned I = 0; I < CharDistance; ++I, ++LinePos)
794       if (LinePos >= LineLength || LineStart[LinePos] != '\t')
795         ++TabExpandedCol;
796       else
797         TabExpandedCol =
798           (TabExpandedCol/DiagOpts.TabStop + 1) * DiagOpts.TabStop;
799 
800     // Adjust the fixit line to match this column.
801     FixItInsertionLine.insert(FixItPos, TabExpandedCol-FixItPos, ' ');
802     FixItPos = TabExpandedCol;
803 
804     // Walk to the end of the word.
805     while (FixItPos < FixItInsertionLine.size() &&
806            FixItInsertionLine[FixItPos] != ' ')
807       ++FixItPos;
808   }
809 
810   return FixItInsertionLine;
811 }
812 
813 void TextDiagnostic::expandTabs(std::string &SourceLine,
814                                 std::string &CaretLine) {
815   // Scan the source line, looking for tabs.  If we find any, manually expand
816   // them to spaces and update the CaretLine to match.
817   for (unsigned i = 0; i != SourceLine.size(); ++i) {
818     if (SourceLine[i] != '\t') continue;
819 
820     // Replace this tab with at least one space.
821     SourceLine[i] = ' ';
822 
823     // Compute the number of spaces we need to insert.
824     unsigned TabStop = DiagOpts.TabStop;
825     assert(0 < TabStop && TabStop <= DiagnosticOptions::MaxTabStop &&
826            "Invalid -ftabstop value");
827     unsigned NumSpaces = ((i+TabStop)/TabStop * TabStop) - (i+1);
828     assert(NumSpaces < TabStop && "Invalid computation of space amt");
829 
830     // Insert spaces into the SourceLine.
831     SourceLine.insert(i+1, NumSpaces, ' ');
832 
833     // Insert spaces or ~'s into CaretLine.
834     CaretLine.insert(i+1, NumSpaces, CaretLine[i] == '~' ? '~' : ' ');
835   }
836 }
837 
838 void TextDiagnostic::emitParseableFixits(ArrayRef<FixItHint> Hints) {
839   if (!DiagOpts.ShowParseableFixits)
840     return;
841 
842   // We follow FixItRewriter's example in not (yet) handling
843   // fix-its in macros.
844   for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
845        I != E; ++I) {
846     if (I->RemoveRange.isInvalid() ||
847         I->RemoveRange.getBegin().isMacroID() ||
848         I->RemoveRange.getEnd().isMacroID())
849       return;
850   }
851 
852   for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
853        I != E; ++I) {
854     SourceLocation BLoc = I->RemoveRange.getBegin();
855     SourceLocation ELoc = I->RemoveRange.getEnd();
856 
857     std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(BLoc);
858     std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(ELoc);
859 
860     // Adjust for token ranges.
861     if (I->RemoveRange.isTokenRange())
862       EInfo.second += Lexer::MeasureTokenLength(ELoc, SM, LangOpts);
863 
864     // We specifically do not do word-wrapping or tab-expansion here,
865     // because this is supposed to be easy to parse.
866     PresumedLoc PLoc = SM.getPresumedLoc(BLoc);
867     if (PLoc.isInvalid())
868       break;
869 
870     OS << "fix-it:\"";
871     OS.write_escaped(PLoc.getFilename());
872     OS << "\":{" << SM.getLineNumber(BInfo.first, BInfo.second)
873       << ':' << SM.getColumnNumber(BInfo.first, BInfo.second)
874       << '-' << SM.getLineNumber(EInfo.first, EInfo.second)
875       << ':' << SM.getColumnNumber(EInfo.first, EInfo.second)
876       << "}:\"";
877     OS.write_escaped(I->CodeToInsert);
878     OS << "\"\n";
879   }
880 }
881 
882