blob: 8b7332dbeb5cfec77d6ff557b2888877398873c1 [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"
11#include "clang/Basic/FileManager.h"
12#include "clang/Basic/SourceManager.h"
Seth Cantrell99e2fa82012-04-18 02:44:46 +000013#include "clang/Basic/ConvertUTF.h"
Chandler Carrutha3028852011-10-15 23:43:53 +000014#include "clang/Frontend/DiagnosticOptions.h"
15#include "clang/Lex/Lexer.h"
16#include "llvm/Support/MemoryBuffer.h"
17#include "llvm/Support/raw_ostream.h"
18#include "llvm/Support/ErrorHandling.h"
Seth Cantrell99e2fa82012-04-18 02:44:46 +000019#include "llvm/Support/Locale.h"
Chandler Carrutha3028852011-10-15 23:43:53 +000020#include "llvm/ADT/SmallString.h"
Seth Cantrell99e2fa82012-04-18 02:44:46 +000021#include "llvm/ADT/StringExtras.h"
Chandler Carrutha3028852011-10-15 23:43:53 +000022#include <algorithm>
Seth Cantrell99e2fa82012-04-18 02:44:46 +000023
Chandler Carrutha3028852011-10-15 23:43:53 +000024using namespace clang;
25
26static const enum raw_ostream::Colors noteColor =
27 raw_ostream::BLACK;
28static const enum raw_ostream::Colors fixitColor =
29 raw_ostream::GREEN;
30static const enum raw_ostream::Colors caretColor =
31 raw_ostream::GREEN;
32static const enum raw_ostream::Colors warningColor =
33 raw_ostream::MAGENTA;
Richard Trieu91844232012-06-26 18:18:47 +000034static const enum raw_ostream::Colors templateColor =
35 raw_ostream::CYAN;
Chandler Carrutha3028852011-10-15 23:43:53 +000036static const enum raw_ostream::Colors errorColor = raw_ostream::RED;
37static const enum raw_ostream::Colors fatalColor = raw_ostream::RED;
38// Used for changing only the bold attribute.
39static const enum raw_ostream::Colors savedColor =
40 raw_ostream::SAVEDCOLOR;
41
Richard Trieu91844232012-06-26 18:18:47 +000042/// \brief Add highlights to differences in template strings.
43static void applyTemplateHighlighting(raw_ostream &OS, StringRef Str,
44 bool &Normal) {
45 for (unsigned i = 0, e = Str.size(); i < e; ++i)
46 if (Str[i] != ToggleHighlight) {
47 OS << Str[i];
48 } else {
49 if (Normal)
50 OS.changeColor(templateColor, true);
51 else
52 OS.resetColor();
53 Normal = !Normal;
54 }
55}
56
Chandler Carrutha3028852011-10-15 23:43:53 +000057/// \brief Number of spaces to indent when word-wrapping.
58const unsigned WordWrapIndentation = 6;
59
Benjamin Kramer556ab5e2012-05-01 14:34:11 +000060static int bytesSincePreviousTabOrLineBegin(StringRef SourceLine, size_t i) {
Seth Cantrell99e2fa82012-04-18 02:44:46 +000061 int bytes = 0;
62 while (0<i) {
63 if (SourceLine[--i]=='\t')
64 break;
65 ++bytes;
66 }
67 return bytes;
68}
69
70/// \brief returns a printable representation of first item from input range
71///
72/// This function returns a printable representation of the next item in a line
73/// of source. If the next byte begins a valid and printable character, that
74/// character is returned along with 'true'.
75///
76/// Otherwise, if the next byte begins a valid, but unprintable character, a
77/// printable, escaped representation of the character is returned, along with
78/// 'false'. Otherwise a printable, escaped representation of the next byte
79/// is returned along with 'false'.
80///
81/// \note The index is updated to be used with a subsequent call to
82/// printableTextForNextCharacter.
83///
84/// \param SourceLine The line of source
85/// \param i Pointer to byte index,
86/// \param TabStop used to expand tabs
87/// \return pair(printable text, 'true' iff original text was printable)
88///
Benjamin Kramer556ab5e2012-05-01 14:34:11 +000089static std::pair<SmallString<16>, bool>
Seth Cantrell99e2fa82012-04-18 02:44:46 +000090printableTextForNextCharacter(StringRef SourceLine, size_t *i,
91 unsigned TabStop) {
92 assert(i && "i must not be null");
93 assert(*i<SourceLine.size() && "must point to a valid index");
94
95 if (SourceLine[*i]=='\t') {
96 assert(0 < TabStop && TabStop <= DiagnosticOptions::MaxTabStop &&
97 "Invalid -ftabstop value");
98 unsigned col = bytesSincePreviousTabOrLineBegin(SourceLine, *i);
99 unsigned NumSpaces = TabStop - col%TabStop;
100 assert(0 < NumSpaces && NumSpaces <= TabStop
101 && "Invalid computation of space amt");
102 ++(*i);
103
104 SmallString<16> expandedTab;
105 expandedTab.assign(NumSpaces, ' ');
106 return std::make_pair(expandedTab, true);
107 }
108
109 // FIXME: this data is copied from the private implementation of ConvertUTF.h
110 static const char trailingBytesForUTF8[256] = {
111 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
112 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
113 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
114 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
115 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
116 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
117 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
118 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5
119 };
120
121 unsigned char const *begin, *end;
122 begin = reinterpret_cast<unsigned char const *>(&*(SourceLine.begin() + *i));
123 end = begin + SourceLine.size();
124
125 if (isLegalUTF8Sequence(begin, end)) {
126 UTF32 c;
127 UTF32 *cptr = &c;
128 unsigned char const *original_begin = begin;
129 char trailingBytes = trailingBytesForUTF8[(unsigned char)SourceLine[*i]];
130 unsigned char const *cp_end = begin+trailingBytes+1;
131
132 ConversionResult res = ConvertUTF8toUTF32(&begin, cp_end, &cptr, cptr+1,
133 strictConversion);
Matt Beaumont-Gay69e227b2012-04-18 17:25:16 +0000134 (void)res;
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000135 assert(conversionOK==res);
136 assert(0 < begin-original_begin
137 && "we must be further along in the string now");
138 *i += begin-original_begin;
139
140 if (!llvm::sys::locale::isPrint(c)) {
141 // If next character is valid UTF-8, but not printable
142 SmallString<16> expandedCP("<U+>");
143 while (c) {
144 expandedCP.insert(expandedCP.begin()+3, llvm::hexdigit(c%16));
145 c/=16;
146 }
147 while (expandedCP.size() < 8)
148 expandedCP.insert(expandedCP.begin()+3, llvm::hexdigit(0));
149 return std::make_pair(expandedCP, false);
150 }
151
152 // If next character is valid UTF-8, and printable
153 return std::make_pair(SmallString<16>(original_begin, cp_end), true);
154
155 }
156
157 // If next byte is not valid UTF-8 (and therefore not printable)
158 SmallString<16> expandedByte("<XX>");
159 unsigned char byte = SourceLine[*i];
160 expandedByte[1] = llvm::hexdigit(byte / 16);
161 expandedByte[2] = llvm::hexdigit(byte % 16);
162 ++(*i);
163 return std::make_pair(expandedByte, false);
164}
165
Benjamin Kramer556ab5e2012-05-01 14:34:11 +0000166static void expandTabs(std::string &SourceLine, unsigned TabStop) {
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000167 size_t i = SourceLine.size();
168 while (i>0) {
169 i--;
170 if (SourceLine[i]!='\t')
171 continue;
172 size_t tmp_i = i;
173 std::pair<SmallString<16>,bool> res
174 = printableTextForNextCharacter(SourceLine, &tmp_i, TabStop);
175 SourceLine.replace(i, 1, res.first.c_str());
176 }
177}
178
179/// This function takes a raw source line and produces a mapping from the bytes
180/// of the printable representation of the line to the columns those printable
181/// characters will appear at (numbering the first column as 0).
182///
183/// If a byte 'i' corresponds to muliple columns (e.g. the byte contains a tab
184/// character) then the the array will map that byte to the first column the
185/// tab appears at and the next value in the map will have been incremented
186/// more than once.
187///
188/// If a byte is the first in a sequence of bytes that together map to a single
189/// entity in the output, then the array will map that byte to the appropriate
190/// column while the subsequent bytes will be -1.
191///
192/// The last element in the array does not correspond to any byte in the input
193/// and instead is the number of columns needed to display the source
194///
195/// example: (given a tabstop of 8)
196///
197/// "a \t \u3042" -> {0,1,2,8,9,-1,-1,11}
198///
James Dennettf347d932012-06-22 05:33:23 +0000199/// (\\u3042 is represented in UTF-8 by three bytes and takes two columns to
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000200/// display)
Benjamin Kramer556ab5e2012-05-01 14:34:11 +0000201static void byteToColumn(StringRef SourceLine, unsigned TabStop,
202 SmallVectorImpl<int> &out) {
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000203 out.clear();
204
205 if (SourceLine.empty()) {
206 out.resize(1u,0);
207 return;
208 }
209
210 out.resize(SourceLine.size()+1, -1);
211
212 int columns = 0;
213 size_t i = 0;
214 while (i<SourceLine.size()) {
215 out[i] = columns;
216 std::pair<SmallString<16>,bool> res
217 = printableTextForNextCharacter(SourceLine, &i, TabStop);
218 columns += llvm::sys::locale::columnWidth(res.first);
219 }
220 out.back() = columns;
221}
222
223/// This function takes a raw source line and produces a mapping from columns
224/// to the byte of the source line that produced the character displaying at
225/// that column. This is the inverse of the mapping produced by byteToColumn()
226///
227/// The last element in the array is the number of bytes in the source string
228///
229/// example: (given a tabstop of 8)
230///
231/// "a \t \u3042" -> {0,1,2,-1,-1,-1,-1,-1,3,4,-1,7}
232///
James Dennettf347d932012-06-22 05:33:23 +0000233/// (\\u3042 is represented in UTF-8 by three bytes and takes two columns to
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000234/// display)
Benjamin Kramer556ab5e2012-05-01 14:34:11 +0000235static void columnToByte(StringRef SourceLine, unsigned TabStop,
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000236 SmallVectorImpl<int> &out) {
237 out.clear();
238
239 if (SourceLine.empty()) {
240 out.resize(1u, 0);
241 return;
242 }
243
244 int columns = 0;
245 size_t i = 0;
246 while (i<SourceLine.size()) {
247 out.resize(columns+1, -1);
248 out.back() = i;
249 std::pair<SmallString<16>,bool> res
250 = printableTextForNextCharacter(SourceLine, &i, TabStop);
251 columns += llvm::sys::locale::columnWidth(res.first);
252 }
253 out.resize(columns+1, -1);
254 out.back() = i;
255}
256
257struct SourceColumnMap {
258 SourceColumnMap(StringRef SourceLine, unsigned TabStop)
259 : m_SourceLine(SourceLine) {
260
261 ::byteToColumn(SourceLine, TabStop, m_byteToColumn);
262 ::columnToByte(SourceLine, TabStop, m_columnToByte);
263
264 assert(m_byteToColumn.size()==SourceLine.size()+1);
265 assert(0 < m_byteToColumn.size() && 0 < m_columnToByte.size());
266 assert(m_byteToColumn.size()
267 == static_cast<unsigned>(m_columnToByte.back()+1));
268 assert(static_cast<unsigned>(m_byteToColumn.back()+1)
269 == m_columnToByte.size());
270 }
271 int columns() const { return m_byteToColumn.back(); }
272 int bytes() const { return m_columnToByte.back(); }
273 int byteToColumn(int n) const {
274 assert(0<=n && n<static_cast<int>(m_byteToColumn.size()));
275 return m_byteToColumn[n];
276 }
277 int columnToByte(int n) const {
278 assert(0<=n && n<static_cast<int>(m_columnToByte.size()));
279 return m_columnToByte[n];
280 }
281 StringRef getSourceLine() const {
282 return m_SourceLine;
283 }
284
285private:
286 const std::string m_SourceLine;
287 SmallVector<int,200> m_byteToColumn;
288 SmallVector<int,200> m_columnToByte;
289};
290
291// used in assert in selectInterestingSourceRegion()
292namespace {
293struct char_out_of_range {
294 const char lower,upper;
295 char_out_of_range(char lower, char upper) :
296 lower(lower), upper(upper) {}
297 bool operator()(char c) { return c < lower || upper < c; }
298};
299}
300
Chandler Carrutha3028852011-10-15 23:43:53 +0000301/// \brief When the source code line we want to print is too long for
302/// the terminal, select the "interesting" region.
Chandler Carruthab4c1da2011-10-15 23:54:09 +0000303static void selectInterestingSourceRegion(std::string &SourceLine,
Chandler Carrutha3028852011-10-15 23:43:53 +0000304 std::string &CaretLine,
305 std::string &FixItInsertionLine,
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000306 unsigned Columns,
307 const SourceColumnMap &map) {
308 unsigned MaxColumns = std::max<unsigned>(map.columns(),
309 std::max(CaretLine.size(),
310 FixItInsertionLine.size()));
311 // if the number of columns is less than the desired number we're done
312 if (MaxColumns <= Columns)
313 return;
314
315 // no special characters allowed in CaretLine or FixItInsertionLine
316 assert(CaretLine.end() ==
317 std::find_if(CaretLine.begin(), CaretLine.end(),
318 char_out_of_range(' ','~')));
319 assert(FixItInsertionLine.end() ==
320 std::find_if(FixItInsertionLine.begin(), FixItInsertionLine.end(),
321 char_out_of_range(' ','~')));
322
Chandler Carrutha3028852011-10-15 23:43:53 +0000323 // Find the slice that we need to display the full caret line
324 // correctly.
325 unsigned CaretStart = 0, CaretEnd = CaretLine.size();
326 for (; CaretStart != CaretEnd; ++CaretStart)
Seth Cantrell14340ca2012-05-25 00:03:29 +0000327 if (!isspace(static_cast<unsigned char>(CaretLine[CaretStart])))
Chandler Carrutha3028852011-10-15 23:43:53 +0000328 break;
329
330 for (; CaretEnd != CaretStart; --CaretEnd)
Seth Cantrell14340ca2012-05-25 00:03:29 +0000331 if (!isspace(static_cast<unsigned char>(CaretLine[CaretEnd - 1])))
Chandler Carrutha3028852011-10-15 23:43:53 +0000332 break;
333
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000334 // caret has already been inserted into CaretLine so the above whitespace
335 // check is guaranteed to include the caret
Chandler Carrutha3028852011-10-15 23:43:53 +0000336
337 // If we have a fix-it line, make sure the slice includes all of the
338 // fix-it information.
339 if (!FixItInsertionLine.empty()) {
340 unsigned FixItStart = 0, FixItEnd = FixItInsertionLine.size();
341 for (; FixItStart != FixItEnd; ++FixItStart)
Seth Cantrell14340ca2012-05-25 00:03:29 +0000342 if (!isspace(static_cast<unsigned char>(FixItInsertionLine[FixItStart])))
Chandler Carrutha3028852011-10-15 23:43:53 +0000343 break;
344
345 for (; FixItEnd != FixItStart; --FixItEnd)
Seth Cantrell14340ca2012-05-25 00:03:29 +0000346 if (!isspace(static_cast<unsigned char>(FixItInsertionLine[FixItEnd - 1])))
Chandler Carrutha3028852011-10-15 23:43:53 +0000347 break;
348
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000349 CaretStart = std::min(FixItStart, CaretStart);
350 CaretEnd = std::max(FixItEnd, CaretEnd);
Chandler Carrutha3028852011-10-15 23:43:53 +0000351 }
352
Seth Cantrellac6fb8f2012-05-24 05:14:44 +0000353 // CaretEnd may have been set at the middle of a character
354 // If it's not at a character's first column then advance it past the current
355 // character.
356 while (static_cast<int>(CaretEnd) < map.columns() &&
357 -1 == map.columnToByte(CaretEnd))
358 ++CaretEnd;
359
360 assert((static_cast<int>(CaretStart) > map.columns() ||
361 -1!=map.columnToByte(CaretStart)) &&
362 "CaretStart must not point to a column in the middle of a source"
363 " line character");
364 assert((static_cast<int>(CaretEnd) > map.columns() ||
365 -1!=map.columnToByte(CaretEnd)) &&
366 "CaretEnd must not point to a column in the middle of a source line"
367 " character");
368
Chandler Carrutha3028852011-10-15 23:43:53 +0000369 // CaretLine[CaretStart, CaretEnd) contains all of the interesting
370 // parts of the caret line. While this slice is smaller than the
371 // number of columns we have, try to grow the slice to encompass
372 // more context.
373
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000374 unsigned SourceStart = map.columnToByte(std::min<unsigned>(CaretStart,
375 map.columns()));
376 unsigned SourceEnd = map.columnToByte(std::min<unsigned>(CaretEnd,
377 map.columns()));
378
379 unsigned CaretColumnsOutsideSource = CaretEnd-CaretStart
380 - (map.byteToColumn(SourceEnd)-map.byteToColumn(SourceStart));
381
382 char const *front_ellipse = " ...";
383 char const *front_space = " ";
384 char const *back_ellipse = "...";
385 unsigned ellipses_space = strlen(front_ellipse) + strlen(back_ellipse);
Chandler Carrutha3028852011-10-15 23:43:53 +0000386
387 unsigned TargetColumns = Columns;
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000388 // Give us extra room for the ellipses
389 // and any of the caret line that extends past the source
390 if (TargetColumns > ellipses_space+CaretColumnsOutsideSource)
391 TargetColumns -= ellipses_space+CaretColumnsOutsideSource;
392
393 while (SourceStart>0 || SourceEnd<SourceLine.size()) {
Chandler Carrutha3028852011-10-15 23:43:53 +0000394 bool ExpandedRegion = false;
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000395
396 if (SourceStart>0) {
397 unsigned NewStart = SourceStart-1;
Chandler Carrutha3028852011-10-15 23:43:53 +0000398
399 // Skip over any whitespace we see here; we're looking for
400 // another bit of interesting text.
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000401 while (NewStart &&
Seth Cantrell14340ca2012-05-25 00:03:29 +0000402 (map.byteToColumn(NewStart)==-1 ||
403 isspace(static_cast<unsigned char>(SourceLine[NewStart]))))
Chandler Carrutha3028852011-10-15 23:43:53 +0000404 --NewStart;
405
406 // Skip over this bit of "interesting" text.
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000407 while (NewStart &&
Seth Cantrell14340ca2012-05-25 00:03:29 +0000408 (map.byteToColumn(NewStart)!=-1 &&
409 !isspace(static_cast<unsigned char>(SourceLine[NewStart]))))
Chandler Carrutha3028852011-10-15 23:43:53 +0000410 --NewStart;
411
412 // Move up to the non-whitespace character we just saw.
413 if (NewStart)
414 ++NewStart;
415
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000416 unsigned NewColumns = map.byteToColumn(SourceEnd) -
417 map.byteToColumn(NewStart);
418 if (NewColumns <= TargetColumns) {
419 SourceStart = NewStart;
Chandler Carrutha3028852011-10-15 23:43:53 +0000420 ExpandedRegion = true;
421 }
422 }
423
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000424 if (SourceEnd<SourceLine.size()) {
425 unsigned NewEnd = SourceEnd+1;
Chandler Carrutha3028852011-10-15 23:43:53 +0000426
427 // Skip over any whitespace we see here; we're looking for
428 // another bit of interesting text.
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000429 while (NewEnd<SourceLine.size() &&
Seth Cantrell14340ca2012-05-25 00:03:29 +0000430 (map.byteToColumn(NewEnd)==-1 ||
431 isspace(static_cast<unsigned char>(SourceLine[NewEnd]))))
Chandler Carrutha3028852011-10-15 23:43:53 +0000432 ++NewEnd;
433
434 // Skip over this bit of "interesting" text.
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000435 while (NewEnd<SourceLine.size() &&
Seth Cantrell14340ca2012-05-25 00:03:29 +0000436 (map.byteToColumn(NewEnd)!=-1 &&
437 !isspace(static_cast<unsigned char>(SourceLine[NewEnd]))))
Chandler Carrutha3028852011-10-15 23:43:53 +0000438 ++NewEnd;
439
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000440 unsigned NewColumns = map.byteToColumn(NewEnd) -
441 map.byteToColumn(SourceStart);
442 if (NewColumns <= TargetColumns) {
443 SourceEnd = NewEnd;
Chandler Carrutha3028852011-10-15 23:43:53 +0000444 ExpandedRegion = true;
445 }
446 }
447
448 if (!ExpandedRegion)
449 break;
450 }
451
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000452 CaretStart = map.byteToColumn(SourceStart);
453 CaretEnd = map.byteToColumn(SourceEnd) + CaretColumnsOutsideSource;
454
Chandler Carrutha3028852011-10-15 23:43:53 +0000455 // [CaretStart, CaretEnd) is the slice we want. Update the various
456 // output lines to show only this slice, with two-space padding
457 // before the lines so that it looks nicer.
Chandler Carrutha3028852011-10-15 23:43:53 +0000458
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000459 assert(CaretStart!=(unsigned)-1 && CaretEnd!=(unsigned)-1 &&
460 SourceStart!=(unsigned)-1 && SourceEnd!=(unsigned)-1);
461 assert(SourceStart <= SourceEnd);
462 assert(CaretStart <= CaretEnd);
463
464 unsigned BackColumnsRemoved
465 = map.byteToColumn(SourceLine.size())-map.byteToColumn(SourceEnd);
466 unsigned FrontColumnsRemoved = CaretStart;
467 unsigned ColumnsKept = CaretEnd-CaretStart;
468
469 // We checked up front that the line needed truncation
470 assert(FrontColumnsRemoved+ColumnsKept+BackColumnsRemoved > Columns);
471
472 // The line needs some trunctiona, and we'd prefer to keep the front
473 // if possible, so remove the back
474 if (BackColumnsRemoved)
475 SourceLine.replace(SourceEnd, std::string::npos, back_ellipse);
476
477 // If that's enough then we're done
478 if (FrontColumnsRemoved+ColumnsKept <= Columns)
479 return;
480
481 // Otherwise remove the front as well
482 if (FrontColumnsRemoved) {
483 SourceLine.replace(0, SourceStart, front_ellipse);
484 CaretLine.replace(0, CaretStart, front_space);
485 if (!FixItInsertionLine.empty())
486 FixItInsertionLine.replace(0, CaretStart, front_space);
Chandler Carrutha3028852011-10-15 23:43:53 +0000487 }
488}
489
Chandler Carrutha3028852011-10-15 23:43:53 +0000490/// \brief Skip over whitespace in the string, starting at the given
491/// index.
492///
493/// \returns The index of the first non-whitespace character that is
494/// greater than or equal to Idx or, if no such character exists,
495/// returns the end of the string.
496static unsigned skipWhitespace(unsigned Idx, StringRef Str, unsigned Length) {
497 while (Idx < Length && isspace(Str[Idx]))
498 ++Idx;
499 return Idx;
500}
501
502/// \brief If the given character is the start of some kind of
503/// balanced punctuation (e.g., quotes or parentheses), return the
504/// character that will terminate the punctuation.
505///
506/// \returns The ending punctuation character, if any, or the NULL
507/// character if the input character does not start any punctuation.
508static inline char findMatchingPunctuation(char c) {
509 switch (c) {
510 case '\'': return '\'';
511 case '`': return '\'';
512 case '"': return '"';
513 case '(': return ')';
514 case '[': return ']';
515 case '{': return '}';
516 default: break;
517 }
518
519 return 0;
520}
521
522/// \brief Find the end of the word starting at the given offset
523/// within a string.
524///
525/// \returns the index pointing one character past the end of the
526/// word.
527static unsigned findEndOfWord(unsigned Start, StringRef Str,
528 unsigned Length, unsigned Column,
529 unsigned Columns) {
530 assert(Start < Str.size() && "Invalid start position!");
531 unsigned End = Start + 1;
532
533 // If we are already at the end of the string, take that as the word.
534 if (End == Str.size())
535 return End;
536
537 // Determine if the start of the string is actually opening
538 // punctuation, e.g., a quote or parentheses.
539 char EndPunct = findMatchingPunctuation(Str[Start]);
540 if (!EndPunct) {
541 // This is a normal word. Just find the first space character.
542 while (End < Length && !isspace(Str[End]))
543 ++End;
544 return End;
545 }
546
547 // We have the start of a balanced punctuation sequence (quotes,
548 // parentheses, etc.). Determine the full sequence is.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000549 SmallString<16> PunctuationEndStack;
Chandler Carrutha3028852011-10-15 23:43:53 +0000550 PunctuationEndStack.push_back(EndPunct);
551 while (End < Length && !PunctuationEndStack.empty()) {
552 if (Str[End] == PunctuationEndStack.back())
553 PunctuationEndStack.pop_back();
554 else if (char SubEndPunct = findMatchingPunctuation(Str[End]))
555 PunctuationEndStack.push_back(SubEndPunct);
556
557 ++End;
558 }
559
560 // Find the first space character after the punctuation ended.
561 while (End < Length && !isspace(Str[End]))
562 ++End;
563
564 unsigned PunctWordLength = End - Start;
565 if (// If the word fits on this line
566 Column + PunctWordLength <= Columns ||
567 // ... or the word is "short enough" to take up the next line
568 // without too much ugly white space
569 PunctWordLength < Columns/3)
570 return End; // Take the whole thing as a single "word".
571
572 // The whole quoted/parenthesized string is too long to print as a
573 // single "word". Instead, find the "word" that starts just after
574 // the punctuation and use that end-point instead. This will recurse
575 // until it finds something small enough to consider a word.
576 return findEndOfWord(Start + 1, Str, Length, Column + 1, Columns);
577}
578
579/// \brief Print the given string to a stream, word-wrapping it to
580/// some number of columns in the process.
581///
582/// \param OS the stream to which the word-wrapping string will be
583/// emitted.
584/// \param Str the string to word-wrap and output.
585/// \param Columns the number of columns to word-wrap to.
586/// \param Column the column number at which the first character of \p
587/// Str will be printed. This will be non-zero when part of the first
588/// line has already been printed.
589/// \param Indentation the number of spaces to indent any lines beyond
590/// the first line.
591/// \returns true if word-wrapping was required, or false if the
592/// string fit on the first line.
593static bool printWordWrapped(raw_ostream &OS, StringRef Str,
594 unsigned Columns,
595 unsigned Column = 0,
596 unsigned Indentation = WordWrapIndentation) {
597 const unsigned Length = std::min(Str.find('\n'), Str.size());
Richard Trieu91844232012-06-26 18:18:47 +0000598 bool TextNormal = true;
Chandler Carrutha3028852011-10-15 23:43:53 +0000599
600 // The string used to indent each line.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000601 SmallString<16> IndentStr;
Chandler Carrutha3028852011-10-15 23:43:53 +0000602 IndentStr.assign(Indentation, ' ');
603 bool Wrapped = false;
604 for (unsigned WordStart = 0, WordEnd; WordStart < Length;
605 WordStart = WordEnd) {
606 // Find the beginning of the next word.
607 WordStart = skipWhitespace(WordStart, Str, Length);
608 if (WordStart == Length)
609 break;
610
611 // Find the end of this word.
612 WordEnd = findEndOfWord(WordStart, Str, Length, Column, Columns);
613
614 // Does this word fit on the current line?
615 unsigned WordLength = WordEnd - WordStart;
616 if (Column + WordLength < Columns) {
617 // This word fits on the current line; print it there.
618 if (WordStart) {
619 OS << ' ';
620 Column += 1;
621 }
Richard Trieu91844232012-06-26 18:18:47 +0000622 applyTemplateHighlighting(OS, Str.substr(WordStart, WordLength),
623 TextNormal);
Chandler Carrutha3028852011-10-15 23:43:53 +0000624 Column += WordLength;
625 continue;
626 }
627
628 // This word does not fit on the current line, so wrap to the next
629 // line.
630 OS << '\n';
631 OS.write(&IndentStr[0], Indentation);
Richard Trieu91844232012-06-26 18:18:47 +0000632 applyTemplateHighlighting(OS, Str.substr(WordStart, WordLength),
633 TextNormal);
Chandler Carrutha3028852011-10-15 23:43:53 +0000634 Column = Indentation + WordLength;
635 Wrapped = true;
636 }
637
638 // Append any remaning text from the message with its existing formatting.
Richard Trieu91844232012-06-26 18:18:47 +0000639 applyTemplateHighlighting(OS, Str.substr(Length), TextNormal);
640
641 assert(TextNormal && "Text highlighted at end of diagnostic message.");
Chandler Carrutha3028852011-10-15 23:43:53 +0000642
643 return Wrapped;
644}
645
646TextDiagnostic::TextDiagnostic(raw_ostream &OS,
Chandler Carrutha3028852011-10-15 23:43:53 +0000647 const LangOptions &LangOpts,
Chandler Carruth3eb8b542011-10-16 02:57:39 +0000648 const DiagnosticOptions &DiagOpts)
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +0000649 : DiagnosticRenderer(LangOpts, DiagOpts), OS(OS) {}
Chandler Carrutha3028852011-10-15 23:43:53 +0000650
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000651TextDiagnostic::~TextDiagnostic() {}
Chandler Carrutha3028852011-10-15 23:43:53 +0000652
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000653void
654TextDiagnostic::emitDiagnosticMessage(SourceLocation Loc,
655 PresumedLoc PLoc,
656 DiagnosticsEngine::Level Level,
657 StringRef Message,
658 ArrayRef<clang::CharSourceRange> Ranges,
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +0000659 const SourceManager *SM,
Ted Kremenek0964cca2012-02-14 02:46:00 +0000660 DiagOrStoredDiag D) {
Chandler Carrutha3028852011-10-15 23:43:53 +0000661 uint64_t StartOfLocationInfo = OS.tell();
662
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000663 // Emit the location of this particular diagnostic.
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +0000664 if (Loc.isValid())
665 emitDiagnosticLoc(Loc, PLoc, Level, Ranges, *SM);
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000666
Chandler Carrutha3028852011-10-15 23:43:53 +0000667 if (DiagOpts.ShowColors)
668 OS.resetColor();
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000669
Chandler Carrutha3028852011-10-15 23:43:53 +0000670 printDiagnosticLevel(OS, Level, DiagOpts.ShowColors);
671 printDiagnosticMessage(OS, Level, Message,
672 OS.tell() - StartOfLocationInfo,
673 DiagOpts.MessageLength, DiagOpts.ShowColors);
Chandler Carrutha3028852011-10-15 23:43:53 +0000674}
675
Chandler Carruth07c346d2011-10-15 23:48:02 +0000676/*static*/ void
677TextDiagnostic::printDiagnosticLevel(raw_ostream &OS,
678 DiagnosticsEngine::Level Level,
679 bool ShowColors) {
680 if (ShowColors) {
681 // Print diagnostic category in bold and color
682 switch (Level) {
683 case DiagnosticsEngine::Ignored:
684 llvm_unreachable("Invalid diagnostic type");
685 case DiagnosticsEngine::Note: OS.changeColor(noteColor, true); break;
686 case DiagnosticsEngine::Warning: OS.changeColor(warningColor, true); break;
687 case DiagnosticsEngine::Error: OS.changeColor(errorColor, true); break;
688 case DiagnosticsEngine::Fatal: OS.changeColor(fatalColor, true); break;
689 }
690 }
691
692 switch (Level) {
693 case DiagnosticsEngine::Ignored:
694 llvm_unreachable("Invalid diagnostic type");
695 case DiagnosticsEngine::Note: OS << "note: "; break;
696 case DiagnosticsEngine::Warning: OS << "warning: "; break;
697 case DiagnosticsEngine::Error: OS << "error: "; break;
698 case DiagnosticsEngine::Fatal: OS << "fatal error: "; break;
699 }
700
701 if (ShowColors)
702 OS.resetColor();
703}
704
705/*static*/ void
706TextDiagnostic::printDiagnosticMessage(raw_ostream &OS,
707 DiagnosticsEngine::Level Level,
708 StringRef Message,
709 unsigned CurrentColumn, unsigned Columns,
710 bool ShowColors) {
711 if (ShowColors) {
712 // Print warnings, errors and fatal errors in bold, no color
713 switch (Level) {
714 case DiagnosticsEngine::Warning: OS.changeColor(savedColor, true); break;
715 case DiagnosticsEngine::Error: OS.changeColor(savedColor, true); break;
716 case DiagnosticsEngine::Fatal: OS.changeColor(savedColor, true); break;
717 default: break; //don't bold notes
718 }
719 }
720
721 if (Columns)
722 printWordWrapped(OS, Message, Columns, CurrentColumn);
723 else
724 OS << Message;
725
726 if (ShowColors)
727 OS.resetColor();
728 OS << '\n';
729}
730
Chandler Carruth07c346d2011-10-15 23:48:02 +0000731/// \brief Print out the file/line/column information and include trace.
732///
733/// This method handlen the emission of the diagnostic location information.
734/// This includes extracting as much location information as is present for
735/// the diagnostic and printing it, as well as any include stack or source
736/// ranges necessary.
Chandler Carruthab4c1da2011-10-15 23:54:09 +0000737void TextDiagnostic::emitDiagnosticLoc(SourceLocation Loc, PresumedLoc PLoc,
Chandler Carruth07c346d2011-10-15 23:48:02 +0000738 DiagnosticsEngine::Level Level,
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +0000739 ArrayRef<CharSourceRange> Ranges,
740 const SourceManager &SM) {
Chandler Carruth07c346d2011-10-15 23:48:02 +0000741 if (PLoc.isInvalid()) {
742 // At least print the file name if available:
743 FileID FID = SM.getFileID(Loc);
744 if (!FID.isInvalid()) {
745 const FileEntry* FE = SM.getFileEntryForID(FID);
746 if (FE && FE->getName()) {
747 OS << FE->getName();
748 if (FE->getDevice() == 0 && FE->getInode() == 0
749 && FE->getFileMode() == 0) {
750 // in PCH is a guess, but a good one:
751 OS << " (in PCH)";
752 }
753 OS << ": ";
754 }
755 }
756 return;
757 }
758 unsigned LineNo = PLoc.getLine();
759
760 if (!DiagOpts.ShowLocation)
761 return;
762
763 if (DiagOpts.ShowColors)
764 OS.changeColor(savedColor, true);
765
766 OS << PLoc.getFilename();
767 switch (DiagOpts.Format) {
768 case DiagnosticOptions::Clang: OS << ':' << LineNo; break;
769 case DiagnosticOptions::Msvc: OS << '(' << LineNo; break;
770 case DiagnosticOptions::Vi: OS << " +" << LineNo; break;
771 }
772
773 if (DiagOpts.ShowColumn)
774 // Compute the column number.
775 if (unsigned ColNo = PLoc.getColumn()) {
776 if (DiagOpts.Format == DiagnosticOptions::Msvc) {
777 OS << ',';
778 ColNo--;
779 } else
780 OS << ':';
781 OS << ColNo;
782 }
783 switch (DiagOpts.Format) {
784 case DiagnosticOptions::Clang:
785 case DiagnosticOptions::Vi: OS << ':'; break;
786 case DiagnosticOptions::Msvc: OS << ") : "; break;
787 }
788
789 if (DiagOpts.ShowSourceRanges && !Ranges.empty()) {
790 FileID CaretFileID =
791 SM.getFileID(SM.getExpansionLoc(Loc));
792 bool PrintedRange = false;
793
794 for (ArrayRef<CharSourceRange>::const_iterator RI = Ranges.begin(),
795 RE = Ranges.end();
796 RI != RE; ++RI) {
797 // Ignore invalid ranges.
798 if (!RI->isValid()) continue;
799
800 SourceLocation B = SM.getExpansionLoc(RI->getBegin());
801 SourceLocation E = SM.getExpansionLoc(RI->getEnd());
802
803 // If the End location and the start location are the same and are a
804 // macro location, then the range was something that came from a
805 // macro expansion or _Pragma. If this is an object-like macro, the
806 // best we can do is to highlight the range. If this is a
807 // function-like macro, we'd also like to highlight the arguments.
808 if (B == E && RI->getEnd().isMacroID())
809 E = SM.getExpansionRange(RI->getEnd()).second;
810
811 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(B);
812 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E);
813
814 // If the start or end of the range is in another file, just discard
815 // it.
816 if (BInfo.first != CaretFileID || EInfo.first != CaretFileID)
817 continue;
818
819 // Add in the length of the token, so that we cover multi-char
820 // tokens.
821 unsigned TokSize = 0;
822 if (RI->isTokenRange())
823 TokSize = Lexer::MeasureTokenLength(E, SM, LangOpts);
824
825 OS << '{' << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
826 << SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
827 << SM.getLineNumber(EInfo.first, EInfo.second) << ':'
828 << (SM.getColumnNumber(EInfo.first, EInfo.second)+TokSize)
829 << '}';
830 PrintedRange = true;
831 }
832
833 if (PrintedRange)
834 OS << ':';
835 }
836 OS << ' ';
837}
838
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000839void TextDiagnostic::emitBasicNote(StringRef Message) {
840 // FIXME: Emit this as a real note diagnostic.
841 // FIXME: Format an actual diagnostic rather than a hard coded string.
842 OS << "note: " << Message << "\n";
843}
Chandler Carrutha3028852011-10-15 23:43:53 +0000844
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000845void TextDiagnostic::emitIncludeLocation(SourceLocation Loc,
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +0000846 PresumedLoc PLoc,
847 const SourceManager &SM) {
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000848 if (DiagOpts.ShowLocation)
849 OS << "In file included from " << PLoc.getFilename() << ':'
850 << PLoc.getLine() << ":\n";
851 else
852 OS << "In included file:\n";
Chandler Carrutha3028852011-10-15 23:43:53 +0000853}
854
855/// \brief Emit a code snippet and caret line.
856///
857/// This routine emits a single line's code snippet and caret line..
858///
859/// \param Loc The location for the caret.
860/// \param Ranges The underlined ranges for this code snippet.
861/// \param Hints The FixIt hints active for this diagnostic.
Chandler Carruthab4c1da2011-10-15 23:54:09 +0000862void TextDiagnostic::emitSnippetAndCaret(
Chandler Carruthdc2f2572011-10-16 07:20:28 +0000863 SourceLocation Loc, DiagnosticsEngine::Level Level,
Chandler Carrutha3028852011-10-15 23:43:53 +0000864 SmallVectorImpl<CharSourceRange>& Ranges,
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +0000865 ArrayRef<FixItHint> Hints,
866 const SourceManager &SM) {
Chandler Carrutha3028852011-10-15 23:43:53 +0000867 assert(!Loc.isInvalid() && "must have a valid source location here");
868 assert(Loc.isFileID() && "must have a file location here");
869
Chandler Carruthdc2f2572011-10-16 07:20:28 +0000870 // If caret diagnostics are enabled and we have location, we want to
871 // emit the caret. However, we only do this if the location moved
872 // from the last diagnostic, if the last diagnostic was a note that
873 // was part of a different warning or error diagnostic, or if the
874 // diagnostic has ranges. We don't want to emit the same caret
875 // multiple times if one loc has multiple diagnostics.
876 if (!DiagOpts.ShowCarets)
877 return;
878 if (Loc == LastLoc && Ranges.empty() && Hints.empty() &&
879 (LastLevel != DiagnosticsEngine::Note || Level == LastLevel))
880 return;
881
Chandler Carrutha3028852011-10-15 23:43:53 +0000882 // Decompose the location into a FID/Offset pair.
883 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
884 FileID FID = LocInfo.first;
885 unsigned FileOffset = LocInfo.second;
886
887 // Get information about the buffer it points into.
888 bool Invalid = false;
Nico Weber35131222012-04-26 21:39:46 +0000889 const char *BufStart = SM.getBufferData(FID, &Invalid).data();
Chandler Carrutha3028852011-10-15 23:43:53 +0000890 if (Invalid)
891 return;
892
893 unsigned LineNo = SM.getLineNumber(FID, FileOffset);
894 unsigned ColNo = SM.getColumnNumber(FID, FileOffset);
895 unsigned CaretEndColNo
896 = ColNo + Lexer::MeasureTokenLength(Loc, SM, LangOpts);
897
898 // Rewind from the current position to the start of the line.
899 const char *TokPtr = BufStart+FileOffset;
900 const char *LineStart = TokPtr-ColNo+1; // Column # is 1-based.
901
902
903 // Compute the line end. Scan forward from the error position to the end of
904 // the line.
905 const char *LineEnd = TokPtr;
Nico Weber35131222012-04-26 21:39:46 +0000906 while (*LineEnd != '\n' && *LineEnd != '\r' && *LineEnd != '\0')
Chandler Carrutha3028852011-10-15 23:43:53 +0000907 ++LineEnd;
908
909 // FIXME: This shouldn't be necessary, but the CaretEndColNo can extend past
910 // the source line length as currently being computed. See
911 // test/Misc/message-length.c.
912 CaretEndColNo = std::min(CaretEndColNo, unsigned(LineEnd - LineStart));
913
914 // Copy the line of code into an std::string for ease of manipulation.
915 std::string SourceLine(LineStart, LineEnd);
916
917 // Create a line for the caret that is filled with spaces that is the same
918 // length as the line of source code.
919 std::string CaretLine(LineEnd-LineStart, ' ');
920
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000921 const SourceColumnMap sourceColMap(SourceLine, DiagOpts.TabStop);
922
Chandler Carrutha3028852011-10-15 23:43:53 +0000923 // Highlight all of the characters covered by Ranges with ~ characters.
924 for (SmallVectorImpl<CharSourceRange>::iterator I = Ranges.begin(),
925 E = Ranges.end();
926 I != E; ++I)
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +0000927 highlightRange(*I, LineNo, FID, sourceColMap, CaretLine, SM);
Chandler Carrutha3028852011-10-15 23:43:53 +0000928
929 // Next, insert the caret itself.
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000930 ColNo = sourceColMap.byteToColumn(ColNo-1);
931 if (CaretLine.size()<ColNo+1)
932 CaretLine.resize(ColNo+1, ' ');
933 CaretLine[ColNo] = '^';
Chandler Carrutha3028852011-10-15 23:43:53 +0000934
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000935 std::string FixItInsertionLine = buildFixItInsertionLine(LineNo,
936 sourceColMap,
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +0000937 Hints, SM);
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000938
939 // If the source line is too long for our terminal, select only the
940 // "interesting" source region within that line.
941 unsigned Columns = DiagOpts.MessageLength;
942 if (Columns)
943 selectInterestingSourceRegion(SourceLine, CaretLine, FixItInsertionLine,
944 Columns, sourceColMap);
Chandler Carrutha3028852011-10-15 23:43:53 +0000945
946 // If we are in -fdiagnostics-print-source-range-info mode, we are trying
947 // to produce easily machine parsable output. Add a space before the
948 // source line and the caret to make it trivial to tell the main diagnostic
949 // line from what the user is intended to see.
950 if (DiagOpts.ShowSourceRanges) {
951 SourceLine = ' ' + SourceLine;
952 CaretLine = ' ' + CaretLine;
953 }
954
Chandler Carrutha3028852011-10-15 23:43:53 +0000955 // Finally, remove any blank spaces from the end of CaretLine.
956 while (CaretLine[CaretLine.size()-1] == ' ')
957 CaretLine.erase(CaretLine.end()-1);
958
959 // Emit what we have computed.
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000960 emitSnippet(SourceLine);
Chandler Carrutha3028852011-10-15 23:43:53 +0000961
962 if (DiagOpts.ShowColors)
963 OS.changeColor(caretColor, true);
964 OS << CaretLine << '\n';
965 if (DiagOpts.ShowColors)
966 OS.resetColor();
967
968 if (!FixItInsertionLine.empty()) {
969 if (DiagOpts.ShowColors)
970 // Print fixit line in color
971 OS.changeColor(fixitColor, false);
972 if (DiagOpts.ShowSourceRanges)
973 OS << ' ';
974 OS << FixItInsertionLine << '\n';
975 if (DiagOpts.ShowColors)
976 OS.resetColor();
977 }
978
979 // Print out any parseable fixit information requested by the options.
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +0000980 emitParseableFixits(Hints, SM);
Chandler Carrutha3028852011-10-15 23:43:53 +0000981}
982
Benjamin Kramer556ab5e2012-05-01 14:34:11 +0000983void TextDiagnostic::emitSnippet(StringRef line) {
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000984 if (line.empty())
985 return;
986
987 size_t i = 0;
988
989 std::string to_print;
990 bool print_reversed = false;
991
992 while (i<line.size()) {
993 std::pair<SmallString<16>,bool> res
994 = printableTextForNextCharacter(line, &i, DiagOpts.TabStop);
995 bool was_printable = res.second;
996
Nico Weber35131222012-04-26 21:39:46 +0000997 if (DiagOpts.ShowColors && was_printable == print_reversed) {
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000998 if (print_reversed)
999 OS.reverseColor();
1000 OS << to_print;
1001 to_print.clear();
1002 if (DiagOpts.ShowColors)
1003 OS.resetColor();
1004 }
1005
1006 print_reversed = !was_printable;
1007 to_print += res.first.str();
1008 }
1009
1010 if (print_reversed && DiagOpts.ShowColors)
1011 OS.reverseColor();
1012 OS << to_print;
1013 if (print_reversed && DiagOpts.ShowColors)
1014 OS.resetColor();
1015
1016 OS << '\n';
1017}
1018
Chandler Carrutha3028852011-10-15 23:43:53 +00001019/// \brief Highlight a SourceRange (with ~'s) for any characters on LineNo.
Chandler Carruthab4c1da2011-10-15 23:54:09 +00001020void TextDiagnostic::highlightRange(const CharSourceRange &R,
Chandler Carrutha3028852011-10-15 23:43:53 +00001021 unsigned LineNo, FileID FID,
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001022 const SourceColumnMap &map,
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +00001023 std::string &CaretLine,
1024 const SourceManager &SM) {
Chandler Carrutha3028852011-10-15 23:43:53 +00001025 if (!R.isValid()) return;
1026
1027 SourceLocation Begin = SM.getExpansionLoc(R.getBegin());
1028 SourceLocation End = SM.getExpansionLoc(R.getEnd());
1029
1030 // If the End location and the start location are the same and are a macro
1031 // location, then the range was something that came from a macro expansion
1032 // or _Pragma. If this is an object-like macro, the best we can do is to
1033 // highlight the range. If this is a function-like macro, we'd also like to
1034 // highlight the arguments.
1035 if (Begin == End && R.getEnd().isMacroID())
1036 End = SM.getExpansionRange(R.getEnd()).second;
1037
1038 unsigned StartLineNo = SM.getExpansionLineNumber(Begin);
1039 if (StartLineNo > LineNo || SM.getFileID(Begin) != FID)
1040 return; // No intersection.
1041
1042 unsigned EndLineNo = SM.getExpansionLineNumber(End);
1043 if (EndLineNo < LineNo || SM.getFileID(End) != FID)
1044 return; // No intersection.
1045
1046 // Compute the column number of the start.
1047 unsigned StartColNo = 0;
1048 if (StartLineNo == LineNo) {
1049 StartColNo = SM.getExpansionColumnNumber(Begin);
1050 if (StartColNo) --StartColNo; // Zero base the col #.
1051 }
1052
1053 // Compute the column number of the end.
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001054 unsigned EndColNo = map.getSourceLine().size();
Chandler Carrutha3028852011-10-15 23:43:53 +00001055 if (EndLineNo == LineNo) {
1056 EndColNo = SM.getExpansionColumnNumber(End);
1057 if (EndColNo) {
1058 --EndColNo; // Zero base the col #.
1059
1060 // Add in the length of the token, so that we cover multi-char tokens if
1061 // this is a token range.
1062 if (R.isTokenRange())
1063 EndColNo += Lexer::MeasureTokenLength(End, SM, LangOpts);
1064 } else {
1065 EndColNo = CaretLine.size();
1066 }
1067 }
1068
1069 assert(StartColNo <= EndColNo && "Invalid range!");
1070
1071 // Check that a token range does not highlight only whitespace.
1072 if (R.isTokenRange()) {
1073 // Pick the first non-whitespace column.
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001074 while (StartColNo < map.getSourceLine().size() &&
1075 (map.getSourceLine()[StartColNo] == ' ' ||
1076 map.getSourceLine()[StartColNo] == '\t'))
Chandler Carrutha3028852011-10-15 23:43:53 +00001077 ++StartColNo;
1078
1079 // Pick the last non-whitespace column.
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001080 if (EndColNo > map.getSourceLine().size())
1081 EndColNo = map.getSourceLine().size();
Chandler Carrutha3028852011-10-15 23:43:53 +00001082 while (EndColNo-1 &&
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001083 (map.getSourceLine()[EndColNo-1] == ' ' ||
1084 map.getSourceLine()[EndColNo-1] == '\t'))
Chandler Carrutha3028852011-10-15 23:43:53 +00001085 --EndColNo;
1086
1087 // If the start/end passed each other, then we are trying to highlight a
1088 // range that just exists in whitespace, which must be some sort of other
1089 // bug.
1090 assert(StartColNo <= EndColNo && "Trying to highlight whitespace??");
1091 }
1092
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001093 assert(StartColNo <= map.getSourceLine().size() && "Invalid range!");
1094 assert(EndColNo <= map.getSourceLine().size() && "Invalid range!");
1095
Chandler Carrutha3028852011-10-15 23:43:53 +00001096 // Fill the range with ~'s.
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001097 StartColNo = map.byteToColumn(StartColNo);
1098 EndColNo = map.byteToColumn(EndColNo);
1099
1100 assert(StartColNo <= EndColNo && "Invalid range!");
1101 if (CaretLine.size() < EndColNo)
1102 CaretLine.resize(EndColNo,' ');
1103 std::fill(CaretLine.begin()+StartColNo,CaretLine.begin()+EndColNo,'~');
Chandler Carrutha3028852011-10-15 23:43:53 +00001104}
1105
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001106std::string TextDiagnostic::buildFixItInsertionLine(
1107 unsigned LineNo,
1108 const SourceColumnMap &map,
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +00001109 ArrayRef<FixItHint> Hints,
1110 const SourceManager &SM) {
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001111
Chandler Carrutha3028852011-10-15 23:43:53 +00001112 std::string FixItInsertionLine;
1113 if (Hints.empty() || !DiagOpts.ShowFixits)
1114 return FixItInsertionLine;
Jordan Roseb5a94f42012-06-08 21:14:19 +00001115 unsigned PrevHintEnd = 0;
Chandler Carrutha3028852011-10-15 23:43:53 +00001116
1117 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1118 I != E; ++I) {
1119 if (!I->CodeToInsert.empty()) {
1120 // We have an insertion hint. Determine whether the inserted
1121 // code is on the same line as the caret.
1122 std::pair<FileID, unsigned> HintLocInfo
1123 = SM.getDecomposedExpansionLoc(I->RemoveRange.getBegin());
1124 if (LineNo == SM.getLineNumber(HintLocInfo.first, HintLocInfo.second)) {
1125 // Insert the new code into the line just below the code
1126 // that the user wrote.
1127 unsigned HintColNo
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001128 = SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second) - 1;
1129 // hint must start inside the source or right at the end
1130 assert(HintColNo<static_cast<unsigned>(map.bytes())+1);
1131 HintColNo = map.byteToColumn(HintColNo);
1132
Jordan Roseb5a94f42012-06-08 21:14:19 +00001133 // If we inserted a long previous hint, push this one forwards, and add
1134 // an extra space to show that this is not part of the previous
1135 // completion. This is sort of the best we can do when two hints appear
1136 // to overlap.
1137 //
1138 // Note that if this hint is located immediately after the previous
1139 // hint, no space will be added, since the location is more important.
1140 if (HintColNo < PrevHintEnd)
1141 HintColNo = PrevHintEnd + 1;
1142
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001143 // FIXME: if the fixit includes tabs or other characters that do not
1144 // take up a single column per byte when displayed then
1145 // I->CodeToInsert.size() is not a column number and we're mixing
1146 // units (columns + bytes). We should get printable versions
1147 // of each fixit before using them.
Chandler Carrutha3028852011-10-15 23:43:53 +00001148 unsigned LastColumnModified
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001149 = HintColNo + I->CodeToInsert.size();
1150
Jordan Roseb5a94f42012-06-08 21:14:19 +00001151 if (LastColumnModified <= static_cast<unsigned>(map.bytes()))
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001152 LastColumnModified = map.byteToColumn(LastColumnModified);
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001153
Chandler Carrutha3028852011-10-15 23:43:53 +00001154 if (LastColumnModified > FixItInsertionLine.size())
1155 FixItInsertionLine.resize(LastColumnModified, ' ');
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001156 assert(HintColNo+I->CodeToInsert.size() <= FixItInsertionLine.size());
Chandler Carrutha3028852011-10-15 23:43:53 +00001157 std::copy(I->CodeToInsert.begin(), I->CodeToInsert.end(),
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001158 FixItInsertionLine.begin() + HintColNo);
Jordan Roseb5a94f42012-06-08 21:14:19 +00001159
1160 PrevHintEnd = LastColumnModified;
Chandler Carrutha3028852011-10-15 23:43:53 +00001161 } else {
1162 FixItInsertionLine.clear();
1163 break;
1164 }
1165 }
1166 }
1167
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001168 expandTabs(FixItInsertionLine, DiagOpts.TabStop);
Chandler Carrutha3028852011-10-15 23:43:53 +00001169
1170 return FixItInsertionLine;
1171}
1172
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +00001173void TextDiagnostic::emitParseableFixits(ArrayRef<FixItHint> Hints,
1174 const SourceManager &SM) {
Chandler Carrutha3028852011-10-15 23:43:53 +00001175 if (!DiagOpts.ShowParseableFixits)
1176 return;
1177
1178 // We follow FixItRewriter's example in not (yet) handling
1179 // fix-its in macros.
1180 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1181 I != E; ++I) {
1182 if (I->RemoveRange.isInvalid() ||
1183 I->RemoveRange.getBegin().isMacroID() ||
1184 I->RemoveRange.getEnd().isMacroID())
1185 return;
1186 }
1187
1188 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1189 I != E; ++I) {
1190 SourceLocation BLoc = I->RemoveRange.getBegin();
1191 SourceLocation ELoc = I->RemoveRange.getEnd();
1192
1193 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(BLoc);
1194 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(ELoc);
1195
1196 // Adjust for token ranges.
1197 if (I->RemoveRange.isTokenRange())
1198 EInfo.second += Lexer::MeasureTokenLength(ELoc, SM, LangOpts);
1199
1200 // We specifically do not do word-wrapping or tab-expansion here,
1201 // because this is supposed to be easy to parse.
1202 PresumedLoc PLoc = SM.getPresumedLoc(BLoc);
1203 if (PLoc.isInvalid())
1204 break;
1205
1206 OS << "fix-it:\"";
1207 OS.write_escaped(PLoc.getFilename());
1208 OS << "\":{" << SM.getLineNumber(BInfo.first, BInfo.second)
1209 << ':' << SM.getColumnNumber(BInfo.first, BInfo.second)
1210 << '-' << SM.getLineNumber(EInfo.first, EInfo.second)
1211 << ':' << SM.getColumnNumber(EInfo.first, EInfo.second)
1212 << "}:\"";
1213 OS.write_escaped(I->CodeToInsert);
1214 OS << "\"\n";
1215 }
1216}