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