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/CharInfo.h"
12 #include "clang/Basic/DiagnosticOptions.h"
13 #include "clang/Basic/FileManager.h"
14 #include "clang/Basic/SourceManager.h"
15 #include "clang/Lex/Lexer.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/Support/ConvertUTF.h"
19 #include "llvm/Support/ErrorHandling.h"
20 #include "llvm/Support/Locale.h"
21 #include "llvm/Support/raw_ostream.h"
22 #include <algorithm>
23 
24 using namespace clang;
25 
26 static const enum raw_ostream::Colors noteColor =
27   raw_ostream::BLACK;
28 static const enum raw_ostream::Colors remarkColor =
29   raw_ostream::BLUE;
30 static const enum raw_ostream::Colors fixitColor =
31   raw_ostream::GREEN;
32 static const enum raw_ostream::Colors caretColor =
33   raw_ostream::GREEN;
34 static const enum raw_ostream::Colors warningColor =
35   raw_ostream::MAGENTA;
36 static const enum raw_ostream::Colors templateColor =
37   raw_ostream::CYAN;
38 static const enum raw_ostream::Colors errorColor = raw_ostream::RED;
39 static const enum raw_ostream::Colors fatalColor = raw_ostream::RED;
40 // Used for changing only the bold attribute.
41 static const enum raw_ostream::Colors savedColor =
42   raw_ostream::SAVEDCOLOR;
43 
44 /// \brief Add highlights to differences in template strings.
45 static void applyTemplateHighlighting(raw_ostream &OS, StringRef Str,
46                                       bool &Normal, bool Bold) {
47   while (1) {
48     size_t Pos = Str.find(ToggleHighlight);
49     OS << Str.slice(0, Pos);
50     if (Pos == StringRef::npos)
51       break;
52 
53     Str = Str.substr(Pos + 1);
54     if (Normal)
55       OS.changeColor(templateColor, true);
56     else {
57       OS.resetColor();
58       if (Bold)
59         OS.changeColor(savedColor, true);
60     }
61     Normal = !Normal;
62   }
63 }
64 
65 /// \brief Number of spaces to indent when word-wrapping.
66 const unsigned WordWrapIndentation = 6;
67 
68 static int bytesSincePreviousTabOrLineBegin(StringRef SourceLine, size_t i) {
69   int bytes = 0;
70   while (0<i) {
71     if (SourceLine[--i]=='\t')
72       break;
73     ++bytes;
74   }
75   return bytes;
76 }
77 
78 /// \brief returns a printable representation of first item from input range
79 ///
80 /// This function returns a printable representation of the next item in a line
81 ///  of source. If the next byte begins a valid and printable character, that
82 ///  character is returned along with 'true'.
83 ///
84 /// Otherwise, if the next byte begins a valid, but unprintable character, a
85 ///  printable, escaped representation of the character is returned, along with
86 ///  'false'. Otherwise a printable, escaped representation of the next byte
87 ///  is returned along with 'false'.
88 ///
89 /// \note The index is updated to be used with a subsequent call to
90 ///        printableTextForNextCharacter.
91 ///
92 /// \param SourceLine The line of source
93 /// \param i Pointer to byte index,
94 /// \param TabStop used to expand tabs
95 /// \return pair(printable text, 'true' iff original text was printable)
96 ///
97 static std::pair<SmallString<16>, bool>
98 printableTextForNextCharacter(StringRef SourceLine, size_t *i,
99                               unsigned TabStop) {
100   assert(i && "i must not be null");
101   assert(*i<SourceLine.size() && "must point to a valid index");
102 
103   if (SourceLine[*i]=='\t') {
104     assert(0 < TabStop && TabStop <= DiagnosticOptions::MaxTabStop &&
105            "Invalid -ftabstop value");
106     unsigned col = bytesSincePreviousTabOrLineBegin(SourceLine, *i);
107     unsigned NumSpaces = TabStop - col%TabStop;
108     assert(0 < NumSpaces && NumSpaces <= TabStop
109            && "Invalid computation of space amt");
110     ++(*i);
111 
112     SmallString<16> expandedTab;
113     expandedTab.assign(NumSpaces, ' ');
114     return std::make_pair(expandedTab, true);
115   }
116 
117   unsigned char const *begin, *end;
118   begin = reinterpret_cast<unsigned char const *>(&*(SourceLine.begin() + *i));
119   end = begin + (SourceLine.size() - *i);
120 
121   if (isLegalUTF8Sequence(begin, end)) {
122     UTF32 c;
123     UTF32 *cptr = &c;
124     unsigned char const *original_begin = begin;
125     unsigned char const *cp_end = begin+getNumBytesForUTF8(SourceLine[*i]);
126 
127     ConversionResult res = ConvertUTF8toUTF32(&begin, cp_end, &cptr, cptr+1,
128                                               strictConversion);
129     (void)res;
130     assert(conversionOK==res);
131     assert(0 < begin-original_begin
132            && "we must be further along in the string now");
133     *i += begin-original_begin;
134 
135     if (!llvm::sys::locale::isPrint(c)) {
136       // If next character is valid UTF-8, but not printable
137       SmallString<16> expandedCP("<U+>");
138       while (c) {
139         expandedCP.insert(expandedCP.begin()+3, llvm::hexdigit(c%16));
140         c/=16;
141       }
142       while (expandedCP.size() < 8)
143         expandedCP.insert(expandedCP.begin()+3, llvm::hexdigit(0));
144       return std::make_pair(expandedCP, false);
145     }
146 
147     // If next character is valid UTF-8, and printable
148     return std::make_pair(SmallString<16>(original_begin, cp_end), true);
149 
150   }
151 
152   // If next byte is not valid UTF-8 (and therefore not printable)
153   SmallString<16> expandedByte("<XX>");
154   unsigned char byte = SourceLine[*i];
155   expandedByte[1] = llvm::hexdigit(byte / 16);
156   expandedByte[2] = llvm::hexdigit(byte % 16);
157   ++(*i);
158   return std::make_pair(expandedByte, false);
159 }
160 
161 static void expandTabs(std::string &SourceLine, unsigned TabStop) {
162   size_t i = SourceLine.size();
163   while (i>0) {
164     i--;
165     if (SourceLine[i]!='\t')
166       continue;
167     size_t tmp_i = i;
168     std::pair<SmallString<16>,bool> res
169       = printableTextForNextCharacter(SourceLine, &tmp_i, TabStop);
170     SourceLine.replace(i, 1, res.first.c_str());
171   }
172 }
173 
174 /// This function takes a raw source line and produces a mapping from the bytes
175 ///  of the printable representation of the line to the columns those printable
176 ///  characters will appear at (numbering the first column as 0).
177 ///
178 /// If a byte 'i' corresponds to multiple columns (e.g. the byte contains a tab
179 ///  character) then the array will map that byte to the first column the
180 ///  tab appears at and the next value in the map will have been incremented
181 ///  more than once.
182 ///
183 /// If a byte is the first in a sequence of bytes that together map to a single
184 ///  entity in the output, then the array will map that byte to the appropriate
185 ///  column while the subsequent bytes will be -1.
186 ///
187 /// The last element in the array does not correspond to any byte in the input
188 ///  and instead is the number of columns needed to display the source
189 ///
190 /// example: (given a tabstop of 8)
191 ///
192 ///    "a \t \u3042" -> {0,1,2,8,9,-1,-1,11}
193 ///
194 ///  (\\u3042 is represented in UTF-8 by three bytes and takes two columns to
195 ///   display)
196 static void byteToColumn(StringRef SourceLine, unsigned TabStop,
197                          SmallVectorImpl<int> &out) {
198   out.clear();
199 
200   if (SourceLine.empty()) {
201     out.resize(1u,0);
202     return;
203   }
204 
205   out.resize(SourceLine.size()+1, -1);
206 
207   int columns = 0;
208   size_t i = 0;
209   while (i<SourceLine.size()) {
210     out[i] = columns;
211     std::pair<SmallString<16>,bool> res
212       = printableTextForNextCharacter(SourceLine, &i, TabStop);
213     columns += llvm::sys::locale::columnWidth(res.first);
214   }
215   out.back() = columns;
216 }
217 
218 /// This function takes a raw source line and produces a mapping from columns
219 ///  to the byte of the source line that produced the character displaying at
220 ///  that column. This is the inverse of the mapping produced by byteToColumn()
221 ///
222 /// The last element in the array is the number of bytes in the source string
223 ///
224 /// example: (given a tabstop of 8)
225 ///
226 ///    "a \t \u3042" -> {0,1,2,-1,-1,-1,-1,-1,3,4,-1,7}
227 ///
228 ///  (\\u3042 is represented in UTF-8 by three bytes and takes two columns to
229 ///   display)
230 static void columnToByte(StringRef SourceLine, unsigned TabStop,
231                          SmallVectorImpl<int> &out) {
232   out.clear();
233 
234   if (SourceLine.empty()) {
235     out.resize(1u, 0);
236     return;
237   }
238 
239   int columns = 0;
240   size_t i = 0;
241   while (i<SourceLine.size()) {
242     out.resize(columns+1, -1);
243     out.back() = i;
244     std::pair<SmallString<16>,bool> res
245       = printableTextForNextCharacter(SourceLine, &i, TabStop);
246     columns += llvm::sys::locale::columnWidth(res.first);
247   }
248   out.resize(columns+1, -1);
249   out.back() = i;
250 }
251 
252 namespace {
253 struct SourceColumnMap {
254   SourceColumnMap(StringRef SourceLine, unsigned TabStop)
255   : m_SourceLine(SourceLine) {
256 
257     ::byteToColumn(SourceLine, TabStop, m_byteToColumn);
258     ::columnToByte(SourceLine, TabStop, m_columnToByte);
259 
260     assert(m_byteToColumn.size()==SourceLine.size()+1);
261     assert(0 < m_byteToColumn.size() && 0 < m_columnToByte.size());
262     assert(m_byteToColumn.size()
263            == static_cast<unsigned>(m_columnToByte.back()+1));
264     assert(static_cast<unsigned>(m_byteToColumn.back()+1)
265            == m_columnToByte.size());
266   }
267   int columns() const { return m_byteToColumn.back(); }
268   int bytes() const { return m_columnToByte.back(); }
269 
270   /// \brief Map a byte to the column which it is at the start of, or return -1
271   /// if it is not at the start of a column (for a UTF-8 trailing byte).
272   int byteToColumn(int n) const {
273     assert(0<=n && n<static_cast<int>(m_byteToColumn.size()));
274     return m_byteToColumn[n];
275   }
276 
277   /// \brief Map a byte to the first column which contains it.
278   int byteToContainingColumn(int N) const {
279     assert(0 <= N && N < static_cast<int>(m_byteToColumn.size()));
280     while (m_byteToColumn[N] == -1)
281       --N;
282     return m_byteToColumn[N];
283   }
284 
285   /// \brief Map a column to the byte which starts the column, or return -1 if
286   /// the column the second or subsequent column of an expanded tab or similar
287   /// multi-column entity.
288   int columnToByte(int n) const {
289     assert(0<=n && n<static_cast<int>(m_columnToByte.size()));
290     return m_columnToByte[n];
291   }
292 
293   /// \brief Map from a byte index to the next byte which starts a column.
294   int startOfNextColumn(int N) const {
295     assert(0 <= N && N < static_cast<int>(m_byteToColumn.size() - 1));
296     while (byteToColumn(++N) == -1) {}
297     return N;
298   }
299 
300   /// \brief Map from a byte index to the previous byte which starts a column.
301   int startOfPreviousColumn(int N) const {
302     assert(0 < N && N < static_cast<int>(m_byteToColumn.size()));
303     while (byteToColumn(--N) == -1) {}
304     return N;
305   }
306 
307   StringRef getSourceLine() const {
308     return m_SourceLine;
309   }
310 
311 private:
312   const std::string m_SourceLine;
313   SmallVector<int,200> m_byteToColumn;
314   SmallVector<int,200> m_columnToByte;
315 };
316 } // end anonymous namespace
317 
318 /// \brief When the source code line we want to print is too long for
319 /// the terminal, select the "interesting" region.
320 static void selectInterestingSourceRegion(std::string &SourceLine,
321                                           std::string &CaretLine,
322                                           std::string &FixItInsertionLine,
323                                           unsigned Columns,
324                                           const SourceColumnMap &map) {
325   unsigned CaretColumns = CaretLine.size();
326   unsigned FixItColumns = llvm::sys::locale::columnWidth(FixItInsertionLine);
327   unsigned MaxColumns = std::max(static_cast<unsigned>(map.columns()),
328                                  std::max(CaretColumns, FixItColumns));
329   // if the number of columns is less than the desired number we're done
330   if (MaxColumns <= Columns)
331     return;
332 
333   // No special characters are allowed in CaretLine.
334   assert(CaretLine.end() ==
335          std::find_if(CaretLine.begin(), CaretLine.end(),
336                       [](char c) { return c < ' ' || '~' < c; }));
337 
338   // Find the slice that we need to display the full caret line
339   // correctly.
340   unsigned CaretStart = 0, CaretEnd = CaretLine.size();
341   for (; CaretStart != CaretEnd; ++CaretStart)
342     if (!isWhitespace(CaretLine[CaretStart]))
343       break;
344 
345   for (; CaretEnd != CaretStart; --CaretEnd)
346     if (!isWhitespace(CaretLine[CaretEnd - 1]))
347       break;
348 
349   // caret has already been inserted into CaretLine so the above whitespace
350   // check is guaranteed to include the caret
351 
352   // If we have a fix-it line, make sure the slice includes all of the
353   // fix-it information.
354   if (!FixItInsertionLine.empty()) {
355     unsigned FixItStart = 0, FixItEnd = FixItInsertionLine.size();
356     for (; FixItStart != FixItEnd; ++FixItStart)
357       if (!isWhitespace(FixItInsertionLine[FixItStart]))
358         break;
359 
360     for (; FixItEnd != FixItStart; --FixItEnd)
361       if (!isWhitespace(FixItInsertionLine[FixItEnd - 1]))
362         break;
363 
364     // We can safely use the byte offset FixItStart as the column offset
365     // because the characters up until FixItStart are all ASCII whitespace
366     // characters.
367     unsigned FixItStartCol = FixItStart;
368     unsigned FixItEndCol
369       = llvm::sys::locale::columnWidth(FixItInsertionLine.substr(0, FixItEnd));
370 
371     CaretStart = std::min(FixItStartCol, CaretStart);
372     CaretEnd = std::max(FixItEndCol, CaretEnd);
373   }
374 
375   // CaretEnd may have been set at the middle of a character
376   // If it's not at a character's first column then advance it past the current
377   //   character.
378   while (static_cast<int>(CaretEnd) < map.columns() &&
379          -1 == map.columnToByte(CaretEnd))
380     ++CaretEnd;
381 
382   assert((static_cast<int>(CaretStart) > map.columns() ||
383           -1!=map.columnToByte(CaretStart)) &&
384          "CaretStart must not point to a column in the middle of a source"
385          " line character");
386   assert((static_cast<int>(CaretEnd) > map.columns() ||
387           -1!=map.columnToByte(CaretEnd)) &&
388          "CaretEnd must not point to a column in the middle of a source line"
389          " character");
390 
391   // CaretLine[CaretStart, CaretEnd) contains all of the interesting
392   // parts of the caret line. While this slice is smaller than the
393   // number of columns we have, try to grow the slice to encompass
394   // more context.
395 
396   unsigned SourceStart = map.columnToByte(std::min<unsigned>(CaretStart,
397                                                              map.columns()));
398   unsigned SourceEnd = map.columnToByte(std::min<unsigned>(CaretEnd,
399                                                            map.columns()));
400 
401   unsigned CaretColumnsOutsideSource = CaretEnd-CaretStart
402     - (map.byteToColumn(SourceEnd)-map.byteToColumn(SourceStart));
403 
404   char const *front_ellipse = "  ...";
405   char const *front_space   = "     ";
406   char const *back_ellipse = "...";
407   unsigned ellipses_space = strlen(front_ellipse) + strlen(back_ellipse);
408 
409   unsigned TargetColumns = Columns;
410   // Give us extra room for the ellipses
411   //  and any of the caret line that extends past the source
412   if (TargetColumns > ellipses_space+CaretColumnsOutsideSource)
413     TargetColumns -= ellipses_space+CaretColumnsOutsideSource;
414 
415   while (SourceStart>0 || SourceEnd<SourceLine.size()) {
416     bool ExpandedRegion = false;
417 
418     if (SourceStart>0) {
419       unsigned NewStart = map.startOfPreviousColumn(SourceStart);
420 
421       // Skip over any whitespace we see here; we're looking for
422       // another bit of interesting text.
423       // FIXME: Detect non-ASCII whitespace characters too.
424       while (NewStart && isWhitespace(SourceLine[NewStart]))
425         NewStart = map.startOfPreviousColumn(NewStart);
426 
427       // Skip over this bit of "interesting" text.
428       while (NewStart) {
429         unsigned Prev = map.startOfPreviousColumn(NewStart);
430         if (isWhitespace(SourceLine[Prev]))
431           break;
432         NewStart = Prev;
433       }
434 
435       assert(map.byteToColumn(NewStart) != -1);
436       unsigned NewColumns = map.byteToColumn(SourceEnd) -
437                               map.byteToColumn(NewStart);
438       if (NewColumns <= TargetColumns) {
439         SourceStart = NewStart;
440         ExpandedRegion = true;
441       }
442     }
443 
444     if (SourceEnd<SourceLine.size()) {
445       unsigned NewEnd = map.startOfNextColumn(SourceEnd);
446 
447       // Skip over any whitespace we see here; we're looking for
448       // another bit of interesting text.
449       // FIXME: Detect non-ASCII whitespace characters too.
450       while (NewEnd < SourceLine.size() && isWhitespace(SourceLine[NewEnd]))
451         NewEnd = map.startOfNextColumn(NewEnd);
452 
453       // Skip over this bit of "interesting" text.
454       while (NewEnd < SourceLine.size() && isWhitespace(SourceLine[NewEnd]))
455         NewEnd = map.startOfNextColumn(NewEnd);
456 
457       assert(map.byteToColumn(NewEnd) != -1);
458       unsigned NewColumns = map.byteToColumn(NewEnd) -
459                               map.byteToColumn(SourceStart);
460       if (NewColumns <= TargetColumns) {
461         SourceEnd = NewEnd;
462         ExpandedRegion = true;
463       }
464     }
465 
466     if (!ExpandedRegion)
467       break;
468   }
469 
470   CaretStart = map.byteToColumn(SourceStart);
471   CaretEnd = map.byteToColumn(SourceEnd) + CaretColumnsOutsideSource;
472 
473   // [CaretStart, CaretEnd) is the slice we want. Update the various
474   // output lines to show only this slice, with two-space padding
475   // before the lines so that it looks nicer.
476 
477   assert(CaretStart!=(unsigned)-1 && CaretEnd!=(unsigned)-1 &&
478          SourceStart!=(unsigned)-1 && SourceEnd!=(unsigned)-1);
479   assert(SourceStart <= SourceEnd);
480   assert(CaretStart <= CaretEnd);
481 
482   unsigned BackColumnsRemoved
483     = map.byteToColumn(SourceLine.size())-map.byteToColumn(SourceEnd);
484   unsigned FrontColumnsRemoved = CaretStart;
485   unsigned ColumnsKept = CaretEnd-CaretStart;
486 
487   // We checked up front that the line needed truncation
488   assert(FrontColumnsRemoved+ColumnsKept+BackColumnsRemoved > Columns);
489 
490   // The line needs some truncation, and we'd prefer to keep the front
491   //  if possible, so remove the back
492   if (BackColumnsRemoved > strlen(back_ellipse))
493     SourceLine.replace(SourceEnd, std::string::npos, back_ellipse);
494 
495   // If that's enough then we're done
496   if (FrontColumnsRemoved+ColumnsKept <= Columns)
497     return;
498 
499   // Otherwise remove the front as well
500   if (FrontColumnsRemoved > strlen(front_ellipse)) {
501     SourceLine.replace(0, SourceStart, front_ellipse);
502     CaretLine.replace(0, CaretStart, front_space);
503     if (!FixItInsertionLine.empty())
504       FixItInsertionLine.replace(0, CaretStart, front_space);
505   }
506 }
507 
508 /// \brief Skip over whitespace in the string, starting at the given
509 /// index.
510 ///
511 /// \returns The index of the first non-whitespace character that is
512 /// greater than or equal to Idx or, if no such character exists,
513 /// returns the end of the string.
514 static unsigned skipWhitespace(unsigned Idx, StringRef Str, unsigned Length) {
515   while (Idx < Length && isWhitespace(Str[Idx]))
516     ++Idx;
517   return Idx;
518 }
519 
520 /// \brief If the given character is the start of some kind of
521 /// balanced punctuation (e.g., quotes or parentheses), return the
522 /// character that will terminate the punctuation.
523 ///
524 /// \returns The ending punctuation character, if any, or the NULL
525 /// character if the input character does not start any punctuation.
526 static inline char findMatchingPunctuation(char c) {
527   switch (c) {
528   case '\'': return '\'';
529   case '`': return '\'';
530   case '"':  return '"';
531   case '(':  return ')';
532   case '[': return ']';
533   case '{': return '}';
534   default: break;
535   }
536 
537   return 0;
538 }
539 
540 /// \brief Find the end of the word starting at the given offset
541 /// within a string.
542 ///
543 /// \returns the index pointing one character past the end of the
544 /// word.
545 static unsigned findEndOfWord(unsigned Start, StringRef Str,
546                               unsigned Length, unsigned Column,
547                               unsigned Columns) {
548   assert(Start < Str.size() && "Invalid start position!");
549   unsigned End = Start + 1;
550 
551   // If we are already at the end of the string, take that as the word.
552   if (End == Str.size())
553     return End;
554 
555   // Determine if the start of the string is actually opening
556   // punctuation, e.g., a quote or parentheses.
557   char EndPunct = findMatchingPunctuation(Str[Start]);
558   if (!EndPunct) {
559     // This is a normal word. Just find the first space character.
560     while (End < Length && !isWhitespace(Str[End]))
561       ++End;
562     return End;
563   }
564 
565   // We have the start of a balanced punctuation sequence (quotes,
566   // parentheses, etc.). Determine the full sequence is.
567   SmallString<16> PunctuationEndStack;
568   PunctuationEndStack.push_back(EndPunct);
569   while (End < Length && !PunctuationEndStack.empty()) {
570     if (Str[End] == PunctuationEndStack.back())
571       PunctuationEndStack.pop_back();
572     else if (char SubEndPunct = findMatchingPunctuation(Str[End]))
573       PunctuationEndStack.push_back(SubEndPunct);
574 
575     ++End;
576   }
577 
578   // Find the first space character after the punctuation ended.
579   while (End < Length && !isWhitespace(Str[End]))
580     ++End;
581 
582   unsigned PunctWordLength = End - Start;
583   if (// If the word fits on this line
584       Column + PunctWordLength <= Columns ||
585       // ... or the word is "short enough" to take up the next line
586       // without too much ugly white space
587       PunctWordLength < Columns/3)
588     return End; // Take the whole thing as a single "word".
589 
590   // The whole quoted/parenthesized string is too long to print as a
591   // single "word". Instead, find the "word" that starts just after
592   // the punctuation and use that end-point instead. This will recurse
593   // until it finds something small enough to consider a word.
594   return findEndOfWord(Start + 1, Str, Length, Column + 1, Columns);
595 }
596 
597 /// \brief Print the given string to a stream, word-wrapping it to
598 /// some number of columns in the process.
599 ///
600 /// \param OS the stream to which the word-wrapping string will be
601 /// emitted.
602 /// \param Str the string to word-wrap and output.
603 /// \param Columns the number of columns to word-wrap to.
604 /// \param Column the column number at which the first character of \p
605 /// Str will be printed. This will be non-zero when part of the first
606 /// line has already been printed.
607 /// \param Bold if the current text should be bold
608 /// \param Indentation the number of spaces to indent any lines beyond
609 /// the first line.
610 /// \returns true if word-wrapping was required, or false if the
611 /// string fit on the first line.
612 static bool printWordWrapped(raw_ostream &OS, StringRef Str,
613                              unsigned Columns,
614                              unsigned Column = 0,
615                              bool Bold = false,
616                              unsigned Indentation = WordWrapIndentation) {
617   const unsigned Length = std::min(Str.find('\n'), Str.size());
618   bool TextNormal = true;
619 
620   // The string used to indent each line.
621   SmallString<16> IndentStr;
622   IndentStr.assign(Indentation, ' ');
623   bool Wrapped = false;
624   for (unsigned WordStart = 0, WordEnd; WordStart < Length;
625        WordStart = WordEnd) {
626     // Find the beginning of the next word.
627     WordStart = skipWhitespace(WordStart, Str, Length);
628     if (WordStart == Length)
629       break;
630 
631     // Find the end of this word.
632     WordEnd = findEndOfWord(WordStart, Str, Length, Column, Columns);
633 
634     // Does this word fit on the current line?
635     unsigned WordLength = WordEnd - WordStart;
636     if (Column + WordLength < Columns) {
637       // This word fits on the current line; print it there.
638       if (WordStart) {
639         OS << ' ';
640         Column += 1;
641       }
642       applyTemplateHighlighting(OS, Str.substr(WordStart, WordLength),
643                                 TextNormal, Bold);
644       Column += WordLength;
645       continue;
646     }
647 
648     // This word does not fit on the current line, so wrap to the next
649     // line.
650     OS << '\n';
651     OS.write(&IndentStr[0], Indentation);
652     applyTemplateHighlighting(OS, Str.substr(WordStart, WordLength),
653                               TextNormal, Bold);
654     Column = Indentation + WordLength;
655     Wrapped = true;
656   }
657 
658   // Append any remaning text from the message with its existing formatting.
659   applyTemplateHighlighting(OS, Str.substr(Length), TextNormal, Bold);
660 
661   assert(TextNormal && "Text highlighted at end of diagnostic message.");
662 
663   return Wrapped;
664 }
665 
666 TextDiagnostic::TextDiagnostic(raw_ostream &OS,
667                                const LangOptions &LangOpts,
668                                DiagnosticOptions *DiagOpts)
669   : DiagnosticRenderer(LangOpts, DiagOpts), OS(OS) {}
670 
671 TextDiagnostic::~TextDiagnostic() {}
672 
673 void
674 TextDiagnostic::emitDiagnosticMessage(SourceLocation Loc,
675                                       PresumedLoc PLoc,
676                                       DiagnosticsEngine::Level Level,
677                                       StringRef Message,
678                                       ArrayRef<clang::CharSourceRange> Ranges,
679                                       const SourceManager *SM,
680                                       DiagOrStoredDiag D) {
681   uint64_t StartOfLocationInfo = OS.tell();
682 
683   // Emit the location of this particular diagnostic.
684   if (Loc.isValid())
685     emitDiagnosticLoc(Loc, PLoc, Level, Ranges, *SM);
686 
687   if (DiagOpts->ShowColors)
688     OS.resetColor();
689 
690   printDiagnosticLevel(OS, Level, DiagOpts->ShowColors,
691                        DiagOpts->CLFallbackMode);
692   printDiagnosticMessage(OS,
693                          /*IsSupplemental*/ Level == DiagnosticsEngine::Note,
694                          Message, OS.tell() - StartOfLocationInfo,
695                          DiagOpts->MessageLength, DiagOpts->ShowColors);
696 }
697 
698 /*static*/ void
699 TextDiagnostic::printDiagnosticLevel(raw_ostream &OS,
700                                      DiagnosticsEngine::Level Level,
701                                      bool ShowColors,
702                                      bool CLFallbackMode) {
703   if (ShowColors) {
704     // Print diagnostic category in bold and color
705     switch (Level) {
706     case DiagnosticsEngine::Ignored:
707       llvm_unreachable("Invalid diagnostic type");
708     case DiagnosticsEngine::Note:    OS.changeColor(noteColor, true); break;
709     case DiagnosticsEngine::Remark:  OS.changeColor(remarkColor, true); break;
710     case DiagnosticsEngine::Warning: OS.changeColor(warningColor, true); break;
711     case DiagnosticsEngine::Error:   OS.changeColor(errorColor, true); break;
712     case DiagnosticsEngine::Fatal:   OS.changeColor(fatalColor, true); break;
713     }
714   }
715 
716   switch (Level) {
717   case DiagnosticsEngine::Ignored:
718     llvm_unreachable("Invalid diagnostic type");
719   case DiagnosticsEngine::Note:    OS << "note"; break;
720   case DiagnosticsEngine::Remark:  OS << "remark"; break;
721   case DiagnosticsEngine::Warning: OS << "warning"; break;
722   case DiagnosticsEngine::Error:   OS << "error"; break;
723   case DiagnosticsEngine::Fatal:   OS << "fatal error"; break;
724   }
725 
726   // In clang-cl /fallback mode, print diagnostics as "error(clang):". This
727   // makes it more clear whether a message is coming from clang or cl.exe,
728   // and it prevents MSBuild from concluding that the build failed just because
729   // there is an "error:" in the output.
730   if (CLFallbackMode)
731     OS << "(clang)";
732 
733   OS << ": ";
734 
735   if (ShowColors)
736     OS.resetColor();
737 }
738 
739 /*static*/
740 void TextDiagnostic::printDiagnosticMessage(raw_ostream &OS,
741                                             bool IsSupplemental,
742                                             StringRef Message,
743                                             unsigned CurrentColumn,
744                                             unsigned Columns, bool ShowColors) {
745   bool Bold = false;
746   if (ShowColors && !IsSupplemental) {
747     // Print primary diagnostic messages in bold and without color, to visually
748     // indicate the transition from continuation notes and other output.
749     OS.changeColor(savedColor, true);
750     Bold = true;
751   }
752 
753   if (Columns)
754     printWordWrapped(OS, Message, Columns, CurrentColumn, Bold);
755   else {
756     bool Normal = true;
757     applyTemplateHighlighting(OS, Message, Normal, Bold);
758     assert(Normal && "Formatting should have returned to normal");
759   }
760 
761   if (ShowColors)
762     OS.resetColor();
763   OS << '\n';
764 }
765 
766 /// \brief Print out the file/line/column information and include trace.
767 ///
768 /// This method handlen the emission of the diagnostic location information.
769 /// This includes extracting as much location information as is present for
770 /// the diagnostic and printing it, as well as any include stack or source
771 /// ranges necessary.
772 void TextDiagnostic::emitDiagnosticLoc(SourceLocation Loc, PresumedLoc PLoc,
773                                        DiagnosticsEngine::Level Level,
774                                        ArrayRef<CharSourceRange> Ranges,
775                                        const SourceManager &SM) {
776   if (PLoc.isInvalid()) {
777     // At least print the file name if available:
778     FileID FID = SM.getFileID(Loc);
779     if (FID.isValid()) {
780       const FileEntry* FE = SM.getFileEntryForID(FID);
781       if (FE && FE->isValid()) {
782         OS << FE->getName();
783         if (FE->isInPCH())
784           OS << " (in PCH)";
785         OS << ": ";
786       }
787     }
788     return;
789   }
790   unsigned LineNo = PLoc.getLine();
791 
792   if (!DiagOpts->ShowLocation)
793     return;
794 
795   if (DiagOpts->ShowColors)
796     OS.changeColor(savedColor, true);
797 
798   OS << PLoc.getFilename();
799   switch (DiagOpts->getFormat()) {
800   case DiagnosticOptions::Clang: OS << ':'  << LineNo; break;
801   case DiagnosticOptions::MSVC:  OS << '('  << LineNo; break;
802   case DiagnosticOptions::Vi:    OS << " +" << LineNo; break;
803   }
804 
805   if (DiagOpts->ShowColumn)
806     // Compute the column number.
807     if (unsigned ColNo = PLoc.getColumn()) {
808       if (DiagOpts->getFormat() == DiagnosticOptions::MSVC) {
809         OS << ',';
810         // Visual Studio 2010 or earlier expects column number to be off by one
811         if (LangOpts.MSCompatibilityVersion &&
812             !LangOpts.isCompatibleWithMSVC(LangOptions::MSVC2012))
813           ColNo--;
814       } else
815         OS << ':';
816       OS << ColNo;
817     }
818   switch (DiagOpts->getFormat()) {
819   case DiagnosticOptions::Clang:
820   case DiagnosticOptions::Vi:    OS << ':';    break;
821   case DiagnosticOptions::MSVC:
822     // MSVC2013 and before print 'file(4) : error'. MSVC2015 gets rid of the
823     // space and prints 'file(4): error'.
824     OS << ')';
825     if (LangOpts.MSCompatibilityVersion &&
826         !LangOpts.isCompatibleWithMSVC(LangOptions::MSVC2015))
827       OS << ' ';
828     OS << ": ";
829     break;
830   }
831 
832   if (DiagOpts->ShowSourceRanges && !Ranges.empty()) {
833     FileID CaretFileID =
834       SM.getFileID(SM.getExpansionLoc(Loc));
835     bool PrintedRange = false;
836 
837     for (ArrayRef<CharSourceRange>::const_iterator RI = Ranges.begin(),
838          RE = Ranges.end();
839          RI != RE; ++RI) {
840       // Ignore invalid ranges.
841       if (!RI->isValid()) continue;
842 
843       SourceLocation B = SM.getExpansionLoc(RI->getBegin());
844       SourceLocation E = SM.getExpansionLoc(RI->getEnd());
845 
846       // If the End location and the start location are the same and are a
847       // macro location, then the range was something that came from a
848       // macro expansion or _Pragma.  If this is an object-like macro, the
849       // best we can do is to highlight the range.  If this is a
850       // function-like macro, we'd also like to highlight the arguments.
851       if (B == E && RI->getEnd().isMacroID())
852         E = SM.getExpansionRange(RI->getEnd()).second;
853 
854       std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(B);
855       std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E);
856 
857       // If the start or end of the range is in another file, just discard
858       // it.
859       if (BInfo.first != CaretFileID || EInfo.first != CaretFileID)
860         continue;
861 
862       // Add in the length of the token, so that we cover multi-char
863       // tokens.
864       unsigned TokSize = 0;
865       if (RI->isTokenRange())
866         TokSize = Lexer::MeasureTokenLength(E, SM, LangOpts);
867 
868       OS << '{' << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
869         << SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
870         << SM.getLineNumber(EInfo.first, EInfo.second) << ':'
871         << (SM.getColumnNumber(EInfo.first, EInfo.second)+TokSize)
872         << '}';
873       PrintedRange = true;
874     }
875 
876     if (PrintedRange)
877       OS << ':';
878   }
879   OS << ' ';
880 }
881 
882 void TextDiagnostic::emitIncludeLocation(SourceLocation Loc,
883                                          PresumedLoc PLoc,
884                                          const SourceManager &SM) {
885   if (DiagOpts->ShowLocation && PLoc.isValid())
886     OS << "In file included from " << PLoc.getFilename() << ':'
887        << PLoc.getLine() << ":\n";
888   else
889     OS << "In included file:\n";
890 }
891 
892 void TextDiagnostic::emitImportLocation(SourceLocation Loc, PresumedLoc PLoc,
893                                         StringRef ModuleName,
894                                         const SourceManager &SM) {
895   if (DiagOpts->ShowLocation && PLoc.isValid())
896     OS << "In module '" << ModuleName << "' imported from "
897        << PLoc.getFilename() << ':' << PLoc.getLine() << ":\n";
898   else
899     OS << "In module '" << ModuleName << "':\n";
900 }
901 
902 void TextDiagnostic::emitBuildingModuleLocation(SourceLocation Loc,
903                                                 PresumedLoc PLoc,
904                                                 StringRef ModuleName,
905                                                 const SourceManager &SM) {
906   if (DiagOpts->ShowLocation && PLoc.isValid())
907     OS << "While building module '" << ModuleName << "' imported from "
908       << PLoc.getFilename() << ':' << PLoc.getLine() << ":\n";
909   else
910     OS << "While building module '" << ModuleName << "':\n";
911 }
912 
913 /// \brief Highlight a SourceRange (with ~'s) for any characters on LineNo.
914 static void highlightRange(const CharSourceRange &R,
915                            unsigned LineNo, FileID FID,
916                            const SourceColumnMap &map,
917                            std::string &CaretLine,
918                            const SourceManager &SM,
919                            const LangOptions &LangOpts) {
920   if (!R.isValid()) return;
921 
922   SourceLocation Begin = R.getBegin();
923   SourceLocation End = R.getEnd();
924 
925   unsigned StartLineNo = SM.getExpansionLineNumber(Begin);
926   if (StartLineNo > LineNo || SM.getFileID(Begin) != FID)
927     return;  // No intersection.
928 
929   unsigned EndLineNo = SM.getExpansionLineNumber(End);
930   if (EndLineNo < LineNo || SM.getFileID(End) != FID)
931     return;  // No intersection.
932 
933   // Compute the column number of the start.
934   unsigned StartColNo = 0;
935   if (StartLineNo == LineNo) {
936     StartColNo = SM.getExpansionColumnNumber(Begin);
937     if (StartColNo) --StartColNo;  // Zero base the col #.
938   }
939 
940   // Compute the column number of the end.
941   unsigned EndColNo = map.getSourceLine().size();
942   if (EndLineNo == LineNo) {
943     EndColNo = SM.getExpansionColumnNumber(End);
944     if (EndColNo) {
945       --EndColNo;  // Zero base the col #.
946 
947       // Add in the length of the token, so that we cover multi-char tokens if
948       // this is a token range.
949       if (R.isTokenRange())
950         EndColNo += Lexer::MeasureTokenLength(End, SM, LangOpts);
951     } else {
952       EndColNo = CaretLine.size();
953     }
954   }
955 
956   assert(StartColNo <= EndColNo && "Invalid range!");
957 
958   // Check that a token range does not highlight only whitespace.
959   if (R.isTokenRange()) {
960     // Pick the first non-whitespace column.
961     while (StartColNo < map.getSourceLine().size() &&
962            (map.getSourceLine()[StartColNo] == ' ' ||
963             map.getSourceLine()[StartColNo] == '\t'))
964       StartColNo = map.startOfNextColumn(StartColNo);
965 
966     // Pick the last non-whitespace column.
967     if (EndColNo > map.getSourceLine().size())
968       EndColNo = map.getSourceLine().size();
969     while (EndColNo &&
970            (map.getSourceLine()[EndColNo-1] == ' ' ||
971             map.getSourceLine()[EndColNo-1] == '\t'))
972       EndColNo = map.startOfPreviousColumn(EndColNo);
973 
974     // If the start/end passed each other, then we are trying to highlight a
975     // range that just exists in whitespace, which must be some sort of other
976     // bug.
977     assert(StartColNo <= EndColNo && "Trying to highlight whitespace??");
978   }
979 
980   assert(StartColNo <= map.getSourceLine().size() && "Invalid range!");
981   assert(EndColNo <= map.getSourceLine().size() && "Invalid range!");
982 
983   // Fill the range with ~'s.
984   StartColNo = map.byteToContainingColumn(StartColNo);
985   EndColNo = map.byteToContainingColumn(EndColNo);
986 
987   assert(StartColNo <= EndColNo && "Invalid range!");
988   if (CaretLine.size() < EndColNo)
989     CaretLine.resize(EndColNo,' ');
990   std::fill(CaretLine.begin()+StartColNo,CaretLine.begin()+EndColNo,'~');
991 }
992 
993 static std::string buildFixItInsertionLine(unsigned LineNo,
994                                            const SourceColumnMap &map,
995                                            ArrayRef<FixItHint> Hints,
996                                            const SourceManager &SM,
997                                            const DiagnosticOptions *DiagOpts) {
998   std::string FixItInsertionLine;
999   if (Hints.empty() || !DiagOpts->ShowFixits)
1000     return FixItInsertionLine;
1001   unsigned PrevHintEndCol = 0;
1002 
1003   for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1004        I != E; ++I) {
1005     if (!I->CodeToInsert.empty()) {
1006       // We have an insertion hint. Determine whether the inserted
1007       // code contains no newlines and is on the same line as the caret.
1008       std::pair<FileID, unsigned> HintLocInfo
1009         = SM.getDecomposedExpansionLoc(I->RemoveRange.getBegin());
1010       if (LineNo == SM.getLineNumber(HintLocInfo.first, HintLocInfo.second) &&
1011           StringRef(I->CodeToInsert).find_first_of("\n\r") == StringRef::npos) {
1012         // Insert the new code into the line just below the code
1013         // that the user wrote.
1014         // Note: When modifying this function, be very careful about what is a
1015         // "column" (printed width, platform-dependent) and what is a
1016         // "byte offset" (SourceManager "column").
1017         unsigned HintByteOffset
1018           = SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second) - 1;
1019 
1020         // The hint must start inside the source or right at the end
1021         assert(HintByteOffset < static_cast<unsigned>(map.bytes())+1);
1022         unsigned HintCol = map.byteToContainingColumn(HintByteOffset);
1023 
1024         // If we inserted a long previous hint, push this one forwards, and add
1025         // an extra space to show that this is not part of the previous
1026         // completion. This is sort of the best we can do when two hints appear
1027         // to overlap.
1028         //
1029         // Note that if this hint is located immediately after the previous
1030         // hint, no space will be added, since the location is more important.
1031         if (HintCol < PrevHintEndCol)
1032           HintCol = PrevHintEndCol + 1;
1033 
1034         // This should NOT use HintByteOffset, because the source might have
1035         // Unicode characters in earlier columns.
1036         unsigned NewFixItLineSize = FixItInsertionLine.size() +
1037           (HintCol - PrevHintEndCol) + I->CodeToInsert.size();
1038         if (NewFixItLineSize > FixItInsertionLine.size())
1039           FixItInsertionLine.resize(NewFixItLineSize, ' ');
1040 
1041         std::copy(I->CodeToInsert.begin(), I->CodeToInsert.end(),
1042                   FixItInsertionLine.end() - I->CodeToInsert.size());
1043 
1044         PrevHintEndCol =
1045           HintCol + llvm::sys::locale::columnWidth(I->CodeToInsert);
1046       } else {
1047         FixItInsertionLine.clear();
1048         break;
1049       }
1050     }
1051   }
1052 
1053   expandTabs(FixItInsertionLine, DiagOpts->TabStop);
1054 
1055   return FixItInsertionLine;
1056 }
1057 
1058 /// \brief Emit a code snippet and caret line.
1059 ///
1060 /// This routine emits a single line's code snippet and caret line..
1061 ///
1062 /// \param Loc The location for the caret.
1063 /// \param Ranges The underlined ranges for this code snippet.
1064 /// \param Hints The FixIt hints active for this diagnostic.
1065 void TextDiagnostic::emitSnippetAndCaret(
1066     SourceLocation Loc, DiagnosticsEngine::Level Level,
1067     SmallVectorImpl<CharSourceRange>& Ranges,
1068     ArrayRef<FixItHint> Hints,
1069     const SourceManager &SM) {
1070   assert(Loc.isValid() && "must have a valid source location here");
1071   assert(Loc.isFileID() && "must have a file location here");
1072 
1073   // If caret diagnostics are enabled and we have location, we want to
1074   // emit the caret.  However, we only do this if the location moved
1075   // from the last diagnostic, if the last diagnostic was a note that
1076   // was part of a different warning or error diagnostic, or if the
1077   // diagnostic has ranges.  We don't want to emit the same caret
1078   // multiple times if one loc has multiple diagnostics.
1079   if (!DiagOpts->ShowCarets)
1080     return;
1081   if (Loc == LastLoc && Ranges.empty() && Hints.empty() &&
1082       (LastLevel != DiagnosticsEngine::Note || Level == LastLevel))
1083     return;
1084 
1085   // Decompose the location into a FID/Offset pair.
1086   std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1087   FileID FID = LocInfo.first;
1088   unsigned FileOffset = LocInfo.second;
1089 
1090   // Get information about the buffer it points into.
1091   bool Invalid = false;
1092   StringRef BufData = SM.getBufferData(FID, &Invalid);
1093   if (Invalid)
1094     return;
1095 
1096   const char *BufStart = BufData.data();
1097   const char *BufEnd = BufStart + BufData.size();
1098 
1099   unsigned LineNo = SM.getLineNumber(FID, FileOffset);
1100   unsigned ColNo = SM.getColumnNumber(FID, FileOffset);
1101 
1102   // Arbitrarily stop showing snippets when the line is too long.
1103   static const size_t MaxLineLengthToPrint = 4096;
1104   if (ColNo > MaxLineLengthToPrint)
1105     return;
1106 
1107   // Rewind from the current position to the start of the line.
1108   const char *TokPtr = BufStart+FileOffset;
1109   const char *LineStart = TokPtr-ColNo+1; // Column # is 1-based.
1110 
1111   // Compute the line end.  Scan forward from the error position to the end of
1112   // the line.
1113   const char *LineEnd = TokPtr;
1114   while (*LineEnd != '\n' && *LineEnd != '\r' && LineEnd != BufEnd)
1115     ++LineEnd;
1116 
1117   // Arbitrarily stop showing snippets when the line is too long.
1118   if (size_t(LineEnd - LineStart) > MaxLineLengthToPrint)
1119     return;
1120 
1121   // Trim trailing null-bytes.
1122   StringRef Line(LineStart, LineEnd - LineStart);
1123   while (Line.size() > ColNo && Line.back() == '\0')
1124     Line = Line.drop_back();
1125 
1126   // Copy the line of code into an std::string for ease of manipulation.
1127   std::string SourceLine(Line.begin(), Line.end());
1128 
1129   // Build the byte to column map.
1130   const SourceColumnMap sourceColMap(SourceLine, DiagOpts->TabStop);
1131 
1132   // Create a line for the caret that is filled with spaces that is the same
1133   // number of columns as the line of source code.
1134   std::string CaretLine(sourceColMap.columns(), ' ');
1135 
1136   // Highlight all of the characters covered by Ranges with ~ characters.
1137   for (SmallVectorImpl<CharSourceRange>::iterator I = Ranges.begin(),
1138                                                   E = Ranges.end();
1139        I != E; ++I)
1140     highlightRange(*I, LineNo, FID, sourceColMap, CaretLine, SM, LangOpts);
1141 
1142   // Next, insert the caret itself.
1143   ColNo = sourceColMap.byteToContainingColumn(ColNo-1);
1144   if (CaretLine.size()<ColNo+1)
1145     CaretLine.resize(ColNo+1, ' ');
1146   CaretLine[ColNo] = '^';
1147 
1148   std::string FixItInsertionLine = buildFixItInsertionLine(LineNo,
1149                                                            sourceColMap,
1150                                                            Hints, SM,
1151                                                            DiagOpts.get());
1152 
1153   // If the source line is too long for our terminal, select only the
1154   // "interesting" source region within that line.
1155   unsigned Columns = DiagOpts->MessageLength;
1156   if (Columns)
1157     selectInterestingSourceRegion(SourceLine, CaretLine, FixItInsertionLine,
1158                                   Columns, sourceColMap);
1159 
1160   // If we are in -fdiagnostics-print-source-range-info mode, we are trying
1161   // to produce easily machine parsable output.  Add a space before the
1162   // source line and the caret to make it trivial to tell the main diagnostic
1163   // line from what the user is intended to see.
1164   if (DiagOpts->ShowSourceRanges) {
1165     SourceLine = ' ' + SourceLine;
1166     CaretLine = ' ' + CaretLine;
1167   }
1168 
1169   // Finally, remove any blank spaces from the end of CaretLine.
1170   while (CaretLine[CaretLine.size()-1] == ' ')
1171     CaretLine.erase(CaretLine.end()-1);
1172 
1173   // Emit what we have computed.
1174   emitSnippet(SourceLine);
1175 
1176   if (DiagOpts->ShowColors)
1177     OS.changeColor(caretColor, true);
1178   OS << CaretLine << '\n';
1179   if (DiagOpts->ShowColors)
1180     OS.resetColor();
1181 
1182   if (!FixItInsertionLine.empty()) {
1183     if (DiagOpts->ShowColors)
1184       // Print fixit line in color
1185       OS.changeColor(fixitColor, false);
1186     if (DiagOpts->ShowSourceRanges)
1187       OS << ' ';
1188     OS << FixItInsertionLine << '\n';
1189     if (DiagOpts->ShowColors)
1190       OS.resetColor();
1191   }
1192 
1193   // Print out any parseable fixit information requested by the options.
1194   emitParseableFixits(Hints, SM);
1195 }
1196 
1197 void TextDiagnostic::emitSnippet(StringRef line) {
1198   if (line.empty())
1199     return;
1200 
1201   size_t i = 0;
1202 
1203   std::string to_print;
1204   bool print_reversed = false;
1205 
1206   while (i<line.size()) {
1207     std::pair<SmallString<16>,bool> res
1208         = printableTextForNextCharacter(line, &i, DiagOpts->TabStop);
1209     bool was_printable = res.second;
1210 
1211     if (DiagOpts->ShowColors && was_printable == print_reversed) {
1212       if (print_reversed)
1213         OS.reverseColor();
1214       OS << to_print;
1215       to_print.clear();
1216       if (DiagOpts->ShowColors)
1217         OS.resetColor();
1218     }
1219 
1220     print_reversed = !was_printable;
1221     to_print += res.first.str();
1222   }
1223 
1224   if (print_reversed && DiagOpts->ShowColors)
1225     OS.reverseColor();
1226   OS << to_print;
1227   if (print_reversed && DiagOpts->ShowColors)
1228     OS.resetColor();
1229 
1230   OS << '\n';
1231 }
1232 
1233 void TextDiagnostic::emitParseableFixits(ArrayRef<FixItHint> Hints,
1234                                          const SourceManager &SM) {
1235   if (!DiagOpts->ShowParseableFixits)
1236     return;
1237 
1238   // We follow FixItRewriter's example in not (yet) handling
1239   // fix-its in macros.
1240   for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1241        I != E; ++I) {
1242     if (I->RemoveRange.isInvalid() ||
1243         I->RemoveRange.getBegin().isMacroID() ||
1244         I->RemoveRange.getEnd().isMacroID())
1245       return;
1246   }
1247 
1248   for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1249        I != E; ++I) {
1250     SourceLocation BLoc = I->RemoveRange.getBegin();
1251     SourceLocation ELoc = I->RemoveRange.getEnd();
1252 
1253     std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(BLoc);
1254     std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(ELoc);
1255 
1256     // Adjust for token ranges.
1257     if (I->RemoveRange.isTokenRange())
1258       EInfo.second += Lexer::MeasureTokenLength(ELoc, SM, LangOpts);
1259 
1260     // We specifically do not do word-wrapping or tab-expansion here,
1261     // because this is supposed to be easy to parse.
1262     PresumedLoc PLoc = SM.getPresumedLoc(BLoc);
1263     if (PLoc.isInvalid())
1264       break;
1265 
1266     OS << "fix-it:\"";
1267     OS.write_escaped(PLoc.getFilename());
1268     OS << "\":{" << SM.getLineNumber(BInfo.first, BInfo.second)
1269       << ':' << SM.getColumnNumber(BInfo.first, BInfo.second)
1270       << '-' << SM.getLineNumber(EInfo.first, EInfo.second)
1271       << ':' << SM.getColumnNumber(EInfo.first, EInfo.second)
1272       << "}:\"";
1273     OS.write_escaped(I->CodeToInsert);
1274     OS << "\"\n";
1275   }
1276 }
1277