22#include <algorithm> 23using namespace clang; 24 25static const enum llvm::raw_ostream::Colors noteColor = 26 llvm::raw_ostream::BLACK; 27static const enum llvm::raw_ostream::Colors fixitColor = 28 llvm::raw_ostream::GREEN; 29static const enum llvm::raw_ostream::Colors caretColor = 30 llvm::raw_ostream::GREEN; 31static const enum llvm::raw_ostream::Colors warningColor = 32 llvm::raw_ostream::MAGENTA; 33static const enum llvm::raw_ostream::Colors errorColor = llvm::raw_ostream::RED; 34static const enum llvm::raw_ostream::Colors fatalColor = llvm::raw_ostream::RED; 35// Used for changing only the bold attribute. 36static const enum llvm::raw_ostream::Colors savedColor = 37 llvm::raw_ostream::SAVEDCOLOR; 38 39/// \brief Number of spaces to indent when word-wrapping. 40const unsigned WordWrapIndentation = 6; 41 42TextDiagnosticPrinter::TextDiagnosticPrinter(llvm::raw_ostream &os, 43 const DiagnosticOptions &diags, 44 bool _OwnsOutputStream) 45 : OS(os), LangOpts(0), DiagOpts(&diags), 46 LastCaretDiagnosticWasNote(0), 47 OwnsOutputStream(_OwnsOutputStream) { 48} 49 50TextDiagnosticPrinter::~TextDiagnosticPrinter() { 51 if (OwnsOutputStream) 52 delete &OS; 53} 54 55void TextDiagnosticPrinter:: 56PrintIncludeStack(SourceLocation Loc, const SourceManager &SM) { 57 if (Loc.isInvalid()) return; 58 59 PresumedLoc PLoc = SM.getPresumedLoc(Loc); 60 61 // Print out the other include frames first. 62 PrintIncludeStack(PLoc.getIncludeLoc(), SM); 63 64 if (DiagOpts->ShowLocation) 65 OS << "In file included from " << PLoc.getFilename() 66 << ':' << PLoc.getLine() << ":\n"; 67 else 68 OS << "In included file:\n"; 69} 70 71/// HighlightRange - Given a SourceRange and a line number, highlight (with ~'s) 72/// any characters in LineNo that intersect the SourceRange. 73void TextDiagnosticPrinter::HighlightRange(const SourceRange &R, 74 const SourceManager &SM, 75 unsigned LineNo, FileID FID, 76 std::string &CaretLine, 77 const std::string &SourceLine) { 78 assert(CaretLine.size() == SourceLine.size() && 79 "Expect a correspondence between source and caret line!"); 80 if (!R.isValid()) return; 81 82 SourceLocation Begin = SM.getInstantiationLoc(R.getBegin()); 83 SourceLocation End = SM.getInstantiationLoc(R.getEnd()); 84 85 // If the End location and the start location are the same and are a macro 86 // location, then the range was something that came from a macro expansion 87 // or _Pragma. If this is an object-like macro, the best we can do is to 88 // highlight the range. If this is a function-like macro, we'd also like to 89 // highlight the arguments. 90 if (Begin == End && R.getEnd().isMacroID()) 91 End = SM.getInstantiationRange(R.getEnd()).second; 92 93 unsigned StartLineNo = SM.getInstantiationLineNumber(Begin); 94 if (StartLineNo > LineNo || SM.getFileID(Begin) != FID) 95 return; // No intersection. 96 97 unsigned EndLineNo = SM.getInstantiationLineNumber(End); 98 if (EndLineNo < LineNo || SM.getFileID(End) != FID) 99 return; // No intersection. 100 101 // Compute the column number of the start. 102 unsigned StartColNo = 0; 103 if (StartLineNo == LineNo) { 104 StartColNo = SM.getInstantiationColumnNumber(Begin); 105 if (StartColNo) --StartColNo; // Zero base the col #. 106 } 107 108 // Compute the column number of the end. 109 unsigned EndColNo = CaretLine.size(); 110 if (EndLineNo == LineNo) { 111 EndColNo = SM.getInstantiationColumnNumber(End); 112 if (EndColNo) { 113 --EndColNo; // Zero base the col #. 114 115 // Add in the length of the token, so that we cover multi-char tokens. 116 EndColNo += Lexer::MeasureTokenLength(End, SM, *LangOpts); 117 } else { 118 EndColNo = CaretLine.size(); 119 } 120 } 121 122 assert(StartColNo <= EndColNo && "Invalid range!"); 123 124 // Pick the first non-whitespace column. 125 while (StartColNo < SourceLine.size() && 126 (SourceLine[StartColNo] == ' ' || SourceLine[StartColNo] == '\t')) 127 ++StartColNo; 128 129 // Pick the last non-whitespace column. 130 if (EndColNo > SourceLine.size()) 131 EndColNo = SourceLine.size(); 132 while (EndColNo-1 && 133 (SourceLine[EndColNo-1] == ' ' || SourceLine[EndColNo-1] == '\t')) 134 --EndColNo; 135 136 // If the start/end passed each other, then we are trying to highlight a range 137 // that just exists in whitespace, which must be some sort of other bug. 138 assert(StartColNo <= EndColNo && "Trying to highlight whitespace??"); 139 140 // Fill the range with ~'s. 141 for (unsigned i = StartColNo; i < EndColNo; ++i) 142 CaretLine[i] = '~'; 143} 144 145/// \brief When the source code line we want to print is too long for 146/// the terminal, select the "interesting" region. 147static void SelectInterestingSourceRegion(std::string &SourceLine, 148 std::string &CaretLine, 149 std::string &FixItInsertionLine, 150 unsigned EndOfCaretToken, 151 unsigned Columns) { 152 unsigned MaxSize = std::max(SourceLine.size(), 153 std::max(CaretLine.size(), 154 FixItInsertionLine.size())); 155 if (MaxSize > SourceLine.size()) 156 SourceLine.resize(MaxSize, ' '); 157 if (MaxSize > CaretLine.size()) 158 CaretLine.resize(MaxSize, ' '); 159 if (!FixItInsertionLine.empty() && MaxSize > FixItInsertionLine.size()) 160 FixItInsertionLine.resize(MaxSize, ' '); 161 162 // Find the slice that we need to display the full caret line 163 // correctly. 164 unsigned CaretStart = 0, CaretEnd = CaretLine.size(); 165 for (; CaretStart != CaretEnd; ++CaretStart) 166 if (!isspace(CaretLine[CaretStart])) 167 break; 168 169 for (; CaretEnd != CaretStart; --CaretEnd) 170 if (!isspace(CaretLine[CaretEnd - 1])) 171 break; 172 173 // Make sure we don't chop the string shorter than the caret token 174 // itself. 175 if (CaretEnd < EndOfCaretToken) 176 CaretEnd = EndOfCaretToken; 177 178 // If we have a fix-it line, make sure the slice includes all of the 179 // fix-it information. 180 if (!FixItInsertionLine.empty()) { 181 unsigned FixItStart = 0, FixItEnd = FixItInsertionLine.size(); 182 for (; FixItStart != FixItEnd; ++FixItStart) 183 if (!isspace(FixItInsertionLine[FixItStart])) 184 break; 185 186 for (; FixItEnd != FixItStart; --FixItEnd) 187 if (!isspace(FixItInsertionLine[FixItEnd - 1])) 188 break; 189 190 if (FixItStart < CaretStart) 191 CaretStart = FixItStart; 192 if (FixItEnd > CaretEnd) 193 CaretEnd = FixItEnd; 194 } 195 196 // CaretLine[CaretStart, CaretEnd) contains all of the interesting 197 // parts of the caret line. While this slice is smaller than the 198 // number of columns we have, try to grow the slice to encompass 199 // more context. 200 201 // If the end of the interesting region comes before we run out of 202 // space in the terminal, start at the beginning of the line. 203 if (Columns > 3 && CaretEnd < Columns - 3) 204 CaretStart = 0; 205 206 unsigned TargetColumns = Columns; 207 if (TargetColumns > 8) 208 TargetColumns -= 8; // Give us extra room for the ellipses. 209 unsigned SourceLength = SourceLine.size(); 210 while ((CaretEnd - CaretStart) < TargetColumns) { 211 bool ExpandedRegion = false; 212 // Move the start of the interesting region left until we've 213 // pulled in something else interesting. 214 if (CaretStart == 1) 215 CaretStart = 0; 216 else if (CaretStart > 1) { 217 unsigned NewStart = CaretStart - 1; 218 219 // Skip over any whitespace we see here; we're looking for 220 // another bit of interesting text. 221 while (NewStart && isspace(SourceLine[NewStart])) 222 --NewStart; 223 224 // Skip over this bit of "interesting" text. 225 while (NewStart && !isspace(SourceLine[NewStart])) 226 --NewStart; 227 228 // Move up to the non-whitespace character we just saw. 229 if (NewStart) 230 ++NewStart; 231 232 // If we're still within our limit, update the starting 233 // position within the source/caret line. 234 if (CaretEnd - NewStart <= TargetColumns) { 235 CaretStart = NewStart; 236 ExpandedRegion = true; 237 } 238 } 239 240 // Move the end of the interesting region right until we've 241 // pulled in something else interesting. 242 if (CaretEnd != SourceLength) { 243 assert(CaretEnd < SourceLength && "Unexpected caret position!"); 244 unsigned NewEnd = CaretEnd; 245 246 // Skip over any whitespace we see here; we're looking for 247 // another bit of interesting text. 248 while (NewEnd != SourceLength && isspace(SourceLine[NewEnd - 1])) 249 ++NewEnd; 250 251 // Skip over this bit of "interesting" text. 252 while (NewEnd != SourceLength && !isspace(SourceLine[NewEnd - 1])) 253 ++NewEnd; 254 255 if (NewEnd - CaretStart <= TargetColumns) { 256 CaretEnd = NewEnd; 257 ExpandedRegion = true; 258 } 259 } 260 261 if (!ExpandedRegion) 262 break; 263 } 264 265 // [CaretStart, CaretEnd) is the slice we want. Update the various 266 // output lines to show only this slice, with two-space padding 267 // before the lines so that it looks nicer. 268 if (CaretEnd < SourceLine.size()) 269 SourceLine.replace(CaretEnd, std::string::npos, "..."); 270 if (CaretEnd < CaretLine.size()) 271 CaretLine.erase(CaretEnd, std::string::npos); 272 if (FixItInsertionLine.size() > CaretEnd) 273 FixItInsertionLine.erase(CaretEnd, std::string::npos); 274 275 if (CaretStart > 2) { 276 SourceLine.replace(0, CaretStart, " ..."); 277 CaretLine.replace(0, CaretStart, " "); 278 if (FixItInsertionLine.size() >= CaretStart) 279 FixItInsertionLine.replace(0, CaretStart, " "); 280 } 281} 282 283void TextDiagnosticPrinter::EmitCaretDiagnostic(SourceLocation Loc, 284 SourceRange *Ranges, 285 unsigned NumRanges, 286 const SourceManager &SM, 287 const FixItHint *Hints, 288 unsigned NumHints, 289 unsigned Columns, 290 unsigned OnMacroInst, 291 unsigned MacroSkipStart, 292 unsigned MacroSkipEnd) { 293 assert(LangOpts && "Unexpected diagnostic outside source file processing"); 294 assert(!Loc.isInvalid() && "must have a valid source location here"); 295 296 // If this is a macro ID, first emit information about where this was 297 // instantiated (recursively) then emit information about where the token was 298 // spelled from. 299 if (!Loc.isFileID()) { 300 // Whether to suppress printing this macro instantiation. 301 bool Suppressed 302 = OnMacroInst >= MacroSkipStart && OnMacroInst < MacroSkipEnd; 303 304 305 SourceLocation OneLevelUp = SM.getImmediateInstantiationRange(Loc).first; 306 // FIXME: Map ranges? 307 EmitCaretDiagnostic(OneLevelUp, Ranges, NumRanges, SM, 0, 0, Columns, 308 OnMacroInst + 1, MacroSkipStart, MacroSkipEnd); 309 310 // Map the location. 311 Loc = SM.getImmediateSpellingLoc(Loc); 312 313 // Map the ranges. 314 for (unsigned i = 0; i != NumRanges; ++i) { 315 SourceLocation S = Ranges[i].getBegin(), E = Ranges[i].getEnd(); 316 if (S.isMacroID()) S = SM.getImmediateSpellingLoc(S); 317 if (E.isMacroID()) E = SM.getImmediateSpellingLoc(E); 318 Ranges[i] = SourceRange(S, E); 319 } 320 321 if (!Suppressed) { 322 // Get the pretty name, according to #line directives etc. 323 PresumedLoc PLoc = SM.getPresumedLoc(Loc); 324 325 // If this diagnostic is not in the main file, print out the 326 // "included from" lines. 327 if (LastWarningLoc != PLoc.getIncludeLoc()) { 328 LastWarningLoc = PLoc.getIncludeLoc(); 329 PrintIncludeStack(LastWarningLoc, SM); 330 } 331 332 if (DiagOpts->ShowLocation) { 333 // Emit the file/line/column that this expansion came from. 334 OS << PLoc.getFilename() << ':' << PLoc.getLine() << ':'; 335 if (DiagOpts->ShowColumn) 336 OS << PLoc.getColumn() << ':'; 337 OS << ' '; 338 } 339 OS << "note: instantiated from:\n"; 340 341 EmitCaretDiagnostic(Loc, Ranges, NumRanges, SM, Hints, NumHints, Columns, 342 OnMacroInst + 1, MacroSkipStart, MacroSkipEnd); 343 return; 344 } 345 346 if (OnMacroInst == MacroSkipStart) { 347 // Tell the user that we've skipped contexts. 348 OS << "note: (skipping " << (MacroSkipEnd - MacroSkipStart) 349 << " contexts in backtrace; use -fmacro-backtrace-limit=0 to see " 350 "all)\n"; 351 } 352 353 return; 354 } 355 356 // Decompose the location into a FID/Offset pair. 357 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); 358 FileID FID = LocInfo.first; 359 unsigned FileOffset = LocInfo.second; 360 361 // Get information about the buffer it points into. 362 bool Invalid = false; 363 const char *BufStart = SM.getBufferData(FID, &Invalid).data(); 364 if (Invalid) 365 return; 366 367 unsigned ColNo = SM.getColumnNumber(FID, FileOffset); 368 unsigned CaretEndColNo 369 = ColNo + Lexer::MeasureTokenLength(Loc, SM, *LangOpts); 370 371 // Rewind from the current position to the start of the line. 372 const char *TokPtr = BufStart+FileOffset; 373 const char *LineStart = TokPtr-ColNo+1; // Column # is 1-based. 374 375 376 // Compute the line end. Scan forward from the error position to the end of 377 // the line. 378 const char *LineEnd = TokPtr; 379 while (*LineEnd != '\n' && *LineEnd != '\r' && *LineEnd != '\0') 380 ++LineEnd; 381 382 // FIXME: This shouldn't be necessary, but the CaretEndColNo can extend past 383 // the source line length as currently being computed. See 384 // test/Misc/message-length.c. 385 CaretEndColNo = std::min(CaretEndColNo, unsigned(LineEnd - LineStart)); 386 387 // Copy the line of code into an std::string for ease of manipulation. 388 std::string SourceLine(LineStart, LineEnd); 389 390 // Create a line for the caret that is filled with spaces that is the same 391 // length as the line of source code. 392 std::string CaretLine(LineEnd-LineStart, ' '); 393 394 // Highlight all of the characters covered by Ranges with ~ characters. 395 if (NumRanges) { 396 unsigned LineNo = SM.getLineNumber(FID, FileOffset); 397 398 for (unsigned i = 0, e = NumRanges; i != e; ++i) 399 HighlightRange(Ranges[i], SM, LineNo, FID, CaretLine, SourceLine); 400 } 401 402 // Next, insert the caret itself. 403 if (ColNo-1 < CaretLine.size()) 404 CaretLine[ColNo-1] = '^'; 405 else 406 CaretLine.push_back('^'); 407 408 // Scan the source line, looking for tabs. If we find any, manually expand 409 // them to spaces and update the CaretLine to match. 410 for (unsigned i = 0; i != SourceLine.size(); ++i) { 411 if (SourceLine[i] != '\t') continue; 412 413 // Replace this tab with at least one space. 414 SourceLine[i] = ' '; 415 416 // Compute the number of spaces we need to insert. 417 unsigned TabStop = DiagOpts->TabStop; 418 assert(0 < TabStop && TabStop <= DiagnosticOptions::MaxTabStop && 419 "Invalid -ftabstop value"); 420 unsigned NumSpaces = ((i+TabStop)/TabStop * TabStop) - (i+1); 421 assert(NumSpaces < TabStop && "Invalid computation of space amt"); 422 423 // Insert spaces into the SourceLine. 424 SourceLine.insert(i+1, NumSpaces, ' '); 425 426 // Insert spaces or ~'s into CaretLine. 427 CaretLine.insert(i+1, NumSpaces, CaretLine[i] == '~' ? '~' : ' '); 428 } 429 430 // If we are in -fdiagnostics-print-source-range-info mode, we are trying to 431 // produce easily machine parsable output. Add a space before the source line 432 // and the caret to make it trivial to tell the main diagnostic line from what 433 // the user is intended to see. 434 if (DiagOpts->ShowSourceRanges) { 435 SourceLine = ' ' + SourceLine; 436 CaretLine = ' ' + CaretLine; 437 } 438 439 std::string FixItInsertionLine; 440 if (NumHints && DiagOpts->ShowFixits) { 441 for (const FixItHint *Hint = Hints, *LastHint = Hints + NumHints; 442 Hint != LastHint; ++Hint) { 443 if (Hint->InsertionLoc.isValid()) { 444 // We have an insertion hint. Determine whether the inserted 445 // code is on the same line as the caret. 446 std::pair<FileID, unsigned> HintLocInfo 447 = SM.getDecomposedInstantiationLoc(Hint->InsertionLoc); 448 if (SM.getLineNumber(HintLocInfo.first, HintLocInfo.second) == 449 SM.getLineNumber(FID, FileOffset)) { 450 // Insert the new code into the line just below the code 451 // that the user wrote. 452 unsigned HintColNo 453 = SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second); 454 unsigned LastColumnModified 455 = HintColNo - 1 + Hint->CodeToInsert.size(); 456 if (LastColumnModified > FixItInsertionLine.size()) 457 FixItInsertionLine.resize(LastColumnModified, ' '); 458 std::copy(Hint->CodeToInsert.begin(), Hint->CodeToInsert.end(), 459 FixItInsertionLine.begin() + HintColNo - 1); 460 } else { 461 FixItInsertionLine.clear(); 462 break; 463 } 464 } 465 } 466 // Now that we have the entire fixit line, expand the tabs in it. 467 // Since we don't want to insert spaces in the middle of a word, 468 // find each word and the column it should line up with and insert 469 // spaces until they match. 470 if (!FixItInsertionLine.empty()) { 471 unsigned FixItPos = 0; 472 unsigned LinePos = 0; 473 unsigned TabExpandedCol = 0; 474 unsigned LineLength = LineEnd - LineStart; 475 476 while (FixItPos < FixItInsertionLine.size() && LinePos < LineLength) { 477 // Find the next word in the FixIt line. 478 while (FixItPos < FixItInsertionLine.size() && 479 FixItInsertionLine[FixItPos] == ' ') 480 ++FixItPos; 481 unsigned CharDistance = FixItPos - TabExpandedCol; 482 483 // Walk forward in the source line, keeping track of 484 // the tab-expanded column. 485 for (unsigned I = 0; I < CharDistance; ++I, ++LinePos) 486 if (LinePos >= LineLength || LineStart[LinePos] != '\t') 487 ++TabExpandedCol; 488 else 489 TabExpandedCol = 490 (TabExpandedCol/DiagOpts->TabStop + 1) * DiagOpts->TabStop; 491 492 // Adjust the fixit line to match this column. 493 FixItInsertionLine.insert(FixItPos, TabExpandedCol-FixItPos, ' '); 494 FixItPos = TabExpandedCol; 495 496 // Walk to the end of the word. 497 while (FixItPos < FixItInsertionLine.size() && 498 FixItInsertionLine[FixItPos] != ' ') 499 ++FixItPos; 500 } 501 } 502 } 503 504 // If the source line is too long for our terminal, select only the 505 // "interesting" source region within that line. 506 if (Columns && SourceLine.size() > Columns) 507 SelectInterestingSourceRegion(SourceLine, CaretLine, FixItInsertionLine, 508 CaretEndColNo, Columns); 509 510 // Finally, remove any blank spaces from the end of CaretLine. 511 while (CaretLine[CaretLine.size()-1] == ' ') 512 CaretLine.erase(CaretLine.end()-1); 513 514 // Emit what we have computed. 515 OS << SourceLine << '\n'; 516 517 if (DiagOpts->ShowColors) 518 OS.changeColor(caretColor, true); 519 OS << CaretLine << '\n'; 520 if (DiagOpts->ShowColors) 521 OS.resetColor(); 522 523 if (!FixItInsertionLine.empty()) { 524 if (DiagOpts->ShowColors) 525 // Print fixit line in color 526 OS.changeColor(fixitColor, false); 527 if (DiagOpts->ShowSourceRanges) 528 OS << ' '; 529 OS << FixItInsertionLine << '\n'; 530 if (DiagOpts->ShowColors) 531 OS.resetColor(); 532 } 533} 534 535/// \brief Skip over whitespace in the string, starting at the given 536/// index. 537/// 538/// \returns The index of the first non-whitespace character that is 539/// greater than or equal to Idx or, if no such character exists, 540/// returns the end of the string. 541static unsigned skipWhitespace(unsigned Idx, 542 const llvm::SmallVectorImpl<char> &Str, 543 unsigned Length) { 544 while (Idx < Length && isspace(Str[Idx])) 545 ++Idx; 546 return Idx; 547} 548 549/// \brief If the given character is the start of some kind of 550/// balanced punctuation (e.g., quotes or parentheses), return the 551/// character that will terminate the punctuation. 552/// 553/// \returns The ending punctuation character, if any, or the NULL 554/// character if the input character does not start any punctuation. 555static inline char findMatchingPunctuation(char c) { 556 switch (c) { 557 case '\'': return '\''; 558 case '`': return '\''; 559 case '"': return '"'; 560 case '(': return ')'; 561 case '[': return ']'; 562 case '{': return '}'; 563 default: break; 564 } 565 566 return 0; 567} 568 569/// \brief Find the end of the word starting at the given offset 570/// within a string. 571/// 572/// \returns the index pointing one character past the end of the 573/// word. 574static unsigned findEndOfWord(unsigned Start, 575 const llvm::SmallVectorImpl<char> &Str, 576 unsigned Length, unsigned Column, 577 unsigned Columns) { 578 assert(Start < Str.size() && "Invalid start position!"); 579 unsigned End = Start + 1; 580 581 // If we are already at the end of the string, take that as the word. 582 if (End == Str.size()) 583 return End; 584 585 // Determine if the start of the string is actually opening 586 // punctuation, e.g., a quote or parentheses. 587 char EndPunct = findMatchingPunctuation(Str[Start]); 588 if (!EndPunct) { 589 // This is a normal word. Just find the first space character. 590 while (End < Length && !isspace(Str[End])) 591 ++End; 592 return End; 593 } 594 595 // We have the start of a balanced punctuation sequence (quotes, 596 // parentheses, etc.). Determine the full sequence is. 597 llvm::SmallString<16> PunctuationEndStack; 598 PunctuationEndStack.push_back(EndPunct); 599 while (End < Length && !PunctuationEndStack.empty()) { 600 if (Str[End] == PunctuationEndStack.back()) 601 PunctuationEndStack.pop_back(); 602 else if (char SubEndPunct = findMatchingPunctuation(Str[End])) 603 PunctuationEndStack.push_back(SubEndPunct); 604 605 ++End; 606 } 607 608 // Find the first space character after the punctuation ended. 609 while (End < Length && !isspace(Str[End])) 610 ++End; 611 612 unsigned PunctWordLength = End - Start; 613 if (// If the word fits on this line 614 Column + PunctWordLength <= Columns || 615 // ... or the word is "short enough" to take up the next line 616 // without too much ugly white space 617 PunctWordLength < Columns/3) 618 return End; // Take the whole thing as a single "word". 619 620 // The whole quoted/parenthesized string is too long to print as a 621 // single "word". Instead, find the "word" that starts just after 622 // the punctuation and use that end-point instead. This will recurse 623 // until it finds something small enough to consider a word. 624 return findEndOfWord(Start + 1, Str, Length, Column + 1, Columns); 625} 626 627/// \brief Print the given string to a stream, word-wrapping it to 628/// some number of columns in the process. 629/// 630/// \brief OS the stream to which the word-wrapping string will be 631/// emitted. 632/// 633/// \brief Str the string to word-wrap and output. 634/// 635/// \brief Columns the number of columns to word-wrap to. 636/// 637/// \brief Column the column number at which the first character of \p 638/// Str will be printed. This will be non-zero when part of the first 639/// line has already been printed. 640/// 641/// \brief Indentation the number of spaces to indent any lines beyond 642/// the first line. 643/// 644/// \returns true if word-wrapping was required, or false if the 645/// string fit on the first line. 646static bool PrintWordWrapped(llvm::raw_ostream &OS, 647 const llvm::SmallVectorImpl<char> &Str, 648 unsigned Columns, 649 unsigned Column = 0, 650 unsigned Indentation = WordWrapIndentation) { 651 unsigned Length = Str.size(); 652 653 // If there is a newline in this message somewhere, find that 654 // newline and split the message into the part before the newline 655 // (which will be word-wrapped) and the part from the newline one 656 // (which will be emitted unchanged). 657 for (unsigned I = 0; I != Length; ++I) 658 if (Str[I] == '\n') { 659 Length = I; 660 break; 661 } 662 663 // The string used to indent each line. 664 llvm::SmallString<16> IndentStr; 665 IndentStr.assign(Indentation, ' '); 666 bool Wrapped = false; 667 for (unsigned WordStart = 0, WordEnd; WordStart < Length; 668 WordStart = WordEnd) { 669 // Find the beginning of the next word. 670 WordStart = skipWhitespace(WordStart, Str, Length); 671 if (WordStart == Length) 672 break; 673 674 // Find the end of this word. 675 WordEnd = findEndOfWord(WordStart, Str, Length, Column, Columns); 676 677 // Does this word fit on the current line? 678 unsigned WordLength = WordEnd - WordStart; 679 if (Column + WordLength < Columns) { 680 // This word fits on the current line; print it there. 681 if (WordStart) { 682 OS << ' '; 683 Column += 1; 684 } 685 OS.write(&Str[WordStart], WordLength); 686 Column += WordLength; 687 continue; 688 } 689 690 // This word does not fit on the current line, so wrap to the next 691 // line. 692 OS << '\n'; 693 OS.write(&IndentStr[0], Indentation); 694 OS.write(&Str[WordStart], WordLength); 695 Column = Indentation + WordLength; 696 Wrapped = true; 697 } 698 699 if (Length == Str.size()) 700 return Wrapped; // We're done. 701 702 // There is a newline in the message, followed by something that 703 // will not be word-wrapped. Print that. 704 OS.write(&Str[Length], Str.size() - Length); 705 return true; 706} 707 708void TextDiagnosticPrinter::HandleDiagnostic(Diagnostic::Level Level, 709 const DiagnosticInfo &Info) { 710 // Keeps track of the the starting position of the location 711 // information (e.g., "foo.c:10:4:") that precedes the error 712 // message. We use this information to determine how long the 713 // file+line+column number prefix is. 714 uint64_t StartOfLocationInfo = OS.tell(); 715 716 if (!Prefix.empty()) 717 OS << Prefix << ": "; 718 719 // If the location is specified, print out a file/line/col and include trace 720 // if enabled. 721 if (Info.getLocation().isValid()) { 722 const SourceManager &SM = Info.getLocation().getManager(); 723 PresumedLoc PLoc = SM.getPresumedLoc(Info.getLocation()); 724 unsigned LineNo = PLoc.getLine(); 725 726 // First, if this diagnostic is not in the main file, print out the 727 // "included from" lines. 728 if (LastWarningLoc != PLoc.getIncludeLoc()) { 729 LastWarningLoc = PLoc.getIncludeLoc(); 730 PrintIncludeStack(LastWarningLoc, SM); 731 StartOfLocationInfo = OS.tell(); 732 } 733 734 // Compute the column number. 735 if (DiagOpts->ShowLocation) { 736 if (DiagOpts->ShowColors) 737 OS.changeColor(savedColor, true); 738 739 // Emit a Visual Studio compatible line number syntax. 740 if (LangOpts && LangOpts->Microsoft) { 741 OS << PLoc.getFilename() << '(' << LineNo << ')'; 742 OS << " : "; 743 } else { 744 OS << PLoc.getFilename() << ':' << LineNo << ':'; 745 if (DiagOpts->ShowColumn) 746 if (unsigned ColNo = PLoc.getColumn()) 747 OS << ColNo << ':'; 748 } 749 if (DiagOpts->ShowSourceRanges && Info.getNumRanges()) { 750 FileID CaretFileID = 751 SM.getFileID(SM.getInstantiationLoc(Info.getLocation())); 752 bool PrintedRange = false; 753 754 for (unsigned i = 0, e = Info.getNumRanges(); i != e; ++i) { 755 // Ignore invalid ranges. 756 if (!Info.getRange(i).isValid()) continue; 757 758 SourceLocation B = Info.getRange(i).getBegin(); 759 SourceLocation E = Info.getRange(i).getEnd(); 760 B = SM.getInstantiationLoc(B); 761 E = SM.getInstantiationLoc(E); 762 763 // If the End location and the start location are the same and are a 764 // macro location, then the range was something that came from a macro 765 // expansion or _Pragma. If this is an object-like macro, the best we 766 // can do is to highlight the range. If this is a function-like 767 // macro, we'd also like to highlight the arguments. 768 if (B == E && Info.getRange(i).getEnd().isMacroID()) 769 E = SM.getInstantiationRange(Info.getRange(i).getEnd()).second; 770 771 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(B); 772 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E); 773 774 // If the start or end of the range is in another file, just discard 775 // it. 776 if (BInfo.first != CaretFileID || EInfo.first != CaretFileID) 777 continue; 778 779 // Add in the length of the token, so that we cover multi-char tokens. 780 unsigned TokSize = Lexer::MeasureTokenLength(E, SM, *LangOpts); 781 782 OS << '{' << SM.getLineNumber(BInfo.first, BInfo.second) << ':' 783 << SM.getColumnNumber(BInfo.first, BInfo.second) << '-' 784 << SM.getLineNumber(EInfo.first, EInfo.second) << ':' 785 << (SM.getColumnNumber(EInfo.first, EInfo.second)+TokSize) << '}'; 786 PrintedRange = true; 787 } 788 789 if (PrintedRange) 790 OS << ':'; 791 } 792 OS << ' '; 793 if (DiagOpts->ShowColors) 794 OS.resetColor(); 795 } 796 } 797 798 if (DiagOpts->ShowColors) { 799 // Print diagnostic category in bold and color 800 switch (Level) { 801 case Diagnostic::Ignored: assert(0 && "Invalid diagnostic type"); 802 case Diagnostic::Note: OS.changeColor(noteColor, true); break; 803 case Diagnostic::Warning: OS.changeColor(warningColor, true); break; 804 case Diagnostic::Error: OS.changeColor(errorColor, true); break; 805 case Diagnostic::Fatal: OS.changeColor(fatalColor, true); break; 806 } 807 } 808 809 switch (Level) { 810 case Diagnostic::Ignored: assert(0 && "Invalid diagnostic type"); 811 case Diagnostic::Note: OS << "note: "; break; 812 case Diagnostic::Warning: OS << "warning: "; break; 813 case Diagnostic::Error: OS << "error: "; break; 814 case Diagnostic::Fatal: OS << "fatal error: "; break; 815 } 816 817 if (DiagOpts->ShowColors) 818 OS.resetColor(); 819 820 llvm::SmallString<100> OutStr; 821 Info.FormatDiagnostic(OutStr); 822
|