blob: 6e6f3dd1bfee8db5e337f434075c5d2a3e1fee5c [file] [log] [blame]
Chandler Carrutha3028852011-10-15 23:43:53 +00001//===--- TextDiagnostic.cpp - Text Diagnostic Pretty-Printing -------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "clang/Frontend/TextDiagnostic.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000011#include "clang/Basic/CharInfo.h"
Douglas Gregor811db4e2012-10-23 22:26:28 +000012#include "clang/Basic/DiagnosticOptions.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000013#include "clang/Basic/FileManager.h"
14#include "clang/Basic/SourceManager.h"
Chandler Carrutha3028852011-10-15 23:43:53 +000015#include "clang/Lex/Lexer.h"
Chandler Carrutha3028852011-10-15 23:43:53 +000016#include "llvm/ADT/SmallString.h"
Seth Cantrell99e2fa82012-04-18 02:44:46 +000017#include "llvm/ADT/StringExtras.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000018#include "llvm/Support/ConvertUTF.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "llvm/Support/ErrorHandling.h"
20#include "llvm/Support/Locale.h"
21#include "llvm/Support/MemoryBuffer.h"
22#include "llvm/Support/raw_ostream.h"
Chandler Carrutha3028852011-10-15 23:43:53 +000023#include <algorithm>
Seth Cantrell99e2fa82012-04-18 02:44:46 +000024
Chandler Carrutha3028852011-10-15 23:43:53 +000025using namespace clang;
26
27static const enum raw_ostream::Colors noteColor =
28 raw_ostream::BLACK;
Tobias Grosser74160242014-02-28 09:11:08 +000029static const enum raw_ostream::Colors remarkColor =
30 raw_ostream::BLUE;
Chandler Carrutha3028852011-10-15 23:43:53 +000031static const enum raw_ostream::Colors fixitColor =
32 raw_ostream::GREEN;
33static const enum raw_ostream::Colors caretColor =
34 raw_ostream::GREEN;
35static const enum raw_ostream::Colors warningColor =
36 raw_ostream::MAGENTA;
Richard Trieu91844232012-06-26 18:18:47 +000037static const enum raw_ostream::Colors templateColor =
38 raw_ostream::CYAN;
Chandler Carrutha3028852011-10-15 23:43:53 +000039static const enum raw_ostream::Colors errorColor = raw_ostream::RED;
40static const enum raw_ostream::Colors fatalColor = raw_ostream::RED;
41// Used for changing only the bold attribute.
42static const enum raw_ostream::Colors savedColor =
43 raw_ostream::SAVEDCOLOR;
44
Richard Trieu91844232012-06-26 18:18:47 +000045/// \brief Add highlights to differences in template strings.
46static void applyTemplateHighlighting(raw_ostream &OS, StringRef Str,
Richard Trieua71f0de2012-06-28 22:39:03 +000047 bool &Normal, bool Bold) {
Benjamin Kramerfce09f12012-10-18 20:09:54 +000048 while (1) {
49 size_t Pos = Str.find(ToggleHighlight);
50 OS << Str.slice(0, Pos);
51 if (Pos == StringRef::npos)
52 break;
53
54 Str = Str.substr(Pos + 1);
55 if (Normal)
56 OS.changeColor(templateColor, true);
57 else {
58 OS.resetColor();
59 if (Bold)
60 OS.changeColor(savedColor, true);
Richard Trieu91844232012-06-26 18:18:47 +000061 }
Benjamin Kramerfce09f12012-10-18 20:09:54 +000062 Normal = !Normal;
63 }
Richard Trieu91844232012-06-26 18:18:47 +000064}
65
Chandler Carrutha3028852011-10-15 23:43:53 +000066/// \brief Number of spaces to indent when word-wrapping.
67const unsigned WordWrapIndentation = 6;
68
Benjamin Kramer556ab5e2012-05-01 14:34:11 +000069static int bytesSincePreviousTabOrLineBegin(StringRef SourceLine, size_t i) {
Seth Cantrell99e2fa82012-04-18 02:44:46 +000070 int bytes = 0;
71 while (0<i) {
72 if (SourceLine[--i]=='\t')
73 break;
74 ++bytes;
75 }
76 return bytes;
77}
78
79/// \brief returns a printable representation of first item from input range
80///
81/// This function returns a printable representation of the next item in a line
82/// of source. If the next byte begins a valid and printable character, that
83/// character is returned along with 'true'.
84///
85/// Otherwise, if the next byte begins a valid, but unprintable character, a
86/// printable, escaped representation of the character is returned, along with
87/// 'false'. Otherwise a printable, escaped representation of the next byte
88/// is returned along with 'false'.
89///
90/// \note The index is updated to be used with a subsequent call to
91/// printableTextForNextCharacter.
92///
93/// \param SourceLine The line of source
94/// \param i Pointer to byte index,
95/// \param TabStop used to expand tabs
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000096/// \return pair(printable text, 'true' iff original text was printable)
Seth Cantrell99e2fa82012-04-18 02:44:46 +000097///
Benjamin Kramer556ab5e2012-05-01 14:34:11 +000098static std::pair<SmallString<16>, bool>
Seth Cantrell99e2fa82012-04-18 02:44:46 +000099printableTextForNextCharacter(StringRef SourceLine, size_t *i,
100 unsigned TabStop) {
101 assert(i && "i must not be null");
102 assert(*i<SourceLine.size() && "must point to a valid index");
103
104 if (SourceLine[*i]=='\t') {
105 assert(0 < TabStop && TabStop <= DiagnosticOptions::MaxTabStop &&
106 "Invalid -ftabstop value");
107 unsigned col = bytesSincePreviousTabOrLineBegin(SourceLine, *i);
108 unsigned NumSpaces = TabStop - col%TabStop;
109 assert(0 < NumSpaces && NumSpaces <= TabStop
110 && "Invalid computation of space amt");
111 ++(*i);
112
113 SmallString<16> expandedTab;
114 expandedTab.assign(NumSpaces, ' ');
115 return std::make_pair(expandedTab, true);
116 }
117
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000118 unsigned char const *begin, *end;
119 begin = reinterpret_cast<unsigned char const *>(&*(SourceLine.begin() + *i));
Seth Cantrell29394162012-10-30 06:13:50 +0000120 end = begin + (SourceLine.size() - *i);
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000121
122 if (isLegalUTF8Sequence(begin, end)) {
123 UTF32 c;
124 UTF32 *cptr = &c;
125 unsigned char const *original_begin = begin;
Seth Cantrellee2effd2012-10-30 06:13:52 +0000126 unsigned char const *cp_end = begin+getNumBytesForUTF8(SourceLine[*i]);
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000127
128 ConversionResult res = ConvertUTF8toUTF32(&begin, cp_end, &cptr, cptr+1,
129 strictConversion);
Matt Beaumont-Gay69e227b2012-04-18 17:25:16 +0000130 (void)res;
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000131 assert(conversionOK==res);
132 assert(0 < begin-original_begin
133 && "we must be further along in the string now");
134 *i += begin-original_begin;
135
136 if (!llvm::sys::locale::isPrint(c)) {
137 // If next character is valid UTF-8, but not printable
138 SmallString<16> expandedCP("<U+>");
139 while (c) {
140 expandedCP.insert(expandedCP.begin()+3, llvm::hexdigit(c%16));
141 c/=16;
142 }
143 while (expandedCP.size() < 8)
144 expandedCP.insert(expandedCP.begin()+3, llvm::hexdigit(0));
145 return std::make_pair(expandedCP, false);
146 }
147
148 // If next character is valid UTF-8, and printable
149 return std::make_pair(SmallString<16>(original_begin, cp_end), true);
150
151 }
152
153 // If next byte is not valid UTF-8 (and therefore not printable)
154 SmallString<16> expandedByte("<XX>");
155 unsigned char byte = SourceLine[*i];
156 expandedByte[1] = llvm::hexdigit(byte / 16);
157 expandedByte[2] = llvm::hexdigit(byte % 16);
158 ++(*i);
159 return std::make_pair(expandedByte, false);
160}
161
Benjamin Kramer556ab5e2012-05-01 14:34:11 +0000162static void expandTabs(std::string &SourceLine, unsigned TabStop) {
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000163 size_t i = SourceLine.size();
164 while (i>0) {
165 i--;
166 if (SourceLine[i]!='\t')
167 continue;
168 size_t tmp_i = i;
169 std::pair<SmallString<16>,bool> res
170 = printableTextForNextCharacter(SourceLine, &tmp_i, TabStop);
171 SourceLine.replace(i, 1, res.first.c_str());
172 }
173}
174
175/// This function takes a raw source line and produces a mapping from the bytes
176/// of the printable representation of the line to the columns those printable
177/// characters will appear at (numbering the first column as 0).
178///
179/// If a byte 'i' corresponds to muliple columns (e.g. the byte contains a tab
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000180/// character) then the array will map that byte to the first column the
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000181/// tab appears at and the next value in the map will have been incremented
182/// more than once.
183///
184/// If a byte is the first in a sequence of bytes that together map to a single
185/// entity in the output, then the array will map that byte to the appropriate
186/// column while the subsequent bytes will be -1.
187///
188/// The last element in the array does not correspond to any byte in the input
189/// and instead is the number of columns needed to display the source
190///
191/// example: (given a tabstop of 8)
192///
193/// "a \t \u3042" -> {0,1,2,8,9,-1,-1,11}
194///
James Dennettf347d932012-06-22 05:33:23 +0000195/// (\\u3042 is represented in UTF-8 by three bytes and takes two columns to
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000196/// display)
Benjamin Kramer556ab5e2012-05-01 14:34:11 +0000197static void byteToColumn(StringRef SourceLine, unsigned TabStop,
198 SmallVectorImpl<int> &out) {
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000199 out.clear();
200
201 if (SourceLine.empty()) {
202 out.resize(1u,0);
203 return;
204 }
205
206 out.resize(SourceLine.size()+1, -1);
207
208 int columns = 0;
209 size_t i = 0;
210 while (i<SourceLine.size()) {
211 out[i] = columns;
212 std::pair<SmallString<16>,bool> res
213 = printableTextForNextCharacter(SourceLine, &i, TabStop);
214 columns += llvm::sys::locale::columnWidth(res.first);
215 }
216 out.back() = columns;
217}
218
219/// This function takes a raw source line and produces a mapping from columns
220/// to the byte of the source line that produced the character displaying at
221/// that column. This is the inverse of the mapping produced by byteToColumn()
222///
223/// The last element in the array is the number of bytes in the source string
224///
225/// example: (given a tabstop of 8)
226///
227/// "a \t \u3042" -> {0,1,2,-1,-1,-1,-1,-1,3,4,-1,7}
228///
James Dennettf347d932012-06-22 05:33:23 +0000229/// (\\u3042 is represented in UTF-8 by three bytes and takes two columns to
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000230/// display)
Benjamin Kramer556ab5e2012-05-01 14:34:11 +0000231static void columnToByte(StringRef SourceLine, unsigned TabStop,
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000232 SmallVectorImpl<int> &out) {
233 out.clear();
234
235 if (SourceLine.empty()) {
236 out.resize(1u, 0);
237 return;
238 }
239
240 int columns = 0;
241 size_t i = 0;
242 while (i<SourceLine.size()) {
243 out.resize(columns+1, -1);
244 out.back() = i;
245 std::pair<SmallString<16>,bool> res
246 = printableTextForNextCharacter(SourceLine, &i, TabStop);
247 columns += llvm::sys::locale::columnWidth(res.first);
248 }
249 out.resize(columns+1, -1);
250 out.back() = i;
251}
252
Benjamin Kramer2a812282012-12-01 20:58:01 +0000253namespace {
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000254struct SourceColumnMap {
255 SourceColumnMap(StringRef SourceLine, unsigned TabStop)
256 : m_SourceLine(SourceLine) {
257
258 ::byteToColumn(SourceLine, TabStop, m_byteToColumn);
259 ::columnToByte(SourceLine, TabStop, m_columnToByte);
260
261 assert(m_byteToColumn.size()==SourceLine.size()+1);
262 assert(0 < m_byteToColumn.size() && 0 < m_columnToByte.size());
263 assert(m_byteToColumn.size()
264 == static_cast<unsigned>(m_columnToByte.back()+1));
265 assert(static_cast<unsigned>(m_byteToColumn.back()+1)
266 == m_columnToByte.size());
267 }
268 int columns() const { return m_byteToColumn.back(); }
269 int bytes() const { return m_columnToByte.back(); }
Richard Smithfab4b1a2012-09-13 18:37:50 +0000270
271 /// \brief Map a byte to the column which it is at the start of, or return -1
272 /// if it is not at the start of a column (for a UTF-8 trailing byte).
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000273 int byteToColumn(int n) const {
274 assert(0<=n && n<static_cast<int>(m_byteToColumn.size()));
275 return m_byteToColumn[n];
276 }
Richard Smithfab4b1a2012-09-13 18:37:50 +0000277
278 /// \brief Map a byte to the first column which contains it.
279 int byteToContainingColumn(int N) const {
280 assert(0 <= N && N < static_cast<int>(m_byteToColumn.size()));
281 while (m_byteToColumn[N] == -1)
282 --N;
283 return m_byteToColumn[N];
284 }
285
286 /// \brief Map a column to the byte which starts the column, or return -1 if
287 /// the column the second or subsequent column of an expanded tab or similar
288 /// multi-column entity.
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000289 int columnToByte(int n) const {
290 assert(0<=n && n<static_cast<int>(m_columnToByte.size()));
291 return m_columnToByte[n];
292 }
Richard Smithfab4b1a2012-09-13 18:37:50 +0000293
294 /// \brief Map from a byte index to the next byte which starts a column.
295 int startOfNextColumn(int N) const {
296 assert(0 <= N && N < static_cast<int>(m_columnToByte.size() - 1));
297 while (byteToColumn(++N) == -1) {}
298 return N;
299 }
300
301 /// \brief Map from a byte index to the previous byte which starts a column.
302 int startOfPreviousColumn(int N) const {
303 assert(0 < N && N < static_cast<int>(m_columnToByte.size()));
Seth Cantrelld38c7082012-11-03 21:21:14 +0000304 while (byteToColumn(--N) == -1) {}
Richard Smithfab4b1a2012-09-13 18:37:50 +0000305 return N;
306 }
307
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000308 StringRef getSourceLine() const {
309 return m_SourceLine;
310 }
311
312private:
313 const std::string m_SourceLine;
314 SmallVector<int,200> m_byteToColumn;
315 SmallVector<int,200> m_columnToByte;
316};
Benjamin Kramer2a812282012-12-01 20:58:01 +0000317} // end anonymous namespace
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000318
Chandler Carrutha3028852011-10-15 23:43:53 +0000319/// \brief When the source code line we want to print is too long for
320/// the terminal, select the "interesting" region.
Chandler Carruthab4c1da2011-10-15 23:54:09 +0000321static void selectInterestingSourceRegion(std::string &SourceLine,
Chandler Carrutha3028852011-10-15 23:43:53 +0000322 std::string &CaretLine,
323 std::string &FixItInsertionLine,
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000324 unsigned Columns,
325 const SourceColumnMap &map) {
326 unsigned MaxColumns = std::max<unsigned>(map.columns(),
327 std::max(CaretLine.size(),
328 FixItInsertionLine.size()));
329 // if the number of columns is less than the desired number we're done
330 if (MaxColumns <= Columns)
331 return;
332
Jordan Rosee2fad6d2013-06-07 17:16:01 +0000333 // No special characters are allowed in CaretLine.
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000334 assert(CaretLine.end() ==
335 std::find_if(CaretLine.begin(), CaretLine.end(),
Benjamin Kramerbbdd7642014-03-01 14:48:57 +0000336 [](char c) { return c < ' ' || '~' < c; }));
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000337
Chandler Carrutha3028852011-10-15 23:43:53 +0000338 // Find the slice that we need to display the full caret line
339 // correctly.
340 unsigned CaretStart = 0, CaretEnd = CaretLine.size();
341 for (; CaretStart != CaretEnd; ++CaretStart)
Jordan Rosea7d03842013-02-08 22:30:41 +0000342 if (!isWhitespace(CaretLine[CaretStart]))
Chandler Carrutha3028852011-10-15 23:43:53 +0000343 break;
344
345 for (; CaretEnd != CaretStart; --CaretEnd)
Jordan Rosea7d03842013-02-08 22:30:41 +0000346 if (!isWhitespace(CaretLine[CaretEnd - 1]))
Chandler Carrutha3028852011-10-15 23:43:53 +0000347 break;
348
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000349 // caret has already been inserted into CaretLine so the above whitespace
350 // check is guaranteed to include the caret
Chandler Carrutha3028852011-10-15 23:43:53 +0000351
352 // If we have a fix-it line, make sure the slice includes all of the
353 // fix-it information.
354 if (!FixItInsertionLine.empty()) {
355 unsigned FixItStart = 0, FixItEnd = FixItInsertionLine.size();
356 for (; FixItStart != FixItEnd; ++FixItStart)
Jordan Rosea7d03842013-02-08 22:30:41 +0000357 if (!isWhitespace(FixItInsertionLine[FixItStart]))
Chandler Carrutha3028852011-10-15 23:43:53 +0000358 break;
359
360 for (; FixItEnd != FixItStart; --FixItEnd)
Jordan Rosea7d03842013-02-08 22:30:41 +0000361 if (!isWhitespace(FixItInsertionLine[FixItEnd - 1]))
Chandler Carrutha3028852011-10-15 23:43:53 +0000362 break;
363
Jordan Rosee2fad6d2013-06-07 17:16:01 +0000364 // We can safely use the byte offset FixItStart as the column offset
365 // because the characters up until FixItStart are all ASCII whitespace
366 // characters.
367 unsigned FixItStartCol = FixItStart;
368 unsigned FixItEndCol
369 = llvm::sys::locale::columnWidth(FixItInsertionLine.substr(0, FixItEnd));
370
371 CaretStart = std::min(FixItStartCol, CaretStart);
372 CaretEnd = std::max(FixItEndCol, CaretEnd);
Chandler Carrutha3028852011-10-15 23:43:53 +0000373 }
374
Seth Cantrellac6fb8f2012-05-24 05:14:44 +0000375 // CaretEnd may have been set at the middle of a character
376 // If it's not at a character's first column then advance it past the current
377 // character.
378 while (static_cast<int>(CaretEnd) < map.columns() &&
379 -1 == map.columnToByte(CaretEnd))
380 ++CaretEnd;
381
382 assert((static_cast<int>(CaretStart) > map.columns() ||
383 -1!=map.columnToByte(CaretStart)) &&
384 "CaretStart must not point to a column in the middle of a source"
385 " line character");
386 assert((static_cast<int>(CaretEnd) > map.columns() ||
387 -1!=map.columnToByte(CaretEnd)) &&
388 "CaretEnd must not point to a column in the middle of a source line"
389 " character");
390
Chandler Carrutha3028852011-10-15 23:43:53 +0000391 // CaretLine[CaretStart, CaretEnd) contains all of the interesting
392 // parts of the caret line. While this slice is smaller than the
393 // number of columns we have, try to grow the slice to encompass
394 // more context.
395
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000396 unsigned SourceStart = map.columnToByte(std::min<unsigned>(CaretStart,
397 map.columns()));
398 unsigned SourceEnd = map.columnToByte(std::min<unsigned>(CaretEnd,
399 map.columns()));
400
401 unsigned CaretColumnsOutsideSource = CaretEnd-CaretStart
402 - (map.byteToColumn(SourceEnd)-map.byteToColumn(SourceStart));
403
404 char const *front_ellipse = " ...";
405 char const *front_space = " ";
406 char const *back_ellipse = "...";
407 unsigned ellipses_space = strlen(front_ellipse) + strlen(back_ellipse);
Chandler Carrutha3028852011-10-15 23:43:53 +0000408
409 unsigned TargetColumns = Columns;
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000410 // Give us extra room for the ellipses
411 // and any of the caret line that extends past the source
412 if (TargetColumns > ellipses_space+CaretColumnsOutsideSource)
413 TargetColumns -= ellipses_space+CaretColumnsOutsideSource;
414
415 while (SourceStart>0 || SourceEnd<SourceLine.size()) {
Chandler Carrutha3028852011-10-15 23:43:53 +0000416 bool ExpandedRegion = false;
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000417
418 if (SourceStart>0) {
Seth Cantrell6292e5b82012-11-03 21:21:17 +0000419 unsigned NewStart = map.startOfPreviousColumn(SourceStart);
Chandler Carrutha3028852011-10-15 23:43:53 +0000420
421 // Skip over any whitespace we see here; we're looking for
422 // another bit of interesting text.
Richard Smithfab4b1a2012-09-13 18:37:50 +0000423 // FIXME: Detect non-ASCII whitespace characters too.
Jordan Rosea7d03842013-02-08 22:30:41 +0000424 while (NewStart && isWhitespace(SourceLine[NewStart]))
Richard Smithfab4b1a2012-09-13 18:37:50 +0000425 NewStart = map.startOfPreviousColumn(NewStart);
Chandler Carrutha3028852011-10-15 23:43:53 +0000426
427 // Skip over this bit of "interesting" text.
Richard Smithfab4b1a2012-09-13 18:37:50 +0000428 while (NewStart) {
429 unsigned Prev = map.startOfPreviousColumn(NewStart);
Jordan Rosea7d03842013-02-08 22:30:41 +0000430 if (isWhitespace(SourceLine[Prev]))
Richard Smithfab4b1a2012-09-13 18:37:50 +0000431 break;
432 NewStart = Prev;
433 }
Chandler Carrutha3028852011-10-15 23:43:53 +0000434
Richard Smithfab4b1a2012-09-13 18:37:50 +0000435 assert(map.byteToColumn(NewStart) != -1);
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000436 unsigned NewColumns = map.byteToColumn(SourceEnd) -
437 map.byteToColumn(NewStart);
438 if (NewColumns <= TargetColumns) {
439 SourceStart = NewStart;
Chandler Carrutha3028852011-10-15 23:43:53 +0000440 ExpandedRegion = true;
441 }
442 }
443
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000444 if (SourceEnd<SourceLine.size()) {
Seth Cantrell6292e5b82012-11-03 21:21:17 +0000445 unsigned NewEnd = map.startOfNextColumn(SourceEnd);
Chandler Carrutha3028852011-10-15 23:43:53 +0000446
447 // Skip over any whitespace we see here; we're looking for
448 // another bit of interesting text.
Richard Smithfab4b1a2012-09-13 18:37:50 +0000449 // FIXME: Detect non-ASCII whitespace characters too.
Jordan Rosea7d03842013-02-08 22:30:41 +0000450 while (NewEnd < SourceLine.size() && isWhitespace(SourceLine[NewEnd]))
Richard Smithfab4b1a2012-09-13 18:37:50 +0000451 NewEnd = map.startOfNextColumn(NewEnd);
Chandler Carrutha3028852011-10-15 23:43:53 +0000452
453 // Skip over this bit of "interesting" text.
Jordan Rosea7d03842013-02-08 22:30:41 +0000454 while (NewEnd < SourceLine.size() && isWhitespace(SourceLine[NewEnd]))
Richard Smithfab4b1a2012-09-13 18:37:50 +0000455 NewEnd = map.startOfNextColumn(NewEnd);
Chandler Carrutha3028852011-10-15 23:43:53 +0000456
Richard Smithfab4b1a2012-09-13 18:37:50 +0000457 assert(map.byteToColumn(NewEnd) != -1);
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000458 unsigned NewColumns = map.byteToColumn(NewEnd) -
459 map.byteToColumn(SourceStart);
460 if (NewColumns <= TargetColumns) {
461 SourceEnd = NewEnd;
Chandler Carrutha3028852011-10-15 23:43:53 +0000462 ExpandedRegion = true;
463 }
464 }
465
466 if (!ExpandedRegion)
467 break;
468 }
469
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000470 CaretStart = map.byteToColumn(SourceStart);
471 CaretEnd = map.byteToColumn(SourceEnd) + CaretColumnsOutsideSource;
472
Chandler Carrutha3028852011-10-15 23:43:53 +0000473 // [CaretStart, CaretEnd) is the slice we want. Update the various
474 // output lines to show only this slice, with two-space padding
475 // before the lines so that it looks nicer.
Chandler Carrutha3028852011-10-15 23:43:53 +0000476
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000477 assert(CaretStart!=(unsigned)-1 && CaretEnd!=(unsigned)-1 &&
478 SourceStart!=(unsigned)-1 && SourceEnd!=(unsigned)-1);
479 assert(SourceStart <= SourceEnd);
480 assert(CaretStart <= CaretEnd);
481
482 unsigned BackColumnsRemoved
483 = map.byteToColumn(SourceLine.size())-map.byteToColumn(SourceEnd);
484 unsigned FrontColumnsRemoved = CaretStart;
485 unsigned ColumnsKept = CaretEnd-CaretStart;
486
487 // We checked up front that the line needed truncation
488 assert(FrontColumnsRemoved+ColumnsKept+BackColumnsRemoved > Columns);
489
490 // The line needs some trunctiona, and we'd prefer to keep the front
491 // if possible, so remove the back
Seth Cantrell40f87b12012-11-03 23:56:43 +0000492 if (BackColumnsRemoved > strlen(back_ellipse))
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000493 SourceLine.replace(SourceEnd, std::string::npos, back_ellipse);
494
495 // If that's enough then we're done
496 if (FrontColumnsRemoved+ColumnsKept <= Columns)
497 return;
498
499 // Otherwise remove the front as well
Seth Cantrell40f87b12012-11-03 23:56:43 +0000500 if (FrontColumnsRemoved > strlen(front_ellipse)) {
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000501 SourceLine.replace(0, SourceStart, front_ellipse);
502 CaretLine.replace(0, CaretStart, front_space);
503 if (!FixItInsertionLine.empty())
504 FixItInsertionLine.replace(0, CaretStart, front_space);
Chandler Carrutha3028852011-10-15 23:43:53 +0000505 }
506}
507
Chandler Carrutha3028852011-10-15 23:43:53 +0000508/// \brief Skip over whitespace in the string, starting at the given
509/// index.
510///
511/// \returns The index of the first non-whitespace character that is
512/// greater than or equal to Idx or, if no such character exists,
513/// returns the end of the string.
514static unsigned skipWhitespace(unsigned Idx, StringRef Str, unsigned Length) {
Jordan Rosea7d03842013-02-08 22:30:41 +0000515 while (Idx < Length && isWhitespace(Str[Idx]))
Chandler Carrutha3028852011-10-15 23:43:53 +0000516 ++Idx;
517 return Idx;
518}
519
520/// \brief If the given character is the start of some kind of
521/// balanced punctuation (e.g., quotes or parentheses), return the
522/// character that will terminate the punctuation.
523///
524/// \returns The ending punctuation character, if any, or the NULL
525/// character if the input character does not start any punctuation.
526static inline char findMatchingPunctuation(char c) {
527 switch (c) {
528 case '\'': return '\'';
529 case '`': return '\'';
530 case '"': return '"';
531 case '(': return ')';
532 case '[': return ']';
533 case '{': return '}';
534 default: break;
535 }
536
537 return 0;
538}
539
540/// \brief Find the end of the word starting at the given offset
541/// within a string.
542///
543/// \returns the index pointing one character past the end of the
544/// word.
545static unsigned findEndOfWord(unsigned Start, StringRef Str,
546 unsigned Length, unsigned Column,
547 unsigned Columns) {
548 assert(Start < Str.size() && "Invalid start position!");
549 unsigned End = Start + 1;
550
551 // If we are already at the end of the string, take that as the word.
552 if (End == Str.size())
553 return End;
554
555 // Determine if the start of the string is actually opening
556 // punctuation, e.g., a quote or parentheses.
557 char EndPunct = findMatchingPunctuation(Str[Start]);
558 if (!EndPunct) {
559 // This is a normal word. Just find the first space character.
Jordan Rosea7d03842013-02-08 22:30:41 +0000560 while (End < Length && !isWhitespace(Str[End]))
Chandler Carrutha3028852011-10-15 23:43:53 +0000561 ++End;
562 return End;
563 }
564
565 // We have the start of a balanced punctuation sequence (quotes,
566 // parentheses, etc.). Determine the full sequence is.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000567 SmallString<16> PunctuationEndStack;
Chandler Carrutha3028852011-10-15 23:43:53 +0000568 PunctuationEndStack.push_back(EndPunct);
569 while (End < Length && !PunctuationEndStack.empty()) {
570 if (Str[End] == PunctuationEndStack.back())
571 PunctuationEndStack.pop_back();
572 else if (char SubEndPunct = findMatchingPunctuation(Str[End]))
573 PunctuationEndStack.push_back(SubEndPunct);
574
575 ++End;
576 }
577
578 // Find the first space character after the punctuation ended.
Jordan Rosea7d03842013-02-08 22:30:41 +0000579 while (End < Length && !isWhitespace(Str[End]))
Chandler Carrutha3028852011-10-15 23:43:53 +0000580 ++End;
581
582 unsigned PunctWordLength = End - Start;
583 if (// If the word fits on this line
584 Column + PunctWordLength <= Columns ||
585 // ... or the word is "short enough" to take up the next line
586 // without too much ugly white space
587 PunctWordLength < Columns/3)
588 return End; // Take the whole thing as a single "word".
589
590 // The whole quoted/parenthesized string is too long to print as a
591 // single "word". Instead, find the "word" that starts just after
592 // the punctuation and use that end-point instead. This will recurse
593 // until it finds something small enough to consider a word.
594 return findEndOfWord(Start + 1, Str, Length, Column + 1, Columns);
595}
596
597/// \brief Print the given string to a stream, word-wrapping it to
598/// some number of columns in the process.
599///
600/// \param OS the stream to which the word-wrapping string will be
601/// emitted.
602/// \param Str the string to word-wrap and output.
603/// \param Columns the number of columns to word-wrap to.
604/// \param Column the column number at which the first character of \p
605/// Str will be printed. This will be non-zero when part of the first
606/// line has already been printed.
Richard Trieua71f0de2012-06-28 22:39:03 +0000607/// \param Bold if the current text should be bold
Chandler Carrutha3028852011-10-15 23:43:53 +0000608/// \param Indentation the number of spaces to indent any lines beyond
609/// the first line.
610/// \returns true if word-wrapping was required, or false if the
611/// string fit on the first line.
612static bool printWordWrapped(raw_ostream &OS, StringRef Str,
613 unsigned Columns,
614 unsigned Column = 0,
Richard Trieua71f0de2012-06-28 22:39:03 +0000615 bool Bold = false,
Chandler Carrutha3028852011-10-15 23:43:53 +0000616 unsigned Indentation = WordWrapIndentation) {
617 const unsigned Length = std::min(Str.find('\n'), Str.size());
Richard Trieu91844232012-06-26 18:18:47 +0000618 bool TextNormal = true;
Chandler Carrutha3028852011-10-15 23:43:53 +0000619
620 // The string used to indent each line.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000621 SmallString<16> IndentStr;
Chandler Carrutha3028852011-10-15 23:43:53 +0000622 IndentStr.assign(Indentation, ' ');
623 bool Wrapped = false;
624 for (unsigned WordStart = 0, WordEnd; WordStart < Length;
625 WordStart = WordEnd) {
626 // Find the beginning of the next word.
627 WordStart = skipWhitespace(WordStart, Str, Length);
628 if (WordStart == Length)
629 break;
630
631 // Find the end of this word.
632 WordEnd = findEndOfWord(WordStart, Str, Length, Column, Columns);
633
634 // Does this word fit on the current line?
635 unsigned WordLength = WordEnd - WordStart;
636 if (Column + WordLength < Columns) {
637 // This word fits on the current line; print it there.
638 if (WordStart) {
639 OS << ' ';
640 Column += 1;
641 }
Richard Trieu91844232012-06-26 18:18:47 +0000642 applyTemplateHighlighting(OS, Str.substr(WordStart, WordLength),
Richard Trieua71f0de2012-06-28 22:39:03 +0000643 TextNormal, Bold);
Chandler Carrutha3028852011-10-15 23:43:53 +0000644 Column += WordLength;
645 continue;
646 }
647
648 // This word does not fit on the current line, so wrap to the next
649 // line.
650 OS << '\n';
651 OS.write(&IndentStr[0], Indentation);
Richard Trieu91844232012-06-26 18:18:47 +0000652 applyTemplateHighlighting(OS, Str.substr(WordStart, WordLength),
Richard Trieua71f0de2012-06-28 22:39:03 +0000653 TextNormal, Bold);
Chandler Carrutha3028852011-10-15 23:43:53 +0000654 Column = Indentation + WordLength;
655 Wrapped = true;
656 }
657
658 // Append any remaning text from the message with its existing formatting.
Richard Trieua71f0de2012-06-28 22:39:03 +0000659 applyTemplateHighlighting(OS, Str.substr(Length), TextNormal, Bold);
Richard Trieu91844232012-06-26 18:18:47 +0000660
661 assert(TextNormal && "Text highlighted at end of diagnostic message.");
Chandler Carrutha3028852011-10-15 23:43:53 +0000662
663 return Wrapped;
664}
665
666TextDiagnostic::TextDiagnostic(raw_ostream &OS,
Chandler Carrutha3028852011-10-15 23:43:53 +0000667 const LangOptions &LangOpts,
Douglas Gregor811db4e2012-10-23 22:26:28 +0000668 DiagnosticOptions *DiagOpts)
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +0000669 : DiagnosticRenderer(LangOpts, DiagOpts), OS(OS) {}
Chandler Carrutha3028852011-10-15 23:43:53 +0000670
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000671TextDiagnostic::~TextDiagnostic() {}
Chandler Carrutha3028852011-10-15 23:43:53 +0000672
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000673void
674TextDiagnostic::emitDiagnosticMessage(SourceLocation Loc,
675 PresumedLoc PLoc,
676 DiagnosticsEngine::Level Level,
677 StringRef Message,
678 ArrayRef<clang::CharSourceRange> Ranges,
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +0000679 const SourceManager *SM,
Ted Kremenek0964cca2012-02-14 02:46:00 +0000680 DiagOrStoredDiag D) {
Chandler Carrutha3028852011-10-15 23:43:53 +0000681 uint64_t StartOfLocationInfo = OS.tell();
682
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000683 // Emit the location of this particular diagnostic.
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +0000684 if (Loc.isValid())
685 emitDiagnosticLoc(Loc, PLoc, Level, Ranges, *SM);
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000686
Douglas Gregor811db4e2012-10-23 22:26:28 +0000687 if (DiagOpts->ShowColors)
Chandler Carrutha3028852011-10-15 23:43:53 +0000688 OS.resetColor();
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000689
Hans Wennborgf4aee182013-09-24 00:08:55 +0000690 printDiagnosticLevel(OS, Level, DiagOpts->ShowColors,
691 DiagOpts->CLFallbackMode);
Alp Tokera68ad102014-06-21 23:31:52 +0000692 printDiagnosticMessage(OS,
693 /*IsSupplemental*/ Level == DiagnosticsEngine::Note,
694 Message, OS.tell() - StartOfLocationInfo,
Douglas Gregor811db4e2012-10-23 22:26:28 +0000695 DiagOpts->MessageLength, DiagOpts->ShowColors);
Chandler Carrutha3028852011-10-15 23:43:53 +0000696}
697
Chandler Carruth07c346d2011-10-15 23:48:02 +0000698/*static*/ void
699TextDiagnostic::printDiagnosticLevel(raw_ostream &OS,
700 DiagnosticsEngine::Level Level,
Hans Wennborgf4aee182013-09-24 00:08:55 +0000701 bool ShowColors,
702 bool CLFallbackMode) {
Chandler Carruth07c346d2011-10-15 23:48:02 +0000703 if (ShowColors) {
704 // Print diagnostic category in bold and color
705 switch (Level) {
706 case DiagnosticsEngine::Ignored:
707 llvm_unreachable("Invalid diagnostic type");
708 case DiagnosticsEngine::Note: OS.changeColor(noteColor, true); break;
Tobias Grosser74160242014-02-28 09:11:08 +0000709 case DiagnosticsEngine::Remark: OS.changeColor(remarkColor, true); break;
Chandler Carruth07c346d2011-10-15 23:48:02 +0000710 case DiagnosticsEngine::Warning: OS.changeColor(warningColor, true); break;
711 case DiagnosticsEngine::Error: OS.changeColor(errorColor, true); break;
712 case DiagnosticsEngine::Fatal: OS.changeColor(fatalColor, true); break;
713 }
714 }
715
716 switch (Level) {
717 case DiagnosticsEngine::Ignored:
718 llvm_unreachable("Invalid diagnostic type");
Hans Wennborgf4aee182013-09-24 00:08:55 +0000719 case DiagnosticsEngine::Note: OS << "note"; break;
Tobias Grosser74160242014-02-28 09:11:08 +0000720 case DiagnosticsEngine::Remark: OS << "remark"; break;
Hans Wennborgf4aee182013-09-24 00:08:55 +0000721 case DiagnosticsEngine::Warning: OS << "warning"; break;
722 case DiagnosticsEngine::Error: OS << "error"; break;
723 case DiagnosticsEngine::Fatal: OS << "fatal error"; break;
Chandler Carruth07c346d2011-10-15 23:48:02 +0000724 }
725
Hans Wennborgf4aee182013-09-24 00:08:55 +0000726 // In clang-cl /fallback mode, print diagnostics as "error(clang):". This
727 // makes it more clear whether a message is coming from clang or cl.exe,
728 // and it prevents MSBuild from concluding that the build failed just because
729 // there is an "error:" in the output.
730 if (CLFallbackMode)
731 OS << "(clang)";
732
733 OS << ": ";
734
Chandler Carruth07c346d2011-10-15 23:48:02 +0000735 if (ShowColors)
736 OS.resetColor();
737}
738
Alp Tokera68ad102014-06-21 23:31:52 +0000739/*static*/
740void TextDiagnostic::printDiagnosticMessage(raw_ostream &OS,
741 bool IsSupplemental,
742 StringRef Message,
743 unsigned CurrentColumn,
744 unsigned Columns, bool ShowColors) {
Richard Trieua71f0de2012-06-28 22:39:03 +0000745 bool Bold = false;
Alp Tokera68ad102014-06-21 23:31:52 +0000746 if (ShowColors && !IsSupplemental) {
747 // Print primary diagnostic messages in bold and without color, to visually
748 // indicate the transition from continuation notes and other output.
749 OS.changeColor(savedColor, true);
750 Bold = true;
Chandler Carruth07c346d2011-10-15 23:48:02 +0000751 }
752
753 if (Columns)
Richard Trieua71f0de2012-06-28 22:39:03 +0000754 printWordWrapped(OS, Message, Columns, CurrentColumn, Bold);
David Blaikie9e55d742012-06-28 21:46:07 +0000755 else {
756 bool Normal = true;
Richard Trieua71f0de2012-06-28 22:39:03 +0000757 applyTemplateHighlighting(OS, Message, Normal, Bold);
David Blaikie9e55d742012-06-28 21:46:07 +0000758 assert(Normal && "Formatting should have returned to normal");
759 }
Chandler Carruth07c346d2011-10-15 23:48:02 +0000760
761 if (ShowColors)
762 OS.resetColor();
763 OS << '\n';
764}
765
Chandler Carruth07c346d2011-10-15 23:48:02 +0000766/// \brief Print out the file/line/column information and include trace.
767///
768/// This method handlen the emission of the diagnostic location information.
769/// This includes extracting as much location information as is present for
770/// the diagnostic and printing it, as well as any include stack or source
771/// ranges necessary.
Chandler Carruthab4c1da2011-10-15 23:54:09 +0000772void TextDiagnostic::emitDiagnosticLoc(SourceLocation Loc, PresumedLoc PLoc,
Chandler Carruth07c346d2011-10-15 23:48:02 +0000773 DiagnosticsEngine::Level Level,
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +0000774 ArrayRef<CharSourceRange> Ranges,
775 const SourceManager &SM) {
Chandler Carruth07c346d2011-10-15 23:48:02 +0000776 if (PLoc.isInvalid()) {
777 // At least print the file name if available:
778 FileID FID = SM.getFileID(Loc);
779 if (!FID.isInvalid()) {
780 const FileEntry* FE = SM.getFileEntryForID(FID);
Ben Langmuirc8a71462014-02-27 17:23:33 +0000781 if (FE && FE->isValid()) {
Chandler Carruth07c346d2011-10-15 23:48:02 +0000782 OS << FE->getName();
Rafael Espindolaf8f91b82013-08-01 21:42:11 +0000783 if (FE->isInPCH())
Chandler Carruth07c346d2011-10-15 23:48:02 +0000784 OS << " (in PCH)";
Chandler Carruth07c346d2011-10-15 23:48:02 +0000785 OS << ": ";
786 }
787 }
788 return;
789 }
790 unsigned LineNo = PLoc.getLine();
791
Douglas Gregor811db4e2012-10-23 22:26:28 +0000792 if (!DiagOpts->ShowLocation)
Chandler Carruth07c346d2011-10-15 23:48:02 +0000793 return;
794
Douglas Gregor811db4e2012-10-23 22:26:28 +0000795 if (DiagOpts->ShowColors)
Chandler Carruth07c346d2011-10-15 23:48:02 +0000796 OS.changeColor(savedColor, true);
797
798 OS << PLoc.getFilename();
Douglas Gregor79591782012-10-23 23:11:23 +0000799 switch (DiagOpts->getFormat()) {
Chandler Carruth07c346d2011-10-15 23:48:02 +0000800 case DiagnosticOptions::Clang: OS << ':' << LineNo; break;
801 case DiagnosticOptions::Msvc: OS << '(' << LineNo; break;
802 case DiagnosticOptions::Vi: OS << " +" << LineNo; break;
803 }
804
Douglas Gregor811db4e2012-10-23 22:26:28 +0000805 if (DiagOpts->ShowColumn)
Chandler Carruth07c346d2011-10-15 23:48:02 +0000806 // Compute the column number.
807 if (unsigned ColNo = PLoc.getColumn()) {
Douglas Gregor79591782012-10-23 23:11:23 +0000808 if (DiagOpts->getFormat() == DiagnosticOptions::Msvc) {
Chandler Carruth07c346d2011-10-15 23:48:02 +0000809 OS << ',';
Yunzhong Gao820c6872014-03-07 00:23:36 +0000810 // Visual Studio 2010 or earlier expects column number to be off by one
Saleem Abdulrasoolc68237b2014-07-16 03:13:50 +0000811 if (LangOpts.MSCompatibilityVersion &&
812 LangOpts.MSCompatibilityVersion < 170000000)
Yunzhong Gao820c6872014-03-07 00:23:36 +0000813 ColNo--;
Chandler Carruth07c346d2011-10-15 23:48:02 +0000814 } else
815 OS << ':';
816 OS << ColNo;
817 }
Douglas Gregor79591782012-10-23 23:11:23 +0000818 switch (DiagOpts->getFormat()) {
Chandler Carruth07c346d2011-10-15 23:48:02 +0000819 case DiagnosticOptions::Clang:
820 case DiagnosticOptions::Vi: OS << ':'; break;
821 case DiagnosticOptions::Msvc: OS << ") : "; break;
822 }
823
Douglas Gregor811db4e2012-10-23 22:26:28 +0000824 if (DiagOpts->ShowSourceRanges && !Ranges.empty()) {
Chandler Carruth07c346d2011-10-15 23:48:02 +0000825 FileID CaretFileID =
826 SM.getFileID(SM.getExpansionLoc(Loc));
827 bool PrintedRange = false;
828
829 for (ArrayRef<CharSourceRange>::const_iterator RI = Ranges.begin(),
830 RE = Ranges.end();
831 RI != RE; ++RI) {
832 // Ignore invalid ranges.
833 if (!RI->isValid()) continue;
834
835 SourceLocation B = SM.getExpansionLoc(RI->getBegin());
836 SourceLocation E = SM.getExpansionLoc(RI->getEnd());
837
838 // If the End location and the start location are the same and are a
839 // macro location, then the range was something that came from a
840 // macro expansion or _Pragma. If this is an object-like macro, the
841 // best we can do is to highlight the range. If this is a
842 // function-like macro, we'd also like to highlight the arguments.
843 if (B == E && RI->getEnd().isMacroID())
844 E = SM.getExpansionRange(RI->getEnd()).second;
845
846 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(B);
847 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E);
848
849 // If the start or end of the range is in another file, just discard
850 // it.
851 if (BInfo.first != CaretFileID || EInfo.first != CaretFileID)
852 continue;
853
854 // Add in the length of the token, so that we cover multi-char
855 // tokens.
856 unsigned TokSize = 0;
857 if (RI->isTokenRange())
858 TokSize = Lexer::MeasureTokenLength(E, SM, LangOpts);
859
860 OS << '{' << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
861 << SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
862 << SM.getLineNumber(EInfo.first, EInfo.second) << ':'
863 << (SM.getColumnNumber(EInfo.first, EInfo.second)+TokSize)
864 << '}';
865 PrintedRange = true;
866 }
867
868 if (PrintedRange)
869 OS << ':';
870 }
871 OS << ' ';
872}
873
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000874void TextDiagnostic::emitIncludeLocation(SourceLocation Loc,
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +0000875 PresumedLoc PLoc,
876 const SourceManager &SM) {
Douglas Gregor811db4e2012-10-23 22:26:28 +0000877 if (DiagOpts->ShowLocation)
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000878 OS << "In file included from " << PLoc.getFilename() << ':'
879 << PLoc.getLine() << ":\n";
880 else
881 OS << "In included file:\n";
Chandler Carrutha3028852011-10-15 23:43:53 +0000882}
883
Douglas Gregor22103e32012-11-30 21:58:49 +0000884void TextDiagnostic::emitImportLocation(SourceLocation Loc, PresumedLoc PLoc,
885 StringRef ModuleName,
886 const SourceManager &SM) {
887 if (DiagOpts->ShowLocation)
888 OS << "In module '" << ModuleName << "' imported from "
889 << PLoc.getFilename() << ':' << PLoc.getLine() << ":\n";
890 else
891 OS << "In module " << ModuleName << "':\n";
892}
893
Douglas Gregoraf8f0262012-11-30 18:38:50 +0000894void TextDiagnostic::emitBuildingModuleLocation(SourceLocation Loc,
895 PresumedLoc PLoc,
896 StringRef ModuleName,
897 const SourceManager &SM) {
Douglas Gregordfc94302012-12-18 23:02:07 +0000898 if (DiagOpts->ShowLocation && PLoc.getFilename())
Douglas Gregoraf8f0262012-11-30 18:38:50 +0000899 OS << "While building module '" << ModuleName << "' imported from "
900 << PLoc.getFilename() << ':' << PLoc.getLine() << ":\n";
901 else
902 OS << "While building module '" << ModuleName << "':\n";
903}
904
Benjamin Kramer2a812282012-12-01 20:58:01 +0000905/// \brief Highlight a SourceRange (with ~'s) for any characters on LineNo.
906static void highlightRange(const CharSourceRange &R,
907 unsigned LineNo, FileID FID,
908 const SourceColumnMap &map,
909 std::string &CaretLine,
910 const SourceManager &SM,
911 const LangOptions &LangOpts) {
912 if (!R.isValid()) return;
913
914 SourceLocation Begin = R.getBegin();
915 SourceLocation End = R.getEnd();
916
917 unsigned StartLineNo = SM.getExpansionLineNumber(Begin);
918 if (StartLineNo > LineNo || SM.getFileID(Begin) != FID)
919 return; // No intersection.
920
921 unsigned EndLineNo = SM.getExpansionLineNumber(End);
922 if (EndLineNo < LineNo || SM.getFileID(End) != FID)
923 return; // No intersection.
924
925 // Compute the column number of the start.
926 unsigned StartColNo = 0;
927 if (StartLineNo == LineNo) {
928 StartColNo = SM.getExpansionColumnNumber(Begin);
929 if (StartColNo) --StartColNo; // Zero base the col #.
930 }
931
932 // Compute the column number of the end.
933 unsigned EndColNo = map.getSourceLine().size();
934 if (EndLineNo == LineNo) {
935 EndColNo = SM.getExpansionColumnNumber(End);
936 if (EndColNo) {
937 --EndColNo; // Zero base the col #.
938
939 // Add in the length of the token, so that we cover multi-char tokens if
940 // this is a token range.
941 if (R.isTokenRange())
942 EndColNo += Lexer::MeasureTokenLength(End, SM, LangOpts);
943 } else {
944 EndColNo = CaretLine.size();
945 }
946 }
947
948 assert(StartColNo <= EndColNo && "Invalid range!");
949
950 // Check that a token range does not highlight only whitespace.
951 if (R.isTokenRange()) {
952 // Pick the first non-whitespace column.
953 while (StartColNo < map.getSourceLine().size() &&
954 (map.getSourceLine()[StartColNo] == ' ' ||
955 map.getSourceLine()[StartColNo] == '\t'))
956 StartColNo = map.startOfNextColumn(StartColNo);
957
958 // Pick the last non-whitespace column.
959 if (EndColNo > map.getSourceLine().size())
960 EndColNo = map.getSourceLine().size();
Ted Kremenek90d7fa12013-03-15 23:09:37 +0000961 while (EndColNo &&
Benjamin Kramer2a812282012-12-01 20:58:01 +0000962 (map.getSourceLine()[EndColNo-1] == ' ' ||
963 map.getSourceLine()[EndColNo-1] == '\t'))
964 EndColNo = map.startOfPreviousColumn(EndColNo);
965
966 // If the start/end passed each other, then we are trying to highlight a
967 // range that just exists in whitespace, which must be some sort of other
968 // bug.
969 assert(StartColNo <= EndColNo && "Trying to highlight whitespace??");
970 }
971
972 assert(StartColNo <= map.getSourceLine().size() && "Invalid range!");
973 assert(EndColNo <= map.getSourceLine().size() && "Invalid range!");
974
975 // Fill the range with ~'s.
976 StartColNo = map.byteToContainingColumn(StartColNo);
977 EndColNo = map.byteToContainingColumn(EndColNo);
978
979 assert(StartColNo <= EndColNo && "Invalid range!");
980 if (CaretLine.size() < EndColNo)
981 CaretLine.resize(EndColNo,' ');
982 std::fill(CaretLine.begin()+StartColNo,CaretLine.begin()+EndColNo,'~');
983}
984
985static std::string buildFixItInsertionLine(unsigned LineNo,
986 const SourceColumnMap &map,
987 ArrayRef<FixItHint> Hints,
988 const SourceManager &SM,
989 const DiagnosticOptions *DiagOpts) {
990 std::string FixItInsertionLine;
991 if (Hints.empty() || !DiagOpts->ShowFixits)
992 return FixItInsertionLine;
993 unsigned PrevHintEndCol = 0;
994
995 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
996 I != E; ++I) {
997 if (!I->CodeToInsert.empty()) {
998 // We have an insertion hint. Determine whether the inserted
999 // code contains no newlines and is on the same line as the caret.
1000 std::pair<FileID, unsigned> HintLocInfo
1001 = SM.getDecomposedExpansionLoc(I->RemoveRange.getBegin());
1002 if (LineNo == SM.getLineNumber(HintLocInfo.first, HintLocInfo.second) &&
1003 StringRef(I->CodeToInsert).find_first_of("\n\r") == StringRef::npos) {
1004 // Insert the new code into the line just below the code
1005 // that the user wrote.
1006 // Note: When modifying this function, be very careful about what is a
1007 // "column" (printed width, platform-dependent) and what is a
1008 // "byte offset" (SourceManager "column").
1009 unsigned HintByteOffset
1010 = SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second) - 1;
1011
1012 // The hint must start inside the source or right at the end
1013 assert(HintByteOffset < static_cast<unsigned>(map.bytes())+1);
1014 unsigned HintCol = map.byteToContainingColumn(HintByteOffset);
1015
1016 // If we inserted a long previous hint, push this one forwards, and add
1017 // an extra space to show that this is not part of the previous
1018 // completion. This is sort of the best we can do when two hints appear
1019 // to overlap.
1020 //
1021 // Note that if this hint is located immediately after the previous
1022 // hint, no space will be added, since the location is more important.
1023 if (HintCol < PrevHintEndCol)
1024 HintCol = PrevHintEndCol + 1;
1025
Benjamin Kramer2a812282012-12-01 20:58:01 +00001026 // This should NOT use HintByteOffset, because the source might have
1027 // Unicode characters in earlier columns.
Jordan Rosee2fad6d2013-06-07 17:16:01 +00001028 unsigned NewFixItLineSize = FixItInsertionLine.size() +
1029 (HintCol - PrevHintEndCol) + I->CodeToInsert.size();
1030 if (NewFixItLineSize > FixItInsertionLine.size())
1031 FixItInsertionLine.resize(NewFixItLineSize, ' ');
Benjamin Kramer2a812282012-12-01 20:58:01 +00001032
1033 std::copy(I->CodeToInsert.begin(), I->CodeToInsert.end(),
Jordan Rosee2fad6d2013-06-07 17:16:01 +00001034 FixItInsertionLine.end() - I->CodeToInsert.size());
Benjamin Kramer2a812282012-12-01 20:58:01 +00001035
Jordan Rosee2fad6d2013-06-07 17:16:01 +00001036 PrevHintEndCol =
1037 HintCol + llvm::sys::locale::columnWidth(I->CodeToInsert);
Benjamin Kramer2a812282012-12-01 20:58:01 +00001038 } else {
1039 FixItInsertionLine.clear();
1040 break;
1041 }
1042 }
1043 }
1044
1045 expandTabs(FixItInsertionLine, DiagOpts->TabStop);
1046
1047 return FixItInsertionLine;
1048}
1049
Chandler Carrutha3028852011-10-15 23:43:53 +00001050/// \brief Emit a code snippet and caret line.
1051///
1052/// This routine emits a single line's code snippet and caret line..
1053///
1054/// \param Loc The location for the caret.
1055/// \param Ranges The underlined ranges for this code snippet.
1056/// \param Hints The FixIt hints active for this diagnostic.
Chandler Carruthab4c1da2011-10-15 23:54:09 +00001057void TextDiagnostic::emitSnippetAndCaret(
Chandler Carruthdc2f2572011-10-16 07:20:28 +00001058 SourceLocation Loc, DiagnosticsEngine::Level Level,
Chandler Carrutha3028852011-10-15 23:43:53 +00001059 SmallVectorImpl<CharSourceRange>& Ranges,
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +00001060 ArrayRef<FixItHint> Hints,
1061 const SourceManager &SM) {
Chandler Carrutha3028852011-10-15 23:43:53 +00001062 assert(!Loc.isInvalid() && "must have a valid source location here");
1063 assert(Loc.isFileID() && "must have a file location here");
1064
Chandler Carruthdc2f2572011-10-16 07:20:28 +00001065 // If caret diagnostics are enabled and we have location, we want to
1066 // emit the caret. However, we only do this if the location moved
1067 // from the last diagnostic, if the last diagnostic was a note that
1068 // was part of a different warning or error diagnostic, or if the
1069 // diagnostic has ranges. We don't want to emit the same caret
1070 // multiple times if one loc has multiple diagnostics.
Douglas Gregor811db4e2012-10-23 22:26:28 +00001071 if (!DiagOpts->ShowCarets)
Chandler Carruthdc2f2572011-10-16 07:20:28 +00001072 return;
1073 if (Loc == LastLoc && Ranges.empty() && Hints.empty() &&
1074 (LastLevel != DiagnosticsEngine::Note || Level == LastLevel))
1075 return;
1076
Chandler Carrutha3028852011-10-15 23:43:53 +00001077 // Decompose the location into a FID/Offset pair.
1078 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1079 FileID FID = LocInfo.first;
1080 unsigned FileOffset = LocInfo.second;
1081
1082 // Get information about the buffer it points into.
1083 bool Invalid = false;
Nico Weber35131222012-04-26 21:39:46 +00001084 const char *BufStart = SM.getBufferData(FID, &Invalid).data();
Chandler Carrutha3028852011-10-15 23:43:53 +00001085 if (Invalid)
1086 return;
1087
1088 unsigned LineNo = SM.getLineNumber(FID, FileOffset);
1089 unsigned ColNo = SM.getColumnNumber(FID, FileOffset);
Jordan Rose2da0d1c2013-01-30 21:41:07 +00001090
1091 // Arbitrarily stop showing snippets when the line is too long.
Benjamin Kramerd408de62013-04-23 14:42:47 +00001092 static const size_t MaxLineLengthToPrint = 4096;
Jordan Rosec40b0fa2013-01-30 22:14:15 +00001093 if (ColNo > MaxLineLengthToPrint)
Jordan Rose2da0d1c2013-01-30 21:41:07 +00001094 return;
Chandler Carrutha3028852011-10-15 23:43:53 +00001095
1096 // Rewind from the current position to the start of the line.
1097 const char *TokPtr = BufStart+FileOffset;
1098 const char *LineStart = TokPtr-ColNo+1; // Column # is 1-based.
1099
Chandler Carrutha3028852011-10-15 23:43:53 +00001100 // Compute the line end. Scan forward from the error position to the end of
1101 // the line.
1102 const char *LineEnd = TokPtr;
Nico Weber35131222012-04-26 21:39:46 +00001103 while (*LineEnd != '\n' && *LineEnd != '\r' && *LineEnd != '\0')
Chandler Carrutha3028852011-10-15 23:43:53 +00001104 ++LineEnd;
1105
Jordan Rose2da0d1c2013-01-30 21:41:07 +00001106 // Arbitrarily stop showing snippets when the line is too long.
Benjamin Kramerd408de62013-04-23 14:42:47 +00001107 if (size_t(LineEnd - LineStart) > MaxLineLengthToPrint)
Jordan Rose2da0d1c2013-01-30 21:41:07 +00001108 return;
1109
Chandler Carrutha3028852011-10-15 23:43:53 +00001110 // Copy the line of code into an std::string for ease of manipulation.
1111 std::string SourceLine(LineStart, LineEnd);
1112
1113 // Create a line for the caret that is filled with spaces that is the same
1114 // length as the line of source code.
1115 std::string CaretLine(LineEnd-LineStart, ' ');
1116
Douglas Gregor811db4e2012-10-23 22:26:28 +00001117 const SourceColumnMap sourceColMap(SourceLine, DiagOpts->TabStop);
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001118
Chandler Carrutha3028852011-10-15 23:43:53 +00001119 // Highlight all of the characters covered by Ranges with ~ characters.
1120 for (SmallVectorImpl<CharSourceRange>::iterator I = Ranges.begin(),
1121 E = Ranges.end();
1122 I != E; ++I)
Benjamin Kramer2a812282012-12-01 20:58:01 +00001123 highlightRange(*I, LineNo, FID, sourceColMap, CaretLine, SM, LangOpts);
Chandler Carrutha3028852011-10-15 23:43:53 +00001124
1125 // Next, insert the caret itself.
Richard Smithfab4b1a2012-09-13 18:37:50 +00001126 ColNo = sourceColMap.byteToContainingColumn(ColNo-1);
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001127 if (CaretLine.size()<ColNo+1)
1128 CaretLine.resize(ColNo+1, ' ');
1129 CaretLine[ColNo] = '^';
Chandler Carrutha3028852011-10-15 23:43:53 +00001130
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001131 std::string FixItInsertionLine = buildFixItInsertionLine(LineNo,
1132 sourceColMap,
Benjamin Kramer2a812282012-12-01 20:58:01 +00001133 Hints, SM,
Alp Tokerf994cef2014-07-05 03:08:06 +00001134 DiagOpts.get());
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001135
1136 // If the source line is too long for our terminal, select only the
1137 // "interesting" source region within that line.
Douglas Gregor811db4e2012-10-23 22:26:28 +00001138 unsigned Columns = DiagOpts->MessageLength;
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001139 if (Columns)
1140 selectInterestingSourceRegion(SourceLine, CaretLine, FixItInsertionLine,
1141 Columns, sourceColMap);
Chandler Carrutha3028852011-10-15 23:43:53 +00001142
1143 // If we are in -fdiagnostics-print-source-range-info mode, we are trying
1144 // to produce easily machine parsable output. Add a space before the
1145 // source line and the caret to make it trivial to tell the main diagnostic
1146 // line from what the user is intended to see.
Douglas Gregor811db4e2012-10-23 22:26:28 +00001147 if (DiagOpts->ShowSourceRanges) {
Chandler Carrutha3028852011-10-15 23:43:53 +00001148 SourceLine = ' ' + SourceLine;
1149 CaretLine = ' ' + CaretLine;
1150 }
1151
Chandler Carrutha3028852011-10-15 23:43:53 +00001152 // Finally, remove any blank spaces from the end of CaretLine.
1153 while (CaretLine[CaretLine.size()-1] == ' ')
1154 CaretLine.erase(CaretLine.end()-1);
1155
1156 // Emit what we have computed.
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001157 emitSnippet(SourceLine);
Chandler Carrutha3028852011-10-15 23:43:53 +00001158
Douglas Gregor811db4e2012-10-23 22:26:28 +00001159 if (DiagOpts->ShowColors)
Chandler Carrutha3028852011-10-15 23:43:53 +00001160 OS.changeColor(caretColor, true);
1161 OS << CaretLine << '\n';
Douglas Gregor811db4e2012-10-23 22:26:28 +00001162 if (DiagOpts->ShowColors)
Chandler Carrutha3028852011-10-15 23:43:53 +00001163 OS.resetColor();
1164
1165 if (!FixItInsertionLine.empty()) {
Douglas Gregor811db4e2012-10-23 22:26:28 +00001166 if (DiagOpts->ShowColors)
Chandler Carrutha3028852011-10-15 23:43:53 +00001167 // Print fixit line in color
1168 OS.changeColor(fixitColor, false);
Douglas Gregor811db4e2012-10-23 22:26:28 +00001169 if (DiagOpts->ShowSourceRanges)
Chandler Carrutha3028852011-10-15 23:43:53 +00001170 OS << ' ';
1171 OS << FixItInsertionLine << '\n';
Douglas Gregor811db4e2012-10-23 22:26:28 +00001172 if (DiagOpts->ShowColors)
Chandler Carrutha3028852011-10-15 23:43:53 +00001173 OS.resetColor();
1174 }
1175
1176 // Print out any parseable fixit information requested by the options.
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +00001177 emitParseableFixits(Hints, SM);
Chandler Carrutha3028852011-10-15 23:43:53 +00001178}
1179
Benjamin Kramer556ab5e2012-05-01 14:34:11 +00001180void TextDiagnostic::emitSnippet(StringRef line) {
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001181 if (line.empty())
1182 return;
1183
1184 size_t i = 0;
1185
1186 std::string to_print;
1187 bool print_reversed = false;
1188
1189 while (i<line.size()) {
1190 std::pair<SmallString<16>,bool> res
Douglas Gregor811db4e2012-10-23 22:26:28 +00001191 = printableTextForNextCharacter(line, &i, DiagOpts->TabStop);
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001192 bool was_printable = res.second;
1193
Douglas Gregor811db4e2012-10-23 22:26:28 +00001194 if (DiagOpts->ShowColors && was_printable == print_reversed) {
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001195 if (print_reversed)
1196 OS.reverseColor();
1197 OS << to_print;
1198 to_print.clear();
Douglas Gregor811db4e2012-10-23 22:26:28 +00001199 if (DiagOpts->ShowColors)
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001200 OS.resetColor();
1201 }
1202
1203 print_reversed = !was_printable;
1204 to_print += res.first.str();
1205 }
1206
Douglas Gregor811db4e2012-10-23 22:26:28 +00001207 if (print_reversed && DiagOpts->ShowColors)
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001208 OS.reverseColor();
1209 OS << to_print;
Douglas Gregor811db4e2012-10-23 22:26:28 +00001210 if (print_reversed && DiagOpts->ShowColors)
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001211 OS.resetColor();
1212
1213 OS << '\n';
1214}
1215
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +00001216void TextDiagnostic::emitParseableFixits(ArrayRef<FixItHint> Hints,
1217 const SourceManager &SM) {
Douglas Gregor811db4e2012-10-23 22:26:28 +00001218 if (!DiagOpts->ShowParseableFixits)
Chandler Carrutha3028852011-10-15 23:43:53 +00001219 return;
1220
1221 // We follow FixItRewriter's example in not (yet) handling
1222 // fix-its in macros.
1223 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1224 I != E; ++I) {
1225 if (I->RemoveRange.isInvalid() ||
1226 I->RemoveRange.getBegin().isMacroID() ||
1227 I->RemoveRange.getEnd().isMacroID())
1228 return;
1229 }
1230
1231 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1232 I != E; ++I) {
1233 SourceLocation BLoc = I->RemoveRange.getBegin();
1234 SourceLocation ELoc = I->RemoveRange.getEnd();
1235
1236 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(BLoc);
1237 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(ELoc);
1238
1239 // Adjust for token ranges.
1240 if (I->RemoveRange.isTokenRange())
1241 EInfo.second += Lexer::MeasureTokenLength(ELoc, SM, LangOpts);
1242
1243 // We specifically do not do word-wrapping or tab-expansion here,
1244 // because this is supposed to be easy to parse.
1245 PresumedLoc PLoc = SM.getPresumedLoc(BLoc);
1246 if (PLoc.isInvalid())
1247 break;
1248
1249 OS << "fix-it:\"";
1250 OS.write_escaped(PLoc.getFilename());
1251 OS << "\":{" << SM.getLineNumber(BInfo.first, BInfo.second)
1252 << ':' << SM.getColumnNumber(BInfo.first, BInfo.second)
1253 << '-' << SM.getLineNumber(EInfo.first, EInfo.second)
1254 << ':' << SM.getColumnNumber(EInfo.first, EInfo.second)
1255 << "}:\"";
1256 OS.write_escaped(I->CodeToInsert);
1257 OS << "\"\n";
1258 }
1259}