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