blob: d95b925355b48827d744f0e42734e8058b77a0ae [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};
317
318// used in assert in selectInterestingSourceRegion()
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000319struct char_out_of_range {
320 const char lower,upper;
321 char_out_of_range(char lower, char upper) :
322 lower(lower), upper(upper) {}
323 bool operator()(char c) { return c < lower || upper < c; }
324};
Benjamin Kramer2a812282012-12-01 20:58:01 +0000325} // end anonymous namespace
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000326
Chandler Carrutha3028852011-10-15 23:43:53 +0000327/// \brief When the source code line we want to print is too long for
328/// the terminal, select the "interesting" region.
Chandler Carruthab4c1da2011-10-15 23:54:09 +0000329static void selectInterestingSourceRegion(std::string &SourceLine,
Chandler Carrutha3028852011-10-15 23:43:53 +0000330 std::string &CaretLine,
331 std::string &FixItInsertionLine,
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000332 unsigned Columns,
333 const SourceColumnMap &map) {
334 unsigned MaxColumns = std::max<unsigned>(map.columns(),
335 std::max(CaretLine.size(),
336 FixItInsertionLine.size()));
337 // if the number of columns is less than the desired number we're done
338 if (MaxColumns <= Columns)
339 return;
340
Jordan Rosee2fad6d2013-06-07 17:16:01 +0000341 // No special characters are allowed in CaretLine.
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000342 assert(CaretLine.end() ==
343 std::find_if(CaretLine.begin(), CaretLine.end(),
344 char_out_of_range(' ','~')));
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000345
Chandler Carrutha3028852011-10-15 23:43:53 +0000346 // Find the slice that we need to display the full caret line
347 // correctly.
348 unsigned CaretStart = 0, CaretEnd = CaretLine.size();
349 for (; CaretStart != CaretEnd; ++CaretStart)
Jordan Rosea7d03842013-02-08 22:30:41 +0000350 if (!isWhitespace(CaretLine[CaretStart]))
Chandler Carrutha3028852011-10-15 23:43:53 +0000351 break;
352
353 for (; CaretEnd != CaretStart; --CaretEnd)
Jordan Rosea7d03842013-02-08 22:30:41 +0000354 if (!isWhitespace(CaretLine[CaretEnd - 1]))
Chandler Carrutha3028852011-10-15 23:43:53 +0000355 break;
356
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000357 // caret has already been inserted into CaretLine so the above whitespace
358 // check is guaranteed to include the caret
Chandler Carrutha3028852011-10-15 23:43:53 +0000359
360 // If we have a fix-it line, make sure the slice includes all of the
361 // fix-it information.
362 if (!FixItInsertionLine.empty()) {
363 unsigned FixItStart = 0, FixItEnd = FixItInsertionLine.size();
364 for (; FixItStart != FixItEnd; ++FixItStart)
Jordan Rosea7d03842013-02-08 22:30:41 +0000365 if (!isWhitespace(FixItInsertionLine[FixItStart]))
Chandler Carrutha3028852011-10-15 23:43:53 +0000366 break;
367
368 for (; FixItEnd != FixItStart; --FixItEnd)
Jordan Rosea7d03842013-02-08 22:30:41 +0000369 if (!isWhitespace(FixItInsertionLine[FixItEnd - 1]))
Chandler Carrutha3028852011-10-15 23:43:53 +0000370 break;
371
Jordan Rosee2fad6d2013-06-07 17:16:01 +0000372 // We can safely use the byte offset FixItStart as the column offset
373 // because the characters up until FixItStart are all ASCII whitespace
374 // characters.
375 unsigned FixItStartCol = FixItStart;
376 unsigned FixItEndCol
377 = llvm::sys::locale::columnWidth(FixItInsertionLine.substr(0, FixItEnd));
378
379 CaretStart = std::min(FixItStartCol, CaretStart);
380 CaretEnd = std::max(FixItEndCol, CaretEnd);
Chandler Carrutha3028852011-10-15 23:43:53 +0000381 }
382
Seth Cantrellac6fb8f2012-05-24 05:14:44 +0000383 // CaretEnd may have been set at the middle of a character
384 // If it's not at a character's first column then advance it past the current
385 // character.
386 while (static_cast<int>(CaretEnd) < map.columns() &&
387 -1 == map.columnToByte(CaretEnd))
388 ++CaretEnd;
389
390 assert((static_cast<int>(CaretStart) > map.columns() ||
391 -1!=map.columnToByte(CaretStart)) &&
392 "CaretStart must not point to a column in the middle of a source"
393 " line character");
394 assert((static_cast<int>(CaretEnd) > map.columns() ||
395 -1!=map.columnToByte(CaretEnd)) &&
396 "CaretEnd must not point to a column in the middle of a source line"
397 " character");
398
Chandler Carrutha3028852011-10-15 23:43:53 +0000399 // CaretLine[CaretStart, CaretEnd) contains all of the interesting
400 // parts of the caret line. While this slice is smaller than the
401 // number of columns we have, try to grow the slice to encompass
402 // more context.
403
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000404 unsigned SourceStart = map.columnToByte(std::min<unsigned>(CaretStart,
405 map.columns()));
406 unsigned SourceEnd = map.columnToByte(std::min<unsigned>(CaretEnd,
407 map.columns()));
408
409 unsigned CaretColumnsOutsideSource = CaretEnd-CaretStart
410 - (map.byteToColumn(SourceEnd)-map.byteToColumn(SourceStart));
411
412 char const *front_ellipse = " ...";
413 char const *front_space = " ";
414 char const *back_ellipse = "...";
415 unsigned ellipses_space = strlen(front_ellipse) + strlen(back_ellipse);
Chandler Carrutha3028852011-10-15 23:43:53 +0000416
417 unsigned TargetColumns = Columns;
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000418 // Give us extra room for the ellipses
419 // and any of the caret line that extends past the source
420 if (TargetColumns > ellipses_space+CaretColumnsOutsideSource)
421 TargetColumns -= ellipses_space+CaretColumnsOutsideSource;
422
423 while (SourceStart>0 || SourceEnd<SourceLine.size()) {
Chandler Carrutha3028852011-10-15 23:43:53 +0000424 bool ExpandedRegion = false;
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000425
426 if (SourceStart>0) {
Seth Cantrell6292e5b82012-11-03 21:21:17 +0000427 unsigned NewStart = map.startOfPreviousColumn(SourceStart);
Chandler Carrutha3028852011-10-15 23:43:53 +0000428
429 // Skip over any whitespace we see here; we're looking for
430 // another bit of interesting text.
Richard Smithfab4b1a2012-09-13 18:37:50 +0000431 // FIXME: Detect non-ASCII whitespace characters too.
Jordan Rosea7d03842013-02-08 22:30:41 +0000432 while (NewStart && isWhitespace(SourceLine[NewStart]))
Richard Smithfab4b1a2012-09-13 18:37:50 +0000433 NewStart = map.startOfPreviousColumn(NewStart);
Chandler Carrutha3028852011-10-15 23:43:53 +0000434
435 // Skip over this bit of "interesting" text.
Richard Smithfab4b1a2012-09-13 18:37:50 +0000436 while (NewStart) {
437 unsigned Prev = map.startOfPreviousColumn(NewStart);
Jordan Rosea7d03842013-02-08 22:30:41 +0000438 if (isWhitespace(SourceLine[Prev]))
Richard Smithfab4b1a2012-09-13 18:37:50 +0000439 break;
440 NewStart = Prev;
441 }
Chandler Carrutha3028852011-10-15 23:43:53 +0000442
Richard Smithfab4b1a2012-09-13 18:37:50 +0000443 assert(map.byteToColumn(NewStart) != -1);
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000444 unsigned NewColumns = map.byteToColumn(SourceEnd) -
445 map.byteToColumn(NewStart);
446 if (NewColumns <= TargetColumns) {
447 SourceStart = NewStart;
Chandler Carrutha3028852011-10-15 23:43:53 +0000448 ExpandedRegion = true;
449 }
450 }
451
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000452 if (SourceEnd<SourceLine.size()) {
Seth Cantrell6292e5b82012-11-03 21:21:17 +0000453 unsigned NewEnd = map.startOfNextColumn(SourceEnd);
Chandler Carrutha3028852011-10-15 23:43:53 +0000454
455 // Skip over any whitespace we see here; we're looking for
456 // another bit of interesting text.
Richard Smithfab4b1a2012-09-13 18:37:50 +0000457 // FIXME: Detect non-ASCII whitespace characters too.
Jordan Rosea7d03842013-02-08 22:30:41 +0000458 while (NewEnd < SourceLine.size() && isWhitespace(SourceLine[NewEnd]))
Richard Smithfab4b1a2012-09-13 18:37:50 +0000459 NewEnd = map.startOfNextColumn(NewEnd);
Chandler Carrutha3028852011-10-15 23:43:53 +0000460
461 // Skip over this bit of "interesting" text.
Jordan Rosea7d03842013-02-08 22:30:41 +0000462 while (NewEnd < SourceLine.size() && isWhitespace(SourceLine[NewEnd]))
Richard Smithfab4b1a2012-09-13 18:37:50 +0000463 NewEnd = map.startOfNextColumn(NewEnd);
Chandler Carrutha3028852011-10-15 23:43:53 +0000464
Richard Smithfab4b1a2012-09-13 18:37:50 +0000465 assert(map.byteToColumn(NewEnd) != -1);
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000466 unsigned NewColumns = map.byteToColumn(NewEnd) -
467 map.byteToColumn(SourceStart);
468 if (NewColumns <= TargetColumns) {
469 SourceEnd = NewEnd;
Chandler Carrutha3028852011-10-15 23:43:53 +0000470 ExpandedRegion = true;
471 }
472 }
473
474 if (!ExpandedRegion)
475 break;
476 }
477
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000478 CaretStart = map.byteToColumn(SourceStart);
479 CaretEnd = map.byteToColumn(SourceEnd) + CaretColumnsOutsideSource;
480
Chandler Carrutha3028852011-10-15 23:43:53 +0000481 // [CaretStart, CaretEnd) is the slice we want. Update the various
482 // output lines to show only this slice, with two-space padding
483 // before the lines so that it looks nicer.
Chandler Carrutha3028852011-10-15 23:43:53 +0000484
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000485 assert(CaretStart!=(unsigned)-1 && CaretEnd!=(unsigned)-1 &&
486 SourceStart!=(unsigned)-1 && SourceEnd!=(unsigned)-1);
487 assert(SourceStart <= SourceEnd);
488 assert(CaretStart <= CaretEnd);
489
490 unsigned BackColumnsRemoved
491 = map.byteToColumn(SourceLine.size())-map.byteToColumn(SourceEnd);
492 unsigned FrontColumnsRemoved = CaretStart;
493 unsigned ColumnsKept = CaretEnd-CaretStart;
494
495 // We checked up front that the line needed truncation
496 assert(FrontColumnsRemoved+ColumnsKept+BackColumnsRemoved > Columns);
497
498 // The line needs some trunctiona, and we'd prefer to keep the front
499 // if possible, so remove the back
Seth Cantrell40f87b12012-11-03 23:56:43 +0000500 if (BackColumnsRemoved > strlen(back_ellipse))
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000501 SourceLine.replace(SourceEnd, std::string::npos, back_ellipse);
502
503 // If that's enough then we're done
504 if (FrontColumnsRemoved+ColumnsKept <= Columns)
505 return;
506
507 // Otherwise remove the front as well
Seth Cantrell40f87b12012-11-03 23:56:43 +0000508 if (FrontColumnsRemoved > strlen(front_ellipse)) {
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000509 SourceLine.replace(0, SourceStart, front_ellipse);
510 CaretLine.replace(0, CaretStart, front_space);
511 if (!FixItInsertionLine.empty())
512 FixItInsertionLine.replace(0, CaretStart, front_space);
Chandler Carrutha3028852011-10-15 23:43:53 +0000513 }
514}
515
Chandler Carrutha3028852011-10-15 23:43:53 +0000516/// \brief Skip over whitespace in the string, starting at the given
517/// index.
518///
519/// \returns The index of the first non-whitespace character that is
520/// greater than or equal to Idx or, if no such character exists,
521/// returns the end of the string.
522static unsigned skipWhitespace(unsigned Idx, StringRef Str, unsigned Length) {
Jordan Rosea7d03842013-02-08 22:30:41 +0000523 while (Idx < Length && isWhitespace(Str[Idx]))
Chandler Carrutha3028852011-10-15 23:43:53 +0000524 ++Idx;
525 return Idx;
526}
527
528/// \brief If the given character is the start of some kind of
529/// balanced punctuation (e.g., quotes or parentheses), return the
530/// character that will terminate the punctuation.
531///
532/// \returns The ending punctuation character, if any, or the NULL
533/// character if the input character does not start any punctuation.
534static inline char findMatchingPunctuation(char c) {
535 switch (c) {
536 case '\'': return '\'';
537 case '`': return '\'';
538 case '"': return '"';
539 case '(': return ')';
540 case '[': return ']';
541 case '{': return '}';
542 default: break;
543 }
544
545 return 0;
546}
547
548/// \brief Find the end of the word starting at the given offset
549/// within a string.
550///
551/// \returns the index pointing one character past the end of the
552/// word.
553static unsigned findEndOfWord(unsigned Start, StringRef Str,
554 unsigned Length, unsigned Column,
555 unsigned Columns) {
556 assert(Start < Str.size() && "Invalid start position!");
557 unsigned End = Start + 1;
558
559 // If we are already at the end of the string, take that as the word.
560 if (End == Str.size())
561 return End;
562
563 // Determine if the start of the string is actually opening
564 // punctuation, e.g., a quote or parentheses.
565 char EndPunct = findMatchingPunctuation(Str[Start]);
566 if (!EndPunct) {
567 // This is a normal word. Just find the first space character.
Jordan Rosea7d03842013-02-08 22:30:41 +0000568 while (End < Length && !isWhitespace(Str[End]))
Chandler Carrutha3028852011-10-15 23:43:53 +0000569 ++End;
570 return End;
571 }
572
573 // We have the start of a balanced punctuation sequence (quotes,
574 // parentheses, etc.). Determine the full sequence is.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000575 SmallString<16> PunctuationEndStack;
Chandler Carrutha3028852011-10-15 23:43:53 +0000576 PunctuationEndStack.push_back(EndPunct);
577 while (End < Length && !PunctuationEndStack.empty()) {
578 if (Str[End] == PunctuationEndStack.back())
579 PunctuationEndStack.pop_back();
580 else if (char SubEndPunct = findMatchingPunctuation(Str[End]))
581 PunctuationEndStack.push_back(SubEndPunct);
582
583 ++End;
584 }
585
586 // Find the first space character after the punctuation ended.
Jordan Rosea7d03842013-02-08 22:30:41 +0000587 while (End < Length && !isWhitespace(Str[End]))
Chandler Carrutha3028852011-10-15 23:43:53 +0000588 ++End;
589
590 unsigned PunctWordLength = End - Start;
591 if (// If the word fits on this line
592 Column + PunctWordLength <= Columns ||
593 // ... or the word is "short enough" to take up the next line
594 // without too much ugly white space
595 PunctWordLength < Columns/3)
596 return End; // Take the whole thing as a single "word".
597
598 // The whole quoted/parenthesized string is too long to print as a
599 // single "word". Instead, find the "word" that starts just after
600 // the punctuation and use that end-point instead. This will recurse
601 // until it finds something small enough to consider a word.
602 return findEndOfWord(Start + 1, Str, Length, Column + 1, Columns);
603}
604
605/// \brief Print the given string to a stream, word-wrapping it to
606/// some number of columns in the process.
607///
608/// \param OS the stream to which the word-wrapping string will be
609/// emitted.
610/// \param Str the string to word-wrap and output.
611/// \param Columns the number of columns to word-wrap to.
612/// \param Column the column number at which the first character of \p
613/// Str will be printed. This will be non-zero when part of the first
614/// line has already been printed.
Richard Trieua71f0de2012-06-28 22:39:03 +0000615/// \param Bold if the current text should be bold
Chandler Carrutha3028852011-10-15 23:43:53 +0000616/// \param Indentation the number of spaces to indent any lines beyond
617/// the first line.
618/// \returns true if word-wrapping was required, or false if the
619/// string fit on the first line.
620static bool printWordWrapped(raw_ostream &OS, StringRef Str,
621 unsigned Columns,
622 unsigned Column = 0,
Richard Trieua71f0de2012-06-28 22:39:03 +0000623 bool Bold = false,
Chandler Carrutha3028852011-10-15 23:43:53 +0000624 unsigned Indentation = WordWrapIndentation) {
625 const unsigned Length = std::min(Str.find('\n'), Str.size());
Richard Trieu91844232012-06-26 18:18:47 +0000626 bool TextNormal = true;
Chandler Carrutha3028852011-10-15 23:43:53 +0000627
628 // The string used to indent each line.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000629 SmallString<16> IndentStr;
Chandler Carrutha3028852011-10-15 23:43:53 +0000630 IndentStr.assign(Indentation, ' ');
631 bool Wrapped = false;
632 for (unsigned WordStart = 0, WordEnd; WordStart < Length;
633 WordStart = WordEnd) {
634 // Find the beginning of the next word.
635 WordStart = skipWhitespace(WordStart, Str, Length);
636 if (WordStart == Length)
637 break;
638
639 // Find the end of this word.
640 WordEnd = findEndOfWord(WordStart, Str, Length, Column, Columns);
641
642 // Does this word fit on the current line?
643 unsigned WordLength = WordEnd - WordStart;
644 if (Column + WordLength < Columns) {
645 // This word fits on the current line; print it there.
646 if (WordStart) {
647 OS << ' ';
648 Column += 1;
649 }
Richard Trieu91844232012-06-26 18:18:47 +0000650 applyTemplateHighlighting(OS, Str.substr(WordStart, WordLength),
Richard Trieua71f0de2012-06-28 22:39:03 +0000651 TextNormal, Bold);
Chandler Carrutha3028852011-10-15 23:43:53 +0000652 Column += WordLength;
653 continue;
654 }
655
656 // This word does not fit on the current line, so wrap to the next
657 // line.
658 OS << '\n';
659 OS.write(&IndentStr[0], Indentation);
Richard Trieu91844232012-06-26 18:18:47 +0000660 applyTemplateHighlighting(OS, Str.substr(WordStart, WordLength),
Richard Trieua71f0de2012-06-28 22:39:03 +0000661 TextNormal, Bold);
Chandler Carrutha3028852011-10-15 23:43:53 +0000662 Column = Indentation + WordLength;
663 Wrapped = true;
664 }
665
666 // Append any remaning text from the message with its existing formatting.
Richard Trieua71f0de2012-06-28 22:39:03 +0000667 applyTemplateHighlighting(OS, Str.substr(Length), TextNormal, Bold);
Richard Trieu91844232012-06-26 18:18:47 +0000668
669 assert(TextNormal && "Text highlighted at end of diagnostic message.");
Chandler Carrutha3028852011-10-15 23:43:53 +0000670
671 return Wrapped;
672}
673
674TextDiagnostic::TextDiagnostic(raw_ostream &OS,
Chandler Carrutha3028852011-10-15 23:43:53 +0000675 const LangOptions &LangOpts,
Douglas Gregor811db4e2012-10-23 22:26:28 +0000676 DiagnosticOptions *DiagOpts)
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +0000677 : DiagnosticRenderer(LangOpts, DiagOpts), OS(OS) {}
Chandler Carrutha3028852011-10-15 23:43:53 +0000678
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000679TextDiagnostic::~TextDiagnostic() {}
Chandler Carrutha3028852011-10-15 23:43:53 +0000680
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000681void
682TextDiagnostic::emitDiagnosticMessage(SourceLocation Loc,
683 PresumedLoc PLoc,
684 DiagnosticsEngine::Level Level,
685 StringRef Message,
686 ArrayRef<clang::CharSourceRange> Ranges,
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +0000687 const SourceManager *SM,
Ted Kremenek0964cca2012-02-14 02:46:00 +0000688 DiagOrStoredDiag D) {
Chandler Carrutha3028852011-10-15 23:43:53 +0000689 uint64_t StartOfLocationInfo = OS.tell();
690
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000691 // Emit the location of this particular diagnostic.
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +0000692 if (Loc.isValid())
693 emitDiagnosticLoc(Loc, PLoc, Level, Ranges, *SM);
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000694
Douglas Gregor811db4e2012-10-23 22:26:28 +0000695 if (DiagOpts->ShowColors)
Chandler Carrutha3028852011-10-15 23:43:53 +0000696 OS.resetColor();
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000697
Hans Wennborgf4aee182013-09-24 00:08:55 +0000698 printDiagnosticLevel(OS, Level, DiagOpts->ShowColors,
699 DiagOpts->CLFallbackMode);
Chandler Carrutha3028852011-10-15 23:43:53 +0000700 printDiagnosticMessage(OS, Level, Message,
701 OS.tell() - StartOfLocationInfo,
Douglas Gregor811db4e2012-10-23 22:26:28 +0000702 DiagOpts->MessageLength, DiagOpts->ShowColors);
Chandler Carrutha3028852011-10-15 23:43:53 +0000703}
704
Chandler Carruth07c346d2011-10-15 23:48:02 +0000705/*static*/ void
706TextDiagnostic::printDiagnosticLevel(raw_ostream &OS,
707 DiagnosticsEngine::Level Level,
Hans Wennborgf4aee182013-09-24 00:08:55 +0000708 bool ShowColors,
709 bool CLFallbackMode) {
Chandler Carruth07c346d2011-10-15 23:48:02 +0000710 if (ShowColors) {
711 // Print diagnostic category in bold and color
712 switch (Level) {
713 case DiagnosticsEngine::Ignored:
714 llvm_unreachable("Invalid diagnostic type");
715 case DiagnosticsEngine::Note: OS.changeColor(noteColor, true); break;
Tobias Grosser74160242014-02-28 09:11:08 +0000716 case DiagnosticsEngine::Remark: OS.changeColor(remarkColor, true); break;
Chandler Carruth07c346d2011-10-15 23:48:02 +0000717 case DiagnosticsEngine::Warning: OS.changeColor(warningColor, true); break;
718 case DiagnosticsEngine::Error: OS.changeColor(errorColor, true); break;
719 case DiagnosticsEngine::Fatal: OS.changeColor(fatalColor, true); break;
720 }
721 }
722
723 switch (Level) {
724 case DiagnosticsEngine::Ignored:
725 llvm_unreachable("Invalid diagnostic type");
Hans Wennborgf4aee182013-09-24 00:08:55 +0000726 case DiagnosticsEngine::Note: OS << "note"; break;
Tobias Grosser74160242014-02-28 09:11:08 +0000727 case DiagnosticsEngine::Remark: OS << "remark"; break;
Hans Wennborgf4aee182013-09-24 00:08:55 +0000728 case DiagnosticsEngine::Warning: OS << "warning"; break;
729 case DiagnosticsEngine::Error: OS << "error"; break;
730 case DiagnosticsEngine::Fatal: OS << "fatal error"; break;
Chandler Carruth07c346d2011-10-15 23:48:02 +0000731 }
732
Hans Wennborgf4aee182013-09-24 00:08:55 +0000733 // In clang-cl /fallback mode, print diagnostics as "error(clang):". This
734 // makes it more clear whether a message is coming from clang or cl.exe,
735 // and it prevents MSBuild from concluding that the build failed just because
736 // there is an "error:" in the output.
737 if (CLFallbackMode)
738 OS << "(clang)";
739
740 OS << ": ";
741
Chandler Carruth07c346d2011-10-15 23:48:02 +0000742 if (ShowColors)
743 OS.resetColor();
744}
745
746/*static*/ void
747TextDiagnostic::printDiagnosticMessage(raw_ostream &OS,
748 DiagnosticsEngine::Level Level,
749 StringRef Message,
750 unsigned CurrentColumn, unsigned Columns,
751 bool ShowColors) {
Richard Trieua71f0de2012-06-28 22:39:03 +0000752 bool Bold = false;
Chandler Carruth07c346d2011-10-15 23:48:02 +0000753 if (ShowColors) {
754 // Print warnings, errors and fatal errors in bold, no color
755 switch (Level) {
Richard Trieua71f0de2012-06-28 22:39:03 +0000756 case DiagnosticsEngine::Warning:
757 case DiagnosticsEngine::Error:
758 case DiagnosticsEngine::Fatal:
759 OS.changeColor(savedColor, true);
760 Bold = true;
761 break;
Chandler Carruth07c346d2011-10-15 23:48:02 +0000762 default: break; //don't bold notes
763 }
764 }
765
766 if (Columns)
Richard Trieua71f0de2012-06-28 22:39:03 +0000767 printWordWrapped(OS, Message, Columns, CurrentColumn, Bold);
David Blaikie9e55d742012-06-28 21:46:07 +0000768 else {
769 bool Normal = true;
Richard Trieua71f0de2012-06-28 22:39:03 +0000770 applyTemplateHighlighting(OS, Message, Normal, Bold);
David Blaikie9e55d742012-06-28 21:46:07 +0000771 assert(Normal && "Formatting should have returned to normal");
772 }
Chandler Carruth07c346d2011-10-15 23:48:02 +0000773
774 if (ShowColors)
775 OS.resetColor();
776 OS << '\n';
777}
778
Chandler Carruth07c346d2011-10-15 23:48:02 +0000779/// \brief Print out the file/line/column information and include trace.
780///
781/// This method handlen the emission of the diagnostic location information.
782/// This includes extracting as much location information as is present for
783/// the diagnostic and printing it, as well as any include stack or source
784/// ranges necessary.
Chandler Carruthab4c1da2011-10-15 23:54:09 +0000785void TextDiagnostic::emitDiagnosticLoc(SourceLocation Loc, PresumedLoc PLoc,
Chandler Carruth07c346d2011-10-15 23:48:02 +0000786 DiagnosticsEngine::Level Level,
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +0000787 ArrayRef<CharSourceRange> Ranges,
788 const SourceManager &SM) {
Chandler Carruth07c346d2011-10-15 23:48:02 +0000789 if (PLoc.isInvalid()) {
790 // At least print the file name if available:
791 FileID FID = SM.getFileID(Loc);
792 if (!FID.isInvalid()) {
793 const FileEntry* FE = SM.getFileEntryForID(FID);
Ben Langmuirc8a71462014-02-27 17:23:33 +0000794 if (FE && FE->isValid()) {
Chandler Carruth07c346d2011-10-15 23:48:02 +0000795 OS << FE->getName();
Rafael Espindolaf8f91b82013-08-01 21:42:11 +0000796 if (FE->isInPCH())
Chandler Carruth07c346d2011-10-15 23:48:02 +0000797 OS << " (in PCH)";
Chandler Carruth07c346d2011-10-15 23:48:02 +0000798 OS << ": ";
799 }
800 }
801 return;
802 }
803 unsigned LineNo = PLoc.getLine();
804
Douglas Gregor811db4e2012-10-23 22:26:28 +0000805 if (!DiagOpts->ShowLocation)
Chandler Carruth07c346d2011-10-15 23:48:02 +0000806 return;
807
Douglas Gregor811db4e2012-10-23 22:26:28 +0000808 if (DiagOpts->ShowColors)
Chandler Carruth07c346d2011-10-15 23:48:02 +0000809 OS.changeColor(savedColor, true);
810
811 OS << PLoc.getFilename();
Douglas Gregor79591782012-10-23 23:11:23 +0000812 switch (DiagOpts->getFormat()) {
Chandler Carruth07c346d2011-10-15 23:48:02 +0000813 case DiagnosticOptions::Clang: OS << ':' << LineNo; break;
814 case DiagnosticOptions::Msvc: OS << '(' << LineNo; break;
815 case DiagnosticOptions::Vi: OS << " +" << LineNo; break;
816 }
817
Douglas Gregor811db4e2012-10-23 22:26:28 +0000818 if (DiagOpts->ShowColumn)
Chandler Carruth07c346d2011-10-15 23:48:02 +0000819 // Compute the column number.
820 if (unsigned ColNo = PLoc.getColumn()) {
Douglas Gregor79591782012-10-23 23:11:23 +0000821 if (DiagOpts->getFormat() == DiagnosticOptions::Msvc) {
Chandler Carruth07c346d2011-10-15 23:48:02 +0000822 OS << ',';
823 ColNo--;
824 } else
825 OS << ':';
826 OS << ColNo;
827 }
Douglas Gregor79591782012-10-23 23:11:23 +0000828 switch (DiagOpts->getFormat()) {
Chandler Carruth07c346d2011-10-15 23:48:02 +0000829 case DiagnosticOptions::Clang:
830 case DiagnosticOptions::Vi: OS << ':'; break;
831 case DiagnosticOptions::Msvc: OS << ") : "; break;
832 }
833
Douglas Gregor811db4e2012-10-23 22:26:28 +0000834 if (DiagOpts->ShowSourceRanges && !Ranges.empty()) {
Chandler Carruth07c346d2011-10-15 23:48:02 +0000835 FileID CaretFileID =
836 SM.getFileID(SM.getExpansionLoc(Loc));
837 bool PrintedRange = false;
838
839 for (ArrayRef<CharSourceRange>::const_iterator RI = Ranges.begin(),
840 RE = Ranges.end();
841 RI != RE; ++RI) {
842 // Ignore invalid ranges.
843 if (!RI->isValid()) continue;
844
845 SourceLocation B = SM.getExpansionLoc(RI->getBegin());
846 SourceLocation E = SM.getExpansionLoc(RI->getEnd());
847
848 // If the End location and the start location are the same and are a
849 // macro location, then the range was something that came from a
850 // macro expansion or _Pragma. If this is an object-like macro, the
851 // best we can do is to highlight the range. If this is a
852 // function-like macro, we'd also like to highlight the arguments.
853 if (B == E && RI->getEnd().isMacroID())
854 E = SM.getExpansionRange(RI->getEnd()).second;
855
856 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(B);
857 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E);
858
859 // If the start or end of the range is in another file, just discard
860 // it.
861 if (BInfo.first != CaretFileID || EInfo.first != CaretFileID)
862 continue;
863
864 // Add in the length of the token, so that we cover multi-char
865 // tokens.
866 unsigned TokSize = 0;
867 if (RI->isTokenRange())
868 TokSize = Lexer::MeasureTokenLength(E, SM, LangOpts);
869
870 OS << '{' << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
871 << SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
872 << SM.getLineNumber(EInfo.first, EInfo.second) << ':'
873 << (SM.getColumnNumber(EInfo.first, EInfo.second)+TokSize)
874 << '}';
875 PrintedRange = true;
876 }
877
878 if (PrintedRange)
879 OS << ':';
880 }
881 OS << ' ';
882}
883
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000884void TextDiagnostic::emitBasicNote(StringRef Message) {
885 // FIXME: Emit this as a real note diagnostic.
886 // FIXME: Format an actual diagnostic rather than a hard coded string.
887 OS << "note: " << Message << "\n";
888}
Chandler Carrutha3028852011-10-15 23:43:53 +0000889
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000890void TextDiagnostic::emitIncludeLocation(SourceLocation Loc,
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +0000891 PresumedLoc PLoc,
892 const SourceManager &SM) {
Douglas Gregor811db4e2012-10-23 22:26:28 +0000893 if (DiagOpts->ShowLocation)
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000894 OS << "In file included from " << PLoc.getFilename() << ':'
895 << PLoc.getLine() << ":\n";
896 else
897 OS << "In included file:\n";
Chandler Carrutha3028852011-10-15 23:43:53 +0000898}
899
Douglas Gregor22103e32012-11-30 21:58:49 +0000900void TextDiagnostic::emitImportLocation(SourceLocation Loc, PresumedLoc PLoc,
901 StringRef ModuleName,
902 const SourceManager &SM) {
903 if (DiagOpts->ShowLocation)
904 OS << "In module '" << ModuleName << "' imported from "
905 << PLoc.getFilename() << ':' << PLoc.getLine() << ":\n";
906 else
907 OS << "In module " << ModuleName << "':\n";
908}
909
Douglas Gregoraf8f0262012-11-30 18:38:50 +0000910void TextDiagnostic::emitBuildingModuleLocation(SourceLocation Loc,
911 PresumedLoc PLoc,
912 StringRef ModuleName,
913 const SourceManager &SM) {
Douglas Gregordfc94302012-12-18 23:02:07 +0000914 if (DiagOpts->ShowLocation && PLoc.getFilename())
Douglas Gregoraf8f0262012-11-30 18:38:50 +0000915 OS << "While building module '" << ModuleName << "' imported from "
916 << PLoc.getFilename() << ':' << PLoc.getLine() << ":\n";
917 else
918 OS << "While building module '" << ModuleName << "':\n";
919}
920
Benjamin Kramer2a812282012-12-01 20:58:01 +0000921/// \brief Highlight a SourceRange (with ~'s) for any characters on LineNo.
922static void highlightRange(const CharSourceRange &R,
923 unsigned LineNo, FileID FID,
924 const SourceColumnMap &map,
925 std::string &CaretLine,
926 const SourceManager &SM,
927 const LangOptions &LangOpts) {
928 if (!R.isValid()) return;
929
930 SourceLocation Begin = R.getBegin();
931 SourceLocation End = R.getEnd();
932
933 unsigned StartLineNo = SM.getExpansionLineNumber(Begin);
934 if (StartLineNo > LineNo || SM.getFileID(Begin) != FID)
935 return; // No intersection.
936
937 unsigned EndLineNo = SM.getExpansionLineNumber(End);
938 if (EndLineNo < LineNo || SM.getFileID(End) != FID)
939 return; // No intersection.
940
941 // Compute the column number of the start.
942 unsigned StartColNo = 0;
943 if (StartLineNo == LineNo) {
944 StartColNo = SM.getExpansionColumnNumber(Begin);
945 if (StartColNo) --StartColNo; // Zero base the col #.
946 }
947
948 // Compute the column number of the end.
949 unsigned EndColNo = map.getSourceLine().size();
950 if (EndLineNo == LineNo) {
951 EndColNo = SM.getExpansionColumnNumber(End);
952 if (EndColNo) {
953 --EndColNo; // Zero base the col #.
954
955 // Add in the length of the token, so that we cover multi-char tokens if
956 // this is a token range.
957 if (R.isTokenRange())
958 EndColNo += Lexer::MeasureTokenLength(End, SM, LangOpts);
959 } else {
960 EndColNo = CaretLine.size();
961 }
962 }
963
964 assert(StartColNo <= EndColNo && "Invalid range!");
965
966 // Check that a token range does not highlight only whitespace.
967 if (R.isTokenRange()) {
968 // Pick the first non-whitespace column.
969 while (StartColNo < map.getSourceLine().size() &&
970 (map.getSourceLine()[StartColNo] == ' ' ||
971 map.getSourceLine()[StartColNo] == '\t'))
972 StartColNo = map.startOfNextColumn(StartColNo);
973
974 // Pick the last non-whitespace column.
975 if (EndColNo > map.getSourceLine().size())
976 EndColNo = map.getSourceLine().size();
Ted Kremenek90d7fa12013-03-15 23:09:37 +0000977 while (EndColNo &&
Benjamin Kramer2a812282012-12-01 20:58:01 +0000978 (map.getSourceLine()[EndColNo-1] == ' ' ||
979 map.getSourceLine()[EndColNo-1] == '\t'))
980 EndColNo = map.startOfPreviousColumn(EndColNo);
981
982 // If the start/end passed each other, then we are trying to highlight a
983 // range that just exists in whitespace, which must be some sort of other
984 // bug.
985 assert(StartColNo <= EndColNo && "Trying to highlight whitespace??");
986 }
987
988 assert(StartColNo <= map.getSourceLine().size() && "Invalid range!");
989 assert(EndColNo <= map.getSourceLine().size() && "Invalid range!");
990
991 // Fill the range with ~'s.
992 StartColNo = map.byteToContainingColumn(StartColNo);
993 EndColNo = map.byteToContainingColumn(EndColNo);
994
995 assert(StartColNo <= EndColNo && "Invalid range!");
996 if (CaretLine.size() < EndColNo)
997 CaretLine.resize(EndColNo,' ');
998 std::fill(CaretLine.begin()+StartColNo,CaretLine.begin()+EndColNo,'~');
999}
1000
1001static std::string buildFixItInsertionLine(unsigned LineNo,
1002 const SourceColumnMap &map,
1003 ArrayRef<FixItHint> Hints,
1004 const SourceManager &SM,
1005 const DiagnosticOptions *DiagOpts) {
1006 std::string FixItInsertionLine;
1007 if (Hints.empty() || !DiagOpts->ShowFixits)
1008 return FixItInsertionLine;
1009 unsigned PrevHintEndCol = 0;
1010
1011 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1012 I != E; ++I) {
1013 if (!I->CodeToInsert.empty()) {
1014 // We have an insertion hint. Determine whether the inserted
1015 // code contains no newlines and is on the same line as the caret.
1016 std::pair<FileID, unsigned> HintLocInfo
1017 = SM.getDecomposedExpansionLoc(I->RemoveRange.getBegin());
1018 if (LineNo == SM.getLineNumber(HintLocInfo.first, HintLocInfo.second) &&
1019 StringRef(I->CodeToInsert).find_first_of("\n\r") == StringRef::npos) {
1020 // Insert the new code into the line just below the code
1021 // that the user wrote.
1022 // Note: When modifying this function, be very careful about what is a
1023 // "column" (printed width, platform-dependent) and what is a
1024 // "byte offset" (SourceManager "column").
1025 unsigned HintByteOffset
1026 = SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second) - 1;
1027
1028 // The hint must start inside the source or right at the end
1029 assert(HintByteOffset < static_cast<unsigned>(map.bytes())+1);
1030 unsigned HintCol = map.byteToContainingColumn(HintByteOffset);
1031
1032 // If we inserted a long previous hint, push this one forwards, and add
1033 // an extra space to show that this is not part of the previous
1034 // completion. This is sort of the best we can do when two hints appear
1035 // to overlap.
1036 //
1037 // Note that if this hint is located immediately after the previous
1038 // hint, no space will be added, since the location is more important.
1039 if (HintCol < PrevHintEndCol)
1040 HintCol = PrevHintEndCol + 1;
1041
Benjamin Kramer2a812282012-12-01 20:58:01 +00001042 // This should NOT use HintByteOffset, because the source might have
1043 // Unicode characters in earlier columns.
Jordan Rosee2fad6d2013-06-07 17:16:01 +00001044 unsigned NewFixItLineSize = FixItInsertionLine.size() +
1045 (HintCol - PrevHintEndCol) + I->CodeToInsert.size();
1046 if (NewFixItLineSize > FixItInsertionLine.size())
1047 FixItInsertionLine.resize(NewFixItLineSize, ' ');
Benjamin Kramer2a812282012-12-01 20:58:01 +00001048
1049 std::copy(I->CodeToInsert.begin(), I->CodeToInsert.end(),
Jordan Rosee2fad6d2013-06-07 17:16:01 +00001050 FixItInsertionLine.end() - I->CodeToInsert.size());
Benjamin Kramer2a812282012-12-01 20:58:01 +00001051
Jordan Rosee2fad6d2013-06-07 17:16:01 +00001052 PrevHintEndCol =
1053 HintCol + llvm::sys::locale::columnWidth(I->CodeToInsert);
Benjamin Kramer2a812282012-12-01 20:58:01 +00001054 } else {
1055 FixItInsertionLine.clear();
1056 break;
1057 }
1058 }
1059 }
1060
1061 expandTabs(FixItInsertionLine, DiagOpts->TabStop);
1062
1063 return FixItInsertionLine;
1064}
1065
Chandler Carrutha3028852011-10-15 23:43:53 +00001066/// \brief Emit a code snippet and caret line.
1067///
1068/// This routine emits a single line's code snippet and caret line..
1069///
1070/// \param Loc The location for the caret.
1071/// \param Ranges The underlined ranges for this code snippet.
1072/// \param Hints The FixIt hints active for this diagnostic.
Chandler Carruthab4c1da2011-10-15 23:54:09 +00001073void TextDiagnostic::emitSnippetAndCaret(
Chandler Carruthdc2f2572011-10-16 07:20:28 +00001074 SourceLocation Loc, DiagnosticsEngine::Level Level,
Chandler Carrutha3028852011-10-15 23:43:53 +00001075 SmallVectorImpl<CharSourceRange>& Ranges,
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +00001076 ArrayRef<FixItHint> Hints,
1077 const SourceManager &SM) {
Chandler Carrutha3028852011-10-15 23:43:53 +00001078 assert(!Loc.isInvalid() && "must have a valid source location here");
1079 assert(Loc.isFileID() && "must have a file location here");
1080
Chandler Carruthdc2f2572011-10-16 07:20:28 +00001081 // If caret diagnostics are enabled and we have location, we want to
1082 // emit the caret. However, we only do this if the location moved
1083 // from the last diagnostic, if the last diagnostic was a note that
1084 // was part of a different warning or error diagnostic, or if the
1085 // diagnostic has ranges. We don't want to emit the same caret
1086 // multiple times if one loc has multiple diagnostics.
Douglas Gregor811db4e2012-10-23 22:26:28 +00001087 if (!DiagOpts->ShowCarets)
Chandler Carruthdc2f2572011-10-16 07:20:28 +00001088 return;
1089 if (Loc == LastLoc && Ranges.empty() && Hints.empty() &&
1090 (LastLevel != DiagnosticsEngine::Note || Level == LastLevel))
1091 return;
1092
Chandler Carrutha3028852011-10-15 23:43:53 +00001093 // Decompose the location into a FID/Offset pair.
1094 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1095 FileID FID = LocInfo.first;
1096 unsigned FileOffset = LocInfo.second;
1097
1098 // Get information about the buffer it points into.
1099 bool Invalid = false;
Nico Weber35131222012-04-26 21:39:46 +00001100 const char *BufStart = SM.getBufferData(FID, &Invalid).data();
Chandler Carrutha3028852011-10-15 23:43:53 +00001101 if (Invalid)
1102 return;
1103
1104 unsigned LineNo = SM.getLineNumber(FID, FileOffset);
1105 unsigned ColNo = SM.getColumnNumber(FID, FileOffset);
Jordan Rose2da0d1c2013-01-30 21:41:07 +00001106
1107 // Arbitrarily stop showing snippets when the line is too long.
Benjamin Kramerd408de62013-04-23 14:42:47 +00001108 static const size_t MaxLineLengthToPrint = 4096;
Jordan Rosec40b0fa2013-01-30 22:14:15 +00001109 if (ColNo > MaxLineLengthToPrint)
Jordan Rose2da0d1c2013-01-30 21:41:07 +00001110 return;
Chandler Carrutha3028852011-10-15 23:43:53 +00001111
1112 // Rewind from the current position to the start of the line.
1113 const char *TokPtr = BufStart+FileOffset;
1114 const char *LineStart = TokPtr-ColNo+1; // Column # is 1-based.
1115
Chandler Carrutha3028852011-10-15 23:43:53 +00001116 // Compute the line end. Scan forward from the error position to the end of
1117 // the line.
1118 const char *LineEnd = TokPtr;
Nico Weber35131222012-04-26 21:39:46 +00001119 while (*LineEnd != '\n' && *LineEnd != '\r' && *LineEnd != '\0')
Chandler Carrutha3028852011-10-15 23:43:53 +00001120 ++LineEnd;
1121
Jordan Rose2da0d1c2013-01-30 21:41:07 +00001122 // Arbitrarily stop showing snippets when the line is too long.
Benjamin Kramerd408de62013-04-23 14:42:47 +00001123 if (size_t(LineEnd - LineStart) > MaxLineLengthToPrint)
Jordan Rose2da0d1c2013-01-30 21:41:07 +00001124 return;
1125
Chandler Carrutha3028852011-10-15 23:43:53 +00001126 // Copy the line of code into an std::string for ease of manipulation.
1127 std::string SourceLine(LineStart, LineEnd);
1128
1129 // Create a line for the caret that is filled with spaces that is the same
1130 // length as the line of source code.
1131 std::string CaretLine(LineEnd-LineStart, ' ');
1132
Douglas Gregor811db4e2012-10-23 22:26:28 +00001133 const SourceColumnMap sourceColMap(SourceLine, DiagOpts->TabStop);
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001134
Chandler Carrutha3028852011-10-15 23:43:53 +00001135 // Highlight all of the characters covered by Ranges with ~ characters.
1136 for (SmallVectorImpl<CharSourceRange>::iterator I = Ranges.begin(),
1137 E = Ranges.end();
1138 I != E; ++I)
Benjamin Kramer2a812282012-12-01 20:58:01 +00001139 highlightRange(*I, LineNo, FID, sourceColMap, CaretLine, SM, LangOpts);
Chandler Carrutha3028852011-10-15 23:43:53 +00001140
1141 // Next, insert the caret itself.
Richard Smithfab4b1a2012-09-13 18:37:50 +00001142 ColNo = sourceColMap.byteToContainingColumn(ColNo-1);
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001143 if (CaretLine.size()<ColNo+1)
1144 CaretLine.resize(ColNo+1, ' ');
1145 CaretLine[ColNo] = '^';
Chandler Carrutha3028852011-10-15 23:43:53 +00001146
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001147 std::string FixItInsertionLine = buildFixItInsertionLine(LineNo,
1148 sourceColMap,
Benjamin Kramer2a812282012-12-01 20:58:01 +00001149 Hints, SM,
1150 DiagOpts.getPtr());
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001151
1152 // If the source line is too long for our terminal, select only the
1153 // "interesting" source region within that line.
Douglas Gregor811db4e2012-10-23 22:26:28 +00001154 unsigned Columns = DiagOpts->MessageLength;
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001155 if (Columns)
1156 selectInterestingSourceRegion(SourceLine, CaretLine, FixItInsertionLine,
1157 Columns, sourceColMap);
Chandler Carrutha3028852011-10-15 23:43:53 +00001158
1159 // If we are in -fdiagnostics-print-source-range-info mode, we are trying
1160 // to produce easily machine parsable output. Add a space before the
1161 // source line and the caret to make it trivial to tell the main diagnostic
1162 // line from what the user is intended to see.
Douglas Gregor811db4e2012-10-23 22:26:28 +00001163 if (DiagOpts->ShowSourceRanges) {
Chandler Carrutha3028852011-10-15 23:43:53 +00001164 SourceLine = ' ' + SourceLine;
1165 CaretLine = ' ' + CaretLine;
1166 }
1167
Chandler Carrutha3028852011-10-15 23:43:53 +00001168 // Finally, remove any blank spaces from the end of CaretLine.
1169 while (CaretLine[CaretLine.size()-1] == ' ')
1170 CaretLine.erase(CaretLine.end()-1);
1171
1172 // Emit what we have computed.
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001173 emitSnippet(SourceLine);
Chandler Carrutha3028852011-10-15 23:43:53 +00001174
Douglas Gregor811db4e2012-10-23 22:26:28 +00001175 if (DiagOpts->ShowColors)
Chandler Carrutha3028852011-10-15 23:43:53 +00001176 OS.changeColor(caretColor, true);
1177 OS << CaretLine << '\n';
Douglas Gregor811db4e2012-10-23 22:26:28 +00001178 if (DiagOpts->ShowColors)
Chandler Carrutha3028852011-10-15 23:43:53 +00001179 OS.resetColor();
1180
1181 if (!FixItInsertionLine.empty()) {
Douglas Gregor811db4e2012-10-23 22:26:28 +00001182 if (DiagOpts->ShowColors)
Chandler Carrutha3028852011-10-15 23:43:53 +00001183 // Print fixit line in color
1184 OS.changeColor(fixitColor, false);
Douglas Gregor811db4e2012-10-23 22:26:28 +00001185 if (DiagOpts->ShowSourceRanges)
Chandler Carrutha3028852011-10-15 23:43:53 +00001186 OS << ' ';
1187 OS << FixItInsertionLine << '\n';
Douglas Gregor811db4e2012-10-23 22:26:28 +00001188 if (DiagOpts->ShowColors)
Chandler Carrutha3028852011-10-15 23:43:53 +00001189 OS.resetColor();
1190 }
1191
1192 // Print out any parseable fixit information requested by the options.
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +00001193 emitParseableFixits(Hints, SM);
Chandler Carrutha3028852011-10-15 23:43:53 +00001194}
1195
Benjamin Kramer556ab5e2012-05-01 14:34:11 +00001196void TextDiagnostic::emitSnippet(StringRef line) {
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001197 if (line.empty())
1198 return;
1199
1200 size_t i = 0;
1201
1202 std::string to_print;
1203 bool print_reversed = false;
1204
1205 while (i<line.size()) {
1206 std::pair<SmallString<16>,bool> res
Douglas Gregor811db4e2012-10-23 22:26:28 +00001207 = printableTextForNextCharacter(line, &i, DiagOpts->TabStop);
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001208 bool was_printable = res.second;
1209
Douglas Gregor811db4e2012-10-23 22:26:28 +00001210 if (DiagOpts->ShowColors && was_printable == print_reversed) {
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001211 if (print_reversed)
1212 OS.reverseColor();
1213 OS << to_print;
1214 to_print.clear();
Douglas Gregor811db4e2012-10-23 22:26:28 +00001215 if (DiagOpts->ShowColors)
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001216 OS.resetColor();
1217 }
1218
1219 print_reversed = !was_printable;
1220 to_print += res.first.str();
1221 }
1222
Douglas Gregor811db4e2012-10-23 22:26:28 +00001223 if (print_reversed && DiagOpts->ShowColors)
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001224 OS.reverseColor();
1225 OS << to_print;
Douglas Gregor811db4e2012-10-23 22:26:28 +00001226 if (print_reversed && DiagOpts->ShowColors)
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001227 OS.resetColor();
1228
1229 OS << '\n';
1230}
1231
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +00001232void TextDiagnostic::emitParseableFixits(ArrayRef<FixItHint> Hints,
1233 const SourceManager &SM) {
Douglas Gregor811db4e2012-10-23 22:26:28 +00001234 if (!DiagOpts->ShowParseableFixits)
Chandler Carrutha3028852011-10-15 23:43:53 +00001235 return;
1236
1237 // We follow FixItRewriter's example in not (yet) handling
1238 // fix-its in macros.
1239 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1240 I != E; ++I) {
1241 if (I->RemoveRange.isInvalid() ||
1242 I->RemoveRange.getBegin().isMacroID() ||
1243 I->RemoveRange.getEnd().isMacroID())
1244 return;
1245 }
1246
1247 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1248 I != E; ++I) {
1249 SourceLocation BLoc = I->RemoveRange.getBegin();
1250 SourceLocation ELoc = I->RemoveRange.getEnd();
1251
1252 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(BLoc);
1253 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(ELoc);
1254
1255 // Adjust for token ranges.
1256 if (I->RemoveRange.isTokenRange())
1257 EInfo.second += Lexer::MeasureTokenLength(ELoc, SM, LangOpts);
1258
1259 // We specifically do not do word-wrapping or tab-expansion here,
1260 // because this is supposed to be easy to parse.
1261 PresumedLoc PLoc = SM.getPresumedLoc(BLoc);
1262 if (PLoc.isInvalid())
1263 break;
1264
1265 OS << "fix-it:\"";
1266 OS.write_escaped(PLoc.getFilename());
1267 OS << "\":{" << SM.getLineNumber(BInfo.first, BInfo.second)
1268 << ':' << SM.getColumnNumber(BInfo.first, BInfo.second)
1269 << '-' << SM.getLineNumber(EInfo.first, EInfo.second)
1270 << ':' << SM.getColumnNumber(EInfo.first, EInfo.second)
1271 << "}:\"";
1272 OS.write_escaped(I->CodeToInsert);
1273 OS << "\"\n";
1274 }
1275}