blob: 454018b29693ea59e7baa27e97ecb8281ff8cf21 [file] [log] [blame]
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001//===--- TextDiagnostic.cpp - Text Diagnostic Pretty-Printing -------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "clang/Frontend/TextDiagnostic.h"
11#include "clang/Basic/FileManager.h"
12#include "clang/Basic/SourceManager.h"
Seth Cantrell6749dd52012-04-18 02:44:46 +000013#include "clang/Basic/ConvertUTF.h"
Chandler Carruthdb463bb2011-10-15 23:43:53 +000014#include "clang/Frontend/DiagnosticOptions.h"
15#include "clang/Lex/Lexer.h"
16#include "llvm/Support/MemoryBuffer.h"
17#include "llvm/Support/raw_ostream.h"
18#include "llvm/Support/ErrorHandling.h"
Seth Cantrell6749dd52012-04-18 02:44:46 +000019#include "llvm/Support/Locale.h"
Chandler Carruthdb463bb2011-10-15 23:43:53 +000020#include "llvm/ADT/SmallString.h"
Seth Cantrell6749dd52012-04-18 02:44:46 +000021#include "llvm/ADT/StringExtras.h"
Chandler Carruthdb463bb2011-10-15 23:43:53 +000022#include <algorithm>
Seth Cantrell6749dd52012-04-18 02:44:46 +000023
Chandler Carruthdb463bb2011-10-15 23:43:53 +000024using namespace clang;
25
26static const enum raw_ostream::Colors noteColor =
27 raw_ostream::BLACK;
28static const enum raw_ostream::Colors fixitColor =
29 raw_ostream::GREEN;
30static const enum raw_ostream::Colors caretColor =
31 raw_ostream::GREEN;
32static const enum raw_ostream::Colors warningColor =
33 raw_ostream::MAGENTA;
34static const enum raw_ostream::Colors errorColor = raw_ostream::RED;
35static const enum raw_ostream::Colors fatalColor = raw_ostream::RED;
36// Used for changing only the bold attribute.
37static const enum raw_ostream::Colors savedColor =
38 raw_ostream::SAVEDCOLOR;
39
40/// \brief Number of spaces to indent when word-wrapping.
41const unsigned WordWrapIndentation = 6;
42
Benjamin Kramerd1fda032012-05-01 14:34:11 +000043static int bytesSincePreviousTabOrLineBegin(StringRef SourceLine, size_t i) {
Seth Cantrell6749dd52012-04-18 02:44:46 +000044 int bytes = 0;
45 while (0<i) {
46 if (SourceLine[--i]=='\t')
47 break;
48 ++bytes;
49 }
50 return bytes;
51}
52
53/// \brief returns a printable representation of first item from input range
54///
55/// This function returns a printable representation of the next item in a line
56/// of source. If the next byte begins a valid and printable character, that
57/// character is returned along with 'true'.
58///
59/// Otherwise, if the next byte begins a valid, but unprintable character, a
60/// printable, escaped representation of the character is returned, along with
61/// 'false'. Otherwise a printable, escaped representation of the next byte
62/// is returned along with 'false'.
63///
64/// \note The index is updated to be used with a subsequent call to
65/// printableTextForNextCharacter.
66///
67/// \param SourceLine The line of source
68/// \param i Pointer to byte index,
69/// \param TabStop used to expand tabs
70/// \return pair(printable text, 'true' iff original text was printable)
71///
Benjamin Kramerd1fda032012-05-01 14:34:11 +000072static std::pair<SmallString<16>, bool>
Seth Cantrell6749dd52012-04-18 02:44:46 +000073printableTextForNextCharacter(StringRef SourceLine, size_t *i,
74 unsigned TabStop) {
75 assert(i && "i must not be null");
76 assert(*i<SourceLine.size() && "must point to a valid index");
77
78 if (SourceLine[*i]=='\t') {
79 assert(0 < TabStop && TabStop <= DiagnosticOptions::MaxTabStop &&
80 "Invalid -ftabstop value");
81 unsigned col = bytesSincePreviousTabOrLineBegin(SourceLine, *i);
82 unsigned NumSpaces = TabStop - col%TabStop;
83 assert(0 < NumSpaces && NumSpaces <= TabStop
84 && "Invalid computation of space amt");
85 ++(*i);
86
87 SmallString<16> expandedTab;
88 expandedTab.assign(NumSpaces, ' ');
89 return std::make_pair(expandedTab, true);
90 }
91
92 // FIXME: this data is copied from the private implementation of ConvertUTF.h
93 static const char trailingBytesForUTF8[256] = {
94 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
95 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
96 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
97 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
98 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
99 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
100 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
101 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5
102 };
103
104 unsigned char const *begin, *end;
105 begin = reinterpret_cast<unsigned char const *>(&*(SourceLine.begin() + *i));
106 end = begin + SourceLine.size();
107
108 if (isLegalUTF8Sequence(begin, end)) {
109 UTF32 c;
110 UTF32 *cptr = &c;
111 unsigned char const *original_begin = begin;
112 char trailingBytes = trailingBytesForUTF8[(unsigned char)SourceLine[*i]];
113 unsigned char const *cp_end = begin+trailingBytes+1;
114
115 ConversionResult res = ConvertUTF8toUTF32(&begin, cp_end, &cptr, cptr+1,
116 strictConversion);
Matt Beaumont-Gay0ddb0972012-04-18 17:25:16 +0000117 (void)res;
Seth Cantrell6749dd52012-04-18 02:44:46 +0000118 assert(conversionOK==res);
119 assert(0 < begin-original_begin
120 && "we must be further along in the string now");
121 *i += begin-original_begin;
122
123 if (!llvm::sys::locale::isPrint(c)) {
124 // If next character is valid UTF-8, but not printable
125 SmallString<16> expandedCP("<U+>");
126 while (c) {
127 expandedCP.insert(expandedCP.begin()+3, llvm::hexdigit(c%16));
128 c/=16;
129 }
130 while (expandedCP.size() < 8)
131 expandedCP.insert(expandedCP.begin()+3, llvm::hexdigit(0));
132 return std::make_pair(expandedCP, false);
133 }
134
135 // If next character is valid UTF-8, and printable
136 return std::make_pair(SmallString<16>(original_begin, cp_end), true);
137
138 }
139
140 // If next byte is not valid UTF-8 (and therefore not printable)
141 SmallString<16> expandedByte("<XX>");
142 unsigned char byte = SourceLine[*i];
143 expandedByte[1] = llvm::hexdigit(byte / 16);
144 expandedByte[2] = llvm::hexdigit(byte % 16);
145 ++(*i);
146 return std::make_pair(expandedByte, false);
147}
148
Benjamin Kramerd1fda032012-05-01 14:34:11 +0000149static void expandTabs(std::string &SourceLine, unsigned TabStop) {
Seth Cantrell6749dd52012-04-18 02:44:46 +0000150 size_t i = SourceLine.size();
151 while (i>0) {
152 i--;
153 if (SourceLine[i]!='\t')
154 continue;
155 size_t tmp_i = i;
156 std::pair<SmallString<16>,bool> res
157 = printableTextForNextCharacter(SourceLine, &tmp_i, TabStop);
158 SourceLine.replace(i, 1, res.first.c_str());
159 }
160}
161
162/// This function takes a raw source line and produces a mapping from the bytes
163/// of the printable representation of the line to the columns those printable
164/// characters will appear at (numbering the first column as 0).
165///
166/// If a byte 'i' corresponds to muliple columns (e.g. the byte contains a tab
167/// character) then the the array will map that byte to the first column the
168/// tab appears at and the next value in the map will have been incremented
169/// more than once.
170///
171/// If a byte is the first in a sequence of bytes that together map to a single
172/// entity in the output, then the array will map that byte to the appropriate
173/// column while the subsequent bytes will be -1.
174///
175/// The last element in the array does not correspond to any byte in the input
176/// and instead is the number of columns needed to display the source
177///
178/// example: (given a tabstop of 8)
179///
180/// "a \t \u3042" -> {0,1,2,8,9,-1,-1,11}
181///
182/// (\u3042 is represented in UTF-8 by three bytes and takes two columns to
183/// display)
Benjamin Kramerd1fda032012-05-01 14:34:11 +0000184static void byteToColumn(StringRef SourceLine, unsigned TabStop,
185 SmallVectorImpl<int> &out) {
Seth Cantrell6749dd52012-04-18 02:44:46 +0000186 out.clear();
187
188 if (SourceLine.empty()) {
189 out.resize(1u,0);
190 return;
191 }
192
193 out.resize(SourceLine.size()+1, -1);
194
195 int columns = 0;
196 size_t i = 0;
197 while (i<SourceLine.size()) {
198 out[i] = columns;
199 std::pair<SmallString<16>,bool> res
200 = printableTextForNextCharacter(SourceLine, &i, TabStop);
201 columns += llvm::sys::locale::columnWidth(res.first);
202 }
203 out.back() = columns;
204}
205
206/// This function takes a raw source line and produces a mapping from columns
207/// to the byte of the source line that produced the character displaying at
208/// that column. This is the inverse of the mapping produced by byteToColumn()
209///
210/// The last element in the array is the number of bytes in the source string
211///
212/// example: (given a tabstop of 8)
213///
214/// "a \t \u3042" -> {0,1,2,-1,-1,-1,-1,-1,3,4,-1,7}
215///
216/// (\u3042 is represented in UTF-8 by three bytes and takes two columns to
217/// display)
Benjamin Kramerd1fda032012-05-01 14:34:11 +0000218static void columnToByte(StringRef SourceLine, unsigned TabStop,
Seth Cantrell6749dd52012-04-18 02:44:46 +0000219 SmallVectorImpl<int> &out) {
220 out.clear();
221
222 if (SourceLine.empty()) {
223 out.resize(1u, 0);
224 return;
225 }
226
227 int columns = 0;
228 size_t i = 0;
229 while (i<SourceLine.size()) {
230 out.resize(columns+1, -1);
231 out.back() = i;
232 std::pair<SmallString<16>,bool> res
233 = printableTextForNextCharacter(SourceLine, &i, TabStop);
234 columns += llvm::sys::locale::columnWidth(res.first);
235 }
236 out.resize(columns+1, -1);
237 out.back() = i;
238}
239
240struct SourceColumnMap {
241 SourceColumnMap(StringRef SourceLine, unsigned TabStop)
242 : m_SourceLine(SourceLine) {
243
244 ::byteToColumn(SourceLine, TabStop, m_byteToColumn);
245 ::columnToByte(SourceLine, TabStop, m_columnToByte);
246
247 assert(m_byteToColumn.size()==SourceLine.size()+1);
248 assert(0 < m_byteToColumn.size() && 0 < m_columnToByte.size());
249 assert(m_byteToColumn.size()
250 == static_cast<unsigned>(m_columnToByte.back()+1));
251 assert(static_cast<unsigned>(m_byteToColumn.back()+1)
252 == m_columnToByte.size());
253 }
254 int columns() const { return m_byteToColumn.back(); }
255 int bytes() const { return m_columnToByte.back(); }
256 int byteToColumn(int n) const {
257 assert(0<=n && n<static_cast<int>(m_byteToColumn.size()));
258 return m_byteToColumn[n];
259 }
260 int columnToByte(int n) const {
261 assert(0<=n && n<static_cast<int>(m_columnToByte.size()));
262 return m_columnToByte[n];
263 }
264 StringRef getSourceLine() const {
265 return m_SourceLine;
266 }
267
268private:
269 const std::string m_SourceLine;
270 SmallVector<int,200> m_byteToColumn;
271 SmallVector<int,200> m_columnToByte;
272};
273
274// used in assert in selectInterestingSourceRegion()
275namespace {
276struct char_out_of_range {
277 const char lower,upper;
278 char_out_of_range(char lower, char upper) :
279 lower(lower), upper(upper) {}
280 bool operator()(char c) { return c < lower || upper < c; }
281};
282}
283
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000284/// \brief When the source code line we want to print is too long for
285/// the terminal, select the "interesting" region.
Chandler Carruth7531f572011-10-15 23:54:09 +0000286static void selectInterestingSourceRegion(std::string &SourceLine,
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000287 std::string &CaretLine,
288 std::string &FixItInsertionLine,
Seth Cantrell6749dd52012-04-18 02:44:46 +0000289 unsigned Columns,
290 const SourceColumnMap &map) {
291 unsigned MaxColumns = std::max<unsigned>(map.columns(),
292 std::max(CaretLine.size(),
293 FixItInsertionLine.size()));
294 // if the number of columns is less than the desired number we're done
295 if (MaxColumns <= Columns)
296 return;
297
298 // no special characters allowed in CaretLine or FixItInsertionLine
299 assert(CaretLine.end() ==
300 std::find_if(CaretLine.begin(), CaretLine.end(),
301 char_out_of_range(' ','~')));
302 assert(FixItInsertionLine.end() ==
303 std::find_if(FixItInsertionLine.begin(), FixItInsertionLine.end(),
304 char_out_of_range(' ','~')));
305
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000306 // Find the slice that we need to display the full caret line
307 // correctly.
308 unsigned CaretStart = 0, CaretEnd = CaretLine.size();
309 for (; CaretStart != CaretEnd; ++CaretStart)
310 if (!isspace(CaretLine[CaretStart]))
311 break;
312
313 for (; CaretEnd != CaretStart; --CaretEnd)
314 if (!isspace(CaretLine[CaretEnd - 1]))
315 break;
316
Seth Cantrell6749dd52012-04-18 02:44:46 +0000317 // caret has already been inserted into CaretLine so the above whitespace
318 // check is guaranteed to include the caret
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000319
320 // If we have a fix-it line, make sure the slice includes all of the
321 // fix-it information.
322 if (!FixItInsertionLine.empty()) {
323 unsigned FixItStart = 0, FixItEnd = FixItInsertionLine.size();
324 for (; FixItStart != FixItEnd; ++FixItStart)
325 if (!isspace(FixItInsertionLine[FixItStart]))
326 break;
327
328 for (; FixItEnd != FixItStart; --FixItEnd)
329 if (!isspace(FixItInsertionLine[FixItEnd - 1]))
330 break;
331
Seth Cantrell6749dd52012-04-18 02:44:46 +0000332 CaretStart = std::min(FixItStart, CaretStart);
333 CaretEnd = std::max(FixItEnd, CaretEnd);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000334 }
335
336 // CaretLine[CaretStart, CaretEnd) contains all of the interesting
337 // parts of the caret line. While this slice is smaller than the
338 // number of columns we have, try to grow the slice to encompass
339 // more context.
340
Seth Cantrell6749dd52012-04-18 02:44:46 +0000341 unsigned SourceStart = map.columnToByte(std::min<unsigned>(CaretStart,
342 map.columns()));
343 unsigned SourceEnd = map.columnToByte(std::min<unsigned>(CaretEnd,
344 map.columns()));
345
346 unsigned CaretColumnsOutsideSource = CaretEnd-CaretStart
347 - (map.byteToColumn(SourceEnd)-map.byteToColumn(SourceStart));
348
349 char const *front_ellipse = " ...";
350 char const *front_space = " ";
351 char const *back_ellipse = "...";
352 unsigned ellipses_space = strlen(front_ellipse) + strlen(back_ellipse);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000353
354 unsigned TargetColumns = Columns;
Seth Cantrell6749dd52012-04-18 02:44:46 +0000355 // Give us extra room for the ellipses
356 // and any of the caret line that extends past the source
357 if (TargetColumns > ellipses_space+CaretColumnsOutsideSource)
358 TargetColumns -= ellipses_space+CaretColumnsOutsideSource;
359
360 while (SourceStart>0 || SourceEnd<SourceLine.size()) {
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000361 bool ExpandedRegion = false;
Seth Cantrell6749dd52012-04-18 02:44:46 +0000362
363 if (SourceStart>0) {
364 unsigned NewStart = SourceStart-1;
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000365
366 // Skip over any whitespace we see here; we're looking for
367 // another bit of interesting text.
Seth Cantrell6749dd52012-04-18 02:44:46 +0000368 while (NewStart &&
369 (map.byteToColumn(NewStart)==-1 || isspace(SourceLine[NewStart])))
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000370 --NewStart;
371
372 // Skip over this bit of "interesting" text.
Seth Cantrell6749dd52012-04-18 02:44:46 +0000373 while (NewStart &&
374 (map.byteToColumn(NewStart)!=-1 && !isspace(SourceLine[NewStart])))
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000375 --NewStart;
376
377 // Move up to the non-whitespace character we just saw.
378 if (NewStart)
379 ++NewStart;
380
Seth Cantrell6749dd52012-04-18 02:44:46 +0000381 unsigned NewColumns = map.byteToColumn(SourceEnd) -
382 map.byteToColumn(NewStart);
383 if (NewColumns <= TargetColumns) {
384 SourceStart = NewStart;
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000385 ExpandedRegion = true;
386 }
387 }
388
Seth Cantrell6749dd52012-04-18 02:44:46 +0000389 if (SourceEnd<SourceLine.size()) {
390 unsigned NewEnd = SourceEnd+1;
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000391
392 // Skip over any whitespace we see here; we're looking for
393 // another bit of interesting text.
Seth Cantrell6749dd52012-04-18 02:44:46 +0000394 while (NewEnd<SourceLine.size() &&
395 (map.byteToColumn(NewEnd)==-1 || isspace(SourceLine[NewEnd])))
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000396 ++NewEnd;
397
398 // Skip over this bit of "interesting" text.
Seth Cantrell6749dd52012-04-18 02:44:46 +0000399 while (NewEnd<SourceLine.size() &&
400 (map.byteToColumn(NewEnd)!=-1 && !isspace(SourceLine[NewEnd])))
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000401 ++NewEnd;
402
Seth Cantrell6749dd52012-04-18 02:44:46 +0000403 unsigned NewColumns = map.byteToColumn(NewEnd) -
404 map.byteToColumn(SourceStart);
405 if (NewColumns <= TargetColumns) {
406 SourceEnd = NewEnd;
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000407 ExpandedRegion = true;
408 }
409 }
410
411 if (!ExpandedRegion)
412 break;
413 }
414
Seth Cantrell6749dd52012-04-18 02:44:46 +0000415 CaretStart = map.byteToColumn(SourceStart);
416 CaretEnd = map.byteToColumn(SourceEnd) + CaretColumnsOutsideSource;
417
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000418 // [CaretStart, CaretEnd) is the slice we want. Update the various
419 // output lines to show only this slice, with two-space padding
420 // before the lines so that it looks nicer.
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000421
Seth Cantrell6749dd52012-04-18 02:44:46 +0000422 assert(CaretStart!=(unsigned)-1 && CaretEnd!=(unsigned)-1 &&
423 SourceStart!=(unsigned)-1 && SourceEnd!=(unsigned)-1);
424 assert(SourceStart <= SourceEnd);
425 assert(CaretStart <= CaretEnd);
426
427 unsigned BackColumnsRemoved
428 = map.byteToColumn(SourceLine.size())-map.byteToColumn(SourceEnd);
429 unsigned FrontColumnsRemoved = CaretStart;
430 unsigned ColumnsKept = CaretEnd-CaretStart;
431
432 // We checked up front that the line needed truncation
433 assert(FrontColumnsRemoved+ColumnsKept+BackColumnsRemoved > Columns);
434
435 // The line needs some trunctiona, and we'd prefer to keep the front
436 // if possible, so remove the back
437 if (BackColumnsRemoved)
438 SourceLine.replace(SourceEnd, std::string::npos, back_ellipse);
439
440 // If that's enough then we're done
441 if (FrontColumnsRemoved+ColumnsKept <= Columns)
442 return;
443
444 // Otherwise remove the front as well
445 if (FrontColumnsRemoved) {
446 SourceLine.replace(0, SourceStart, front_ellipse);
447 CaretLine.replace(0, CaretStart, front_space);
448 if (!FixItInsertionLine.empty())
449 FixItInsertionLine.replace(0, CaretStart, front_space);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000450 }
451}
452
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000453/// \brief Skip over whitespace in the string, starting at the given
454/// index.
455///
456/// \returns The index of the first non-whitespace character that is
457/// greater than or equal to Idx or, if no such character exists,
458/// returns the end of the string.
459static unsigned skipWhitespace(unsigned Idx, StringRef Str, unsigned Length) {
460 while (Idx < Length && isspace(Str[Idx]))
461 ++Idx;
462 return Idx;
463}
464
465/// \brief If the given character is the start of some kind of
466/// balanced punctuation (e.g., quotes or parentheses), return the
467/// character that will terminate the punctuation.
468///
469/// \returns The ending punctuation character, if any, or the NULL
470/// character if the input character does not start any punctuation.
471static inline char findMatchingPunctuation(char c) {
472 switch (c) {
473 case '\'': return '\'';
474 case '`': return '\'';
475 case '"': return '"';
476 case '(': return ')';
477 case '[': return ']';
478 case '{': return '}';
479 default: break;
480 }
481
482 return 0;
483}
484
485/// \brief Find the end of the word starting at the given offset
486/// within a string.
487///
488/// \returns the index pointing one character past the end of the
489/// word.
490static unsigned findEndOfWord(unsigned Start, StringRef Str,
491 unsigned Length, unsigned Column,
492 unsigned Columns) {
493 assert(Start < Str.size() && "Invalid start position!");
494 unsigned End = Start + 1;
495
496 // If we are already at the end of the string, take that as the word.
497 if (End == Str.size())
498 return End;
499
500 // Determine if the start of the string is actually opening
501 // punctuation, e.g., a quote or parentheses.
502 char EndPunct = findMatchingPunctuation(Str[Start]);
503 if (!EndPunct) {
504 // This is a normal word. Just find the first space character.
505 while (End < Length && !isspace(Str[End]))
506 ++End;
507 return End;
508 }
509
510 // We have the start of a balanced punctuation sequence (quotes,
511 // parentheses, etc.). Determine the full sequence is.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000512 SmallString<16> PunctuationEndStack;
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000513 PunctuationEndStack.push_back(EndPunct);
514 while (End < Length && !PunctuationEndStack.empty()) {
515 if (Str[End] == PunctuationEndStack.back())
516 PunctuationEndStack.pop_back();
517 else if (char SubEndPunct = findMatchingPunctuation(Str[End]))
518 PunctuationEndStack.push_back(SubEndPunct);
519
520 ++End;
521 }
522
523 // Find the first space character after the punctuation ended.
524 while (End < Length && !isspace(Str[End]))
525 ++End;
526
527 unsigned PunctWordLength = End - Start;
528 if (// If the word fits on this line
529 Column + PunctWordLength <= Columns ||
530 // ... or the word is "short enough" to take up the next line
531 // without too much ugly white space
532 PunctWordLength < Columns/3)
533 return End; // Take the whole thing as a single "word".
534
535 // The whole quoted/parenthesized string is too long to print as a
536 // single "word". Instead, find the "word" that starts just after
537 // the punctuation and use that end-point instead. This will recurse
538 // until it finds something small enough to consider a word.
539 return findEndOfWord(Start + 1, Str, Length, Column + 1, Columns);
540}
541
542/// \brief Print the given string to a stream, word-wrapping it to
543/// some number of columns in the process.
544///
545/// \param OS the stream to which the word-wrapping string will be
546/// emitted.
547/// \param Str the string to word-wrap and output.
548/// \param Columns the number of columns to word-wrap to.
549/// \param Column the column number at which the first character of \p
550/// Str will be printed. This will be non-zero when part of the first
551/// line has already been printed.
552/// \param Indentation the number of spaces to indent any lines beyond
553/// the first line.
554/// \returns true if word-wrapping was required, or false if the
555/// string fit on the first line.
556static bool printWordWrapped(raw_ostream &OS, StringRef Str,
557 unsigned Columns,
558 unsigned Column = 0,
559 unsigned Indentation = WordWrapIndentation) {
560 const unsigned Length = std::min(Str.find('\n'), Str.size());
561
562 // The string used to indent each line.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000563 SmallString<16> IndentStr;
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000564 IndentStr.assign(Indentation, ' ');
565 bool Wrapped = false;
566 for (unsigned WordStart = 0, WordEnd; WordStart < Length;
567 WordStart = WordEnd) {
568 // Find the beginning of the next word.
569 WordStart = skipWhitespace(WordStart, Str, Length);
570 if (WordStart == Length)
571 break;
572
573 // Find the end of this word.
574 WordEnd = findEndOfWord(WordStart, Str, Length, Column, Columns);
575
576 // Does this word fit on the current line?
577 unsigned WordLength = WordEnd - WordStart;
578 if (Column + WordLength < Columns) {
579 // This word fits on the current line; print it there.
580 if (WordStart) {
581 OS << ' ';
582 Column += 1;
583 }
584 OS << Str.substr(WordStart, WordLength);
585 Column += WordLength;
586 continue;
587 }
588
589 // This word does not fit on the current line, so wrap to the next
590 // line.
591 OS << '\n';
592 OS.write(&IndentStr[0], Indentation);
593 OS << Str.substr(WordStart, WordLength);
594 Column = Indentation + WordLength;
595 Wrapped = true;
596 }
597
598 // Append any remaning text from the message with its existing formatting.
599 OS << Str.substr(Length);
600
601 return Wrapped;
602}
603
604TextDiagnostic::TextDiagnostic(raw_ostream &OS,
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000605 const LangOptions &LangOpts,
Chandler Carruth21a869a2011-10-16 02:57:39 +0000606 const DiagnosticOptions &DiagOpts)
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000607 : DiagnosticRenderer(LangOpts, DiagOpts), OS(OS) {}
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000608
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000609TextDiagnostic::~TextDiagnostic() {}
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000610
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000611void
612TextDiagnostic::emitDiagnosticMessage(SourceLocation Loc,
613 PresumedLoc PLoc,
614 DiagnosticsEngine::Level Level,
615 StringRef Message,
616 ArrayRef<clang::CharSourceRange> Ranges,
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000617 const SourceManager *SM,
Ted Kremenek8be51ea2012-02-14 02:46:00 +0000618 DiagOrStoredDiag D) {
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000619 uint64_t StartOfLocationInfo = OS.tell();
620
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000621 // Emit the location of this particular diagnostic.
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000622 if (Loc.isValid())
623 emitDiagnosticLoc(Loc, PLoc, Level, Ranges, *SM);
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000624
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000625 if (DiagOpts.ShowColors)
626 OS.resetColor();
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000627
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000628 printDiagnosticLevel(OS, Level, DiagOpts.ShowColors);
629 printDiagnosticMessage(OS, Level, Message,
630 OS.tell() - StartOfLocationInfo,
631 DiagOpts.MessageLength, DiagOpts.ShowColors);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000632}
633
Chandler Carruth6ddd8872011-10-15 23:48:02 +0000634/*static*/ void
635TextDiagnostic::printDiagnosticLevel(raw_ostream &OS,
636 DiagnosticsEngine::Level Level,
637 bool ShowColors) {
638 if (ShowColors) {
639 // Print diagnostic category in bold and color
640 switch (Level) {
641 case DiagnosticsEngine::Ignored:
642 llvm_unreachable("Invalid diagnostic type");
643 case DiagnosticsEngine::Note: OS.changeColor(noteColor, true); break;
644 case DiagnosticsEngine::Warning: OS.changeColor(warningColor, true); break;
645 case DiagnosticsEngine::Error: OS.changeColor(errorColor, true); break;
646 case DiagnosticsEngine::Fatal: OS.changeColor(fatalColor, true); break;
647 }
648 }
649
650 switch (Level) {
651 case DiagnosticsEngine::Ignored:
652 llvm_unreachable("Invalid diagnostic type");
653 case DiagnosticsEngine::Note: OS << "note: "; break;
654 case DiagnosticsEngine::Warning: OS << "warning: "; break;
655 case DiagnosticsEngine::Error: OS << "error: "; break;
656 case DiagnosticsEngine::Fatal: OS << "fatal error: "; break;
657 }
658
659 if (ShowColors)
660 OS.resetColor();
661}
662
663/*static*/ void
664TextDiagnostic::printDiagnosticMessage(raw_ostream &OS,
665 DiagnosticsEngine::Level Level,
666 StringRef Message,
667 unsigned CurrentColumn, unsigned Columns,
668 bool ShowColors) {
669 if (ShowColors) {
670 // Print warnings, errors and fatal errors in bold, no color
671 switch (Level) {
672 case DiagnosticsEngine::Warning: OS.changeColor(savedColor, true); break;
673 case DiagnosticsEngine::Error: OS.changeColor(savedColor, true); break;
674 case DiagnosticsEngine::Fatal: OS.changeColor(savedColor, true); break;
675 default: break; //don't bold notes
676 }
677 }
678
679 if (Columns)
680 printWordWrapped(OS, Message, Columns, CurrentColumn);
681 else
682 OS << Message;
683
684 if (ShowColors)
685 OS.resetColor();
686 OS << '\n';
687}
688
Chandler Carruth6ddd8872011-10-15 23:48:02 +0000689/// \brief Print out the file/line/column information and include trace.
690///
691/// This method handlen the emission of the diagnostic location information.
692/// This includes extracting as much location information as is present for
693/// the diagnostic and printing it, as well as any include stack or source
694/// ranges necessary.
Chandler Carruth7531f572011-10-15 23:54:09 +0000695void TextDiagnostic::emitDiagnosticLoc(SourceLocation Loc, PresumedLoc PLoc,
Chandler Carruth6ddd8872011-10-15 23:48:02 +0000696 DiagnosticsEngine::Level Level,
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000697 ArrayRef<CharSourceRange> Ranges,
698 const SourceManager &SM) {
Chandler Carruth6ddd8872011-10-15 23:48:02 +0000699 if (PLoc.isInvalid()) {
700 // At least print the file name if available:
701 FileID FID = SM.getFileID(Loc);
702 if (!FID.isInvalid()) {
703 const FileEntry* FE = SM.getFileEntryForID(FID);
704 if (FE && FE->getName()) {
705 OS << FE->getName();
706 if (FE->getDevice() == 0 && FE->getInode() == 0
707 && FE->getFileMode() == 0) {
708 // in PCH is a guess, but a good one:
709 OS << " (in PCH)";
710 }
711 OS << ": ";
712 }
713 }
714 return;
715 }
716 unsigned LineNo = PLoc.getLine();
717
718 if (!DiagOpts.ShowLocation)
719 return;
720
721 if (DiagOpts.ShowColors)
722 OS.changeColor(savedColor, true);
723
724 OS << PLoc.getFilename();
725 switch (DiagOpts.Format) {
726 case DiagnosticOptions::Clang: OS << ':' << LineNo; break;
727 case DiagnosticOptions::Msvc: OS << '(' << LineNo; break;
728 case DiagnosticOptions::Vi: OS << " +" << LineNo; break;
729 }
730
731 if (DiagOpts.ShowColumn)
732 // Compute the column number.
733 if (unsigned ColNo = PLoc.getColumn()) {
734 if (DiagOpts.Format == DiagnosticOptions::Msvc) {
735 OS << ',';
736 ColNo--;
737 } else
738 OS << ':';
739 OS << ColNo;
740 }
741 switch (DiagOpts.Format) {
742 case DiagnosticOptions::Clang:
743 case DiagnosticOptions::Vi: OS << ':'; break;
744 case DiagnosticOptions::Msvc: OS << ") : "; break;
745 }
746
747 if (DiagOpts.ShowSourceRanges && !Ranges.empty()) {
748 FileID CaretFileID =
749 SM.getFileID(SM.getExpansionLoc(Loc));
750 bool PrintedRange = false;
751
752 for (ArrayRef<CharSourceRange>::const_iterator RI = Ranges.begin(),
753 RE = Ranges.end();
754 RI != RE; ++RI) {
755 // Ignore invalid ranges.
756 if (!RI->isValid()) continue;
757
758 SourceLocation B = SM.getExpansionLoc(RI->getBegin());
759 SourceLocation E = SM.getExpansionLoc(RI->getEnd());
760
761 // If the End location and the start location are the same and are a
762 // macro location, then the range was something that came from a
763 // macro expansion or _Pragma. If this is an object-like macro, the
764 // best we can do is to highlight the range. If this is a
765 // function-like macro, we'd also like to highlight the arguments.
766 if (B == E && RI->getEnd().isMacroID())
767 E = SM.getExpansionRange(RI->getEnd()).second;
768
769 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(B);
770 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E);
771
772 // If the start or end of the range is in another file, just discard
773 // it.
774 if (BInfo.first != CaretFileID || EInfo.first != CaretFileID)
775 continue;
776
777 // Add in the length of the token, so that we cover multi-char
778 // tokens.
779 unsigned TokSize = 0;
780 if (RI->isTokenRange())
781 TokSize = Lexer::MeasureTokenLength(E, SM, LangOpts);
782
783 OS << '{' << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
784 << SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
785 << SM.getLineNumber(EInfo.first, EInfo.second) << ':'
786 << (SM.getColumnNumber(EInfo.first, EInfo.second)+TokSize)
787 << '}';
788 PrintedRange = true;
789 }
790
791 if (PrintedRange)
792 OS << ':';
793 }
794 OS << ' ';
795}
796
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000797void TextDiagnostic::emitBasicNote(StringRef Message) {
798 // FIXME: Emit this as a real note diagnostic.
799 // FIXME: Format an actual diagnostic rather than a hard coded string.
800 OS << "note: " << Message << "\n";
801}
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000802
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000803void TextDiagnostic::emitIncludeLocation(SourceLocation Loc,
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000804 PresumedLoc PLoc,
805 const SourceManager &SM) {
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000806 if (DiagOpts.ShowLocation)
807 OS << "In file included from " << PLoc.getFilename() << ':'
808 << PLoc.getLine() << ":\n";
809 else
810 OS << "In included file:\n";
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000811}
812
813/// \brief Emit a code snippet and caret line.
814///
815/// This routine emits a single line's code snippet and caret line..
816///
817/// \param Loc The location for the caret.
818/// \param Ranges The underlined ranges for this code snippet.
819/// \param Hints The FixIt hints active for this diagnostic.
Chandler Carruth7531f572011-10-15 23:54:09 +0000820void TextDiagnostic::emitSnippetAndCaret(
Chandler Carruth4ba55652011-10-16 07:20:28 +0000821 SourceLocation Loc, DiagnosticsEngine::Level Level,
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000822 SmallVectorImpl<CharSourceRange>& Ranges,
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000823 ArrayRef<FixItHint> Hints,
824 const SourceManager &SM) {
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000825 assert(!Loc.isInvalid() && "must have a valid source location here");
826 assert(Loc.isFileID() && "must have a file location here");
827
Chandler Carruth4ba55652011-10-16 07:20:28 +0000828 // If caret diagnostics are enabled and we have location, we want to
829 // emit the caret. However, we only do this if the location moved
830 // from the last diagnostic, if the last diagnostic was a note that
831 // was part of a different warning or error diagnostic, or if the
832 // diagnostic has ranges. We don't want to emit the same caret
833 // multiple times if one loc has multiple diagnostics.
834 if (!DiagOpts.ShowCarets)
835 return;
836 if (Loc == LastLoc && Ranges.empty() && Hints.empty() &&
837 (LastLevel != DiagnosticsEngine::Note || Level == LastLevel))
838 return;
839
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000840 // Decompose the location into a FID/Offset pair.
841 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
842 FileID FID = LocInfo.first;
843 unsigned FileOffset = LocInfo.second;
844
845 // Get information about the buffer it points into.
846 bool Invalid = false;
Nico Weber40d8e972012-04-26 21:39:46 +0000847 const char *BufStart = SM.getBufferData(FID, &Invalid).data();
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000848 if (Invalid)
849 return;
850
851 unsigned LineNo = SM.getLineNumber(FID, FileOffset);
852 unsigned ColNo = SM.getColumnNumber(FID, FileOffset);
853 unsigned CaretEndColNo
854 = ColNo + Lexer::MeasureTokenLength(Loc, SM, LangOpts);
855
856 // Rewind from the current position to the start of the line.
857 const char *TokPtr = BufStart+FileOffset;
858 const char *LineStart = TokPtr-ColNo+1; // Column # is 1-based.
859
860
861 // Compute the line end. Scan forward from the error position to the end of
862 // the line.
863 const char *LineEnd = TokPtr;
Nico Weber40d8e972012-04-26 21:39:46 +0000864 while (*LineEnd != '\n' && *LineEnd != '\r' && *LineEnd != '\0')
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000865 ++LineEnd;
866
867 // FIXME: This shouldn't be necessary, but the CaretEndColNo can extend past
868 // the source line length as currently being computed. See
869 // test/Misc/message-length.c.
870 CaretEndColNo = std::min(CaretEndColNo, unsigned(LineEnd - LineStart));
871
872 // Copy the line of code into an std::string for ease of manipulation.
873 std::string SourceLine(LineStart, LineEnd);
874
875 // Create a line for the caret that is filled with spaces that is the same
876 // length as the line of source code.
877 std::string CaretLine(LineEnd-LineStart, ' ');
878
Seth Cantrell6749dd52012-04-18 02:44:46 +0000879 const SourceColumnMap sourceColMap(SourceLine, DiagOpts.TabStop);
880
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000881 // Highlight all of the characters covered by Ranges with ~ characters.
882 for (SmallVectorImpl<CharSourceRange>::iterator I = Ranges.begin(),
883 E = Ranges.end();
884 I != E; ++I)
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000885 highlightRange(*I, LineNo, FID, sourceColMap, CaretLine, SM);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000886
887 // Next, insert the caret itself.
Seth Cantrell6749dd52012-04-18 02:44:46 +0000888 ColNo = sourceColMap.byteToColumn(ColNo-1);
889 if (CaretLine.size()<ColNo+1)
890 CaretLine.resize(ColNo+1, ' ');
891 CaretLine[ColNo] = '^';
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000892
Seth Cantrell6749dd52012-04-18 02:44:46 +0000893 std::string FixItInsertionLine = buildFixItInsertionLine(LineNo,
894 sourceColMap,
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000895 Hints, SM);
Seth Cantrell6749dd52012-04-18 02:44:46 +0000896
897 // If the source line is too long for our terminal, select only the
898 // "interesting" source region within that line.
899 unsigned Columns = DiagOpts.MessageLength;
900 if (Columns)
901 selectInterestingSourceRegion(SourceLine, CaretLine, FixItInsertionLine,
902 Columns, sourceColMap);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000903
904 // If we are in -fdiagnostics-print-source-range-info mode, we are trying
905 // to produce easily machine parsable output. Add a space before the
906 // source line and the caret to make it trivial to tell the main diagnostic
907 // line from what the user is intended to see.
908 if (DiagOpts.ShowSourceRanges) {
909 SourceLine = ' ' + SourceLine;
910 CaretLine = ' ' + CaretLine;
911 }
912
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000913 // Finally, remove any blank spaces from the end of CaretLine.
914 while (CaretLine[CaretLine.size()-1] == ' ')
915 CaretLine.erase(CaretLine.end()-1);
916
917 // Emit what we have computed.
Seth Cantrell6749dd52012-04-18 02:44:46 +0000918 emitSnippet(SourceLine);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000919
920 if (DiagOpts.ShowColors)
921 OS.changeColor(caretColor, true);
922 OS << CaretLine << '\n';
923 if (DiagOpts.ShowColors)
924 OS.resetColor();
925
926 if (!FixItInsertionLine.empty()) {
927 if (DiagOpts.ShowColors)
928 // Print fixit line in color
929 OS.changeColor(fixitColor, false);
930 if (DiagOpts.ShowSourceRanges)
931 OS << ' ';
932 OS << FixItInsertionLine << '\n';
933 if (DiagOpts.ShowColors)
934 OS.resetColor();
935 }
936
937 // Print out any parseable fixit information requested by the options.
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000938 emitParseableFixits(Hints, SM);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000939}
940
Benjamin Kramerd1fda032012-05-01 14:34:11 +0000941void TextDiagnostic::emitSnippet(StringRef line) {
Seth Cantrell6749dd52012-04-18 02:44:46 +0000942 if (line.empty())
943 return;
944
945 size_t i = 0;
946
947 std::string to_print;
948 bool print_reversed = false;
949
950 while (i<line.size()) {
951 std::pair<SmallString<16>,bool> res
952 = printableTextForNextCharacter(line, &i, DiagOpts.TabStop);
953 bool was_printable = res.second;
954
Nico Weber40d8e972012-04-26 21:39:46 +0000955 if (DiagOpts.ShowColors && was_printable == print_reversed) {
Seth Cantrell6749dd52012-04-18 02:44:46 +0000956 if (print_reversed)
957 OS.reverseColor();
958 OS << to_print;
959 to_print.clear();
960 if (DiagOpts.ShowColors)
961 OS.resetColor();
962 }
963
964 print_reversed = !was_printable;
965 to_print += res.first.str();
966 }
967
968 if (print_reversed && DiagOpts.ShowColors)
969 OS.reverseColor();
970 OS << to_print;
971 if (print_reversed && DiagOpts.ShowColors)
972 OS.resetColor();
973
974 OS << '\n';
975}
976
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000977/// \brief Highlight a SourceRange (with ~'s) for any characters on LineNo.
Chandler Carruth7531f572011-10-15 23:54:09 +0000978void TextDiagnostic::highlightRange(const CharSourceRange &R,
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000979 unsigned LineNo, FileID FID,
Seth Cantrell6749dd52012-04-18 02:44:46 +0000980 const SourceColumnMap &map,
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000981 std::string &CaretLine,
982 const SourceManager &SM) {
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000983 if (!R.isValid()) return;
984
985 SourceLocation Begin = SM.getExpansionLoc(R.getBegin());
986 SourceLocation End = SM.getExpansionLoc(R.getEnd());
987
988 // If the End location and the start location are the same and are a macro
989 // location, then the range was something that came from a macro expansion
990 // or _Pragma. If this is an object-like macro, the best we can do is to
991 // highlight the range. If this is a function-like macro, we'd also like to
992 // highlight the arguments.
993 if (Begin == End && R.getEnd().isMacroID())
994 End = SM.getExpansionRange(R.getEnd()).second;
995
996 unsigned StartLineNo = SM.getExpansionLineNumber(Begin);
997 if (StartLineNo > LineNo || SM.getFileID(Begin) != FID)
998 return; // No intersection.
999
1000 unsigned EndLineNo = SM.getExpansionLineNumber(End);
1001 if (EndLineNo < LineNo || SM.getFileID(End) != FID)
1002 return; // No intersection.
1003
1004 // Compute the column number of the start.
1005 unsigned StartColNo = 0;
1006 if (StartLineNo == LineNo) {
1007 StartColNo = SM.getExpansionColumnNumber(Begin);
1008 if (StartColNo) --StartColNo; // Zero base the col #.
1009 }
1010
1011 // Compute the column number of the end.
Seth Cantrell6749dd52012-04-18 02:44:46 +00001012 unsigned EndColNo = map.getSourceLine().size();
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001013 if (EndLineNo == LineNo) {
1014 EndColNo = SM.getExpansionColumnNumber(End);
1015 if (EndColNo) {
1016 --EndColNo; // Zero base the col #.
1017
1018 // Add in the length of the token, so that we cover multi-char tokens if
1019 // this is a token range.
1020 if (R.isTokenRange())
1021 EndColNo += Lexer::MeasureTokenLength(End, SM, LangOpts);
1022 } else {
1023 EndColNo = CaretLine.size();
1024 }
1025 }
1026
1027 assert(StartColNo <= EndColNo && "Invalid range!");
1028
1029 // Check that a token range does not highlight only whitespace.
1030 if (R.isTokenRange()) {
1031 // Pick the first non-whitespace column.
Seth Cantrell6749dd52012-04-18 02:44:46 +00001032 while (StartColNo < map.getSourceLine().size() &&
1033 (map.getSourceLine()[StartColNo] == ' ' ||
1034 map.getSourceLine()[StartColNo] == '\t'))
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001035 ++StartColNo;
1036
1037 // Pick the last non-whitespace column.
Seth Cantrell6749dd52012-04-18 02:44:46 +00001038 if (EndColNo > map.getSourceLine().size())
1039 EndColNo = map.getSourceLine().size();
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001040 while (EndColNo-1 &&
Seth Cantrell6749dd52012-04-18 02:44:46 +00001041 (map.getSourceLine()[EndColNo-1] == ' ' ||
1042 map.getSourceLine()[EndColNo-1] == '\t'))
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001043 --EndColNo;
1044
1045 // If the start/end passed each other, then we are trying to highlight a
1046 // range that just exists in whitespace, which must be some sort of other
1047 // bug.
1048 assert(StartColNo <= EndColNo && "Trying to highlight whitespace??");
1049 }
1050
Seth Cantrell6749dd52012-04-18 02:44:46 +00001051 assert(StartColNo <= map.getSourceLine().size() && "Invalid range!");
1052 assert(EndColNo <= map.getSourceLine().size() && "Invalid range!");
1053
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001054 // Fill the range with ~'s.
Seth Cantrell6749dd52012-04-18 02:44:46 +00001055 StartColNo = map.byteToColumn(StartColNo);
1056 EndColNo = map.byteToColumn(EndColNo);
1057
1058 assert(StartColNo <= EndColNo && "Invalid range!");
1059 if (CaretLine.size() < EndColNo)
1060 CaretLine.resize(EndColNo,' ');
1061 std::fill(CaretLine.begin()+StartColNo,CaretLine.begin()+EndColNo,'~');
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001062}
1063
Seth Cantrell6749dd52012-04-18 02:44:46 +00001064std::string TextDiagnostic::buildFixItInsertionLine(
1065 unsigned LineNo,
1066 const SourceColumnMap &map,
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +00001067 ArrayRef<FixItHint> Hints,
1068 const SourceManager &SM) {
Seth Cantrell6749dd52012-04-18 02:44:46 +00001069
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001070 std::string FixItInsertionLine;
1071 if (Hints.empty() || !DiagOpts.ShowFixits)
1072 return FixItInsertionLine;
1073
1074 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1075 I != E; ++I) {
1076 if (!I->CodeToInsert.empty()) {
1077 // We have an insertion hint. Determine whether the inserted
1078 // code is on the same line as the caret.
1079 std::pair<FileID, unsigned> HintLocInfo
1080 = SM.getDecomposedExpansionLoc(I->RemoveRange.getBegin());
1081 if (LineNo == SM.getLineNumber(HintLocInfo.first, HintLocInfo.second)) {
1082 // Insert the new code into the line just below the code
1083 // that the user wrote.
1084 unsigned HintColNo
Seth Cantrell6749dd52012-04-18 02:44:46 +00001085 = SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second) - 1;
1086 // hint must start inside the source or right at the end
1087 assert(HintColNo<static_cast<unsigned>(map.bytes())+1);
1088 HintColNo = map.byteToColumn(HintColNo);
1089
1090 // FIXME: if the fixit includes tabs or other characters that do not
1091 // take up a single column per byte when displayed then
1092 // I->CodeToInsert.size() is not a column number and we're mixing
1093 // units (columns + bytes). We should get printable versions
1094 // of each fixit before using them.
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001095 unsigned LastColumnModified
Seth Cantrell6749dd52012-04-18 02:44:46 +00001096 = HintColNo + I->CodeToInsert.size();
1097
1098 if (LastColumnModified > static_cast<unsigned>(map.bytes())) {
1099 unsigned LastExistingColumn = map.byteToColumn(map.bytes());
1100 unsigned AddedColumns = LastColumnModified-LastExistingColumn;
1101 LastColumnModified = LastExistingColumn + AddedColumns;
1102 } else {
1103 LastColumnModified = map.byteToColumn(LastColumnModified);
1104 }
1105
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001106 if (LastColumnModified > FixItInsertionLine.size())
1107 FixItInsertionLine.resize(LastColumnModified, ' ');
Seth Cantrell6749dd52012-04-18 02:44:46 +00001108 assert(HintColNo+I->CodeToInsert.size() <= FixItInsertionLine.size());
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001109 std::copy(I->CodeToInsert.begin(), I->CodeToInsert.end(),
Seth Cantrell6749dd52012-04-18 02:44:46 +00001110 FixItInsertionLine.begin() + HintColNo);
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001111 } else {
1112 FixItInsertionLine.clear();
1113 break;
1114 }
1115 }
1116 }
1117
Seth Cantrell6749dd52012-04-18 02:44:46 +00001118 expandTabs(FixItInsertionLine, DiagOpts.TabStop);
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001119
1120 return FixItInsertionLine;
1121}
1122
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +00001123void TextDiagnostic::emitParseableFixits(ArrayRef<FixItHint> Hints,
1124 const SourceManager &SM) {
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001125 if (!DiagOpts.ShowParseableFixits)
1126 return;
1127
1128 // We follow FixItRewriter's example in not (yet) handling
1129 // fix-its in macros.
1130 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1131 I != E; ++I) {
1132 if (I->RemoveRange.isInvalid() ||
1133 I->RemoveRange.getBegin().isMacroID() ||
1134 I->RemoveRange.getEnd().isMacroID())
1135 return;
1136 }
1137
1138 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1139 I != E; ++I) {
1140 SourceLocation BLoc = I->RemoveRange.getBegin();
1141 SourceLocation ELoc = I->RemoveRange.getEnd();
1142
1143 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(BLoc);
1144 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(ELoc);
1145
1146 // Adjust for token ranges.
1147 if (I->RemoveRange.isTokenRange())
1148 EInfo.second += Lexer::MeasureTokenLength(ELoc, SM, LangOpts);
1149
1150 // We specifically do not do word-wrapping or tab-expansion here,
1151 // because this is supposed to be easy to parse.
1152 PresumedLoc PLoc = SM.getPresumedLoc(BLoc);
1153 if (PLoc.isInvalid())
1154 break;
1155
1156 OS << "fix-it:\"";
1157 OS.write_escaped(PLoc.getFilename());
1158 OS << "\":{" << SM.getLineNumber(BInfo.first, BInfo.second)
1159 << ':' << SM.getColumnNumber(BInfo.first, BInfo.second)
1160 << '-' << SM.getLineNumber(EInfo.first, EInfo.second)
1161 << ':' << SM.getColumnNumber(EInfo.first, EInfo.second)
1162 << "}:\"";
1163 OS.write_escaped(I->CodeToInsert);
1164 OS << "\"\n";
1165 }
1166}