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