blob: 663dc96af7d22cf05182e1af5ad3933eba5f1a4c [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;
34static const enum raw_ostream::Colors errorColor = raw_ostream::RED;
35static const enum raw_ostream::Colors fatalColor = raw_ostream::RED;
36// Used for changing only the bold attribute.
37static const enum raw_ostream::Colors savedColor =
38 raw_ostream::SAVEDCOLOR;
39
40/// \brief Number of spaces to indent when word-wrapping.
41const unsigned WordWrapIndentation = 6;
42
Benjamin Kramer556ab5e2012-05-01 14:34:11 +000043static int bytesSincePreviousTabOrLineBegin(StringRef SourceLine, size_t i) {
Seth Cantrell99e2fa82012-04-18 02:44:46 +000044 int bytes = 0;
45 while (0<i) {
46 if (SourceLine[--i]=='\t')
47 break;
48 ++bytes;
49 }
50 return bytes;
51}
52
53/// \brief returns a printable representation of first item from input range
54///
55/// This function returns a printable representation of the next item in a line
56/// of source. If the next byte begins a valid and printable character, that
57/// character is returned along with 'true'.
58///
59/// Otherwise, if the next byte begins a valid, but unprintable character, a
60/// printable, escaped representation of the character is returned, along with
61/// 'false'. Otherwise a printable, escaped representation of the next byte
62/// is returned along with 'false'.
63///
64/// \note The index is updated to be used with a subsequent call to
65/// printableTextForNextCharacter.
66///
67/// \param SourceLine The line of source
68/// \param i Pointer to byte index,
69/// \param TabStop used to expand tabs
70/// \return pair(printable text, 'true' iff original text was printable)
71///
Benjamin Kramer556ab5e2012-05-01 14:34:11 +000072static std::pair<SmallString<16>, bool>
Seth Cantrell99e2fa82012-04-18 02:44:46 +000073printableTextForNextCharacter(StringRef SourceLine, size_t *i,
74 unsigned TabStop) {
75 assert(i && "i must not be null");
76 assert(*i<SourceLine.size() && "must point to a valid index");
77
78 if (SourceLine[*i]=='\t') {
79 assert(0 < TabStop && TabStop <= DiagnosticOptions::MaxTabStop &&
80 "Invalid -ftabstop value");
81 unsigned col = bytesSincePreviousTabOrLineBegin(SourceLine, *i);
82 unsigned NumSpaces = TabStop - col%TabStop;
83 assert(0 < NumSpaces && NumSpaces <= TabStop
84 && "Invalid computation of space amt");
85 ++(*i);
86
87 SmallString<16> expandedTab;
88 expandedTab.assign(NumSpaces, ' ');
89 return std::make_pair(expandedTab, true);
90 }
91
92 // FIXME: this data is copied from the private implementation of ConvertUTF.h
93 static const char trailingBytesForUTF8[256] = {
94 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,
95 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,
96 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,
97 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,
98 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,
99 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,
100 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,
101 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
102 };
103
104 unsigned char const *begin, *end;
105 begin = reinterpret_cast<unsigned char const *>(&*(SourceLine.begin() + *i));
106 end = begin + SourceLine.size();
107
108 if (isLegalUTF8Sequence(begin, end)) {
109 UTF32 c;
110 UTF32 *cptr = &c;
111 unsigned char const *original_begin = begin;
112 char trailingBytes = trailingBytesForUTF8[(unsigned char)SourceLine[*i]];
113 unsigned char const *cp_end = begin+trailingBytes+1;
114
115 ConversionResult res = ConvertUTF8toUTF32(&begin, cp_end, &cptr, cptr+1,
116 strictConversion);
Matt Beaumont-Gay69e227b2012-04-18 17:25:16 +0000117 (void)res;
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000118 assert(conversionOK==res);
119 assert(0 < begin-original_begin
120 && "we must be further along in the string now");
121 *i += begin-original_begin;
122
123 if (!llvm::sys::locale::isPrint(c)) {
124 // If next character is valid UTF-8, but not printable
125 SmallString<16> expandedCP("<U+>");
126 while (c) {
127 expandedCP.insert(expandedCP.begin()+3, llvm::hexdigit(c%16));
128 c/=16;
129 }
130 while (expandedCP.size() < 8)
131 expandedCP.insert(expandedCP.begin()+3, llvm::hexdigit(0));
132 return std::make_pair(expandedCP, false);
133 }
134
135 // If next character is valid UTF-8, and printable
136 return std::make_pair(SmallString<16>(original_begin, cp_end), true);
137
138 }
139
140 // If next byte is not valid UTF-8 (and therefore not printable)
141 SmallString<16> expandedByte("<XX>");
142 unsigned char byte = SourceLine[*i];
143 expandedByte[1] = llvm::hexdigit(byte / 16);
144 expandedByte[2] = llvm::hexdigit(byte % 16);
145 ++(*i);
146 return std::make_pair(expandedByte, false);
147}
148
Benjamin Kramer556ab5e2012-05-01 14:34:11 +0000149static void expandTabs(std::string &SourceLine, unsigned TabStop) {
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000150 size_t i = SourceLine.size();
151 while (i>0) {
152 i--;
153 if (SourceLine[i]!='\t')
154 continue;
155 size_t tmp_i = i;
156 std::pair<SmallString<16>,bool> res
157 = printableTextForNextCharacter(SourceLine, &tmp_i, TabStop);
158 SourceLine.replace(i, 1, res.first.c_str());
159 }
160}
161
162/// This function takes a raw source line and produces a mapping from the bytes
163/// of the printable representation of the line to the columns those printable
164/// characters will appear at (numbering the first column as 0).
165///
166/// If a byte 'i' corresponds to muliple columns (e.g. the byte contains a tab
167/// character) then the the array will map that byte to the first column the
168/// tab appears at and the next value in the map will have been incremented
169/// more than once.
170///
171/// If a byte is the first in a sequence of bytes that together map to a single
172/// entity in the output, then the array will map that byte to the appropriate
173/// column while the subsequent bytes will be -1.
174///
175/// The last element in the array does not correspond to any byte in the input
176/// and instead is the number of columns needed to display the source
177///
178/// example: (given a tabstop of 8)
179///
180/// "a \t \u3042" -> {0,1,2,8,9,-1,-1,11}
181///
182/// (\u3042 is represented in UTF-8 by three bytes and takes two columns to
183/// display)
Benjamin Kramer556ab5e2012-05-01 14:34:11 +0000184static void byteToColumn(StringRef SourceLine, unsigned TabStop,
185 SmallVectorImpl<int> &out) {
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000186 out.clear();
187
188 if (SourceLine.empty()) {
189 out.resize(1u,0);
190 return;
191 }
192
193 out.resize(SourceLine.size()+1, -1);
194
195 int columns = 0;
196 size_t i = 0;
197 while (i<SourceLine.size()) {
198 out[i] = columns;
199 std::pair<SmallString<16>,bool> res
200 = printableTextForNextCharacter(SourceLine, &i, TabStop);
201 columns += llvm::sys::locale::columnWidth(res.first);
202 }
203 out.back() = columns;
204}
205
206/// This function takes a raw source line and produces a mapping from columns
207/// to the byte of the source line that produced the character displaying at
208/// that column. This is the inverse of the mapping produced by byteToColumn()
209///
210/// The last element in the array is the number of bytes in the source string
211///
212/// example: (given a tabstop of 8)
213///
214/// "a \t \u3042" -> {0,1,2,-1,-1,-1,-1,-1,3,4,-1,7}
215///
216/// (\u3042 is represented in UTF-8 by three bytes and takes two columns to
217/// display)
Benjamin Kramer556ab5e2012-05-01 14:34:11 +0000218static void columnToByte(StringRef SourceLine, unsigned TabStop,
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000219 SmallVectorImpl<int> &out) {
220 out.clear();
221
222 if (SourceLine.empty()) {
223 out.resize(1u, 0);
224 return;
225 }
226
227 int columns = 0;
228 size_t i = 0;
229 while (i<SourceLine.size()) {
230 out.resize(columns+1, -1);
231 out.back() = i;
232 std::pair<SmallString<16>,bool> res
233 = printableTextForNextCharacter(SourceLine, &i, TabStop);
234 columns += llvm::sys::locale::columnWidth(res.first);
235 }
236 out.resize(columns+1, -1);
237 out.back() = i;
238}
239
240struct SourceColumnMap {
241 SourceColumnMap(StringRef SourceLine, unsigned TabStop)
242 : m_SourceLine(SourceLine) {
243
244 ::byteToColumn(SourceLine, TabStop, m_byteToColumn);
245 ::columnToByte(SourceLine, TabStop, m_columnToByte);
246
247 assert(m_byteToColumn.size()==SourceLine.size()+1);
248 assert(0 < m_byteToColumn.size() && 0 < m_columnToByte.size());
249 assert(m_byteToColumn.size()
250 == static_cast<unsigned>(m_columnToByte.back()+1));
251 assert(static_cast<unsigned>(m_byteToColumn.back()+1)
252 == m_columnToByte.size());
253 }
254 int columns() const { return m_byteToColumn.back(); }
255 int bytes() const { return m_columnToByte.back(); }
256 int byteToColumn(int n) const {
257 assert(0<=n && n<static_cast<int>(m_byteToColumn.size()));
258 return m_byteToColumn[n];
259 }
260 int columnToByte(int n) const {
261 assert(0<=n && n<static_cast<int>(m_columnToByte.size()));
262 return m_columnToByte[n];
263 }
264 StringRef getSourceLine() const {
265 return m_SourceLine;
266 }
267
268private:
269 const std::string m_SourceLine;
270 SmallVector<int,200> m_byteToColumn;
271 SmallVector<int,200> m_columnToByte;
272};
273
274// used in assert in selectInterestingSourceRegion()
275namespace {
276struct char_out_of_range {
277 const char lower,upper;
278 char_out_of_range(char lower, char upper) :
279 lower(lower), upper(upper) {}
280 bool operator()(char c) { return c < lower || upper < c; }
281};
282}
283
Chandler Carrutha3028852011-10-15 23:43:53 +0000284/// \brief When the source code line we want to print is too long for
285/// the terminal, select the "interesting" region.
Chandler Carruthab4c1da2011-10-15 23:54:09 +0000286static void selectInterestingSourceRegion(std::string &SourceLine,
Chandler Carrutha3028852011-10-15 23:43:53 +0000287 std::string &CaretLine,
288 std::string &FixItInsertionLine,
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000289 unsigned Columns,
290 const SourceColumnMap &map) {
291 unsigned MaxColumns = std::max<unsigned>(map.columns(),
292 std::max(CaretLine.size(),
293 FixItInsertionLine.size()));
294 // if the number of columns is less than the desired number we're done
295 if (MaxColumns <= Columns)
296 return;
297
298 // no special characters allowed in CaretLine or FixItInsertionLine
299 assert(CaretLine.end() ==
300 std::find_if(CaretLine.begin(), CaretLine.end(),
301 char_out_of_range(' ','~')));
302 assert(FixItInsertionLine.end() ==
303 std::find_if(FixItInsertionLine.begin(), FixItInsertionLine.end(),
304 char_out_of_range(' ','~')));
305
Chandler Carrutha3028852011-10-15 23:43:53 +0000306 // Find the slice that we need to display the full caret line
307 // correctly.
308 unsigned CaretStart = 0, CaretEnd = CaretLine.size();
309 for (; CaretStart != CaretEnd; ++CaretStart)
310 if (!isspace(CaretLine[CaretStart]))
311 break;
312
313 for (; CaretEnd != CaretStart; --CaretEnd)
314 if (!isspace(CaretLine[CaretEnd - 1]))
315 break;
316
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000317 // caret has already been inserted into CaretLine so the above whitespace
318 // check is guaranteed to include the caret
Chandler Carrutha3028852011-10-15 23:43:53 +0000319
320 // If we have a fix-it line, make sure the slice includes all of the
321 // fix-it information.
322 if (!FixItInsertionLine.empty()) {
323 unsigned FixItStart = 0, FixItEnd = FixItInsertionLine.size();
324 for (; FixItStart != FixItEnd; ++FixItStart)
325 if (!isspace(FixItInsertionLine[FixItStart]))
326 break;
327
328 for (; FixItEnd != FixItStart; --FixItEnd)
329 if (!isspace(FixItInsertionLine[FixItEnd - 1]))
330 break;
331
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000332 CaretStart = std::min(FixItStart, CaretStart);
333 CaretEnd = std::max(FixItEnd, CaretEnd);
Chandler Carrutha3028852011-10-15 23:43:53 +0000334 }
335
Seth Cantrellac6fb8f2012-05-24 05:14:44 +0000336 // CaretEnd may have been set at the middle of a character
337 // If it's not at a character's first column then advance it past the current
338 // character.
339 while (static_cast<int>(CaretEnd) < map.columns() &&
340 -1 == map.columnToByte(CaretEnd))
341 ++CaretEnd;
342
343 assert((static_cast<int>(CaretStart) > map.columns() ||
344 -1!=map.columnToByte(CaretStart)) &&
345 "CaretStart must not point to a column in the middle of a source"
346 " line character");
347 assert((static_cast<int>(CaretEnd) > map.columns() ||
348 -1!=map.columnToByte(CaretEnd)) &&
349 "CaretEnd must not point to a column in the middle of a source line"
350 " character");
351
Chandler Carrutha3028852011-10-15 23:43:53 +0000352 // CaretLine[CaretStart, CaretEnd) contains all of the interesting
353 // parts of the caret line. While this slice is smaller than the
354 // number of columns we have, try to grow the slice to encompass
355 // more context.
356
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000357 unsigned SourceStart = map.columnToByte(std::min<unsigned>(CaretStart,
358 map.columns()));
359 unsigned SourceEnd = map.columnToByte(std::min<unsigned>(CaretEnd,
360 map.columns()));
361
362 unsigned CaretColumnsOutsideSource = CaretEnd-CaretStart
363 - (map.byteToColumn(SourceEnd)-map.byteToColumn(SourceStart));
364
365 char const *front_ellipse = " ...";
366 char const *front_space = " ";
367 char const *back_ellipse = "...";
368 unsigned ellipses_space = strlen(front_ellipse) + strlen(back_ellipse);
Chandler Carrutha3028852011-10-15 23:43:53 +0000369
370 unsigned TargetColumns = Columns;
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000371 // Give us extra room for the ellipses
372 // and any of the caret line that extends past the source
373 if (TargetColumns > ellipses_space+CaretColumnsOutsideSource)
374 TargetColumns -= ellipses_space+CaretColumnsOutsideSource;
375
376 while (SourceStart>0 || SourceEnd<SourceLine.size()) {
Chandler Carrutha3028852011-10-15 23:43:53 +0000377 bool ExpandedRegion = false;
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000378
379 if (SourceStart>0) {
380 unsigned NewStart = SourceStart-1;
Chandler Carrutha3028852011-10-15 23:43:53 +0000381
382 // Skip over any whitespace we see here; we're looking for
383 // another bit of interesting text.
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000384 while (NewStart &&
385 (map.byteToColumn(NewStart)==-1 || isspace(SourceLine[NewStart])))
Chandler Carrutha3028852011-10-15 23:43:53 +0000386 --NewStart;
387
388 // Skip over this bit of "interesting" text.
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000389 while (NewStart &&
390 (map.byteToColumn(NewStart)!=-1 && !isspace(SourceLine[NewStart])))
Chandler Carrutha3028852011-10-15 23:43:53 +0000391 --NewStart;
392
393 // Move up to the non-whitespace character we just saw.
394 if (NewStart)
395 ++NewStart;
396
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000397 unsigned NewColumns = map.byteToColumn(SourceEnd) -
398 map.byteToColumn(NewStart);
399 if (NewColumns <= TargetColumns) {
400 SourceStart = NewStart;
Chandler Carrutha3028852011-10-15 23:43:53 +0000401 ExpandedRegion = true;
402 }
403 }
404
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000405 if (SourceEnd<SourceLine.size()) {
406 unsigned NewEnd = SourceEnd+1;
Chandler Carrutha3028852011-10-15 23:43:53 +0000407
408 // Skip over any whitespace we see here; we're looking for
409 // another bit of interesting text.
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000410 while (NewEnd<SourceLine.size() &&
411 (map.byteToColumn(NewEnd)==-1 || isspace(SourceLine[NewEnd])))
Chandler Carrutha3028852011-10-15 23:43:53 +0000412 ++NewEnd;
413
414 // Skip over this bit of "interesting" text.
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000415 while (NewEnd<SourceLine.size() &&
416 (map.byteToColumn(NewEnd)!=-1 && !isspace(SourceLine[NewEnd])))
Chandler Carrutha3028852011-10-15 23:43:53 +0000417 ++NewEnd;
418
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000419 unsigned NewColumns = map.byteToColumn(NewEnd) -
420 map.byteToColumn(SourceStart);
421 if (NewColumns <= TargetColumns) {
422 SourceEnd = NewEnd;
Chandler Carrutha3028852011-10-15 23:43:53 +0000423 ExpandedRegion = true;
424 }
425 }
426
427 if (!ExpandedRegion)
428 break;
429 }
430
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000431 CaretStart = map.byteToColumn(SourceStart);
432 CaretEnd = map.byteToColumn(SourceEnd) + CaretColumnsOutsideSource;
433
Chandler Carrutha3028852011-10-15 23:43:53 +0000434 // [CaretStart, CaretEnd) is the slice we want. Update the various
435 // output lines to show only this slice, with two-space padding
436 // before the lines so that it looks nicer.
Chandler Carrutha3028852011-10-15 23:43:53 +0000437
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000438 assert(CaretStart!=(unsigned)-1 && CaretEnd!=(unsigned)-1 &&
439 SourceStart!=(unsigned)-1 && SourceEnd!=(unsigned)-1);
440 assert(SourceStart <= SourceEnd);
441 assert(CaretStart <= CaretEnd);
442
443 unsigned BackColumnsRemoved
444 = map.byteToColumn(SourceLine.size())-map.byteToColumn(SourceEnd);
445 unsigned FrontColumnsRemoved = CaretStart;
446 unsigned ColumnsKept = CaretEnd-CaretStart;
447
448 // We checked up front that the line needed truncation
449 assert(FrontColumnsRemoved+ColumnsKept+BackColumnsRemoved > Columns);
450
451 // The line needs some trunctiona, and we'd prefer to keep the front
452 // if possible, so remove the back
453 if (BackColumnsRemoved)
454 SourceLine.replace(SourceEnd, std::string::npos, back_ellipse);
455
456 // If that's enough then we're done
457 if (FrontColumnsRemoved+ColumnsKept <= Columns)
458 return;
459
460 // Otherwise remove the front as well
461 if (FrontColumnsRemoved) {
462 SourceLine.replace(0, SourceStart, front_ellipse);
463 CaretLine.replace(0, CaretStart, front_space);
464 if (!FixItInsertionLine.empty())
465 FixItInsertionLine.replace(0, CaretStart, front_space);
Chandler Carrutha3028852011-10-15 23:43:53 +0000466 }
467}
468
Chandler Carrutha3028852011-10-15 23:43:53 +0000469/// \brief Skip over whitespace in the string, starting at the given
470/// index.
471///
472/// \returns The index of the first non-whitespace character that is
473/// greater than or equal to Idx or, if no such character exists,
474/// returns the end of the string.
475static unsigned skipWhitespace(unsigned Idx, StringRef Str, unsigned Length) {
476 while (Idx < Length && isspace(Str[Idx]))
477 ++Idx;
478 return Idx;
479}
480
481/// \brief If the given character is the start of some kind of
482/// balanced punctuation (e.g., quotes or parentheses), return the
483/// character that will terminate the punctuation.
484///
485/// \returns The ending punctuation character, if any, or the NULL
486/// character if the input character does not start any punctuation.
487static inline char findMatchingPunctuation(char c) {
488 switch (c) {
489 case '\'': return '\'';
490 case '`': return '\'';
491 case '"': return '"';
492 case '(': return ')';
493 case '[': return ']';
494 case '{': return '}';
495 default: break;
496 }
497
498 return 0;
499}
500
501/// \brief Find the end of the word starting at the given offset
502/// within a string.
503///
504/// \returns the index pointing one character past the end of the
505/// word.
506static unsigned findEndOfWord(unsigned Start, StringRef Str,
507 unsigned Length, unsigned Column,
508 unsigned Columns) {
509 assert(Start < Str.size() && "Invalid start position!");
510 unsigned End = Start + 1;
511
512 // If we are already at the end of the string, take that as the word.
513 if (End == Str.size())
514 return End;
515
516 // Determine if the start of the string is actually opening
517 // punctuation, e.g., a quote or parentheses.
518 char EndPunct = findMatchingPunctuation(Str[Start]);
519 if (!EndPunct) {
520 // This is a normal word. Just find the first space character.
521 while (End < Length && !isspace(Str[End]))
522 ++End;
523 return End;
524 }
525
526 // We have the start of a balanced punctuation sequence (quotes,
527 // parentheses, etc.). Determine the full sequence is.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000528 SmallString<16> PunctuationEndStack;
Chandler Carrutha3028852011-10-15 23:43:53 +0000529 PunctuationEndStack.push_back(EndPunct);
530 while (End < Length && !PunctuationEndStack.empty()) {
531 if (Str[End] == PunctuationEndStack.back())
532 PunctuationEndStack.pop_back();
533 else if (char SubEndPunct = findMatchingPunctuation(Str[End]))
534 PunctuationEndStack.push_back(SubEndPunct);
535
536 ++End;
537 }
538
539 // Find the first space character after the punctuation ended.
540 while (End < Length && !isspace(Str[End]))
541 ++End;
542
543 unsigned PunctWordLength = End - Start;
544 if (// If the word fits on this line
545 Column + PunctWordLength <= Columns ||
546 // ... or the word is "short enough" to take up the next line
547 // without too much ugly white space
548 PunctWordLength < Columns/3)
549 return End; // Take the whole thing as a single "word".
550
551 // The whole quoted/parenthesized string is too long to print as a
552 // single "word". Instead, find the "word" that starts just after
553 // the punctuation and use that end-point instead. This will recurse
554 // until it finds something small enough to consider a word.
555 return findEndOfWord(Start + 1, Str, Length, Column + 1, Columns);
556}
557
558/// \brief Print the given string to a stream, word-wrapping it to
559/// some number of columns in the process.
560///
561/// \param OS the stream to which the word-wrapping string will be
562/// emitted.
563/// \param Str the string to word-wrap and output.
564/// \param Columns the number of columns to word-wrap to.
565/// \param Column the column number at which the first character of \p
566/// Str will be printed. This will be non-zero when part of the first
567/// line has already been printed.
568/// \param Indentation the number of spaces to indent any lines beyond
569/// the first line.
570/// \returns true if word-wrapping was required, or false if the
571/// string fit on the first line.
572static bool printWordWrapped(raw_ostream &OS, StringRef Str,
573 unsigned Columns,
574 unsigned Column = 0,
575 unsigned Indentation = WordWrapIndentation) {
576 const unsigned Length = std::min(Str.find('\n'), Str.size());
577
578 // The string used to indent each line.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000579 SmallString<16> IndentStr;
Chandler Carrutha3028852011-10-15 23:43:53 +0000580 IndentStr.assign(Indentation, ' ');
581 bool Wrapped = false;
582 for (unsigned WordStart = 0, WordEnd; WordStart < Length;
583 WordStart = WordEnd) {
584 // Find the beginning of the next word.
585 WordStart = skipWhitespace(WordStart, Str, Length);
586 if (WordStart == Length)
587 break;
588
589 // Find the end of this word.
590 WordEnd = findEndOfWord(WordStart, Str, Length, Column, Columns);
591
592 // Does this word fit on the current line?
593 unsigned WordLength = WordEnd - WordStart;
594 if (Column + WordLength < Columns) {
595 // This word fits on the current line; print it there.
596 if (WordStart) {
597 OS << ' ';
598 Column += 1;
599 }
600 OS << Str.substr(WordStart, WordLength);
601 Column += WordLength;
602 continue;
603 }
604
605 // This word does not fit on the current line, so wrap to the next
606 // line.
607 OS << '\n';
608 OS.write(&IndentStr[0], Indentation);
609 OS << Str.substr(WordStart, WordLength);
610 Column = Indentation + WordLength;
611 Wrapped = true;
612 }
613
614 // Append any remaning text from the message with its existing formatting.
615 OS << Str.substr(Length);
616
617 return Wrapped;
618}
619
620TextDiagnostic::TextDiagnostic(raw_ostream &OS,
Chandler Carrutha3028852011-10-15 23:43:53 +0000621 const LangOptions &LangOpts,
Chandler Carruth3eb8b542011-10-16 02:57:39 +0000622 const DiagnosticOptions &DiagOpts)
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +0000623 : DiagnosticRenderer(LangOpts, DiagOpts), OS(OS) {}
Chandler Carrutha3028852011-10-15 23:43:53 +0000624
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000625TextDiagnostic::~TextDiagnostic() {}
Chandler Carrutha3028852011-10-15 23:43:53 +0000626
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000627void
628TextDiagnostic::emitDiagnosticMessage(SourceLocation Loc,
629 PresumedLoc PLoc,
630 DiagnosticsEngine::Level Level,
631 StringRef Message,
632 ArrayRef<clang::CharSourceRange> Ranges,
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +0000633 const SourceManager *SM,
Ted Kremenek0964cca2012-02-14 02:46:00 +0000634 DiagOrStoredDiag D) {
Chandler Carrutha3028852011-10-15 23:43:53 +0000635 uint64_t StartOfLocationInfo = OS.tell();
636
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000637 // Emit the location of this particular diagnostic.
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +0000638 if (Loc.isValid())
639 emitDiagnosticLoc(Loc, PLoc, Level, Ranges, *SM);
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000640
Chandler Carrutha3028852011-10-15 23:43:53 +0000641 if (DiagOpts.ShowColors)
642 OS.resetColor();
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000643
Chandler Carrutha3028852011-10-15 23:43:53 +0000644 printDiagnosticLevel(OS, Level, DiagOpts.ShowColors);
645 printDiagnosticMessage(OS, Level, Message,
646 OS.tell() - StartOfLocationInfo,
647 DiagOpts.MessageLength, DiagOpts.ShowColors);
Chandler Carrutha3028852011-10-15 23:43:53 +0000648}
649
Chandler Carruth07c346d2011-10-15 23:48:02 +0000650/*static*/ void
651TextDiagnostic::printDiagnosticLevel(raw_ostream &OS,
652 DiagnosticsEngine::Level Level,
653 bool ShowColors) {
654 if (ShowColors) {
655 // Print diagnostic category in bold and color
656 switch (Level) {
657 case DiagnosticsEngine::Ignored:
658 llvm_unreachable("Invalid diagnostic type");
659 case DiagnosticsEngine::Note: OS.changeColor(noteColor, true); break;
660 case DiagnosticsEngine::Warning: OS.changeColor(warningColor, true); break;
661 case DiagnosticsEngine::Error: OS.changeColor(errorColor, true); break;
662 case DiagnosticsEngine::Fatal: OS.changeColor(fatalColor, true); break;
663 }
664 }
665
666 switch (Level) {
667 case DiagnosticsEngine::Ignored:
668 llvm_unreachable("Invalid diagnostic type");
669 case DiagnosticsEngine::Note: OS << "note: "; break;
670 case DiagnosticsEngine::Warning: OS << "warning: "; break;
671 case DiagnosticsEngine::Error: OS << "error: "; break;
672 case DiagnosticsEngine::Fatal: OS << "fatal error: "; break;
673 }
674
675 if (ShowColors)
676 OS.resetColor();
677}
678
679/*static*/ void
680TextDiagnostic::printDiagnosticMessage(raw_ostream &OS,
681 DiagnosticsEngine::Level Level,
682 StringRef Message,
683 unsigned CurrentColumn, unsigned Columns,
684 bool ShowColors) {
685 if (ShowColors) {
686 // Print warnings, errors and fatal errors in bold, no color
687 switch (Level) {
688 case DiagnosticsEngine::Warning: OS.changeColor(savedColor, true); break;
689 case DiagnosticsEngine::Error: OS.changeColor(savedColor, true); break;
690 case DiagnosticsEngine::Fatal: OS.changeColor(savedColor, true); break;
691 default: break; //don't bold notes
692 }
693 }
694
695 if (Columns)
696 printWordWrapped(OS, Message, Columns, CurrentColumn);
697 else
698 OS << Message;
699
700 if (ShowColors)
701 OS.resetColor();
702 OS << '\n';
703}
704
Chandler Carruth07c346d2011-10-15 23:48:02 +0000705/// \brief Print out the file/line/column information and include trace.
706///
707/// This method handlen the emission of the diagnostic location information.
708/// This includes extracting as much location information as is present for
709/// the diagnostic and printing it, as well as any include stack or source
710/// ranges necessary.
Chandler Carruthab4c1da2011-10-15 23:54:09 +0000711void TextDiagnostic::emitDiagnosticLoc(SourceLocation Loc, PresumedLoc PLoc,
Chandler Carruth07c346d2011-10-15 23:48:02 +0000712 DiagnosticsEngine::Level Level,
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +0000713 ArrayRef<CharSourceRange> Ranges,
714 const SourceManager &SM) {
Chandler Carruth07c346d2011-10-15 23:48:02 +0000715 if (PLoc.isInvalid()) {
716 // At least print the file name if available:
717 FileID FID = SM.getFileID(Loc);
718 if (!FID.isInvalid()) {
719 const FileEntry* FE = SM.getFileEntryForID(FID);
720 if (FE && FE->getName()) {
721 OS << FE->getName();
722 if (FE->getDevice() == 0 && FE->getInode() == 0
723 && FE->getFileMode() == 0) {
724 // in PCH is a guess, but a good one:
725 OS << " (in PCH)";
726 }
727 OS << ": ";
728 }
729 }
730 return;
731 }
732 unsigned LineNo = PLoc.getLine();
733
734 if (!DiagOpts.ShowLocation)
735 return;
736
737 if (DiagOpts.ShowColors)
738 OS.changeColor(savedColor, true);
739
740 OS << PLoc.getFilename();
741 switch (DiagOpts.Format) {
742 case DiagnosticOptions::Clang: OS << ':' << LineNo; break;
743 case DiagnosticOptions::Msvc: OS << '(' << LineNo; break;
744 case DiagnosticOptions::Vi: OS << " +" << LineNo; break;
745 }
746
747 if (DiagOpts.ShowColumn)
748 // Compute the column number.
749 if (unsigned ColNo = PLoc.getColumn()) {
750 if (DiagOpts.Format == DiagnosticOptions::Msvc) {
751 OS << ',';
752 ColNo--;
753 } else
754 OS << ':';
755 OS << ColNo;
756 }
757 switch (DiagOpts.Format) {
758 case DiagnosticOptions::Clang:
759 case DiagnosticOptions::Vi: OS << ':'; break;
760 case DiagnosticOptions::Msvc: OS << ") : "; break;
761 }
762
763 if (DiagOpts.ShowSourceRanges && !Ranges.empty()) {
764 FileID CaretFileID =
765 SM.getFileID(SM.getExpansionLoc(Loc));
766 bool PrintedRange = false;
767
768 for (ArrayRef<CharSourceRange>::const_iterator RI = Ranges.begin(),
769 RE = Ranges.end();
770 RI != RE; ++RI) {
771 // Ignore invalid ranges.
772 if (!RI->isValid()) continue;
773
774 SourceLocation B = SM.getExpansionLoc(RI->getBegin());
775 SourceLocation E = SM.getExpansionLoc(RI->getEnd());
776
777 // If the End location and the start location are the same and are a
778 // macro location, then the range was something that came from a
779 // macro expansion or _Pragma. If this is an object-like macro, the
780 // best we can do is to highlight the range. If this is a
781 // function-like macro, we'd also like to highlight the arguments.
782 if (B == E && RI->getEnd().isMacroID())
783 E = SM.getExpansionRange(RI->getEnd()).second;
784
785 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(B);
786 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E);
787
788 // If the start or end of the range is in another file, just discard
789 // it.
790 if (BInfo.first != CaretFileID || EInfo.first != CaretFileID)
791 continue;
792
793 // Add in the length of the token, so that we cover multi-char
794 // tokens.
795 unsigned TokSize = 0;
796 if (RI->isTokenRange())
797 TokSize = Lexer::MeasureTokenLength(E, SM, LangOpts);
798
799 OS << '{' << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
800 << SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
801 << SM.getLineNumber(EInfo.first, EInfo.second) << ':'
802 << (SM.getColumnNumber(EInfo.first, EInfo.second)+TokSize)
803 << '}';
804 PrintedRange = true;
805 }
806
807 if (PrintedRange)
808 OS << ':';
809 }
810 OS << ' ';
811}
812
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000813void TextDiagnostic::emitBasicNote(StringRef Message) {
814 // FIXME: Emit this as a real note diagnostic.
815 // FIXME: Format an actual diagnostic rather than a hard coded string.
816 OS << "note: " << Message << "\n";
817}
Chandler Carrutha3028852011-10-15 23:43:53 +0000818
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000819void TextDiagnostic::emitIncludeLocation(SourceLocation Loc,
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +0000820 PresumedLoc PLoc,
821 const SourceManager &SM) {
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000822 if (DiagOpts.ShowLocation)
823 OS << "In file included from " << PLoc.getFilename() << ':'
824 << PLoc.getLine() << ":\n";
825 else
826 OS << "In included file:\n";
Chandler Carrutha3028852011-10-15 23:43:53 +0000827}
828
829/// \brief Emit a code snippet and caret line.
830///
831/// This routine emits a single line's code snippet and caret line..
832///
833/// \param Loc The location for the caret.
834/// \param Ranges The underlined ranges for this code snippet.
835/// \param Hints The FixIt hints active for this diagnostic.
Chandler Carruthab4c1da2011-10-15 23:54:09 +0000836void TextDiagnostic::emitSnippetAndCaret(
Chandler Carruthdc2f2572011-10-16 07:20:28 +0000837 SourceLocation Loc, DiagnosticsEngine::Level Level,
Chandler Carrutha3028852011-10-15 23:43:53 +0000838 SmallVectorImpl<CharSourceRange>& Ranges,
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +0000839 ArrayRef<FixItHint> Hints,
840 const SourceManager &SM) {
Chandler Carrutha3028852011-10-15 23:43:53 +0000841 assert(!Loc.isInvalid() && "must have a valid source location here");
842 assert(Loc.isFileID() && "must have a file location here");
843
Chandler Carruthdc2f2572011-10-16 07:20:28 +0000844 // If caret diagnostics are enabled and we have location, we want to
845 // emit the caret. However, we only do this if the location moved
846 // from the last diagnostic, if the last diagnostic was a note that
847 // was part of a different warning or error diagnostic, or if the
848 // diagnostic has ranges. We don't want to emit the same caret
849 // multiple times if one loc has multiple diagnostics.
850 if (!DiagOpts.ShowCarets)
851 return;
852 if (Loc == LastLoc && Ranges.empty() && Hints.empty() &&
853 (LastLevel != DiagnosticsEngine::Note || Level == LastLevel))
854 return;
855
Chandler Carrutha3028852011-10-15 23:43:53 +0000856 // Decompose the location into a FID/Offset pair.
857 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
858 FileID FID = LocInfo.first;
859 unsigned FileOffset = LocInfo.second;
860
861 // Get information about the buffer it points into.
862 bool Invalid = false;
Nico Weber35131222012-04-26 21:39:46 +0000863 const char *BufStart = SM.getBufferData(FID, &Invalid).data();
Chandler Carrutha3028852011-10-15 23:43:53 +0000864 if (Invalid)
865 return;
866
867 unsigned LineNo = SM.getLineNumber(FID, FileOffset);
868 unsigned ColNo = SM.getColumnNumber(FID, FileOffset);
869 unsigned CaretEndColNo
870 = ColNo + Lexer::MeasureTokenLength(Loc, SM, LangOpts);
871
872 // Rewind from the current position to the start of the line.
873 const char *TokPtr = BufStart+FileOffset;
874 const char *LineStart = TokPtr-ColNo+1; // Column # is 1-based.
875
876
877 // Compute the line end. Scan forward from the error position to the end of
878 // the line.
879 const char *LineEnd = TokPtr;
Nico Weber35131222012-04-26 21:39:46 +0000880 while (*LineEnd != '\n' && *LineEnd != '\r' && *LineEnd != '\0')
Chandler Carrutha3028852011-10-15 23:43:53 +0000881 ++LineEnd;
882
883 // FIXME: This shouldn't be necessary, but the CaretEndColNo can extend past
884 // the source line length as currently being computed. See
885 // test/Misc/message-length.c.
886 CaretEndColNo = std::min(CaretEndColNo, unsigned(LineEnd - LineStart));
887
888 // Copy the line of code into an std::string for ease of manipulation.
889 std::string SourceLine(LineStart, LineEnd);
890
891 // Create a line for the caret that is filled with spaces that is the same
892 // length as the line of source code.
893 std::string CaretLine(LineEnd-LineStart, ' ');
894
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000895 const SourceColumnMap sourceColMap(SourceLine, DiagOpts.TabStop);
896
Chandler Carrutha3028852011-10-15 23:43:53 +0000897 // Highlight all of the characters covered by Ranges with ~ characters.
898 for (SmallVectorImpl<CharSourceRange>::iterator I = Ranges.begin(),
899 E = Ranges.end();
900 I != E; ++I)
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +0000901 highlightRange(*I, LineNo, FID, sourceColMap, CaretLine, SM);
Chandler Carrutha3028852011-10-15 23:43:53 +0000902
903 // Next, insert the caret itself.
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000904 ColNo = sourceColMap.byteToColumn(ColNo-1);
905 if (CaretLine.size()<ColNo+1)
906 CaretLine.resize(ColNo+1, ' ');
907 CaretLine[ColNo] = '^';
Chandler Carrutha3028852011-10-15 23:43:53 +0000908
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000909 std::string FixItInsertionLine = buildFixItInsertionLine(LineNo,
910 sourceColMap,
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +0000911 Hints, SM);
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000912
913 // If the source line is too long for our terminal, select only the
914 // "interesting" source region within that line.
915 unsigned Columns = DiagOpts.MessageLength;
916 if (Columns)
917 selectInterestingSourceRegion(SourceLine, CaretLine, FixItInsertionLine,
918 Columns, sourceColMap);
Chandler Carrutha3028852011-10-15 23:43:53 +0000919
920 // If we are in -fdiagnostics-print-source-range-info mode, we are trying
921 // to produce easily machine parsable output. Add a space before the
922 // source line and the caret to make it trivial to tell the main diagnostic
923 // line from what the user is intended to see.
924 if (DiagOpts.ShowSourceRanges) {
925 SourceLine = ' ' + SourceLine;
926 CaretLine = ' ' + CaretLine;
927 }
928
Chandler Carrutha3028852011-10-15 23:43:53 +0000929 // Finally, remove any blank spaces from the end of CaretLine.
930 while (CaretLine[CaretLine.size()-1] == ' ')
931 CaretLine.erase(CaretLine.end()-1);
932
933 // Emit what we have computed.
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000934 emitSnippet(SourceLine);
Chandler Carrutha3028852011-10-15 23:43:53 +0000935
936 if (DiagOpts.ShowColors)
937 OS.changeColor(caretColor, true);
938 OS << CaretLine << '\n';
939 if (DiagOpts.ShowColors)
940 OS.resetColor();
941
942 if (!FixItInsertionLine.empty()) {
943 if (DiagOpts.ShowColors)
944 // Print fixit line in color
945 OS.changeColor(fixitColor, false);
946 if (DiagOpts.ShowSourceRanges)
947 OS << ' ';
948 OS << FixItInsertionLine << '\n';
949 if (DiagOpts.ShowColors)
950 OS.resetColor();
951 }
952
953 // Print out any parseable fixit information requested by the options.
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +0000954 emitParseableFixits(Hints, SM);
Chandler Carrutha3028852011-10-15 23:43:53 +0000955}
956
Benjamin Kramer556ab5e2012-05-01 14:34:11 +0000957void TextDiagnostic::emitSnippet(StringRef line) {
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000958 if (line.empty())
959 return;
960
961 size_t i = 0;
962
963 std::string to_print;
964 bool print_reversed = false;
965
966 while (i<line.size()) {
967 std::pair<SmallString<16>,bool> res
968 = printableTextForNextCharacter(line, &i, DiagOpts.TabStop);
969 bool was_printable = res.second;
970
Nico Weber35131222012-04-26 21:39:46 +0000971 if (DiagOpts.ShowColors && was_printable == print_reversed) {
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000972 if (print_reversed)
973 OS.reverseColor();
974 OS << to_print;
975 to_print.clear();
976 if (DiagOpts.ShowColors)
977 OS.resetColor();
978 }
979
980 print_reversed = !was_printable;
981 to_print += res.first.str();
982 }
983
984 if (print_reversed && DiagOpts.ShowColors)
985 OS.reverseColor();
986 OS << to_print;
987 if (print_reversed && DiagOpts.ShowColors)
988 OS.resetColor();
989
990 OS << '\n';
991}
992
Chandler Carrutha3028852011-10-15 23:43:53 +0000993/// \brief Highlight a SourceRange (with ~'s) for any characters on LineNo.
Chandler Carruthab4c1da2011-10-15 23:54:09 +0000994void TextDiagnostic::highlightRange(const CharSourceRange &R,
Chandler Carrutha3028852011-10-15 23:43:53 +0000995 unsigned LineNo, FileID FID,
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000996 const SourceColumnMap &map,
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +0000997 std::string &CaretLine,
998 const SourceManager &SM) {
Chandler Carrutha3028852011-10-15 23:43:53 +0000999 if (!R.isValid()) return;
1000
1001 SourceLocation Begin = SM.getExpansionLoc(R.getBegin());
1002 SourceLocation End = SM.getExpansionLoc(R.getEnd());
1003
1004 // If the End location and the start location are the same and are a macro
1005 // location, then the range was something that came from a macro expansion
1006 // or _Pragma. If this is an object-like macro, the best we can do is to
1007 // highlight the range. If this is a function-like macro, we'd also like to
1008 // highlight the arguments.
1009 if (Begin == End && R.getEnd().isMacroID())
1010 End = SM.getExpansionRange(R.getEnd()).second;
1011
1012 unsigned StartLineNo = SM.getExpansionLineNumber(Begin);
1013 if (StartLineNo > LineNo || SM.getFileID(Begin) != FID)
1014 return; // No intersection.
1015
1016 unsigned EndLineNo = SM.getExpansionLineNumber(End);
1017 if (EndLineNo < LineNo || SM.getFileID(End) != FID)
1018 return; // No intersection.
1019
1020 // Compute the column number of the start.
1021 unsigned StartColNo = 0;
1022 if (StartLineNo == LineNo) {
1023 StartColNo = SM.getExpansionColumnNumber(Begin);
1024 if (StartColNo) --StartColNo; // Zero base the col #.
1025 }
1026
1027 // Compute the column number of the end.
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001028 unsigned EndColNo = map.getSourceLine().size();
Chandler Carrutha3028852011-10-15 23:43:53 +00001029 if (EndLineNo == LineNo) {
1030 EndColNo = SM.getExpansionColumnNumber(End);
1031 if (EndColNo) {
1032 --EndColNo; // Zero base the col #.
1033
1034 // Add in the length of the token, so that we cover multi-char tokens if
1035 // this is a token range.
1036 if (R.isTokenRange())
1037 EndColNo += Lexer::MeasureTokenLength(End, SM, LangOpts);
1038 } else {
1039 EndColNo = CaretLine.size();
1040 }
1041 }
1042
1043 assert(StartColNo <= EndColNo && "Invalid range!");
1044
1045 // Check that a token range does not highlight only whitespace.
1046 if (R.isTokenRange()) {
1047 // Pick the first non-whitespace column.
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001048 while (StartColNo < map.getSourceLine().size() &&
1049 (map.getSourceLine()[StartColNo] == ' ' ||
1050 map.getSourceLine()[StartColNo] == '\t'))
Chandler Carrutha3028852011-10-15 23:43:53 +00001051 ++StartColNo;
1052
1053 // Pick the last non-whitespace column.
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001054 if (EndColNo > map.getSourceLine().size())
1055 EndColNo = map.getSourceLine().size();
Chandler Carrutha3028852011-10-15 23:43:53 +00001056 while (EndColNo-1 &&
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001057 (map.getSourceLine()[EndColNo-1] == ' ' ||
1058 map.getSourceLine()[EndColNo-1] == '\t'))
Chandler Carrutha3028852011-10-15 23:43:53 +00001059 --EndColNo;
1060
1061 // If the start/end passed each other, then we are trying to highlight a
1062 // range that just exists in whitespace, which must be some sort of other
1063 // bug.
1064 assert(StartColNo <= EndColNo && "Trying to highlight whitespace??");
1065 }
1066
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001067 assert(StartColNo <= map.getSourceLine().size() && "Invalid range!");
1068 assert(EndColNo <= map.getSourceLine().size() && "Invalid range!");
1069
Chandler Carrutha3028852011-10-15 23:43:53 +00001070 // Fill the range with ~'s.
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001071 StartColNo = map.byteToColumn(StartColNo);
1072 EndColNo = map.byteToColumn(EndColNo);
1073
1074 assert(StartColNo <= EndColNo && "Invalid range!");
1075 if (CaretLine.size() < EndColNo)
1076 CaretLine.resize(EndColNo,' ');
1077 std::fill(CaretLine.begin()+StartColNo,CaretLine.begin()+EndColNo,'~');
Chandler Carrutha3028852011-10-15 23:43:53 +00001078}
1079
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001080std::string TextDiagnostic::buildFixItInsertionLine(
1081 unsigned LineNo,
1082 const SourceColumnMap &map,
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +00001083 ArrayRef<FixItHint> Hints,
1084 const SourceManager &SM) {
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001085
Chandler Carrutha3028852011-10-15 23:43:53 +00001086 std::string FixItInsertionLine;
1087 if (Hints.empty() || !DiagOpts.ShowFixits)
1088 return FixItInsertionLine;
1089
1090 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1091 I != E; ++I) {
1092 if (!I->CodeToInsert.empty()) {
1093 // We have an insertion hint. Determine whether the inserted
1094 // code is on the same line as the caret.
1095 std::pair<FileID, unsigned> HintLocInfo
1096 = SM.getDecomposedExpansionLoc(I->RemoveRange.getBegin());
1097 if (LineNo == SM.getLineNumber(HintLocInfo.first, HintLocInfo.second)) {
1098 // Insert the new code into the line just below the code
1099 // that the user wrote.
1100 unsigned HintColNo
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001101 = SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second) - 1;
1102 // hint must start inside the source or right at the end
1103 assert(HintColNo<static_cast<unsigned>(map.bytes())+1);
1104 HintColNo = map.byteToColumn(HintColNo);
1105
1106 // FIXME: if the fixit includes tabs or other characters that do not
1107 // take up a single column per byte when displayed then
1108 // I->CodeToInsert.size() is not a column number and we're mixing
1109 // units (columns + bytes). We should get printable versions
1110 // of each fixit before using them.
Chandler Carrutha3028852011-10-15 23:43:53 +00001111 unsigned LastColumnModified
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001112 = HintColNo + I->CodeToInsert.size();
1113
1114 if (LastColumnModified > static_cast<unsigned>(map.bytes())) {
1115 unsigned LastExistingColumn = map.byteToColumn(map.bytes());
1116 unsigned AddedColumns = LastColumnModified-LastExistingColumn;
1117 LastColumnModified = LastExistingColumn + AddedColumns;
1118 } else {
1119 LastColumnModified = map.byteToColumn(LastColumnModified);
1120 }
1121
Chandler Carrutha3028852011-10-15 23:43:53 +00001122 if (LastColumnModified > FixItInsertionLine.size())
1123 FixItInsertionLine.resize(LastColumnModified, ' ');
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001124 assert(HintColNo+I->CodeToInsert.size() <= FixItInsertionLine.size());
Chandler Carrutha3028852011-10-15 23:43:53 +00001125 std::copy(I->CodeToInsert.begin(), I->CodeToInsert.end(),
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001126 FixItInsertionLine.begin() + HintColNo);
Chandler Carrutha3028852011-10-15 23:43:53 +00001127 } else {
1128 FixItInsertionLine.clear();
1129 break;
1130 }
1131 }
1132 }
1133
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001134 expandTabs(FixItInsertionLine, DiagOpts.TabStop);
Chandler Carrutha3028852011-10-15 23:43:53 +00001135
1136 return FixItInsertionLine;
1137}
1138
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +00001139void TextDiagnostic::emitParseableFixits(ArrayRef<FixItHint> Hints,
1140 const SourceManager &SM) {
Chandler Carrutha3028852011-10-15 23:43:53 +00001141 if (!DiagOpts.ShowParseableFixits)
1142 return;
1143
1144 // We follow FixItRewriter's example in not (yet) handling
1145 // fix-its in macros.
1146 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1147 I != E; ++I) {
1148 if (I->RemoveRange.isInvalid() ||
1149 I->RemoveRange.getBegin().isMacroID() ||
1150 I->RemoveRange.getEnd().isMacroID())
1151 return;
1152 }
1153
1154 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1155 I != E; ++I) {
1156 SourceLocation BLoc = I->RemoveRange.getBegin();
1157 SourceLocation ELoc = I->RemoveRange.getEnd();
1158
1159 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(BLoc);
1160 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(ELoc);
1161
1162 // Adjust for token ranges.
1163 if (I->RemoveRange.isTokenRange())
1164 EInfo.second += Lexer::MeasureTokenLength(ELoc, SM, LangOpts);
1165
1166 // We specifically do not do word-wrapping or tab-expansion here,
1167 // because this is supposed to be easy to parse.
1168 PresumedLoc PLoc = SM.getPresumedLoc(BLoc);
1169 if (PLoc.isInvalid())
1170 break;
1171
1172 OS << "fix-it:\"";
1173 OS.write_escaped(PLoc.getFilename());
1174 OS << "\":{" << SM.getLineNumber(BInfo.first, BInfo.second)
1175 << ':' << SM.getColumnNumber(BInfo.first, BInfo.second)
1176 << '-' << SM.getLineNumber(EInfo.first, EInfo.second)
1177 << ':' << SM.getColumnNumber(EInfo.first, EInfo.second)
1178 << "}:\"";
1179 OS.write_escaped(I->CodeToInsert);
1180 OS << "\"\n";
1181 }
1182}