1 //===--- 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/CharInfo.h" 12 #include "clang/Basic/DiagnosticOptions.h" 13 #include "clang/Basic/FileManager.h" 14 #include "clang/Basic/SourceManager.h" 15 #include "clang/Lex/Lexer.h" 16 #include "llvm/ADT/SmallString.h" 17 #include "llvm/ADT/StringExtras.h" 18 #include "llvm/Support/ConvertUTF.h" 19 #include "llvm/Support/ErrorHandling.h" 20 #include "llvm/Support/Locale.h" 21 #include "llvm/Support/Path.h" 22 #include "llvm/Support/raw_ostream.h" 23 #include <algorithm> 24 25 using namespace clang; 26 27 static const enum raw_ostream::Colors noteColor = 28 raw_ostream::BLACK; 29 static const enum raw_ostream::Colors remarkColor = 30 raw_ostream::BLUE; 31 static const enum raw_ostream::Colors fixitColor = 32 raw_ostream::GREEN; 33 static const enum raw_ostream::Colors caretColor = 34 raw_ostream::GREEN; 35 static const enum raw_ostream::Colors warningColor = 36 raw_ostream::MAGENTA; 37 static const enum raw_ostream::Colors templateColor = 38 raw_ostream::CYAN; 39 static const enum raw_ostream::Colors errorColor = raw_ostream::RED; 40 static const enum raw_ostream::Colors fatalColor = raw_ostream::RED; 41 // Used for changing only the bold attribute. 42 static const enum raw_ostream::Colors savedColor = 43 raw_ostream::SAVEDCOLOR; 44 45 /// \brief Add highlights to differences in template strings. 46 static void applyTemplateHighlighting(raw_ostream &OS, StringRef Str, 47 bool &Normal, bool Bold) { 48 while (1) { 49 size_t Pos = Str.find(ToggleHighlight); 50 OS << Str.slice(0, Pos); 51 if (Pos == StringRef::npos) 52 break; 53 54 Str = Str.substr(Pos + 1); 55 if (Normal) 56 OS.changeColor(templateColor, true); 57 else { 58 OS.resetColor(); 59 if (Bold) 60 OS.changeColor(savedColor, true); 61 } 62 Normal = !Normal; 63 } 64 } 65 66 /// \brief Number of spaces to indent when word-wrapping. 67 const unsigned WordWrapIndentation = 6; 68 69 static int bytesSincePreviousTabOrLineBegin(StringRef SourceLine, size_t i) { 70 int bytes = 0; 71 while (0<i) { 72 if (SourceLine[--i]=='\t') 73 break; 74 ++bytes; 75 } 76 return bytes; 77 } 78 79 /// \brief returns a printable representation of first item from input range 80 /// 81 /// This function returns a printable representation of the next item in a line 82 /// of source. If the next byte begins a valid and printable character, that 83 /// character is returned along with 'true'. 84 /// 85 /// Otherwise, if the next byte begins a valid, but unprintable character, a 86 /// printable, escaped representation of the character is returned, along with 87 /// 'false'. Otherwise a printable, escaped representation of the next byte 88 /// is returned along with 'false'. 89 /// 90 /// \note The index is updated to be used with a subsequent call to 91 /// printableTextForNextCharacter. 92 /// 93 /// \param SourceLine The line of source 94 /// \param i Pointer to byte index, 95 /// \param TabStop used to expand tabs 96 /// \return pair(printable text, 'true' iff original text was printable) 97 /// 98 static std::pair<SmallString<16>, bool> 99 printableTextForNextCharacter(StringRef SourceLine, size_t *i, 100 unsigned TabStop) { 101 assert(i && "i must not be null"); 102 assert(*i<SourceLine.size() && "must point to a valid index"); 103 104 if (SourceLine[*i]=='\t') { 105 assert(0 < TabStop && TabStop <= DiagnosticOptions::MaxTabStop && 106 "Invalid -ftabstop value"); 107 unsigned col = bytesSincePreviousTabOrLineBegin(SourceLine, *i); 108 unsigned NumSpaces = TabStop - col%TabStop; 109 assert(0 < NumSpaces && NumSpaces <= TabStop 110 && "Invalid computation of space amt"); 111 ++(*i); 112 113 SmallString<16> expandedTab; 114 expandedTab.assign(NumSpaces, ' '); 115 return std::make_pair(expandedTab, true); 116 } 117 118 unsigned char const *begin, *end; 119 begin = reinterpret_cast<unsigned char const *>(&*(SourceLine.begin() + *i)); 120 end = begin + (SourceLine.size() - *i); 121 122 if (llvm::isLegalUTF8Sequence(begin, end)) { 123 llvm::UTF32 c; 124 llvm::UTF32 *cptr = &c; 125 unsigned char const *original_begin = begin; 126 unsigned char const *cp_end = 127 begin + llvm::getNumBytesForUTF8(SourceLine[*i]); 128 129 llvm::ConversionResult res = llvm::ConvertUTF8toUTF32( 130 &begin, cp_end, &cptr, cptr + 1, llvm::strictConversion); 131 (void)res; 132 assert(llvm::conversionOK == res); 133 assert(0 < begin-original_begin 134 && "we must be further along in the string now"); 135 *i += begin-original_begin; 136 137 if (!llvm::sys::locale::isPrint(c)) { 138 // If next character is valid UTF-8, but not printable 139 SmallString<16> expandedCP("<U+>"); 140 while (c) { 141 expandedCP.insert(expandedCP.begin()+3, llvm::hexdigit(c%16)); 142 c/=16; 143 } 144 while (expandedCP.size() < 8) 145 expandedCP.insert(expandedCP.begin()+3, llvm::hexdigit(0)); 146 return std::make_pair(expandedCP, false); 147 } 148 149 // If next character is valid UTF-8, and printable 150 return std::make_pair(SmallString<16>(original_begin, cp_end), true); 151 152 } 153 154 // If next byte is not valid UTF-8 (and therefore not printable) 155 SmallString<16> expandedByte("<XX>"); 156 unsigned char byte = SourceLine[*i]; 157 expandedByte[1] = llvm::hexdigit(byte / 16); 158 expandedByte[2] = llvm::hexdigit(byte % 16); 159 ++(*i); 160 return std::make_pair(expandedByte, false); 161 } 162 163 static void expandTabs(std::string &SourceLine, unsigned TabStop) { 164 size_t i = SourceLine.size(); 165 while (i>0) { 166 i--; 167 if (SourceLine[i]!='\t') 168 continue; 169 size_t tmp_i = i; 170 std::pair<SmallString<16>,bool> res 171 = printableTextForNextCharacter(SourceLine, &tmp_i, TabStop); 172 SourceLine.replace(i, 1, res.first.c_str()); 173 } 174 } 175 176 /// This function takes a raw source line and produces a mapping from the bytes 177 /// of the printable representation of the line to the columns those printable 178 /// characters will appear at (numbering the first column as 0). 179 /// 180 /// If a byte 'i' corresponds to multiple columns (e.g. the byte contains a tab 181 /// character) then the array will map that byte to the first column the 182 /// tab appears at and the next value in the map will have been incremented 183 /// more than once. 184 /// 185 /// If a byte is the first in a sequence of bytes that together map to a single 186 /// entity in the output, then the array will map that byte to the appropriate 187 /// column while the subsequent bytes will be -1. 188 /// 189 /// The last element in the array does not correspond to any byte in the input 190 /// and instead is the number of columns needed to display the source 191 /// 192 /// example: (given a tabstop of 8) 193 /// 194 /// "a \t \u3042" -> {0,1,2,8,9,-1,-1,11} 195 /// 196 /// (\\u3042 is represented in UTF-8 by three bytes and takes two columns to 197 /// display) 198 static void byteToColumn(StringRef SourceLine, unsigned TabStop, 199 SmallVectorImpl<int> &out) { 200 out.clear(); 201 202 if (SourceLine.empty()) { 203 out.resize(1u,0); 204 return; 205 } 206 207 out.resize(SourceLine.size()+1, -1); 208 209 int columns = 0; 210 size_t i = 0; 211 while (i<SourceLine.size()) { 212 out[i] = columns; 213 std::pair<SmallString<16>,bool> res 214 = printableTextForNextCharacter(SourceLine, &i, TabStop); 215 columns += llvm::sys::locale::columnWidth(res.first); 216 } 217 out.back() = columns; 218 } 219 220 /// This function takes a raw source line and produces a mapping from columns 221 /// to the byte of the source line that produced the character displaying at 222 /// that column. This is the inverse of the mapping produced by byteToColumn() 223 /// 224 /// The last element in the array is the number of bytes in the source string 225 /// 226 /// example: (given a tabstop of 8) 227 /// 228 /// "a \t \u3042" -> {0,1,2,-1,-1,-1,-1,-1,3,4,-1,7} 229 /// 230 /// (\\u3042 is represented in UTF-8 by three bytes and takes two columns to 231 /// display) 232 static void columnToByte(StringRef SourceLine, unsigned TabStop, 233 SmallVectorImpl<int> &out) { 234 out.clear(); 235 236 if (SourceLine.empty()) { 237 out.resize(1u, 0); 238 return; 239 } 240 241 int columns = 0; 242 size_t i = 0; 243 while (i<SourceLine.size()) { 244 out.resize(columns+1, -1); 245 out.back() = i; 246 std::pair<SmallString<16>,bool> res 247 = printableTextForNextCharacter(SourceLine, &i, TabStop); 248 columns += llvm::sys::locale::columnWidth(res.first); 249 } 250 out.resize(columns+1, -1); 251 out.back() = i; 252 } 253 254 namespace { 255 struct SourceColumnMap { 256 SourceColumnMap(StringRef SourceLine, unsigned TabStop) 257 : m_SourceLine(SourceLine) { 258 259 ::byteToColumn(SourceLine, TabStop, m_byteToColumn); 260 ::columnToByte(SourceLine, TabStop, m_columnToByte); 261 262 assert(m_byteToColumn.size()==SourceLine.size()+1); 263 assert(0 < m_byteToColumn.size() && 0 < m_columnToByte.size()); 264 assert(m_byteToColumn.size() 265 == static_cast<unsigned>(m_columnToByte.back()+1)); 266 assert(static_cast<unsigned>(m_byteToColumn.back()+1) 267 == m_columnToByte.size()); 268 } 269 int columns() const { return m_byteToColumn.back(); } 270 int bytes() const { return m_columnToByte.back(); } 271 272 /// \brief Map a byte to the column which it is at the start of, or return -1 273 /// if it is not at the start of a column (for a UTF-8 trailing byte). 274 int byteToColumn(int n) const { 275 assert(0<=n && n<static_cast<int>(m_byteToColumn.size())); 276 return m_byteToColumn[n]; 277 } 278 279 /// \brief Map a byte to the first column which contains it. 280 int byteToContainingColumn(int N) const { 281 assert(0 <= N && N < static_cast<int>(m_byteToColumn.size())); 282 while (m_byteToColumn[N] == -1) 283 --N; 284 return m_byteToColumn[N]; 285 } 286 287 /// \brief Map a column to the byte which starts the column, or return -1 if 288 /// the column the second or subsequent column of an expanded tab or similar 289 /// multi-column entity. 290 int columnToByte(int n) const { 291 assert(0<=n && n<static_cast<int>(m_columnToByte.size())); 292 return m_columnToByte[n]; 293 } 294 295 /// \brief Map from a byte index to the next byte which starts a column. 296 int startOfNextColumn(int N) const { 297 assert(0 <= N && N < static_cast<int>(m_byteToColumn.size() - 1)); 298 while (byteToColumn(++N) == -1) {} 299 return N; 300 } 301 302 /// \brief Map from a byte index to the previous byte which starts a column. 303 int startOfPreviousColumn(int N) const { 304 assert(0 < N && N < static_cast<int>(m_byteToColumn.size())); 305 while (byteToColumn(--N) == -1) {} 306 return N; 307 } 308 309 StringRef getSourceLine() const { 310 return m_SourceLine; 311 } 312 313 private: 314 const std::string m_SourceLine; 315 SmallVector<int,200> m_byteToColumn; 316 SmallVector<int,200> m_columnToByte; 317 }; 318 } // end anonymous namespace 319 320 /// \brief When the source code line we want to print is too long for 321 /// the terminal, select the "interesting" region. 322 static void selectInterestingSourceRegion(std::string &SourceLine, 323 std::string &CaretLine, 324 std::string &FixItInsertionLine, 325 unsigned Columns, 326 const SourceColumnMap &map) { 327 unsigned CaretColumns = CaretLine.size(); 328 unsigned FixItColumns = llvm::sys::locale::columnWidth(FixItInsertionLine); 329 unsigned MaxColumns = std::max(static_cast<unsigned>(map.columns()), 330 std::max(CaretColumns, FixItColumns)); 331 // if the number of columns is less than the desired number we're done 332 if (MaxColumns <= Columns) 333 return; 334 335 // No special characters are allowed in CaretLine. 336 assert(CaretLine.end() == 337 std::find_if(CaretLine.begin(), CaretLine.end(), 338 [](char c) { return c < ' ' || '~' < c; })); 339 340 // Find the slice that we need to display the full caret line 341 // correctly. 342 unsigned CaretStart = 0, CaretEnd = CaretLine.size(); 343 for (; CaretStart != CaretEnd; ++CaretStart) 344 if (!isWhitespace(CaretLine[CaretStart])) 345 break; 346 347 for (; CaretEnd != CaretStart; --CaretEnd) 348 if (!isWhitespace(CaretLine[CaretEnd - 1])) 349 break; 350 351 // caret has already been inserted into CaretLine so the above whitespace 352 // check is guaranteed to include the caret 353 354 // If we have a fix-it line, make sure the slice includes all of the 355 // fix-it information. 356 if (!FixItInsertionLine.empty()) { 357 unsigned FixItStart = 0, FixItEnd = FixItInsertionLine.size(); 358 for (; FixItStart != FixItEnd; ++FixItStart) 359 if (!isWhitespace(FixItInsertionLine[FixItStart])) 360 break; 361 362 for (; FixItEnd != FixItStart; --FixItEnd) 363 if (!isWhitespace(FixItInsertionLine[FixItEnd - 1])) 364 break; 365 366 // We can safely use the byte offset FixItStart as the column offset 367 // because the characters up until FixItStart are all ASCII whitespace 368 // characters. 369 unsigned FixItStartCol = FixItStart; 370 unsigned FixItEndCol 371 = llvm::sys::locale::columnWidth(FixItInsertionLine.substr(0, FixItEnd)); 372 373 CaretStart = std::min(FixItStartCol, CaretStart); 374 CaretEnd = std::max(FixItEndCol, CaretEnd); 375 } 376 377 // CaretEnd may have been set at the middle of a character 378 // If it's not at a character's first column then advance it past the current 379 // character. 380 while (static_cast<int>(CaretEnd) < map.columns() && 381 -1 == map.columnToByte(CaretEnd)) 382 ++CaretEnd; 383 384 assert((static_cast<int>(CaretStart) > map.columns() || 385 -1!=map.columnToByte(CaretStart)) && 386 "CaretStart must not point to a column in the middle of a source" 387 " line character"); 388 assert((static_cast<int>(CaretEnd) > map.columns() || 389 -1!=map.columnToByte(CaretEnd)) && 390 "CaretEnd must not point to a column in the middle of a source line" 391 " character"); 392 393 // CaretLine[CaretStart, CaretEnd) contains all of the interesting 394 // parts of the caret line. While this slice is smaller than the 395 // number of columns we have, try to grow the slice to encompass 396 // more context. 397 398 unsigned SourceStart = map.columnToByte(std::min<unsigned>(CaretStart, 399 map.columns())); 400 unsigned SourceEnd = map.columnToByte(std::min<unsigned>(CaretEnd, 401 map.columns())); 402 403 unsigned CaretColumnsOutsideSource = CaretEnd-CaretStart 404 - (map.byteToColumn(SourceEnd)-map.byteToColumn(SourceStart)); 405 406 char const *front_ellipse = " ..."; 407 char const *front_space = " "; 408 char const *back_ellipse = "..."; 409 unsigned ellipses_space = strlen(front_ellipse) + strlen(back_ellipse); 410 411 unsigned TargetColumns = Columns; 412 // Give us extra room for the ellipses 413 // and any of the caret line that extends past the source 414 if (TargetColumns > ellipses_space+CaretColumnsOutsideSource) 415 TargetColumns -= ellipses_space+CaretColumnsOutsideSource; 416 417 while (SourceStart>0 || SourceEnd<SourceLine.size()) { 418 bool ExpandedRegion = false; 419 420 if (SourceStart>0) { 421 unsigned NewStart = map.startOfPreviousColumn(SourceStart); 422 423 // Skip over any whitespace we see here; we're looking for 424 // another bit of interesting text. 425 // FIXME: Detect non-ASCII whitespace characters too. 426 while (NewStart && isWhitespace(SourceLine[NewStart])) 427 NewStart = map.startOfPreviousColumn(NewStart); 428 429 // Skip over this bit of "interesting" text. 430 while (NewStart) { 431 unsigned Prev = map.startOfPreviousColumn(NewStart); 432 if (isWhitespace(SourceLine[Prev])) 433 break; 434 NewStart = Prev; 435 } 436 437 assert(map.byteToColumn(NewStart) != -1); 438 unsigned NewColumns = map.byteToColumn(SourceEnd) - 439 map.byteToColumn(NewStart); 440 if (NewColumns <= TargetColumns) { 441 SourceStart = NewStart; 442 ExpandedRegion = true; 443 } 444 } 445 446 if (SourceEnd<SourceLine.size()) { 447 unsigned NewEnd = map.startOfNextColumn(SourceEnd); 448 449 // Skip over any whitespace we see here; we're looking for 450 // another bit of interesting text. 451 // FIXME: Detect non-ASCII whitespace characters too. 452 while (NewEnd < SourceLine.size() && isWhitespace(SourceLine[NewEnd])) 453 NewEnd = map.startOfNextColumn(NewEnd); 454 455 // Skip over this bit of "interesting" text. 456 while (NewEnd < SourceLine.size() && isWhitespace(SourceLine[NewEnd])) 457 NewEnd = map.startOfNextColumn(NewEnd); 458 459 assert(map.byteToColumn(NewEnd) != -1); 460 unsigned NewColumns = map.byteToColumn(NewEnd) - 461 map.byteToColumn(SourceStart); 462 if (NewColumns <= TargetColumns) { 463 SourceEnd = NewEnd; 464 ExpandedRegion = true; 465 } 466 } 467 468 if (!ExpandedRegion) 469 break; 470 } 471 472 CaretStart = map.byteToColumn(SourceStart); 473 CaretEnd = map.byteToColumn(SourceEnd) + CaretColumnsOutsideSource; 474 475 // [CaretStart, CaretEnd) is the slice we want. Update the various 476 // output lines to show only this slice, with two-space padding 477 // before the lines so that it looks nicer. 478 479 assert(CaretStart!=(unsigned)-1 && CaretEnd!=(unsigned)-1 && 480 SourceStart!=(unsigned)-1 && SourceEnd!=(unsigned)-1); 481 assert(SourceStart <= SourceEnd); 482 assert(CaretStart <= CaretEnd); 483 484 unsigned BackColumnsRemoved 485 = map.byteToColumn(SourceLine.size())-map.byteToColumn(SourceEnd); 486 unsigned FrontColumnsRemoved = CaretStart; 487 unsigned ColumnsKept = CaretEnd-CaretStart; 488 489 // We checked up front that the line needed truncation 490 assert(FrontColumnsRemoved+ColumnsKept+BackColumnsRemoved > Columns); 491 492 // The line needs some truncation, and we'd prefer to keep the front 493 // if possible, so remove the back 494 if (BackColumnsRemoved > strlen(back_ellipse)) 495 SourceLine.replace(SourceEnd, std::string::npos, back_ellipse); 496 497 // If that's enough then we're done 498 if (FrontColumnsRemoved+ColumnsKept <= Columns) 499 return; 500 501 // Otherwise remove the front as well 502 if (FrontColumnsRemoved > strlen(front_ellipse)) { 503 SourceLine.replace(0, SourceStart, front_ellipse); 504 CaretLine.replace(0, CaretStart, front_space); 505 if (!FixItInsertionLine.empty()) 506 FixItInsertionLine.replace(0, CaretStart, front_space); 507 } 508 } 509 510 /// \brief Skip over whitespace in the string, starting at the given 511 /// index. 512 /// 513 /// \returns The index of the first non-whitespace character that is 514 /// greater than or equal to Idx or, if no such character exists, 515 /// returns the end of the string. 516 static unsigned skipWhitespace(unsigned Idx, StringRef Str, unsigned Length) { 517 while (Idx < Length && isWhitespace(Str[Idx])) 518 ++Idx; 519 return Idx; 520 } 521 522 /// \brief If the given character is the start of some kind of 523 /// balanced punctuation (e.g., quotes or parentheses), return the 524 /// character that will terminate the punctuation. 525 /// 526 /// \returns The ending punctuation character, if any, or the NULL 527 /// character if the input character does not start any punctuation. 528 static inline char findMatchingPunctuation(char c) { 529 switch (c) { 530 case '\'': return '\''; 531 case '`': return '\''; 532 case '"': return '"'; 533 case '(': return ')'; 534 case '[': return ']'; 535 case '{': return '}'; 536 default: break; 537 } 538 539 return 0; 540 } 541 542 /// \brief Find the end of the word starting at the given offset 543 /// within a string. 544 /// 545 /// \returns the index pointing one character past the end of the 546 /// word. 547 static unsigned findEndOfWord(unsigned Start, StringRef Str, 548 unsigned Length, unsigned Column, 549 unsigned Columns) { 550 assert(Start < Str.size() && "Invalid start position!"); 551 unsigned End = Start + 1; 552 553 // If we are already at the end of the string, take that as the word. 554 if (End == Str.size()) 555 return End; 556 557 // Determine if the start of the string is actually opening 558 // punctuation, e.g., a quote or parentheses. 559 char EndPunct = findMatchingPunctuation(Str[Start]); 560 if (!EndPunct) { 561 // This is a normal word. Just find the first space character. 562 while (End < Length && !isWhitespace(Str[End])) 563 ++End; 564 return End; 565 } 566 567 // We have the start of a balanced punctuation sequence (quotes, 568 // parentheses, etc.). Determine the full sequence is. 569 SmallString<16> PunctuationEndStack; 570 PunctuationEndStack.push_back(EndPunct); 571 while (End < Length && !PunctuationEndStack.empty()) { 572 if (Str[End] == PunctuationEndStack.back()) 573 PunctuationEndStack.pop_back(); 574 else if (char SubEndPunct = findMatchingPunctuation(Str[End])) 575 PunctuationEndStack.push_back(SubEndPunct); 576 577 ++End; 578 } 579 580 // Find the first space character after the punctuation ended. 581 while (End < Length && !isWhitespace(Str[End])) 582 ++End; 583 584 unsigned PunctWordLength = End - Start; 585 if (// If the word fits on this line 586 Column + PunctWordLength <= Columns || 587 // ... or the word is "short enough" to take up the next line 588 // without too much ugly white space 589 PunctWordLength < Columns/3) 590 return End; // Take the whole thing as a single "word". 591 592 // The whole quoted/parenthesized string is too long to print as a 593 // single "word". Instead, find the "word" that starts just after 594 // the punctuation and use that end-point instead. This will recurse 595 // until it finds something small enough to consider a word. 596 return findEndOfWord(Start + 1, Str, Length, Column + 1, Columns); 597 } 598 599 /// \brief Print the given string to a stream, word-wrapping it to 600 /// some number of columns in the process. 601 /// 602 /// \param OS the stream to which the word-wrapping string will be 603 /// emitted. 604 /// \param Str the string to word-wrap and output. 605 /// \param Columns the number of columns to word-wrap to. 606 /// \param Column the column number at which the first character of \p 607 /// Str will be printed. This will be non-zero when part of the first 608 /// line has already been printed. 609 /// \param Bold if the current text should be bold 610 /// \param Indentation the number of spaces to indent any lines beyond 611 /// the first line. 612 /// \returns true if word-wrapping was required, or false if the 613 /// string fit on the first line. 614 static bool printWordWrapped(raw_ostream &OS, StringRef Str, 615 unsigned Columns, 616 unsigned Column = 0, 617 bool Bold = false, 618 unsigned Indentation = WordWrapIndentation) { 619 const unsigned Length = std::min(Str.find('\n'), Str.size()); 620 bool TextNormal = true; 621 622 // The string used to indent each line. 623 SmallString<16> IndentStr; 624 IndentStr.assign(Indentation, ' '); 625 bool Wrapped = false; 626 for (unsigned WordStart = 0, WordEnd; WordStart < Length; 627 WordStart = WordEnd) { 628 // Find the beginning of the next word. 629 WordStart = skipWhitespace(WordStart, Str, Length); 630 if (WordStart == Length) 631 break; 632 633 // Find the end of this word. 634 WordEnd = findEndOfWord(WordStart, Str, Length, Column, Columns); 635 636 // Does this word fit on the current line? 637 unsigned WordLength = WordEnd - WordStart; 638 if (Column + WordLength < Columns) { 639 // This word fits on the current line; print it there. 640 if (WordStart) { 641 OS << ' '; 642 Column += 1; 643 } 644 applyTemplateHighlighting(OS, Str.substr(WordStart, WordLength), 645 TextNormal, Bold); 646 Column += WordLength; 647 continue; 648 } 649 650 // This word does not fit on the current line, so wrap to the next 651 // line. 652 OS << '\n'; 653 OS.write(&IndentStr[0], Indentation); 654 applyTemplateHighlighting(OS, Str.substr(WordStart, WordLength), 655 TextNormal, Bold); 656 Column = Indentation + WordLength; 657 Wrapped = true; 658 } 659 660 // Append any remaning text from the message with its existing formatting. 661 applyTemplateHighlighting(OS, Str.substr(Length), TextNormal, Bold); 662 663 assert(TextNormal && "Text highlighted at end of diagnostic message."); 664 665 return Wrapped; 666 } 667 668 TextDiagnostic::TextDiagnostic(raw_ostream &OS, 669 const LangOptions &LangOpts, 670 DiagnosticOptions *DiagOpts) 671 : DiagnosticRenderer(LangOpts, DiagOpts), OS(OS) {} 672 673 TextDiagnostic::~TextDiagnostic() {} 674 675 void 676 TextDiagnostic::emitDiagnosticMessage(SourceLocation Loc, 677 PresumedLoc PLoc, 678 DiagnosticsEngine::Level Level, 679 StringRef Message, 680 ArrayRef<clang::CharSourceRange> Ranges, 681 const SourceManager *SM, 682 DiagOrStoredDiag D) { 683 uint64_t StartOfLocationInfo = OS.tell(); 684 685 // Emit the location of this particular diagnostic. 686 if (Loc.isValid()) 687 emitDiagnosticLoc(Loc, PLoc, Level, Ranges, *SM); 688 689 if (DiagOpts->ShowColors) 690 OS.resetColor(); 691 692 printDiagnosticLevel(OS, Level, DiagOpts->ShowColors, 693 DiagOpts->CLFallbackMode); 694 printDiagnosticMessage(OS, 695 /*IsSupplemental*/ Level == DiagnosticsEngine::Note, 696 Message, OS.tell() - StartOfLocationInfo, 697 DiagOpts->MessageLength, DiagOpts->ShowColors); 698 } 699 700 /*static*/ void 701 TextDiagnostic::printDiagnosticLevel(raw_ostream &OS, 702 DiagnosticsEngine::Level Level, 703 bool ShowColors, 704 bool CLFallbackMode) { 705 if (ShowColors) { 706 // Print diagnostic category in bold and color 707 switch (Level) { 708 case DiagnosticsEngine::Ignored: 709 llvm_unreachable("Invalid diagnostic type"); 710 case DiagnosticsEngine::Note: OS.changeColor(noteColor, true); break; 711 case DiagnosticsEngine::Remark: OS.changeColor(remarkColor, true); break; 712 case DiagnosticsEngine::Warning: OS.changeColor(warningColor, true); break; 713 case DiagnosticsEngine::Error: OS.changeColor(errorColor, true); break; 714 case DiagnosticsEngine::Fatal: OS.changeColor(fatalColor, true); break; 715 } 716 } 717 718 switch (Level) { 719 case DiagnosticsEngine::Ignored: 720 llvm_unreachable("Invalid diagnostic type"); 721 case DiagnosticsEngine::Note: OS << "note"; break; 722 case DiagnosticsEngine::Remark: OS << "remark"; break; 723 case DiagnosticsEngine::Warning: OS << "warning"; break; 724 case DiagnosticsEngine::Error: OS << "error"; break; 725 case DiagnosticsEngine::Fatal: OS << "fatal error"; break; 726 } 727 728 // In clang-cl /fallback mode, print diagnostics as "error(clang):". This 729 // makes it more clear whether a message is coming from clang or cl.exe, 730 // and it prevents MSBuild from concluding that the build failed just because 731 // there is an "error:" in the output. 732 if (CLFallbackMode) 733 OS << "(clang)"; 734 735 OS << ": "; 736 737 if (ShowColors) 738 OS.resetColor(); 739 } 740 741 /*static*/ 742 void TextDiagnostic::printDiagnosticMessage(raw_ostream &OS, 743 bool IsSupplemental, 744 StringRef Message, 745 unsigned CurrentColumn, 746 unsigned Columns, bool ShowColors) { 747 bool Bold = false; 748 if (ShowColors && !IsSupplemental) { 749 // Print primary diagnostic messages in bold and without color, to visually 750 // indicate the transition from continuation notes and other output. 751 OS.changeColor(savedColor, true); 752 Bold = true; 753 } 754 755 if (Columns) 756 printWordWrapped(OS, Message, Columns, CurrentColumn, Bold); 757 else { 758 bool Normal = true; 759 applyTemplateHighlighting(OS, Message, Normal, Bold); 760 assert(Normal && "Formatting should have returned to normal"); 761 } 762 763 if (ShowColors) 764 OS.resetColor(); 765 OS << '\n'; 766 } 767 768 void TextDiagnostic::emitFilename(StringRef Filename, const SourceManager &SM) { 769 SmallVector<char, 128> AbsoluteFilename; 770 if (DiagOpts->AbsolutePath) { 771 const DirectoryEntry *Dir = SM.getFileManager().getDirectory( 772 llvm::sys::path::parent_path(Filename)); 773 if (Dir) { 774 StringRef DirName = SM.getFileManager().getCanonicalName(Dir); 775 llvm::sys::path::append(AbsoluteFilename, DirName, 776 llvm::sys::path::filename(Filename)); 777 Filename = StringRef(AbsoluteFilename.data(), AbsoluteFilename.size()); 778 } 779 } 780 781 OS << Filename; 782 } 783 784 /// \brief Print out the file/line/column information and include trace. 785 /// 786 /// This method handlen the emission of the diagnostic location information. 787 /// This includes extracting as much location information as is present for 788 /// the diagnostic and printing it, as well as any include stack or source 789 /// ranges necessary. 790 void TextDiagnostic::emitDiagnosticLoc(SourceLocation Loc, PresumedLoc PLoc, 791 DiagnosticsEngine::Level Level, 792 ArrayRef<CharSourceRange> Ranges, 793 const SourceManager &SM) { 794 if (PLoc.isInvalid()) { 795 // At least print the file name if available: 796 FileID FID = SM.getFileID(Loc); 797 if (FID.isValid()) { 798 const FileEntry* FE = SM.getFileEntryForID(FID); 799 if (FE && FE->isValid()) { 800 emitFilename(FE->getName(), SM); 801 if (FE->isInPCH()) 802 OS << " (in PCH)"; 803 OS << ": "; 804 } 805 } 806 return; 807 } 808 unsigned LineNo = PLoc.getLine(); 809 810 if (!DiagOpts->ShowLocation) 811 return; 812 813 if (DiagOpts->ShowColors) 814 OS.changeColor(savedColor, true); 815 816 emitFilename(PLoc.getFilename(), SM); 817 switch (DiagOpts->getFormat()) { 818 case DiagnosticOptions::Clang: OS << ':' << LineNo; break; 819 case DiagnosticOptions::MSVC: OS << '(' << LineNo; break; 820 case DiagnosticOptions::Vi: OS << " +" << LineNo; break; 821 } 822 823 if (DiagOpts->ShowColumn) 824 // Compute the column number. 825 if (unsigned ColNo = PLoc.getColumn()) { 826 if (DiagOpts->getFormat() == DiagnosticOptions::MSVC) { 827 OS << ','; 828 // Visual Studio 2010 or earlier expects column number to be off by one 829 if (LangOpts.MSCompatibilityVersion && 830 !LangOpts.isCompatibleWithMSVC(LangOptions::MSVC2012)) 831 ColNo--; 832 } else 833 OS << ':'; 834 OS << ColNo; 835 } 836 switch (DiagOpts->getFormat()) { 837 case DiagnosticOptions::Clang: 838 case DiagnosticOptions::Vi: OS << ':'; break; 839 case DiagnosticOptions::MSVC: 840 // MSVC2013 and before print 'file(4) : error'. MSVC2015 gets rid of the 841 // space and prints 'file(4): error'. 842 OS << ')'; 843 if (LangOpts.MSCompatibilityVersion && 844 !LangOpts.isCompatibleWithMSVC(LangOptions::MSVC2015)) 845 OS << ' '; 846 OS << ": "; 847 break; 848 } 849 850 if (DiagOpts->ShowSourceRanges && !Ranges.empty()) { 851 FileID CaretFileID = 852 SM.getFileID(SM.getExpansionLoc(Loc)); 853 bool PrintedRange = false; 854 855 for (ArrayRef<CharSourceRange>::const_iterator RI = Ranges.begin(), 856 RE = Ranges.end(); 857 RI != RE; ++RI) { 858 // Ignore invalid ranges. 859 if (!RI->isValid()) continue; 860 861 SourceLocation B = SM.getExpansionLoc(RI->getBegin()); 862 SourceLocation E = SM.getExpansionLoc(RI->getEnd()); 863 864 // If the End location and the start location are the same and are a 865 // macro location, then the range was something that came from a 866 // macro expansion or _Pragma. If this is an object-like macro, the 867 // best we can do is to highlight the range. If this is a 868 // function-like macro, we'd also like to highlight the arguments. 869 if (B == E && RI->getEnd().isMacroID()) 870 E = SM.getExpansionRange(RI->getEnd()).second; 871 872 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(B); 873 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E); 874 875 // If the start or end of the range is in another file, just discard 876 // it. 877 if (BInfo.first != CaretFileID || EInfo.first != CaretFileID) 878 continue; 879 880 // Add in the length of the token, so that we cover multi-char 881 // tokens. 882 unsigned TokSize = 0; 883 if (RI->isTokenRange()) 884 TokSize = Lexer::MeasureTokenLength(E, SM, LangOpts); 885 886 OS << '{' << SM.getLineNumber(BInfo.first, BInfo.second) << ':' 887 << SM.getColumnNumber(BInfo.first, BInfo.second) << '-' 888 << SM.getLineNumber(EInfo.first, EInfo.second) << ':' 889 << (SM.getColumnNumber(EInfo.first, EInfo.second)+TokSize) 890 << '}'; 891 PrintedRange = true; 892 } 893 894 if (PrintedRange) 895 OS << ':'; 896 } 897 OS << ' '; 898 } 899 900 void TextDiagnostic::emitIncludeLocation(SourceLocation Loc, 901 PresumedLoc PLoc, 902 const SourceManager &SM) { 903 if (DiagOpts->ShowLocation && PLoc.isValid()) 904 OS << "In file included from " << PLoc.getFilename() << ':' 905 << PLoc.getLine() << ":\n"; 906 else 907 OS << "In included file:\n"; 908 } 909 910 void TextDiagnostic::emitImportLocation(SourceLocation Loc, PresumedLoc PLoc, 911 StringRef ModuleName, 912 const SourceManager &SM) { 913 if (DiagOpts->ShowLocation && PLoc.isValid()) 914 OS << "In module '" << ModuleName << "' imported from " 915 << PLoc.getFilename() << ':' << PLoc.getLine() << ":\n"; 916 else 917 OS << "In module '" << ModuleName << "':\n"; 918 } 919 920 void TextDiagnostic::emitBuildingModuleLocation(SourceLocation Loc, 921 PresumedLoc PLoc, 922 StringRef ModuleName, 923 const SourceManager &SM) { 924 if (DiagOpts->ShowLocation && PLoc.isValid()) 925 OS << "While building module '" << ModuleName << "' imported from " 926 << PLoc.getFilename() << ':' << PLoc.getLine() << ":\n"; 927 else 928 OS << "While building module '" << ModuleName << "':\n"; 929 } 930 931 /// \brief Highlight a SourceRange (with ~'s) for any characters on LineNo. 932 static void highlightRange(const CharSourceRange &R, 933 unsigned LineNo, FileID FID, 934 const SourceColumnMap &map, 935 std::string &CaretLine, 936 const SourceManager &SM, 937 const LangOptions &LangOpts) { 938 if (!R.isValid()) return; 939 940 SourceLocation Begin = R.getBegin(); 941 SourceLocation End = R.getEnd(); 942 943 unsigned StartLineNo = SM.getExpansionLineNumber(Begin); 944 if (StartLineNo > LineNo || SM.getFileID(Begin) != FID) 945 return; // No intersection. 946 947 unsigned EndLineNo = SM.getExpansionLineNumber(End); 948 if (EndLineNo < LineNo || SM.getFileID(End) != FID) 949 return; // No intersection. 950 951 // Compute the column number of the start. 952 unsigned StartColNo = 0; 953 if (StartLineNo == LineNo) { 954 StartColNo = SM.getExpansionColumnNumber(Begin); 955 if (StartColNo) --StartColNo; // Zero base the col #. 956 } 957 958 // Compute the column number of the end. 959 unsigned EndColNo = map.getSourceLine().size(); 960 if (EndLineNo == LineNo) { 961 EndColNo = SM.getExpansionColumnNumber(End); 962 if (EndColNo) { 963 --EndColNo; // Zero base the col #. 964 965 // Add in the length of the token, so that we cover multi-char tokens if 966 // this is a token range. 967 if (R.isTokenRange()) 968 EndColNo += Lexer::MeasureTokenLength(End, SM, LangOpts); 969 } else { 970 EndColNo = CaretLine.size(); 971 } 972 } 973 974 assert(StartColNo <= EndColNo && "Invalid range!"); 975 976 // Check that a token range does not highlight only whitespace. 977 if (R.isTokenRange()) { 978 // Pick the first non-whitespace column. 979 while (StartColNo < map.getSourceLine().size() && 980 (map.getSourceLine()[StartColNo] == ' ' || 981 map.getSourceLine()[StartColNo] == '\t')) 982 StartColNo = map.startOfNextColumn(StartColNo); 983 984 // Pick the last non-whitespace column. 985 if (EndColNo > map.getSourceLine().size()) 986 EndColNo = map.getSourceLine().size(); 987 while (EndColNo && 988 (map.getSourceLine()[EndColNo-1] == ' ' || 989 map.getSourceLine()[EndColNo-1] == '\t')) 990 EndColNo = map.startOfPreviousColumn(EndColNo); 991 992 // If the start/end passed each other, then we are trying to highlight a 993 // range that just exists in whitespace, which must be some sort of other 994 // bug. 995 assert(StartColNo <= EndColNo && "Trying to highlight whitespace??"); 996 } 997 998 assert(StartColNo <= map.getSourceLine().size() && "Invalid range!"); 999 assert(EndColNo <= map.getSourceLine().size() && "Invalid range!"); 1000 1001 // Fill the range with ~'s. 1002 StartColNo = map.byteToContainingColumn(StartColNo); 1003 EndColNo = map.byteToContainingColumn(EndColNo); 1004 1005 assert(StartColNo <= EndColNo && "Invalid range!"); 1006 if (CaretLine.size() < EndColNo) 1007 CaretLine.resize(EndColNo,' '); 1008 std::fill(CaretLine.begin()+StartColNo,CaretLine.begin()+EndColNo,'~'); 1009 } 1010 1011 static std::string buildFixItInsertionLine(unsigned LineNo, 1012 const SourceColumnMap &map, 1013 ArrayRef<FixItHint> Hints, 1014 const SourceManager &SM, 1015 const DiagnosticOptions *DiagOpts) { 1016 std::string FixItInsertionLine; 1017 if (Hints.empty() || !DiagOpts->ShowFixits) 1018 return FixItInsertionLine; 1019 unsigned PrevHintEndCol = 0; 1020 1021 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end(); 1022 I != E; ++I) { 1023 if (!I->CodeToInsert.empty()) { 1024 // We have an insertion hint. Determine whether the inserted 1025 // code contains no newlines and is on the same line as the caret. 1026 std::pair<FileID, unsigned> HintLocInfo 1027 = SM.getDecomposedExpansionLoc(I->RemoveRange.getBegin()); 1028 if (LineNo == SM.getLineNumber(HintLocInfo.first, HintLocInfo.second) && 1029 StringRef(I->CodeToInsert).find_first_of("\n\r") == StringRef::npos) { 1030 // Insert the new code into the line just below the code 1031 // that the user wrote. 1032 // Note: When modifying this function, be very careful about what is a 1033 // "column" (printed width, platform-dependent) and what is a 1034 // "byte offset" (SourceManager "column"). 1035 unsigned HintByteOffset 1036 = SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second) - 1; 1037 1038 // The hint must start inside the source or right at the end 1039 assert(HintByteOffset < static_cast<unsigned>(map.bytes())+1); 1040 unsigned HintCol = map.byteToContainingColumn(HintByteOffset); 1041 1042 // If we inserted a long previous hint, push this one forwards, and add 1043 // an extra space to show that this is not part of the previous 1044 // completion. This is sort of the best we can do when two hints appear 1045 // to overlap. 1046 // 1047 // Note that if this hint is located immediately after the previous 1048 // hint, no space will be added, since the location is more important. 1049 if (HintCol < PrevHintEndCol) 1050 HintCol = PrevHintEndCol + 1; 1051 1052 // This should NOT use HintByteOffset, because the source might have 1053 // Unicode characters in earlier columns. 1054 unsigned NewFixItLineSize = FixItInsertionLine.size() + 1055 (HintCol - PrevHintEndCol) + I->CodeToInsert.size(); 1056 if (NewFixItLineSize > FixItInsertionLine.size()) 1057 FixItInsertionLine.resize(NewFixItLineSize, ' '); 1058 1059 std::copy(I->CodeToInsert.begin(), I->CodeToInsert.end(), 1060 FixItInsertionLine.end() - I->CodeToInsert.size()); 1061 1062 PrevHintEndCol = 1063 HintCol + llvm::sys::locale::columnWidth(I->CodeToInsert); 1064 } else { 1065 FixItInsertionLine.clear(); 1066 break; 1067 } 1068 } 1069 } 1070 1071 expandTabs(FixItInsertionLine, DiagOpts->TabStop); 1072 1073 return FixItInsertionLine; 1074 } 1075 1076 /// \brief Emit a code snippet and caret line. 1077 /// 1078 /// This routine emits a single line's code snippet and caret line.. 1079 /// 1080 /// \param Loc The location for the caret. 1081 /// \param Ranges The underlined ranges for this code snippet. 1082 /// \param Hints The FixIt hints active for this diagnostic. 1083 void TextDiagnostic::emitSnippetAndCaret( 1084 SourceLocation Loc, DiagnosticsEngine::Level Level, 1085 SmallVectorImpl<CharSourceRange>& Ranges, 1086 ArrayRef<FixItHint> Hints, 1087 const SourceManager &SM) { 1088 assert(Loc.isValid() && "must have a valid source location here"); 1089 assert(Loc.isFileID() && "must have a file location here"); 1090 1091 // If caret diagnostics are enabled and we have location, we want to 1092 // emit the caret. However, we only do this if the location moved 1093 // from the last diagnostic, if the last diagnostic was a note that 1094 // was part of a different warning or error diagnostic, or if the 1095 // diagnostic has ranges. We don't want to emit the same caret 1096 // multiple times if one loc has multiple diagnostics. 1097 if (!DiagOpts->ShowCarets) 1098 return; 1099 if (Loc == LastLoc && Ranges.empty() && Hints.empty() && 1100 (LastLevel != DiagnosticsEngine::Note || Level == LastLevel)) 1101 return; 1102 1103 // Decompose the location into a FID/Offset pair. 1104 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); 1105 FileID FID = LocInfo.first; 1106 unsigned FileOffset = LocInfo.second; 1107 1108 // Get information about the buffer it points into. 1109 bool Invalid = false; 1110 StringRef BufData = SM.getBufferData(FID, &Invalid); 1111 if (Invalid) 1112 return; 1113 1114 const char *BufStart = BufData.data(); 1115 const char *BufEnd = BufStart + BufData.size(); 1116 1117 unsigned LineNo = SM.getLineNumber(FID, FileOffset); 1118 unsigned ColNo = SM.getColumnNumber(FID, FileOffset); 1119 1120 // Arbitrarily stop showing snippets when the line is too long. 1121 static const size_t MaxLineLengthToPrint = 4096; 1122 if (ColNo > MaxLineLengthToPrint) 1123 return; 1124 1125 // Rewind from the current position to the start of the line. 1126 const char *TokPtr = BufStart+FileOffset; 1127 const char *LineStart = TokPtr-ColNo+1; // Column # is 1-based. 1128 1129 // Compute the line end. Scan forward from the error position to the end of 1130 // the line. 1131 const char *LineEnd = TokPtr; 1132 while (*LineEnd != '\n' && *LineEnd != '\r' && LineEnd != BufEnd) 1133 ++LineEnd; 1134 1135 // Arbitrarily stop showing snippets when the line is too long. 1136 if (size_t(LineEnd - LineStart) > MaxLineLengthToPrint) 1137 return; 1138 1139 // Trim trailing null-bytes. 1140 StringRef Line(LineStart, LineEnd - LineStart); 1141 while (Line.size() > ColNo && Line.back() == '\0') 1142 Line = Line.drop_back(); 1143 1144 // Copy the line of code into an std::string for ease of manipulation. 1145 std::string SourceLine(Line.begin(), Line.end()); 1146 1147 // Build the byte to column map. 1148 const SourceColumnMap sourceColMap(SourceLine, DiagOpts->TabStop); 1149 1150 // Create a line for the caret that is filled with spaces that is the same 1151 // number of columns as the line of source code. 1152 std::string CaretLine(sourceColMap.columns(), ' '); 1153 1154 // Highlight all of the characters covered by Ranges with ~ characters. 1155 for (SmallVectorImpl<CharSourceRange>::iterator I = Ranges.begin(), 1156 E = Ranges.end(); 1157 I != E; ++I) 1158 highlightRange(*I, LineNo, FID, sourceColMap, CaretLine, SM, LangOpts); 1159 1160 // Next, insert the caret itself. 1161 ColNo = sourceColMap.byteToContainingColumn(ColNo-1); 1162 if (CaretLine.size()<ColNo+1) 1163 CaretLine.resize(ColNo+1, ' '); 1164 CaretLine[ColNo] = '^'; 1165 1166 std::string FixItInsertionLine = buildFixItInsertionLine(LineNo, 1167 sourceColMap, 1168 Hints, SM, 1169 DiagOpts.get()); 1170 1171 // If the source line is too long for our terminal, select only the 1172 // "interesting" source region within that line. 1173 unsigned Columns = DiagOpts->MessageLength; 1174 if (Columns) 1175 selectInterestingSourceRegion(SourceLine, CaretLine, FixItInsertionLine, 1176 Columns, sourceColMap); 1177 1178 // If we are in -fdiagnostics-print-source-range-info mode, we are trying 1179 // to produce easily machine parsable output. Add a space before the 1180 // source line and the caret to make it trivial to tell the main diagnostic 1181 // line from what the user is intended to see. 1182 if (DiagOpts->ShowSourceRanges) { 1183 SourceLine = ' ' + SourceLine; 1184 CaretLine = ' ' + CaretLine; 1185 } 1186 1187 // Finally, remove any blank spaces from the end of CaretLine. 1188 while (CaretLine[CaretLine.size()-1] == ' ') 1189 CaretLine.erase(CaretLine.end()-1); 1190 1191 // Emit what we have computed. 1192 emitSnippet(SourceLine); 1193 1194 if (DiagOpts->ShowColors) 1195 OS.changeColor(caretColor, true); 1196 OS << CaretLine << '\n'; 1197 if (DiagOpts->ShowColors) 1198 OS.resetColor(); 1199 1200 if (!FixItInsertionLine.empty()) { 1201 if (DiagOpts->ShowColors) 1202 // Print fixit line in color 1203 OS.changeColor(fixitColor, false); 1204 if (DiagOpts->ShowSourceRanges) 1205 OS << ' '; 1206 OS << FixItInsertionLine << '\n'; 1207 if (DiagOpts->ShowColors) 1208 OS.resetColor(); 1209 } 1210 1211 // Print out any parseable fixit information requested by the options. 1212 emitParseableFixits(Hints, SM); 1213 } 1214 1215 void TextDiagnostic::emitSnippet(StringRef line) { 1216 if (line.empty()) 1217 return; 1218 1219 size_t i = 0; 1220 1221 std::string to_print; 1222 bool print_reversed = false; 1223 1224 while (i<line.size()) { 1225 std::pair<SmallString<16>,bool> res 1226 = printableTextForNextCharacter(line, &i, DiagOpts->TabStop); 1227 bool was_printable = res.second; 1228 1229 if (DiagOpts->ShowColors && was_printable == print_reversed) { 1230 if (print_reversed) 1231 OS.reverseColor(); 1232 OS << to_print; 1233 to_print.clear(); 1234 if (DiagOpts->ShowColors) 1235 OS.resetColor(); 1236 } 1237 1238 print_reversed = !was_printable; 1239 to_print += res.first.str(); 1240 } 1241 1242 if (print_reversed && DiagOpts->ShowColors) 1243 OS.reverseColor(); 1244 OS << to_print; 1245 if (print_reversed && DiagOpts->ShowColors) 1246 OS.resetColor(); 1247 1248 OS << '\n'; 1249 } 1250 1251 void TextDiagnostic::emitParseableFixits(ArrayRef<FixItHint> Hints, 1252 const SourceManager &SM) { 1253 if (!DiagOpts->ShowParseableFixits) 1254 return; 1255 1256 // We follow FixItRewriter's example in not (yet) handling 1257 // fix-its in macros. 1258 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end(); 1259 I != E; ++I) { 1260 if (I->RemoveRange.isInvalid() || 1261 I->RemoveRange.getBegin().isMacroID() || 1262 I->RemoveRange.getEnd().isMacroID()) 1263 return; 1264 } 1265 1266 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end(); 1267 I != E; ++I) { 1268 SourceLocation BLoc = I->RemoveRange.getBegin(); 1269 SourceLocation ELoc = I->RemoveRange.getEnd(); 1270 1271 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(BLoc); 1272 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(ELoc); 1273 1274 // Adjust for token ranges. 1275 if (I->RemoveRange.isTokenRange()) 1276 EInfo.second += Lexer::MeasureTokenLength(ELoc, SM, LangOpts); 1277 1278 // We specifically do not do word-wrapping or tab-expansion here, 1279 // because this is supposed to be easy to parse. 1280 PresumedLoc PLoc = SM.getPresumedLoc(BLoc); 1281 if (PLoc.isInvalid()) 1282 break; 1283 1284 OS << "fix-it:\""; 1285 OS.write_escaped(PLoc.getFilename()); 1286 OS << "\":{" << SM.getLineNumber(BInfo.first, BInfo.second) 1287 << ':' << SM.getColumnNumber(BInfo.first, BInfo.second) 1288 << '-' << SM.getLineNumber(EInfo.first, EInfo.second) 1289 << ':' << SM.getColumnNumber(EInfo.first, EInfo.second) 1290 << "}:\""; 1291 OS.write_escaped(I->CodeToInsert); 1292 OS << "\"\n"; 1293 } 1294 } 1295