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