blob: ae1396672b77fa99dc974b71a660359e9979e7be [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;
Richard Trieu246b6aa2012-06-26 18:18:47 +000034static const enum raw_ostream::Colors templateColor =
35 raw_ostream::CYAN;
Chandler Carruthdb463bb2011-10-15 23:43:53 +000036static const enum raw_ostream::Colors errorColor = raw_ostream::RED;
37static const enum raw_ostream::Colors fatalColor = raw_ostream::RED;
38// Used for changing only the bold attribute.
39static const enum raw_ostream::Colors savedColor =
40 raw_ostream::SAVEDCOLOR;
41
Richard Trieu246b6aa2012-06-26 18:18:47 +000042/// \brief Add highlights to differences in template strings.
43static void applyTemplateHighlighting(raw_ostream &OS, StringRef Str,
Richard Trieub956e5a2012-06-28 22:39:03 +000044 bool &Normal, bool Bold) {
Richard Trieu246b6aa2012-06-26 18:18:47 +000045 for (unsigned i = 0, e = Str.size(); i < e; ++i)
46 if (Str[i] != ToggleHighlight) {
47 OS << Str[i];
48 } else {
49 if (Normal)
50 OS.changeColor(templateColor, true);
Richard Trieub956e5a2012-06-28 22:39:03 +000051 else {
Richard Trieu246b6aa2012-06-26 18:18:47 +000052 OS.resetColor();
Richard Trieub956e5a2012-06-28 22:39:03 +000053 if (Bold)
54 OS.changeColor(savedColor, true);
55 }
Richard Trieu246b6aa2012-06-26 18:18:47 +000056 Normal = !Normal;
57 }
58}
59
Chandler Carruthdb463bb2011-10-15 23:43:53 +000060/// \brief Number of spaces to indent when word-wrapping.
61const unsigned WordWrapIndentation = 6;
62
Benjamin Kramerd1fda032012-05-01 14:34:11 +000063static int bytesSincePreviousTabOrLineBegin(StringRef SourceLine, size_t i) {
Seth Cantrell6749dd52012-04-18 02:44:46 +000064 int bytes = 0;
65 while (0<i) {
66 if (SourceLine[--i]=='\t')
67 break;
68 ++bytes;
69 }
70 return bytes;
71}
72
73/// \brief returns a printable representation of first item from input range
74///
75/// This function returns a printable representation of the next item in a line
76/// of source. If the next byte begins a valid and printable character, that
77/// character is returned along with 'true'.
78///
79/// Otherwise, if the next byte begins a valid, but unprintable character, a
80/// printable, escaped representation of the character is returned, along with
81/// 'false'. Otherwise a printable, escaped representation of the next byte
82/// is returned along with 'false'.
83///
84/// \note The index is updated to be used with a subsequent call to
85/// printableTextForNextCharacter.
86///
87/// \param SourceLine The line of source
88/// \param i Pointer to byte index,
89/// \param TabStop used to expand tabs
90/// \return pair(printable text, 'true' iff original text was printable)
91///
Benjamin Kramerd1fda032012-05-01 14:34:11 +000092static std::pair<SmallString<16>, bool>
Seth Cantrell6749dd52012-04-18 02:44:46 +000093printableTextForNextCharacter(StringRef SourceLine, size_t *i,
94 unsigned TabStop) {
95 assert(i && "i must not be null");
96 assert(*i<SourceLine.size() && "must point to a valid index");
97
98 if (SourceLine[*i]=='\t') {
99 assert(0 < TabStop && TabStop <= DiagnosticOptions::MaxTabStop &&
100 "Invalid -ftabstop value");
101 unsigned col = bytesSincePreviousTabOrLineBegin(SourceLine, *i);
102 unsigned NumSpaces = TabStop - col%TabStop;
103 assert(0 < NumSpaces && NumSpaces <= TabStop
104 && "Invalid computation of space amt");
105 ++(*i);
106
107 SmallString<16> expandedTab;
108 expandedTab.assign(NumSpaces, ' ');
109 return std::make_pair(expandedTab, true);
110 }
111
112 // FIXME: this data is copied from the private implementation of ConvertUTF.h
113 static const char trailingBytesForUTF8[256] = {
114 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
115 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
116 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
117 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,
118 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,
119 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,
120 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,
121 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
122 };
123
124 unsigned char const *begin, *end;
125 begin = reinterpret_cast<unsigned char const *>(&*(SourceLine.begin() + *i));
126 end = begin + SourceLine.size();
127
128 if (isLegalUTF8Sequence(begin, end)) {
129 UTF32 c;
130 UTF32 *cptr = &c;
131 unsigned char const *original_begin = begin;
132 char trailingBytes = trailingBytesForUTF8[(unsigned char)SourceLine[*i]];
133 unsigned char const *cp_end = begin+trailingBytes+1;
134
135 ConversionResult res = ConvertUTF8toUTF32(&begin, cp_end, &cptr, cptr+1,
136 strictConversion);
Matt Beaumont-Gay0ddb0972012-04-18 17:25:16 +0000137 (void)res;
Seth Cantrell6749dd52012-04-18 02:44:46 +0000138 assert(conversionOK==res);
139 assert(0 < begin-original_begin
140 && "we must be further along in the string now");
141 *i += begin-original_begin;
142
143 if (!llvm::sys::locale::isPrint(c)) {
144 // If next character is valid UTF-8, but not printable
145 SmallString<16> expandedCP("<U+>");
146 while (c) {
147 expandedCP.insert(expandedCP.begin()+3, llvm::hexdigit(c%16));
148 c/=16;
149 }
150 while (expandedCP.size() < 8)
151 expandedCP.insert(expandedCP.begin()+3, llvm::hexdigit(0));
152 return std::make_pair(expandedCP, false);
153 }
154
155 // If next character is valid UTF-8, and printable
156 return std::make_pair(SmallString<16>(original_begin, cp_end), true);
157
158 }
159
160 // If next byte is not valid UTF-8 (and therefore not printable)
161 SmallString<16> expandedByte("<XX>");
162 unsigned char byte = SourceLine[*i];
163 expandedByte[1] = llvm::hexdigit(byte / 16);
164 expandedByte[2] = llvm::hexdigit(byte % 16);
165 ++(*i);
166 return std::make_pair(expandedByte, false);
167}
168
Benjamin Kramerd1fda032012-05-01 14:34:11 +0000169static void expandTabs(std::string &SourceLine, unsigned TabStop) {
Seth Cantrell6749dd52012-04-18 02:44:46 +0000170 size_t i = SourceLine.size();
171 while (i>0) {
172 i--;
173 if (SourceLine[i]!='\t')
174 continue;
175 size_t tmp_i = i;
176 std::pair<SmallString<16>,bool> res
177 = printableTextForNextCharacter(SourceLine, &tmp_i, TabStop);
178 SourceLine.replace(i, 1, res.first.c_str());
179 }
180}
181
182/// This function takes a raw source line and produces a mapping from the bytes
183/// of the printable representation of the line to the columns those printable
184/// characters will appear at (numbering the first column as 0).
185///
186/// If a byte 'i' corresponds to muliple columns (e.g. the byte contains a tab
187/// character) then the the array will map that byte to the first column the
188/// tab appears at and the next value in the map will have been incremented
189/// more than once.
190///
191/// If a byte is the first in a sequence of bytes that together map to a single
192/// entity in the output, then the array will map that byte to the appropriate
193/// column while the subsequent bytes will be -1.
194///
195/// The last element in the array does not correspond to any byte in the input
196/// and instead is the number of columns needed to display the source
197///
198/// example: (given a tabstop of 8)
199///
200/// "a \t \u3042" -> {0,1,2,8,9,-1,-1,11}
201///
James Dennett6b4f5062012-06-22 05:33:23 +0000202/// (\\u3042 is represented in UTF-8 by three bytes and takes two columns to
Seth Cantrell6749dd52012-04-18 02:44:46 +0000203/// display)
Benjamin Kramerd1fda032012-05-01 14:34:11 +0000204static void byteToColumn(StringRef SourceLine, unsigned TabStop,
205 SmallVectorImpl<int> &out) {
Seth Cantrell6749dd52012-04-18 02:44:46 +0000206 out.clear();
207
208 if (SourceLine.empty()) {
209 out.resize(1u,0);
210 return;
211 }
212
213 out.resize(SourceLine.size()+1, -1);
214
215 int columns = 0;
216 size_t i = 0;
217 while (i<SourceLine.size()) {
218 out[i] = columns;
219 std::pair<SmallString<16>,bool> res
220 = printableTextForNextCharacter(SourceLine, &i, TabStop);
221 columns += llvm::sys::locale::columnWidth(res.first);
222 }
223 out.back() = columns;
224}
225
226/// This function takes a raw source line and produces a mapping from columns
227/// to the byte of the source line that produced the character displaying at
228/// that column. This is the inverse of the mapping produced by byteToColumn()
229///
230/// The last element in the array is the number of bytes in the source string
231///
232/// example: (given a tabstop of 8)
233///
234/// "a \t \u3042" -> {0,1,2,-1,-1,-1,-1,-1,3,4,-1,7}
235///
James Dennett6b4f5062012-06-22 05:33:23 +0000236/// (\\u3042 is represented in UTF-8 by three bytes and takes two columns to
Seth Cantrell6749dd52012-04-18 02:44:46 +0000237/// display)
Benjamin Kramerd1fda032012-05-01 14:34:11 +0000238static void columnToByte(StringRef SourceLine, unsigned TabStop,
Seth Cantrell6749dd52012-04-18 02:44:46 +0000239 SmallVectorImpl<int> &out) {
240 out.clear();
241
242 if (SourceLine.empty()) {
243 out.resize(1u, 0);
244 return;
245 }
246
247 int columns = 0;
248 size_t i = 0;
249 while (i<SourceLine.size()) {
250 out.resize(columns+1, -1);
251 out.back() = i;
252 std::pair<SmallString<16>,bool> res
253 = printableTextForNextCharacter(SourceLine, &i, TabStop);
254 columns += llvm::sys::locale::columnWidth(res.first);
255 }
256 out.resize(columns+1, -1);
257 out.back() = i;
258}
259
260struct SourceColumnMap {
261 SourceColumnMap(StringRef SourceLine, unsigned TabStop)
262 : m_SourceLine(SourceLine) {
263
264 ::byteToColumn(SourceLine, TabStop, m_byteToColumn);
265 ::columnToByte(SourceLine, TabStop, m_columnToByte);
266
267 assert(m_byteToColumn.size()==SourceLine.size()+1);
268 assert(0 < m_byteToColumn.size() && 0 < m_columnToByte.size());
269 assert(m_byteToColumn.size()
270 == static_cast<unsigned>(m_columnToByte.back()+1));
271 assert(static_cast<unsigned>(m_byteToColumn.back()+1)
272 == m_columnToByte.size());
273 }
274 int columns() const { return m_byteToColumn.back(); }
275 int bytes() const { return m_columnToByte.back(); }
276 int byteToColumn(int n) const {
277 assert(0<=n && n<static_cast<int>(m_byteToColumn.size()));
278 return m_byteToColumn[n];
279 }
280 int columnToByte(int n) const {
281 assert(0<=n && n<static_cast<int>(m_columnToByte.size()));
282 return m_columnToByte[n];
283 }
284 StringRef getSourceLine() const {
285 return m_SourceLine;
286 }
287
288private:
289 const std::string m_SourceLine;
290 SmallVector<int,200> m_byteToColumn;
291 SmallVector<int,200> m_columnToByte;
292};
293
294// used in assert in selectInterestingSourceRegion()
295namespace {
296struct char_out_of_range {
297 const char lower,upper;
298 char_out_of_range(char lower, char upper) :
299 lower(lower), upper(upper) {}
300 bool operator()(char c) { return c < lower || upper < c; }
301};
302}
303
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000304/// \brief When the source code line we want to print is too long for
305/// the terminal, select the "interesting" region.
Chandler Carruth7531f572011-10-15 23:54:09 +0000306static void selectInterestingSourceRegion(std::string &SourceLine,
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000307 std::string &CaretLine,
308 std::string &FixItInsertionLine,
Seth Cantrell6749dd52012-04-18 02:44:46 +0000309 unsigned Columns,
310 const SourceColumnMap &map) {
311 unsigned MaxColumns = std::max<unsigned>(map.columns(),
312 std::max(CaretLine.size(),
313 FixItInsertionLine.size()));
314 // if the number of columns is less than the desired number we're done
315 if (MaxColumns <= Columns)
316 return;
317
318 // no special characters allowed in CaretLine or FixItInsertionLine
319 assert(CaretLine.end() ==
320 std::find_if(CaretLine.begin(), CaretLine.end(),
321 char_out_of_range(' ','~')));
322 assert(FixItInsertionLine.end() ==
323 std::find_if(FixItInsertionLine.begin(), FixItInsertionLine.end(),
324 char_out_of_range(' ','~')));
325
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000326 // Find the slice that we need to display the full caret line
327 // correctly.
328 unsigned CaretStart = 0, CaretEnd = CaretLine.size();
329 for (; CaretStart != CaretEnd; ++CaretStart)
Seth Cantrell4031a372012-05-25 00:03:29 +0000330 if (!isspace(static_cast<unsigned char>(CaretLine[CaretStart])))
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000331 break;
332
333 for (; CaretEnd != CaretStart; --CaretEnd)
Seth Cantrell4031a372012-05-25 00:03:29 +0000334 if (!isspace(static_cast<unsigned char>(CaretLine[CaretEnd - 1])))
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000335 break;
336
Seth Cantrell6749dd52012-04-18 02:44:46 +0000337 // caret has already been inserted into CaretLine so the above whitespace
338 // check is guaranteed to include the caret
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000339
340 // If we have a fix-it line, make sure the slice includes all of the
341 // fix-it information.
342 if (!FixItInsertionLine.empty()) {
343 unsigned FixItStart = 0, FixItEnd = FixItInsertionLine.size();
344 for (; FixItStart != FixItEnd; ++FixItStart)
Seth Cantrell4031a372012-05-25 00:03:29 +0000345 if (!isspace(static_cast<unsigned char>(FixItInsertionLine[FixItStart])))
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000346 break;
347
348 for (; FixItEnd != FixItStart; --FixItEnd)
Seth Cantrell4031a372012-05-25 00:03:29 +0000349 if (!isspace(static_cast<unsigned char>(FixItInsertionLine[FixItEnd - 1])))
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000350 break;
351
Seth Cantrell6749dd52012-04-18 02:44:46 +0000352 CaretStart = std::min(FixItStart, CaretStart);
353 CaretEnd = std::max(FixItEnd, CaretEnd);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000354 }
355
Seth Cantrellc5493d72012-05-24 05:14:44 +0000356 // CaretEnd may have been set at the middle of a character
357 // If it's not at a character's first column then advance it past the current
358 // character.
359 while (static_cast<int>(CaretEnd) < map.columns() &&
360 -1 == map.columnToByte(CaretEnd))
361 ++CaretEnd;
362
363 assert((static_cast<int>(CaretStart) > map.columns() ||
364 -1!=map.columnToByte(CaretStart)) &&
365 "CaretStart must not point to a column in the middle of a source"
366 " line character");
367 assert((static_cast<int>(CaretEnd) > map.columns() ||
368 -1!=map.columnToByte(CaretEnd)) &&
369 "CaretEnd must not point to a column in the middle of a source line"
370 " character");
371
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000372 // CaretLine[CaretStart, CaretEnd) contains all of the interesting
373 // parts of the caret line. While this slice is smaller than the
374 // number of columns we have, try to grow the slice to encompass
375 // more context.
376
Seth Cantrell6749dd52012-04-18 02:44:46 +0000377 unsigned SourceStart = map.columnToByte(std::min<unsigned>(CaretStart,
378 map.columns()));
379 unsigned SourceEnd = map.columnToByte(std::min<unsigned>(CaretEnd,
380 map.columns()));
381
382 unsigned CaretColumnsOutsideSource = CaretEnd-CaretStart
383 - (map.byteToColumn(SourceEnd)-map.byteToColumn(SourceStart));
384
385 char const *front_ellipse = " ...";
386 char const *front_space = " ";
387 char const *back_ellipse = "...";
388 unsigned ellipses_space = strlen(front_ellipse) + strlen(back_ellipse);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000389
390 unsigned TargetColumns = Columns;
Seth Cantrell6749dd52012-04-18 02:44:46 +0000391 // Give us extra room for the ellipses
392 // and any of the caret line that extends past the source
393 if (TargetColumns > ellipses_space+CaretColumnsOutsideSource)
394 TargetColumns -= ellipses_space+CaretColumnsOutsideSource;
395
396 while (SourceStart>0 || SourceEnd<SourceLine.size()) {
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000397 bool ExpandedRegion = false;
Seth Cantrell6749dd52012-04-18 02:44:46 +0000398
399 if (SourceStart>0) {
400 unsigned NewStart = SourceStart-1;
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000401
402 // Skip over any whitespace we see here; we're looking for
403 // another bit of interesting text.
Seth Cantrell6749dd52012-04-18 02:44:46 +0000404 while (NewStart &&
Seth Cantrell4031a372012-05-25 00:03:29 +0000405 (map.byteToColumn(NewStart)==-1 ||
406 isspace(static_cast<unsigned char>(SourceLine[NewStart]))))
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000407 --NewStart;
408
409 // Skip over this bit of "interesting" text.
Seth Cantrell6749dd52012-04-18 02:44:46 +0000410 while (NewStart &&
Seth Cantrell4031a372012-05-25 00:03:29 +0000411 (map.byteToColumn(NewStart)!=-1 &&
412 !isspace(static_cast<unsigned char>(SourceLine[NewStart]))))
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000413 --NewStart;
414
415 // Move up to the non-whitespace character we just saw.
416 if (NewStart)
417 ++NewStart;
418
Seth Cantrell6749dd52012-04-18 02:44:46 +0000419 unsigned NewColumns = map.byteToColumn(SourceEnd) -
420 map.byteToColumn(NewStart);
421 if (NewColumns <= TargetColumns) {
422 SourceStart = NewStart;
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000423 ExpandedRegion = true;
424 }
425 }
426
Seth Cantrell6749dd52012-04-18 02:44:46 +0000427 if (SourceEnd<SourceLine.size()) {
428 unsigned NewEnd = SourceEnd+1;
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000429
430 // Skip over any whitespace we see here; we're looking for
431 // another bit of interesting text.
Seth Cantrell6749dd52012-04-18 02:44:46 +0000432 while (NewEnd<SourceLine.size() &&
Seth Cantrell4031a372012-05-25 00:03:29 +0000433 (map.byteToColumn(NewEnd)==-1 ||
434 isspace(static_cast<unsigned char>(SourceLine[NewEnd]))))
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000435 ++NewEnd;
436
437 // Skip over this bit of "interesting" text.
Seth Cantrell6749dd52012-04-18 02:44:46 +0000438 while (NewEnd<SourceLine.size() &&
Seth Cantrell4031a372012-05-25 00:03:29 +0000439 (map.byteToColumn(NewEnd)!=-1 &&
440 !isspace(static_cast<unsigned char>(SourceLine[NewEnd]))))
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000441 ++NewEnd;
442
Seth Cantrell6749dd52012-04-18 02:44:46 +0000443 unsigned NewColumns = map.byteToColumn(NewEnd) -
444 map.byteToColumn(SourceStart);
445 if (NewColumns <= TargetColumns) {
446 SourceEnd = NewEnd;
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000447 ExpandedRegion = true;
448 }
449 }
450
451 if (!ExpandedRegion)
452 break;
453 }
454
Seth Cantrell6749dd52012-04-18 02:44:46 +0000455 CaretStart = map.byteToColumn(SourceStart);
456 CaretEnd = map.byteToColumn(SourceEnd) + CaretColumnsOutsideSource;
457
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000458 // [CaretStart, CaretEnd) is the slice we want. Update the various
459 // output lines to show only this slice, with two-space padding
460 // before the lines so that it looks nicer.
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000461
Seth Cantrell6749dd52012-04-18 02:44:46 +0000462 assert(CaretStart!=(unsigned)-1 && CaretEnd!=(unsigned)-1 &&
463 SourceStart!=(unsigned)-1 && SourceEnd!=(unsigned)-1);
464 assert(SourceStart <= SourceEnd);
465 assert(CaretStart <= CaretEnd);
466
467 unsigned BackColumnsRemoved
468 = map.byteToColumn(SourceLine.size())-map.byteToColumn(SourceEnd);
469 unsigned FrontColumnsRemoved = CaretStart;
470 unsigned ColumnsKept = CaretEnd-CaretStart;
471
472 // We checked up front that the line needed truncation
473 assert(FrontColumnsRemoved+ColumnsKept+BackColumnsRemoved > Columns);
474
475 // The line needs some trunctiona, and we'd prefer to keep the front
476 // if possible, so remove the back
477 if (BackColumnsRemoved)
478 SourceLine.replace(SourceEnd, std::string::npos, back_ellipse);
479
480 // If that's enough then we're done
481 if (FrontColumnsRemoved+ColumnsKept <= Columns)
482 return;
483
484 // Otherwise remove the front as well
485 if (FrontColumnsRemoved) {
486 SourceLine.replace(0, SourceStart, front_ellipse);
487 CaretLine.replace(0, CaretStart, front_space);
488 if (!FixItInsertionLine.empty())
489 FixItInsertionLine.replace(0, CaretStart, front_space);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000490 }
491}
492
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000493/// \brief Skip over whitespace in the string, starting at the given
494/// index.
495///
496/// \returns The index of the first non-whitespace character that is
497/// greater than or equal to Idx or, if no such character exists,
498/// returns the end of the string.
499static unsigned skipWhitespace(unsigned Idx, StringRef Str, unsigned Length) {
500 while (Idx < Length && isspace(Str[Idx]))
501 ++Idx;
502 return Idx;
503}
504
505/// \brief If the given character is the start of some kind of
506/// balanced punctuation (e.g., quotes or parentheses), return the
507/// character that will terminate the punctuation.
508///
509/// \returns The ending punctuation character, if any, or the NULL
510/// character if the input character does not start any punctuation.
511static inline char findMatchingPunctuation(char c) {
512 switch (c) {
513 case '\'': return '\'';
514 case '`': return '\'';
515 case '"': return '"';
516 case '(': return ')';
517 case '[': return ']';
518 case '{': return '}';
519 default: break;
520 }
521
522 return 0;
523}
524
525/// \brief Find the end of the word starting at the given offset
526/// within a string.
527///
528/// \returns the index pointing one character past the end of the
529/// word.
530static unsigned findEndOfWord(unsigned Start, StringRef Str,
531 unsigned Length, unsigned Column,
532 unsigned Columns) {
533 assert(Start < Str.size() && "Invalid start position!");
534 unsigned End = Start + 1;
535
536 // If we are already at the end of the string, take that as the word.
537 if (End == Str.size())
538 return End;
539
540 // Determine if the start of the string is actually opening
541 // punctuation, e.g., a quote or parentheses.
542 char EndPunct = findMatchingPunctuation(Str[Start]);
543 if (!EndPunct) {
544 // This is a normal word. Just find the first space character.
545 while (End < Length && !isspace(Str[End]))
546 ++End;
547 return End;
548 }
549
550 // We have the start of a balanced punctuation sequence (quotes,
551 // parentheses, etc.). Determine the full sequence is.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000552 SmallString<16> PunctuationEndStack;
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000553 PunctuationEndStack.push_back(EndPunct);
554 while (End < Length && !PunctuationEndStack.empty()) {
555 if (Str[End] == PunctuationEndStack.back())
556 PunctuationEndStack.pop_back();
557 else if (char SubEndPunct = findMatchingPunctuation(Str[End]))
558 PunctuationEndStack.push_back(SubEndPunct);
559
560 ++End;
561 }
562
563 // Find the first space character after the punctuation ended.
564 while (End < Length && !isspace(Str[End]))
565 ++End;
566
567 unsigned PunctWordLength = End - Start;
568 if (// If the word fits on this line
569 Column + PunctWordLength <= Columns ||
570 // ... or the word is "short enough" to take up the next line
571 // without too much ugly white space
572 PunctWordLength < Columns/3)
573 return End; // Take the whole thing as a single "word".
574
575 // The whole quoted/parenthesized string is too long to print as a
576 // single "word". Instead, find the "word" that starts just after
577 // the punctuation and use that end-point instead. This will recurse
578 // until it finds something small enough to consider a word.
579 return findEndOfWord(Start + 1, Str, Length, Column + 1, Columns);
580}
581
582/// \brief Print the given string to a stream, word-wrapping it to
583/// some number of columns in the process.
584///
585/// \param OS the stream to which the word-wrapping string will be
586/// emitted.
587/// \param Str the string to word-wrap and output.
588/// \param Columns the number of columns to word-wrap to.
589/// \param Column the column number at which the first character of \p
590/// Str will be printed. This will be non-zero when part of the first
591/// line has already been printed.
Richard Trieub956e5a2012-06-28 22:39:03 +0000592/// \param Bold if the current text should be bold
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000593/// \param Indentation the number of spaces to indent any lines beyond
594/// the first line.
595/// \returns true if word-wrapping was required, or false if the
596/// string fit on the first line.
597static bool printWordWrapped(raw_ostream &OS, StringRef Str,
598 unsigned Columns,
599 unsigned Column = 0,
Richard Trieub956e5a2012-06-28 22:39:03 +0000600 bool Bold = false,
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000601 unsigned Indentation = WordWrapIndentation) {
602 const unsigned Length = std::min(Str.find('\n'), Str.size());
Richard Trieu246b6aa2012-06-26 18:18:47 +0000603 bool TextNormal = true;
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000604
605 // The string used to indent each line.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000606 SmallString<16> IndentStr;
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000607 IndentStr.assign(Indentation, ' ');
608 bool Wrapped = false;
609 for (unsigned WordStart = 0, WordEnd; WordStart < Length;
610 WordStart = WordEnd) {
611 // Find the beginning of the next word.
612 WordStart = skipWhitespace(WordStart, Str, Length);
613 if (WordStart == Length)
614 break;
615
616 // Find the end of this word.
617 WordEnd = findEndOfWord(WordStart, Str, Length, Column, Columns);
618
619 // Does this word fit on the current line?
620 unsigned WordLength = WordEnd - WordStart;
621 if (Column + WordLength < Columns) {
622 // This word fits on the current line; print it there.
623 if (WordStart) {
624 OS << ' ';
625 Column += 1;
626 }
Richard Trieu246b6aa2012-06-26 18:18:47 +0000627 applyTemplateHighlighting(OS, Str.substr(WordStart, WordLength),
Richard Trieub956e5a2012-06-28 22:39:03 +0000628 TextNormal, Bold);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000629 Column += WordLength;
630 continue;
631 }
632
633 // This word does not fit on the current line, so wrap to the next
634 // line.
635 OS << '\n';
636 OS.write(&IndentStr[0], Indentation);
Richard Trieu246b6aa2012-06-26 18:18:47 +0000637 applyTemplateHighlighting(OS, Str.substr(WordStart, WordLength),
Richard Trieub956e5a2012-06-28 22:39:03 +0000638 TextNormal, Bold);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000639 Column = Indentation + WordLength;
640 Wrapped = true;
641 }
642
643 // Append any remaning text from the message with its existing formatting.
Richard Trieub956e5a2012-06-28 22:39:03 +0000644 applyTemplateHighlighting(OS, Str.substr(Length), TextNormal, Bold);
Richard Trieu246b6aa2012-06-26 18:18:47 +0000645
646 assert(TextNormal && "Text highlighted at end of diagnostic message.");
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000647
648 return Wrapped;
649}
650
651TextDiagnostic::TextDiagnostic(raw_ostream &OS,
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000652 const LangOptions &LangOpts,
Chandler Carruth21a869a2011-10-16 02:57:39 +0000653 const DiagnosticOptions &DiagOpts)
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000654 : DiagnosticRenderer(LangOpts, DiagOpts), OS(OS) {}
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000655
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000656TextDiagnostic::~TextDiagnostic() {}
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000657
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000658void
659TextDiagnostic::emitDiagnosticMessage(SourceLocation Loc,
660 PresumedLoc PLoc,
661 DiagnosticsEngine::Level Level,
662 StringRef Message,
663 ArrayRef<clang::CharSourceRange> Ranges,
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000664 const SourceManager *SM,
Ted Kremenek8be51ea2012-02-14 02:46:00 +0000665 DiagOrStoredDiag D) {
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000666 uint64_t StartOfLocationInfo = OS.tell();
667
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000668 // Emit the location of this particular diagnostic.
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000669 if (Loc.isValid())
670 emitDiagnosticLoc(Loc, PLoc, Level, Ranges, *SM);
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000671
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000672 if (DiagOpts.ShowColors)
673 OS.resetColor();
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000674
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000675 printDiagnosticLevel(OS, Level, DiagOpts.ShowColors);
676 printDiagnosticMessage(OS, Level, Message,
677 OS.tell() - StartOfLocationInfo,
678 DiagOpts.MessageLength, DiagOpts.ShowColors);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000679}
680
Chandler Carruth6ddd8872011-10-15 23:48:02 +0000681/*static*/ void
682TextDiagnostic::printDiagnosticLevel(raw_ostream &OS,
683 DiagnosticsEngine::Level Level,
684 bool ShowColors) {
685 if (ShowColors) {
686 // Print diagnostic category in bold and color
687 switch (Level) {
688 case DiagnosticsEngine::Ignored:
689 llvm_unreachable("Invalid diagnostic type");
690 case DiagnosticsEngine::Note: OS.changeColor(noteColor, true); break;
691 case DiagnosticsEngine::Warning: OS.changeColor(warningColor, true); break;
692 case DiagnosticsEngine::Error: OS.changeColor(errorColor, true); break;
693 case DiagnosticsEngine::Fatal: OS.changeColor(fatalColor, true); break;
694 }
695 }
696
697 switch (Level) {
698 case DiagnosticsEngine::Ignored:
699 llvm_unreachable("Invalid diagnostic type");
700 case DiagnosticsEngine::Note: OS << "note: "; break;
701 case DiagnosticsEngine::Warning: OS << "warning: "; break;
702 case DiagnosticsEngine::Error: OS << "error: "; break;
703 case DiagnosticsEngine::Fatal: OS << "fatal error: "; break;
704 }
705
706 if (ShowColors)
707 OS.resetColor();
708}
709
710/*static*/ void
711TextDiagnostic::printDiagnosticMessage(raw_ostream &OS,
712 DiagnosticsEngine::Level Level,
713 StringRef Message,
714 unsigned CurrentColumn, unsigned Columns,
715 bool ShowColors) {
Richard Trieub956e5a2012-06-28 22:39:03 +0000716 bool Bold = false;
Chandler Carruth6ddd8872011-10-15 23:48:02 +0000717 if (ShowColors) {
718 // Print warnings, errors and fatal errors in bold, no color
719 switch (Level) {
Richard Trieub956e5a2012-06-28 22:39:03 +0000720 case DiagnosticsEngine::Warning:
721 case DiagnosticsEngine::Error:
722 case DiagnosticsEngine::Fatal:
723 OS.changeColor(savedColor, true);
724 Bold = true;
725 break;
Chandler Carruth6ddd8872011-10-15 23:48:02 +0000726 default: break; //don't bold notes
727 }
728 }
729
730 if (Columns)
Richard Trieub956e5a2012-06-28 22:39:03 +0000731 printWordWrapped(OS, Message, Columns, CurrentColumn, Bold);
David Blaikie50badd52012-06-28 21:46:07 +0000732 else {
733 bool Normal = true;
Richard Trieub956e5a2012-06-28 22:39:03 +0000734 applyTemplateHighlighting(OS, Message, Normal, Bold);
David Blaikie50badd52012-06-28 21:46:07 +0000735 assert(Normal && "Formatting should have returned to normal");
736 }
Chandler Carruth6ddd8872011-10-15 23:48:02 +0000737
738 if (ShowColors)
739 OS.resetColor();
740 OS << '\n';
741}
742
Chandler Carruth6ddd8872011-10-15 23:48:02 +0000743/// \brief Print out the file/line/column information and include trace.
744///
745/// This method handlen the emission of the diagnostic location information.
746/// This includes extracting as much location information as is present for
747/// the diagnostic and printing it, as well as any include stack or source
748/// ranges necessary.
Chandler Carruth7531f572011-10-15 23:54:09 +0000749void TextDiagnostic::emitDiagnosticLoc(SourceLocation Loc, PresumedLoc PLoc,
Chandler Carruth6ddd8872011-10-15 23:48:02 +0000750 DiagnosticsEngine::Level Level,
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000751 ArrayRef<CharSourceRange> Ranges,
752 const SourceManager &SM) {
Chandler Carruth6ddd8872011-10-15 23:48:02 +0000753 if (PLoc.isInvalid()) {
754 // At least print the file name if available:
755 FileID FID = SM.getFileID(Loc);
756 if (!FID.isInvalid()) {
757 const FileEntry* FE = SM.getFileEntryForID(FID);
758 if (FE && FE->getName()) {
759 OS << FE->getName();
760 if (FE->getDevice() == 0 && FE->getInode() == 0
761 && FE->getFileMode() == 0) {
762 // in PCH is a guess, but a good one:
763 OS << " (in PCH)";
764 }
765 OS << ": ";
766 }
767 }
768 return;
769 }
770 unsigned LineNo = PLoc.getLine();
771
772 if (!DiagOpts.ShowLocation)
773 return;
774
775 if (DiagOpts.ShowColors)
776 OS.changeColor(savedColor, true);
777
778 OS << PLoc.getFilename();
779 switch (DiagOpts.Format) {
780 case DiagnosticOptions::Clang: OS << ':' << LineNo; break;
781 case DiagnosticOptions::Msvc: OS << '(' << LineNo; break;
782 case DiagnosticOptions::Vi: OS << " +" << LineNo; break;
783 }
784
785 if (DiagOpts.ShowColumn)
786 // Compute the column number.
787 if (unsigned ColNo = PLoc.getColumn()) {
788 if (DiagOpts.Format == DiagnosticOptions::Msvc) {
789 OS << ',';
790 ColNo--;
791 } else
792 OS << ':';
793 OS << ColNo;
794 }
795 switch (DiagOpts.Format) {
796 case DiagnosticOptions::Clang:
797 case DiagnosticOptions::Vi: OS << ':'; break;
798 case DiagnosticOptions::Msvc: OS << ") : "; break;
799 }
800
801 if (DiagOpts.ShowSourceRanges && !Ranges.empty()) {
802 FileID CaretFileID =
803 SM.getFileID(SM.getExpansionLoc(Loc));
804 bool PrintedRange = false;
805
806 for (ArrayRef<CharSourceRange>::const_iterator RI = Ranges.begin(),
807 RE = Ranges.end();
808 RI != RE; ++RI) {
809 // Ignore invalid ranges.
810 if (!RI->isValid()) continue;
811
812 SourceLocation B = SM.getExpansionLoc(RI->getBegin());
813 SourceLocation E = SM.getExpansionLoc(RI->getEnd());
814
815 // If the End location and the start location are the same and are a
816 // macro location, then the range was something that came from a
817 // macro expansion or _Pragma. If this is an object-like macro, the
818 // best we can do is to highlight the range. If this is a
819 // function-like macro, we'd also like to highlight the arguments.
820 if (B == E && RI->getEnd().isMacroID())
821 E = SM.getExpansionRange(RI->getEnd()).second;
822
823 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(B);
824 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E);
825
826 // If the start or end of the range is in another file, just discard
827 // it.
828 if (BInfo.first != CaretFileID || EInfo.first != CaretFileID)
829 continue;
830
831 // Add in the length of the token, so that we cover multi-char
832 // tokens.
833 unsigned TokSize = 0;
834 if (RI->isTokenRange())
835 TokSize = Lexer::MeasureTokenLength(E, SM, LangOpts);
836
837 OS << '{' << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
838 << SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
839 << SM.getLineNumber(EInfo.first, EInfo.second) << ':'
840 << (SM.getColumnNumber(EInfo.first, EInfo.second)+TokSize)
841 << '}';
842 PrintedRange = true;
843 }
844
845 if (PrintedRange)
846 OS << ':';
847 }
848 OS << ' ';
849}
850
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000851void TextDiagnostic::emitBasicNote(StringRef Message) {
852 // FIXME: Emit this as a real note diagnostic.
853 // FIXME: Format an actual diagnostic rather than a hard coded string.
854 OS << "note: " << Message << "\n";
855}
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000856
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000857void TextDiagnostic::emitIncludeLocation(SourceLocation Loc,
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000858 PresumedLoc PLoc,
859 const SourceManager &SM) {
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000860 if (DiagOpts.ShowLocation)
861 OS << "In file included from " << PLoc.getFilename() << ':'
862 << PLoc.getLine() << ":\n";
863 else
864 OS << "In included file:\n";
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000865}
866
867/// \brief Emit a code snippet and caret line.
868///
869/// This routine emits a single line's code snippet and caret line..
870///
871/// \param Loc The location for the caret.
872/// \param Ranges The underlined ranges for this code snippet.
873/// \param Hints The FixIt hints active for this diagnostic.
Chandler Carruth7531f572011-10-15 23:54:09 +0000874void TextDiagnostic::emitSnippetAndCaret(
Chandler Carruth4ba55652011-10-16 07:20:28 +0000875 SourceLocation Loc, DiagnosticsEngine::Level Level,
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000876 SmallVectorImpl<CharSourceRange>& Ranges,
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000877 ArrayRef<FixItHint> Hints,
878 const SourceManager &SM) {
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000879 assert(!Loc.isInvalid() && "must have a valid source location here");
880 assert(Loc.isFileID() && "must have a file location here");
881
Chandler Carruth4ba55652011-10-16 07:20:28 +0000882 // If caret diagnostics are enabled and we have location, we want to
883 // emit the caret. However, we only do this if the location moved
884 // from the last diagnostic, if the last diagnostic was a note that
885 // was part of a different warning or error diagnostic, or if the
886 // diagnostic has ranges. We don't want to emit the same caret
887 // multiple times if one loc has multiple diagnostics.
888 if (!DiagOpts.ShowCarets)
889 return;
890 if (Loc == LastLoc && Ranges.empty() && Hints.empty() &&
891 (LastLevel != DiagnosticsEngine::Note || Level == LastLevel))
892 return;
893
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000894 // Decompose the location into a FID/Offset pair.
895 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
896 FileID FID = LocInfo.first;
897 unsigned FileOffset = LocInfo.second;
898
899 // Get information about the buffer it points into.
900 bool Invalid = false;
Nico Weber40d8e972012-04-26 21:39:46 +0000901 const char *BufStart = SM.getBufferData(FID, &Invalid).data();
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000902 if (Invalid)
903 return;
904
905 unsigned LineNo = SM.getLineNumber(FID, FileOffset);
906 unsigned ColNo = SM.getColumnNumber(FID, FileOffset);
907 unsigned CaretEndColNo
908 = ColNo + Lexer::MeasureTokenLength(Loc, SM, LangOpts);
909
910 // Rewind from the current position to the start of the line.
911 const char *TokPtr = BufStart+FileOffset;
912 const char *LineStart = TokPtr-ColNo+1; // Column # is 1-based.
913
914
915 // Compute the line end. Scan forward from the error position to the end of
916 // the line.
917 const char *LineEnd = TokPtr;
Nico Weber40d8e972012-04-26 21:39:46 +0000918 while (*LineEnd != '\n' && *LineEnd != '\r' && *LineEnd != '\0')
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000919 ++LineEnd;
920
921 // FIXME: This shouldn't be necessary, but the CaretEndColNo can extend past
922 // the source line length as currently being computed. See
923 // test/Misc/message-length.c.
924 CaretEndColNo = std::min(CaretEndColNo, unsigned(LineEnd - LineStart));
925
926 // Copy the line of code into an std::string for ease of manipulation.
927 std::string SourceLine(LineStart, LineEnd);
928
929 // Create a line for the caret that is filled with spaces that is the same
930 // length as the line of source code.
931 std::string CaretLine(LineEnd-LineStart, ' ');
932
Seth Cantrell6749dd52012-04-18 02:44:46 +0000933 const SourceColumnMap sourceColMap(SourceLine, DiagOpts.TabStop);
934
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000935 // Highlight all of the characters covered by Ranges with ~ characters.
936 for (SmallVectorImpl<CharSourceRange>::iterator I = Ranges.begin(),
937 E = Ranges.end();
938 I != E; ++I)
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000939 highlightRange(*I, LineNo, FID, sourceColMap, CaretLine, SM);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000940
941 // Next, insert the caret itself.
Seth Cantrell6749dd52012-04-18 02:44:46 +0000942 ColNo = sourceColMap.byteToColumn(ColNo-1);
943 if (CaretLine.size()<ColNo+1)
944 CaretLine.resize(ColNo+1, ' ');
945 CaretLine[ColNo] = '^';
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000946
Seth Cantrell6749dd52012-04-18 02:44:46 +0000947 std::string FixItInsertionLine = buildFixItInsertionLine(LineNo,
948 sourceColMap,
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000949 Hints, SM);
Seth Cantrell6749dd52012-04-18 02:44:46 +0000950
951 // If the source line is too long for our terminal, select only the
952 // "interesting" source region within that line.
953 unsigned Columns = DiagOpts.MessageLength;
954 if (Columns)
955 selectInterestingSourceRegion(SourceLine, CaretLine, FixItInsertionLine,
956 Columns, sourceColMap);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000957
958 // If we are in -fdiagnostics-print-source-range-info mode, we are trying
959 // to produce easily machine parsable output. Add a space before the
960 // source line and the caret to make it trivial to tell the main diagnostic
961 // line from what the user is intended to see.
962 if (DiagOpts.ShowSourceRanges) {
963 SourceLine = ' ' + SourceLine;
964 CaretLine = ' ' + CaretLine;
965 }
966
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000967 // Finally, remove any blank spaces from the end of CaretLine.
968 while (CaretLine[CaretLine.size()-1] == ' ')
969 CaretLine.erase(CaretLine.end()-1);
970
971 // Emit what we have computed.
Seth Cantrell6749dd52012-04-18 02:44:46 +0000972 emitSnippet(SourceLine);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000973
974 if (DiagOpts.ShowColors)
975 OS.changeColor(caretColor, true);
976 OS << CaretLine << '\n';
977 if (DiagOpts.ShowColors)
978 OS.resetColor();
979
980 if (!FixItInsertionLine.empty()) {
981 if (DiagOpts.ShowColors)
982 // Print fixit line in color
983 OS.changeColor(fixitColor, false);
984 if (DiagOpts.ShowSourceRanges)
985 OS << ' ';
986 OS << FixItInsertionLine << '\n';
987 if (DiagOpts.ShowColors)
988 OS.resetColor();
989 }
990
991 // Print out any parseable fixit information requested by the options.
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000992 emitParseableFixits(Hints, SM);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000993}
994
Benjamin Kramerd1fda032012-05-01 14:34:11 +0000995void TextDiagnostic::emitSnippet(StringRef line) {
Seth Cantrell6749dd52012-04-18 02:44:46 +0000996 if (line.empty())
997 return;
998
999 size_t i = 0;
1000
1001 std::string to_print;
1002 bool print_reversed = false;
1003
1004 while (i<line.size()) {
1005 std::pair<SmallString<16>,bool> res
1006 = printableTextForNextCharacter(line, &i, DiagOpts.TabStop);
1007 bool was_printable = res.second;
1008
Nico Weber40d8e972012-04-26 21:39:46 +00001009 if (DiagOpts.ShowColors && was_printable == print_reversed) {
Seth Cantrell6749dd52012-04-18 02:44:46 +00001010 if (print_reversed)
1011 OS.reverseColor();
1012 OS << to_print;
1013 to_print.clear();
1014 if (DiagOpts.ShowColors)
1015 OS.resetColor();
1016 }
1017
1018 print_reversed = !was_printable;
1019 to_print += res.first.str();
1020 }
1021
1022 if (print_reversed && DiagOpts.ShowColors)
1023 OS.reverseColor();
1024 OS << to_print;
1025 if (print_reversed && DiagOpts.ShowColors)
1026 OS.resetColor();
1027
1028 OS << '\n';
1029}
1030
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001031/// \brief Highlight a SourceRange (with ~'s) for any characters on LineNo.
Chandler Carruth7531f572011-10-15 23:54:09 +00001032void TextDiagnostic::highlightRange(const CharSourceRange &R,
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001033 unsigned LineNo, FileID FID,
Seth Cantrell6749dd52012-04-18 02:44:46 +00001034 const SourceColumnMap &map,
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +00001035 std::string &CaretLine,
1036 const SourceManager &SM) {
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001037 if (!R.isValid()) return;
1038
1039 SourceLocation Begin = SM.getExpansionLoc(R.getBegin());
1040 SourceLocation End = SM.getExpansionLoc(R.getEnd());
1041
1042 // If the End location and the start location are the same and are a macro
1043 // location, then the range was something that came from a macro expansion
1044 // or _Pragma. If this is an object-like macro, the best we can do is to
1045 // highlight the range. If this is a function-like macro, we'd also like to
1046 // highlight the arguments.
1047 if (Begin == End && R.getEnd().isMacroID())
1048 End = SM.getExpansionRange(R.getEnd()).second;
1049
1050 unsigned StartLineNo = SM.getExpansionLineNumber(Begin);
1051 if (StartLineNo > LineNo || SM.getFileID(Begin) != FID)
1052 return; // No intersection.
1053
1054 unsigned EndLineNo = SM.getExpansionLineNumber(End);
1055 if (EndLineNo < LineNo || SM.getFileID(End) != FID)
1056 return; // No intersection.
1057
1058 // Compute the column number of the start.
1059 unsigned StartColNo = 0;
1060 if (StartLineNo == LineNo) {
1061 StartColNo = SM.getExpansionColumnNumber(Begin);
1062 if (StartColNo) --StartColNo; // Zero base the col #.
1063 }
1064
1065 // Compute the column number of the end.
Seth Cantrell6749dd52012-04-18 02:44:46 +00001066 unsigned EndColNo = map.getSourceLine().size();
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001067 if (EndLineNo == LineNo) {
1068 EndColNo = SM.getExpansionColumnNumber(End);
1069 if (EndColNo) {
1070 --EndColNo; // Zero base the col #.
1071
1072 // Add in the length of the token, so that we cover multi-char tokens if
1073 // this is a token range.
1074 if (R.isTokenRange())
1075 EndColNo += Lexer::MeasureTokenLength(End, SM, LangOpts);
1076 } else {
1077 EndColNo = CaretLine.size();
1078 }
1079 }
1080
1081 assert(StartColNo <= EndColNo && "Invalid range!");
1082
1083 // Check that a token range does not highlight only whitespace.
1084 if (R.isTokenRange()) {
1085 // Pick the first non-whitespace column.
Seth Cantrell6749dd52012-04-18 02:44:46 +00001086 while (StartColNo < map.getSourceLine().size() &&
1087 (map.getSourceLine()[StartColNo] == ' ' ||
1088 map.getSourceLine()[StartColNo] == '\t'))
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001089 ++StartColNo;
1090
1091 // Pick the last non-whitespace column.
Seth Cantrell6749dd52012-04-18 02:44:46 +00001092 if (EndColNo > map.getSourceLine().size())
1093 EndColNo = map.getSourceLine().size();
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001094 while (EndColNo-1 &&
Seth Cantrell6749dd52012-04-18 02:44:46 +00001095 (map.getSourceLine()[EndColNo-1] == ' ' ||
1096 map.getSourceLine()[EndColNo-1] == '\t'))
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001097 --EndColNo;
1098
1099 // If the start/end passed each other, then we are trying to highlight a
1100 // range that just exists in whitespace, which must be some sort of other
1101 // bug.
1102 assert(StartColNo <= EndColNo && "Trying to highlight whitespace??");
1103 }
1104
Seth Cantrell6749dd52012-04-18 02:44:46 +00001105 assert(StartColNo <= map.getSourceLine().size() && "Invalid range!");
1106 assert(EndColNo <= map.getSourceLine().size() && "Invalid range!");
1107
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001108 // Fill the range with ~'s.
Seth Cantrell6749dd52012-04-18 02:44:46 +00001109 StartColNo = map.byteToColumn(StartColNo);
1110 EndColNo = map.byteToColumn(EndColNo);
1111
1112 assert(StartColNo <= EndColNo && "Invalid range!");
1113 if (CaretLine.size() < EndColNo)
1114 CaretLine.resize(EndColNo,' ');
1115 std::fill(CaretLine.begin()+StartColNo,CaretLine.begin()+EndColNo,'~');
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001116}
1117
Seth Cantrell6749dd52012-04-18 02:44:46 +00001118std::string TextDiagnostic::buildFixItInsertionLine(
1119 unsigned LineNo,
1120 const SourceColumnMap &map,
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +00001121 ArrayRef<FixItHint> Hints,
1122 const SourceManager &SM) {
Seth Cantrell6749dd52012-04-18 02:44:46 +00001123
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001124 std::string FixItInsertionLine;
1125 if (Hints.empty() || !DiagOpts.ShowFixits)
1126 return FixItInsertionLine;
Jordan Rose3772c9a2012-06-08 21:14:19 +00001127 unsigned PrevHintEnd = 0;
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001128
1129 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1130 I != E; ++I) {
1131 if (!I->CodeToInsert.empty()) {
1132 // We have an insertion hint. Determine whether the inserted
1133 // code is on the same line as the caret.
1134 std::pair<FileID, unsigned> HintLocInfo
1135 = SM.getDecomposedExpansionLoc(I->RemoveRange.getBegin());
1136 if (LineNo == SM.getLineNumber(HintLocInfo.first, HintLocInfo.second)) {
1137 // Insert the new code into the line just below the code
1138 // that the user wrote.
1139 unsigned HintColNo
Seth Cantrell6749dd52012-04-18 02:44:46 +00001140 = SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second) - 1;
1141 // hint must start inside the source or right at the end
1142 assert(HintColNo<static_cast<unsigned>(map.bytes())+1);
1143 HintColNo = map.byteToColumn(HintColNo);
1144
Jordan Rose3772c9a2012-06-08 21:14:19 +00001145 // If we inserted a long previous hint, push this one forwards, and add
1146 // an extra space to show that this is not part of the previous
1147 // completion. This is sort of the best we can do when two hints appear
1148 // to overlap.
1149 //
1150 // Note that if this hint is located immediately after the previous
1151 // hint, no space will be added, since the location is more important.
1152 if (HintColNo < PrevHintEnd)
1153 HintColNo = PrevHintEnd + 1;
1154
Seth Cantrell6749dd52012-04-18 02:44:46 +00001155 // FIXME: if the fixit includes tabs or other characters that do not
1156 // take up a single column per byte when displayed then
1157 // I->CodeToInsert.size() is not a column number and we're mixing
1158 // units (columns + bytes). We should get printable versions
1159 // of each fixit before using them.
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001160 unsigned LastColumnModified
Seth Cantrell6749dd52012-04-18 02:44:46 +00001161 = HintColNo + I->CodeToInsert.size();
1162
Jordan Rose3772c9a2012-06-08 21:14:19 +00001163 if (LastColumnModified <= static_cast<unsigned>(map.bytes()))
Seth Cantrell6749dd52012-04-18 02:44:46 +00001164 LastColumnModified = map.byteToColumn(LastColumnModified);
Seth Cantrell6749dd52012-04-18 02:44:46 +00001165
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001166 if (LastColumnModified > FixItInsertionLine.size())
1167 FixItInsertionLine.resize(LastColumnModified, ' ');
Seth Cantrell6749dd52012-04-18 02:44:46 +00001168 assert(HintColNo+I->CodeToInsert.size() <= FixItInsertionLine.size());
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001169 std::copy(I->CodeToInsert.begin(), I->CodeToInsert.end(),
Seth Cantrell6749dd52012-04-18 02:44:46 +00001170 FixItInsertionLine.begin() + HintColNo);
Jordan Rose3772c9a2012-06-08 21:14:19 +00001171
1172 PrevHintEnd = LastColumnModified;
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001173 } else {
1174 FixItInsertionLine.clear();
1175 break;
1176 }
1177 }
1178 }
1179
Seth Cantrell6749dd52012-04-18 02:44:46 +00001180 expandTabs(FixItInsertionLine, DiagOpts.TabStop);
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001181
1182 return FixItInsertionLine;
1183}
1184
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +00001185void TextDiagnostic::emitParseableFixits(ArrayRef<FixItHint> Hints,
1186 const SourceManager &SM) {
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001187 if (!DiagOpts.ShowParseableFixits)
1188 return;
1189
1190 // We follow FixItRewriter's example in not (yet) handling
1191 // fix-its in macros.
1192 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1193 I != E; ++I) {
1194 if (I->RemoveRange.isInvalid() ||
1195 I->RemoveRange.getBegin().isMacroID() ||
1196 I->RemoveRange.getEnd().isMacroID())
1197 return;
1198 }
1199
1200 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1201 I != E; ++I) {
1202 SourceLocation BLoc = I->RemoveRange.getBegin();
1203 SourceLocation ELoc = I->RemoveRange.getEnd();
1204
1205 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(BLoc);
1206 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(ELoc);
1207
1208 // Adjust for token ranges.
1209 if (I->RemoveRange.isTokenRange())
1210 EInfo.second += Lexer::MeasureTokenLength(ELoc, SM, LangOpts);
1211
1212 // We specifically do not do word-wrapping or tab-expansion here,
1213 // because this is supposed to be easy to parse.
1214 PresumedLoc PLoc = SM.getPresumedLoc(BLoc);
1215 if (PLoc.isInvalid())
1216 break;
1217
1218 OS << "fix-it:\"";
1219 OS.write_escaped(PLoc.getFilename());
1220 OS << "\":{" << SM.getLineNumber(BInfo.first, BInfo.second)
1221 << ':' << SM.getColumnNumber(BInfo.first, BInfo.second)
1222 << '-' << SM.getLineNumber(EInfo.first, EInfo.second)
1223 << ':' << SM.getColumnNumber(EInfo.first, EInfo.second)
1224 << "}:\"";
1225 OS.write_escaped(I->CodeToInsert);
1226 OS << "\"\n";
1227 }
1228}