blob: e47b5687ff498985fb1538f84950d4e97868d003 [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>
Joerg Sonnenberger7094dee2012-08-10 10:58:18 +000023#include <cctype>
Seth Cantrell6749dd52012-04-18 02:44:46 +000024
Chandler Carruthdb463bb2011-10-15 23:43:53 +000025using namespace clang;
26
27static const enum raw_ostream::Colors noteColor =
28 raw_ostream::BLACK;
29static const enum raw_ostream::Colors fixitColor =
30 raw_ostream::GREEN;
31static const enum raw_ostream::Colors caretColor =
32 raw_ostream::GREEN;
33static const enum raw_ostream::Colors warningColor =
34 raw_ostream::MAGENTA;
Richard Trieu246b6aa2012-06-26 18:18:47 +000035static const enum raw_ostream::Colors templateColor =
36 raw_ostream::CYAN;
Chandler Carruthdb463bb2011-10-15 23:43:53 +000037static const enum raw_ostream::Colors errorColor = raw_ostream::RED;
38static const enum raw_ostream::Colors fatalColor = raw_ostream::RED;
39// Used for changing only the bold attribute.
40static const enum raw_ostream::Colors savedColor =
41 raw_ostream::SAVEDCOLOR;
42
Richard Trieu246b6aa2012-06-26 18:18:47 +000043/// \brief Add highlights to differences in template strings.
44static void applyTemplateHighlighting(raw_ostream &OS, StringRef Str,
Richard Trieub956e5a2012-06-28 22:39:03 +000045 bool &Normal, bool Bold) {
Benjamin Kramer4ca3abd2012-10-18 20:09:54 +000046 while (1) {
47 size_t Pos = Str.find(ToggleHighlight);
48 OS << Str.slice(0, Pos);
49 if (Pos == StringRef::npos)
50 break;
51
52 Str = Str.substr(Pos + 1);
53 if (Normal)
54 OS.changeColor(templateColor, true);
55 else {
56 OS.resetColor();
57 if (Bold)
58 OS.changeColor(savedColor, true);
Richard Trieu246b6aa2012-06-26 18:18:47 +000059 }
Benjamin Kramer4ca3abd2012-10-18 20:09:54 +000060 Normal = !Normal;
61 }
Richard Trieu246b6aa2012-06-26 18:18:47 +000062}
63
Chandler Carruthdb463bb2011-10-15 23:43:53 +000064/// \brief Number of spaces to indent when word-wrapping.
65const unsigned WordWrapIndentation = 6;
66
Benjamin Kramerd1fda032012-05-01 14:34:11 +000067static int bytesSincePreviousTabOrLineBegin(StringRef SourceLine, size_t i) {
Seth Cantrell6749dd52012-04-18 02:44:46 +000068 int bytes = 0;
69 while (0<i) {
70 if (SourceLine[--i]=='\t')
71 break;
72 ++bytes;
73 }
74 return bytes;
75}
76
77/// \brief returns a printable representation of first item from input range
78///
79/// This function returns a printable representation of the next item in a line
80/// of source. If the next byte begins a valid and printable character, that
81/// character is returned along with 'true'.
82///
83/// Otherwise, if the next byte begins a valid, but unprintable character, a
84/// printable, escaped representation of the character is returned, along with
85/// 'false'. Otherwise a printable, escaped representation of the next byte
86/// is returned along with 'false'.
87///
88/// \note The index is updated to be used with a subsequent call to
89/// printableTextForNextCharacter.
90///
91/// \param SourceLine The line of source
92/// \param i Pointer to byte index,
93/// \param TabStop used to expand tabs
Sylvestre Ledruf3477c12012-09-27 10:16:10 +000094/// \return pair(printable text, 'true' iff original text was printable)
Seth Cantrell6749dd52012-04-18 02:44:46 +000095///
Benjamin Kramerd1fda032012-05-01 14:34:11 +000096static std::pair<SmallString<16>, bool>
Seth Cantrell6749dd52012-04-18 02:44:46 +000097printableTextForNextCharacter(StringRef SourceLine, size_t *i,
98 unsigned TabStop) {
99 assert(i && "i must not be null");
100 assert(*i<SourceLine.size() && "must point to a valid index");
101
102 if (SourceLine[*i]=='\t') {
103 assert(0 < TabStop && TabStop <= DiagnosticOptions::MaxTabStop &&
104 "Invalid -ftabstop value");
105 unsigned col = bytesSincePreviousTabOrLineBegin(SourceLine, *i);
106 unsigned NumSpaces = TabStop - col%TabStop;
107 assert(0 < NumSpaces && NumSpaces <= TabStop
108 && "Invalid computation of space amt");
109 ++(*i);
110
111 SmallString<16> expandedTab;
112 expandedTab.assign(NumSpaces, ' ');
113 return std::make_pair(expandedTab, true);
114 }
115
116 // FIXME: this data is copied from the private implementation of ConvertUTF.h
117 static const char trailingBytesForUTF8[256] = {
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 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,
121 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,
122 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,
123 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,
124 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,
125 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
126 };
127
128 unsigned char const *begin, *end;
129 begin = reinterpret_cast<unsigned char const *>(&*(SourceLine.begin() + *i));
130 end = begin + SourceLine.size();
131
132 if (isLegalUTF8Sequence(begin, end)) {
133 UTF32 c;
134 UTF32 *cptr = &c;
135 unsigned char const *original_begin = begin;
136 char trailingBytes = trailingBytesForUTF8[(unsigned char)SourceLine[*i]];
137 unsigned char const *cp_end = begin+trailingBytes+1;
138
139 ConversionResult res = ConvertUTF8toUTF32(&begin, cp_end, &cptr, cptr+1,
140 strictConversion);
Matt Beaumont-Gay0ddb0972012-04-18 17:25:16 +0000141 (void)res;
Seth Cantrell6749dd52012-04-18 02:44:46 +0000142 assert(conversionOK==res);
143 assert(0 < begin-original_begin
144 && "we must be further along in the string now");
145 *i += begin-original_begin;
146
147 if (!llvm::sys::locale::isPrint(c)) {
148 // If next character is valid UTF-8, but not printable
149 SmallString<16> expandedCP("<U+>");
150 while (c) {
151 expandedCP.insert(expandedCP.begin()+3, llvm::hexdigit(c%16));
152 c/=16;
153 }
154 while (expandedCP.size() < 8)
155 expandedCP.insert(expandedCP.begin()+3, llvm::hexdigit(0));
156 return std::make_pair(expandedCP, false);
157 }
158
159 // If next character is valid UTF-8, and printable
160 return std::make_pair(SmallString<16>(original_begin, cp_end), true);
161
162 }
163
164 // If next byte is not valid UTF-8 (and therefore not printable)
165 SmallString<16> expandedByte("<XX>");
166 unsigned char byte = SourceLine[*i];
167 expandedByte[1] = llvm::hexdigit(byte / 16);
168 expandedByte[2] = llvm::hexdigit(byte % 16);
169 ++(*i);
170 return std::make_pair(expandedByte, false);
171}
172
Benjamin Kramerd1fda032012-05-01 14:34:11 +0000173static void expandTabs(std::string &SourceLine, unsigned TabStop) {
Seth Cantrell6749dd52012-04-18 02:44:46 +0000174 size_t i = SourceLine.size();
175 while (i>0) {
176 i--;
177 if (SourceLine[i]!='\t')
178 continue;
179 size_t tmp_i = i;
180 std::pair<SmallString<16>,bool> res
181 = printableTextForNextCharacter(SourceLine, &tmp_i, TabStop);
182 SourceLine.replace(i, 1, res.first.c_str());
183 }
184}
185
186/// This function takes a raw source line and produces a mapping from the bytes
187/// of the printable representation of the line to the columns those printable
188/// characters will appear at (numbering the first column as 0).
189///
190/// If a byte 'i' corresponds to muliple columns (e.g. the byte contains a tab
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +0000191/// character) then the array will map that byte to the first column the
Seth Cantrell6749dd52012-04-18 02:44:46 +0000192/// tab appears at and the next value in the map will have been incremented
193/// more than once.
194///
195/// If a byte is the first in a sequence of bytes that together map to a single
196/// entity in the output, then the array will map that byte to the appropriate
197/// column while the subsequent bytes will be -1.
198///
199/// The last element in the array does not correspond to any byte in the input
200/// and instead is the number of columns needed to display the source
201///
202/// example: (given a tabstop of 8)
203///
204/// "a \t \u3042" -> {0,1,2,8,9,-1,-1,11}
205///
James Dennett6b4f5062012-06-22 05:33:23 +0000206/// (\\u3042 is represented in UTF-8 by three bytes and takes two columns to
Seth Cantrell6749dd52012-04-18 02:44:46 +0000207/// display)
Benjamin Kramerd1fda032012-05-01 14:34:11 +0000208static void byteToColumn(StringRef SourceLine, unsigned TabStop,
209 SmallVectorImpl<int> &out) {
Seth Cantrell6749dd52012-04-18 02:44:46 +0000210 out.clear();
211
212 if (SourceLine.empty()) {
213 out.resize(1u,0);
214 return;
215 }
216
217 out.resize(SourceLine.size()+1, -1);
218
219 int columns = 0;
220 size_t i = 0;
221 while (i<SourceLine.size()) {
222 out[i] = columns;
223 std::pair<SmallString<16>,bool> res
224 = printableTextForNextCharacter(SourceLine, &i, TabStop);
225 columns += llvm::sys::locale::columnWidth(res.first);
226 }
227 out.back() = columns;
228}
229
230/// This function takes a raw source line and produces a mapping from columns
231/// to the byte of the source line that produced the character displaying at
232/// that column. This is the inverse of the mapping produced by byteToColumn()
233///
234/// The last element in the array is the number of bytes in the source string
235///
236/// example: (given a tabstop of 8)
237///
238/// "a \t \u3042" -> {0,1,2,-1,-1,-1,-1,-1,3,4,-1,7}
239///
James Dennett6b4f5062012-06-22 05:33:23 +0000240/// (\\u3042 is represented in UTF-8 by three bytes and takes two columns to
Seth Cantrell6749dd52012-04-18 02:44:46 +0000241/// display)
Benjamin Kramerd1fda032012-05-01 14:34:11 +0000242static void columnToByte(StringRef SourceLine, unsigned TabStop,
Seth Cantrell6749dd52012-04-18 02:44:46 +0000243 SmallVectorImpl<int> &out) {
244 out.clear();
245
246 if (SourceLine.empty()) {
247 out.resize(1u, 0);
248 return;
249 }
250
251 int columns = 0;
252 size_t i = 0;
253 while (i<SourceLine.size()) {
254 out.resize(columns+1, -1);
255 out.back() = i;
256 std::pair<SmallString<16>,bool> res
257 = printableTextForNextCharacter(SourceLine, &i, TabStop);
258 columns += llvm::sys::locale::columnWidth(res.first);
259 }
260 out.resize(columns+1, -1);
261 out.back() = i;
262}
263
264struct SourceColumnMap {
265 SourceColumnMap(StringRef SourceLine, unsigned TabStop)
266 : m_SourceLine(SourceLine) {
267
268 ::byteToColumn(SourceLine, TabStop, m_byteToColumn);
269 ::columnToByte(SourceLine, TabStop, m_columnToByte);
270
271 assert(m_byteToColumn.size()==SourceLine.size()+1);
272 assert(0 < m_byteToColumn.size() && 0 < m_columnToByte.size());
273 assert(m_byteToColumn.size()
274 == static_cast<unsigned>(m_columnToByte.back()+1));
275 assert(static_cast<unsigned>(m_byteToColumn.back()+1)
276 == m_columnToByte.size());
277 }
278 int columns() const { return m_byteToColumn.back(); }
279 int bytes() const { return m_columnToByte.back(); }
Richard Smithc7bb3842012-09-13 18:37:50 +0000280
281 /// \brief Map a byte to the column which it is at the start of, or return -1
282 /// if it is not at the start of a column (for a UTF-8 trailing byte).
Seth Cantrell6749dd52012-04-18 02:44:46 +0000283 int byteToColumn(int n) const {
284 assert(0<=n && n<static_cast<int>(m_byteToColumn.size()));
285 return m_byteToColumn[n];
286 }
Richard Smithc7bb3842012-09-13 18:37:50 +0000287
288 /// \brief Map a byte to the first column which contains it.
289 int byteToContainingColumn(int N) const {
290 assert(0 <= N && N < static_cast<int>(m_byteToColumn.size()));
291 while (m_byteToColumn[N] == -1)
292 --N;
293 return m_byteToColumn[N];
294 }
295
296 /// \brief Map a column to the byte which starts the column, or return -1 if
297 /// the column the second or subsequent column of an expanded tab or similar
298 /// multi-column entity.
Seth Cantrell6749dd52012-04-18 02:44:46 +0000299 int columnToByte(int n) const {
300 assert(0<=n && n<static_cast<int>(m_columnToByte.size()));
301 return m_columnToByte[n];
302 }
Richard Smithc7bb3842012-09-13 18:37:50 +0000303
304 /// \brief Map from a byte index to the next byte which starts a column.
305 int startOfNextColumn(int N) const {
306 assert(0 <= N && N < static_cast<int>(m_columnToByte.size() - 1));
307 while (byteToColumn(++N) == -1) {}
308 return N;
309 }
310
311 /// \brief Map from a byte index to the previous byte which starts a column.
312 int startOfPreviousColumn(int N) const {
313 assert(0 < N && N < static_cast<int>(m_columnToByte.size()));
314 while (byteToColumn(N--) == -1) {}
315 return N;
316 }
317
Seth Cantrell6749dd52012-04-18 02:44:46 +0000318 StringRef getSourceLine() const {
319 return m_SourceLine;
320 }
321
322private:
323 const std::string m_SourceLine;
324 SmallVector<int,200> m_byteToColumn;
325 SmallVector<int,200> m_columnToByte;
326};
327
328// used in assert in selectInterestingSourceRegion()
329namespace {
330struct char_out_of_range {
331 const char lower,upper;
332 char_out_of_range(char lower, char upper) :
333 lower(lower), upper(upper) {}
334 bool operator()(char c) { return c < lower || upper < c; }
335};
336}
337
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000338/// \brief When the source code line we want to print is too long for
339/// the terminal, select the "interesting" region.
Chandler Carruth7531f572011-10-15 23:54:09 +0000340static void selectInterestingSourceRegion(std::string &SourceLine,
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000341 std::string &CaretLine,
342 std::string &FixItInsertionLine,
Seth Cantrell6749dd52012-04-18 02:44:46 +0000343 unsigned Columns,
344 const SourceColumnMap &map) {
345 unsigned MaxColumns = std::max<unsigned>(map.columns(),
346 std::max(CaretLine.size(),
347 FixItInsertionLine.size()));
348 // if the number of columns is less than the desired number we're done
349 if (MaxColumns <= Columns)
350 return;
351
352 // no special characters allowed in CaretLine or FixItInsertionLine
353 assert(CaretLine.end() ==
354 std::find_if(CaretLine.begin(), CaretLine.end(),
355 char_out_of_range(' ','~')));
356 assert(FixItInsertionLine.end() ==
357 std::find_if(FixItInsertionLine.begin(), FixItInsertionLine.end(),
358 char_out_of_range(' ','~')));
359
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000360 // Find the slice that we need to display the full caret line
361 // correctly.
362 unsigned CaretStart = 0, CaretEnd = CaretLine.size();
363 for (; CaretStart != CaretEnd; ++CaretStart)
Seth Cantrell4031a372012-05-25 00:03:29 +0000364 if (!isspace(static_cast<unsigned char>(CaretLine[CaretStart])))
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000365 break;
366
367 for (; CaretEnd != CaretStart; --CaretEnd)
Seth Cantrell4031a372012-05-25 00:03:29 +0000368 if (!isspace(static_cast<unsigned char>(CaretLine[CaretEnd - 1])))
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000369 break;
370
Seth Cantrell6749dd52012-04-18 02:44:46 +0000371 // caret has already been inserted into CaretLine so the above whitespace
372 // check is guaranteed to include the caret
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000373
374 // If we have a fix-it line, make sure the slice includes all of the
375 // fix-it information.
376 if (!FixItInsertionLine.empty()) {
377 unsigned FixItStart = 0, FixItEnd = FixItInsertionLine.size();
378 for (; FixItStart != FixItEnd; ++FixItStart)
Seth Cantrell4031a372012-05-25 00:03:29 +0000379 if (!isspace(static_cast<unsigned char>(FixItInsertionLine[FixItStart])))
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000380 break;
381
382 for (; FixItEnd != FixItStart; --FixItEnd)
Seth Cantrell4031a372012-05-25 00:03:29 +0000383 if (!isspace(static_cast<unsigned char>(FixItInsertionLine[FixItEnd - 1])))
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000384 break;
385
Seth Cantrell6749dd52012-04-18 02:44:46 +0000386 CaretStart = std::min(FixItStart, CaretStart);
387 CaretEnd = std::max(FixItEnd, CaretEnd);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000388 }
389
Seth Cantrellc5493d72012-05-24 05:14:44 +0000390 // CaretEnd may have been set at the middle of a character
391 // If it's not at a character's first column then advance it past the current
392 // character.
393 while (static_cast<int>(CaretEnd) < map.columns() &&
394 -1 == map.columnToByte(CaretEnd))
395 ++CaretEnd;
396
397 assert((static_cast<int>(CaretStart) > map.columns() ||
398 -1!=map.columnToByte(CaretStart)) &&
399 "CaretStart must not point to a column in the middle of a source"
400 " line character");
401 assert((static_cast<int>(CaretEnd) > map.columns() ||
402 -1!=map.columnToByte(CaretEnd)) &&
403 "CaretEnd must not point to a column in the middle of a source line"
404 " character");
405
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000406 // CaretLine[CaretStart, CaretEnd) contains all of the interesting
407 // parts of the caret line. While this slice is smaller than the
408 // number of columns we have, try to grow the slice to encompass
409 // more context.
410
Seth Cantrell6749dd52012-04-18 02:44:46 +0000411 unsigned SourceStart = map.columnToByte(std::min<unsigned>(CaretStart,
412 map.columns()));
413 unsigned SourceEnd = map.columnToByte(std::min<unsigned>(CaretEnd,
414 map.columns()));
415
416 unsigned CaretColumnsOutsideSource = CaretEnd-CaretStart
417 - (map.byteToColumn(SourceEnd)-map.byteToColumn(SourceStart));
418
419 char const *front_ellipse = " ...";
420 char const *front_space = " ";
421 char const *back_ellipse = "...";
422 unsigned ellipses_space = strlen(front_ellipse) + strlen(back_ellipse);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000423
424 unsigned TargetColumns = Columns;
Seth Cantrell6749dd52012-04-18 02:44:46 +0000425 // Give us extra room for the ellipses
426 // and any of the caret line that extends past the source
427 if (TargetColumns > ellipses_space+CaretColumnsOutsideSource)
428 TargetColumns -= ellipses_space+CaretColumnsOutsideSource;
429
430 while (SourceStart>0 || SourceEnd<SourceLine.size()) {
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000431 bool ExpandedRegion = false;
Seth Cantrell6749dd52012-04-18 02:44:46 +0000432
433 if (SourceStart>0) {
434 unsigned NewStart = SourceStart-1;
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000435
436 // Skip over any whitespace we see here; we're looking for
437 // another bit of interesting text.
Richard Smithc7bb3842012-09-13 18:37:50 +0000438 // FIXME: Detect non-ASCII whitespace characters too.
Seth Cantrell6749dd52012-04-18 02:44:46 +0000439 while (NewStart &&
Richard Smithc7bb3842012-09-13 18:37:50 +0000440 isspace(static_cast<unsigned char>(SourceLine[NewStart])))
441 NewStart = map.startOfPreviousColumn(NewStart);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000442
443 // Skip over this bit of "interesting" text.
Richard Smithc7bb3842012-09-13 18:37:50 +0000444 while (NewStart) {
445 unsigned Prev = map.startOfPreviousColumn(NewStart);
446 if (isspace(static_cast<unsigned char>(SourceLine[Prev])))
447 break;
448 NewStart = Prev;
449 }
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000450
Richard Smithc7bb3842012-09-13 18:37:50 +0000451 assert(map.byteToColumn(NewStart) != -1);
Seth Cantrell6749dd52012-04-18 02:44:46 +0000452 unsigned NewColumns = map.byteToColumn(SourceEnd) -
453 map.byteToColumn(NewStart);
454 if (NewColumns <= TargetColumns) {
455 SourceStart = NewStart;
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000456 ExpandedRegion = true;
457 }
458 }
459
Seth Cantrell6749dd52012-04-18 02:44:46 +0000460 if (SourceEnd<SourceLine.size()) {
461 unsigned NewEnd = SourceEnd+1;
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000462
463 // Skip over any whitespace we see here; we're looking for
464 // another bit of interesting text.
Richard Smithc7bb3842012-09-13 18:37:50 +0000465 // FIXME: Detect non-ASCII whitespace characters too.
466 while (NewEnd < SourceLine.size() &&
467 isspace(static_cast<unsigned char>(SourceLine[NewEnd])))
468 NewEnd = map.startOfNextColumn(NewEnd);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000469
470 // Skip over this bit of "interesting" text.
Richard Smithc7bb3842012-09-13 18:37:50 +0000471 while (NewEnd < SourceLine.size() &&
472 !isspace(static_cast<unsigned char>(SourceLine[NewEnd])))
473 NewEnd = map.startOfNextColumn(NewEnd);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000474
Richard Smithc7bb3842012-09-13 18:37:50 +0000475 assert(map.byteToColumn(NewEnd) != -1);
Seth Cantrell6749dd52012-04-18 02:44:46 +0000476 unsigned NewColumns = map.byteToColumn(NewEnd) -
477 map.byteToColumn(SourceStart);
478 if (NewColumns <= TargetColumns) {
479 SourceEnd = NewEnd;
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000480 ExpandedRegion = true;
481 }
482 }
483
484 if (!ExpandedRegion)
485 break;
486 }
487
Seth Cantrell6749dd52012-04-18 02:44:46 +0000488 CaretStart = map.byteToColumn(SourceStart);
489 CaretEnd = map.byteToColumn(SourceEnd) + CaretColumnsOutsideSource;
490
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000491 // [CaretStart, CaretEnd) is the slice we want. Update the various
492 // output lines to show only this slice, with two-space padding
493 // before the lines so that it looks nicer.
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000494
Seth Cantrell6749dd52012-04-18 02:44:46 +0000495 assert(CaretStart!=(unsigned)-1 && CaretEnd!=(unsigned)-1 &&
496 SourceStart!=(unsigned)-1 && SourceEnd!=(unsigned)-1);
497 assert(SourceStart <= SourceEnd);
498 assert(CaretStart <= CaretEnd);
499
500 unsigned BackColumnsRemoved
501 = map.byteToColumn(SourceLine.size())-map.byteToColumn(SourceEnd);
502 unsigned FrontColumnsRemoved = CaretStart;
503 unsigned ColumnsKept = CaretEnd-CaretStart;
504
505 // We checked up front that the line needed truncation
506 assert(FrontColumnsRemoved+ColumnsKept+BackColumnsRemoved > Columns);
507
508 // The line needs some trunctiona, and we'd prefer to keep the front
509 // if possible, so remove the back
510 if (BackColumnsRemoved)
511 SourceLine.replace(SourceEnd, std::string::npos, back_ellipse);
512
513 // If that's enough then we're done
514 if (FrontColumnsRemoved+ColumnsKept <= Columns)
515 return;
516
517 // Otherwise remove the front as well
518 if (FrontColumnsRemoved) {
519 SourceLine.replace(0, SourceStart, front_ellipse);
520 CaretLine.replace(0, CaretStart, front_space);
521 if (!FixItInsertionLine.empty())
522 FixItInsertionLine.replace(0, CaretStart, front_space);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000523 }
524}
525
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000526/// \brief Skip over whitespace in the string, starting at the given
527/// index.
528///
529/// \returns The index of the first non-whitespace character that is
530/// greater than or equal to Idx or, if no such character exists,
531/// returns the end of the string.
532static unsigned skipWhitespace(unsigned Idx, StringRef Str, unsigned Length) {
533 while (Idx < Length && isspace(Str[Idx]))
534 ++Idx;
535 return Idx;
536}
537
538/// \brief If the given character is the start of some kind of
539/// balanced punctuation (e.g., quotes or parentheses), return the
540/// character that will terminate the punctuation.
541///
542/// \returns The ending punctuation character, if any, or the NULL
543/// character if the input character does not start any punctuation.
544static inline char findMatchingPunctuation(char c) {
545 switch (c) {
546 case '\'': return '\'';
547 case '`': return '\'';
548 case '"': return '"';
549 case '(': return ')';
550 case '[': return ']';
551 case '{': return '}';
552 default: break;
553 }
554
555 return 0;
556}
557
558/// \brief Find the end of the word starting at the given offset
559/// within a string.
560///
561/// \returns the index pointing one character past the end of the
562/// word.
563static unsigned findEndOfWord(unsigned Start, StringRef Str,
564 unsigned Length, unsigned Column,
565 unsigned Columns) {
566 assert(Start < Str.size() && "Invalid start position!");
567 unsigned End = Start + 1;
568
569 // If we are already at the end of the string, take that as the word.
570 if (End == Str.size())
571 return End;
572
573 // Determine if the start of the string is actually opening
574 // punctuation, e.g., a quote or parentheses.
575 char EndPunct = findMatchingPunctuation(Str[Start]);
576 if (!EndPunct) {
577 // This is a normal word. Just find the first space character.
578 while (End < Length && !isspace(Str[End]))
579 ++End;
580 return End;
581 }
582
583 // We have the start of a balanced punctuation sequence (quotes,
584 // parentheses, etc.). Determine the full sequence is.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000585 SmallString<16> PunctuationEndStack;
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000586 PunctuationEndStack.push_back(EndPunct);
587 while (End < Length && !PunctuationEndStack.empty()) {
588 if (Str[End] == PunctuationEndStack.back())
589 PunctuationEndStack.pop_back();
590 else if (char SubEndPunct = findMatchingPunctuation(Str[End]))
591 PunctuationEndStack.push_back(SubEndPunct);
592
593 ++End;
594 }
595
596 // Find the first space character after the punctuation ended.
597 while (End < Length && !isspace(Str[End]))
598 ++End;
599
600 unsigned PunctWordLength = End - Start;
601 if (// If the word fits on this line
602 Column + PunctWordLength <= Columns ||
603 // ... or the word is "short enough" to take up the next line
604 // without too much ugly white space
605 PunctWordLength < Columns/3)
606 return End; // Take the whole thing as a single "word".
607
608 // The whole quoted/parenthesized string is too long to print as a
609 // single "word". Instead, find the "word" that starts just after
610 // the punctuation and use that end-point instead. This will recurse
611 // until it finds something small enough to consider a word.
612 return findEndOfWord(Start + 1, Str, Length, Column + 1, Columns);
613}
614
615/// \brief Print the given string to a stream, word-wrapping it to
616/// some number of columns in the process.
617///
618/// \param OS the stream to which the word-wrapping string will be
619/// emitted.
620/// \param Str the string to word-wrap and output.
621/// \param Columns the number of columns to word-wrap to.
622/// \param Column the column number at which the first character of \p
623/// Str will be printed. This will be non-zero when part of the first
624/// line has already been printed.
Richard Trieub956e5a2012-06-28 22:39:03 +0000625/// \param Bold if the current text should be bold
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000626/// \param Indentation the number of spaces to indent any lines beyond
627/// the first line.
628/// \returns true if word-wrapping was required, or false if the
629/// string fit on the first line.
630static bool printWordWrapped(raw_ostream &OS, StringRef Str,
631 unsigned Columns,
632 unsigned Column = 0,
Richard Trieub956e5a2012-06-28 22:39:03 +0000633 bool Bold = false,
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000634 unsigned Indentation = WordWrapIndentation) {
635 const unsigned Length = std::min(Str.find('\n'), Str.size());
Richard Trieu246b6aa2012-06-26 18:18:47 +0000636 bool TextNormal = true;
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000637
638 // The string used to indent each line.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000639 SmallString<16> IndentStr;
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000640 IndentStr.assign(Indentation, ' ');
641 bool Wrapped = false;
642 for (unsigned WordStart = 0, WordEnd; WordStart < Length;
643 WordStart = WordEnd) {
644 // Find the beginning of the next word.
645 WordStart = skipWhitespace(WordStart, Str, Length);
646 if (WordStart == Length)
647 break;
648
649 // Find the end of this word.
650 WordEnd = findEndOfWord(WordStart, Str, Length, Column, Columns);
651
652 // Does this word fit on the current line?
653 unsigned WordLength = WordEnd - WordStart;
654 if (Column + WordLength < Columns) {
655 // This word fits on the current line; print it there.
656 if (WordStart) {
657 OS << ' ';
658 Column += 1;
659 }
Richard Trieu246b6aa2012-06-26 18:18:47 +0000660 applyTemplateHighlighting(OS, Str.substr(WordStart, WordLength),
Richard Trieub956e5a2012-06-28 22:39:03 +0000661 TextNormal, Bold);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000662 Column += WordLength;
663 continue;
664 }
665
666 // This word does not fit on the current line, so wrap to the next
667 // line.
668 OS << '\n';
669 OS.write(&IndentStr[0], Indentation);
Richard Trieu246b6aa2012-06-26 18:18:47 +0000670 applyTemplateHighlighting(OS, Str.substr(WordStart, WordLength),
Richard Trieub956e5a2012-06-28 22:39:03 +0000671 TextNormal, Bold);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000672 Column = Indentation + WordLength;
673 Wrapped = true;
674 }
675
676 // Append any remaning text from the message with its existing formatting.
Richard Trieub956e5a2012-06-28 22:39:03 +0000677 applyTemplateHighlighting(OS, Str.substr(Length), TextNormal, Bold);
Richard Trieu246b6aa2012-06-26 18:18:47 +0000678
679 assert(TextNormal && "Text highlighted at end of diagnostic message.");
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000680
681 return Wrapped;
682}
683
684TextDiagnostic::TextDiagnostic(raw_ostream &OS,
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000685 const LangOptions &LangOpts,
Chandler Carruth21a869a2011-10-16 02:57:39 +0000686 const DiagnosticOptions &DiagOpts)
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000687 : DiagnosticRenderer(LangOpts, DiagOpts), OS(OS) {}
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000688
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000689TextDiagnostic::~TextDiagnostic() {}
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000690
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000691void
692TextDiagnostic::emitDiagnosticMessage(SourceLocation Loc,
693 PresumedLoc PLoc,
694 DiagnosticsEngine::Level Level,
695 StringRef Message,
696 ArrayRef<clang::CharSourceRange> Ranges,
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000697 const SourceManager *SM,
Ted Kremenek8be51ea2012-02-14 02:46:00 +0000698 DiagOrStoredDiag D) {
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000699 uint64_t StartOfLocationInfo = OS.tell();
700
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000701 // Emit the location of this particular diagnostic.
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000702 if (Loc.isValid())
703 emitDiagnosticLoc(Loc, PLoc, Level, Ranges, *SM);
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000704
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000705 if (DiagOpts.ShowColors)
706 OS.resetColor();
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000707
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000708 printDiagnosticLevel(OS, Level, DiagOpts.ShowColors);
709 printDiagnosticMessage(OS, Level, Message,
710 OS.tell() - StartOfLocationInfo,
711 DiagOpts.MessageLength, DiagOpts.ShowColors);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000712}
713
Chandler Carruth6ddd8872011-10-15 23:48:02 +0000714/*static*/ void
715TextDiagnostic::printDiagnosticLevel(raw_ostream &OS,
716 DiagnosticsEngine::Level Level,
717 bool ShowColors) {
718 if (ShowColors) {
719 // Print diagnostic category in bold and color
720 switch (Level) {
721 case DiagnosticsEngine::Ignored:
722 llvm_unreachable("Invalid diagnostic type");
723 case DiagnosticsEngine::Note: OS.changeColor(noteColor, true); break;
724 case DiagnosticsEngine::Warning: OS.changeColor(warningColor, true); break;
725 case DiagnosticsEngine::Error: OS.changeColor(errorColor, true); break;
726 case DiagnosticsEngine::Fatal: OS.changeColor(fatalColor, true); break;
727 }
728 }
729
730 switch (Level) {
731 case DiagnosticsEngine::Ignored:
732 llvm_unreachable("Invalid diagnostic type");
733 case DiagnosticsEngine::Note: OS << "note: "; break;
734 case DiagnosticsEngine::Warning: OS << "warning: "; break;
735 case DiagnosticsEngine::Error: OS << "error: "; break;
736 case DiagnosticsEngine::Fatal: OS << "fatal error: "; break;
737 }
738
739 if (ShowColors)
740 OS.resetColor();
741}
742
743/*static*/ void
744TextDiagnostic::printDiagnosticMessage(raw_ostream &OS,
745 DiagnosticsEngine::Level Level,
746 StringRef Message,
747 unsigned CurrentColumn, unsigned Columns,
748 bool ShowColors) {
Richard Trieub956e5a2012-06-28 22:39:03 +0000749 bool Bold = false;
Chandler Carruth6ddd8872011-10-15 23:48:02 +0000750 if (ShowColors) {
751 // Print warnings, errors and fatal errors in bold, no color
752 switch (Level) {
Richard Trieub956e5a2012-06-28 22:39:03 +0000753 case DiagnosticsEngine::Warning:
754 case DiagnosticsEngine::Error:
755 case DiagnosticsEngine::Fatal:
756 OS.changeColor(savedColor, true);
757 Bold = true;
758 break;
Chandler Carruth6ddd8872011-10-15 23:48:02 +0000759 default: break; //don't bold notes
760 }
761 }
762
763 if (Columns)
Richard Trieub956e5a2012-06-28 22:39:03 +0000764 printWordWrapped(OS, Message, Columns, CurrentColumn, Bold);
David Blaikie50badd52012-06-28 21:46:07 +0000765 else {
766 bool Normal = true;
Richard Trieub956e5a2012-06-28 22:39:03 +0000767 applyTemplateHighlighting(OS, Message, Normal, Bold);
David Blaikie50badd52012-06-28 21:46:07 +0000768 assert(Normal && "Formatting should have returned to normal");
769 }
Chandler Carruth6ddd8872011-10-15 23:48:02 +0000770
771 if (ShowColors)
772 OS.resetColor();
773 OS << '\n';
774}
775
Chandler Carruth6ddd8872011-10-15 23:48:02 +0000776/// \brief Print out the file/line/column information and include trace.
777///
778/// This method handlen the emission of the diagnostic location information.
779/// This includes extracting as much location information as is present for
780/// the diagnostic and printing it, as well as any include stack or source
781/// ranges necessary.
Chandler Carruth7531f572011-10-15 23:54:09 +0000782void TextDiagnostic::emitDiagnosticLoc(SourceLocation Loc, PresumedLoc PLoc,
Chandler Carruth6ddd8872011-10-15 23:48:02 +0000783 DiagnosticsEngine::Level Level,
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000784 ArrayRef<CharSourceRange> Ranges,
785 const SourceManager &SM) {
Chandler Carruth6ddd8872011-10-15 23:48:02 +0000786 if (PLoc.isInvalid()) {
787 // At least print the file name if available:
788 FileID FID = SM.getFileID(Loc);
789 if (!FID.isInvalid()) {
790 const FileEntry* FE = SM.getFileEntryForID(FID);
791 if (FE && FE->getName()) {
792 OS << FE->getName();
793 if (FE->getDevice() == 0 && FE->getInode() == 0
794 && FE->getFileMode() == 0) {
795 // in PCH is a guess, but a good one:
796 OS << " (in PCH)";
797 }
798 OS << ": ";
799 }
800 }
801 return;
802 }
803 unsigned LineNo = PLoc.getLine();
804
805 if (!DiagOpts.ShowLocation)
806 return;
807
808 if (DiagOpts.ShowColors)
809 OS.changeColor(savedColor, true);
810
811 OS << PLoc.getFilename();
812 switch (DiagOpts.Format) {
813 case DiagnosticOptions::Clang: OS << ':' << LineNo; break;
814 case DiagnosticOptions::Msvc: OS << '(' << LineNo; break;
815 case DiagnosticOptions::Vi: OS << " +" << LineNo; break;
816 }
817
818 if (DiagOpts.ShowColumn)
819 // Compute the column number.
820 if (unsigned ColNo = PLoc.getColumn()) {
821 if (DiagOpts.Format == DiagnosticOptions::Msvc) {
822 OS << ',';
823 ColNo--;
824 } else
825 OS << ':';
826 OS << ColNo;
827 }
828 switch (DiagOpts.Format) {
829 case DiagnosticOptions::Clang:
830 case DiagnosticOptions::Vi: OS << ':'; break;
831 case DiagnosticOptions::Msvc: OS << ") : "; break;
832 }
833
834 if (DiagOpts.ShowSourceRanges && !Ranges.empty()) {
835 FileID CaretFileID =
836 SM.getFileID(SM.getExpansionLoc(Loc));
837 bool PrintedRange = false;
838
839 for (ArrayRef<CharSourceRange>::const_iterator RI = Ranges.begin(),
840 RE = Ranges.end();
841 RI != RE; ++RI) {
842 // Ignore invalid ranges.
843 if (!RI->isValid()) continue;
844
845 SourceLocation B = SM.getExpansionLoc(RI->getBegin());
846 SourceLocation E = SM.getExpansionLoc(RI->getEnd());
847
848 // If the End location and the start location are the same and are a
849 // macro location, then the range was something that came from a
850 // macro expansion or _Pragma. If this is an object-like macro, the
851 // best we can do is to highlight the range. If this is a
852 // function-like macro, we'd also like to highlight the arguments.
853 if (B == E && RI->getEnd().isMacroID())
854 E = SM.getExpansionRange(RI->getEnd()).second;
855
856 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(B);
857 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E);
858
859 // If the start or end of the range is in another file, just discard
860 // it.
861 if (BInfo.first != CaretFileID || EInfo.first != CaretFileID)
862 continue;
863
864 // Add in the length of the token, so that we cover multi-char
865 // tokens.
866 unsigned TokSize = 0;
867 if (RI->isTokenRange())
868 TokSize = Lexer::MeasureTokenLength(E, SM, LangOpts);
869
870 OS << '{' << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
871 << SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
872 << SM.getLineNumber(EInfo.first, EInfo.second) << ':'
873 << (SM.getColumnNumber(EInfo.first, EInfo.second)+TokSize)
874 << '}';
875 PrintedRange = true;
876 }
877
878 if (PrintedRange)
879 OS << ':';
880 }
881 OS << ' ';
882}
883
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000884void TextDiagnostic::emitBasicNote(StringRef Message) {
885 // FIXME: Emit this as a real note diagnostic.
886 // FIXME: Format an actual diagnostic rather than a hard coded string.
887 OS << "note: " << Message << "\n";
888}
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000889
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000890void TextDiagnostic::emitIncludeLocation(SourceLocation Loc,
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000891 PresumedLoc PLoc,
892 const SourceManager &SM) {
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000893 if (DiagOpts.ShowLocation)
894 OS << "In file included from " << PLoc.getFilename() << ':'
895 << PLoc.getLine() << ":\n";
896 else
897 OS << "In included file:\n";
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000898}
899
900/// \brief Emit a code snippet and caret line.
901///
902/// This routine emits a single line's code snippet and caret line..
903///
904/// \param Loc The location for the caret.
905/// \param Ranges The underlined ranges for this code snippet.
906/// \param Hints The FixIt hints active for this diagnostic.
Chandler Carruth7531f572011-10-15 23:54:09 +0000907void TextDiagnostic::emitSnippetAndCaret(
Chandler Carruth4ba55652011-10-16 07:20:28 +0000908 SourceLocation Loc, DiagnosticsEngine::Level Level,
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000909 SmallVectorImpl<CharSourceRange>& Ranges,
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000910 ArrayRef<FixItHint> Hints,
911 const SourceManager &SM) {
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000912 assert(!Loc.isInvalid() && "must have a valid source location here");
913 assert(Loc.isFileID() && "must have a file location here");
914
Chandler Carruth4ba55652011-10-16 07:20:28 +0000915 // If caret diagnostics are enabled and we have location, we want to
916 // emit the caret. However, we only do this if the location moved
917 // from the last diagnostic, if the last diagnostic was a note that
918 // was part of a different warning or error diagnostic, or if the
919 // diagnostic has ranges. We don't want to emit the same caret
920 // multiple times if one loc has multiple diagnostics.
921 if (!DiagOpts.ShowCarets)
922 return;
923 if (Loc == LastLoc && Ranges.empty() && Hints.empty() &&
924 (LastLevel != DiagnosticsEngine::Note || Level == LastLevel))
925 return;
926
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000927 // Decompose the location into a FID/Offset pair.
928 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
929 FileID FID = LocInfo.first;
930 unsigned FileOffset = LocInfo.second;
931
932 // Get information about the buffer it points into.
933 bool Invalid = false;
Nico Weber40d8e972012-04-26 21:39:46 +0000934 const char *BufStart = SM.getBufferData(FID, &Invalid).data();
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000935 if (Invalid)
936 return;
937
938 unsigned LineNo = SM.getLineNumber(FID, FileOffset);
939 unsigned ColNo = SM.getColumnNumber(FID, FileOffset);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000940
941 // Rewind from the current position to the start of the line.
942 const char *TokPtr = BufStart+FileOffset;
943 const char *LineStart = TokPtr-ColNo+1; // Column # is 1-based.
944
945
946 // Compute the line end. Scan forward from the error position to the end of
947 // the line.
948 const char *LineEnd = TokPtr;
Nico Weber40d8e972012-04-26 21:39:46 +0000949 while (*LineEnd != '\n' && *LineEnd != '\r' && *LineEnd != '\0')
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000950 ++LineEnd;
951
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000952 // Copy the line of code into an std::string for ease of manipulation.
953 std::string SourceLine(LineStart, LineEnd);
954
955 // Create a line for the caret that is filled with spaces that is the same
956 // length as the line of source code.
957 std::string CaretLine(LineEnd-LineStart, ' ');
958
Seth Cantrell6749dd52012-04-18 02:44:46 +0000959 const SourceColumnMap sourceColMap(SourceLine, DiagOpts.TabStop);
960
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000961 // Highlight all of the characters covered by Ranges with ~ characters.
962 for (SmallVectorImpl<CharSourceRange>::iterator I = Ranges.begin(),
963 E = Ranges.end();
964 I != E; ++I)
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000965 highlightRange(*I, LineNo, FID, sourceColMap, CaretLine, SM);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000966
967 // Next, insert the caret itself.
Richard Smithc7bb3842012-09-13 18:37:50 +0000968 ColNo = sourceColMap.byteToContainingColumn(ColNo-1);
Seth Cantrell6749dd52012-04-18 02:44:46 +0000969 if (CaretLine.size()<ColNo+1)
970 CaretLine.resize(ColNo+1, ' ');
971 CaretLine[ColNo] = '^';
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000972
Seth Cantrell6749dd52012-04-18 02:44:46 +0000973 std::string FixItInsertionLine = buildFixItInsertionLine(LineNo,
974 sourceColMap,
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000975 Hints, SM);
Seth Cantrell6749dd52012-04-18 02:44:46 +0000976
977 // If the source line is too long for our terminal, select only the
978 // "interesting" source region within that line.
979 unsigned Columns = DiagOpts.MessageLength;
980 if (Columns)
981 selectInterestingSourceRegion(SourceLine, CaretLine, FixItInsertionLine,
982 Columns, sourceColMap);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000983
984 // If we are in -fdiagnostics-print-source-range-info mode, we are trying
985 // to produce easily machine parsable output. Add a space before the
986 // source line and the caret to make it trivial to tell the main diagnostic
987 // line from what the user is intended to see.
988 if (DiagOpts.ShowSourceRanges) {
989 SourceLine = ' ' + SourceLine;
990 CaretLine = ' ' + CaretLine;
991 }
992
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000993 // Finally, remove any blank spaces from the end of CaretLine.
994 while (CaretLine[CaretLine.size()-1] == ' ')
995 CaretLine.erase(CaretLine.end()-1);
996
997 // Emit what we have computed.
Seth Cantrell6749dd52012-04-18 02:44:46 +0000998 emitSnippet(SourceLine);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000999
1000 if (DiagOpts.ShowColors)
1001 OS.changeColor(caretColor, true);
1002 OS << CaretLine << '\n';
1003 if (DiagOpts.ShowColors)
1004 OS.resetColor();
1005
1006 if (!FixItInsertionLine.empty()) {
1007 if (DiagOpts.ShowColors)
1008 // Print fixit line in color
1009 OS.changeColor(fixitColor, false);
1010 if (DiagOpts.ShowSourceRanges)
1011 OS << ' ';
1012 OS << FixItInsertionLine << '\n';
1013 if (DiagOpts.ShowColors)
1014 OS.resetColor();
1015 }
1016
1017 // Print out any parseable fixit information requested by the options.
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +00001018 emitParseableFixits(Hints, SM);
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001019}
1020
Benjamin Kramerd1fda032012-05-01 14:34:11 +00001021void TextDiagnostic::emitSnippet(StringRef line) {
Seth Cantrell6749dd52012-04-18 02:44:46 +00001022 if (line.empty())
1023 return;
1024
1025 size_t i = 0;
1026
1027 std::string to_print;
1028 bool print_reversed = false;
1029
1030 while (i<line.size()) {
1031 std::pair<SmallString<16>,bool> res
1032 = printableTextForNextCharacter(line, &i, DiagOpts.TabStop);
1033 bool was_printable = res.second;
1034
Nico Weber40d8e972012-04-26 21:39:46 +00001035 if (DiagOpts.ShowColors && was_printable == print_reversed) {
Seth Cantrell6749dd52012-04-18 02:44:46 +00001036 if (print_reversed)
1037 OS.reverseColor();
1038 OS << to_print;
1039 to_print.clear();
1040 if (DiagOpts.ShowColors)
1041 OS.resetColor();
1042 }
1043
1044 print_reversed = !was_printable;
1045 to_print += res.first.str();
1046 }
1047
1048 if (print_reversed && DiagOpts.ShowColors)
1049 OS.reverseColor();
1050 OS << to_print;
1051 if (print_reversed && DiagOpts.ShowColors)
1052 OS.resetColor();
1053
1054 OS << '\n';
1055}
1056
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001057/// \brief Highlight a SourceRange (with ~'s) for any characters on LineNo.
Chandler Carruth7531f572011-10-15 23:54:09 +00001058void TextDiagnostic::highlightRange(const CharSourceRange &R,
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001059 unsigned LineNo, FileID FID,
Seth Cantrell6749dd52012-04-18 02:44:46 +00001060 const SourceColumnMap &map,
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +00001061 std::string &CaretLine,
1062 const SourceManager &SM) {
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001063 if (!R.isValid()) return;
1064
1065 SourceLocation Begin = SM.getExpansionLoc(R.getBegin());
1066 SourceLocation End = SM.getExpansionLoc(R.getEnd());
1067
1068 // If the End location and the start location are the same and are a macro
1069 // location, then the range was something that came from a macro expansion
1070 // or _Pragma. If this is an object-like macro, the best we can do is to
1071 // highlight the range. If this is a function-like macro, we'd also like to
1072 // highlight the arguments.
1073 if (Begin == End && R.getEnd().isMacroID())
1074 End = SM.getExpansionRange(R.getEnd()).second;
1075
1076 unsigned StartLineNo = SM.getExpansionLineNumber(Begin);
1077 if (StartLineNo > LineNo || SM.getFileID(Begin) != FID)
1078 return; // No intersection.
1079
1080 unsigned EndLineNo = SM.getExpansionLineNumber(End);
1081 if (EndLineNo < LineNo || SM.getFileID(End) != FID)
1082 return; // No intersection.
1083
1084 // Compute the column number of the start.
1085 unsigned StartColNo = 0;
1086 if (StartLineNo == LineNo) {
1087 StartColNo = SM.getExpansionColumnNumber(Begin);
1088 if (StartColNo) --StartColNo; // Zero base the col #.
1089 }
1090
1091 // Compute the column number of the end.
Seth Cantrell6749dd52012-04-18 02:44:46 +00001092 unsigned EndColNo = map.getSourceLine().size();
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001093 if (EndLineNo == LineNo) {
1094 EndColNo = SM.getExpansionColumnNumber(End);
1095 if (EndColNo) {
1096 --EndColNo; // Zero base the col #.
1097
1098 // Add in the length of the token, so that we cover multi-char tokens if
1099 // this is a token range.
1100 if (R.isTokenRange())
1101 EndColNo += Lexer::MeasureTokenLength(End, SM, LangOpts);
1102 } else {
1103 EndColNo = CaretLine.size();
1104 }
1105 }
1106
1107 assert(StartColNo <= EndColNo && "Invalid range!");
1108
1109 // Check that a token range does not highlight only whitespace.
1110 if (R.isTokenRange()) {
1111 // Pick the first non-whitespace column.
Seth Cantrell6749dd52012-04-18 02:44:46 +00001112 while (StartColNo < map.getSourceLine().size() &&
1113 (map.getSourceLine()[StartColNo] == ' ' ||
1114 map.getSourceLine()[StartColNo] == '\t'))
Richard Smithc7bb3842012-09-13 18:37:50 +00001115 StartColNo = map.startOfNextColumn(StartColNo);
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001116
1117 // Pick the last non-whitespace column.
Seth Cantrell6749dd52012-04-18 02:44:46 +00001118 if (EndColNo > map.getSourceLine().size())
1119 EndColNo = map.getSourceLine().size();
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001120 while (EndColNo-1 &&
Seth Cantrell6749dd52012-04-18 02:44:46 +00001121 (map.getSourceLine()[EndColNo-1] == ' ' ||
1122 map.getSourceLine()[EndColNo-1] == '\t'))
Richard Smithc7bb3842012-09-13 18:37:50 +00001123 EndColNo = map.startOfPreviousColumn(EndColNo);
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001124
1125 // If the start/end passed each other, then we are trying to highlight a
1126 // range that just exists in whitespace, which must be some sort of other
1127 // bug.
1128 assert(StartColNo <= EndColNo && "Trying to highlight whitespace??");
1129 }
1130
Seth Cantrell6749dd52012-04-18 02:44:46 +00001131 assert(StartColNo <= map.getSourceLine().size() && "Invalid range!");
1132 assert(EndColNo <= map.getSourceLine().size() && "Invalid range!");
1133
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001134 // Fill the range with ~'s.
Richard Smithc7bb3842012-09-13 18:37:50 +00001135 StartColNo = map.byteToContainingColumn(StartColNo);
1136 EndColNo = map.byteToContainingColumn(EndColNo);
Seth Cantrell6749dd52012-04-18 02:44:46 +00001137
1138 assert(StartColNo <= EndColNo && "Invalid range!");
1139 if (CaretLine.size() < EndColNo)
1140 CaretLine.resize(EndColNo,' ');
1141 std::fill(CaretLine.begin()+StartColNo,CaretLine.begin()+EndColNo,'~');
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001142}
1143
Seth Cantrell6749dd52012-04-18 02:44:46 +00001144std::string TextDiagnostic::buildFixItInsertionLine(
1145 unsigned LineNo,
1146 const SourceColumnMap &map,
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +00001147 ArrayRef<FixItHint> Hints,
1148 const SourceManager &SM) {
Seth Cantrell6749dd52012-04-18 02:44:46 +00001149
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001150 std::string FixItInsertionLine;
1151 if (Hints.empty() || !DiagOpts.ShowFixits)
1152 return FixItInsertionLine;
Jordan Rosebbe01752012-07-20 18:50:51 +00001153 unsigned PrevHintEndCol = 0;
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001154
1155 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1156 I != E; ++I) {
1157 if (!I->CodeToInsert.empty()) {
1158 // We have an insertion hint. Determine whether the inserted
Jordan Rosebbe01752012-07-20 18:50:51 +00001159 // code contains no newlines and is on the same line as the caret.
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001160 std::pair<FileID, unsigned> HintLocInfo
1161 = SM.getDecomposedExpansionLoc(I->RemoveRange.getBegin());
Jordan Rosebbe01752012-07-20 18:50:51 +00001162 if (LineNo == SM.getLineNumber(HintLocInfo.first, HintLocInfo.second) &&
1163 StringRef(I->CodeToInsert).find_first_of("\n\r") == StringRef::npos) {
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001164 // Insert the new code into the line just below the code
1165 // that the user wrote.
Jordan Rosebbe01752012-07-20 18:50:51 +00001166 // Note: When modifying this function, be very careful about what is a
1167 // "column" (printed width, platform-dependent) and what is a
1168 // "byte offset" (SourceManager "column").
1169 unsigned HintByteOffset
Seth Cantrell6749dd52012-04-18 02:44:46 +00001170 = SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second) - 1;
Jordan Rosebbe01752012-07-20 18:50:51 +00001171
1172 // The hint must start inside the source or right at the end
1173 assert(HintByteOffset < static_cast<unsigned>(map.bytes())+1);
Richard Smithc7bb3842012-09-13 18:37:50 +00001174 unsigned HintCol = map.byteToContainingColumn(HintByteOffset);
Seth Cantrell6749dd52012-04-18 02:44:46 +00001175
Jordan Rose3772c9a2012-06-08 21:14:19 +00001176 // If we inserted a long previous hint, push this one forwards, and add
1177 // an extra space to show that this is not part of the previous
1178 // completion. This is sort of the best we can do when two hints appear
1179 // to overlap.
1180 //
1181 // Note that if this hint is located immediately after the previous
1182 // hint, no space will be added, since the location is more important.
Jordan Rosebbe01752012-07-20 18:50:51 +00001183 if (HintCol < PrevHintEndCol)
1184 HintCol = PrevHintEndCol + 1;
Jordan Rose3772c9a2012-06-08 21:14:19 +00001185
Jordan Rosebbe01752012-07-20 18:50:51 +00001186 // FIXME: This function handles multibyte characters in the source, but
1187 // not in the fixits. This assertion is intended to catch unintended
1188 // use of multibyte characters in fixits. If we decide to do this, we'll
1189 // have to track separate byte widths for the source and fixit lines.
1190 assert((size_t)llvm::sys::locale::columnWidth(I->CodeToInsert) ==
1191 I->CodeToInsert.size());
Seth Cantrell6749dd52012-04-18 02:44:46 +00001192
Jordan Rosebbe01752012-07-20 18:50:51 +00001193 // This relies on one byte per column in our fixit hints.
1194 // This should NOT use HintByteOffset, because the source might have
1195 // Unicode characters in earlier columns.
1196 unsigned LastColumnModified = HintCol + I->CodeToInsert.size();
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001197 if (LastColumnModified > FixItInsertionLine.size())
1198 FixItInsertionLine.resize(LastColumnModified, ' ');
Jordan Rose6f977c32012-07-16 20:52:12 +00001199
Jordan Rosebbe01752012-07-20 18:50:51 +00001200 std::copy(I->CodeToInsert.begin(), I->CodeToInsert.end(),
1201 FixItInsertionLine.begin() + HintCol);
1202
1203 PrevHintEndCol = LastColumnModified;
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001204 } else {
1205 FixItInsertionLine.clear();
1206 break;
1207 }
1208 }
1209 }
1210
Seth Cantrell6749dd52012-04-18 02:44:46 +00001211 expandTabs(FixItInsertionLine, DiagOpts.TabStop);
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001212
1213 return FixItInsertionLine;
1214}
1215
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +00001216void TextDiagnostic::emitParseableFixits(ArrayRef<FixItHint> Hints,
1217 const SourceManager &SM) {
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001218 if (!DiagOpts.ShowParseableFixits)
1219 return;
1220
1221 // We follow FixItRewriter's example in not (yet) handling
1222 // fix-its in macros.
1223 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1224 I != E; ++I) {
1225 if (I->RemoveRange.isInvalid() ||
1226 I->RemoveRange.getBegin().isMacroID() ||
1227 I->RemoveRange.getEnd().isMacroID())
1228 return;
1229 }
1230
1231 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1232 I != E; ++I) {
1233 SourceLocation BLoc = I->RemoveRange.getBegin();
1234 SourceLocation ELoc = I->RemoveRange.getEnd();
1235
1236 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(BLoc);
1237 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(ELoc);
1238
1239 // Adjust for token ranges.
1240 if (I->RemoveRange.isTokenRange())
1241 EInfo.second += Lexer::MeasureTokenLength(ELoc, SM, LangOpts);
1242
1243 // We specifically do not do word-wrapping or tab-expansion here,
1244 // because this is supposed to be easy to parse.
1245 PresumedLoc PLoc = SM.getPresumedLoc(BLoc);
1246 if (PLoc.isInvalid())
1247 break;
1248
1249 OS << "fix-it:\"";
1250 OS.write_escaped(PLoc.getFilename());
1251 OS << "\":{" << SM.getLineNumber(BInfo.first, BInfo.second)
1252 << ':' << SM.getColumnNumber(BInfo.first, BInfo.second)
1253 << '-' << SM.getLineNumber(EInfo.first, EInfo.second)
1254 << ':' << SM.getColumnNumber(EInfo.first, EInfo.second)
1255 << "}:\"";
1256 OS.write_escaped(I->CodeToInsert);
1257 OS << "\"\n";
1258 }
1259}