blob: 2da66d3b3247d4549bc5937bafb81ae66b3b269f [file] [log] [blame]
Chandler Carruthdb463bb2011-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 Rose3f6f51e2013-02-08 22:30:41 +000011#include "clang/Basic/CharInfo.h"
Douglas Gregor02c23eb2012-10-23 22:26:28 +000012#include "clang/Basic/DiagnosticOptions.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000013#include "clang/Basic/FileManager.h"
14#include "clang/Basic/SourceManager.h"
Chandler Carruthdb463bb2011-10-15 23:43:53 +000015#include "clang/Lex/Lexer.h"
Chandler Carruthdb463bb2011-10-15 23:43:53 +000016#include "llvm/ADT/SmallString.h"
Seth Cantrell6749dd52012-04-18 02:44:46 +000017#include "llvm/ADT/StringExtras.h"
Dmitri Gribenkocb5620c2013-01-30 12:06:08 +000018#include "llvm/Support/ConvertUTF.h"
Chandler Carruth55fc8732012-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 Carruthdb463bb2011-10-15 23:43:53 +000023#include <algorithm>
Seth Cantrell6749dd52012-04-18 02:44:46 +000024
Chandler Carruthdb463bb2011-10-15 23:43:53 +000025using namespace clang;
26
27static const enum raw_ostream::Colors noteColor =
28 raw_ostream::BLACK;
29static const enum raw_ostream::Colors fixitColor =
30 raw_ostream::GREEN;
31static const enum raw_ostream::Colors caretColor =
32 raw_ostream::GREEN;
33static const enum raw_ostream::Colors warningColor =
34 raw_ostream::MAGENTA;
Richard Trieu246b6aa2012-06-26 18:18:47 +000035static const enum raw_ostream::Colors templateColor =
36 raw_ostream::CYAN;
Chandler Carruthdb463bb2011-10-15 23:43:53 +000037static const enum raw_ostream::Colors errorColor = raw_ostream::RED;
38static const enum raw_ostream::Colors fatalColor = raw_ostream::RED;
39// Used for changing only the bold attribute.
40static const enum raw_ostream::Colors savedColor =
41 raw_ostream::SAVEDCOLOR;
42
Richard Trieu246b6aa2012-06-26 18:18:47 +000043/// \brief Add highlights to differences in template strings.
44static void applyTemplateHighlighting(raw_ostream &OS, StringRef Str,
Richard Trieub956e5a2012-06-28 22:39:03 +000045 bool &Normal, bool Bold) {
Benjamin Kramer4ca3abd2012-10-18 20:09:54 +000046 while (1) {
47 size_t Pos = Str.find(ToggleHighlight);
48 OS << Str.slice(0, Pos);
49 if (Pos == StringRef::npos)
50 break;
51
52 Str = Str.substr(Pos + 1);
53 if (Normal)
54 OS.changeColor(templateColor, true);
55 else {
56 OS.resetColor();
57 if (Bold)
58 OS.changeColor(savedColor, true);
Richard Trieu246b6aa2012-06-26 18:18:47 +000059 }
Benjamin Kramer4ca3abd2012-10-18 20:09:54 +000060 Normal = !Normal;
61 }
Richard Trieu246b6aa2012-06-26 18:18:47 +000062}
63
Chandler Carruthdb463bb2011-10-15 23:43:53 +000064/// \brief Number of spaces to indent when word-wrapping.
65const unsigned WordWrapIndentation = 6;
66
Benjamin Kramerd1fda032012-05-01 14:34:11 +000067static int bytesSincePreviousTabOrLineBegin(StringRef SourceLine, size_t i) {
Seth Cantrell6749dd52012-04-18 02:44:46 +000068 int bytes = 0;
69 while (0<i) {
70 if (SourceLine[--i]=='\t')
71 break;
72 ++bytes;
73 }
74 return bytes;
75}
76
77/// \brief returns a printable representation of first item from input range
78///
79/// This function returns a printable representation of the next item in a line
80/// of source. If the next byte begins a valid and printable character, that
81/// character is returned along with 'true'.
82///
83/// Otherwise, if the next byte begins a valid, but unprintable character, a
84/// printable, escaped representation of the character is returned, along with
85/// 'false'. Otherwise a printable, escaped representation of the next byte
86/// is returned along with 'false'.
87///
88/// \note The index is updated to be used with a subsequent call to
89/// printableTextForNextCharacter.
90///
91/// \param SourceLine The line of source
92/// \param i Pointer to byte index,
93/// \param TabStop used to expand tabs
Sylvestre Ledruf3477c12012-09-27 10:16:10 +000094/// \return pair(printable text, 'true' iff original text was printable)
Seth Cantrell6749dd52012-04-18 02:44:46 +000095///
Benjamin Kramerd1fda032012-05-01 14:34:11 +000096static std::pair<SmallString<16>, bool>
Seth Cantrell6749dd52012-04-18 02:44:46 +000097printableTextForNextCharacter(StringRef SourceLine, size_t *i,
98 unsigned TabStop) {
99 assert(i && "i must not be null");
100 assert(*i<SourceLine.size() && "must point to a valid index");
101
102 if (SourceLine[*i]=='\t') {
103 assert(0 < TabStop && TabStop <= DiagnosticOptions::MaxTabStop &&
104 "Invalid -ftabstop value");
105 unsigned col = bytesSincePreviousTabOrLineBegin(SourceLine, *i);
106 unsigned NumSpaces = TabStop - col%TabStop;
107 assert(0 < NumSpaces && NumSpaces <= TabStop
108 && "Invalid computation of space amt");
109 ++(*i);
110
111 SmallString<16> expandedTab;
112 expandedTab.assign(NumSpaces, ' ');
113 return std::make_pair(expandedTab, true);
114 }
115
Seth Cantrell6749dd52012-04-18 02:44:46 +0000116 unsigned char const *begin, *end;
117 begin = reinterpret_cast<unsigned char const *>(&*(SourceLine.begin() + *i));
Seth Cantrellc6a2f6e2012-10-30 06:13:50 +0000118 end = begin + (SourceLine.size() - *i);
Seth Cantrell6749dd52012-04-18 02:44:46 +0000119
120 if (isLegalUTF8Sequence(begin, end)) {
121 UTF32 c;
122 UTF32 *cptr = &c;
123 unsigned char const *original_begin = begin;
Seth Cantrell0d1e6452012-10-30 06:13:52 +0000124 unsigned char const *cp_end = begin+getNumBytesForUTF8(SourceLine[*i]);
Seth Cantrell6749dd52012-04-18 02:44:46 +0000125
126 ConversionResult res = ConvertUTF8toUTF32(&begin, cp_end, &cptr, cptr+1,
127 strictConversion);
Matt Beaumont-Gay0ddb0972012-04-18 17:25:16 +0000128 (void)res;
Seth Cantrell6749dd52012-04-18 02:44:46 +0000129 assert(conversionOK==res);
130 assert(0 < begin-original_begin
131 && "we must be further along in the string now");
132 *i += begin-original_begin;
133
134 if (!llvm::sys::locale::isPrint(c)) {
135 // If next character is valid UTF-8, but not printable
136 SmallString<16> expandedCP("<U+>");
137 while (c) {
138 expandedCP.insert(expandedCP.begin()+3, llvm::hexdigit(c%16));
139 c/=16;
140 }
141 while (expandedCP.size() < 8)
142 expandedCP.insert(expandedCP.begin()+3, llvm::hexdigit(0));
143 return std::make_pair(expandedCP, false);
144 }
145
146 // If next character is valid UTF-8, and printable
147 return std::make_pair(SmallString<16>(original_begin, cp_end), true);
148
149 }
150
151 // If next byte is not valid UTF-8 (and therefore not printable)
152 SmallString<16> expandedByte("<XX>");
153 unsigned char byte = SourceLine[*i];
154 expandedByte[1] = llvm::hexdigit(byte / 16);
155 expandedByte[2] = llvm::hexdigit(byte % 16);
156 ++(*i);
157 return std::make_pair(expandedByte, false);
158}
159
Benjamin Kramerd1fda032012-05-01 14:34:11 +0000160static void expandTabs(std::string &SourceLine, unsigned TabStop) {
Seth Cantrell6749dd52012-04-18 02:44:46 +0000161 size_t i = SourceLine.size();
162 while (i>0) {
163 i--;
164 if (SourceLine[i]!='\t')
165 continue;
166 size_t tmp_i = i;
167 std::pair<SmallString<16>,bool> res
168 = printableTextForNextCharacter(SourceLine, &tmp_i, TabStop);
169 SourceLine.replace(i, 1, res.first.c_str());
170 }
171}
172
173/// This function takes a raw source line and produces a mapping from the bytes
174/// of the printable representation of the line to the columns those printable
175/// characters will appear at (numbering the first column as 0).
176///
177/// If a byte 'i' corresponds to muliple columns (e.g. the byte contains a tab
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +0000178/// character) then the array will map that byte to the first column the
Seth Cantrell6749dd52012-04-18 02:44:46 +0000179/// tab appears at and the next value in the map will have been incremented
180/// more than once.
181///
182/// If a byte is the first in a sequence of bytes that together map to a single
183/// entity in the output, then the array will map that byte to the appropriate
184/// column while the subsequent bytes will be -1.
185///
186/// The last element in the array does not correspond to any byte in the input
187/// and instead is the number of columns needed to display the source
188///
189/// example: (given a tabstop of 8)
190///
191/// "a \t \u3042" -> {0,1,2,8,9,-1,-1,11}
192///
James Dennett6b4f5062012-06-22 05:33:23 +0000193/// (\\u3042 is represented in UTF-8 by three bytes and takes two columns to
Seth Cantrell6749dd52012-04-18 02:44:46 +0000194/// display)
Benjamin Kramerd1fda032012-05-01 14:34:11 +0000195static void byteToColumn(StringRef SourceLine, unsigned TabStop,
196 SmallVectorImpl<int> &out) {
Seth Cantrell6749dd52012-04-18 02:44:46 +0000197 out.clear();
198
199 if (SourceLine.empty()) {
200 out.resize(1u,0);
201 return;
202 }
203
204 out.resize(SourceLine.size()+1, -1);
205
206 int columns = 0;
207 size_t i = 0;
208 while (i<SourceLine.size()) {
209 out[i] = columns;
210 std::pair<SmallString<16>,bool> res
211 = printableTextForNextCharacter(SourceLine, &i, TabStop);
212 columns += llvm::sys::locale::columnWidth(res.first);
213 }
214 out.back() = columns;
215}
216
217/// This function takes a raw source line and produces a mapping from columns
218/// to the byte of the source line that produced the character displaying at
219/// that column. This is the inverse of the mapping produced by byteToColumn()
220///
221/// The last element in the array is the number of bytes in the source string
222///
223/// example: (given a tabstop of 8)
224///
225/// "a \t \u3042" -> {0,1,2,-1,-1,-1,-1,-1,3,4,-1,7}
226///
James Dennett6b4f5062012-06-22 05:33:23 +0000227/// (\\u3042 is represented in UTF-8 by three bytes and takes two columns to
Seth Cantrell6749dd52012-04-18 02:44:46 +0000228/// display)
Benjamin Kramerd1fda032012-05-01 14:34:11 +0000229static void columnToByte(StringRef SourceLine, unsigned TabStop,
Seth Cantrell6749dd52012-04-18 02:44:46 +0000230 SmallVectorImpl<int> &out) {
231 out.clear();
232
233 if (SourceLine.empty()) {
234 out.resize(1u, 0);
235 return;
236 }
237
238 int columns = 0;
239 size_t i = 0;
240 while (i<SourceLine.size()) {
241 out.resize(columns+1, -1);
242 out.back() = i;
243 std::pair<SmallString<16>,bool> res
244 = printableTextForNextCharacter(SourceLine, &i, TabStop);
245 columns += llvm::sys::locale::columnWidth(res.first);
246 }
247 out.resize(columns+1, -1);
248 out.back() = i;
249}
250
Benjamin Kramerc2b914f2012-12-01 20:58:01 +0000251namespace {
Seth Cantrell6749dd52012-04-18 02:44:46 +0000252struct SourceColumnMap {
253 SourceColumnMap(StringRef SourceLine, unsigned TabStop)
254 : m_SourceLine(SourceLine) {
255
256 ::byteToColumn(SourceLine, TabStop, m_byteToColumn);
257 ::columnToByte(SourceLine, TabStop, m_columnToByte);
258
259 assert(m_byteToColumn.size()==SourceLine.size()+1);
260 assert(0 < m_byteToColumn.size() && 0 < m_columnToByte.size());
261 assert(m_byteToColumn.size()
262 == static_cast<unsigned>(m_columnToByte.back()+1));
263 assert(static_cast<unsigned>(m_byteToColumn.back()+1)
264 == m_columnToByte.size());
265 }
266 int columns() const { return m_byteToColumn.back(); }
267 int bytes() const { return m_columnToByte.back(); }
Richard Smithc7bb3842012-09-13 18:37:50 +0000268
269 /// \brief Map a byte to the column which it is at the start of, or return -1
270 /// if it is not at the start of a column (for a UTF-8 trailing byte).
Seth Cantrell6749dd52012-04-18 02:44:46 +0000271 int byteToColumn(int n) const {
272 assert(0<=n && n<static_cast<int>(m_byteToColumn.size()));
273 return m_byteToColumn[n];
274 }
Richard Smithc7bb3842012-09-13 18:37:50 +0000275
276 /// \brief Map a byte to the first column which contains it.
277 int byteToContainingColumn(int N) const {
278 assert(0 <= N && N < static_cast<int>(m_byteToColumn.size()));
279 while (m_byteToColumn[N] == -1)
280 --N;
281 return m_byteToColumn[N];
282 }
283
284 /// \brief Map a column to the byte which starts the column, or return -1 if
285 /// the column the second or subsequent column of an expanded tab or similar
286 /// multi-column entity.
Seth Cantrell6749dd52012-04-18 02:44:46 +0000287 int columnToByte(int n) const {
288 assert(0<=n && n<static_cast<int>(m_columnToByte.size()));
289 return m_columnToByte[n];
290 }
Richard Smithc7bb3842012-09-13 18:37:50 +0000291
292 /// \brief Map from a byte index to the next byte which starts a column.
293 int startOfNextColumn(int N) const {
294 assert(0 <= N && N < static_cast<int>(m_columnToByte.size() - 1));
295 while (byteToColumn(++N) == -1) {}
296 return N;
297 }
298
299 /// \brief Map from a byte index to the previous byte which starts a column.
300 int startOfPreviousColumn(int N) const {
301 assert(0 < N && N < static_cast<int>(m_columnToByte.size()));
Seth Cantrelleaa5a2b2012-11-03 21:21:14 +0000302 while (byteToColumn(--N) == -1) {}
Richard Smithc7bb3842012-09-13 18:37:50 +0000303 return N;
304 }
305
Seth Cantrell6749dd52012-04-18 02:44:46 +0000306 StringRef getSourceLine() const {
307 return m_SourceLine;
308 }
309
310private:
311 const std::string m_SourceLine;
312 SmallVector<int,200> m_byteToColumn;
313 SmallVector<int,200> m_columnToByte;
314};
315
316// used in assert in selectInterestingSourceRegion()
Seth Cantrell6749dd52012-04-18 02:44:46 +0000317struct char_out_of_range {
318 const char lower,upper;
319 char_out_of_range(char lower, char upper) :
320 lower(lower), upper(upper) {}
321 bool operator()(char c) { return c < lower || upper < c; }
322};
Benjamin Kramerc2b914f2012-12-01 20:58:01 +0000323} // end anonymous namespace
Seth Cantrell6749dd52012-04-18 02:44:46 +0000324
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000325/// \brief When the source code line we want to print is too long for
326/// the terminal, select the "interesting" region.
Chandler Carruth7531f572011-10-15 23:54:09 +0000327static void selectInterestingSourceRegion(std::string &SourceLine,
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000328 std::string &CaretLine,
329 std::string &FixItInsertionLine,
Seth Cantrell6749dd52012-04-18 02:44:46 +0000330 unsigned Columns,
331 const SourceColumnMap &map) {
332 unsigned MaxColumns = std::max<unsigned>(map.columns(),
333 std::max(CaretLine.size(),
334 FixItInsertionLine.size()));
335 // if the number of columns is less than the desired number we're done
336 if (MaxColumns <= Columns)
337 return;
338
Jordan Rose1f13fbd2013-06-07 17:16:01 +0000339 // No special characters are allowed in CaretLine.
Seth Cantrell6749dd52012-04-18 02:44:46 +0000340 assert(CaretLine.end() ==
341 std::find_if(CaretLine.begin(), CaretLine.end(),
342 char_out_of_range(' ','~')));
Seth Cantrell6749dd52012-04-18 02:44:46 +0000343
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000344 // Find the slice that we need to display the full caret line
345 // correctly.
346 unsigned CaretStart = 0, CaretEnd = CaretLine.size();
347 for (; CaretStart != CaretEnd; ++CaretStart)
Jordan Rose3f6f51e2013-02-08 22:30:41 +0000348 if (!isWhitespace(CaretLine[CaretStart]))
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000349 break;
350
351 for (; CaretEnd != CaretStart; --CaretEnd)
Jordan Rose3f6f51e2013-02-08 22:30:41 +0000352 if (!isWhitespace(CaretLine[CaretEnd - 1]))
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000353 break;
354
Seth Cantrell6749dd52012-04-18 02:44:46 +0000355 // caret has already been inserted into CaretLine so the above whitespace
356 // check is guaranteed to include the caret
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000357
358 // If we have a fix-it line, make sure the slice includes all of the
359 // fix-it information.
360 if (!FixItInsertionLine.empty()) {
361 unsigned FixItStart = 0, FixItEnd = FixItInsertionLine.size();
362 for (; FixItStart != FixItEnd; ++FixItStart)
Jordan Rose3f6f51e2013-02-08 22:30:41 +0000363 if (!isWhitespace(FixItInsertionLine[FixItStart]))
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000364 break;
365
366 for (; FixItEnd != FixItStart; --FixItEnd)
Jordan Rose3f6f51e2013-02-08 22:30:41 +0000367 if (!isWhitespace(FixItInsertionLine[FixItEnd - 1]))
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000368 break;
369
Jordan Rose1f13fbd2013-06-07 17:16:01 +0000370 // We can safely use the byte offset FixItStart as the column offset
371 // because the characters up until FixItStart are all ASCII whitespace
372 // characters.
373 unsigned FixItStartCol = FixItStart;
374 unsigned FixItEndCol
375 = llvm::sys::locale::columnWidth(FixItInsertionLine.substr(0, FixItEnd));
376
377 CaretStart = std::min(FixItStartCol, CaretStart);
378 CaretEnd = std::max(FixItEndCol, CaretEnd);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000379 }
380
Seth Cantrellc5493d72012-05-24 05:14:44 +0000381 // CaretEnd may have been set at the middle of a character
382 // If it's not at a character's first column then advance it past the current
383 // character.
384 while (static_cast<int>(CaretEnd) < map.columns() &&
385 -1 == map.columnToByte(CaretEnd))
386 ++CaretEnd;
387
388 assert((static_cast<int>(CaretStart) > map.columns() ||
389 -1!=map.columnToByte(CaretStart)) &&
390 "CaretStart must not point to a column in the middle of a source"
391 " line character");
392 assert((static_cast<int>(CaretEnd) > map.columns() ||
393 -1!=map.columnToByte(CaretEnd)) &&
394 "CaretEnd must not point to a column in the middle of a source line"
395 " character");
396
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000397 // CaretLine[CaretStart, CaretEnd) contains all of the interesting
398 // parts of the caret line. While this slice is smaller than the
399 // number of columns we have, try to grow the slice to encompass
400 // more context.
401
Seth Cantrell6749dd52012-04-18 02:44:46 +0000402 unsigned SourceStart = map.columnToByte(std::min<unsigned>(CaretStart,
403 map.columns()));
404 unsigned SourceEnd = map.columnToByte(std::min<unsigned>(CaretEnd,
405 map.columns()));
406
407 unsigned CaretColumnsOutsideSource = CaretEnd-CaretStart
408 - (map.byteToColumn(SourceEnd)-map.byteToColumn(SourceStart));
409
410 char const *front_ellipse = " ...";
411 char const *front_space = " ";
412 char const *back_ellipse = "...";
413 unsigned ellipses_space = strlen(front_ellipse) + strlen(back_ellipse);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000414
415 unsigned TargetColumns = Columns;
Seth Cantrell6749dd52012-04-18 02:44:46 +0000416 // Give us extra room for the ellipses
417 // and any of the caret line that extends past the source
418 if (TargetColumns > ellipses_space+CaretColumnsOutsideSource)
419 TargetColumns -= ellipses_space+CaretColumnsOutsideSource;
420
421 while (SourceStart>0 || SourceEnd<SourceLine.size()) {
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000422 bool ExpandedRegion = false;
Seth Cantrell6749dd52012-04-18 02:44:46 +0000423
424 if (SourceStart>0) {
Seth Cantrell9cffb4a2012-11-03 21:21:17 +0000425 unsigned NewStart = map.startOfPreviousColumn(SourceStart);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000426
427 // Skip over any whitespace we see here; we're looking for
428 // another bit of interesting text.
Richard Smithc7bb3842012-09-13 18:37:50 +0000429 // FIXME: Detect non-ASCII whitespace characters too.
Jordan Rose3f6f51e2013-02-08 22:30:41 +0000430 while (NewStart && isWhitespace(SourceLine[NewStart]))
Richard Smithc7bb3842012-09-13 18:37:50 +0000431 NewStart = map.startOfPreviousColumn(NewStart);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000432
433 // Skip over this bit of "interesting" text.
Richard Smithc7bb3842012-09-13 18:37:50 +0000434 while (NewStart) {
435 unsigned Prev = map.startOfPreviousColumn(NewStart);
Jordan Rose3f6f51e2013-02-08 22:30:41 +0000436 if (isWhitespace(SourceLine[Prev]))
Richard Smithc7bb3842012-09-13 18:37:50 +0000437 break;
438 NewStart = Prev;
439 }
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000440
Richard Smithc7bb3842012-09-13 18:37:50 +0000441 assert(map.byteToColumn(NewStart) != -1);
Seth Cantrell6749dd52012-04-18 02:44:46 +0000442 unsigned NewColumns = map.byteToColumn(SourceEnd) -
443 map.byteToColumn(NewStart);
444 if (NewColumns <= TargetColumns) {
445 SourceStart = NewStart;
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000446 ExpandedRegion = true;
447 }
448 }
449
Seth Cantrell6749dd52012-04-18 02:44:46 +0000450 if (SourceEnd<SourceLine.size()) {
Seth Cantrell9cffb4a2012-11-03 21:21:17 +0000451 unsigned NewEnd = map.startOfNextColumn(SourceEnd);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000452
453 // Skip over any whitespace we see here; we're looking for
454 // another bit of interesting text.
Richard Smithc7bb3842012-09-13 18:37:50 +0000455 // FIXME: Detect non-ASCII whitespace characters too.
Jordan Rose3f6f51e2013-02-08 22:30:41 +0000456 while (NewEnd < SourceLine.size() && isWhitespace(SourceLine[NewEnd]))
Richard Smithc7bb3842012-09-13 18:37:50 +0000457 NewEnd = map.startOfNextColumn(NewEnd);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000458
459 // Skip over this bit of "interesting" text.
Jordan Rose3f6f51e2013-02-08 22:30:41 +0000460 while (NewEnd < SourceLine.size() && isWhitespace(SourceLine[NewEnd]))
Richard Smithc7bb3842012-09-13 18:37:50 +0000461 NewEnd = map.startOfNextColumn(NewEnd);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000462
Richard Smithc7bb3842012-09-13 18:37:50 +0000463 assert(map.byteToColumn(NewEnd) != -1);
Seth Cantrell6749dd52012-04-18 02:44:46 +0000464 unsigned NewColumns = map.byteToColumn(NewEnd) -
465 map.byteToColumn(SourceStart);
466 if (NewColumns <= TargetColumns) {
467 SourceEnd = NewEnd;
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000468 ExpandedRegion = true;
469 }
470 }
471
472 if (!ExpandedRegion)
473 break;
474 }
475
Seth Cantrell6749dd52012-04-18 02:44:46 +0000476 CaretStart = map.byteToColumn(SourceStart);
477 CaretEnd = map.byteToColumn(SourceEnd) + CaretColumnsOutsideSource;
478
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000479 // [CaretStart, CaretEnd) is the slice we want. Update the various
480 // output lines to show only this slice, with two-space padding
481 // before the lines so that it looks nicer.
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000482
Seth Cantrell6749dd52012-04-18 02:44:46 +0000483 assert(CaretStart!=(unsigned)-1 && CaretEnd!=(unsigned)-1 &&
484 SourceStart!=(unsigned)-1 && SourceEnd!=(unsigned)-1);
485 assert(SourceStart <= SourceEnd);
486 assert(CaretStart <= CaretEnd);
487
488 unsigned BackColumnsRemoved
489 = map.byteToColumn(SourceLine.size())-map.byteToColumn(SourceEnd);
490 unsigned FrontColumnsRemoved = CaretStart;
491 unsigned ColumnsKept = CaretEnd-CaretStart;
492
493 // We checked up front that the line needed truncation
494 assert(FrontColumnsRemoved+ColumnsKept+BackColumnsRemoved > Columns);
495
496 // The line needs some trunctiona, and we'd prefer to keep the front
497 // if possible, so remove the back
Seth Cantrell191db6d2012-11-03 23:56:43 +0000498 if (BackColumnsRemoved > strlen(back_ellipse))
Seth Cantrell6749dd52012-04-18 02:44:46 +0000499 SourceLine.replace(SourceEnd, std::string::npos, back_ellipse);
500
501 // If that's enough then we're done
502 if (FrontColumnsRemoved+ColumnsKept <= Columns)
503 return;
504
505 // Otherwise remove the front as well
Seth Cantrell191db6d2012-11-03 23:56:43 +0000506 if (FrontColumnsRemoved > strlen(front_ellipse)) {
Seth Cantrell6749dd52012-04-18 02:44:46 +0000507 SourceLine.replace(0, SourceStart, front_ellipse);
508 CaretLine.replace(0, CaretStart, front_space);
509 if (!FixItInsertionLine.empty())
510 FixItInsertionLine.replace(0, CaretStart, front_space);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000511 }
512}
513
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000514/// \brief Skip over whitespace in the string, starting at the given
515/// index.
516///
517/// \returns The index of the first non-whitespace character that is
518/// greater than or equal to Idx or, if no such character exists,
519/// returns the end of the string.
520static unsigned skipWhitespace(unsigned Idx, StringRef Str, unsigned Length) {
Jordan Rose3f6f51e2013-02-08 22:30:41 +0000521 while (Idx < Length && isWhitespace(Str[Idx]))
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000522 ++Idx;
523 return Idx;
524}
525
526/// \brief If the given character is the start of some kind of
527/// balanced punctuation (e.g., quotes or parentheses), return the
528/// character that will terminate the punctuation.
529///
530/// \returns The ending punctuation character, if any, or the NULL
531/// character if the input character does not start any punctuation.
532static inline char findMatchingPunctuation(char c) {
533 switch (c) {
534 case '\'': return '\'';
535 case '`': return '\'';
536 case '"': return '"';
537 case '(': return ')';
538 case '[': return ']';
539 case '{': return '}';
540 default: break;
541 }
542
543 return 0;
544}
545
546/// \brief Find the end of the word starting at the given offset
547/// within a string.
548///
549/// \returns the index pointing one character past the end of the
550/// word.
551static unsigned findEndOfWord(unsigned Start, StringRef Str,
552 unsigned Length, unsigned Column,
553 unsigned Columns) {
554 assert(Start < Str.size() && "Invalid start position!");
555 unsigned End = Start + 1;
556
557 // If we are already at the end of the string, take that as the word.
558 if (End == Str.size())
559 return End;
560
561 // Determine if the start of the string is actually opening
562 // punctuation, e.g., a quote or parentheses.
563 char EndPunct = findMatchingPunctuation(Str[Start]);
564 if (!EndPunct) {
565 // This is a normal word. Just find the first space character.
Jordan Rose3f6f51e2013-02-08 22:30:41 +0000566 while (End < Length && !isWhitespace(Str[End]))
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000567 ++End;
568 return End;
569 }
570
571 // We have the start of a balanced punctuation sequence (quotes,
572 // parentheses, etc.). Determine the full sequence is.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000573 SmallString<16> PunctuationEndStack;
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000574 PunctuationEndStack.push_back(EndPunct);
575 while (End < Length && !PunctuationEndStack.empty()) {
576 if (Str[End] == PunctuationEndStack.back())
577 PunctuationEndStack.pop_back();
578 else if (char SubEndPunct = findMatchingPunctuation(Str[End]))
579 PunctuationEndStack.push_back(SubEndPunct);
580
581 ++End;
582 }
583
584 // Find the first space character after the punctuation ended.
Jordan Rose3f6f51e2013-02-08 22:30:41 +0000585 while (End < Length && !isWhitespace(Str[End]))
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000586 ++End;
587
588 unsigned PunctWordLength = End - Start;
589 if (// If the word fits on this line
590 Column + PunctWordLength <= Columns ||
591 // ... or the word is "short enough" to take up the next line
592 // without too much ugly white space
593 PunctWordLength < Columns/3)
594 return End; // Take the whole thing as a single "word".
595
596 // The whole quoted/parenthesized string is too long to print as a
597 // single "word". Instead, find the "word" that starts just after
598 // the punctuation and use that end-point instead. This will recurse
599 // until it finds something small enough to consider a word.
600 return findEndOfWord(Start + 1, Str, Length, Column + 1, Columns);
601}
602
603/// \brief Print the given string to a stream, word-wrapping it to
604/// some number of columns in the process.
605///
606/// \param OS the stream to which the word-wrapping string will be
607/// emitted.
608/// \param Str the string to word-wrap and output.
609/// \param Columns the number of columns to word-wrap to.
610/// \param Column the column number at which the first character of \p
611/// Str will be printed. This will be non-zero when part of the first
612/// line has already been printed.
Richard Trieub956e5a2012-06-28 22:39:03 +0000613/// \param Bold if the current text should be bold
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000614/// \param Indentation the number of spaces to indent any lines beyond
615/// the first line.
616/// \returns true if word-wrapping was required, or false if the
617/// string fit on the first line.
618static bool printWordWrapped(raw_ostream &OS, StringRef Str,
619 unsigned Columns,
620 unsigned Column = 0,
Richard Trieub956e5a2012-06-28 22:39:03 +0000621 bool Bold = false,
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000622 unsigned Indentation = WordWrapIndentation) {
623 const unsigned Length = std::min(Str.find('\n'), Str.size());
Richard Trieu246b6aa2012-06-26 18:18:47 +0000624 bool TextNormal = true;
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000625
626 // The string used to indent each line.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000627 SmallString<16> IndentStr;
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000628 IndentStr.assign(Indentation, ' ');
629 bool Wrapped = false;
630 for (unsigned WordStart = 0, WordEnd; WordStart < Length;
631 WordStart = WordEnd) {
632 // Find the beginning of the next word.
633 WordStart = skipWhitespace(WordStart, Str, Length);
634 if (WordStart == Length)
635 break;
636
637 // Find the end of this word.
638 WordEnd = findEndOfWord(WordStart, Str, Length, Column, Columns);
639
640 // Does this word fit on the current line?
641 unsigned WordLength = WordEnd - WordStart;
642 if (Column + WordLength < Columns) {
643 // This word fits on the current line; print it there.
644 if (WordStart) {
645 OS << ' ';
646 Column += 1;
647 }
Richard Trieu246b6aa2012-06-26 18:18:47 +0000648 applyTemplateHighlighting(OS, Str.substr(WordStart, WordLength),
Richard Trieub956e5a2012-06-28 22:39:03 +0000649 TextNormal, Bold);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000650 Column += WordLength;
651 continue;
652 }
653
654 // This word does not fit on the current line, so wrap to the next
655 // line.
656 OS << '\n';
657 OS.write(&IndentStr[0], Indentation);
Richard Trieu246b6aa2012-06-26 18:18:47 +0000658 applyTemplateHighlighting(OS, Str.substr(WordStart, WordLength),
Richard Trieub956e5a2012-06-28 22:39:03 +0000659 TextNormal, Bold);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000660 Column = Indentation + WordLength;
661 Wrapped = true;
662 }
663
664 // Append any remaning text from the message with its existing formatting.
Richard Trieub956e5a2012-06-28 22:39:03 +0000665 applyTemplateHighlighting(OS, Str.substr(Length), TextNormal, Bold);
Richard Trieu246b6aa2012-06-26 18:18:47 +0000666
667 assert(TextNormal && "Text highlighted at end of diagnostic message.");
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000668
669 return Wrapped;
670}
671
672TextDiagnostic::TextDiagnostic(raw_ostream &OS,
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000673 const LangOptions &LangOpts,
Douglas Gregor02c23eb2012-10-23 22:26:28 +0000674 DiagnosticOptions *DiagOpts)
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000675 : DiagnosticRenderer(LangOpts, DiagOpts), OS(OS) {}
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000676
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000677TextDiagnostic::~TextDiagnostic() {}
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000678
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000679void
680TextDiagnostic::emitDiagnosticMessage(SourceLocation Loc,
681 PresumedLoc PLoc,
682 DiagnosticsEngine::Level Level,
683 StringRef Message,
684 ArrayRef<clang::CharSourceRange> Ranges,
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000685 const SourceManager *SM,
Ted Kremenek8be51ea2012-02-14 02:46:00 +0000686 DiagOrStoredDiag D) {
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000687 uint64_t StartOfLocationInfo = OS.tell();
688
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000689 // Emit the location of this particular diagnostic.
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000690 if (Loc.isValid())
691 emitDiagnosticLoc(Loc, PLoc, Level, Ranges, *SM);
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000692
Douglas Gregor02c23eb2012-10-23 22:26:28 +0000693 if (DiagOpts->ShowColors)
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000694 OS.resetColor();
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000695
Douglas Gregor02c23eb2012-10-23 22:26:28 +0000696 printDiagnosticLevel(OS, Level, DiagOpts->ShowColors);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000697 printDiagnosticMessage(OS, Level, Message,
698 OS.tell() - StartOfLocationInfo,
Douglas Gregor02c23eb2012-10-23 22:26:28 +0000699 DiagOpts->MessageLength, DiagOpts->ShowColors);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000700}
701
Chandler Carruth6ddd8872011-10-15 23:48:02 +0000702/*static*/ void
703TextDiagnostic::printDiagnosticLevel(raw_ostream &OS,
704 DiagnosticsEngine::Level Level,
705 bool ShowColors) {
706 if (ShowColors) {
707 // Print diagnostic category in bold and color
708 switch (Level) {
709 case DiagnosticsEngine::Ignored:
710 llvm_unreachable("Invalid diagnostic type");
711 case DiagnosticsEngine::Note: OS.changeColor(noteColor, true); break;
712 case DiagnosticsEngine::Warning: OS.changeColor(warningColor, true); break;
713 case DiagnosticsEngine::Error: OS.changeColor(errorColor, true); break;
714 case DiagnosticsEngine::Fatal: OS.changeColor(fatalColor, true); break;
715 }
716 }
717
718 switch (Level) {
719 case DiagnosticsEngine::Ignored:
720 llvm_unreachable("Invalid diagnostic type");
721 case DiagnosticsEngine::Note: OS << "note: "; break;
722 case DiagnosticsEngine::Warning: OS << "warning: "; break;
723 case DiagnosticsEngine::Error: OS << "error: "; break;
724 case DiagnosticsEngine::Fatal: OS << "fatal error: "; break;
725 }
726
727 if (ShowColors)
728 OS.resetColor();
729}
730
731/*static*/ void
732TextDiagnostic::printDiagnosticMessage(raw_ostream &OS,
733 DiagnosticsEngine::Level Level,
734 StringRef Message,
735 unsigned CurrentColumn, unsigned Columns,
736 bool ShowColors) {
Richard Trieub956e5a2012-06-28 22:39:03 +0000737 bool Bold = false;
Chandler Carruth6ddd8872011-10-15 23:48:02 +0000738 if (ShowColors) {
739 // Print warnings, errors and fatal errors in bold, no color
740 switch (Level) {
Richard Trieub956e5a2012-06-28 22:39:03 +0000741 case DiagnosticsEngine::Warning:
742 case DiagnosticsEngine::Error:
743 case DiagnosticsEngine::Fatal:
744 OS.changeColor(savedColor, true);
745 Bold = true;
746 break;
Chandler Carruth6ddd8872011-10-15 23:48:02 +0000747 default: break; //don't bold notes
748 }
749 }
750
751 if (Columns)
Richard Trieub956e5a2012-06-28 22:39:03 +0000752 printWordWrapped(OS, Message, Columns, CurrentColumn, Bold);
David Blaikie50badd52012-06-28 21:46:07 +0000753 else {
754 bool Normal = true;
Richard Trieub956e5a2012-06-28 22:39:03 +0000755 applyTemplateHighlighting(OS, Message, Normal, Bold);
David Blaikie50badd52012-06-28 21:46:07 +0000756 assert(Normal && "Formatting should have returned to normal");
757 }
Chandler Carruth6ddd8872011-10-15 23:48:02 +0000758
759 if (ShowColors)
760 OS.resetColor();
761 OS << '\n';
762}
763
Chandler Carruth6ddd8872011-10-15 23:48:02 +0000764/// \brief Print out the file/line/column information and include trace.
765///
766/// This method handlen the emission of the diagnostic location information.
767/// This includes extracting as much location information as is present for
768/// the diagnostic and printing it, as well as any include stack or source
769/// ranges necessary.
Chandler Carruth7531f572011-10-15 23:54:09 +0000770void TextDiagnostic::emitDiagnosticLoc(SourceLocation Loc, PresumedLoc PLoc,
Chandler Carruth6ddd8872011-10-15 23:48:02 +0000771 DiagnosticsEngine::Level Level,
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000772 ArrayRef<CharSourceRange> Ranges,
773 const SourceManager &SM) {
Chandler Carruth6ddd8872011-10-15 23:48:02 +0000774 if (PLoc.isInvalid()) {
775 // At least print the file name if available:
776 FileID FID = SM.getFileID(Loc);
777 if (!FID.isInvalid()) {
778 const FileEntry* FE = SM.getFileEntryForID(FID);
779 if (FE && FE->getName()) {
780 OS << FE->getName();
781 if (FE->getDevice() == 0 && FE->getInode() == 0
782 && FE->getFileMode() == 0) {
783 // in PCH is a guess, but a good one:
784 OS << " (in PCH)";
785 }
786 OS << ": ";
787 }
788 }
789 return;
790 }
791 unsigned LineNo = PLoc.getLine();
792
Douglas Gregor02c23eb2012-10-23 22:26:28 +0000793 if (!DiagOpts->ShowLocation)
Chandler Carruth6ddd8872011-10-15 23:48:02 +0000794 return;
795
Douglas Gregor02c23eb2012-10-23 22:26:28 +0000796 if (DiagOpts->ShowColors)
Chandler Carruth6ddd8872011-10-15 23:48:02 +0000797 OS.changeColor(savedColor, true);
798
799 OS << PLoc.getFilename();
Douglas Gregordc7b6412012-10-23 23:11:23 +0000800 switch (DiagOpts->getFormat()) {
Chandler Carruth6ddd8872011-10-15 23:48:02 +0000801 case DiagnosticOptions::Clang: OS << ':' << LineNo; break;
802 case DiagnosticOptions::Msvc: OS << '(' << LineNo; break;
803 case DiagnosticOptions::Vi: OS << " +" << LineNo; break;
804 }
805
Douglas Gregor02c23eb2012-10-23 22:26:28 +0000806 if (DiagOpts->ShowColumn)
Chandler Carruth6ddd8872011-10-15 23:48:02 +0000807 // Compute the column number.
808 if (unsigned ColNo = PLoc.getColumn()) {
Douglas Gregordc7b6412012-10-23 23:11:23 +0000809 if (DiagOpts->getFormat() == DiagnosticOptions::Msvc) {
Chandler Carruth6ddd8872011-10-15 23:48:02 +0000810 OS << ',';
811 ColNo--;
812 } else
813 OS << ':';
814 OS << ColNo;
815 }
Douglas Gregordc7b6412012-10-23 23:11:23 +0000816 switch (DiagOpts->getFormat()) {
Chandler Carruth6ddd8872011-10-15 23:48:02 +0000817 case DiagnosticOptions::Clang:
818 case DiagnosticOptions::Vi: OS << ':'; break;
819 case DiagnosticOptions::Msvc: OS << ") : "; break;
820 }
821
Douglas Gregor02c23eb2012-10-23 22:26:28 +0000822 if (DiagOpts->ShowSourceRanges && !Ranges.empty()) {
Chandler Carruth6ddd8872011-10-15 23:48:02 +0000823 FileID CaretFileID =
824 SM.getFileID(SM.getExpansionLoc(Loc));
825 bool PrintedRange = false;
826
827 for (ArrayRef<CharSourceRange>::const_iterator RI = Ranges.begin(),
828 RE = Ranges.end();
829 RI != RE; ++RI) {
830 // Ignore invalid ranges.
831 if (!RI->isValid()) continue;
832
833 SourceLocation B = SM.getExpansionLoc(RI->getBegin());
834 SourceLocation E = SM.getExpansionLoc(RI->getEnd());
835
836 // If the End location and the start location are the same and are a
837 // macro location, then the range was something that came from a
838 // macro expansion or _Pragma. If this is an object-like macro, the
839 // best we can do is to highlight the range. If this is a
840 // function-like macro, we'd also like to highlight the arguments.
841 if (B == E && RI->getEnd().isMacroID())
842 E = SM.getExpansionRange(RI->getEnd()).second;
843
844 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(B);
845 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E);
846
847 // If the start or end of the range is in another file, just discard
848 // it.
849 if (BInfo.first != CaretFileID || EInfo.first != CaretFileID)
850 continue;
851
852 // Add in the length of the token, so that we cover multi-char
853 // tokens.
854 unsigned TokSize = 0;
855 if (RI->isTokenRange())
856 TokSize = Lexer::MeasureTokenLength(E, SM, LangOpts);
857
858 OS << '{' << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
859 << SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
860 << SM.getLineNumber(EInfo.first, EInfo.second) << ':'
861 << (SM.getColumnNumber(EInfo.first, EInfo.second)+TokSize)
862 << '}';
863 PrintedRange = true;
864 }
865
866 if (PrintedRange)
867 OS << ':';
868 }
869 OS << ' ';
870}
871
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000872void TextDiagnostic::emitBasicNote(StringRef Message) {
873 // FIXME: Emit this as a real note diagnostic.
874 // FIXME: Format an actual diagnostic rather than a hard coded string.
875 OS << "note: " << Message << "\n";
876}
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000877
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000878void TextDiagnostic::emitIncludeLocation(SourceLocation Loc,
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000879 PresumedLoc PLoc,
880 const SourceManager &SM) {
Douglas Gregor02c23eb2012-10-23 22:26:28 +0000881 if (DiagOpts->ShowLocation)
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000882 OS << "In file included from " << PLoc.getFilename() << ':'
883 << PLoc.getLine() << ":\n";
884 else
885 OS << "In included file:\n";
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000886}
887
Douglas Gregor6c325432012-11-30 21:58:49 +0000888void TextDiagnostic::emitImportLocation(SourceLocation Loc, PresumedLoc PLoc,
889 StringRef ModuleName,
890 const SourceManager &SM) {
891 if (DiagOpts->ShowLocation)
892 OS << "In module '" << ModuleName << "' imported from "
893 << PLoc.getFilename() << ':' << PLoc.getLine() << ":\n";
894 else
895 OS << "In module " << ModuleName << "':\n";
896}
897
Douglas Gregor830ea5b2012-11-30 18:38:50 +0000898void TextDiagnostic::emitBuildingModuleLocation(SourceLocation Loc,
899 PresumedLoc PLoc,
900 StringRef ModuleName,
901 const SourceManager &SM) {
Douglas Gregor813bc7f2012-12-18 23:02:07 +0000902 if (DiagOpts->ShowLocation && PLoc.getFilename())
Douglas Gregor830ea5b2012-11-30 18:38:50 +0000903 OS << "While building module '" << ModuleName << "' imported from "
904 << PLoc.getFilename() << ':' << PLoc.getLine() << ":\n";
905 else
906 OS << "While building module '" << ModuleName << "':\n";
907}
908
Benjamin Kramerc2b914f2012-12-01 20:58:01 +0000909/// \brief Highlight a SourceRange (with ~'s) for any characters on LineNo.
910static void highlightRange(const CharSourceRange &R,
911 unsigned LineNo, FileID FID,
912 const SourceColumnMap &map,
913 std::string &CaretLine,
914 const SourceManager &SM,
915 const LangOptions &LangOpts) {
916 if (!R.isValid()) return;
917
918 SourceLocation Begin = R.getBegin();
919 SourceLocation End = R.getEnd();
920
921 unsigned StartLineNo = SM.getExpansionLineNumber(Begin);
922 if (StartLineNo > LineNo || SM.getFileID(Begin) != FID)
923 return; // No intersection.
924
925 unsigned EndLineNo = SM.getExpansionLineNumber(End);
926 if (EndLineNo < LineNo || SM.getFileID(End) != FID)
927 return; // No intersection.
928
929 // Compute the column number of the start.
930 unsigned StartColNo = 0;
931 if (StartLineNo == LineNo) {
932 StartColNo = SM.getExpansionColumnNumber(Begin);
933 if (StartColNo) --StartColNo; // Zero base the col #.
934 }
935
936 // Compute the column number of the end.
937 unsigned EndColNo = map.getSourceLine().size();
938 if (EndLineNo == LineNo) {
939 EndColNo = SM.getExpansionColumnNumber(End);
940 if (EndColNo) {
941 --EndColNo; // Zero base the col #.
942
943 // Add in the length of the token, so that we cover multi-char tokens if
944 // this is a token range.
945 if (R.isTokenRange())
946 EndColNo += Lexer::MeasureTokenLength(End, SM, LangOpts);
947 } else {
948 EndColNo = CaretLine.size();
949 }
950 }
951
952 assert(StartColNo <= EndColNo && "Invalid range!");
953
954 // Check that a token range does not highlight only whitespace.
955 if (R.isTokenRange()) {
956 // Pick the first non-whitespace column.
957 while (StartColNo < map.getSourceLine().size() &&
958 (map.getSourceLine()[StartColNo] == ' ' ||
959 map.getSourceLine()[StartColNo] == '\t'))
960 StartColNo = map.startOfNextColumn(StartColNo);
961
962 // Pick the last non-whitespace column.
963 if (EndColNo > map.getSourceLine().size())
964 EndColNo = map.getSourceLine().size();
Ted Kremenek316dd542013-03-15 23:09:37 +0000965 while (EndColNo &&
Benjamin Kramerc2b914f2012-12-01 20:58:01 +0000966 (map.getSourceLine()[EndColNo-1] == ' ' ||
967 map.getSourceLine()[EndColNo-1] == '\t'))
968 EndColNo = map.startOfPreviousColumn(EndColNo);
969
970 // If the start/end passed each other, then we are trying to highlight a
971 // range that just exists in whitespace, which must be some sort of other
972 // bug.
973 assert(StartColNo <= EndColNo && "Trying to highlight whitespace??");
974 }
975
976 assert(StartColNo <= map.getSourceLine().size() && "Invalid range!");
977 assert(EndColNo <= map.getSourceLine().size() && "Invalid range!");
978
979 // Fill the range with ~'s.
980 StartColNo = map.byteToContainingColumn(StartColNo);
981 EndColNo = map.byteToContainingColumn(EndColNo);
982
983 assert(StartColNo <= EndColNo && "Invalid range!");
984 if (CaretLine.size() < EndColNo)
985 CaretLine.resize(EndColNo,' ');
986 std::fill(CaretLine.begin()+StartColNo,CaretLine.begin()+EndColNo,'~');
987}
988
989static std::string buildFixItInsertionLine(unsigned LineNo,
990 const SourceColumnMap &map,
991 ArrayRef<FixItHint> Hints,
992 const SourceManager &SM,
993 const DiagnosticOptions *DiagOpts) {
994 std::string FixItInsertionLine;
995 if (Hints.empty() || !DiagOpts->ShowFixits)
996 return FixItInsertionLine;
997 unsigned PrevHintEndCol = 0;
998
999 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1000 I != E; ++I) {
1001 if (!I->CodeToInsert.empty()) {
1002 // We have an insertion hint. Determine whether the inserted
1003 // code contains no newlines and is on the same line as the caret.
1004 std::pair<FileID, unsigned> HintLocInfo
1005 = SM.getDecomposedExpansionLoc(I->RemoveRange.getBegin());
1006 if (LineNo == SM.getLineNumber(HintLocInfo.first, HintLocInfo.second) &&
1007 StringRef(I->CodeToInsert).find_first_of("\n\r") == StringRef::npos) {
1008 // Insert the new code into the line just below the code
1009 // that the user wrote.
1010 // Note: When modifying this function, be very careful about what is a
1011 // "column" (printed width, platform-dependent) and what is a
1012 // "byte offset" (SourceManager "column").
1013 unsigned HintByteOffset
1014 = SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second) - 1;
1015
1016 // The hint must start inside the source or right at the end
1017 assert(HintByteOffset < static_cast<unsigned>(map.bytes())+1);
1018 unsigned HintCol = map.byteToContainingColumn(HintByteOffset);
1019
1020 // If we inserted a long previous hint, push this one forwards, and add
1021 // an extra space to show that this is not part of the previous
1022 // completion. This is sort of the best we can do when two hints appear
1023 // to overlap.
1024 //
1025 // Note that if this hint is located immediately after the previous
1026 // hint, no space will be added, since the location is more important.
1027 if (HintCol < PrevHintEndCol)
1028 HintCol = PrevHintEndCol + 1;
1029
Benjamin Kramerc2b914f2012-12-01 20:58:01 +00001030 // This should NOT use HintByteOffset, because the source might have
1031 // Unicode characters in earlier columns.
Jordan Rose1f13fbd2013-06-07 17:16:01 +00001032 unsigned NewFixItLineSize = FixItInsertionLine.size() +
1033 (HintCol - PrevHintEndCol) + I->CodeToInsert.size();
1034 if (NewFixItLineSize > FixItInsertionLine.size())
1035 FixItInsertionLine.resize(NewFixItLineSize, ' ');
Benjamin Kramerc2b914f2012-12-01 20:58:01 +00001036
1037 std::copy(I->CodeToInsert.begin(), I->CodeToInsert.end(),
Jordan Rose1f13fbd2013-06-07 17:16:01 +00001038 FixItInsertionLine.end() - I->CodeToInsert.size());
Benjamin Kramerc2b914f2012-12-01 20:58:01 +00001039
Jordan Rose1f13fbd2013-06-07 17:16:01 +00001040 PrevHintEndCol =
1041 HintCol + llvm::sys::locale::columnWidth(I->CodeToInsert);
Benjamin Kramerc2b914f2012-12-01 20:58:01 +00001042 } else {
1043 FixItInsertionLine.clear();
1044 break;
1045 }
1046 }
1047 }
1048
1049 expandTabs(FixItInsertionLine, DiagOpts->TabStop);
1050
1051 return FixItInsertionLine;
1052}
1053
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001054/// \brief Emit a code snippet and caret line.
1055///
1056/// This routine emits a single line's code snippet and caret line..
1057///
1058/// \param Loc The location for the caret.
1059/// \param Ranges The underlined ranges for this code snippet.
1060/// \param Hints The FixIt hints active for this diagnostic.
Chandler Carruth7531f572011-10-15 23:54:09 +00001061void TextDiagnostic::emitSnippetAndCaret(
Chandler Carruth4ba55652011-10-16 07:20:28 +00001062 SourceLocation Loc, DiagnosticsEngine::Level Level,
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001063 SmallVectorImpl<CharSourceRange>& Ranges,
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +00001064 ArrayRef<FixItHint> Hints,
1065 const SourceManager &SM) {
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001066 assert(!Loc.isInvalid() && "must have a valid source location here");
1067 assert(Loc.isFileID() && "must have a file location here");
1068
Chandler Carruth4ba55652011-10-16 07:20:28 +00001069 // If caret diagnostics are enabled and we have location, we want to
1070 // emit the caret. However, we only do this if the location moved
1071 // from the last diagnostic, if the last diagnostic was a note that
1072 // was part of a different warning or error diagnostic, or if the
1073 // diagnostic has ranges. We don't want to emit the same caret
1074 // multiple times if one loc has multiple diagnostics.
Douglas Gregor02c23eb2012-10-23 22:26:28 +00001075 if (!DiagOpts->ShowCarets)
Chandler Carruth4ba55652011-10-16 07:20:28 +00001076 return;
1077 if (Loc == LastLoc && Ranges.empty() && Hints.empty() &&
1078 (LastLevel != DiagnosticsEngine::Note || Level == LastLevel))
1079 return;
1080
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001081 // Decompose the location into a FID/Offset pair.
1082 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1083 FileID FID = LocInfo.first;
1084 unsigned FileOffset = LocInfo.second;
1085
1086 // Get information about the buffer it points into.
1087 bool Invalid = false;
Nico Weber40d8e972012-04-26 21:39:46 +00001088 const char *BufStart = SM.getBufferData(FID, &Invalid).data();
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001089 if (Invalid)
1090 return;
1091
1092 unsigned LineNo = SM.getLineNumber(FID, FileOffset);
1093 unsigned ColNo = SM.getColumnNumber(FID, FileOffset);
Jordan Rosef6e74a32013-01-30 21:41:07 +00001094
1095 // Arbitrarily stop showing snippets when the line is too long.
Benjamin Kramerdd3e2d92013-04-23 14:42:47 +00001096 static const size_t MaxLineLengthToPrint = 4096;
Jordan Rose91165e72013-01-30 22:14:15 +00001097 if (ColNo > MaxLineLengthToPrint)
Jordan Rosef6e74a32013-01-30 21:41:07 +00001098 return;
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001099
1100 // Rewind from the current position to the start of the line.
1101 const char *TokPtr = BufStart+FileOffset;
1102 const char *LineStart = TokPtr-ColNo+1; // Column # is 1-based.
1103
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001104 // Compute the line end. Scan forward from the error position to the end of
1105 // the line.
1106 const char *LineEnd = TokPtr;
Nico Weber40d8e972012-04-26 21:39:46 +00001107 while (*LineEnd != '\n' && *LineEnd != '\r' && *LineEnd != '\0')
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001108 ++LineEnd;
1109
Jordan Rosef6e74a32013-01-30 21:41:07 +00001110 // Arbitrarily stop showing snippets when the line is too long.
Benjamin Kramerdd3e2d92013-04-23 14:42:47 +00001111 if (size_t(LineEnd - LineStart) > MaxLineLengthToPrint)
Jordan Rosef6e74a32013-01-30 21:41:07 +00001112 return;
1113
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001114 // Copy the line of code into an std::string for ease of manipulation.
1115 std::string SourceLine(LineStart, LineEnd);
1116
1117 // Create a line for the caret that is filled with spaces that is the same
1118 // length as the line of source code.
1119 std::string CaretLine(LineEnd-LineStart, ' ');
1120
Douglas Gregor02c23eb2012-10-23 22:26:28 +00001121 const SourceColumnMap sourceColMap(SourceLine, DiagOpts->TabStop);
Seth Cantrell6749dd52012-04-18 02:44:46 +00001122
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001123 // Highlight all of the characters covered by Ranges with ~ characters.
1124 for (SmallVectorImpl<CharSourceRange>::iterator I = Ranges.begin(),
1125 E = Ranges.end();
1126 I != E; ++I)
Benjamin Kramerc2b914f2012-12-01 20:58:01 +00001127 highlightRange(*I, LineNo, FID, sourceColMap, CaretLine, SM, LangOpts);
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001128
1129 // Next, insert the caret itself.
Richard Smithc7bb3842012-09-13 18:37:50 +00001130 ColNo = sourceColMap.byteToContainingColumn(ColNo-1);
Seth Cantrell6749dd52012-04-18 02:44:46 +00001131 if (CaretLine.size()<ColNo+1)
1132 CaretLine.resize(ColNo+1, ' ');
1133 CaretLine[ColNo] = '^';
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001134
Seth Cantrell6749dd52012-04-18 02:44:46 +00001135 std::string FixItInsertionLine = buildFixItInsertionLine(LineNo,
1136 sourceColMap,
Benjamin Kramerc2b914f2012-12-01 20:58:01 +00001137 Hints, SM,
1138 DiagOpts.getPtr());
Seth Cantrell6749dd52012-04-18 02:44:46 +00001139
1140 // If the source line is too long for our terminal, select only the
1141 // "interesting" source region within that line.
Douglas Gregor02c23eb2012-10-23 22:26:28 +00001142 unsigned Columns = DiagOpts->MessageLength;
Seth Cantrell6749dd52012-04-18 02:44:46 +00001143 if (Columns)
1144 selectInterestingSourceRegion(SourceLine, CaretLine, FixItInsertionLine,
1145 Columns, sourceColMap);
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001146
1147 // If we are in -fdiagnostics-print-source-range-info mode, we are trying
1148 // to produce easily machine parsable output. Add a space before the
1149 // source line and the caret to make it trivial to tell the main diagnostic
1150 // line from what the user is intended to see.
Douglas Gregor02c23eb2012-10-23 22:26:28 +00001151 if (DiagOpts->ShowSourceRanges) {
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001152 SourceLine = ' ' + SourceLine;
1153 CaretLine = ' ' + CaretLine;
1154 }
1155
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001156 // Finally, remove any blank spaces from the end of CaretLine.
1157 while (CaretLine[CaretLine.size()-1] == ' ')
1158 CaretLine.erase(CaretLine.end()-1);
1159
1160 // Emit what we have computed.
Seth Cantrell6749dd52012-04-18 02:44:46 +00001161 emitSnippet(SourceLine);
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001162
Douglas Gregor02c23eb2012-10-23 22:26:28 +00001163 if (DiagOpts->ShowColors)
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001164 OS.changeColor(caretColor, true);
1165 OS << CaretLine << '\n';
Douglas Gregor02c23eb2012-10-23 22:26:28 +00001166 if (DiagOpts->ShowColors)
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001167 OS.resetColor();
1168
1169 if (!FixItInsertionLine.empty()) {
Douglas Gregor02c23eb2012-10-23 22:26:28 +00001170 if (DiagOpts->ShowColors)
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001171 // Print fixit line in color
1172 OS.changeColor(fixitColor, false);
Douglas Gregor02c23eb2012-10-23 22:26:28 +00001173 if (DiagOpts->ShowSourceRanges)
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001174 OS << ' ';
1175 OS << FixItInsertionLine << '\n';
Douglas Gregor02c23eb2012-10-23 22:26:28 +00001176 if (DiagOpts->ShowColors)
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001177 OS.resetColor();
1178 }
1179
1180 // Print out any parseable fixit information requested by the options.
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +00001181 emitParseableFixits(Hints, SM);
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001182}
1183
Benjamin Kramerd1fda032012-05-01 14:34:11 +00001184void TextDiagnostic::emitSnippet(StringRef line) {
Seth Cantrell6749dd52012-04-18 02:44:46 +00001185 if (line.empty())
1186 return;
1187
1188 size_t i = 0;
1189
1190 std::string to_print;
1191 bool print_reversed = false;
1192
1193 while (i<line.size()) {
1194 std::pair<SmallString<16>,bool> res
Douglas Gregor02c23eb2012-10-23 22:26:28 +00001195 = printableTextForNextCharacter(line, &i, DiagOpts->TabStop);
Seth Cantrell6749dd52012-04-18 02:44:46 +00001196 bool was_printable = res.second;
1197
Douglas Gregor02c23eb2012-10-23 22:26:28 +00001198 if (DiagOpts->ShowColors && was_printable == print_reversed) {
Seth Cantrell6749dd52012-04-18 02:44:46 +00001199 if (print_reversed)
1200 OS.reverseColor();
1201 OS << to_print;
1202 to_print.clear();
Douglas Gregor02c23eb2012-10-23 22:26:28 +00001203 if (DiagOpts->ShowColors)
Seth Cantrell6749dd52012-04-18 02:44:46 +00001204 OS.resetColor();
1205 }
1206
1207 print_reversed = !was_printable;
1208 to_print += res.first.str();
1209 }
1210
Douglas Gregor02c23eb2012-10-23 22:26:28 +00001211 if (print_reversed && DiagOpts->ShowColors)
Seth Cantrell6749dd52012-04-18 02:44:46 +00001212 OS.reverseColor();
1213 OS << to_print;
Douglas Gregor02c23eb2012-10-23 22:26:28 +00001214 if (print_reversed && DiagOpts->ShowColors)
Seth Cantrell6749dd52012-04-18 02:44:46 +00001215 OS.resetColor();
1216
1217 OS << '\n';
1218}
1219
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +00001220void TextDiagnostic::emitParseableFixits(ArrayRef<FixItHint> Hints,
1221 const SourceManager &SM) {
Douglas Gregor02c23eb2012-10-23 22:26:28 +00001222 if (!DiagOpts->ShowParseableFixits)
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001223 return;
1224
1225 // We follow FixItRewriter's example in not (yet) handling
1226 // fix-its in macros.
1227 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1228 I != E; ++I) {
1229 if (I->RemoveRange.isInvalid() ||
1230 I->RemoveRange.getBegin().isMacroID() ||
1231 I->RemoveRange.getEnd().isMacroID())
1232 return;
1233 }
1234
1235 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1236 I != E; ++I) {
1237 SourceLocation BLoc = I->RemoveRange.getBegin();
1238 SourceLocation ELoc = I->RemoveRange.getEnd();
1239
1240 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(BLoc);
1241 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(ELoc);
1242
1243 // Adjust for token ranges.
1244 if (I->RemoveRange.isTokenRange())
1245 EInfo.second += Lexer::MeasureTokenLength(ELoc, SM, LangOpts);
1246
1247 // We specifically do not do word-wrapping or tab-expansion here,
1248 // because this is supposed to be easy to parse.
1249 PresumedLoc PLoc = SM.getPresumedLoc(BLoc);
1250 if (PLoc.isInvalid())
1251 break;
1252
1253 OS << "fix-it:\"";
1254 OS.write_escaped(PLoc.getFilename());
1255 OS << "\":{" << SM.getLineNumber(BInfo.first, BInfo.second)
1256 << ':' << SM.getColumnNumber(BInfo.first, BInfo.second)
1257 << '-' << SM.getLineNumber(EInfo.first, EInfo.second)
1258 << ':' << SM.getColumnNumber(EInfo.first, EInfo.second)
1259 << "}:\"";
1260 OS.write_escaped(I->CodeToInsert);
1261 OS << "\"\n";
1262 }
1263}