blob: 3c35ab24f2ff3f5a88424abd1b5e6c9619da0c87 [file] [log] [blame]
Chandler Carrutha3028852011-10-15 23:43:53 +00001//===--- TextDiagnostic.cpp - Text Diagnostic Pretty-Printing -------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "clang/Frontend/TextDiagnostic.h"
11#include "clang/Basic/FileManager.h"
12#include "clang/Basic/SourceManager.h"
Seth Cantrell99e2fa82012-04-18 02:44:46 +000013#include "clang/Basic/ConvertUTF.h"
Chandler Carrutha3028852011-10-15 23:43:53 +000014#include "clang/Frontend/DiagnosticOptions.h"
15#include "clang/Lex/Lexer.h"
16#include "llvm/Support/MemoryBuffer.h"
17#include "llvm/Support/raw_ostream.h"
18#include "llvm/Support/ErrorHandling.h"
Seth Cantrell99e2fa82012-04-18 02:44:46 +000019#include "llvm/Support/Locale.h"
Chandler Carrutha3028852011-10-15 23:43:53 +000020#include "llvm/ADT/SmallString.h"
Seth Cantrell99e2fa82012-04-18 02:44:46 +000021#include "llvm/ADT/StringExtras.h"
Chandler Carrutha3028852011-10-15 23:43:53 +000022#include <algorithm>
Seth Cantrell99e2fa82012-04-18 02:44:46 +000023
Chandler Carrutha3028852011-10-15 23:43:53 +000024using namespace clang;
25
26static const enum raw_ostream::Colors noteColor =
27 raw_ostream::BLACK;
28static const enum raw_ostream::Colors fixitColor =
29 raw_ostream::GREEN;
30static const enum raw_ostream::Colors caretColor =
31 raw_ostream::GREEN;
32static const enum raw_ostream::Colors warningColor =
33 raw_ostream::MAGENTA;
34static const enum raw_ostream::Colors errorColor = raw_ostream::RED;
35static const enum raw_ostream::Colors fatalColor = raw_ostream::RED;
36// Used for changing only the bold attribute.
37static const enum raw_ostream::Colors savedColor =
38 raw_ostream::SAVEDCOLOR;
39
40/// \brief Number of spaces to indent when word-wrapping.
41const unsigned WordWrapIndentation = 6;
42
Seth Cantrell99e2fa82012-04-18 02:44:46 +000043int bytesSincePreviousTabOrLineBegin(StringRef SourceLine, size_t i) {
44 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///
72std::pair<SmallString<16>,bool>
73printableTextForNextCharacter(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);
117 assert(conversionOK==res);
118 assert(0 < begin-original_begin
119 && "we must be further along in the string now");
120 *i += begin-original_begin;
121
122 if (!llvm::sys::locale::isPrint(c)) {
123 // If next character is valid UTF-8, but not printable
124 SmallString<16> expandedCP("<U+>");
125 while (c) {
126 expandedCP.insert(expandedCP.begin()+3, llvm::hexdigit(c%16));
127 c/=16;
128 }
129 while (expandedCP.size() < 8)
130 expandedCP.insert(expandedCP.begin()+3, llvm::hexdigit(0));
131 return std::make_pair(expandedCP, false);
132 }
133
134 // If next character is valid UTF-8, and printable
135 return std::make_pair(SmallString<16>(original_begin, cp_end), true);
136
137 }
138
139 // If next byte is not valid UTF-8 (and therefore not printable)
140 SmallString<16> expandedByte("<XX>");
141 unsigned char byte = SourceLine[*i];
142 expandedByte[1] = llvm::hexdigit(byte / 16);
143 expandedByte[2] = llvm::hexdigit(byte % 16);
144 ++(*i);
145 return std::make_pair(expandedByte, false);
146}
147
148void expandTabs(std::string &SourceLine, unsigned TabStop) {
149 size_t i = SourceLine.size();
150 while (i>0) {
151 i--;
152 if (SourceLine[i]!='\t')
153 continue;
154 size_t tmp_i = i;
155 std::pair<SmallString<16>,bool> res
156 = printableTextForNextCharacter(SourceLine, &tmp_i, TabStop);
157 SourceLine.replace(i, 1, res.first.c_str());
158 }
159}
160
161/// This function takes a raw source line and produces a mapping from the bytes
162/// of the printable representation of the line to the columns those printable
163/// characters will appear at (numbering the first column as 0).
164///
165/// If a byte 'i' corresponds to muliple columns (e.g. the byte contains a tab
166/// character) then the the array will map that byte to the first column the
167/// tab appears at and the next value in the map will have been incremented
168/// more than once.
169///
170/// If a byte is the first in a sequence of bytes that together map to a single
171/// entity in the output, then the array will map that byte to the appropriate
172/// column while the subsequent bytes will be -1.
173///
174/// The last element in the array does not correspond to any byte in the input
175/// and instead is the number of columns needed to display the source
176///
177/// example: (given a tabstop of 8)
178///
179/// "a \t \u3042" -> {0,1,2,8,9,-1,-1,11}
180///
181/// (\u3042 is represented in UTF-8 by three bytes and takes two columns to
182/// display)
183void byteToColumn(StringRef SourceLine, unsigned TabStop,
184 SmallVectorImpl<int> &out) {
185 out.clear();
186
187 if (SourceLine.empty()) {
188 out.resize(1u,0);
189 return;
190 }
191
192 out.resize(SourceLine.size()+1, -1);
193
194 int columns = 0;
195 size_t i = 0;
196 while (i<SourceLine.size()) {
197 out[i] = columns;
198 std::pair<SmallString<16>,bool> res
199 = printableTextForNextCharacter(SourceLine, &i, TabStop);
200 columns += llvm::sys::locale::columnWidth(res.first);
201 }
202 out.back() = columns;
203}
204
205/// This function takes a raw source line and produces a mapping from columns
206/// to the byte of the source line that produced the character displaying at
207/// that column. This is the inverse of the mapping produced by byteToColumn()
208///
209/// The last element in the array is the number of bytes in the source string
210///
211/// example: (given a tabstop of 8)
212///
213/// "a \t \u3042" -> {0,1,2,-1,-1,-1,-1,-1,3,4,-1,7}
214///
215/// (\u3042 is represented in UTF-8 by three bytes and takes two columns to
216/// display)
217void columnToByte(StringRef SourceLine, unsigned TabStop,
218 SmallVectorImpl<int> &out) {
219 out.clear();
220
221 if (SourceLine.empty()) {
222 out.resize(1u, 0);
223 return;
224 }
225
226 int columns = 0;
227 size_t i = 0;
228 while (i<SourceLine.size()) {
229 out.resize(columns+1, -1);
230 out.back() = i;
231 std::pair<SmallString<16>,bool> res
232 = printableTextForNextCharacter(SourceLine, &i, TabStop);
233 columns += llvm::sys::locale::columnWidth(res.first);
234 }
235 out.resize(columns+1, -1);
236 out.back() = i;
237}
238
239struct SourceColumnMap {
240 SourceColumnMap(StringRef SourceLine, unsigned TabStop)
241 : m_SourceLine(SourceLine) {
242
243 ::byteToColumn(SourceLine, TabStop, m_byteToColumn);
244 ::columnToByte(SourceLine, TabStop, m_columnToByte);
245
246 assert(m_byteToColumn.size()==SourceLine.size()+1);
247 assert(0 < m_byteToColumn.size() && 0 < m_columnToByte.size());
248 assert(m_byteToColumn.size()
249 == static_cast<unsigned>(m_columnToByte.back()+1));
250 assert(static_cast<unsigned>(m_byteToColumn.back()+1)
251 == m_columnToByte.size());
252 }
253 int columns() const { return m_byteToColumn.back(); }
254 int bytes() const { return m_columnToByte.back(); }
255 int byteToColumn(int n) const {
256 assert(0<=n && n<static_cast<int>(m_byteToColumn.size()));
257 return m_byteToColumn[n];
258 }
259 int columnToByte(int n) const {
260 assert(0<=n && n<static_cast<int>(m_columnToByte.size()));
261 return m_columnToByte[n];
262 }
263 StringRef getSourceLine() const {
264 return m_SourceLine;
265 }
266
267private:
268 const std::string m_SourceLine;
269 SmallVector<int,200> m_byteToColumn;
270 SmallVector<int,200> m_columnToByte;
271};
272
273// used in assert in selectInterestingSourceRegion()
274namespace {
275struct char_out_of_range {
276 const char lower,upper;
277 char_out_of_range(char lower, char upper) :
278 lower(lower), upper(upper) {}
279 bool operator()(char c) { return c < lower || upper < c; }
280};
281}
282
Chandler Carrutha3028852011-10-15 23:43:53 +0000283/// \brief When the source code line we want to print is too long for
284/// the terminal, select the "interesting" region.
Chandler Carruthab4c1da2011-10-15 23:54:09 +0000285static void selectInterestingSourceRegion(std::string &SourceLine,
Chandler Carrutha3028852011-10-15 23:43:53 +0000286 std::string &CaretLine,
287 std::string &FixItInsertionLine,
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000288 unsigned Columns,
289 const SourceColumnMap &map) {
290 unsigned MaxColumns = std::max<unsigned>(map.columns(),
291 std::max(CaretLine.size(),
292 FixItInsertionLine.size()));
293 // if the number of columns is less than the desired number we're done
294 if (MaxColumns <= Columns)
295 return;
296
297 // no special characters allowed in CaretLine or FixItInsertionLine
298 assert(CaretLine.end() ==
299 std::find_if(CaretLine.begin(), CaretLine.end(),
300 char_out_of_range(' ','~')));
301 assert(FixItInsertionLine.end() ==
302 std::find_if(FixItInsertionLine.begin(), FixItInsertionLine.end(),
303 char_out_of_range(' ','~')));
304
Chandler Carrutha3028852011-10-15 23:43:53 +0000305 // Find the slice that we need to display the full caret line
306 // correctly.
307 unsigned CaretStart = 0, CaretEnd = CaretLine.size();
308 for (; CaretStart != CaretEnd; ++CaretStart)
309 if (!isspace(CaretLine[CaretStart]))
310 break;
311
312 for (; CaretEnd != CaretStart; --CaretEnd)
313 if (!isspace(CaretLine[CaretEnd - 1]))
314 break;
315
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000316 // caret has already been inserted into CaretLine so the above whitespace
317 // check is guaranteed to include the caret
Chandler Carrutha3028852011-10-15 23:43:53 +0000318
319 // If we have a fix-it line, make sure the slice includes all of the
320 // fix-it information.
321 if (!FixItInsertionLine.empty()) {
322 unsigned FixItStart = 0, FixItEnd = FixItInsertionLine.size();
323 for (; FixItStart != FixItEnd; ++FixItStart)
324 if (!isspace(FixItInsertionLine[FixItStart]))
325 break;
326
327 for (; FixItEnd != FixItStart; --FixItEnd)
328 if (!isspace(FixItInsertionLine[FixItEnd - 1]))
329 break;
330
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000331 CaretStart = std::min(FixItStart, CaretStart);
332 CaretEnd = std::max(FixItEnd, CaretEnd);
Chandler Carrutha3028852011-10-15 23:43:53 +0000333 }
334
335 // CaretLine[CaretStart, CaretEnd) contains all of the interesting
336 // parts of the caret line. While this slice is smaller than the
337 // number of columns we have, try to grow the slice to encompass
338 // more context.
339
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000340 unsigned SourceStart = map.columnToByte(std::min<unsigned>(CaretStart,
341 map.columns()));
342 unsigned SourceEnd = map.columnToByte(std::min<unsigned>(CaretEnd,
343 map.columns()));
344
345 unsigned CaretColumnsOutsideSource = CaretEnd-CaretStart
346 - (map.byteToColumn(SourceEnd)-map.byteToColumn(SourceStart));
347
348 char const *front_ellipse = " ...";
349 char const *front_space = " ";
350 char const *back_ellipse = "...";
351 unsigned ellipses_space = strlen(front_ellipse) + strlen(back_ellipse);
Chandler Carrutha3028852011-10-15 23:43:53 +0000352
353 unsigned TargetColumns = Columns;
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000354 // Give us extra room for the ellipses
355 // and any of the caret line that extends past the source
356 if (TargetColumns > ellipses_space+CaretColumnsOutsideSource)
357 TargetColumns -= ellipses_space+CaretColumnsOutsideSource;
358
359 while (SourceStart>0 || SourceEnd<SourceLine.size()) {
Chandler Carrutha3028852011-10-15 23:43:53 +0000360 bool ExpandedRegion = false;
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000361
362 if (SourceStart>0) {
363 unsigned NewStart = SourceStart-1;
Chandler Carrutha3028852011-10-15 23:43:53 +0000364
365 // Skip over any whitespace we see here; we're looking for
366 // another bit of interesting text.
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000367 while (NewStart &&
368 (map.byteToColumn(NewStart)==-1 || isspace(SourceLine[NewStart])))
Chandler Carrutha3028852011-10-15 23:43:53 +0000369 --NewStart;
370
371 // Skip over this bit of "interesting" text.
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000372 while (NewStart &&
373 (map.byteToColumn(NewStart)!=-1 && !isspace(SourceLine[NewStart])))
Chandler Carrutha3028852011-10-15 23:43:53 +0000374 --NewStart;
375
376 // Move up to the non-whitespace character we just saw.
377 if (NewStart)
378 ++NewStart;
379
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000380 unsigned NewColumns = map.byteToColumn(SourceEnd) -
381 map.byteToColumn(NewStart);
382 if (NewColumns <= TargetColumns) {
383 SourceStart = NewStart;
Chandler Carrutha3028852011-10-15 23:43:53 +0000384 ExpandedRegion = true;
385 }
386 }
387
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000388 if (SourceEnd<SourceLine.size()) {
389 unsigned NewEnd = SourceEnd+1;
Chandler Carrutha3028852011-10-15 23:43:53 +0000390
391 // Skip over any whitespace we see here; we're looking for
392 // another bit of interesting text.
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000393 while (NewEnd<SourceLine.size() &&
394 (map.byteToColumn(NewEnd)==-1 || isspace(SourceLine[NewEnd])))
Chandler Carrutha3028852011-10-15 23:43:53 +0000395 ++NewEnd;
396
397 // Skip over this bit of "interesting" text.
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000398 while (NewEnd<SourceLine.size() &&
399 (map.byteToColumn(NewEnd)!=-1 && !isspace(SourceLine[NewEnd])))
Chandler Carrutha3028852011-10-15 23:43:53 +0000400 ++NewEnd;
401
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000402 unsigned NewColumns = map.byteToColumn(NewEnd) -
403 map.byteToColumn(SourceStart);
404 if (NewColumns <= TargetColumns) {
405 SourceEnd = NewEnd;
Chandler Carrutha3028852011-10-15 23:43:53 +0000406 ExpandedRegion = true;
407 }
408 }
409
410 if (!ExpandedRegion)
411 break;
412 }
413
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000414 CaretStart = map.byteToColumn(SourceStart);
415 CaretEnd = map.byteToColumn(SourceEnd) + CaretColumnsOutsideSource;
416
Chandler Carrutha3028852011-10-15 23:43:53 +0000417 // [CaretStart, CaretEnd) is the slice we want. Update the various
418 // output lines to show only this slice, with two-space padding
419 // before the lines so that it looks nicer.
Chandler Carrutha3028852011-10-15 23:43:53 +0000420
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000421 assert(CaretStart!=(unsigned)-1 && CaretEnd!=(unsigned)-1 &&
422 SourceStart!=(unsigned)-1 && SourceEnd!=(unsigned)-1);
423 assert(SourceStart <= SourceEnd);
424 assert(CaretStart <= CaretEnd);
425
426 unsigned BackColumnsRemoved
427 = map.byteToColumn(SourceLine.size())-map.byteToColumn(SourceEnd);
428 unsigned FrontColumnsRemoved = CaretStart;
429 unsigned ColumnsKept = CaretEnd-CaretStart;
430
431 // We checked up front that the line needed truncation
432 assert(FrontColumnsRemoved+ColumnsKept+BackColumnsRemoved > Columns);
433
434 // The line needs some trunctiona, and we'd prefer to keep the front
435 // if possible, so remove the back
436 if (BackColumnsRemoved)
437 SourceLine.replace(SourceEnd, std::string::npos, back_ellipse);
438
439 // If that's enough then we're done
440 if (FrontColumnsRemoved+ColumnsKept <= Columns)
441 return;
442
443 // Otherwise remove the front as well
444 if (FrontColumnsRemoved) {
445 SourceLine.replace(0, SourceStart, front_ellipse);
446 CaretLine.replace(0, CaretStart, front_space);
447 if (!FixItInsertionLine.empty())
448 FixItInsertionLine.replace(0, CaretStart, front_space);
Chandler Carrutha3028852011-10-15 23:43:53 +0000449 }
450}
451
Chandler Carrutha3028852011-10-15 23:43:53 +0000452/// \brief Skip over whitespace in the string, starting at the given
453/// index.
454///
455/// \returns The index of the first non-whitespace character that is
456/// greater than or equal to Idx or, if no such character exists,
457/// returns the end of the string.
458static unsigned skipWhitespace(unsigned Idx, StringRef Str, unsigned Length) {
459 while (Idx < Length && isspace(Str[Idx]))
460 ++Idx;
461 return Idx;
462}
463
464/// \brief If the given character is the start of some kind of
465/// balanced punctuation (e.g., quotes or parentheses), return the
466/// character that will terminate the punctuation.
467///
468/// \returns The ending punctuation character, if any, or the NULL
469/// character if the input character does not start any punctuation.
470static inline char findMatchingPunctuation(char c) {
471 switch (c) {
472 case '\'': return '\'';
473 case '`': return '\'';
474 case '"': return '"';
475 case '(': return ')';
476 case '[': return ']';
477 case '{': return '}';
478 default: break;
479 }
480
481 return 0;
482}
483
484/// \brief Find the end of the word starting at the given offset
485/// within a string.
486///
487/// \returns the index pointing one character past the end of the
488/// word.
489static unsigned findEndOfWord(unsigned Start, StringRef Str,
490 unsigned Length, unsigned Column,
491 unsigned Columns) {
492 assert(Start < Str.size() && "Invalid start position!");
493 unsigned End = Start + 1;
494
495 // If we are already at the end of the string, take that as the word.
496 if (End == Str.size())
497 return End;
498
499 // Determine if the start of the string is actually opening
500 // punctuation, e.g., a quote or parentheses.
501 char EndPunct = findMatchingPunctuation(Str[Start]);
502 if (!EndPunct) {
503 // This is a normal word. Just find the first space character.
504 while (End < Length && !isspace(Str[End]))
505 ++End;
506 return End;
507 }
508
509 // We have the start of a balanced punctuation sequence (quotes,
510 // parentheses, etc.). Determine the full sequence is.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000511 SmallString<16> PunctuationEndStack;
Chandler Carrutha3028852011-10-15 23:43:53 +0000512 PunctuationEndStack.push_back(EndPunct);
513 while (End < Length && !PunctuationEndStack.empty()) {
514 if (Str[End] == PunctuationEndStack.back())
515 PunctuationEndStack.pop_back();
516 else if (char SubEndPunct = findMatchingPunctuation(Str[End]))
517 PunctuationEndStack.push_back(SubEndPunct);
518
519 ++End;
520 }
521
522 // Find the first space character after the punctuation ended.
523 while (End < Length && !isspace(Str[End]))
524 ++End;
525
526 unsigned PunctWordLength = End - Start;
527 if (// If the word fits on this line
528 Column + PunctWordLength <= Columns ||
529 // ... or the word is "short enough" to take up the next line
530 // without too much ugly white space
531 PunctWordLength < Columns/3)
532 return End; // Take the whole thing as a single "word".
533
534 // The whole quoted/parenthesized string is too long to print as a
535 // single "word". Instead, find the "word" that starts just after
536 // the punctuation and use that end-point instead. This will recurse
537 // until it finds something small enough to consider a word.
538 return findEndOfWord(Start + 1, Str, Length, Column + 1, Columns);
539}
540
541/// \brief Print the given string to a stream, word-wrapping it to
542/// some number of columns in the process.
543///
544/// \param OS the stream to which the word-wrapping string will be
545/// emitted.
546/// \param Str the string to word-wrap and output.
547/// \param Columns the number of columns to word-wrap to.
548/// \param Column the column number at which the first character of \p
549/// Str will be printed. This will be non-zero when part of the first
550/// line has already been printed.
551/// \param Indentation the number of spaces to indent any lines beyond
552/// the first line.
553/// \returns true if word-wrapping was required, or false if the
554/// string fit on the first line.
555static bool printWordWrapped(raw_ostream &OS, StringRef Str,
556 unsigned Columns,
557 unsigned Column = 0,
558 unsigned Indentation = WordWrapIndentation) {
559 const unsigned Length = std::min(Str.find('\n'), Str.size());
560
561 // The string used to indent each line.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000562 SmallString<16> IndentStr;
Chandler Carrutha3028852011-10-15 23:43:53 +0000563 IndentStr.assign(Indentation, ' ');
564 bool Wrapped = false;
565 for (unsigned WordStart = 0, WordEnd; WordStart < Length;
566 WordStart = WordEnd) {
567 // Find the beginning of the next word.
568 WordStart = skipWhitespace(WordStart, Str, Length);
569 if (WordStart == Length)
570 break;
571
572 // Find the end of this word.
573 WordEnd = findEndOfWord(WordStart, Str, Length, Column, Columns);
574
575 // Does this word fit on the current line?
576 unsigned WordLength = WordEnd - WordStart;
577 if (Column + WordLength < Columns) {
578 // This word fits on the current line; print it there.
579 if (WordStart) {
580 OS << ' ';
581 Column += 1;
582 }
583 OS << Str.substr(WordStart, WordLength);
584 Column += WordLength;
585 continue;
586 }
587
588 // This word does not fit on the current line, so wrap to the next
589 // line.
590 OS << '\n';
591 OS.write(&IndentStr[0], Indentation);
592 OS << Str.substr(WordStart, WordLength);
593 Column = Indentation + WordLength;
594 Wrapped = true;
595 }
596
597 // Append any remaning text from the message with its existing formatting.
598 OS << Str.substr(Length);
599
600 return Wrapped;
601}
602
603TextDiagnostic::TextDiagnostic(raw_ostream &OS,
604 const SourceManager &SM,
605 const LangOptions &LangOpts,
Chandler Carruth3eb8b542011-10-16 02:57:39 +0000606 const DiagnosticOptions &DiagOpts)
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000607 : DiagnosticRenderer(SM, LangOpts, DiagOpts), OS(OS) {}
Chandler Carrutha3028852011-10-15 23:43:53 +0000608
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000609TextDiagnostic::~TextDiagnostic() {}
Chandler Carrutha3028852011-10-15 23:43:53 +0000610
Ted Kremenekc4bbd852011-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,
Ted Kremenek0964cca2012-02-14 02:46:00 +0000617 DiagOrStoredDiag D) {
Chandler Carrutha3028852011-10-15 23:43:53 +0000618 uint64_t StartOfLocationInfo = OS.tell();
619
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000620 // Emit the location of this particular diagnostic.
Chandler Carruthab4c1da2011-10-15 23:54:09 +0000621 emitDiagnosticLoc(Loc, PLoc, Level, Ranges);
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000622
Chandler Carrutha3028852011-10-15 23:43:53 +0000623 if (DiagOpts.ShowColors)
624 OS.resetColor();
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000625
Chandler Carrutha3028852011-10-15 23:43:53 +0000626 printDiagnosticLevel(OS, Level, DiagOpts.ShowColors);
627 printDiagnosticMessage(OS, Level, Message,
628 OS.tell() - StartOfLocationInfo,
629 DiagOpts.MessageLength, DiagOpts.ShowColors);
Chandler Carrutha3028852011-10-15 23:43:53 +0000630}
631
Chandler Carruth07c346d2011-10-15 23:48:02 +0000632/*static*/ void
633TextDiagnostic::printDiagnosticLevel(raw_ostream &OS,
634 DiagnosticsEngine::Level Level,
635 bool ShowColors) {
636 if (ShowColors) {
637 // Print diagnostic category in bold and color
638 switch (Level) {
639 case DiagnosticsEngine::Ignored:
640 llvm_unreachable("Invalid diagnostic type");
641 case DiagnosticsEngine::Note: OS.changeColor(noteColor, true); break;
642 case DiagnosticsEngine::Warning: OS.changeColor(warningColor, true); break;
643 case DiagnosticsEngine::Error: OS.changeColor(errorColor, true); break;
644 case DiagnosticsEngine::Fatal: OS.changeColor(fatalColor, true); break;
645 }
646 }
647
648 switch (Level) {
649 case DiagnosticsEngine::Ignored:
650 llvm_unreachable("Invalid diagnostic type");
651 case DiagnosticsEngine::Note: OS << "note: "; break;
652 case DiagnosticsEngine::Warning: OS << "warning: "; break;
653 case DiagnosticsEngine::Error: OS << "error: "; break;
654 case DiagnosticsEngine::Fatal: OS << "fatal error: "; break;
655 }
656
657 if (ShowColors)
658 OS.resetColor();
659}
660
661/*static*/ void
662TextDiagnostic::printDiagnosticMessage(raw_ostream &OS,
663 DiagnosticsEngine::Level Level,
664 StringRef Message,
665 unsigned CurrentColumn, unsigned Columns,
666 bool ShowColors) {
667 if (ShowColors) {
668 // Print warnings, errors and fatal errors in bold, no color
669 switch (Level) {
670 case DiagnosticsEngine::Warning: OS.changeColor(savedColor, true); break;
671 case DiagnosticsEngine::Error: OS.changeColor(savedColor, true); break;
672 case DiagnosticsEngine::Fatal: OS.changeColor(savedColor, true); break;
673 default: break; //don't bold notes
674 }
675 }
676
677 if (Columns)
678 printWordWrapped(OS, Message, Columns, CurrentColumn);
679 else
680 OS << Message;
681
682 if (ShowColors)
683 OS.resetColor();
684 OS << '\n';
685}
686
Chandler Carruth07c346d2011-10-15 23:48:02 +0000687/// \brief Print out the file/line/column information and include trace.
688///
689/// This method handlen the emission of the diagnostic location information.
690/// This includes extracting as much location information as is present for
691/// the diagnostic and printing it, as well as any include stack or source
692/// ranges necessary.
Chandler Carruthab4c1da2011-10-15 23:54:09 +0000693void TextDiagnostic::emitDiagnosticLoc(SourceLocation Loc, PresumedLoc PLoc,
Chandler Carruth07c346d2011-10-15 23:48:02 +0000694 DiagnosticsEngine::Level Level,
695 ArrayRef<CharSourceRange> Ranges) {
696 if (PLoc.isInvalid()) {
697 // At least print the file name if available:
698 FileID FID = SM.getFileID(Loc);
699 if (!FID.isInvalid()) {
700 const FileEntry* FE = SM.getFileEntryForID(FID);
701 if (FE && FE->getName()) {
702 OS << FE->getName();
703 if (FE->getDevice() == 0 && FE->getInode() == 0
704 && FE->getFileMode() == 0) {
705 // in PCH is a guess, but a good one:
706 OS << " (in PCH)";
707 }
708 OS << ": ";
709 }
710 }
711 return;
712 }
713 unsigned LineNo = PLoc.getLine();
714
715 if (!DiagOpts.ShowLocation)
716 return;
717
718 if (DiagOpts.ShowColors)
719 OS.changeColor(savedColor, true);
720
721 OS << PLoc.getFilename();
722 switch (DiagOpts.Format) {
723 case DiagnosticOptions::Clang: OS << ':' << LineNo; break;
724 case DiagnosticOptions::Msvc: OS << '(' << LineNo; break;
725 case DiagnosticOptions::Vi: OS << " +" << LineNo; break;
726 }
727
728 if (DiagOpts.ShowColumn)
729 // Compute the column number.
730 if (unsigned ColNo = PLoc.getColumn()) {
731 if (DiagOpts.Format == DiagnosticOptions::Msvc) {
732 OS << ',';
733 ColNo--;
734 } else
735 OS << ':';
736 OS << ColNo;
737 }
738 switch (DiagOpts.Format) {
739 case DiagnosticOptions::Clang:
740 case DiagnosticOptions::Vi: OS << ':'; break;
741 case DiagnosticOptions::Msvc: OS << ") : "; break;
742 }
743
744 if (DiagOpts.ShowSourceRanges && !Ranges.empty()) {
745 FileID CaretFileID =
746 SM.getFileID(SM.getExpansionLoc(Loc));
747 bool PrintedRange = false;
748
749 for (ArrayRef<CharSourceRange>::const_iterator RI = Ranges.begin(),
750 RE = Ranges.end();
751 RI != RE; ++RI) {
752 // Ignore invalid ranges.
753 if (!RI->isValid()) continue;
754
755 SourceLocation B = SM.getExpansionLoc(RI->getBegin());
756 SourceLocation E = SM.getExpansionLoc(RI->getEnd());
757
758 // If the End location and the start location are the same and are a
759 // macro location, then the range was something that came from a
760 // macro expansion or _Pragma. If this is an object-like macro, the
761 // best we can do is to highlight the range. If this is a
762 // function-like macro, we'd also like to highlight the arguments.
763 if (B == E && RI->getEnd().isMacroID())
764 E = SM.getExpansionRange(RI->getEnd()).second;
765
766 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(B);
767 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E);
768
769 // If the start or end of the range is in another file, just discard
770 // it.
771 if (BInfo.first != CaretFileID || EInfo.first != CaretFileID)
772 continue;
773
774 // Add in the length of the token, so that we cover multi-char
775 // tokens.
776 unsigned TokSize = 0;
777 if (RI->isTokenRange())
778 TokSize = Lexer::MeasureTokenLength(E, SM, LangOpts);
779
780 OS << '{' << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
781 << SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
782 << SM.getLineNumber(EInfo.first, EInfo.second) << ':'
783 << (SM.getColumnNumber(EInfo.first, EInfo.second)+TokSize)
784 << '}';
785 PrintedRange = true;
786 }
787
788 if (PrintedRange)
789 OS << ':';
790 }
791 OS << ' ';
792}
793
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000794void TextDiagnostic::emitBasicNote(StringRef Message) {
795 // FIXME: Emit this as a real note diagnostic.
796 // FIXME: Format an actual diagnostic rather than a hard coded string.
797 OS << "note: " << Message << "\n";
798}
Chandler Carrutha3028852011-10-15 23:43:53 +0000799
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000800void TextDiagnostic::emitIncludeLocation(SourceLocation Loc,
801 PresumedLoc PLoc) {
802 if (DiagOpts.ShowLocation)
803 OS << "In file included from " << PLoc.getFilename() << ':'
804 << PLoc.getLine() << ":\n";
805 else
806 OS << "In included file:\n";
Chandler Carrutha3028852011-10-15 23:43:53 +0000807}
808
809/// \brief Emit a code snippet and caret line.
810///
811/// This routine emits a single line's code snippet and caret line..
812///
813/// \param Loc The location for the caret.
814/// \param Ranges The underlined ranges for this code snippet.
815/// \param Hints The FixIt hints active for this diagnostic.
Chandler Carruthab4c1da2011-10-15 23:54:09 +0000816void TextDiagnostic::emitSnippetAndCaret(
Chandler Carruthdc2f2572011-10-16 07:20:28 +0000817 SourceLocation Loc, DiagnosticsEngine::Level Level,
Chandler Carrutha3028852011-10-15 23:43:53 +0000818 SmallVectorImpl<CharSourceRange>& Ranges,
819 ArrayRef<FixItHint> Hints) {
820 assert(!Loc.isInvalid() && "must have a valid source location here");
821 assert(Loc.isFileID() && "must have a file location here");
822
Chandler Carruthdc2f2572011-10-16 07:20:28 +0000823 // If caret diagnostics are enabled and we have location, we want to
824 // emit the caret. However, we only do this if the location moved
825 // from the last diagnostic, if the last diagnostic was a note that
826 // was part of a different warning or error diagnostic, or if the
827 // diagnostic has ranges. We don't want to emit the same caret
828 // multiple times if one loc has multiple diagnostics.
829 if (!DiagOpts.ShowCarets)
830 return;
831 if (Loc == LastLoc && Ranges.empty() && Hints.empty() &&
832 (LastLevel != DiagnosticsEngine::Note || Level == LastLevel))
833 return;
834
Chandler Carrutha3028852011-10-15 23:43:53 +0000835 // Decompose the location into a FID/Offset pair.
836 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
837 FileID FID = LocInfo.first;
838 unsigned FileOffset = LocInfo.second;
839
840 // Get information about the buffer it points into.
841 bool Invalid = false;
Seth Cantrell14dc87f2012-04-17 20:59:59 +0000842 const char *BufStart = SM.getBufferData(FID, &Invalid).data();
Chandler Carrutha3028852011-10-15 23:43:53 +0000843 if (Invalid)
844 return;
845
846 unsigned LineNo = SM.getLineNumber(FID, FileOffset);
847 unsigned ColNo = SM.getColumnNumber(FID, FileOffset);
848 unsigned CaretEndColNo
849 = ColNo + Lexer::MeasureTokenLength(Loc, SM, LangOpts);
850
851 // Rewind from the current position to the start of the line.
852 const char *TokPtr = BufStart+FileOffset;
853 const char *LineStart = TokPtr-ColNo+1; // Column # is 1-based.
854
855
856 // Compute the line end. Scan forward from the error position to the end of
857 // the line.
858 const char *LineEnd = TokPtr;
Seth Cantrell14dc87f2012-04-17 20:59:59 +0000859 while (*LineEnd != '\n' && *LineEnd != '\r' && *LineEnd != '\0')
Chandler Carrutha3028852011-10-15 23:43:53 +0000860 ++LineEnd;
861
862 // FIXME: This shouldn't be necessary, but the CaretEndColNo can extend past
863 // the source line length as currently being computed. See
864 // test/Misc/message-length.c.
865 CaretEndColNo = std::min(CaretEndColNo, unsigned(LineEnd - LineStart));
866
867 // Copy the line of code into an std::string for ease of manipulation.
868 std::string SourceLine(LineStart, LineEnd);
869
870 // Create a line for the caret that is filled with spaces that is the same
871 // length as the line of source code.
872 std::string CaretLine(LineEnd-LineStart, ' ');
873
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000874 const SourceColumnMap sourceColMap(SourceLine, DiagOpts.TabStop);
875
Chandler Carrutha3028852011-10-15 23:43:53 +0000876 // Highlight all of the characters covered by Ranges with ~ characters.
877 for (SmallVectorImpl<CharSourceRange>::iterator I = Ranges.begin(),
878 E = Ranges.end();
879 I != E; ++I)
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000880 highlightRange(*I, LineNo, FID, sourceColMap, CaretLine);
Chandler Carrutha3028852011-10-15 23:43:53 +0000881
882 // Next, insert the caret itself.
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000883 ColNo = sourceColMap.byteToColumn(ColNo-1);
884 if (CaretLine.size()<ColNo+1)
885 CaretLine.resize(ColNo+1, ' ');
886 CaretLine[ColNo] = '^';
Chandler Carrutha3028852011-10-15 23:43:53 +0000887
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000888 std::string FixItInsertionLine = buildFixItInsertionLine(LineNo,
889 sourceColMap,
890 Hints);
891
892 // If the source line is too long for our terminal, select only the
893 // "interesting" source region within that line.
894 unsigned Columns = DiagOpts.MessageLength;
895 if (Columns)
896 selectInterestingSourceRegion(SourceLine, CaretLine, FixItInsertionLine,
897 Columns, sourceColMap);
Chandler Carrutha3028852011-10-15 23:43:53 +0000898
899 // If we are in -fdiagnostics-print-source-range-info mode, we are trying
900 // to produce easily machine parsable output. Add a space before the
901 // source line and the caret to make it trivial to tell the main diagnostic
902 // line from what the user is intended to see.
903 if (DiagOpts.ShowSourceRanges) {
904 SourceLine = ' ' + SourceLine;
905 CaretLine = ' ' + CaretLine;
906 }
907
Chandler Carrutha3028852011-10-15 23:43:53 +0000908 // Finally, remove any blank spaces from the end of CaretLine.
909 while (CaretLine[CaretLine.size()-1] == ' ')
910 CaretLine.erase(CaretLine.end()-1);
911
912 // Emit what we have computed.
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000913 emitSnippet(SourceLine);
Chandler Carrutha3028852011-10-15 23:43:53 +0000914
915 if (DiagOpts.ShowColors)
916 OS.changeColor(caretColor, true);
917 OS << CaretLine << '\n';
918 if (DiagOpts.ShowColors)
919 OS.resetColor();
920
921 if (!FixItInsertionLine.empty()) {
922 if (DiagOpts.ShowColors)
923 // Print fixit line in color
924 OS.changeColor(fixitColor, false);
925 if (DiagOpts.ShowSourceRanges)
926 OS << ' ';
927 OS << FixItInsertionLine << '\n';
928 if (DiagOpts.ShowColors)
929 OS.resetColor();
930 }
931
932 // Print out any parseable fixit information requested by the options.
Chandler Carruthab4c1da2011-10-15 23:54:09 +0000933 emitParseableFixits(Hints);
Chandler Carrutha3028852011-10-15 23:43:53 +0000934}
935
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000936void TextDiagnostic::emitSnippet(StringRef line)
937{
938 if (line.empty())
939 return;
940
941 size_t i = 0;
942
943 std::string to_print;
944 bool print_reversed = false;
945
946 while (i<line.size()) {
947 std::pair<SmallString<16>,bool> res
948 = printableTextForNextCharacter(line, &i, DiagOpts.TabStop);
949 bool was_printable = res.second;
950
951 if (DiagOpts.ShowColors
952 && was_printable==print_reversed) {
953 if (print_reversed)
954 OS.reverseColor();
955 OS << to_print;
956 to_print.clear();
957 if (DiagOpts.ShowColors)
958 OS.resetColor();
959 }
960
961 print_reversed = !was_printable;
962 to_print += res.first.str();
963 }
964
965 if (print_reversed && DiagOpts.ShowColors)
966 OS.reverseColor();
967 OS << to_print;
968 if (print_reversed && DiagOpts.ShowColors)
969 OS.resetColor();
970
971 OS << '\n';
972}
973
Chandler Carrutha3028852011-10-15 23:43:53 +0000974/// \brief Highlight a SourceRange (with ~'s) for any characters on LineNo.
Chandler Carruthab4c1da2011-10-15 23:54:09 +0000975void TextDiagnostic::highlightRange(const CharSourceRange &R,
Chandler Carrutha3028852011-10-15 23:43:53 +0000976 unsigned LineNo, FileID FID,
Seth Cantrell99e2fa82012-04-18 02:44:46 +0000977 const SourceColumnMap &map,
Chandler Carrutha3028852011-10-15 23:43:53 +0000978 std::string &CaretLine) {
Chandler Carrutha3028852011-10-15 23:43:53 +0000979 if (!R.isValid()) return;
980
981 SourceLocation Begin = SM.getExpansionLoc(R.getBegin());
982 SourceLocation End = SM.getExpansionLoc(R.getEnd());
983
984 // If the End location and the start location are the same and are a macro
985 // location, then the range was something that came from a macro expansion
986 // or _Pragma. If this is an object-like macro, the best we can do is to
987 // highlight the range. If this is a function-like macro, we'd also like to
988 // highlight the arguments.
989 if (Begin == End && R.getEnd().isMacroID())
990 End = SM.getExpansionRange(R.getEnd()).second;
991
992 unsigned StartLineNo = SM.getExpansionLineNumber(Begin);
993 if (StartLineNo > LineNo || SM.getFileID(Begin) != FID)
994 return; // No intersection.
995
996 unsigned EndLineNo = SM.getExpansionLineNumber(End);
997 if (EndLineNo < LineNo || SM.getFileID(End) != FID)
998 return; // No intersection.
999
1000 // Compute the column number of the start.
1001 unsigned StartColNo = 0;
1002 if (StartLineNo == LineNo) {
1003 StartColNo = SM.getExpansionColumnNumber(Begin);
1004 if (StartColNo) --StartColNo; // Zero base the col #.
1005 }
1006
1007 // Compute the column number of the end.
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001008 unsigned EndColNo = map.getSourceLine().size();
Chandler Carrutha3028852011-10-15 23:43:53 +00001009 if (EndLineNo == LineNo) {
1010 EndColNo = SM.getExpansionColumnNumber(End);
1011 if (EndColNo) {
1012 --EndColNo; // Zero base the col #.
1013
1014 // Add in the length of the token, so that we cover multi-char tokens if
1015 // this is a token range.
1016 if (R.isTokenRange())
1017 EndColNo += Lexer::MeasureTokenLength(End, SM, LangOpts);
1018 } else {
1019 EndColNo = CaretLine.size();
1020 }
1021 }
1022
1023 assert(StartColNo <= EndColNo && "Invalid range!");
1024
1025 // Check that a token range does not highlight only whitespace.
1026 if (R.isTokenRange()) {
1027 // Pick the first non-whitespace column.
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001028 while (StartColNo < map.getSourceLine().size() &&
1029 (map.getSourceLine()[StartColNo] == ' ' ||
1030 map.getSourceLine()[StartColNo] == '\t'))
Chandler Carrutha3028852011-10-15 23:43:53 +00001031 ++StartColNo;
1032
1033 // Pick the last non-whitespace column.
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001034 if (EndColNo > map.getSourceLine().size())
1035 EndColNo = map.getSourceLine().size();
Chandler Carrutha3028852011-10-15 23:43:53 +00001036 while (EndColNo-1 &&
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001037 (map.getSourceLine()[EndColNo-1] == ' ' ||
1038 map.getSourceLine()[EndColNo-1] == '\t'))
Chandler Carrutha3028852011-10-15 23:43:53 +00001039 --EndColNo;
1040
1041 // If the start/end passed each other, then we are trying to highlight a
1042 // range that just exists in whitespace, which must be some sort of other
1043 // bug.
1044 assert(StartColNo <= EndColNo && "Trying to highlight whitespace??");
1045 }
1046
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001047 assert(StartColNo <= map.getSourceLine().size() && "Invalid range!");
1048 assert(EndColNo <= map.getSourceLine().size() && "Invalid range!");
1049
Chandler Carrutha3028852011-10-15 23:43:53 +00001050 // Fill the range with ~'s.
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001051 StartColNo = map.byteToColumn(StartColNo);
1052 EndColNo = map.byteToColumn(EndColNo);
1053
1054 assert(StartColNo <= EndColNo && "Invalid range!");
1055 if (CaretLine.size() < EndColNo)
1056 CaretLine.resize(EndColNo,' ');
1057 std::fill(CaretLine.begin()+StartColNo,CaretLine.begin()+EndColNo,'~');
Chandler Carrutha3028852011-10-15 23:43:53 +00001058}
1059
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001060std::string TextDiagnostic::buildFixItInsertionLine(
1061 unsigned LineNo,
1062 const SourceColumnMap &map,
1063 ArrayRef<FixItHint> Hints) {
1064
Chandler Carrutha3028852011-10-15 23:43:53 +00001065 std::string FixItInsertionLine;
1066 if (Hints.empty() || !DiagOpts.ShowFixits)
1067 return FixItInsertionLine;
1068
1069 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1070 I != E; ++I) {
1071 if (!I->CodeToInsert.empty()) {
1072 // We have an insertion hint. Determine whether the inserted
1073 // code is on the same line as the caret.
1074 std::pair<FileID, unsigned> HintLocInfo
1075 = SM.getDecomposedExpansionLoc(I->RemoveRange.getBegin());
1076 if (LineNo == SM.getLineNumber(HintLocInfo.first, HintLocInfo.second)) {
1077 // Insert the new code into the line just below the code
1078 // that the user wrote.
1079 unsigned HintColNo
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001080 = SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second) - 1;
1081 // hint must start inside the source or right at the end
1082 assert(HintColNo<static_cast<unsigned>(map.bytes())+1);
1083 HintColNo = map.byteToColumn(HintColNo);
1084
1085 // FIXME: if the fixit includes tabs or other characters that do not
1086 // take up a single column per byte when displayed then
1087 // I->CodeToInsert.size() is not a column number and we're mixing
1088 // units (columns + bytes). We should get printable versions
1089 // of each fixit before using them.
Chandler Carrutha3028852011-10-15 23:43:53 +00001090 unsigned LastColumnModified
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001091 = HintColNo + I->CodeToInsert.size();
1092
1093 if (LastColumnModified > static_cast<unsigned>(map.bytes())) {
1094 unsigned LastExistingColumn = map.byteToColumn(map.bytes());
1095 unsigned AddedColumns = LastColumnModified-LastExistingColumn;
1096 LastColumnModified = LastExistingColumn + AddedColumns;
1097 } else {
1098 LastColumnModified = map.byteToColumn(LastColumnModified);
1099 }
1100
Chandler Carrutha3028852011-10-15 23:43:53 +00001101 if (LastColumnModified > FixItInsertionLine.size())
1102 FixItInsertionLine.resize(LastColumnModified, ' ');
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001103 assert(HintColNo+I->CodeToInsert.size() <= FixItInsertionLine.size());
Chandler Carrutha3028852011-10-15 23:43:53 +00001104 std::copy(I->CodeToInsert.begin(), I->CodeToInsert.end(),
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001105 FixItInsertionLine.begin() + HintColNo);
Chandler Carrutha3028852011-10-15 23:43:53 +00001106 } else {
1107 FixItInsertionLine.clear();
1108 break;
1109 }
1110 }
1111 }
1112
Seth Cantrell99e2fa82012-04-18 02:44:46 +00001113 expandTabs(FixItInsertionLine, DiagOpts.TabStop);
Chandler Carrutha3028852011-10-15 23:43:53 +00001114
1115 return FixItInsertionLine;
1116}
1117
Chandler Carruthab4c1da2011-10-15 23:54:09 +00001118void TextDiagnostic::emitParseableFixits(ArrayRef<FixItHint> Hints) {
Chandler Carrutha3028852011-10-15 23:43:53 +00001119 if (!DiagOpts.ShowParseableFixits)
1120 return;
1121
1122 // We follow FixItRewriter's example in not (yet) handling
1123 // fix-its in macros.
1124 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1125 I != E; ++I) {
1126 if (I->RemoveRange.isInvalid() ||
1127 I->RemoveRange.getBegin().isMacroID() ||
1128 I->RemoveRange.getEnd().isMacroID())
1129 return;
1130 }
1131
1132 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1133 I != E; ++I) {
1134 SourceLocation BLoc = I->RemoveRange.getBegin();
1135 SourceLocation ELoc = I->RemoveRange.getEnd();
1136
1137 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(BLoc);
1138 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(ELoc);
1139
1140 // Adjust for token ranges.
1141 if (I->RemoveRange.isTokenRange())
1142 EInfo.second += Lexer::MeasureTokenLength(ELoc, SM, LangOpts);
1143
1144 // We specifically do not do word-wrapping or tab-expansion here,
1145 // because this is supposed to be easy to parse.
1146 PresumedLoc PLoc = SM.getPresumedLoc(BLoc);
1147 if (PLoc.isInvalid())
1148 break;
1149
1150 OS << "fix-it:\"";
1151 OS.write_escaped(PLoc.getFilename());
1152 OS << "\":{" << SM.getLineNumber(BInfo.first, BInfo.second)
1153 << ':' << SM.getColumnNumber(BInfo.first, BInfo.second)
1154 << '-' << SM.getLineNumber(EInfo.first, EInfo.second)
1155 << ':' << SM.getColumnNumber(EInfo.first, EInfo.second)
1156 << "}:\"";
1157 OS.write_escaped(I->CodeToInsert);
1158 OS << "\"\n";
1159 }
1160}
1161