xref: /freebsd/contrib/llvm-project/clang/lib/Frontend/TextDiagnostic.cpp (revision 4542f901cb0c5dd66ab5b541f2fbc659fd46f893)
10b57cec5SDimitry Andric //===--- TextDiagnostic.cpp - Text Diagnostic Pretty-Printing -------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric 
90b57cec5SDimitry Andric #include "clang/Frontend/TextDiagnostic.h"
100b57cec5SDimitry Andric #include "clang/Basic/CharInfo.h"
110b57cec5SDimitry Andric #include "clang/Basic/DiagnosticOptions.h"
120b57cec5SDimitry Andric #include "clang/Basic/FileManager.h"
130b57cec5SDimitry Andric #include "clang/Basic/SourceManager.h"
140b57cec5SDimitry Andric #include "clang/Lex/Lexer.h"
150b57cec5SDimitry Andric #include "llvm/ADT/SmallString.h"
160b57cec5SDimitry Andric #include "llvm/ADT/StringExtras.h"
170b57cec5SDimitry Andric #include "llvm/Support/ConvertUTF.h"
180b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
190b57cec5SDimitry Andric #include "llvm/Support/Locale.h"
200b57cec5SDimitry Andric #include "llvm/Support/Path.h"
210b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
220b57cec5SDimitry Andric #include <algorithm>
23bdd1243dSDimitry Andric #include <optional>
240b57cec5SDimitry Andric 
250b57cec5SDimitry Andric using namespace clang;
260b57cec5SDimitry Andric 
270b57cec5SDimitry Andric static const enum raw_ostream::Colors noteColor =
280b57cec5SDimitry Andric   raw_ostream::BLACK;
290b57cec5SDimitry Andric static const enum raw_ostream::Colors remarkColor =
300b57cec5SDimitry Andric   raw_ostream::BLUE;
310b57cec5SDimitry Andric static const enum raw_ostream::Colors fixitColor =
320b57cec5SDimitry Andric   raw_ostream::GREEN;
330b57cec5SDimitry Andric static const enum raw_ostream::Colors caretColor =
340b57cec5SDimitry Andric   raw_ostream::GREEN;
350b57cec5SDimitry Andric static const enum raw_ostream::Colors warningColor =
360b57cec5SDimitry Andric   raw_ostream::MAGENTA;
370b57cec5SDimitry Andric static const enum raw_ostream::Colors templateColor =
380b57cec5SDimitry Andric   raw_ostream::CYAN;
390b57cec5SDimitry Andric static const enum raw_ostream::Colors errorColor = raw_ostream::RED;
400b57cec5SDimitry Andric static const enum raw_ostream::Colors fatalColor = raw_ostream::RED;
410b57cec5SDimitry Andric // Used for changing only the bold attribute.
420b57cec5SDimitry Andric static const enum raw_ostream::Colors savedColor =
430b57cec5SDimitry Andric   raw_ostream::SAVEDCOLOR;
440b57cec5SDimitry Andric 
450b57cec5SDimitry Andric /// Add highlights to differences in template strings.
460b57cec5SDimitry Andric static void applyTemplateHighlighting(raw_ostream &OS, StringRef Str,
470b57cec5SDimitry Andric                                       bool &Normal, bool Bold) {
4804eeddc0SDimitry Andric   while (true) {
490b57cec5SDimitry Andric     size_t Pos = Str.find(ToggleHighlight);
500b57cec5SDimitry Andric     OS << Str.slice(0, Pos);
510b57cec5SDimitry Andric     if (Pos == StringRef::npos)
520b57cec5SDimitry Andric       break;
530b57cec5SDimitry Andric 
540b57cec5SDimitry Andric     Str = Str.substr(Pos + 1);
550b57cec5SDimitry Andric     if (Normal)
560b57cec5SDimitry Andric       OS.changeColor(templateColor, true);
570b57cec5SDimitry Andric     else {
580b57cec5SDimitry Andric       OS.resetColor();
590b57cec5SDimitry Andric       if (Bold)
600b57cec5SDimitry Andric         OS.changeColor(savedColor, true);
610b57cec5SDimitry Andric     }
620b57cec5SDimitry Andric     Normal = !Normal;
630b57cec5SDimitry Andric   }
640b57cec5SDimitry Andric }
650b57cec5SDimitry Andric 
660b57cec5SDimitry Andric /// Number of spaces to indent when word-wrapping.
670b57cec5SDimitry Andric const unsigned WordWrapIndentation = 6;
680b57cec5SDimitry Andric 
690b57cec5SDimitry Andric static int bytesSincePreviousTabOrLineBegin(StringRef SourceLine, size_t i) {
700b57cec5SDimitry Andric   int bytes = 0;
710b57cec5SDimitry Andric   while (0<i) {
720b57cec5SDimitry Andric     if (SourceLine[--i]=='\t')
730b57cec5SDimitry Andric       break;
740b57cec5SDimitry Andric     ++bytes;
750b57cec5SDimitry Andric   }
760b57cec5SDimitry Andric   return bytes;
770b57cec5SDimitry Andric }
780b57cec5SDimitry Andric 
790b57cec5SDimitry Andric /// returns a printable representation of first item from input range
800b57cec5SDimitry Andric ///
810b57cec5SDimitry Andric /// This function returns a printable representation of the next item in a line
820b57cec5SDimitry Andric ///  of source. If the next byte begins a valid and printable character, that
830b57cec5SDimitry Andric ///  character is returned along with 'true'.
840b57cec5SDimitry Andric ///
850b57cec5SDimitry Andric /// Otherwise, if the next byte begins a valid, but unprintable character, a
860b57cec5SDimitry Andric ///  printable, escaped representation of the character is returned, along with
870b57cec5SDimitry Andric ///  'false'. Otherwise a printable, escaped representation of the next byte
880b57cec5SDimitry Andric ///  is returned along with 'false'.
890b57cec5SDimitry Andric ///
900b57cec5SDimitry Andric /// \note The index is updated to be used with a subsequent call to
910b57cec5SDimitry Andric ///        printableTextForNextCharacter.
920b57cec5SDimitry Andric ///
930b57cec5SDimitry Andric /// \param SourceLine The line of source
9406c3fb27SDimitry Andric /// \param I Pointer to byte index,
950b57cec5SDimitry Andric /// \param TabStop used to expand tabs
960b57cec5SDimitry Andric /// \return pair(printable text, 'true' iff original text was printable)
970b57cec5SDimitry Andric ///
980b57cec5SDimitry Andric static std::pair<SmallString<16>, bool>
9906c3fb27SDimitry Andric printableTextForNextCharacter(StringRef SourceLine, size_t *I,
1000b57cec5SDimitry Andric                               unsigned TabStop) {
10106c3fb27SDimitry Andric   assert(I && "I must not be null");
10206c3fb27SDimitry Andric   assert(*I < SourceLine.size() && "must point to a valid index");
1030b57cec5SDimitry Andric 
10406c3fb27SDimitry Andric   if (SourceLine[*I] == '\t') {
1050b57cec5SDimitry Andric     assert(0 < TabStop && TabStop <= DiagnosticOptions::MaxTabStop &&
1060b57cec5SDimitry Andric            "Invalid -ftabstop value");
10706c3fb27SDimitry Andric     unsigned Col = bytesSincePreviousTabOrLineBegin(SourceLine, *I);
10806c3fb27SDimitry Andric     unsigned NumSpaces = TabStop - (Col % TabStop);
1090b57cec5SDimitry Andric     assert(0 < NumSpaces && NumSpaces <= TabStop
1100b57cec5SDimitry Andric            && "Invalid computation of space amt");
11106c3fb27SDimitry Andric     ++(*I);
1120b57cec5SDimitry Andric 
11306c3fb27SDimitry Andric     SmallString<16> ExpandedTab;
11406c3fb27SDimitry Andric     ExpandedTab.assign(NumSpaces, ' ');
11506c3fb27SDimitry Andric     return std::make_pair(ExpandedTab, true);
1160b57cec5SDimitry Andric   }
1170b57cec5SDimitry Andric 
11806c3fb27SDimitry Andric   const unsigned char *Begin = SourceLine.bytes_begin() + *I;
1190b57cec5SDimitry Andric 
12006c3fb27SDimitry Andric   // Fast path for the common ASCII case.
12106c3fb27SDimitry Andric   if (*Begin < 0x80 && llvm::sys::locale::isPrint(*Begin)) {
12206c3fb27SDimitry Andric     ++(*I);
12306c3fb27SDimitry Andric     return std::make_pair(SmallString<16>(Begin, Begin + 1), true);
1240b57cec5SDimitry Andric   }
12506c3fb27SDimitry Andric   unsigned CharSize = llvm::getNumBytesForUTF8(*Begin);
12606c3fb27SDimitry Andric   const unsigned char *End = Begin + CharSize;
12706c3fb27SDimitry Andric 
12806c3fb27SDimitry Andric   // Convert it to UTF32 and check if it's printable.
12906c3fb27SDimitry Andric   if (End <= SourceLine.bytes_end() && llvm::isLegalUTF8Sequence(Begin, End)) {
13006c3fb27SDimitry Andric     llvm::UTF32 C;
13106c3fb27SDimitry Andric     llvm::UTF32 *CPtr = &C;
13206c3fb27SDimitry Andric 
13306c3fb27SDimitry Andric     // Begin and end before conversion.
13406c3fb27SDimitry Andric     unsigned char const *OriginalBegin = Begin;
13506c3fb27SDimitry Andric     llvm::ConversionResult Res = llvm::ConvertUTF8toUTF32(
13606c3fb27SDimitry Andric         &Begin, End, &CPtr, CPtr + 1, llvm::strictConversion);
13706c3fb27SDimitry Andric     (void)Res;
13806c3fb27SDimitry Andric     assert(Res == llvm::conversionOK);
13906c3fb27SDimitry Andric     assert(OriginalBegin < Begin);
14006c3fb27SDimitry Andric     assert((Begin - OriginalBegin) == CharSize);
14106c3fb27SDimitry Andric 
14206c3fb27SDimitry Andric     (*I) += (Begin - OriginalBegin);
14306c3fb27SDimitry Andric 
14406c3fb27SDimitry Andric     // Valid, multi-byte, printable UTF8 character.
14506c3fb27SDimitry Andric     if (llvm::sys::locale::isPrint(C))
14606c3fb27SDimitry Andric       return std::make_pair(SmallString<16>(OriginalBegin, End), true);
14706c3fb27SDimitry Andric 
14806c3fb27SDimitry Andric     // Valid but not printable.
14906c3fb27SDimitry Andric     SmallString<16> Str("<U+>");
15006c3fb27SDimitry Andric     while (C) {
15106c3fb27SDimitry Andric       Str.insert(Str.begin() + 3, llvm::hexdigit(C % 16));
15206c3fb27SDimitry Andric       C /= 16;
15306c3fb27SDimitry Andric     }
15406c3fb27SDimitry Andric     while (Str.size() < 8)
15506c3fb27SDimitry Andric       Str.insert(Str.begin() + 3, llvm::hexdigit(0));
15606c3fb27SDimitry Andric     return std::make_pair(Str, false);
1570b57cec5SDimitry Andric   }
1580b57cec5SDimitry Andric 
15906c3fb27SDimitry Andric   // Otherwise, not printable since it's not valid UTF8.
16006c3fb27SDimitry Andric   SmallString<16> ExpandedByte("<XX>");
16106c3fb27SDimitry Andric   unsigned char Byte = SourceLine[*I];
16206c3fb27SDimitry Andric   ExpandedByte[1] = llvm::hexdigit(Byte / 16);
16306c3fb27SDimitry Andric   ExpandedByte[2] = llvm::hexdigit(Byte % 16);
16406c3fb27SDimitry Andric   ++(*I);
16506c3fb27SDimitry Andric   return std::make_pair(ExpandedByte, false);
1660b57cec5SDimitry Andric }
1670b57cec5SDimitry Andric 
1680b57cec5SDimitry Andric static void expandTabs(std::string &SourceLine, unsigned TabStop) {
16906c3fb27SDimitry Andric   size_t I = SourceLine.size();
17006c3fb27SDimitry Andric   while (I > 0) {
17106c3fb27SDimitry Andric     I--;
17206c3fb27SDimitry Andric     if (SourceLine[I] != '\t')
1730b57cec5SDimitry Andric       continue;
17406c3fb27SDimitry Andric     size_t TmpI = I;
17506c3fb27SDimitry Andric     auto [Str, Printable] =
17606c3fb27SDimitry Andric         printableTextForNextCharacter(SourceLine, &TmpI, TabStop);
17706c3fb27SDimitry Andric     SourceLine.replace(I, 1, Str.c_str());
1780b57cec5SDimitry Andric   }
1790b57cec5SDimitry Andric }
1800b57cec5SDimitry Andric 
18106c3fb27SDimitry Andric /// \p BytesOut:
18206c3fb27SDimitry Andric ///  A mapping from columns to the byte of the source line that produced the
18306c3fb27SDimitry Andric ///  character displaying at that column. This is the inverse of \p ColumnsOut.
18406c3fb27SDimitry Andric ///
18506c3fb27SDimitry Andric /// The last element in the array is the number of bytes in the source string.
18606c3fb27SDimitry Andric ///
18706c3fb27SDimitry Andric /// example: (given a tabstop of 8)
18806c3fb27SDimitry Andric ///
18906c3fb27SDimitry Andric ///    "a \t \u3042" -> {0,1,2,-1,-1,-1,-1,-1,3,4,-1,7}
19006c3fb27SDimitry Andric ///
19106c3fb27SDimitry Andric ///  (\\u3042 is represented in UTF-8 by three bytes and takes two columns to
19206c3fb27SDimitry Andric ///   display)
19306c3fb27SDimitry Andric ///
19406c3fb27SDimitry Andric /// \p ColumnsOut:
19506c3fb27SDimitry Andric ///  A mapping from the bytes
1960b57cec5SDimitry Andric ///  of the printable representation of the line to the columns those printable
1970b57cec5SDimitry Andric ///  characters will appear at (numbering the first column as 0).
1980b57cec5SDimitry Andric ///
1990b57cec5SDimitry Andric /// If a byte 'i' corresponds to multiple columns (e.g. the byte contains a tab
2000b57cec5SDimitry Andric ///  character) then the array will map that byte to the first column the
2010b57cec5SDimitry Andric ///  tab appears at and the next value in the map will have been incremented
2020b57cec5SDimitry Andric ///  more than once.
2030b57cec5SDimitry Andric ///
2040b57cec5SDimitry Andric /// If a byte is the first in a sequence of bytes that together map to a single
2050b57cec5SDimitry Andric ///  entity in the output, then the array will map that byte to the appropriate
2060b57cec5SDimitry Andric ///  column while the subsequent bytes will be -1.
2070b57cec5SDimitry Andric ///
2080b57cec5SDimitry Andric /// The last element in the array does not correspond to any byte in the input
2090b57cec5SDimitry Andric ///  and instead is the number of columns needed to display the source
2100b57cec5SDimitry Andric ///
2110b57cec5SDimitry Andric /// example: (given a tabstop of 8)
2120b57cec5SDimitry Andric ///
2130b57cec5SDimitry Andric ///    "a \t \u3042" -> {0,1,2,8,9,-1,-1,11}
2140b57cec5SDimitry Andric ///
2150b57cec5SDimitry Andric ///  (\\u3042 is represented in UTF-8 by three bytes and takes two columns to
2160b57cec5SDimitry Andric ///   display)
21706c3fb27SDimitry Andric static void genColumnByteMapping(StringRef SourceLine, unsigned TabStop,
21806c3fb27SDimitry Andric                                  SmallVectorImpl<int> &BytesOut,
21906c3fb27SDimitry Andric                                  SmallVectorImpl<int> &ColumnsOut) {
22006c3fb27SDimitry Andric   assert(BytesOut.empty());
22106c3fb27SDimitry Andric   assert(ColumnsOut.empty());
2220b57cec5SDimitry Andric 
2230b57cec5SDimitry Andric   if (SourceLine.empty()) {
22406c3fb27SDimitry Andric     BytesOut.resize(1u, 0);
22506c3fb27SDimitry Andric     ColumnsOut.resize(1u, 0);
2260b57cec5SDimitry Andric     return;
2270b57cec5SDimitry Andric   }
2280b57cec5SDimitry Andric 
22906c3fb27SDimitry Andric   ColumnsOut.resize(SourceLine.size() + 1, -1);
2300b57cec5SDimitry Andric 
23106c3fb27SDimitry Andric   int Columns = 0;
23206c3fb27SDimitry Andric   size_t I = 0;
23306c3fb27SDimitry Andric   while (I < SourceLine.size()) {
23406c3fb27SDimitry Andric     ColumnsOut[I] = Columns;
23506c3fb27SDimitry Andric     BytesOut.resize(Columns + 1, -1);
23606c3fb27SDimitry Andric     BytesOut.back() = I;
23706c3fb27SDimitry Andric     auto [Str, Printable] =
23806c3fb27SDimitry Andric         printableTextForNextCharacter(SourceLine, &I, TabStop);
23906c3fb27SDimitry Andric     Columns += llvm::sys::locale::columnWidth(Str);
2400b57cec5SDimitry Andric   }
2410b57cec5SDimitry Andric 
24206c3fb27SDimitry Andric   ColumnsOut.back() = Columns;
24306c3fb27SDimitry Andric   BytesOut.resize(Columns + 1, -1);
24406c3fb27SDimitry Andric   BytesOut.back() = I;
2450b57cec5SDimitry Andric }
2460b57cec5SDimitry Andric 
2470b57cec5SDimitry Andric namespace {
2480b57cec5SDimitry Andric struct SourceColumnMap {
2490b57cec5SDimitry Andric   SourceColumnMap(StringRef SourceLine, unsigned TabStop)
2500b57cec5SDimitry Andric   : m_SourceLine(SourceLine) {
2510b57cec5SDimitry Andric 
25206c3fb27SDimitry Andric     genColumnByteMapping(SourceLine, TabStop, m_columnToByte, m_byteToColumn);
2530b57cec5SDimitry Andric 
2540b57cec5SDimitry Andric     assert(m_byteToColumn.size()==SourceLine.size()+1);
2550b57cec5SDimitry Andric     assert(0 < m_byteToColumn.size() && 0 < m_columnToByte.size());
2560b57cec5SDimitry Andric     assert(m_byteToColumn.size()
2570b57cec5SDimitry Andric            == static_cast<unsigned>(m_columnToByte.back()+1));
2580b57cec5SDimitry Andric     assert(static_cast<unsigned>(m_byteToColumn.back()+1)
2590b57cec5SDimitry Andric            == m_columnToByte.size());
2600b57cec5SDimitry Andric   }
2610b57cec5SDimitry Andric   int columns() const { return m_byteToColumn.back(); }
2620b57cec5SDimitry Andric   int bytes() const { return m_columnToByte.back(); }
2630b57cec5SDimitry Andric 
2640b57cec5SDimitry Andric   /// Map a byte to the column which it is at the start of, or return -1
2650b57cec5SDimitry Andric   /// if it is not at the start of a column (for a UTF-8 trailing byte).
2660b57cec5SDimitry Andric   int byteToColumn(int n) const {
2670b57cec5SDimitry Andric     assert(0<=n && n<static_cast<int>(m_byteToColumn.size()));
2680b57cec5SDimitry Andric     return m_byteToColumn[n];
2690b57cec5SDimitry Andric   }
2700b57cec5SDimitry Andric 
2710b57cec5SDimitry Andric   /// Map a byte to the first column which contains it.
2720b57cec5SDimitry Andric   int byteToContainingColumn(int N) const {
2730b57cec5SDimitry Andric     assert(0 <= N && N < static_cast<int>(m_byteToColumn.size()));
2740b57cec5SDimitry Andric     while (m_byteToColumn[N] == -1)
2750b57cec5SDimitry Andric       --N;
2760b57cec5SDimitry Andric     return m_byteToColumn[N];
2770b57cec5SDimitry Andric   }
2780b57cec5SDimitry Andric 
2790b57cec5SDimitry Andric   /// Map a column to the byte which starts the column, or return -1 if
2800b57cec5SDimitry Andric   /// the column the second or subsequent column of an expanded tab or similar
2810b57cec5SDimitry Andric   /// multi-column entity.
2820b57cec5SDimitry Andric   int columnToByte(int n) const {
2830b57cec5SDimitry Andric     assert(0<=n && n<static_cast<int>(m_columnToByte.size()));
2840b57cec5SDimitry Andric     return m_columnToByte[n];
2850b57cec5SDimitry Andric   }
2860b57cec5SDimitry Andric 
2870b57cec5SDimitry Andric   /// Map from a byte index to the next byte which starts a column.
2880b57cec5SDimitry Andric   int startOfNextColumn(int N) const {
2890b57cec5SDimitry Andric     assert(0 <= N && N < static_cast<int>(m_byteToColumn.size() - 1));
2900b57cec5SDimitry Andric     while (byteToColumn(++N) == -1) {}
2910b57cec5SDimitry Andric     return N;
2920b57cec5SDimitry Andric   }
2930b57cec5SDimitry Andric 
2940b57cec5SDimitry Andric   /// Map from a byte index to the previous byte which starts a column.
2950b57cec5SDimitry Andric   int startOfPreviousColumn(int N) const {
2960b57cec5SDimitry Andric     assert(0 < N && N < static_cast<int>(m_byteToColumn.size()));
2970b57cec5SDimitry Andric     while (byteToColumn(--N) == -1) {}
2980b57cec5SDimitry Andric     return N;
2990b57cec5SDimitry Andric   }
3000b57cec5SDimitry Andric 
3010b57cec5SDimitry Andric   StringRef getSourceLine() const {
3020b57cec5SDimitry Andric     return m_SourceLine;
3030b57cec5SDimitry Andric   }
3040b57cec5SDimitry Andric 
3050b57cec5SDimitry Andric private:
3060b57cec5SDimitry Andric   const std::string m_SourceLine;
3070b57cec5SDimitry Andric   SmallVector<int,200> m_byteToColumn;
3080b57cec5SDimitry Andric   SmallVector<int,200> m_columnToByte;
3090b57cec5SDimitry Andric };
3100b57cec5SDimitry Andric } // end anonymous namespace
3110b57cec5SDimitry Andric 
3120b57cec5SDimitry Andric /// When the source code line we want to print is too long for
3130b57cec5SDimitry Andric /// the terminal, select the "interesting" region.
3140b57cec5SDimitry Andric static void selectInterestingSourceRegion(std::string &SourceLine,
3150b57cec5SDimitry Andric                                           std::string &CaretLine,
3160b57cec5SDimitry Andric                                           std::string &FixItInsertionLine,
3170b57cec5SDimitry Andric                                           unsigned Columns,
3180b57cec5SDimitry Andric                                           const SourceColumnMap &map) {
3190b57cec5SDimitry Andric   unsigned CaretColumns = CaretLine.size();
3200b57cec5SDimitry Andric   unsigned FixItColumns = llvm::sys::locale::columnWidth(FixItInsertionLine);
3210b57cec5SDimitry Andric   unsigned MaxColumns = std::max(static_cast<unsigned>(map.columns()),
3220b57cec5SDimitry Andric                                  std::max(CaretColumns, FixItColumns));
3230b57cec5SDimitry Andric   // if the number of columns is less than the desired number we're done
3240b57cec5SDimitry Andric   if (MaxColumns <= Columns)
3250b57cec5SDimitry Andric     return;
3260b57cec5SDimitry Andric 
3270b57cec5SDimitry Andric   // No special characters are allowed in CaretLine.
328bdd1243dSDimitry Andric   assert(llvm::none_of(CaretLine, [](char c) { return c < ' ' || '~' < c; }));
3290b57cec5SDimitry Andric 
3300b57cec5SDimitry Andric   // Find the slice that we need to display the full caret line
3310b57cec5SDimitry Andric   // correctly.
3320b57cec5SDimitry Andric   unsigned CaretStart = 0, CaretEnd = CaretLine.size();
3330b57cec5SDimitry Andric   for (; CaretStart != CaretEnd; ++CaretStart)
3340b57cec5SDimitry Andric     if (!isWhitespace(CaretLine[CaretStart]))
3350b57cec5SDimitry Andric       break;
3360b57cec5SDimitry Andric 
3370b57cec5SDimitry Andric   for (; CaretEnd != CaretStart; --CaretEnd)
3380b57cec5SDimitry Andric     if (!isWhitespace(CaretLine[CaretEnd - 1]))
3390b57cec5SDimitry Andric       break;
3400b57cec5SDimitry Andric 
3410b57cec5SDimitry Andric   // caret has already been inserted into CaretLine so the above whitespace
3420b57cec5SDimitry Andric   // check is guaranteed to include the caret
3430b57cec5SDimitry Andric 
3440b57cec5SDimitry Andric   // If we have a fix-it line, make sure the slice includes all of the
3450b57cec5SDimitry Andric   // fix-it information.
3460b57cec5SDimitry Andric   if (!FixItInsertionLine.empty()) {
3470b57cec5SDimitry Andric     unsigned FixItStart = 0, FixItEnd = FixItInsertionLine.size();
3480b57cec5SDimitry Andric     for (; FixItStart != FixItEnd; ++FixItStart)
3490b57cec5SDimitry Andric       if (!isWhitespace(FixItInsertionLine[FixItStart]))
3500b57cec5SDimitry Andric         break;
3510b57cec5SDimitry Andric 
3520b57cec5SDimitry Andric     for (; FixItEnd != FixItStart; --FixItEnd)
3530b57cec5SDimitry Andric       if (!isWhitespace(FixItInsertionLine[FixItEnd - 1]))
3540b57cec5SDimitry Andric         break;
3550b57cec5SDimitry Andric 
3560b57cec5SDimitry Andric     // We can safely use the byte offset FixItStart as the column offset
3570b57cec5SDimitry Andric     // because the characters up until FixItStart are all ASCII whitespace
3580b57cec5SDimitry Andric     // characters.
3590b57cec5SDimitry Andric     unsigned FixItStartCol = FixItStart;
3600b57cec5SDimitry Andric     unsigned FixItEndCol
3610b57cec5SDimitry Andric       = llvm::sys::locale::columnWidth(FixItInsertionLine.substr(0, FixItEnd));
3620b57cec5SDimitry Andric 
3630b57cec5SDimitry Andric     CaretStart = std::min(FixItStartCol, CaretStart);
3640b57cec5SDimitry Andric     CaretEnd = std::max(FixItEndCol, CaretEnd);
3650b57cec5SDimitry Andric   }
3660b57cec5SDimitry Andric 
3670b57cec5SDimitry Andric   // CaretEnd may have been set at the middle of a character
3680b57cec5SDimitry Andric   // If it's not at a character's first column then advance it past the current
3690b57cec5SDimitry Andric   //   character.
3700b57cec5SDimitry Andric   while (static_cast<int>(CaretEnd) < map.columns() &&
3710b57cec5SDimitry Andric          -1 == map.columnToByte(CaretEnd))
3720b57cec5SDimitry Andric     ++CaretEnd;
3730b57cec5SDimitry Andric 
3740b57cec5SDimitry Andric   assert((static_cast<int>(CaretStart) > map.columns() ||
3750b57cec5SDimitry Andric           -1!=map.columnToByte(CaretStart)) &&
3760b57cec5SDimitry Andric          "CaretStart must not point to a column in the middle of a source"
3770b57cec5SDimitry Andric          " line character");
3780b57cec5SDimitry Andric   assert((static_cast<int>(CaretEnd) > map.columns() ||
3790b57cec5SDimitry Andric           -1!=map.columnToByte(CaretEnd)) &&
3800b57cec5SDimitry Andric          "CaretEnd must not point to a column in the middle of a source line"
3810b57cec5SDimitry Andric          " character");
3820b57cec5SDimitry Andric 
3830b57cec5SDimitry Andric   // CaretLine[CaretStart, CaretEnd) contains all of the interesting
3840b57cec5SDimitry Andric   // parts of the caret line. While this slice is smaller than the
3850b57cec5SDimitry Andric   // number of columns we have, try to grow the slice to encompass
3860b57cec5SDimitry Andric   // more context.
3870b57cec5SDimitry Andric 
3880b57cec5SDimitry Andric   unsigned SourceStart = map.columnToByte(std::min<unsigned>(CaretStart,
3890b57cec5SDimitry Andric                                                              map.columns()));
3900b57cec5SDimitry Andric   unsigned SourceEnd = map.columnToByte(std::min<unsigned>(CaretEnd,
3910b57cec5SDimitry Andric                                                            map.columns()));
3920b57cec5SDimitry Andric 
3930b57cec5SDimitry Andric   unsigned CaretColumnsOutsideSource = CaretEnd-CaretStart
3940b57cec5SDimitry Andric     - (map.byteToColumn(SourceEnd)-map.byteToColumn(SourceStart));
3950b57cec5SDimitry Andric 
3960b57cec5SDimitry Andric   char const *front_ellipse = "  ...";
3970b57cec5SDimitry Andric   char const *front_space   = "     ";
3980b57cec5SDimitry Andric   char const *back_ellipse = "...";
3990b57cec5SDimitry Andric   unsigned ellipses_space = strlen(front_ellipse) + strlen(back_ellipse);
4000b57cec5SDimitry Andric 
4010b57cec5SDimitry Andric   unsigned TargetColumns = Columns;
4020b57cec5SDimitry Andric   // Give us extra room for the ellipses
4030b57cec5SDimitry Andric   //  and any of the caret line that extends past the source
4040b57cec5SDimitry Andric   if (TargetColumns > ellipses_space+CaretColumnsOutsideSource)
4050b57cec5SDimitry Andric     TargetColumns -= ellipses_space+CaretColumnsOutsideSource;
4060b57cec5SDimitry Andric 
4070b57cec5SDimitry Andric   while (SourceStart>0 || SourceEnd<SourceLine.size()) {
4080b57cec5SDimitry Andric     bool ExpandedRegion = false;
4090b57cec5SDimitry Andric 
4100b57cec5SDimitry Andric     if (SourceStart>0) {
4110b57cec5SDimitry Andric       unsigned NewStart = map.startOfPreviousColumn(SourceStart);
4120b57cec5SDimitry Andric 
4130b57cec5SDimitry Andric       // Skip over any whitespace we see here; we're looking for
4140b57cec5SDimitry Andric       // another bit of interesting text.
4150b57cec5SDimitry Andric       // FIXME: Detect non-ASCII whitespace characters too.
4160b57cec5SDimitry Andric       while (NewStart && isWhitespace(SourceLine[NewStart]))
4170b57cec5SDimitry Andric         NewStart = map.startOfPreviousColumn(NewStart);
4180b57cec5SDimitry Andric 
4190b57cec5SDimitry Andric       // Skip over this bit of "interesting" text.
4200b57cec5SDimitry Andric       while (NewStart) {
4210b57cec5SDimitry Andric         unsigned Prev = map.startOfPreviousColumn(NewStart);
4220b57cec5SDimitry Andric         if (isWhitespace(SourceLine[Prev]))
4230b57cec5SDimitry Andric           break;
4240b57cec5SDimitry Andric         NewStart = Prev;
4250b57cec5SDimitry Andric       }
4260b57cec5SDimitry Andric 
4270b57cec5SDimitry Andric       assert(map.byteToColumn(NewStart) != -1);
4280b57cec5SDimitry Andric       unsigned NewColumns = map.byteToColumn(SourceEnd) -
4290b57cec5SDimitry Andric                               map.byteToColumn(NewStart);
4300b57cec5SDimitry Andric       if (NewColumns <= TargetColumns) {
4310b57cec5SDimitry Andric         SourceStart = NewStart;
4320b57cec5SDimitry Andric         ExpandedRegion = true;
4330b57cec5SDimitry Andric       }
4340b57cec5SDimitry Andric     }
4350b57cec5SDimitry Andric 
4360b57cec5SDimitry Andric     if (SourceEnd<SourceLine.size()) {
4370b57cec5SDimitry Andric       unsigned NewEnd = map.startOfNextColumn(SourceEnd);
4380b57cec5SDimitry Andric 
4390b57cec5SDimitry Andric       // Skip over any whitespace we see here; we're looking for
4400b57cec5SDimitry Andric       // another bit of interesting text.
4410b57cec5SDimitry Andric       // FIXME: Detect non-ASCII whitespace characters too.
4420b57cec5SDimitry Andric       while (NewEnd < SourceLine.size() && isWhitespace(SourceLine[NewEnd]))
4430b57cec5SDimitry Andric         NewEnd = map.startOfNextColumn(NewEnd);
4440b57cec5SDimitry Andric 
4450b57cec5SDimitry Andric       // Skip over this bit of "interesting" text.
4460b57cec5SDimitry Andric       while (NewEnd < SourceLine.size() && isWhitespace(SourceLine[NewEnd]))
4470b57cec5SDimitry Andric         NewEnd = map.startOfNextColumn(NewEnd);
4480b57cec5SDimitry Andric 
4490b57cec5SDimitry Andric       assert(map.byteToColumn(NewEnd) != -1);
4500b57cec5SDimitry Andric       unsigned NewColumns = map.byteToColumn(NewEnd) -
4510b57cec5SDimitry Andric                               map.byteToColumn(SourceStart);
4520b57cec5SDimitry Andric       if (NewColumns <= TargetColumns) {
4530b57cec5SDimitry Andric         SourceEnd = NewEnd;
4540b57cec5SDimitry Andric         ExpandedRegion = true;
4550b57cec5SDimitry Andric       }
4560b57cec5SDimitry Andric     }
4570b57cec5SDimitry Andric 
4580b57cec5SDimitry Andric     if (!ExpandedRegion)
4590b57cec5SDimitry Andric       break;
4600b57cec5SDimitry Andric   }
4610b57cec5SDimitry Andric 
4620b57cec5SDimitry Andric   CaretStart = map.byteToColumn(SourceStart);
4630b57cec5SDimitry Andric   CaretEnd = map.byteToColumn(SourceEnd) + CaretColumnsOutsideSource;
4640b57cec5SDimitry Andric 
4650b57cec5SDimitry Andric   // [CaretStart, CaretEnd) is the slice we want. Update the various
46606c3fb27SDimitry Andric   // output lines to show only this slice.
4670b57cec5SDimitry Andric   assert(CaretStart!=(unsigned)-1 && CaretEnd!=(unsigned)-1 &&
4680b57cec5SDimitry Andric          SourceStart!=(unsigned)-1 && SourceEnd!=(unsigned)-1);
4690b57cec5SDimitry Andric   assert(SourceStart <= SourceEnd);
4700b57cec5SDimitry Andric   assert(CaretStart <= CaretEnd);
4710b57cec5SDimitry Andric 
4720b57cec5SDimitry Andric   unsigned BackColumnsRemoved
4730b57cec5SDimitry Andric     = map.byteToColumn(SourceLine.size())-map.byteToColumn(SourceEnd);
4740b57cec5SDimitry Andric   unsigned FrontColumnsRemoved = CaretStart;
4750b57cec5SDimitry Andric   unsigned ColumnsKept = CaretEnd-CaretStart;
4760b57cec5SDimitry Andric 
4770b57cec5SDimitry Andric   // We checked up front that the line needed truncation
4780b57cec5SDimitry Andric   assert(FrontColumnsRemoved+ColumnsKept+BackColumnsRemoved > Columns);
4790b57cec5SDimitry Andric 
4800b57cec5SDimitry Andric   // The line needs some truncation, and we'd prefer to keep the front
4810b57cec5SDimitry Andric   //  if possible, so remove the back
4820b57cec5SDimitry Andric   if (BackColumnsRemoved > strlen(back_ellipse))
4830b57cec5SDimitry Andric     SourceLine.replace(SourceEnd, std::string::npos, back_ellipse);
4840b57cec5SDimitry Andric 
4850b57cec5SDimitry Andric   // If that's enough then we're done
4860b57cec5SDimitry Andric   if (FrontColumnsRemoved+ColumnsKept <= Columns)
4870b57cec5SDimitry Andric     return;
4880b57cec5SDimitry Andric 
4890b57cec5SDimitry Andric   // Otherwise remove the front as well
4900b57cec5SDimitry Andric   if (FrontColumnsRemoved > strlen(front_ellipse)) {
4910b57cec5SDimitry Andric     SourceLine.replace(0, SourceStart, front_ellipse);
4920b57cec5SDimitry Andric     CaretLine.replace(0, CaretStart, front_space);
4930b57cec5SDimitry Andric     if (!FixItInsertionLine.empty())
4940b57cec5SDimitry Andric       FixItInsertionLine.replace(0, CaretStart, front_space);
4950b57cec5SDimitry Andric   }
4960b57cec5SDimitry Andric }
4970b57cec5SDimitry Andric 
4980b57cec5SDimitry Andric /// Skip over whitespace in the string, starting at the given
4990b57cec5SDimitry Andric /// index.
5000b57cec5SDimitry Andric ///
5010b57cec5SDimitry Andric /// \returns The index of the first non-whitespace character that is
5020b57cec5SDimitry Andric /// greater than or equal to Idx or, if no such character exists,
5030b57cec5SDimitry Andric /// returns the end of the string.
5040b57cec5SDimitry Andric static unsigned skipWhitespace(unsigned Idx, StringRef Str, unsigned Length) {
5050b57cec5SDimitry Andric   while (Idx < Length && isWhitespace(Str[Idx]))
5060b57cec5SDimitry Andric     ++Idx;
5070b57cec5SDimitry Andric   return Idx;
5080b57cec5SDimitry Andric }
5090b57cec5SDimitry Andric 
5100b57cec5SDimitry Andric /// If the given character is the start of some kind of
5110b57cec5SDimitry Andric /// balanced punctuation (e.g., quotes or parentheses), return the
5120b57cec5SDimitry Andric /// character that will terminate the punctuation.
5130b57cec5SDimitry Andric ///
5140b57cec5SDimitry Andric /// \returns The ending punctuation character, if any, or the NULL
5150b57cec5SDimitry Andric /// character if the input character does not start any punctuation.
5160b57cec5SDimitry Andric static inline char findMatchingPunctuation(char c) {
5170b57cec5SDimitry Andric   switch (c) {
5180b57cec5SDimitry Andric   case '\'': return '\'';
5190b57cec5SDimitry Andric   case '`': return '\'';
5200b57cec5SDimitry Andric   case '"':  return '"';
5210b57cec5SDimitry Andric   case '(':  return ')';
5220b57cec5SDimitry Andric   case '[': return ']';
5230b57cec5SDimitry Andric   case '{': return '}';
5240b57cec5SDimitry Andric   default: break;
5250b57cec5SDimitry Andric   }
5260b57cec5SDimitry Andric 
5270b57cec5SDimitry Andric   return 0;
5280b57cec5SDimitry Andric }
5290b57cec5SDimitry Andric 
5300b57cec5SDimitry Andric /// Find the end of the word starting at the given offset
5310b57cec5SDimitry Andric /// within a string.
5320b57cec5SDimitry Andric ///
5330b57cec5SDimitry Andric /// \returns the index pointing one character past the end of the
5340b57cec5SDimitry Andric /// word.
5350b57cec5SDimitry Andric static unsigned findEndOfWord(unsigned Start, StringRef Str,
5360b57cec5SDimitry Andric                               unsigned Length, unsigned Column,
5370b57cec5SDimitry Andric                               unsigned Columns) {
5380b57cec5SDimitry Andric   assert(Start < Str.size() && "Invalid start position!");
5390b57cec5SDimitry Andric   unsigned End = Start + 1;
5400b57cec5SDimitry Andric 
5410b57cec5SDimitry Andric   // If we are already at the end of the string, take that as the word.
5420b57cec5SDimitry Andric   if (End == Str.size())
5430b57cec5SDimitry Andric     return End;
5440b57cec5SDimitry Andric 
5450b57cec5SDimitry Andric   // Determine if the start of the string is actually opening
5460b57cec5SDimitry Andric   // punctuation, e.g., a quote or parentheses.
5470b57cec5SDimitry Andric   char EndPunct = findMatchingPunctuation(Str[Start]);
5480b57cec5SDimitry Andric   if (!EndPunct) {
5490b57cec5SDimitry Andric     // This is a normal word. Just find the first space character.
5500b57cec5SDimitry Andric     while (End < Length && !isWhitespace(Str[End]))
5510b57cec5SDimitry Andric       ++End;
5520b57cec5SDimitry Andric     return End;
5530b57cec5SDimitry Andric   }
5540b57cec5SDimitry Andric 
5550b57cec5SDimitry Andric   // We have the start of a balanced punctuation sequence (quotes,
5560b57cec5SDimitry Andric   // parentheses, etc.). Determine the full sequence is.
5570b57cec5SDimitry Andric   SmallString<16> PunctuationEndStack;
5580b57cec5SDimitry Andric   PunctuationEndStack.push_back(EndPunct);
5590b57cec5SDimitry Andric   while (End < Length && !PunctuationEndStack.empty()) {
5600b57cec5SDimitry Andric     if (Str[End] == PunctuationEndStack.back())
5610b57cec5SDimitry Andric       PunctuationEndStack.pop_back();
5620b57cec5SDimitry Andric     else if (char SubEndPunct = findMatchingPunctuation(Str[End]))
5630b57cec5SDimitry Andric       PunctuationEndStack.push_back(SubEndPunct);
5640b57cec5SDimitry Andric 
5650b57cec5SDimitry Andric     ++End;
5660b57cec5SDimitry Andric   }
5670b57cec5SDimitry Andric 
5680b57cec5SDimitry Andric   // Find the first space character after the punctuation ended.
5690b57cec5SDimitry Andric   while (End < Length && !isWhitespace(Str[End]))
5700b57cec5SDimitry Andric     ++End;
5710b57cec5SDimitry Andric 
5720b57cec5SDimitry Andric   unsigned PunctWordLength = End - Start;
5730b57cec5SDimitry Andric   if (// If the word fits on this line
5740b57cec5SDimitry Andric       Column + PunctWordLength <= Columns ||
5750b57cec5SDimitry Andric       // ... or the word is "short enough" to take up the next line
5760b57cec5SDimitry Andric       // without too much ugly white space
5770b57cec5SDimitry Andric       PunctWordLength < Columns/3)
5780b57cec5SDimitry Andric     return End; // Take the whole thing as a single "word".
5790b57cec5SDimitry Andric 
5800b57cec5SDimitry Andric   // The whole quoted/parenthesized string is too long to print as a
5810b57cec5SDimitry Andric   // single "word". Instead, find the "word" that starts just after
5820b57cec5SDimitry Andric   // the punctuation and use that end-point instead. This will recurse
5830b57cec5SDimitry Andric   // until it finds something small enough to consider a word.
5840b57cec5SDimitry Andric   return findEndOfWord(Start + 1, Str, Length, Column + 1, Columns);
5850b57cec5SDimitry Andric }
5860b57cec5SDimitry Andric 
5870b57cec5SDimitry Andric /// Print the given string to a stream, word-wrapping it to
5880b57cec5SDimitry Andric /// some number of columns in the process.
5890b57cec5SDimitry Andric ///
5900b57cec5SDimitry Andric /// \param OS the stream to which the word-wrapping string will be
5910b57cec5SDimitry Andric /// emitted.
5920b57cec5SDimitry Andric /// \param Str the string to word-wrap and output.
5930b57cec5SDimitry Andric /// \param Columns the number of columns to word-wrap to.
5940b57cec5SDimitry Andric /// \param Column the column number at which the first character of \p
5950b57cec5SDimitry Andric /// Str will be printed. This will be non-zero when part of the first
5960b57cec5SDimitry Andric /// line has already been printed.
5970b57cec5SDimitry Andric /// \param Bold if the current text should be bold
5980b57cec5SDimitry Andric /// \returns true if word-wrapping was required, or false if the
5990b57cec5SDimitry Andric /// string fit on the first line.
60006c3fb27SDimitry Andric static bool printWordWrapped(raw_ostream &OS, StringRef Str, unsigned Columns,
60106c3fb27SDimitry Andric                              unsigned Column, bool Bold) {
6020b57cec5SDimitry Andric   const unsigned Length = std::min(Str.find('\n'), Str.size());
6030b57cec5SDimitry Andric   bool TextNormal = true;
6040b57cec5SDimitry Andric 
6050b57cec5SDimitry Andric   bool Wrapped = false;
6060b57cec5SDimitry Andric   for (unsigned WordStart = 0, WordEnd; WordStart < Length;
6070b57cec5SDimitry Andric        WordStart = WordEnd) {
6080b57cec5SDimitry Andric     // Find the beginning of the next word.
6090b57cec5SDimitry Andric     WordStart = skipWhitespace(WordStart, Str, Length);
6100b57cec5SDimitry Andric     if (WordStart == Length)
6110b57cec5SDimitry Andric       break;
6120b57cec5SDimitry Andric 
6130b57cec5SDimitry Andric     // Find the end of this word.
6140b57cec5SDimitry Andric     WordEnd = findEndOfWord(WordStart, Str, Length, Column, Columns);
6150b57cec5SDimitry Andric 
6160b57cec5SDimitry Andric     // Does this word fit on the current line?
6170b57cec5SDimitry Andric     unsigned WordLength = WordEnd - WordStart;
6180b57cec5SDimitry Andric     if (Column + WordLength < Columns) {
6190b57cec5SDimitry Andric       // This word fits on the current line; print it there.
6200b57cec5SDimitry Andric       if (WordStart) {
6210b57cec5SDimitry Andric         OS << ' ';
6220b57cec5SDimitry Andric         Column += 1;
6230b57cec5SDimitry Andric       }
6240b57cec5SDimitry Andric       applyTemplateHighlighting(OS, Str.substr(WordStart, WordLength),
6250b57cec5SDimitry Andric                                 TextNormal, Bold);
6260b57cec5SDimitry Andric       Column += WordLength;
6270b57cec5SDimitry Andric       continue;
6280b57cec5SDimitry Andric     }
6290b57cec5SDimitry Andric 
6300b57cec5SDimitry Andric     // This word does not fit on the current line, so wrap to the next
6310b57cec5SDimitry Andric     // line.
6320b57cec5SDimitry Andric     OS << '\n';
63306c3fb27SDimitry Andric     OS.indent(WordWrapIndentation);
6340b57cec5SDimitry Andric     applyTemplateHighlighting(OS, Str.substr(WordStart, WordLength),
6350b57cec5SDimitry Andric                               TextNormal, Bold);
63606c3fb27SDimitry Andric     Column = WordWrapIndentation + WordLength;
6370b57cec5SDimitry Andric     Wrapped = true;
6380b57cec5SDimitry Andric   }
6390b57cec5SDimitry Andric 
6400b57cec5SDimitry Andric   // Append any remaning text from the message with its existing formatting.
6410b57cec5SDimitry Andric   applyTemplateHighlighting(OS, Str.substr(Length), TextNormal, Bold);
6420b57cec5SDimitry Andric 
6430b57cec5SDimitry Andric   assert(TextNormal && "Text highlighted at end of diagnostic message.");
6440b57cec5SDimitry Andric 
6450b57cec5SDimitry Andric   return Wrapped;
6460b57cec5SDimitry Andric }
6470b57cec5SDimitry Andric 
6480b57cec5SDimitry Andric TextDiagnostic::TextDiagnostic(raw_ostream &OS,
6490b57cec5SDimitry Andric                                const LangOptions &LangOpts,
6500b57cec5SDimitry Andric                                DiagnosticOptions *DiagOpts)
6510b57cec5SDimitry Andric   : DiagnosticRenderer(LangOpts, DiagOpts), OS(OS) {}
6520b57cec5SDimitry Andric 
6530b57cec5SDimitry Andric TextDiagnostic::~TextDiagnostic() {}
6540b57cec5SDimitry Andric 
6550b57cec5SDimitry Andric void TextDiagnostic::emitDiagnosticMessage(
6560b57cec5SDimitry Andric     FullSourceLoc Loc, PresumedLoc PLoc, DiagnosticsEngine::Level Level,
6570b57cec5SDimitry Andric     StringRef Message, ArrayRef<clang::CharSourceRange> Ranges,
6580b57cec5SDimitry Andric     DiagOrStoredDiag D) {
6590b57cec5SDimitry Andric   uint64_t StartOfLocationInfo = OS.tell();
6600b57cec5SDimitry Andric 
6610b57cec5SDimitry Andric   // Emit the location of this particular diagnostic.
6620b57cec5SDimitry Andric   if (Loc.isValid())
6630b57cec5SDimitry Andric     emitDiagnosticLoc(Loc, PLoc, Level, Ranges);
6640b57cec5SDimitry Andric 
6650b57cec5SDimitry Andric   if (DiagOpts->ShowColors)
6660b57cec5SDimitry Andric     OS.resetColor();
6670b57cec5SDimitry Andric 
668a7dea167SDimitry Andric   if (DiagOpts->ShowLevel)
669fe6060f1SDimitry Andric     printDiagnosticLevel(OS, Level, DiagOpts->ShowColors);
6700b57cec5SDimitry Andric   printDiagnosticMessage(OS,
6710b57cec5SDimitry Andric                          /*IsSupplemental*/ Level == DiagnosticsEngine::Note,
6720b57cec5SDimitry Andric                          Message, OS.tell() - StartOfLocationInfo,
6730b57cec5SDimitry Andric                          DiagOpts->MessageLength, DiagOpts->ShowColors);
6740b57cec5SDimitry Andric }
6750b57cec5SDimitry Andric 
6760b57cec5SDimitry Andric /*static*/ void
6770b57cec5SDimitry Andric TextDiagnostic::printDiagnosticLevel(raw_ostream &OS,
6780b57cec5SDimitry Andric                                      DiagnosticsEngine::Level Level,
679fe6060f1SDimitry Andric                                      bool ShowColors) {
6800b57cec5SDimitry Andric   if (ShowColors) {
6810b57cec5SDimitry Andric     // Print diagnostic category in bold and color
6820b57cec5SDimitry Andric     switch (Level) {
6830b57cec5SDimitry Andric     case DiagnosticsEngine::Ignored:
6840b57cec5SDimitry Andric       llvm_unreachable("Invalid diagnostic type");
6850b57cec5SDimitry Andric     case DiagnosticsEngine::Note:    OS.changeColor(noteColor, true); break;
6860b57cec5SDimitry Andric     case DiagnosticsEngine::Remark:  OS.changeColor(remarkColor, true); break;
6870b57cec5SDimitry Andric     case DiagnosticsEngine::Warning: OS.changeColor(warningColor, true); break;
6880b57cec5SDimitry Andric     case DiagnosticsEngine::Error:   OS.changeColor(errorColor, true); break;
6890b57cec5SDimitry Andric     case DiagnosticsEngine::Fatal:   OS.changeColor(fatalColor, true); break;
6900b57cec5SDimitry Andric     }
6910b57cec5SDimitry Andric   }
6920b57cec5SDimitry Andric 
6930b57cec5SDimitry Andric   switch (Level) {
6940b57cec5SDimitry Andric   case DiagnosticsEngine::Ignored:
6950b57cec5SDimitry Andric     llvm_unreachable("Invalid diagnostic type");
696fe6060f1SDimitry Andric   case DiagnosticsEngine::Note:    OS << "note: "; break;
697fe6060f1SDimitry Andric   case DiagnosticsEngine::Remark:  OS << "remark: "; break;
698fe6060f1SDimitry Andric   case DiagnosticsEngine::Warning: OS << "warning: "; break;
699fe6060f1SDimitry Andric   case DiagnosticsEngine::Error:   OS << "error: "; break;
700fe6060f1SDimitry Andric   case DiagnosticsEngine::Fatal:   OS << "fatal error: "; break;
7010b57cec5SDimitry Andric   }
7020b57cec5SDimitry Andric 
7030b57cec5SDimitry Andric   if (ShowColors)
7040b57cec5SDimitry Andric     OS.resetColor();
7050b57cec5SDimitry Andric }
7060b57cec5SDimitry Andric 
7070b57cec5SDimitry Andric /*static*/
7080b57cec5SDimitry Andric void TextDiagnostic::printDiagnosticMessage(raw_ostream &OS,
7090b57cec5SDimitry Andric                                             bool IsSupplemental,
7100b57cec5SDimitry Andric                                             StringRef Message,
7110b57cec5SDimitry Andric                                             unsigned CurrentColumn,
7120b57cec5SDimitry Andric                                             unsigned Columns, bool ShowColors) {
7130b57cec5SDimitry Andric   bool Bold = false;
7140b57cec5SDimitry Andric   if (ShowColors && !IsSupplemental) {
7150b57cec5SDimitry Andric     // Print primary diagnostic messages in bold and without color, to visually
7160b57cec5SDimitry Andric     // indicate the transition from continuation notes and other output.
7170b57cec5SDimitry Andric     OS.changeColor(savedColor, true);
7180b57cec5SDimitry Andric     Bold = true;
7190b57cec5SDimitry Andric   }
7200b57cec5SDimitry Andric 
7210b57cec5SDimitry Andric   if (Columns)
7220b57cec5SDimitry Andric     printWordWrapped(OS, Message, Columns, CurrentColumn, Bold);
7230b57cec5SDimitry Andric   else {
7240b57cec5SDimitry Andric     bool Normal = true;
7250b57cec5SDimitry Andric     applyTemplateHighlighting(OS, Message, Normal, Bold);
7260b57cec5SDimitry Andric     assert(Normal && "Formatting should have returned to normal");
7270b57cec5SDimitry Andric   }
7280b57cec5SDimitry Andric 
7290b57cec5SDimitry Andric   if (ShowColors)
7300b57cec5SDimitry Andric     OS.resetColor();
7310b57cec5SDimitry Andric   OS << '\n';
7320b57cec5SDimitry Andric }
7330b57cec5SDimitry Andric 
7340b57cec5SDimitry Andric void TextDiagnostic::emitFilename(StringRef Filename, const SourceManager &SM) {
735480093f4SDimitry Andric #ifdef _WIN32
736480093f4SDimitry Andric   SmallString<4096> TmpFilename;
737480093f4SDimitry Andric #endif
7380b57cec5SDimitry Andric   if (DiagOpts->AbsolutePath) {
739480093f4SDimitry Andric     auto File = SM.getFileManager().getFile(Filename);
740480093f4SDimitry Andric     if (File) {
7410b57cec5SDimitry Andric       // We want to print a simplified absolute path, i. e. without "dots".
7420b57cec5SDimitry Andric       //
7430b57cec5SDimitry Andric       // The hardest part here are the paths like "<part1>/<link>/../<part2>".
7440b57cec5SDimitry Andric       // On Unix-like systems, we cannot just collapse "<link>/..", because
7450b57cec5SDimitry Andric       // paths are resolved sequentially, and, thereby, the path
7460b57cec5SDimitry Andric       // "<part1>/<part2>" may point to a different location. That is why
7470b57cec5SDimitry Andric       // we use FileManager::getCanonicalName(), which expands all indirections
7480b57cec5SDimitry Andric       // with llvm::sys::fs::real_path() and caches the result.
7490b57cec5SDimitry Andric       //
7500b57cec5SDimitry Andric       // On the other hand, it would be better to preserve as much of the
7510b57cec5SDimitry Andric       // original path as possible, because that helps a user to recognize it.
7520b57cec5SDimitry Andric       // real_path() expands all links, which sometimes too much. Luckily,
7530b57cec5SDimitry Andric       // on Windows we can just use llvm::sys::path::remove_dots(), because,
7540b57cec5SDimitry Andric       // on that system, both aforementioned paths point to the same place.
7550b57cec5SDimitry Andric #ifdef _WIN32
756480093f4SDimitry Andric       TmpFilename = (*File)->getName();
757480093f4SDimitry Andric       llvm::sys::fs::make_absolute(TmpFilename);
758480093f4SDimitry Andric       llvm::sys::path::native(TmpFilename);
759480093f4SDimitry Andric       llvm::sys::path::remove_dots(TmpFilename, /* remove_dot_dot */ true);
760480093f4SDimitry Andric       Filename = StringRef(TmpFilename.data(), TmpFilename.size());
7610b57cec5SDimitry Andric #else
762480093f4SDimitry Andric       Filename = SM.getFileManager().getCanonicalName(*File);
7630b57cec5SDimitry Andric #endif
7640b57cec5SDimitry Andric     }
7650b57cec5SDimitry Andric   }
7660b57cec5SDimitry Andric 
7670b57cec5SDimitry Andric   OS << Filename;
7680b57cec5SDimitry Andric }
7690b57cec5SDimitry Andric 
7700b57cec5SDimitry Andric /// Print out the file/line/column information and include trace.
7710b57cec5SDimitry Andric ///
77206c3fb27SDimitry Andric /// This method handles the emission of the diagnostic location information.
7730b57cec5SDimitry Andric /// This includes extracting as much location information as is present for
7740b57cec5SDimitry Andric /// the diagnostic and printing it, as well as any include stack or source
7750b57cec5SDimitry Andric /// ranges necessary.
7760b57cec5SDimitry Andric void TextDiagnostic::emitDiagnosticLoc(FullSourceLoc Loc, PresumedLoc PLoc,
7770b57cec5SDimitry Andric                                        DiagnosticsEngine::Level Level,
7780b57cec5SDimitry Andric                                        ArrayRef<CharSourceRange> Ranges) {
7790b57cec5SDimitry Andric   if (PLoc.isInvalid()) {
7800b57cec5SDimitry Andric     // At least print the file name if available:
78106c3fb27SDimitry Andric     if (FileID FID = Loc.getFileID(); FID.isValid()) {
78281ad6265SDimitry Andric       if (const FileEntry *FE = Loc.getFileEntry()) {
7830b57cec5SDimitry Andric         emitFilename(FE->getName(), Loc.getManager());
7840b57cec5SDimitry Andric         OS << ": ";
7850b57cec5SDimitry Andric       }
7860b57cec5SDimitry Andric     }
7870b57cec5SDimitry Andric     return;
7880b57cec5SDimitry Andric   }
7890b57cec5SDimitry Andric   unsigned LineNo = PLoc.getLine();
7900b57cec5SDimitry Andric 
7910b57cec5SDimitry Andric   if (!DiagOpts->ShowLocation)
7920b57cec5SDimitry Andric     return;
7930b57cec5SDimitry Andric 
7940b57cec5SDimitry Andric   if (DiagOpts->ShowColors)
7950b57cec5SDimitry Andric     OS.changeColor(savedColor, true);
7960b57cec5SDimitry Andric 
7970b57cec5SDimitry Andric   emitFilename(PLoc.getFilename(), Loc.getManager());
7980b57cec5SDimitry Andric   switch (DiagOpts->getFormat()) {
799fcaf7f86SDimitry Andric   case DiagnosticOptions::SARIF:
800e8d8bef9SDimitry Andric   case DiagnosticOptions::Clang:
801e8d8bef9SDimitry Andric     if (DiagOpts->ShowLine)
802e8d8bef9SDimitry Andric       OS << ':' << LineNo;
803e8d8bef9SDimitry Andric     break;
8040b57cec5SDimitry Andric   case DiagnosticOptions::MSVC:  OS << '('  << LineNo; break;
8050b57cec5SDimitry Andric   case DiagnosticOptions::Vi:    OS << " +" << LineNo; break;
8060b57cec5SDimitry Andric   }
8070b57cec5SDimitry Andric 
8080b57cec5SDimitry Andric   if (DiagOpts->ShowColumn)
8090b57cec5SDimitry Andric     // Compute the column number.
8100b57cec5SDimitry Andric     if (unsigned ColNo = PLoc.getColumn()) {
8110b57cec5SDimitry Andric       if (DiagOpts->getFormat() == DiagnosticOptions::MSVC) {
8120b57cec5SDimitry Andric         OS << ',';
8130b57cec5SDimitry Andric         // Visual Studio 2010 or earlier expects column number to be off by one
8140b57cec5SDimitry Andric         if (LangOpts.MSCompatibilityVersion &&
8150b57cec5SDimitry Andric             !LangOpts.isCompatibleWithMSVC(LangOptions::MSVC2012))
8160b57cec5SDimitry Andric           ColNo--;
8170b57cec5SDimitry Andric       } else
8180b57cec5SDimitry Andric         OS << ':';
8190b57cec5SDimitry Andric       OS << ColNo;
8200b57cec5SDimitry Andric     }
8210b57cec5SDimitry Andric   switch (DiagOpts->getFormat()) {
822fcaf7f86SDimitry Andric   case DiagnosticOptions::SARIF:
8230b57cec5SDimitry Andric   case DiagnosticOptions::Clang:
8240b57cec5SDimitry Andric   case DiagnosticOptions::Vi:    OS << ':';    break;
8250b57cec5SDimitry Andric   case DiagnosticOptions::MSVC:
8260b57cec5SDimitry Andric     // MSVC2013 and before print 'file(4) : error'. MSVC2015 gets rid of the
8270b57cec5SDimitry Andric     // space and prints 'file(4): error'.
8280b57cec5SDimitry Andric     OS << ')';
8290b57cec5SDimitry Andric     if (LangOpts.MSCompatibilityVersion &&
8300b57cec5SDimitry Andric         !LangOpts.isCompatibleWithMSVC(LangOptions::MSVC2015))
8310b57cec5SDimitry Andric       OS << ' ';
8320b57cec5SDimitry Andric     OS << ':';
8330b57cec5SDimitry Andric     break;
8340b57cec5SDimitry Andric   }
8350b57cec5SDimitry Andric 
8360b57cec5SDimitry Andric   if (DiagOpts->ShowSourceRanges && !Ranges.empty()) {
8370b57cec5SDimitry Andric     FileID CaretFileID = Loc.getExpansionLoc().getFileID();
8380b57cec5SDimitry Andric     bool PrintedRange = false;
83906c3fb27SDimitry Andric     const SourceManager &SM = Loc.getManager();
8400b57cec5SDimitry Andric 
84106c3fb27SDimitry Andric     for (const auto &R : Ranges) {
8420b57cec5SDimitry Andric       // Ignore invalid ranges.
84306c3fb27SDimitry Andric       if (!R.isValid())
84406c3fb27SDimitry Andric         continue;
8450b57cec5SDimitry Andric 
84606c3fb27SDimitry Andric       SourceLocation B = SM.getExpansionLoc(R.getBegin());
84706c3fb27SDimitry Andric       CharSourceRange ERange = SM.getExpansionRange(R.getEnd());
8480b57cec5SDimitry Andric       SourceLocation E = ERange.getEnd();
8490b57cec5SDimitry Andric 
85006c3fb27SDimitry Andric       // If the start or end of the range is in another file, just
85106c3fb27SDimitry Andric       // discard it.
85206c3fb27SDimitry Andric       if (SM.getFileID(B) != CaretFileID || SM.getFileID(E) != CaretFileID)
8530b57cec5SDimitry Andric         continue;
8540b57cec5SDimitry Andric 
8550b57cec5SDimitry Andric       // Add in the length of the token, so that we cover multi-char
8560b57cec5SDimitry Andric       // tokens.
8570b57cec5SDimitry Andric       unsigned TokSize = 0;
85806c3fb27SDimitry Andric       if (ERange.isTokenRange())
8590b57cec5SDimitry Andric         TokSize = Lexer::MeasureTokenLength(E, SM, LangOpts);
8600b57cec5SDimitry Andric 
8610b57cec5SDimitry Andric       FullSourceLoc BF(B, SM), EF(E, SM);
8620b57cec5SDimitry Andric       OS << '{'
8630b57cec5SDimitry Andric          << BF.getLineNumber() << ':' << BF.getColumnNumber() << '-'
8640b57cec5SDimitry Andric          << EF.getLineNumber() << ':' << (EF.getColumnNumber() + TokSize)
8650b57cec5SDimitry Andric          << '}';
8660b57cec5SDimitry Andric       PrintedRange = true;
8670b57cec5SDimitry Andric     }
8680b57cec5SDimitry Andric 
8690b57cec5SDimitry Andric     if (PrintedRange)
8700b57cec5SDimitry Andric       OS << ':';
8710b57cec5SDimitry Andric   }
8720b57cec5SDimitry Andric   OS << ' ';
8730b57cec5SDimitry Andric }
8740b57cec5SDimitry Andric 
8750b57cec5SDimitry Andric void TextDiagnostic::emitIncludeLocation(FullSourceLoc Loc, PresumedLoc PLoc) {
87606c3fb27SDimitry Andric   if (DiagOpts->ShowLocation && PLoc.isValid()) {
87706c3fb27SDimitry Andric     OS << "In file included from ";
87806c3fb27SDimitry Andric     emitFilename(PLoc.getFilename(), Loc.getManager());
87906c3fb27SDimitry Andric     OS << ':' << PLoc.getLine() << ":\n";
88006c3fb27SDimitry Andric   } else
8810b57cec5SDimitry Andric     OS << "In included file:\n";
8820b57cec5SDimitry Andric }
8830b57cec5SDimitry Andric 
8840b57cec5SDimitry Andric void TextDiagnostic::emitImportLocation(FullSourceLoc Loc, PresumedLoc PLoc,
8850b57cec5SDimitry Andric                                         StringRef ModuleName) {
8860b57cec5SDimitry Andric   if (DiagOpts->ShowLocation && PLoc.isValid())
8870b57cec5SDimitry Andric     OS << "In module '" << ModuleName << "' imported from "
8880b57cec5SDimitry Andric        << PLoc.getFilename() << ':' << PLoc.getLine() << ":\n";
8890b57cec5SDimitry Andric   else
8900b57cec5SDimitry Andric     OS << "In module '" << ModuleName << "':\n";
8910b57cec5SDimitry Andric }
8920b57cec5SDimitry Andric 
8930b57cec5SDimitry Andric void TextDiagnostic::emitBuildingModuleLocation(FullSourceLoc Loc,
8940b57cec5SDimitry Andric                                                 PresumedLoc PLoc,
8950b57cec5SDimitry Andric                                                 StringRef ModuleName) {
8960b57cec5SDimitry Andric   if (DiagOpts->ShowLocation && PLoc.isValid())
8970b57cec5SDimitry Andric     OS << "While building module '" << ModuleName << "' imported from "
8980b57cec5SDimitry Andric       << PLoc.getFilename() << ':' << PLoc.getLine() << ":\n";
8990b57cec5SDimitry Andric   else
9000b57cec5SDimitry Andric     OS << "While building module '" << ModuleName << "':\n";
9010b57cec5SDimitry Andric }
9020b57cec5SDimitry Andric 
9030b57cec5SDimitry Andric /// Find the suitable set of lines to show to include a set of ranges.
904bdd1243dSDimitry Andric static std::optional<std::pair<unsigned, unsigned>>
9050b57cec5SDimitry Andric findLinesForRange(const CharSourceRange &R, FileID FID,
9060b57cec5SDimitry Andric                   const SourceManager &SM) {
907bdd1243dSDimitry Andric   if (!R.isValid())
908bdd1243dSDimitry Andric     return std::nullopt;
9090b57cec5SDimitry Andric 
9100b57cec5SDimitry Andric   SourceLocation Begin = R.getBegin();
9110b57cec5SDimitry Andric   SourceLocation End = R.getEnd();
9120b57cec5SDimitry Andric   if (SM.getFileID(Begin) != FID || SM.getFileID(End) != FID)
913bdd1243dSDimitry Andric     return std::nullopt;
9140b57cec5SDimitry Andric 
9150b57cec5SDimitry Andric   return std::make_pair(SM.getExpansionLineNumber(Begin),
9160b57cec5SDimitry Andric                         SM.getExpansionLineNumber(End));
9170b57cec5SDimitry Andric }
9180b57cec5SDimitry Andric 
9190b57cec5SDimitry Andric /// Add as much of range B into range A as possible without exceeding a maximum
9200b57cec5SDimitry Andric /// size of MaxRange. Ranges are inclusive.
9210b57cec5SDimitry Andric static std::pair<unsigned, unsigned>
9220b57cec5SDimitry Andric maybeAddRange(std::pair<unsigned, unsigned> A, std::pair<unsigned, unsigned> B,
9230b57cec5SDimitry Andric               unsigned MaxRange) {
9240b57cec5SDimitry Andric   // If A is already the maximum size, we're done.
9250b57cec5SDimitry Andric   unsigned Slack = MaxRange - (A.second - A.first + 1);
9260b57cec5SDimitry Andric   if (Slack == 0)
9270b57cec5SDimitry Andric     return A;
9280b57cec5SDimitry Andric 
9290b57cec5SDimitry Andric   // Easy case: merge succeeds within MaxRange.
9300b57cec5SDimitry Andric   unsigned Min = std::min(A.first, B.first);
9310b57cec5SDimitry Andric   unsigned Max = std::max(A.second, B.second);
9320b57cec5SDimitry Andric   if (Max - Min + 1 <= MaxRange)
9330b57cec5SDimitry Andric     return {Min, Max};
9340b57cec5SDimitry Andric 
9350b57cec5SDimitry Andric   // If we can't reach B from A within MaxRange, there's nothing to do.
9360b57cec5SDimitry Andric   // Don't add lines to the range that contain nothing interesting.
9370b57cec5SDimitry Andric   if ((B.first > A.first && B.first - A.first + 1 > MaxRange) ||
9380b57cec5SDimitry Andric       (B.second < A.second && A.second - B.second + 1 > MaxRange))
9390b57cec5SDimitry Andric     return A;
9400b57cec5SDimitry Andric 
9410b57cec5SDimitry Andric   // Otherwise, expand A towards B to produce a range of size MaxRange. We
9420b57cec5SDimitry Andric   // attempt to expand by the same amount in both directions if B strictly
9430b57cec5SDimitry Andric   // contains A.
9440b57cec5SDimitry Andric 
9450b57cec5SDimitry Andric   // Expand downwards by up to half the available amount, then upwards as
9460b57cec5SDimitry Andric   // much as possible, then downwards as much as possible.
9470b57cec5SDimitry Andric   A.second = std::min(A.second + (Slack + 1) / 2, Max);
9480b57cec5SDimitry Andric   Slack = MaxRange - (A.second - A.first + 1);
9490b57cec5SDimitry Andric   A.first = std::max(Min + Slack, A.first) - Slack;
9500b57cec5SDimitry Andric   A.second = std::min(A.first + MaxRange - 1, Max);
9510b57cec5SDimitry Andric   return A;
9520b57cec5SDimitry Andric }
9530b57cec5SDimitry Andric 
95406c3fb27SDimitry Andric struct LineRange {
95506c3fb27SDimitry Andric   unsigned LineNo;
95606c3fb27SDimitry Andric   unsigned StartCol;
95706c3fb27SDimitry Andric   unsigned EndCol;
95806c3fb27SDimitry Andric };
9590b57cec5SDimitry Andric 
96006c3fb27SDimitry Andric /// Highlight \p R (with ~'s) on the current source line.
96106c3fb27SDimitry Andric static void highlightRange(const LineRange &R, const SourceColumnMap &Map,
96206c3fb27SDimitry Andric                            std::string &CaretLine) {
9630b57cec5SDimitry Andric   // Pick the first non-whitespace column.
96406c3fb27SDimitry Andric   unsigned StartColNo = R.StartCol;
96506c3fb27SDimitry Andric   while (StartColNo < Map.getSourceLine().size() &&
96606c3fb27SDimitry Andric          (Map.getSourceLine()[StartColNo] == ' ' ||
96706c3fb27SDimitry Andric           Map.getSourceLine()[StartColNo] == '\t'))
96806c3fb27SDimitry Andric     StartColNo = Map.startOfNextColumn(StartColNo);
9690b57cec5SDimitry Andric 
9700b57cec5SDimitry Andric   // Pick the last non-whitespace column.
97106c3fb27SDimitry Andric   unsigned EndColNo =
97206c3fb27SDimitry Andric       std::min(static_cast<size_t>(R.EndCol), Map.getSourceLine().size());
97306c3fb27SDimitry Andric   while (EndColNo && (Map.getSourceLine()[EndColNo - 1] == ' ' ||
97406c3fb27SDimitry Andric                       Map.getSourceLine()[EndColNo - 1] == '\t'))
97506c3fb27SDimitry Andric     EndColNo = Map.startOfPreviousColumn(EndColNo);
9760b57cec5SDimitry Andric 
9770b57cec5SDimitry Andric   // If the start/end passed each other, then we are trying to highlight a
9780b57cec5SDimitry Andric   // range that just exists in whitespace. That most likely means we have
9790b57cec5SDimitry Andric   // a multi-line highlighting range that covers a blank line.
98006c3fb27SDimitry Andric   if (StartColNo > EndColNo)
98106c3fb27SDimitry Andric     return;
9820b57cec5SDimitry Andric 
9830b57cec5SDimitry Andric   // Fill the range with ~'s.
98406c3fb27SDimitry Andric   StartColNo = Map.byteToContainingColumn(StartColNo);
98506c3fb27SDimitry Andric   EndColNo = Map.byteToContainingColumn(EndColNo);
9860b57cec5SDimitry Andric 
9870b57cec5SDimitry Andric   assert(StartColNo <= EndColNo && "Invalid range!");
9880b57cec5SDimitry Andric   if (CaretLine.size() < EndColNo)
9890b57cec5SDimitry Andric     CaretLine.resize(EndColNo, ' ');
9900b57cec5SDimitry Andric   std::fill(CaretLine.begin() + StartColNo, CaretLine.begin() + EndColNo, '~');
9910b57cec5SDimitry Andric }
9920b57cec5SDimitry Andric 
9930b57cec5SDimitry Andric static std::string buildFixItInsertionLine(FileID FID,
9940b57cec5SDimitry Andric                                            unsigned LineNo,
9950b57cec5SDimitry Andric                                            const SourceColumnMap &map,
9960b57cec5SDimitry Andric                                            ArrayRef<FixItHint> Hints,
9970b57cec5SDimitry Andric                                            const SourceManager &SM,
9980b57cec5SDimitry Andric                                            const DiagnosticOptions *DiagOpts) {
9990b57cec5SDimitry Andric   std::string FixItInsertionLine;
10000b57cec5SDimitry Andric   if (Hints.empty() || !DiagOpts->ShowFixits)
10010b57cec5SDimitry Andric     return FixItInsertionLine;
10020b57cec5SDimitry Andric   unsigned PrevHintEndCol = 0;
10030b57cec5SDimitry Andric 
100406c3fb27SDimitry Andric   for (const auto &H : Hints) {
100506c3fb27SDimitry Andric     if (H.CodeToInsert.empty())
100606c3fb27SDimitry Andric       continue;
100706c3fb27SDimitry Andric 
10080b57cec5SDimitry Andric     // We have an insertion hint. Determine whether the inserted
10090b57cec5SDimitry Andric     // code contains no newlines and is on the same line as the caret.
101006c3fb27SDimitry Andric     std::pair<FileID, unsigned> HintLocInfo =
101106c3fb27SDimitry Andric         SM.getDecomposedExpansionLoc(H.RemoveRange.getBegin());
10120b57cec5SDimitry Andric     if (FID == HintLocInfo.first &&
10130b57cec5SDimitry Andric         LineNo == SM.getLineNumber(HintLocInfo.first, HintLocInfo.second) &&
101406c3fb27SDimitry Andric         StringRef(H.CodeToInsert).find_first_of("\n\r") == StringRef::npos) {
10150b57cec5SDimitry Andric       // Insert the new code into the line just below the code
10160b57cec5SDimitry Andric       // that the user wrote.
10170b57cec5SDimitry Andric       // Note: When modifying this function, be very careful about what is a
10180b57cec5SDimitry Andric       // "column" (printed width, platform-dependent) and what is a
10190b57cec5SDimitry Andric       // "byte offset" (SourceManager "column").
102006c3fb27SDimitry Andric       unsigned HintByteOffset =
102106c3fb27SDimitry Andric           SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second) - 1;
10220b57cec5SDimitry Andric 
10230b57cec5SDimitry Andric       // The hint must start inside the source or right at the end
10240b57cec5SDimitry Andric       assert(HintByteOffset < static_cast<unsigned>(map.bytes()) + 1);
10250b57cec5SDimitry Andric       unsigned HintCol = map.byteToContainingColumn(HintByteOffset);
10260b57cec5SDimitry Andric 
10270b57cec5SDimitry Andric       // If we inserted a long previous hint, push this one forwards, and add
10280b57cec5SDimitry Andric       // an extra space to show that this is not part of the previous
10290b57cec5SDimitry Andric       // completion. This is sort of the best we can do when two hints appear
10300b57cec5SDimitry Andric       // to overlap.
10310b57cec5SDimitry Andric       //
10320b57cec5SDimitry Andric       // Note that if this hint is located immediately after the previous
10330b57cec5SDimitry Andric       // hint, no space will be added, since the location is more important.
10340b57cec5SDimitry Andric       if (HintCol < PrevHintEndCol)
10350b57cec5SDimitry Andric         HintCol = PrevHintEndCol + 1;
10360b57cec5SDimitry Andric 
10370b57cec5SDimitry Andric       // This should NOT use HintByteOffset, because the source might have
10380b57cec5SDimitry Andric       // Unicode characters in earlier columns.
10390b57cec5SDimitry Andric       unsigned NewFixItLineSize = FixItInsertionLine.size() +
104006c3fb27SDimitry Andric                                   (HintCol - PrevHintEndCol) +
104106c3fb27SDimitry Andric                                   H.CodeToInsert.size();
10420b57cec5SDimitry Andric       if (NewFixItLineSize > FixItInsertionLine.size())
10430b57cec5SDimitry Andric         FixItInsertionLine.resize(NewFixItLineSize, ' ');
10440b57cec5SDimitry Andric 
104506c3fb27SDimitry Andric       std::copy(H.CodeToInsert.begin(), H.CodeToInsert.end(),
104606c3fb27SDimitry Andric                 FixItInsertionLine.end() - H.CodeToInsert.size());
10470b57cec5SDimitry Andric 
104806c3fb27SDimitry Andric       PrevHintEndCol = HintCol + llvm::sys::locale::columnWidth(H.CodeToInsert);
10490b57cec5SDimitry Andric     }
10500b57cec5SDimitry Andric   }
10510b57cec5SDimitry Andric 
10520b57cec5SDimitry Andric   expandTabs(FixItInsertionLine, DiagOpts->TabStop);
10530b57cec5SDimitry Andric 
10540b57cec5SDimitry Andric   return FixItInsertionLine;
10550b57cec5SDimitry Andric }
10560b57cec5SDimitry Andric 
105706c3fb27SDimitry Andric static unsigned getNumDisplayWidth(unsigned N) {
105806c3fb27SDimitry Andric   unsigned L = 1u, M = 10u;
105906c3fb27SDimitry Andric   while (M <= N && ++L != std::numeric_limits<unsigned>::digits10 + 1)
106006c3fb27SDimitry Andric     M *= 10u;
106106c3fb27SDimitry Andric 
106206c3fb27SDimitry Andric   return L;
106306c3fb27SDimitry Andric }
106406c3fb27SDimitry Andric 
106506c3fb27SDimitry Andric /// Filter out invalid ranges, ranges that don't fit into the window of
106606c3fb27SDimitry Andric /// source lines we will print, and ranges from other files.
106706c3fb27SDimitry Andric ///
106806c3fb27SDimitry Andric /// For the remaining ranges, convert them to simple LineRange structs,
106906c3fb27SDimitry Andric /// which only cover one line at a time.
107006c3fb27SDimitry Andric static SmallVector<LineRange>
107106c3fb27SDimitry Andric prepareAndFilterRanges(const SmallVectorImpl<CharSourceRange> &Ranges,
107206c3fb27SDimitry Andric                        const SourceManager &SM,
107306c3fb27SDimitry Andric                        const std::pair<unsigned, unsigned> &Lines, FileID FID,
107406c3fb27SDimitry Andric                        const LangOptions &LangOpts) {
107506c3fb27SDimitry Andric   SmallVector<LineRange> LineRanges;
107606c3fb27SDimitry Andric 
107706c3fb27SDimitry Andric   for (const CharSourceRange &R : Ranges) {
107806c3fb27SDimitry Andric     if (R.isInvalid())
107906c3fb27SDimitry Andric       continue;
108006c3fb27SDimitry Andric     SourceLocation Begin = R.getBegin();
108106c3fb27SDimitry Andric     SourceLocation End = R.getEnd();
108206c3fb27SDimitry Andric 
108306c3fb27SDimitry Andric     unsigned StartLineNo = SM.getExpansionLineNumber(Begin);
108406c3fb27SDimitry Andric     if (StartLineNo > Lines.second || SM.getFileID(Begin) != FID)
108506c3fb27SDimitry Andric       continue;
108606c3fb27SDimitry Andric 
108706c3fb27SDimitry Andric     unsigned EndLineNo = SM.getExpansionLineNumber(End);
108806c3fb27SDimitry Andric     if (EndLineNo < Lines.first || SM.getFileID(End) != FID)
108906c3fb27SDimitry Andric       continue;
109006c3fb27SDimitry Andric 
109106c3fb27SDimitry Andric     unsigned StartColumn = SM.getExpansionColumnNumber(Begin);
109206c3fb27SDimitry Andric     unsigned EndColumn = SM.getExpansionColumnNumber(End);
109306c3fb27SDimitry Andric     if (R.isTokenRange())
109406c3fb27SDimitry Andric       EndColumn += Lexer::MeasureTokenLength(End, SM, LangOpts);
109506c3fb27SDimitry Andric 
109606c3fb27SDimitry Andric     // Only a single line.
109706c3fb27SDimitry Andric     if (StartLineNo == EndLineNo) {
109806c3fb27SDimitry Andric       LineRanges.push_back({StartLineNo, StartColumn - 1, EndColumn - 1});
109906c3fb27SDimitry Andric       continue;
110006c3fb27SDimitry Andric     }
110106c3fb27SDimitry Andric 
110206c3fb27SDimitry Andric     // Start line.
110306c3fb27SDimitry Andric     LineRanges.push_back({StartLineNo, StartColumn - 1, ~0u});
110406c3fb27SDimitry Andric 
110506c3fb27SDimitry Andric     // Middle lines.
110606c3fb27SDimitry Andric     for (unsigned S = StartLineNo + 1; S != EndLineNo; ++S)
110706c3fb27SDimitry Andric       LineRanges.push_back({S, 0, ~0u});
110806c3fb27SDimitry Andric 
110906c3fb27SDimitry Andric     // End line.
111006c3fb27SDimitry Andric     LineRanges.push_back({EndLineNo, 0, EndColumn - 1});
111106c3fb27SDimitry Andric   }
111206c3fb27SDimitry Andric 
111306c3fb27SDimitry Andric   return LineRanges;
111406c3fb27SDimitry Andric }
111506c3fb27SDimitry Andric 
11160b57cec5SDimitry Andric /// Emit a code snippet and caret line.
11170b57cec5SDimitry Andric ///
11180b57cec5SDimitry Andric /// This routine emits a single line's code snippet and caret line..
11190b57cec5SDimitry Andric ///
11200b57cec5SDimitry Andric /// \param Loc The location for the caret.
11210b57cec5SDimitry Andric /// \param Ranges The underlined ranges for this code snippet.
11220b57cec5SDimitry Andric /// \param Hints The FixIt hints active for this diagnostic.
11230b57cec5SDimitry Andric void TextDiagnostic::emitSnippetAndCaret(
11240b57cec5SDimitry Andric     FullSourceLoc Loc, DiagnosticsEngine::Level Level,
11250b57cec5SDimitry Andric     SmallVectorImpl<CharSourceRange> &Ranges, ArrayRef<FixItHint> Hints) {
11260b57cec5SDimitry Andric   assert(Loc.isValid() && "must have a valid source location here");
11270b57cec5SDimitry Andric   assert(Loc.isFileID() && "must have a file location here");
11280b57cec5SDimitry Andric 
11290b57cec5SDimitry Andric   // If caret diagnostics are enabled and we have location, we want to
11300b57cec5SDimitry Andric   // emit the caret.  However, we only do this if the location moved
11310b57cec5SDimitry Andric   // from the last diagnostic, if the last diagnostic was a note that
11320b57cec5SDimitry Andric   // was part of a different warning or error diagnostic, or if the
11330b57cec5SDimitry Andric   // diagnostic has ranges.  We don't want to emit the same caret
11340b57cec5SDimitry Andric   // multiple times if one loc has multiple diagnostics.
11350b57cec5SDimitry Andric   if (!DiagOpts->ShowCarets)
11360b57cec5SDimitry Andric     return;
11370b57cec5SDimitry Andric   if (Loc == LastLoc && Ranges.empty() && Hints.empty() &&
11380b57cec5SDimitry Andric       (LastLevel != DiagnosticsEngine::Note || Level == LastLevel))
11390b57cec5SDimitry Andric     return;
11400b57cec5SDimitry Andric 
114106c3fb27SDimitry Andric   FileID FID = Loc.getFileID();
11420b57cec5SDimitry Andric   const SourceManager &SM = Loc.getManager();
11430b57cec5SDimitry Andric 
11440b57cec5SDimitry Andric   // Get information about the buffer it points into.
11450b57cec5SDimitry Andric   bool Invalid = false;
11460b57cec5SDimitry Andric   StringRef BufData = Loc.getBufferData(&Invalid);
11470b57cec5SDimitry Andric   if (Invalid)
11480b57cec5SDimitry Andric     return;
114906c3fb27SDimitry Andric   const char *BufStart = BufData.data();
115006c3fb27SDimitry Andric   const char *BufEnd = BufStart + BufData.size();
11510b57cec5SDimitry Andric 
11520b57cec5SDimitry Andric   unsigned CaretLineNo = Loc.getLineNumber();
11530b57cec5SDimitry Andric   unsigned CaretColNo = Loc.getColumnNumber();
11540b57cec5SDimitry Andric 
11550b57cec5SDimitry Andric   // Arbitrarily stop showing snippets when the line is too long.
11560b57cec5SDimitry Andric   static const size_t MaxLineLengthToPrint = 4096;
11570b57cec5SDimitry Andric   if (CaretColNo > MaxLineLengthToPrint)
11580b57cec5SDimitry Andric     return;
11590b57cec5SDimitry Andric 
11600b57cec5SDimitry Andric   // Find the set of lines to include.
11610b57cec5SDimitry Andric   const unsigned MaxLines = DiagOpts->SnippetLineLimit;
11620b57cec5SDimitry Andric   std::pair<unsigned, unsigned> Lines = {CaretLineNo, CaretLineNo};
1163*4542f901SDimitry Andric   unsigned DisplayLineNo = Loc.getPresumedLoc().getLine();
116406c3fb27SDimitry Andric   for (const auto &I : Ranges) {
116506c3fb27SDimitry Andric     if (auto OptionalRange = findLinesForRange(I, FID, SM))
11660b57cec5SDimitry Andric       Lines = maybeAddRange(Lines, *OptionalRange, MaxLines);
11670b57cec5SDimitry Andric 
116806c3fb27SDimitry Andric     DisplayLineNo =
116906c3fb27SDimitry Andric         std::min(DisplayLineNo, SM.getPresumedLineNumber(I.getBegin()));
117006c3fb27SDimitry Andric   }
11710b57cec5SDimitry Andric 
117206c3fb27SDimitry Andric   // Our line numbers look like:
117306c3fb27SDimitry Andric   // " [number] | "
117406c3fb27SDimitry Andric   // Where [number] is MaxLineNoDisplayWidth columns
117506c3fb27SDimitry Andric   // and the full thing is therefore MaxLineNoDisplayWidth + 4 columns.
117606c3fb27SDimitry Andric   unsigned MaxLineNoDisplayWidth =
117706c3fb27SDimitry Andric       DiagOpts->ShowLineNumbers
117806c3fb27SDimitry Andric           ? std::max(4u, getNumDisplayWidth(DisplayLineNo + MaxLines))
117906c3fb27SDimitry Andric           : 0;
118006c3fb27SDimitry Andric   auto indentForLineNumbers = [&] {
118106c3fb27SDimitry Andric     if (MaxLineNoDisplayWidth > 0)
118206c3fb27SDimitry Andric       OS.indent(MaxLineNoDisplayWidth + 2) << "| ";
118306c3fb27SDimitry Andric   };
118406c3fb27SDimitry Andric 
118506c3fb27SDimitry Andric   SmallVector<LineRange> LineRanges =
118606c3fb27SDimitry Andric       prepareAndFilterRanges(Ranges, SM, Lines, FID, LangOpts);
118706c3fb27SDimitry Andric 
118806c3fb27SDimitry Andric   for (unsigned LineNo = Lines.first; LineNo != Lines.second + 1;
118906c3fb27SDimitry Andric        ++LineNo, ++DisplayLineNo) {
11900b57cec5SDimitry Andric     // Rewind from the current position to the start of the line.
11910b57cec5SDimitry Andric     const char *LineStart =
11920b57cec5SDimitry Andric         BufStart +
11930b57cec5SDimitry Andric         SM.getDecomposedLoc(SM.translateLineCol(FID, LineNo, 1)).second;
11940b57cec5SDimitry Andric     if (LineStart == BufEnd)
11950b57cec5SDimitry Andric       break;
11960b57cec5SDimitry Andric 
11970b57cec5SDimitry Andric     // Compute the line end.
11980b57cec5SDimitry Andric     const char *LineEnd = LineStart;
11990b57cec5SDimitry Andric     while (*LineEnd != '\n' && *LineEnd != '\r' && LineEnd != BufEnd)
12000b57cec5SDimitry Andric       ++LineEnd;
12010b57cec5SDimitry Andric 
12020b57cec5SDimitry Andric     // Arbitrarily stop showing snippets when the line is too long.
12030b57cec5SDimitry Andric     // FIXME: Don't print any lines in this case.
12040b57cec5SDimitry Andric     if (size_t(LineEnd - LineStart) > MaxLineLengthToPrint)
12050b57cec5SDimitry Andric       return;
12060b57cec5SDimitry Andric 
12070b57cec5SDimitry Andric     // Copy the line of code into an std::string for ease of manipulation.
120806c3fb27SDimitry Andric     std::string SourceLine(LineStart, LineEnd);
120906c3fb27SDimitry Andric     // Remove trailing null bytes.
121006c3fb27SDimitry Andric     while (!SourceLine.empty() && SourceLine.back() == '\0' &&
121106c3fb27SDimitry Andric            (LineNo != CaretLineNo || SourceLine.size() > CaretColNo))
121206c3fb27SDimitry Andric       SourceLine.pop_back();
12130b57cec5SDimitry Andric 
12140b57cec5SDimitry Andric     // Build the byte to column map.
12150b57cec5SDimitry Andric     const SourceColumnMap sourceColMap(SourceLine, DiagOpts->TabStop);
12160b57cec5SDimitry Andric 
121706c3fb27SDimitry Andric     std::string CaretLine;
12180b57cec5SDimitry Andric     // Highlight all of the characters covered by Ranges with ~ characters.
121906c3fb27SDimitry Andric     for (const auto &LR : LineRanges) {
122006c3fb27SDimitry Andric       if (LR.LineNo == LineNo)
122106c3fb27SDimitry Andric         highlightRange(LR, sourceColMap, CaretLine);
122206c3fb27SDimitry Andric     }
12230b57cec5SDimitry Andric 
12240b57cec5SDimitry Andric     // Next, insert the caret itself.
12250b57cec5SDimitry Andric     if (CaretLineNo == LineNo) {
122606c3fb27SDimitry Andric       size_t Col = sourceColMap.byteToContainingColumn(CaretColNo - 1);
122706c3fb27SDimitry Andric       CaretLine.resize(std::max(Col + 1, CaretLine.size()), ' ');
122806c3fb27SDimitry Andric       CaretLine[Col] = '^';
12290b57cec5SDimitry Andric     }
12300b57cec5SDimitry Andric 
12310b57cec5SDimitry Andric     std::string FixItInsertionLine = buildFixItInsertionLine(
12320b57cec5SDimitry Andric         FID, LineNo, sourceColMap, Hints, SM, DiagOpts.get());
12330b57cec5SDimitry Andric 
12340b57cec5SDimitry Andric     // If the source line is too long for our terminal, select only the
12350b57cec5SDimitry Andric     // "interesting" source region within that line.
12360b57cec5SDimitry Andric     unsigned Columns = DiagOpts->MessageLength;
12370b57cec5SDimitry Andric     if (Columns)
12380b57cec5SDimitry Andric       selectInterestingSourceRegion(SourceLine, CaretLine, FixItInsertionLine,
12390b57cec5SDimitry Andric                                     Columns, sourceColMap);
12400b57cec5SDimitry Andric 
12410b57cec5SDimitry Andric     // If we are in -fdiagnostics-print-source-range-info mode, we are trying
12420b57cec5SDimitry Andric     // to produce easily machine parsable output.  Add a space before the
12430b57cec5SDimitry Andric     // source line and the caret to make it trivial to tell the main diagnostic
12440b57cec5SDimitry Andric     // line from what the user is intended to see.
124506c3fb27SDimitry Andric     if (DiagOpts->ShowSourceRanges && !SourceLine.empty()) {
12460b57cec5SDimitry Andric       SourceLine = ' ' + SourceLine;
12470b57cec5SDimitry Andric       CaretLine = ' ' + CaretLine;
12480b57cec5SDimitry Andric     }
12490b57cec5SDimitry Andric 
12500b57cec5SDimitry Andric     // Emit what we have computed.
125106c3fb27SDimitry Andric     emitSnippet(SourceLine, MaxLineNoDisplayWidth, DisplayLineNo);
12520b57cec5SDimitry Andric 
12530b57cec5SDimitry Andric     if (!CaretLine.empty()) {
125406c3fb27SDimitry Andric       indentForLineNumbers();
12550b57cec5SDimitry Andric       if (DiagOpts->ShowColors)
12560b57cec5SDimitry Andric         OS.changeColor(caretColor, true);
12570b57cec5SDimitry Andric       OS << CaretLine << '\n';
12580b57cec5SDimitry Andric       if (DiagOpts->ShowColors)
12590b57cec5SDimitry Andric         OS.resetColor();
12600b57cec5SDimitry Andric     }
12610b57cec5SDimitry Andric 
12620b57cec5SDimitry Andric     if (!FixItInsertionLine.empty()) {
126306c3fb27SDimitry Andric       indentForLineNumbers();
12640b57cec5SDimitry Andric       if (DiagOpts->ShowColors)
12650b57cec5SDimitry Andric         // Print fixit line in color
12660b57cec5SDimitry Andric         OS.changeColor(fixitColor, false);
12670b57cec5SDimitry Andric       if (DiagOpts->ShowSourceRanges)
12680b57cec5SDimitry Andric         OS << ' ';
12690b57cec5SDimitry Andric       OS << FixItInsertionLine << '\n';
12700b57cec5SDimitry Andric       if (DiagOpts->ShowColors)
12710b57cec5SDimitry Andric         OS.resetColor();
12720b57cec5SDimitry Andric     }
12730b57cec5SDimitry Andric   }
12740b57cec5SDimitry Andric 
12750b57cec5SDimitry Andric   // Print out any parseable fixit information requested by the options.
12760b57cec5SDimitry Andric   emitParseableFixits(Hints, SM);
12770b57cec5SDimitry Andric }
12780b57cec5SDimitry Andric 
127906c3fb27SDimitry Andric void TextDiagnostic::emitSnippet(StringRef SourceLine,
128006c3fb27SDimitry Andric                                  unsigned MaxLineNoDisplayWidth,
128106c3fb27SDimitry Andric                                  unsigned LineNo) {
128206c3fb27SDimitry Andric   // Emit line number.
128306c3fb27SDimitry Andric   if (MaxLineNoDisplayWidth > 0) {
128406c3fb27SDimitry Andric     unsigned LineNoDisplayWidth = getNumDisplayWidth(LineNo);
128506c3fb27SDimitry Andric     OS.indent(MaxLineNoDisplayWidth - LineNoDisplayWidth + 1)
128606c3fb27SDimitry Andric         << LineNo << " | ";
128706c3fb27SDimitry Andric   }
12880b57cec5SDimitry Andric 
128906c3fb27SDimitry Andric   // Print the source line one character at a time.
129006c3fb27SDimitry Andric   bool PrintReversed = false;
129106c3fb27SDimitry Andric   size_t I = 0;
129206c3fb27SDimitry Andric   while (I < SourceLine.size()) {
129306c3fb27SDimitry Andric     auto [Str, WasPrintable] =
129406c3fb27SDimitry Andric         printableTextForNextCharacter(SourceLine, &I, DiagOpts->TabStop);
12950b57cec5SDimitry Andric 
129606c3fb27SDimitry Andric     // Toggle inverted colors on or off for this character.
129706c3fb27SDimitry Andric     if (DiagOpts->ShowColors) {
129806c3fb27SDimitry Andric       if (WasPrintable == PrintReversed) {
129906c3fb27SDimitry Andric         PrintReversed = !PrintReversed;
130006c3fb27SDimitry Andric         if (PrintReversed)
13010b57cec5SDimitry Andric           OS.reverseColor();
130206c3fb27SDimitry Andric         else
13030b57cec5SDimitry Andric           OS.resetColor();
13040b57cec5SDimitry Andric       }
130506c3fb27SDimitry Andric     }
130606c3fb27SDimitry Andric     OS << Str;
13070b57cec5SDimitry Andric   }
13080b57cec5SDimitry Andric 
130906c3fb27SDimitry Andric   if (DiagOpts->ShowColors)
13100b57cec5SDimitry Andric     OS.resetColor();
13110b57cec5SDimitry Andric 
13120b57cec5SDimitry Andric   OS << '\n';
13130b57cec5SDimitry Andric }
13140b57cec5SDimitry Andric 
13150b57cec5SDimitry Andric void TextDiagnostic::emitParseableFixits(ArrayRef<FixItHint> Hints,
13160b57cec5SDimitry Andric                                          const SourceManager &SM) {
13170b57cec5SDimitry Andric   if (!DiagOpts->ShowParseableFixits)
13180b57cec5SDimitry Andric     return;
13190b57cec5SDimitry Andric 
13200b57cec5SDimitry Andric   // We follow FixItRewriter's example in not (yet) handling
13210b57cec5SDimitry Andric   // fix-its in macros.
132206c3fb27SDimitry Andric   for (const auto &H : Hints) {
132306c3fb27SDimitry Andric     if (H.RemoveRange.isInvalid() || H.RemoveRange.getBegin().isMacroID() ||
132406c3fb27SDimitry Andric         H.RemoveRange.getEnd().isMacroID())
13250b57cec5SDimitry Andric       return;
13260b57cec5SDimitry Andric   }
13270b57cec5SDimitry Andric 
132806c3fb27SDimitry Andric   for (const auto &H : Hints) {
132906c3fb27SDimitry Andric     SourceLocation BLoc = H.RemoveRange.getBegin();
133006c3fb27SDimitry Andric     SourceLocation ELoc = H.RemoveRange.getEnd();
13310b57cec5SDimitry Andric 
13320b57cec5SDimitry Andric     std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(BLoc);
13330b57cec5SDimitry Andric     std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(ELoc);
13340b57cec5SDimitry Andric 
13350b57cec5SDimitry Andric     // Adjust for token ranges.
133606c3fb27SDimitry Andric     if (H.RemoveRange.isTokenRange())
13370b57cec5SDimitry Andric       EInfo.second += Lexer::MeasureTokenLength(ELoc, SM, LangOpts);
13380b57cec5SDimitry Andric 
13390b57cec5SDimitry Andric     // We specifically do not do word-wrapping or tab-expansion here,
13400b57cec5SDimitry Andric     // because this is supposed to be easy to parse.
13410b57cec5SDimitry Andric     PresumedLoc PLoc = SM.getPresumedLoc(BLoc);
13420b57cec5SDimitry Andric     if (PLoc.isInvalid())
13430b57cec5SDimitry Andric       break;
13440b57cec5SDimitry Andric 
13450b57cec5SDimitry Andric     OS << "fix-it:\"";
13460b57cec5SDimitry Andric     OS.write_escaped(PLoc.getFilename());
13470b57cec5SDimitry Andric     OS << "\":{" << SM.getLineNumber(BInfo.first, BInfo.second)
13480b57cec5SDimitry Andric       << ':' << SM.getColumnNumber(BInfo.first, BInfo.second)
13490b57cec5SDimitry Andric       << '-' << SM.getLineNumber(EInfo.first, EInfo.second)
13500b57cec5SDimitry Andric       << ':' << SM.getColumnNumber(EInfo.first, EInfo.second)
13510b57cec5SDimitry Andric       << "}:\"";
135206c3fb27SDimitry Andric     OS.write_escaped(H.CodeToInsert);
13530b57cec5SDimitry Andric     OS << "\"\n";
13540b57cec5SDimitry Andric   }
13550b57cec5SDimitry Andric }
1356