blob: d0c3626f3cde7905afc0bb0f0aae3253b020eeeb [file] [log] [blame]
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001//===--- TextDiagnostic.cpp - Text Diagnostic Pretty-Printing -------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "clang/Frontend/TextDiagnostic.h"
11#include "clang/Basic/FileManager.h"
12#include "clang/Basic/SourceManager.h"
Seth Cantrell6749dd52012-04-18 02:44:46 +000013#include "clang/Basic/ConvertUTF.h"
Chandler Carruthdb463bb2011-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 Cantrell6749dd52012-04-18 02:44:46 +000019#include "llvm/Support/Locale.h"
Chandler Carruthdb463bb2011-10-15 23:43:53 +000020#include "llvm/ADT/SmallString.h"
Seth Cantrell6749dd52012-04-18 02:44:46 +000021#include "llvm/ADT/StringExtras.h"
Chandler Carruthdb463bb2011-10-15 23:43:53 +000022#include <algorithm>
Seth Cantrell6749dd52012-04-18 02:44:46 +000023
Chandler Carruthdb463bb2011-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 Kramerd1fda032012-05-01 14:34:11 +000043static int bytesSincePreviousTabOrLineBegin(StringRef SourceLine, size_t i) {
Seth Cantrell6749dd52012-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 Kramerd1fda032012-05-01 14:34:11 +000072static std::pair<SmallString<16>, bool>
Seth Cantrell6749dd52012-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-Gay0ddb0972012-04-18 17:25:16 +0000117 (void)res;
Seth Cantrell6749dd52012-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 Kramerd1fda032012-05-01 14:34:11 +0000149static void expandTabs(std::string &SourceLine, unsigned TabStop) {
Seth Cantrell6749dd52012-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///
James Dennett6b4f5062012-06-22 05:33:23 +0000182/// (\\u3042 is represented in UTF-8 by three bytes and takes two columns to
Seth Cantrell6749dd52012-04-18 02:44:46 +0000183/// display)
Benjamin Kramerd1fda032012-05-01 14:34:11 +0000184static void byteToColumn(StringRef SourceLine, unsigned TabStop,
185 SmallVectorImpl<int> &out) {
Seth Cantrell6749dd52012-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///
James Dennett6b4f5062012-06-22 05:33:23 +0000216/// (\\u3042 is represented in UTF-8 by three bytes and takes two columns to
Seth Cantrell6749dd52012-04-18 02:44:46 +0000217/// display)
Benjamin Kramerd1fda032012-05-01 14:34:11 +0000218static void columnToByte(StringRef SourceLine, unsigned TabStop,
Seth Cantrell6749dd52012-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 Carruthdb463bb2011-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 Carruth7531f572011-10-15 23:54:09 +0000286static void selectInterestingSourceRegion(std::string &SourceLine,
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000287 std::string &CaretLine,
288 std::string &FixItInsertionLine,
Seth Cantrell6749dd52012-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 Carruthdb463bb2011-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)
Seth Cantrell4031a372012-05-25 00:03:29 +0000310 if (!isspace(static_cast<unsigned char>(CaretLine[CaretStart])))
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000311 break;
312
313 for (; CaretEnd != CaretStart; --CaretEnd)
Seth Cantrell4031a372012-05-25 00:03:29 +0000314 if (!isspace(static_cast<unsigned char>(CaretLine[CaretEnd - 1])))
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000315 break;
316
Seth Cantrell6749dd52012-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 Carruthdb463bb2011-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)
Seth Cantrell4031a372012-05-25 00:03:29 +0000325 if (!isspace(static_cast<unsigned char>(FixItInsertionLine[FixItStart])))
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000326 break;
327
328 for (; FixItEnd != FixItStart; --FixItEnd)
Seth Cantrell4031a372012-05-25 00:03:29 +0000329 if (!isspace(static_cast<unsigned char>(FixItInsertionLine[FixItEnd - 1])))
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000330 break;
331
Seth Cantrell6749dd52012-04-18 02:44:46 +0000332 CaretStart = std::min(FixItStart, CaretStart);
333 CaretEnd = std::max(FixItEnd, CaretEnd);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000334 }
335
Seth Cantrellc5493d72012-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 Carruthdb463bb2011-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 Cantrell6749dd52012-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 Carruthdb463bb2011-10-15 23:43:53 +0000369
370 unsigned TargetColumns = Columns;
Seth Cantrell6749dd52012-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 Carruthdb463bb2011-10-15 23:43:53 +0000377 bool ExpandedRegion = false;
Seth Cantrell6749dd52012-04-18 02:44:46 +0000378
379 if (SourceStart>0) {
380 unsigned NewStart = SourceStart-1;
Chandler Carruthdb463bb2011-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 Cantrell6749dd52012-04-18 02:44:46 +0000384 while (NewStart &&
Seth Cantrell4031a372012-05-25 00:03:29 +0000385 (map.byteToColumn(NewStart)==-1 ||
386 isspace(static_cast<unsigned char>(SourceLine[NewStart]))))
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000387 --NewStart;
388
389 // Skip over this bit of "interesting" text.
Seth Cantrell6749dd52012-04-18 02:44:46 +0000390 while (NewStart &&
Seth Cantrell4031a372012-05-25 00:03:29 +0000391 (map.byteToColumn(NewStart)!=-1 &&
392 !isspace(static_cast<unsigned char>(SourceLine[NewStart]))))
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000393 --NewStart;
394
395 // Move up to the non-whitespace character we just saw.
396 if (NewStart)
397 ++NewStart;
398
Seth Cantrell6749dd52012-04-18 02:44:46 +0000399 unsigned NewColumns = map.byteToColumn(SourceEnd) -
400 map.byteToColumn(NewStart);
401 if (NewColumns <= TargetColumns) {
402 SourceStart = NewStart;
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000403 ExpandedRegion = true;
404 }
405 }
406
Seth Cantrell6749dd52012-04-18 02:44:46 +0000407 if (SourceEnd<SourceLine.size()) {
408 unsigned NewEnd = SourceEnd+1;
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000409
410 // Skip over any whitespace we see here; we're looking for
411 // another bit of interesting text.
Seth Cantrell6749dd52012-04-18 02:44:46 +0000412 while (NewEnd<SourceLine.size() &&
Seth Cantrell4031a372012-05-25 00:03:29 +0000413 (map.byteToColumn(NewEnd)==-1 ||
414 isspace(static_cast<unsigned char>(SourceLine[NewEnd]))))
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000415 ++NewEnd;
416
417 // Skip over this bit of "interesting" text.
Seth Cantrell6749dd52012-04-18 02:44:46 +0000418 while (NewEnd<SourceLine.size() &&
Seth Cantrell4031a372012-05-25 00:03:29 +0000419 (map.byteToColumn(NewEnd)!=-1 &&
420 !isspace(static_cast<unsigned char>(SourceLine[NewEnd]))))
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000421 ++NewEnd;
422
Seth Cantrell6749dd52012-04-18 02:44:46 +0000423 unsigned NewColumns = map.byteToColumn(NewEnd) -
424 map.byteToColumn(SourceStart);
425 if (NewColumns <= TargetColumns) {
426 SourceEnd = NewEnd;
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000427 ExpandedRegion = true;
428 }
429 }
430
431 if (!ExpandedRegion)
432 break;
433 }
434
Seth Cantrell6749dd52012-04-18 02:44:46 +0000435 CaretStart = map.byteToColumn(SourceStart);
436 CaretEnd = map.byteToColumn(SourceEnd) + CaretColumnsOutsideSource;
437
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000438 // [CaretStart, CaretEnd) is the slice we want. Update the various
439 // output lines to show only this slice, with two-space padding
440 // before the lines so that it looks nicer.
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000441
Seth Cantrell6749dd52012-04-18 02:44:46 +0000442 assert(CaretStart!=(unsigned)-1 && CaretEnd!=(unsigned)-1 &&
443 SourceStart!=(unsigned)-1 && SourceEnd!=(unsigned)-1);
444 assert(SourceStart <= SourceEnd);
445 assert(CaretStart <= CaretEnd);
446
447 unsigned BackColumnsRemoved
448 = map.byteToColumn(SourceLine.size())-map.byteToColumn(SourceEnd);
449 unsigned FrontColumnsRemoved = CaretStart;
450 unsigned ColumnsKept = CaretEnd-CaretStart;
451
452 // We checked up front that the line needed truncation
453 assert(FrontColumnsRemoved+ColumnsKept+BackColumnsRemoved > Columns);
454
455 // The line needs some trunctiona, and we'd prefer to keep the front
456 // if possible, so remove the back
457 if (BackColumnsRemoved)
458 SourceLine.replace(SourceEnd, std::string::npos, back_ellipse);
459
460 // If that's enough then we're done
461 if (FrontColumnsRemoved+ColumnsKept <= Columns)
462 return;
463
464 // Otherwise remove the front as well
465 if (FrontColumnsRemoved) {
466 SourceLine.replace(0, SourceStart, front_ellipse);
467 CaretLine.replace(0, CaretStart, front_space);
468 if (!FixItInsertionLine.empty())
469 FixItInsertionLine.replace(0, CaretStart, front_space);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000470 }
471}
472
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000473/// \brief Skip over whitespace in the string, starting at the given
474/// index.
475///
476/// \returns The index of the first non-whitespace character that is
477/// greater than or equal to Idx or, if no such character exists,
478/// returns the end of the string.
479static unsigned skipWhitespace(unsigned Idx, StringRef Str, unsigned Length) {
480 while (Idx < Length && isspace(Str[Idx]))
481 ++Idx;
482 return Idx;
483}
484
485/// \brief If the given character is the start of some kind of
486/// balanced punctuation (e.g., quotes or parentheses), return the
487/// character that will terminate the punctuation.
488///
489/// \returns The ending punctuation character, if any, or the NULL
490/// character if the input character does not start any punctuation.
491static inline char findMatchingPunctuation(char c) {
492 switch (c) {
493 case '\'': return '\'';
494 case '`': return '\'';
495 case '"': return '"';
496 case '(': return ')';
497 case '[': return ']';
498 case '{': return '}';
499 default: break;
500 }
501
502 return 0;
503}
504
505/// \brief Find the end of the word starting at the given offset
506/// within a string.
507///
508/// \returns the index pointing one character past the end of the
509/// word.
510static unsigned findEndOfWord(unsigned Start, StringRef Str,
511 unsigned Length, unsigned Column,
512 unsigned Columns) {
513 assert(Start < Str.size() && "Invalid start position!");
514 unsigned End = Start + 1;
515
516 // If we are already at the end of the string, take that as the word.
517 if (End == Str.size())
518 return End;
519
520 // Determine if the start of the string is actually opening
521 // punctuation, e.g., a quote or parentheses.
522 char EndPunct = findMatchingPunctuation(Str[Start]);
523 if (!EndPunct) {
524 // This is a normal word. Just find the first space character.
525 while (End < Length && !isspace(Str[End]))
526 ++End;
527 return End;
528 }
529
530 // We have the start of a balanced punctuation sequence (quotes,
531 // parentheses, etc.). Determine the full sequence is.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000532 SmallString<16> PunctuationEndStack;
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000533 PunctuationEndStack.push_back(EndPunct);
534 while (End < Length && !PunctuationEndStack.empty()) {
535 if (Str[End] == PunctuationEndStack.back())
536 PunctuationEndStack.pop_back();
537 else if (char SubEndPunct = findMatchingPunctuation(Str[End]))
538 PunctuationEndStack.push_back(SubEndPunct);
539
540 ++End;
541 }
542
543 // Find the first space character after the punctuation ended.
544 while (End < Length && !isspace(Str[End]))
545 ++End;
546
547 unsigned PunctWordLength = End - Start;
548 if (// If the word fits on this line
549 Column + PunctWordLength <= Columns ||
550 // ... or the word is "short enough" to take up the next line
551 // without too much ugly white space
552 PunctWordLength < Columns/3)
553 return End; // Take the whole thing as a single "word".
554
555 // The whole quoted/parenthesized string is too long to print as a
556 // single "word". Instead, find the "word" that starts just after
557 // the punctuation and use that end-point instead. This will recurse
558 // until it finds something small enough to consider a word.
559 return findEndOfWord(Start + 1, Str, Length, Column + 1, Columns);
560}
561
562/// \brief Print the given string to a stream, word-wrapping it to
563/// some number of columns in the process.
564///
565/// \param OS the stream to which the word-wrapping string will be
566/// emitted.
567/// \param Str the string to word-wrap and output.
568/// \param Columns the number of columns to word-wrap to.
569/// \param Column the column number at which the first character of \p
570/// Str will be printed. This will be non-zero when part of the first
571/// line has already been printed.
572/// \param Indentation the number of spaces to indent any lines beyond
573/// the first line.
574/// \returns true if word-wrapping was required, or false if the
575/// string fit on the first line.
576static bool printWordWrapped(raw_ostream &OS, StringRef Str,
577 unsigned Columns,
578 unsigned Column = 0,
579 unsigned Indentation = WordWrapIndentation) {
580 const unsigned Length = std::min(Str.find('\n'), Str.size());
581
582 // The string used to indent each line.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000583 SmallString<16> IndentStr;
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000584 IndentStr.assign(Indentation, ' ');
585 bool Wrapped = false;
586 for (unsigned WordStart = 0, WordEnd; WordStart < Length;
587 WordStart = WordEnd) {
588 // Find the beginning of the next word.
589 WordStart = skipWhitespace(WordStart, Str, Length);
590 if (WordStart == Length)
591 break;
592
593 // Find the end of this word.
594 WordEnd = findEndOfWord(WordStart, Str, Length, Column, Columns);
595
596 // Does this word fit on the current line?
597 unsigned WordLength = WordEnd - WordStart;
598 if (Column + WordLength < Columns) {
599 // This word fits on the current line; print it there.
600 if (WordStart) {
601 OS << ' ';
602 Column += 1;
603 }
604 OS << Str.substr(WordStart, WordLength);
605 Column += WordLength;
606 continue;
607 }
608
609 // This word does not fit on the current line, so wrap to the next
610 // line.
611 OS << '\n';
612 OS.write(&IndentStr[0], Indentation);
613 OS << Str.substr(WordStart, WordLength);
614 Column = Indentation + WordLength;
615 Wrapped = true;
616 }
617
618 // Append any remaning text from the message with its existing formatting.
619 OS << Str.substr(Length);
620
621 return Wrapped;
622}
623
624TextDiagnostic::TextDiagnostic(raw_ostream &OS,
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000625 const LangOptions &LangOpts,
Chandler Carruth21a869a2011-10-16 02:57:39 +0000626 const DiagnosticOptions &DiagOpts)
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000627 : DiagnosticRenderer(LangOpts, DiagOpts), OS(OS) {}
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000628
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000629TextDiagnostic::~TextDiagnostic() {}
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000630
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000631void
632TextDiagnostic::emitDiagnosticMessage(SourceLocation Loc,
633 PresumedLoc PLoc,
634 DiagnosticsEngine::Level Level,
635 StringRef Message,
636 ArrayRef<clang::CharSourceRange> Ranges,
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000637 const SourceManager *SM,
Ted Kremenek8be51ea2012-02-14 02:46:00 +0000638 DiagOrStoredDiag D) {
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000639 uint64_t StartOfLocationInfo = OS.tell();
640
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000641 // Emit the location of this particular diagnostic.
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000642 if (Loc.isValid())
643 emitDiagnosticLoc(Loc, PLoc, Level, Ranges, *SM);
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000644
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000645 if (DiagOpts.ShowColors)
646 OS.resetColor();
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000647
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000648 printDiagnosticLevel(OS, Level, DiagOpts.ShowColors);
649 printDiagnosticMessage(OS, Level, Message,
650 OS.tell() - StartOfLocationInfo,
651 DiagOpts.MessageLength, DiagOpts.ShowColors);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000652}
653
Chandler Carruth6ddd8872011-10-15 23:48:02 +0000654/*static*/ void
655TextDiagnostic::printDiagnosticLevel(raw_ostream &OS,
656 DiagnosticsEngine::Level Level,
657 bool ShowColors) {
658 if (ShowColors) {
659 // Print diagnostic category in bold and color
660 switch (Level) {
661 case DiagnosticsEngine::Ignored:
662 llvm_unreachable("Invalid diagnostic type");
663 case DiagnosticsEngine::Note: OS.changeColor(noteColor, true); break;
664 case DiagnosticsEngine::Warning: OS.changeColor(warningColor, true); break;
665 case DiagnosticsEngine::Error: OS.changeColor(errorColor, true); break;
666 case DiagnosticsEngine::Fatal: OS.changeColor(fatalColor, true); break;
667 }
668 }
669
670 switch (Level) {
671 case DiagnosticsEngine::Ignored:
672 llvm_unreachable("Invalid diagnostic type");
673 case DiagnosticsEngine::Note: OS << "note: "; break;
674 case DiagnosticsEngine::Warning: OS << "warning: "; break;
675 case DiagnosticsEngine::Error: OS << "error: "; break;
676 case DiagnosticsEngine::Fatal: OS << "fatal error: "; break;
677 }
678
679 if (ShowColors)
680 OS.resetColor();
681}
682
683/*static*/ void
684TextDiagnostic::printDiagnosticMessage(raw_ostream &OS,
685 DiagnosticsEngine::Level Level,
686 StringRef Message,
687 unsigned CurrentColumn, unsigned Columns,
688 bool ShowColors) {
689 if (ShowColors) {
690 // Print warnings, errors and fatal errors in bold, no color
691 switch (Level) {
692 case DiagnosticsEngine::Warning: OS.changeColor(savedColor, true); break;
693 case DiagnosticsEngine::Error: OS.changeColor(savedColor, true); break;
694 case DiagnosticsEngine::Fatal: OS.changeColor(savedColor, true); break;
695 default: break; //don't bold notes
696 }
697 }
698
699 if (Columns)
700 printWordWrapped(OS, Message, Columns, CurrentColumn);
701 else
702 OS << Message;
703
704 if (ShowColors)
705 OS.resetColor();
706 OS << '\n';
707}
708
Chandler Carruth6ddd8872011-10-15 23:48:02 +0000709/// \brief Print out the file/line/column information and include trace.
710///
711/// This method handlen the emission of the diagnostic location information.
712/// This includes extracting as much location information as is present for
713/// the diagnostic and printing it, as well as any include stack or source
714/// ranges necessary.
Chandler Carruth7531f572011-10-15 23:54:09 +0000715void TextDiagnostic::emitDiagnosticLoc(SourceLocation Loc, PresumedLoc PLoc,
Chandler Carruth6ddd8872011-10-15 23:48:02 +0000716 DiagnosticsEngine::Level Level,
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000717 ArrayRef<CharSourceRange> Ranges,
718 const SourceManager &SM) {
Chandler Carruth6ddd8872011-10-15 23:48:02 +0000719 if (PLoc.isInvalid()) {
720 // At least print the file name if available:
721 FileID FID = SM.getFileID(Loc);
722 if (!FID.isInvalid()) {
723 const FileEntry* FE = SM.getFileEntryForID(FID);
724 if (FE && FE->getName()) {
725 OS << FE->getName();
726 if (FE->getDevice() == 0 && FE->getInode() == 0
727 && FE->getFileMode() == 0) {
728 // in PCH is a guess, but a good one:
729 OS << " (in PCH)";
730 }
731 OS << ": ";
732 }
733 }
734 return;
735 }
736 unsigned LineNo = PLoc.getLine();
737
738 if (!DiagOpts.ShowLocation)
739 return;
740
741 if (DiagOpts.ShowColors)
742 OS.changeColor(savedColor, true);
743
744 OS << PLoc.getFilename();
745 switch (DiagOpts.Format) {
746 case DiagnosticOptions::Clang: OS << ':' << LineNo; break;
747 case DiagnosticOptions::Msvc: OS << '(' << LineNo; break;
748 case DiagnosticOptions::Vi: OS << " +" << LineNo; break;
749 }
750
751 if (DiagOpts.ShowColumn)
752 // Compute the column number.
753 if (unsigned ColNo = PLoc.getColumn()) {
754 if (DiagOpts.Format == DiagnosticOptions::Msvc) {
755 OS << ',';
756 ColNo--;
757 } else
758 OS << ':';
759 OS << ColNo;
760 }
761 switch (DiagOpts.Format) {
762 case DiagnosticOptions::Clang:
763 case DiagnosticOptions::Vi: OS << ':'; break;
764 case DiagnosticOptions::Msvc: OS << ") : "; break;
765 }
766
767 if (DiagOpts.ShowSourceRanges && !Ranges.empty()) {
768 FileID CaretFileID =
769 SM.getFileID(SM.getExpansionLoc(Loc));
770 bool PrintedRange = false;
771
772 for (ArrayRef<CharSourceRange>::const_iterator RI = Ranges.begin(),
773 RE = Ranges.end();
774 RI != RE; ++RI) {
775 // Ignore invalid ranges.
776 if (!RI->isValid()) continue;
777
778 SourceLocation B = SM.getExpansionLoc(RI->getBegin());
779 SourceLocation E = SM.getExpansionLoc(RI->getEnd());
780
781 // If the End location and the start location are the same and are a
782 // macro location, then the range was something that came from a
783 // macro expansion or _Pragma. If this is an object-like macro, the
784 // best we can do is to highlight the range. If this is a
785 // function-like macro, we'd also like to highlight the arguments.
786 if (B == E && RI->getEnd().isMacroID())
787 E = SM.getExpansionRange(RI->getEnd()).second;
788
789 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(B);
790 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E);
791
792 // If the start or end of the range is in another file, just discard
793 // it.
794 if (BInfo.first != CaretFileID || EInfo.first != CaretFileID)
795 continue;
796
797 // Add in the length of the token, so that we cover multi-char
798 // tokens.
799 unsigned TokSize = 0;
800 if (RI->isTokenRange())
801 TokSize = Lexer::MeasureTokenLength(E, SM, LangOpts);
802
803 OS << '{' << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
804 << SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
805 << SM.getLineNumber(EInfo.first, EInfo.second) << ':'
806 << (SM.getColumnNumber(EInfo.first, EInfo.second)+TokSize)
807 << '}';
808 PrintedRange = true;
809 }
810
811 if (PrintedRange)
812 OS << ':';
813 }
814 OS << ' ';
815}
816
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000817void TextDiagnostic::emitBasicNote(StringRef Message) {
818 // FIXME: Emit this as a real note diagnostic.
819 // FIXME: Format an actual diagnostic rather than a hard coded string.
820 OS << "note: " << Message << "\n";
821}
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000822
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000823void TextDiagnostic::emitIncludeLocation(SourceLocation Loc,
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000824 PresumedLoc PLoc,
825 const SourceManager &SM) {
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000826 if (DiagOpts.ShowLocation)
827 OS << "In file included from " << PLoc.getFilename() << ':'
828 << PLoc.getLine() << ":\n";
829 else
830 OS << "In included file:\n";
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000831}
832
833/// \brief Emit a code snippet and caret line.
834///
835/// This routine emits a single line's code snippet and caret line..
836///
837/// \param Loc The location for the caret.
838/// \param Ranges The underlined ranges for this code snippet.
839/// \param Hints The FixIt hints active for this diagnostic.
Chandler Carruth7531f572011-10-15 23:54:09 +0000840void TextDiagnostic::emitSnippetAndCaret(
Chandler Carruth4ba55652011-10-16 07:20:28 +0000841 SourceLocation Loc, DiagnosticsEngine::Level Level,
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000842 SmallVectorImpl<CharSourceRange>& Ranges,
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000843 ArrayRef<FixItHint> Hints,
844 const SourceManager &SM) {
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000845 assert(!Loc.isInvalid() && "must have a valid source location here");
846 assert(Loc.isFileID() && "must have a file location here");
847
Chandler Carruth4ba55652011-10-16 07:20:28 +0000848 // If caret diagnostics are enabled and we have location, we want to
849 // emit the caret. However, we only do this if the location moved
850 // from the last diagnostic, if the last diagnostic was a note that
851 // was part of a different warning or error diagnostic, or if the
852 // diagnostic has ranges. We don't want to emit the same caret
853 // multiple times if one loc has multiple diagnostics.
854 if (!DiagOpts.ShowCarets)
855 return;
856 if (Loc == LastLoc && Ranges.empty() && Hints.empty() &&
857 (LastLevel != DiagnosticsEngine::Note || Level == LastLevel))
858 return;
859
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000860 // Decompose the location into a FID/Offset pair.
861 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
862 FileID FID = LocInfo.first;
863 unsigned FileOffset = LocInfo.second;
864
865 // Get information about the buffer it points into.
866 bool Invalid = false;
Nico Weber40d8e972012-04-26 21:39:46 +0000867 const char *BufStart = SM.getBufferData(FID, &Invalid).data();
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000868 if (Invalid)
869 return;
870
871 unsigned LineNo = SM.getLineNumber(FID, FileOffset);
872 unsigned ColNo = SM.getColumnNumber(FID, FileOffset);
873 unsigned CaretEndColNo
874 = ColNo + Lexer::MeasureTokenLength(Loc, SM, LangOpts);
875
876 // Rewind from the current position to the start of the line.
877 const char *TokPtr = BufStart+FileOffset;
878 const char *LineStart = TokPtr-ColNo+1; // Column # is 1-based.
879
880
881 // Compute the line end. Scan forward from the error position to the end of
882 // the line.
883 const char *LineEnd = TokPtr;
Nico Weber40d8e972012-04-26 21:39:46 +0000884 while (*LineEnd != '\n' && *LineEnd != '\r' && *LineEnd != '\0')
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000885 ++LineEnd;
886
887 // FIXME: This shouldn't be necessary, but the CaretEndColNo can extend past
888 // the source line length as currently being computed. See
889 // test/Misc/message-length.c.
890 CaretEndColNo = std::min(CaretEndColNo, unsigned(LineEnd - LineStart));
891
892 // Copy the line of code into an std::string for ease of manipulation.
893 std::string SourceLine(LineStart, LineEnd);
894
895 // Create a line for the caret that is filled with spaces that is the same
896 // length as the line of source code.
897 std::string CaretLine(LineEnd-LineStart, ' ');
898
Seth Cantrell6749dd52012-04-18 02:44:46 +0000899 const SourceColumnMap sourceColMap(SourceLine, DiagOpts.TabStop);
900
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000901 // Highlight all of the characters covered by Ranges with ~ characters.
902 for (SmallVectorImpl<CharSourceRange>::iterator I = Ranges.begin(),
903 E = Ranges.end();
904 I != E; ++I)
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000905 highlightRange(*I, LineNo, FID, sourceColMap, CaretLine, SM);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000906
907 // Next, insert the caret itself.
Seth Cantrell6749dd52012-04-18 02:44:46 +0000908 ColNo = sourceColMap.byteToColumn(ColNo-1);
909 if (CaretLine.size()<ColNo+1)
910 CaretLine.resize(ColNo+1, ' ');
911 CaretLine[ColNo] = '^';
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000912
Seth Cantrell6749dd52012-04-18 02:44:46 +0000913 std::string FixItInsertionLine = buildFixItInsertionLine(LineNo,
914 sourceColMap,
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000915 Hints, SM);
Seth Cantrell6749dd52012-04-18 02:44:46 +0000916
917 // If the source line is too long for our terminal, select only the
918 // "interesting" source region within that line.
919 unsigned Columns = DiagOpts.MessageLength;
920 if (Columns)
921 selectInterestingSourceRegion(SourceLine, CaretLine, FixItInsertionLine,
922 Columns, sourceColMap);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000923
924 // If we are in -fdiagnostics-print-source-range-info mode, we are trying
925 // to produce easily machine parsable output. Add a space before the
926 // source line and the caret to make it trivial to tell the main diagnostic
927 // line from what the user is intended to see.
928 if (DiagOpts.ShowSourceRanges) {
929 SourceLine = ' ' + SourceLine;
930 CaretLine = ' ' + CaretLine;
931 }
932
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000933 // Finally, remove any blank spaces from the end of CaretLine.
934 while (CaretLine[CaretLine.size()-1] == ' ')
935 CaretLine.erase(CaretLine.end()-1);
936
937 // Emit what we have computed.
Seth Cantrell6749dd52012-04-18 02:44:46 +0000938 emitSnippet(SourceLine);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000939
940 if (DiagOpts.ShowColors)
941 OS.changeColor(caretColor, true);
942 OS << CaretLine << '\n';
943 if (DiagOpts.ShowColors)
944 OS.resetColor();
945
946 if (!FixItInsertionLine.empty()) {
947 if (DiagOpts.ShowColors)
948 // Print fixit line in color
949 OS.changeColor(fixitColor, false);
950 if (DiagOpts.ShowSourceRanges)
951 OS << ' ';
952 OS << FixItInsertionLine << '\n';
953 if (DiagOpts.ShowColors)
954 OS.resetColor();
955 }
956
957 // Print out any parseable fixit information requested by the options.
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000958 emitParseableFixits(Hints, SM);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000959}
960
Benjamin Kramerd1fda032012-05-01 14:34:11 +0000961void TextDiagnostic::emitSnippet(StringRef line) {
Seth Cantrell6749dd52012-04-18 02:44:46 +0000962 if (line.empty())
963 return;
964
965 size_t i = 0;
966
967 std::string to_print;
968 bool print_reversed = false;
969
970 while (i<line.size()) {
971 std::pair<SmallString<16>,bool> res
972 = printableTextForNextCharacter(line, &i, DiagOpts.TabStop);
973 bool was_printable = res.second;
974
Nico Weber40d8e972012-04-26 21:39:46 +0000975 if (DiagOpts.ShowColors && was_printable == print_reversed) {
Seth Cantrell6749dd52012-04-18 02:44:46 +0000976 if (print_reversed)
977 OS.reverseColor();
978 OS << to_print;
979 to_print.clear();
980 if (DiagOpts.ShowColors)
981 OS.resetColor();
982 }
983
984 print_reversed = !was_printable;
985 to_print += res.first.str();
986 }
987
988 if (print_reversed && DiagOpts.ShowColors)
989 OS.reverseColor();
990 OS << to_print;
991 if (print_reversed && DiagOpts.ShowColors)
992 OS.resetColor();
993
994 OS << '\n';
995}
996
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000997/// \brief Highlight a SourceRange (with ~'s) for any characters on LineNo.
Chandler Carruth7531f572011-10-15 23:54:09 +0000998void TextDiagnostic::highlightRange(const CharSourceRange &R,
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000999 unsigned LineNo, FileID FID,
Seth Cantrell6749dd52012-04-18 02:44:46 +00001000 const SourceColumnMap &map,
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +00001001 std::string &CaretLine,
1002 const SourceManager &SM) {
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001003 if (!R.isValid()) return;
1004
1005 SourceLocation Begin = SM.getExpansionLoc(R.getBegin());
1006 SourceLocation End = SM.getExpansionLoc(R.getEnd());
1007
1008 // If the End location and the start location are the same and are a macro
1009 // location, then the range was something that came from a macro expansion
1010 // or _Pragma. If this is an object-like macro, the best we can do is to
1011 // highlight the range. If this is a function-like macro, we'd also like to
1012 // highlight the arguments.
1013 if (Begin == End && R.getEnd().isMacroID())
1014 End = SM.getExpansionRange(R.getEnd()).second;
1015
1016 unsigned StartLineNo = SM.getExpansionLineNumber(Begin);
1017 if (StartLineNo > LineNo || SM.getFileID(Begin) != FID)
1018 return; // No intersection.
1019
1020 unsigned EndLineNo = SM.getExpansionLineNumber(End);
1021 if (EndLineNo < LineNo || SM.getFileID(End) != FID)
1022 return; // No intersection.
1023
1024 // Compute the column number of the start.
1025 unsigned StartColNo = 0;
1026 if (StartLineNo == LineNo) {
1027 StartColNo = SM.getExpansionColumnNumber(Begin);
1028 if (StartColNo) --StartColNo; // Zero base the col #.
1029 }
1030
1031 // Compute the column number of the end.
Seth Cantrell6749dd52012-04-18 02:44:46 +00001032 unsigned EndColNo = map.getSourceLine().size();
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001033 if (EndLineNo == LineNo) {
1034 EndColNo = SM.getExpansionColumnNumber(End);
1035 if (EndColNo) {
1036 --EndColNo; // Zero base the col #.
1037
1038 // Add in the length of the token, so that we cover multi-char tokens if
1039 // this is a token range.
1040 if (R.isTokenRange())
1041 EndColNo += Lexer::MeasureTokenLength(End, SM, LangOpts);
1042 } else {
1043 EndColNo = CaretLine.size();
1044 }
1045 }
1046
1047 assert(StartColNo <= EndColNo && "Invalid range!");
1048
1049 // Check that a token range does not highlight only whitespace.
1050 if (R.isTokenRange()) {
1051 // Pick the first non-whitespace column.
Seth Cantrell6749dd52012-04-18 02:44:46 +00001052 while (StartColNo < map.getSourceLine().size() &&
1053 (map.getSourceLine()[StartColNo] == ' ' ||
1054 map.getSourceLine()[StartColNo] == '\t'))
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001055 ++StartColNo;
1056
1057 // Pick the last non-whitespace column.
Seth Cantrell6749dd52012-04-18 02:44:46 +00001058 if (EndColNo > map.getSourceLine().size())
1059 EndColNo = map.getSourceLine().size();
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001060 while (EndColNo-1 &&
Seth Cantrell6749dd52012-04-18 02:44:46 +00001061 (map.getSourceLine()[EndColNo-1] == ' ' ||
1062 map.getSourceLine()[EndColNo-1] == '\t'))
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001063 --EndColNo;
1064
1065 // If the start/end passed each other, then we are trying to highlight a
1066 // range that just exists in whitespace, which must be some sort of other
1067 // bug.
1068 assert(StartColNo <= EndColNo && "Trying to highlight whitespace??");
1069 }
1070
Seth Cantrell6749dd52012-04-18 02:44:46 +00001071 assert(StartColNo <= map.getSourceLine().size() && "Invalid range!");
1072 assert(EndColNo <= map.getSourceLine().size() && "Invalid range!");
1073
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001074 // Fill the range with ~'s.
Seth Cantrell6749dd52012-04-18 02:44:46 +00001075 StartColNo = map.byteToColumn(StartColNo);
1076 EndColNo = map.byteToColumn(EndColNo);
1077
1078 assert(StartColNo <= EndColNo && "Invalid range!");
1079 if (CaretLine.size() < EndColNo)
1080 CaretLine.resize(EndColNo,' ');
1081 std::fill(CaretLine.begin()+StartColNo,CaretLine.begin()+EndColNo,'~');
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001082}
1083
Seth Cantrell6749dd52012-04-18 02:44:46 +00001084std::string TextDiagnostic::buildFixItInsertionLine(
1085 unsigned LineNo,
1086 const SourceColumnMap &map,
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +00001087 ArrayRef<FixItHint> Hints,
1088 const SourceManager &SM) {
Seth Cantrell6749dd52012-04-18 02:44:46 +00001089
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001090 std::string FixItInsertionLine;
1091 if (Hints.empty() || !DiagOpts.ShowFixits)
1092 return FixItInsertionLine;
Jordan Rose3772c9a2012-06-08 21:14:19 +00001093 unsigned PrevHintEnd = 0;
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001094
1095 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1096 I != E; ++I) {
1097 if (!I->CodeToInsert.empty()) {
1098 // We have an insertion hint. Determine whether the inserted
1099 // code is on the same line as the caret.
1100 std::pair<FileID, unsigned> HintLocInfo
1101 = SM.getDecomposedExpansionLoc(I->RemoveRange.getBegin());
1102 if (LineNo == SM.getLineNumber(HintLocInfo.first, HintLocInfo.second)) {
1103 // Insert the new code into the line just below the code
1104 // that the user wrote.
1105 unsigned HintColNo
Seth Cantrell6749dd52012-04-18 02:44:46 +00001106 = SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second) - 1;
1107 // hint must start inside the source or right at the end
1108 assert(HintColNo<static_cast<unsigned>(map.bytes())+1);
1109 HintColNo = map.byteToColumn(HintColNo);
1110
Jordan Rose3772c9a2012-06-08 21:14:19 +00001111 // If we inserted a long previous hint, push this one forwards, and add
1112 // an extra space to show that this is not part of the previous
1113 // completion. This is sort of the best we can do when two hints appear
1114 // to overlap.
1115 //
1116 // Note that if this hint is located immediately after the previous
1117 // hint, no space will be added, since the location is more important.
1118 if (HintColNo < PrevHintEnd)
1119 HintColNo = PrevHintEnd + 1;
1120
Seth Cantrell6749dd52012-04-18 02:44:46 +00001121 // FIXME: if the fixit includes tabs or other characters that do not
1122 // take up a single column per byte when displayed then
1123 // I->CodeToInsert.size() is not a column number and we're mixing
1124 // units (columns + bytes). We should get printable versions
1125 // of each fixit before using them.
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001126 unsigned LastColumnModified
Seth Cantrell6749dd52012-04-18 02:44:46 +00001127 = HintColNo + I->CodeToInsert.size();
1128
Jordan Rose3772c9a2012-06-08 21:14:19 +00001129 if (LastColumnModified <= static_cast<unsigned>(map.bytes()))
Seth Cantrell6749dd52012-04-18 02:44:46 +00001130 LastColumnModified = map.byteToColumn(LastColumnModified);
Seth Cantrell6749dd52012-04-18 02:44:46 +00001131
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001132 if (LastColumnModified > FixItInsertionLine.size())
1133 FixItInsertionLine.resize(LastColumnModified, ' ');
Seth Cantrell6749dd52012-04-18 02:44:46 +00001134 assert(HintColNo+I->CodeToInsert.size() <= FixItInsertionLine.size());
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001135 std::copy(I->CodeToInsert.begin(), I->CodeToInsert.end(),
Seth Cantrell6749dd52012-04-18 02:44:46 +00001136 FixItInsertionLine.begin() + HintColNo);
Jordan Rose3772c9a2012-06-08 21:14:19 +00001137
1138 PrevHintEnd = LastColumnModified;
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001139 } else {
1140 FixItInsertionLine.clear();
1141 break;
1142 }
1143 }
1144 }
1145
Seth Cantrell6749dd52012-04-18 02:44:46 +00001146 expandTabs(FixItInsertionLine, DiagOpts.TabStop);
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001147
1148 return FixItInsertionLine;
1149}
1150
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +00001151void TextDiagnostic::emitParseableFixits(ArrayRef<FixItHint> Hints,
1152 const SourceManager &SM) {
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001153 if (!DiagOpts.ShowParseableFixits)
1154 return;
1155
1156 // We follow FixItRewriter's example in not (yet) handling
1157 // fix-its in macros.
1158 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1159 I != E; ++I) {
1160 if (I->RemoveRange.isInvalid() ||
1161 I->RemoveRange.getBegin().isMacroID() ||
1162 I->RemoveRange.getEnd().isMacroID())
1163 return;
1164 }
1165
1166 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1167 I != E; ++I) {
1168 SourceLocation BLoc = I->RemoveRange.getBegin();
1169 SourceLocation ELoc = I->RemoveRange.getEnd();
1170
1171 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(BLoc);
1172 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(ELoc);
1173
1174 // Adjust for token ranges.
1175 if (I->RemoveRange.isTokenRange())
1176 EInfo.second += Lexer::MeasureTokenLength(ELoc, SM, LangOpts);
1177
1178 // We specifically do not do word-wrapping or tab-expansion here,
1179 // because this is supposed to be easy to parse.
1180 PresumedLoc PLoc = SM.getPresumedLoc(BLoc);
1181 if (PLoc.isInvalid())
1182 break;
1183
1184 OS << "fix-it:\"";
1185 OS.write_escaped(PLoc.getFilename());
1186 OS << "\":{" << SM.getLineNumber(BInfo.first, BInfo.second)
1187 << ':' << SM.getColumnNumber(BInfo.first, BInfo.second)
1188 << '-' << SM.getLineNumber(EInfo.first, EInfo.second)
1189 << ':' << SM.getColumnNumber(EInfo.first, EInfo.second)
1190 << "}:\"";
1191 OS.write_escaped(I->CodeToInsert);
1192 OS << "\"\n";
1193 }
1194}