TextDiagnosticPrinter.cpp revision b9c398b25b9c24769fb30b90c3805a500806e06f
1//===--- TextDiagnosticPrinter.cpp - Diagnostic Printer -------------------===// 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// This diagnostic client prints out their diagnostic messages. 11// 12//===----------------------------------------------------------------------===// 13 14#include "clang/Frontend/TextDiagnosticPrinter.h" 15#include "clang/Basic/FileManager.h" 16#include "clang/Basic/SourceManager.h" 17#include "clang/Frontend/DiagnosticOptions.h" 18#include "clang/Lex/Lexer.h" 19#include "llvm/Support/MemoryBuffer.h" 20#include "llvm/Support/raw_ostream.h" 21#include "llvm/Support/ErrorHandling.h" 22#include "llvm/ADT/SmallString.h" 23#include "llvm/ADT/StringExtras.h" 24#include <algorithm> 25using namespace clang; 26 27static const enum raw_ostream::Colors noteColor = 28 raw_ostream::BLACK; 29static const enum raw_ostream::Colors fixitColor = 30 raw_ostream::GREEN; 31static const enum raw_ostream::Colors caretColor = 32 raw_ostream::GREEN; 33static const enum raw_ostream::Colors warningColor = 34 raw_ostream::MAGENTA; 35static const enum raw_ostream::Colors errorColor = raw_ostream::RED; 36static const enum raw_ostream::Colors fatalColor = raw_ostream::RED; 37// Used for changing only the bold attribute. 38static const enum raw_ostream::Colors savedColor = 39 raw_ostream::SAVEDCOLOR; 40 41/// \brief Number of spaces to indent when word-wrapping. 42const unsigned WordWrapIndentation = 6; 43 44TextDiagnosticPrinter::TextDiagnosticPrinter(raw_ostream &os, 45 const DiagnosticOptions &diags, 46 bool _OwnsOutputStream) 47 : OS(os), LangOpts(0), DiagOpts(&diags), 48 LastCaretDiagnosticWasNote(0), 49 OwnsOutputStream(_OwnsOutputStream) { 50} 51 52TextDiagnosticPrinter::~TextDiagnosticPrinter() { 53 if (OwnsOutputStream) 54 delete &OS; 55} 56 57/// \brief Helper to recursivly walk up the include stack and print each layer 58/// on the way back down. 59static void PrintIncludeStackRecursively(raw_ostream &OS, 60 const SourceManager &SM, 61 SourceLocation Loc, 62 bool ShowLocation) { 63 if (Loc.isInvalid()) 64 return; 65 66 PresumedLoc PLoc = SM.getPresumedLoc(Loc); 67 if (PLoc.isInvalid()) 68 return; 69 70 // Print out the other include frames first. 71 PrintIncludeStackRecursively(OS, SM, PLoc.getIncludeLoc(), ShowLocation); 72 73 if (ShowLocation) 74 OS << "In file included from " << PLoc.getFilename() 75 << ':' << PLoc.getLine() << ":\n"; 76 else 77 OS << "In included file:\n"; 78} 79 80/// \brief Prints an include stack when appropriate for a particular diagnostic 81/// level and location. 82/// 83/// This routine handles all the logic of suppressing particular include stacks 84/// (such as those for notes) and duplicate include stacks when repeated 85/// warnings occur within the same file. It also handles the logic of 86/// customizing the formatting and display of the include stack. 87/// 88/// \param Level The diagnostic level of the message this stack pertains to. 89/// \param Loc The include location of the current file (not the diagnostic 90/// location). 91void TextDiagnosticPrinter::PrintIncludeStack(Diagnostic::Level Level, 92 SourceLocation Loc, 93 const SourceManager &SM) { 94 // Skip redundant include stacks altogether. 95 if (LastWarningLoc == Loc) 96 return; 97 LastWarningLoc = Loc; 98 99 if (!DiagOpts->ShowNoteIncludeStack && Level == Diagnostic::Note) 100 return; 101 102 PrintIncludeStackRecursively(OS, SM, Loc, DiagOpts->ShowLocation); 103} 104 105/// \brief When the source code line we want to print is too long for 106/// the terminal, select the "interesting" region. 107static void SelectInterestingSourceRegion(std::string &SourceLine, 108 std::string &CaretLine, 109 std::string &FixItInsertionLine, 110 unsigned EndOfCaretToken, 111 unsigned Columns) { 112 unsigned MaxSize = std::max(SourceLine.size(), 113 std::max(CaretLine.size(), 114 FixItInsertionLine.size())); 115 if (MaxSize > SourceLine.size()) 116 SourceLine.resize(MaxSize, ' '); 117 if (MaxSize > CaretLine.size()) 118 CaretLine.resize(MaxSize, ' '); 119 if (!FixItInsertionLine.empty() && MaxSize > FixItInsertionLine.size()) 120 FixItInsertionLine.resize(MaxSize, ' '); 121 122 // Find the slice that we need to display the full caret line 123 // correctly. 124 unsigned CaretStart = 0, CaretEnd = CaretLine.size(); 125 for (; CaretStart != CaretEnd; ++CaretStart) 126 if (!isspace(CaretLine[CaretStart])) 127 break; 128 129 for (; CaretEnd != CaretStart; --CaretEnd) 130 if (!isspace(CaretLine[CaretEnd - 1])) 131 break; 132 133 // Make sure we don't chop the string shorter than the caret token 134 // itself. 135 if (CaretEnd < EndOfCaretToken) 136 CaretEnd = EndOfCaretToken; 137 138 // If we have a fix-it line, make sure the slice includes all of the 139 // fix-it information. 140 if (!FixItInsertionLine.empty()) { 141 unsigned FixItStart = 0, FixItEnd = FixItInsertionLine.size(); 142 for (; FixItStart != FixItEnd; ++FixItStart) 143 if (!isspace(FixItInsertionLine[FixItStart])) 144 break; 145 146 for (; FixItEnd != FixItStart; --FixItEnd) 147 if (!isspace(FixItInsertionLine[FixItEnd - 1])) 148 break; 149 150 if (FixItStart < CaretStart) 151 CaretStart = FixItStart; 152 if (FixItEnd > CaretEnd) 153 CaretEnd = FixItEnd; 154 } 155 156 // CaretLine[CaretStart, CaretEnd) contains all of the interesting 157 // parts of the caret line. While this slice is smaller than the 158 // number of columns we have, try to grow the slice to encompass 159 // more context. 160 161 // If the end of the interesting region comes before we run out of 162 // space in the terminal, start at the beginning of the line. 163 if (Columns > 3 && CaretEnd < Columns - 3) 164 CaretStart = 0; 165 166 unsigned TargetColumns = Columns; 167 if (TargetColumns > 8) 168 TargetColumns -= 8; // Give us extra room for the ellipses. 169 unsigned SourceLength = SourceLine.size(); 170 while ((CaretEnd - CaretStart) < TargetColumns) { 171 bool ExpandedRegion = false; 172 // Move the start of the interesting region left until we've 173 // pulled in something else interesting. 174 if (CaretStart == 1) 175 CaretStart = 0; 176 else if (CaretStart > 1) { 177 unsigned NewStart = CaretStart - 1; 178 179 // Skip over any whitespace we see here; we're looking for 180 // another bit of interesting text. 181 while (NewStart && isspace(SourceLine[NewStart])) 182 --NewStart; 183 184 // Skip over this bit of "interesting" text. 185 while (NewStart && !isspace(SourceLine[NewStart])) 186 --NewStart; 187 188 // Move up to the non-whitespace character we just saw. 189 if (NewStart) 190 ++NewStart; 191 192 // If we're still within our limit, update the starting 193 // position within the source/caret line. 194 if (CaretEnd - NewStart <= TargetColumns) { 195 CaretStart = NewStart; 196 ExpandedRegion = true; 197 } 198 } 199 200 // Move the end of the interesting region right until we've 201 // pulled in something else interesting. 202 if (CaretEnd != SourceLength) { 203 assert(CaretEnd < SourceLength && "Unexpected caret position!"); 204 unsigned NewEnd = CaretEnd; 205 206 // Skip over any whitespace we see here; we're looking for 207 // another bit of interesting text. 208 while (NewEnd != SourceLength && isspace(SourceLine[NewEnd - 1])) 209 ++NewEnd; 210 211 // Skip over this bit of "interesting" text. 212 while (NewEnd != SourceLength && !isspace(SourceLine[NewEnd - 1])) 213 ++NewEnd; 214 215 if (NewEnd - CaretStart <= TargetColumns) { 216 CaretEnd = NewEnd; 217 ExpandedRegion = true; 218 } 219 } 220 221 if (!ExpandedRegion) 222 break; 223 } 224 225 // [CaretStart, CaretEnd) is the slice we want. Update the various 226 // output lines to show only this slice, with two-space padding 227 // before the lines so that it looks nicer. 228 if (CaretEnd < SourceLine.size()) 229 SourceLine.replace(CaretEnd, std::string::npos, "..."); 230 if (CaretEnd < CaretLine.size()) 231 CaretLine.erase(CaretEnd, std::string::npos); 232 if (FixItInsertionLine.size() > CaretEnd) 233 FixItInsertionLine.erase(CaretEnd, std::string::npos); 234 235 if (CaretStart > 2) { 236 SourceLine.replace(0, CaretStart, " ..."); 237 CaretLine.replace(0, CaretStart, " "); 238 if (FixItInsertionLine.size() >= CaretStart) 239 FixItInsertionLine.replace(0, CaretStart, " "); 240 } 241} 242 243/// Look through spelling locations for a macro argument expansion, and 244/// if found skip to it so that we can trace the argument rather than the macros 245/// in which that argument is used. If no macro argument expansion is found, 246/// don't skip anything and return the starting location. 247static SourceLocation skipToMacroArgExpansion(const SourceManager &SM, 248 SourceLocation StartLoc) { 249 for (SourceLocation L = StartLoc; L.isMacroID(); 250 L = SM.getImmediateSpellingLoc(L)) { 251 if (SM.isMacroArgExpansion(L)) 252 return L; 253 } 254 255 // Otherwise just return initial location, there's nothing to skip. 256 return StartLoc; 257} 258 259/// Gets the location of the immediate macro caller, one level up the stack 260/// toward the initial macro typed into the source. 261static SourceLocation getImmediateMacroCallerLoc(const SourceManager &SM, 262 SourceLocation Loc) { 263 if (!Loc.isMacroID()) return Loc; 264 265 // When we have the location of (part of) an expanded parameter, its spelling 266 // location points to the argument as typed into the macro call, and 267 // therefore is used to locate the macro caller. 268 if (SM.isMacroArgExpansion(Loc)) 269 return SM.getImmediateSpellingLoc(Loc); 270 271 // Otherwise, the caller of the macro is located where this macro is 272 // expanded (while the spelling is part of the macro definition). 273 return SM.getImmediateExpansionRange(Loc).first; 274} 275 276/// Gets the location of the immediate macro callee, one level down the stack 277/// toward the leaf macro. 278static SourceLocation getImmediateMacroCalleeLoc(const SourceManager &SM, 279 SourceLocation Loc) { 280 if (!Loc.isMacroID()) return Loc; 281 282 // When we have the location of (part of) an expanded parameter, its 283 // expansion location points to the unexpanded paramater reference within 284 // the macro definition (or callee). 285 if (SM.isMacroArgExpansion(Loc)) 286 return SM.getImmediateExpansionRange(Loc).first; 287 288 // Otherwise, the callee of the macro is located where this location was 289 // spelled inside the macro definition. 290 return SM.getImmediateSpellingLoc(Loc); 291} 292 293namespace { 294 295/// \brief Class to encapsulate the logic for printing a caret diagnostic 296/// message. 297/// 298/// This class provides an interface for building and emitting a caret 299/// diagnostic, including all of the macro backtrace caret diagnostics, FixIt 300/// Hints, and code snippets. In the presence of macros this turns into 301/// a recursive process and so the class provides common state across the 302/// emission of a particular diagnostic, while each invocation of \see Emit() 303/// walks down the macro stack. 304/// 305/// This logic assumes that the core diagnostic location and text has already 306/// been emitted and focuses on emitting the pretty caret display and macro 307/// backtrace following that. 308/// 309/// FIXME: Hoist helper routines specific to caret diagnostics into class 310/// methods to reduce paramater passing churn. 311class CaretDiagnostic { 312 TextDiagnosticPrinter &Printer; 313 raw_ostream &OS; 314 const SourceManager &SM; 315 const LangOptions &LangOpts; 316 const DiagnosticOptions &DiagOpts; 317 const unsigned Columns, MacroSkipStart, MacroSkipEnd; 318 319public: 320 CaretDiagnostic(TextDiagnosticPrinter &Printer, 321 raw_ostream &OS, 322 const SourceManager &SM, 323 const LangOptions &LangOpts, 324 const DiagnosticOptions &DiagOpts, 325 unsigned Columns) 326 : Printer(Printer), OS(OS), SM(SM), LangOpts(LangOpts), DiagOpts(DiagOpts), 327 Columns(Columns), MacroSkipStart(0), MacroSkipEnd(0) { 328 } 329 330 /// \brief Emit the caret diagnostic text. 331 /// 332 /// Walks up the macro expansion stack printing the code snippet, caret, 333 /// underlines and FixItHint display as appropriate at each level. Walk is 334 /// accomplished by calling itself recursively. 335 /// 336 /// FIXME: Break up massive function into logical units. 337 /// 338 /// \param Loc The location for this caret. 339 /// \param Ranges The underlined ranges for this code snippet. 340 /// \param Hints The FixIt hints active for this diagnostic. 341 /// \param MacroSkipEnd The depth to stop skipping macro expansions. 342 /// \param OnMacroInst The current depth of the macro expansion stack. 343 void Emit(SourceLocation Loc, 344 SmallVectorImpl<CharSourceRange>& Ranges, 345 ArrayRef<FixItHint> Hints, 346 unsigned &MacroDepth, 347 unsigned OnMacroInst = 0) { 348 assert(!Loc.isInvalid() && "must have a valid source location here"); 349 350 // If this is a file source location, directly emit the source snippet and 351 // caret line. Also record the macro depth reached. 352 if (Loc.isFileID()) { 353 assert(MacroDepth == 0 && "We shouldn't hit a leaf node twice!"); 354 MacroDepth = OnMacroInst; 355 EmitSnippetAndCaret(Loc, Ranges, Hints); 356 return; 357 } 358 // Otherwise recurse through each macro expansion layer. 359 360 // When processing macros, skip over the expansions leading up to 361 // a macro argument, and trace the argument's expansion stack instead. 362 Loc = skipToMacroArgExpansion(SM, Loc); 363 364 SourceLocation OneLevelUp = getImmediateMacroCallerLoc(SM, Loc); 365 366 // FIXME: Map ranges? 367 Emit(OneLevelUp, Ranges, Hints, MacroDepth, OnMacroInst + 1); 368 369 // Map the location. 370 Loc = getImmediateMacroCalleeLoc(SM, Loc); 371 372 unsigned MacroSkipStart = 0, MacroSkipEnd = 0; 373 if (MacroDepth > DiagOpts.MacroBacktraceLimit) { 374 MacroSkipStart = DiagOpts.MacroBacktraceLimit / 2 + 375 DiagOpts.MacroBacktraceLimit % 2; 376 MacroSkipEnd = MacroDepth - DiagOpts.MacroBacktraceLimit / 2; 377 } 378 379 // Whether to suppress printing this macro expansion. 380 bool Suppressed = (OnMacroInst >= MacroSkipStart && 381 OnMacroInst < MacroSkipEnd); 382 383 // Map the ranges. 384 for (SmallVectorImpl<CharSourceRange>::iterator I = Ranges.begin(), 385 E = Ranges.end(); 386 I != E; ++I) { 387 SourceLocation Start = I->getBegin(), End = I->getEnd(); 388 if (Start.isMacroID()) 389 I->setBegin(getImmediateMacroCalleeLoc(SM, Start)); 390 if (End.isMacroID()) 391 I->setEnd(getImmediateMacroCalleeLoc(SM, End)); 392 } 393 394 if (!Suppressed) { 395 // Don't print recursive expansion notes from an expansion note. 396 Loc = SM.getSpellingLoc(Loc); 397 398 // Get the pretty name, according to #line directives etc. 399 PresumedLoc PLoc = SM.getPresumedLoc(Loc); 400 if (PLoc.isInvalid()) 401 return; 402 403 // If this diagnostic is not in the main file, print out the 404 // "included from" lines. 405 Printer.PrintIncludeStack(Diagnostic::Note, PLoc.getIncludeLoc(), SM); 406 407 if (DiagOpts.ShowLocation) { 408 // Emit the file/line/column that this expansion came from. 409 OS << PLoc.getFilename() << ':' << PLoc.getLine() << ':'; 410 if (DiagOpts.ShowColumn) 411 OS << PLoc.getColumn() << ':'; 412 OS << ' '; 413 } 414 OS << "note: expanded from:\n"; 415 416 EmitSnippetAndCaret(Loc, Ranges, ArrayRef<FixItHint>()); 417 return; 418 } 419 420 if (OnMacroInst == MacroSkipStart) { 421 // Tell the user that we've skipped contexts. 422 OS << "note: (skipping " << (MacroSkipEnd - MacroSkipStart) 423 << " expansions in backtrace; use -fmacro-backtrace-limit=0 to see " 424 "all)\n"; 425 } 426 } 427 428 /// \brief Emit a code snippet and caret line. 429 /// 430 /// This routine emits a single line's code snippet and caret line.. 431 /// 432 /// \param Loc The location for the caret. 433 /// \param Ranges The underlined ranges for this code snippet. 434 /// \param Hints The FixIt hints active for this diagnostic. 435 void EmitSnippetAndCaret(SourceLocation Loc, 436 SmallVectorImpl<CharSourceRange>& Ranges, 437 ArrayRef<FixItHint> Hints) { 438 assert(!Loc.isInvalid() && "must have a valid source location here"); 439 assert(Loc.isFileID() && "must have a file location here"); 440 441 // Decompose the location into a FID/Offset pair. 442 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); 443 FileID FID = LocInfo.first; 444 unsigned FileOffset = LocInfo.second; 445 446 // Get information about the buffer it points into. 447 bool Invalid = false; 448 const char *BufStart = SM.getBufferData(FID, &Invalid).data(); 449 if (Invalid) 450 return; 451 452 unsigned LineNo = SM.getLineNumber(FID, FileOffset); 453 unsigned ColNo = SM.getColumnNumber(FID, FileOffset); 454 unsigned CaretEndColNo 455 = ColNo + Lexer::MeasureTokenLength(Loc, SM, LangOpts); 456 457 // Rewind from the current position to the start of the line. 458 const char *TokPtr = BufStart+FileOffset; 459 const char *LineStart = TokPtr-ColNo+1; // Column # is 1-based. 460 461 462 // Compute the line end. Scan forward from the error position to the end of 463 // the line. 464 const char *LineEnd = TokPtr; 465 while (*LineEnd != '\n' && *LineEnd != '\r' && *LineEnd != '\0') 466 ++LineEnd; 467 468 // FIXME: This shouldn't be necessary, but the CaretEndColNo can extend past 469 // the source line length as currently being computed. See 470 // test/Misc/message-length.c. 471 CaretEndColNo = std::min(CaretEndColNo, unsigned(LineEnd - LineStart)); 472 473 // Copy the line of code into an std::string for ease of manipulation. 474 std::string SourceLine(LineStart, LineEnd); 475 476 // Create a line for the caret that is filled with spaces that is the same 477 // length as the line of source code. 478 std::string CaretLine(LineEnd-LineStart, ' '); 479 480 // Highlight all of the characters covered by Ranges with ~ characters. 481 for (SmallVectorImpl<CharSourceRange>::iterator I = Ranges.begin(), 482 E = Ranges.end(); 483 I != E; ++I) 484 HighlightRange(*I, LineNo, FID, SourceLine, CaretLine); 485 486 // Next, insert the caret itself. 487 if (ColNo-1 < CaretLine.size()) 488 CaretLine[ColNo-1] = '^'; 489 else 490 CaretLine.push_back('^'); 491 492 ExpandTabs(SourceLine, CaretLine); 493 494 // If we are in -fdiagnostics-print-source-range-info mode, we are trying 495 // to produce easily machine parsable output. Add a space before the 496 // source line and the caret to make it trivial to tell the main diagnostic 497 // line from what the user is intended to see. 498 if (DiagOpts.ShowSourceRanges) { 499 SourceLine = ' ' + SourceLine; 500 CaretLine = ' ' + CaretLine; 501 } 502 503 std::string FixItInsertionLine = BuildFixItInsertionLine(LineNo, 504 LineStart, LineEnd, 505 Hints); 506 507 // If the source line is too long for our terminal, select only the 508 // "interesting" source region within that line. 509 if (Columns && SourceLine.size() > Columns) 510 SelectInterestingSourceRegion(SourceLine, CaretLine, FixItInsertionLine, 511 CaretEndColNo, Columns); 512 513 // Finally, remove any blank spaces from the end of CaretLine. 514 while (CaretLine[CaretLine.size()-1] == ' ') 515 CaretLine.erase(CaretLine.end()-1); 516 517 // Emit what we have computed. 518 OS << SourceLine << '\n'; 519 520 if (DiagOpts.ShowColors) 521 OS.changeColor(caretColor, true); 522 OS << CaretLine << '\n'; 523 if (DiagOpts.ShowColors) 524 OS.resetColor(); 525 526 if (!FixItInsertionLine.empty()) { 527 if (DiagOpts.ShowColors) 528 // Print fixit line in color 529 OS.changeColor(fixitColor, false); 530 if (DiagOpts.ShowSourceRanges) 531 OS << ' '; 532 OS << FixItInsertionLine << '\n'; 533 if (DiagOpts.ShowColors) 534 OS.resetColor(); 535 } 536 537 // Print out any parseable fixit information requested by the options. 538 EmitParseableFixits(Hints); 539 } 540 541private: 542 /// \brief Highlight a SourceRange (with ~'s) for any characters on LineNo. 543 void HighlightRange(const CharSourceRange &R, 544 unsigned LineNo, FileID FID, 545 const std::string &SourceLine, 546 std::string &CaretLine) { 547 assert(CaretLine.size() == SourceLine.size() && 548 "Expect a correspondence between source and caret line!"); 549 if (!R.isValid()) return; 550 551 SourceLocation Begin = SM.getExpansionLoc(R.getBegin()); 552 SourceLocation End = SM.getExpansionLoc(R.getEnd()); 553 554 // If the End location and the start location are the same and are a macro 555 // location, then the range was something that came from a macro expansion 556 // or _Pragma. If this is an object-like macro, the best we can do is to 557 // highlight the range. If this is a function-like macro, we'd also like to 558 // highlight the arguments. 559 if (Begin == End && R.getEnd().isMacroID()) 560 End = SM.getExpansionRange(R.getEnd()).second; 561 562 unsigned StartLineNo = SM.getExpansionLineNumber(Begin); 563 if (StartLineNo > LineNo || SM.getFileID(Begin) != FID) 564 return; // No intersection. 565 566 unsigned EndLineNo = SM.getExpansionLineNumber(End); 567 if (EndLineNo < LineNo || SM.getFileID(End) != FID) 568 return; // No intersection. 569 570 // Compute the column number of the start. 571 unsigned StartColNo = 0; 572 if (StartLineNo == LineNo) { 573 StartColNo = SM.getExpansionColumnNumber(Begin); 574 if (StartColNo) --StartColNo; // Zero base the col #. 575 } 576 577 // Compute the column number of the end. 578 unsigned EndColNo = CaretLine.size(); 579 if (EndLineNo == LineNo) { 580 EndColNo = SM.getExpansionColumnNumber(End); 581 if (EndColNo) { 582 --EndColNo; // Zero base the col #. 583 584 // Add in the length of the token, so that we cover multi-char tokens if 585 // this is a token range. 586 if (R.isTokenRange()) 587 EndColNo += Lexer::MeasureTokenLength(End, SM, LangOpts); 588 } else { 589 EndColNo = CaretLine.size(); 590 } 591 } 592 593 assert(StartColNo <= EndColNo && "Invalid range!"); 594 595 // Check that a token range does not highlight only whitespace. 596 if (R.isTokenRange()) { 597 // Pick the first non-whitespace column. 598 while (StartColNo < SourceLine.size() && 599 (SourceLine[StartColNo] == ' ' || SourceLine[StartColNo] == '\t')) 600 ++StartColNo; 601 602 // Pick the last non-whitespace column. 603 if (EndColNo > SourceLine.size()) 604 EndColNo = SourceLine.size(); 605 while (EndColNo-1 && 606 (SourceLine[EndColNo-1] == ' ' || SourceLine[EndColNo-1] == '\t')) 607 --EndColNo; 608 609 // If the start/end passed each other, then we are trying to highlight a 610 // range that just exists in whitespace, which must be some sort of other 611 // bug. 612 assert(StartColNo <= EndColNo && "Trying to highlight whitespace??"); 613 } 614 615 // Fill the range with ~'s. 616 for (unsigned i = StartColNo; i < EndColNo; ++i) 617 CaretLine[i] = '~'; 618 } 619 620 std::string BuildFixItInsertionLine(unsigned LineNo, 621 const char *LineStart, 622 const char *LineEnd, 623 ArrayRef<FixItHint> Hints) { 624 std::string FixItInsertionLine; 625 if (Hints.empty() || !DiagOpts.ShowFixits) 626 return FixItInsertionLine; 627 628 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end(); 629 I != E; ++I) { 630 if (!I->CodeToInsert.empty()) { 631 // We have an insertion hint. Determine whether the inserted 632 // code is on the same line as the caret. 633 std::pair<FileID, unsigned> HintLocInfo 634 = SM.getDecomposedExpansionLoc(I->RemoveRange.getBegin()); 635 if (LineNo == SM.getLineNumber(HintLocInfo.first, HintLocInfo.second)) { 636 // Insert the new code into the line just below the code 637 // that the user wrote. 638 unsigned HintColNo 639 = SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second); 640 unsigned LastColumnModified 641 = HintColNo - 1 + I->CodeToInsert.size(); 642 if (LastColumnModified > FixItInsertionLine.size()) 643 FixItInsertionLine.resize(LastColumnModified, ' '); 644 std::copy(I->CodeToInsert.begin(), I->CodeToInsert.end(), 645 FixItInsertionLine.begin() + HintColNo - 1); 646 } else { 647 FixItInsertionLine.clear(); 648 break; 649 } 650 } 651 } 652 653 if (FixItInsertionLine.empty()) 654 return FixItInsertionLine; 655 656 // Now that we have the entire fixit line, expand the tabs in it. 657 // Since we don't want to insert spaces in the middle of a word, 658 // find each word and the column it should line up with and insert 659 // spaces until they match. 660 unsigned FixItPos = 0; 661 unsigned LinePos = 0; 662 unsigned TabExpandedCol = 0; 663 unsigned LineLength = LineEnd - LineStart; 664 665 while (FixItPos < FixItInsertionLine.size() && LinePos < LineLength) { 666 // Find the next word in the FixIt line. 667 while (FixItPos < FixItInsertionLine.size() && 668 FixItInsertionLine[FixItPos] == ' ') 669 ++FixItPos; 670 unsigned CharDistance = FixItPos - TabExpandedCol; 671 672 // Walk forward in the source line, keeping track of 673 // the tab-expanded column. 674 for (unsigned I = 0; I < CharDistance; ++I, ++LinePos) 675 if (LinePos >= LineLength || LineStart[LinePos] != '\t') 676 ++TabExpandedCol; 677 else 678 TabExpandedCol = 679 (TabExpandedCol/DiagOpts.TabStop + 1) * DiagOpts.TabStop; 680 681 // Adjust the fixit line to match this column. 682 FixItInsertionLine.insert(FixItPos, TabExpandedCol-FixItPos, ' '); 683 FixItPos = TabExpandedCol; 684 685 // Walk to the end of the word. 686 while (FixItPos < FixItInsertionLine.size() && 687 FixItInsertionLine[FixItPos] != ' ') 688 ++FixItPos; 689 } 690 691 return FixItInsertionLine; 692 } 693 694 void ExpandTabs(std::string &SourceLine, std::string &CaretLine) { 695 // Scan the source line, looking for tabs. If we find any, manually expand 696 // them to spaces and update the CaretLine to match. 697 for (unsigned i = 0; i != SourceLine.size(); ++i) { 698 if (SourceLine[i] != '\t') continue; 699 700 // Replace this tab with at least one space. 701 SourceLine[i] = ' '; 702 703 // Compute the number of spaces we need to insert. 704 unsigned TabStop = DiagOpts.TabStop; 705 assert(0 < TabStop && TabStop <= DiagnosticOptions::MaxTabStop && 706 "Invalid -ftabstop value"); 707 unsigned NumSpaces = ((i+TabStop)/TabStop * TabStop) - (i+1); 708 assert(NumSpaces < TabStop && "Invalid computation of space amt"); 709 710 // Insert spaces into the SourceLine. 711 SourceLine.insert(i+1, NumSpaces, ' '); 712 713 // Insert spaces or ~'s into CaretLine. 714 CaretLine.insert(i+1, NumSpaces, CaretLine[i] == '~' ? '~' : ' '); 715 } 716 } 717 718 void EmitParseableFixits(ArrayRef<FixItHint> Hints) { 719 if (!DiagOpts.ShowParseableFixits) 720 return; 721 722 // We follow FixItRewriter's example in not (yet) handling 723 // fix-its in macros. 724 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end(); 725 I != E; ++I) { 726 if (I->RemoveRange.isInvalid() || 727 I->RemoveRange.getBegin().isMacroID() || 728 I->RemoveRange.getEnd().isMacroID()) 729 return; 730 } 731 732 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end(); 733 I != E; ++I) { 734 SourceLocation BLoc = I->RemoveRange.getBegin(); 735 SourceLocation ELoc = I->RemoveRange.getEnd(); 736 737 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(BLoc); 738 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(ELoc); 739 740 // Adjust for token ranges. 741 if (I->RemoveRange.isTokenRange()) 742 EInfo.second += Lexer::MeasureTokenLength(ELoc, SM, LangOpts); 743 744 // We specifically do not do word-wrapping or tab-expansion here, 745 // because this is supposed to be easy to parse. 746 PresumedLoc PLoc = SM.getPresumedLoc(BLoc); 747 if (PLoc.isInvalid()) 748 break; 749 750 OS << "fix-it:\""; 751 OS.write_escaped(PLoc.getFilename()); 752 OS << "\":{" << SM.getLineNumber(BInfo.first, BInfo.second) 753 << ':' << SM.getColumnNumber(BInfo.first, BInfo.second) 754 << '-' << SM.getLineNumber(EInfo.first, EInfo.second) 755 << ':' << SM.getColumnNumber(EInfo.first, EInfo.second) 756 << "}:\""; 757 OS.write_escaped(I->CodeToInsert); 758 OS << "\"\n"; 759 } 760 } 761}; 762 763} // end namespace 764 765void TextDiagnosticPrinter::EmitCaretDiagnostic( 766 SourceLocation Loc, 767 SmallVectorImpl<CharSourceRange>& Ranges, 768 const SourceManager &SM, 769 ArrayRef<FixItHint> Hints, 770 unsigned Columns) { 771 assert(LangOpts && "Unexpected diagnostic outside source file processing"); 772 assert(DiagOpts && "Unexpected diagnostic without options set"); 773 774 // FIXME: Remove this method and have clients directly build and call Emit on 775 // the CaretDiagnostic object. 776 CaretDiagnostic CaretDiag(*this, OS, SM, *LangOpts, *DiagOpts, Columns); 777 unsigned MacroDepth = 0; 778 CaretDiag.Emit(Loc, Ranges, Hints, MacroDepth); 779} 780 781/// \brief Skip over whitespace in the string, starting at the given 782/// index. 783/// 784/// \returns The index of the first non-whitespace character that is 785/// greater than or equal to Idx or, if no such character exists, 786/// returns the end of the string. 787static unsigned skipWhitespace(unsigned Idx, 788 const SmallVectorImpl<char> &Str, 789 unsigned Length) { 790 while (Idx < Length && isspace(Str[Idx])) 791 ++Idx; 792 return Idx; 793} 794 795/// \brief If the given character is the start of some kind of 796/// balanced punctuation (e.g., quotes or parentheses), return the 797/// character that will terminate the punctuation. 798/// 799/// \returns The ending punctuation character, if any, or the NULL 800/// character if the input character does not start any punctuation. 801static inline char findMatchingPunctuation(char c) { 802 switch (c) { 803 case '\'': return '\''; 804 case '`': return '\''; 805 case '"': return '"'; 806 case '(': return ')'; 807 case '[': return ']'; 808 case '{': return '}'; 809 default: break; 810 } 811 812 return 0; 813} 814 815/// \brief Find the end of the word starting at the given offset 816/// within a string. 817/// 818/// \returns the index pointing one character past the end of the 819/// word. 820static unsigned findEndOfWord(unsigned Start, 821 const SmallVectorImpl<char> &Str, 822 unsigned Length, unsigned Column, 823 unsigned Columns) { 824 assert(Start < Str.size() && "Invalid start position!"); 825 unsigned End = Start + 1; 826 827 // If we are already at the end of the string, take that as the word. 828 if (End == Str.size()) 829 return End; 830 831 // Determine if the start of the string is actually opening 832 // punctuation, e.g., a quote or parentheses. 833 char EndPunct = findMatchingPunctuation(Str[Start]); 834 if (!EndPunct) { 835 // This is a normal word. Just find the first space character. 836 while (End < Length && !isspace(Str[End])) 837 ++End; 838 return End; 839 } 840 841 // We have the start of a balanced punctuation sequence (quotes, 842 // parentheses, etc.). Determine the full sequence is. 843 llvm::SmallString<16> PunctuationEndStack; 844 PunctuationEndStack.push_back(EndPunct); 845 while (End < Length && !PunctuationEndStack.empty()) { 846 if (Str[End] == PunctuationEndStack.back()) 847 PunctuationEndStack.pop_back(); 848 else if (char SubEndPunct = findMatchingPunctuation(Str[End])) 849 PunctuationEndStack.push_back(SubEndPunct); 850 851 ++End; 852 } 853 854 // Find the first space character after the punctuation ended. 855 while (End < Length && !isspace(Str[End])) 856 ++End; 857 858 unsigned PunctWordLength = End - Start; 859 if (// If the word fits on this line 860 Column + PunctWordLength <= Columns || 861 // ... or the word is "short enough" to take up the next line 862 // without too much ugly white space 863 PunctWordLength < Columns/3) 864 return End; // Take the whole thing as a single "word". 865 866 // The whole quoted/parenthesized string is too long to print as a 867 // single "word". Instead, find the "word" that starts just after 868 // the punctuation and use that end-point instead. This will recurse 869 // until it finds something small enough to consider a word. 870 return findEndOfWord(Start + 1, Str, Length, Column + 1, Columns); 871} 872 873/// \brief Print the given string to a stream, word-wrapping it to 874/// some number of columns in the process. 875/// 876/// \brief OS the stream to which the word-wrapping string will be 877/// emitted. 878/// 879/// \brief Str the string to word-wrap and output. 880/// 881/// \brief Columns the number of columns to word-wrap to. 882/// 883/// \brief Column the column number at which the first character of \p 884/// Str will be printed. This will be non-zero when part of the first 885/// line has already been printed. 886/// 887/// \brief Indentation the number of spaces to indent any lines beyond 888/// the first line. 889/// 890/// \returns true if word-wrapping was required, or false if the 891/// string fit on the first line. 892static bool PrintWordWrapped(raw_ostream &OS, 893 const SmallVectorImpl<char> &Str, 894 unsigned Columns, 895 unsigned Column = 0, 896 unsigned Indentation = WordWrapIndentation) { 897 unsigned Length = Str.size(); 898 899 // If there is a newline in this message somewhere, find that 900 // newline and split the message into the part before the newline 901 // (which will be word-wrapped) and the part from the newline one 902 // (which will be emitted unchanged). 903 for (unsigned I = 0; I != Length; ++I) 904 if (Str[I] == '\n') { 905 Length = I; 906 break; 907 } 908 909 // The string used to indent each line. 910 llvm::SmallString<16> IndentStr; 911 IndentStr.assign(Indentation, ' '); 912 bool Wrapped = false; 913 for (unsigned WordStart = 0, WordEnd; WordStart < Length; 914 WordStart = WordEnd) { 915 // Find the beginning of the next word. 916 WordStart = skipWhitespace(WordStart, Str, Length); 917 if (WordStart == Length) 918 break; 919 920 // Find the end of this word. 921 WordEnd = findEndOfWord(WordStart, Str, Length, Column, Columns); 922 923 // Does this word fit on the current line? 924 unsigned WordLength = WordEnd - WordStart; 925 if (Column + WordLength < Columns) { 926 // This word fits on the current line; print it there. 927 if (WordStart) { 928 OS << ' '; 929 Column += 1; 930 } 931 OS.write(&Str[WordStart], WordLength); 932 Column += WordLength; 933 continue; 934 } 935 936 // This word does not fit on the current line, so wrap to the next 937 // line. 938 OS << '\n'; 939 OS.write(&IndentStr[0], Indentation); 940 OS.write(&Str[WordStart], WordLength); 941 Column = Indentation + WordLength; 942 Wrapped = true; 943 } 944 945 if (Length == Str.size()) 946 return Wrapped; // We're done. 947 948 // There is a newline in the message, followed by something that 949 // will not be word-wrapped. Print that. 950 OS.write(&Str[Length], Str.size() - Length); 951 return true; 952} 953 954/// Get the presumed location of a diagnostic message. This computes the 955/// presumed location for the top of any macro backtrace when present. 956static PresumedLoc getDiagnosticPresumedLoc(const SourceManager &SM, 957 SourceLocation Loc) { 958 // This is a condensed form of the algorithm used by EmitCaretDiagnostic to 959 // walk to the top of the macro call stack. 960 while (Loc.isMacroID()) { 961 Loc = skipToMacroArgExpansion(SM, Loc); 962 Loc = getImmediateMacroCallerLoc(SM, Loc); 963 } 964 965 return SM.getPresumedLoc(Loc); 966} 967 968/// \brief Print out the file/line/column information and include trace. 969/// 970/// This method handlen the emission of the diagnostic location information. 971/// This includes extracting as much location information as is present for the 972/// diagnostic and printing it, as well as any include stack or source ranges 973/// necessary. 974void TextDiagnosticPrinter::EmitDiagnosticLoc(Diagnostic::Level Level, 975 const DiagnosticInfo &Info, 976 const SourceManager &SM, 977 PresumedLoc PLoc) { 978 if (PLoc.isInvalid()) { 979 // At least print the file name if available: 980 FileID FID = SM.getFileID(Info.getLocation()); 981 if (!FID.isInvalid()) { 982 const FileEntry* FE = SM.getFileEntryForID(FID); 983 if (FE && FE->getName()) { 984 OS << FE->getName(); 985 if (FE->getDevice() == 0 && FE->getInode() == 0 986 && FE->getFileMode() == 0) { 987 // in PCH is a guess, but a good one: 988 OS << " (in PCH)"; 989 } 990 OS << ": "; 991 } 992 } 993 return; 994 } 995 unsigned LineNo = PLoc.getLine(); 996 997 if (!DiagOpts->ShowLocation) 998 return; 999 1000 if (DiagOpts->ShowColors) 1001 OS.changeColor(savedColor, true); 1002 1003 OS << PLoc.getFilename(); 1004 switch (DiagOpts->Format) { 1005 case DiagnosticOptions::Clang: OS << ':' << LineNo; break; 1006 case DiagnosticOptions::Msvc: OS << '(' << LineNo; break; 1007 case DiagnosticOptions::Vi: OS << " +" << LineNo; break; 1008 } 1009 1010 if (DiagOpts->ShowColumn) 1011 // Compute the column number. 1012 if (unsigned ColNo = PLoc.getColumn()) { 1013 if (DiagOpts->Format == DiagnosticOptions::Msvc) { 1014 OS << ','; 1015 ColNo--; 1016 } else 1017 OS << ':'; 1018 OS << ColNo; 1019 } 1020 switch (DiagOpts->Format) { 1021 case DiagnosticOptions::Clang: 1022 case DiagnosticOptions::Vi: OS << ':'; break; 1023 case DiagnosticOptions::Msvc: OS << ") : "; break; 1024 } 1025 1026 if (DiagOpts->ShowSourceRanges && Info.getNumRanges()) { 1027 FileID CaretFileID = 1028 SM.getFileID(SM.getExpansionLoc(Info.getLocation())); 1029 bool PrintedRange = false; 1030 1031 for (unsigned i = 0, e = Info.getNumRanges(); i != e; ++i) { 1032 // Ignore invalid ranges. 1033 if (!Info.getRange(i).isValid()) continue; 1034 1035 SourceLocation B = Info.getRange(i).getBegin(); 1036 SourceLocation E = Info.getRange(i).getEnd(); 1037 B = SM.getExpansionLoc(B); 1038 E = SM.getExpansionLoc(E); 1039 1040 // If the End location and the start location are the same and are a 1041 // macro location, then the range was something that came from a 1042 // macro expansion or _Pragma. If this is an object-like macro, the 1043 // best we can do is to highlight the range. If this is a 1044 // function-like macro, we'd also like to highlight the arguments. 1045 if (B == E && Info.getRange(i).getEnd().isMacroID()) 1046 E = SM.getExpansionRange(Info.getRange(i).getEnd()).second; 1047 1048 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(B); 1049 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E); 1050 1051 // If the start or end of the range is in another file, just discard 1052 // it. 1053 if (BInfo.first != CaretFileID || EInfo.first != CaretFileID) 1054 continue; 1055 1056 // Add in the length of the token, so that we cover multi-char 1057 // tokens. 1058 unsigned TokSize = 0; 1059 if (Info.getRange(i).isTokenRange()) 1060 TokSize = Lexer::MeasureTokenLength(E, SM, *LangOpts); 1061 1062 OS << '{' << SM.getLineNumber(BInfo.first, BInfo.second) << ':' 1063 << SM.getColumnNumber(BInfo.first, BInfo.second) << '-' 1064 << SM.getLineNumber(EInfo.first, EInfo.second) << ':' 1065 << (SM.getColumnNumber(EInfo.first, EInfo.second)+TokSize) 1066 << '}'; 1067 PrintedRange = true; 1068 } 1069 1070 if (PrintedRange) 1071 OS << ':'; 1072 } 1073 OS << ' '; 1074} 1075 1076void TextDiagnosticPrinter::HandleDiagnostic(Diagnostic::Level Level, 1077 const DiagnosticInfo &Info) { 1078 // Default implementation (Warnings/errors count). 1079 DiagnosticClient::HandleDiagnostic(Level, Info); 1080 1081 // Keeps track of the the starting position of the location 1082 // information (e.g., "foo.c:10:4:") that precedes the error 1083 // message. We use this information to determine how long the 1084 // file+line+column number prefix is. 1085 uint64_t StartOfLocationInfo = OS.tell(); 1086 1087 if (!Prefix.empty()) 1088 OS << Prefix << ": "; 1089 1090 if (Info.getLocation().isValid()) { 1091 const SourceManager &SM = Info.getSourceManager(); 1092 PresumedLoc PLoc = getDiagnosticPresumedLoc(SM, Info.getLocation()); 1093 1094 // First, if this diagnostic is not in the main file, print out the 1095 // "included from" lines. 1096 PrintIncludeStack(Level, PLoc.getIncludeLoc(), SM); 1097 StartOfLocationInfo = OS.tell(); 1098 1099 // Next emit the location of this particular diagnostic. 1100 EmitDiagnosticLoc(Level, Info, SM, PLoc); 1101 1102 if (DiagOpts->ShowColors) 1103 OS.resetColor(); 1104 } 1105 1106 if (DiagOpts->ShowColors) { 1107 // Print diagnostic category in bold and color 1108 switch (Level) { 1109 case Diagnostic::Ignored: llvm_unreachable("Invalid diagnostic type"); 1110 case Diagnostic::Note: OS.changeColor(noteColor, true); break; 1111 case Diagnostic::Warning: OS.changeColor(warningColor, true); break; 1112 case Diagnostic::Error: OS.changeColor(errorColor, true); break; 1113 case Diagnostic::Fatal: OS.changeColor(fatalColor, true); break; 1114 } 1115 } 1116 1117 switch (Level) { 1118 case Diagnostic::Ignored: llvm_unreachable("Invalid diagnostic type"); 1119 case Diagnostic::Note: OS << "note: "; break; 1120 case Diagnostic::Warning: OS << "warning: "; break; 1121 case Diagnostic::Error: OS << "error: "; break; 1122 case Diagnostic::Fatal: OS << "fatal error: "; break; 1123 } 1124 1125 if (DiagOpts->ShowColors) 1126 OS.resetColor(); 1127 1128 llvm::SmallString<100> OutStr; 1129 Info.FormatDiagnostic(OutStr); 1130 1131 if (DiagOpts->ShowNames && 1132 !DiagnosticIDs::isBuiltinNote(Info.getID())) { 1133 OutStr += " ["; 1134 OutStr += DiagnosticIDs::getName(Info.getID()); 1135 OutStr += "]"; 1136 } 1137 1138 std::string OptionName; 1139 if (DiagOpts->ShowOptionNames) { 1140 // Was this a warning mapped to an error using -Werror or pragma? 1141 if (Level == Diagnostic::Error && 1142 DiagnosticIDs::isBuiltinWarningOrExtension(Info.getID())) { 1143 diag::Mapping mapping = diag::MAP_IGNORE; 1144 Info.getDiags()->getDiagnosticLevel(Info.getID(), Info.getLocation(), 1145 &mapping); 1146 if (mapping == diag::MAP_WARNING) 1147 OptionName += "-Werror"; 1148 } 1149 1150 StringRef Opt = DiagnosticIDs::getWarningOptionForDiag(Info.getID()); 1151 if (!Opt.empty()) { 1152 if (!OptionName.empty()) 1153 OptionName += ','; 1154 OptionName += "-W"; 1155 OptionName += Opt; 1156 } else if (Info.getID() == diag::fatal_too_many_errors) { 1157 OptionName = "-ferror-limit="; 1158 } else { 1159 // If the diagnostic is an extension diagnostic and not enabled by default 1160 // then it must have been turned on with -pedantic. 1161 bool EnabledByDefault; 1162 if (DiagnosticIDs::isBuiltinExtensionDiag(Info.getID(), 1163 EnabledByDefault) && 1164 !EnabledByDefault) 1165 OptionName = "-pedantic"; 1166 } 1167 } 1168 1169 // If the user wants to see category information, include it too. 1170 unsigned DiagCategory = 0; 1171 if (DiagOpts->ShowCategories) 1172 DiagCategory = DiagnosticIDs::getCategoryNumberForDiag(Info.getID()); 1173 1174 // If there is any categorization information, include it. 1175 if (!OptionName.empty() || DiagCategory != 0) { 1176 bool NeedsComma = false; 1177 OutStr += " ["; 1178 1179 if (!OptionName.empty()) { 1180 OutStr += OptionName; 1181 NeedsComma = true; 1182 } 1183 1184 if (DiagCategory) { 1185 if (NeedsComma) OutStr += ','; 1186 if (DiagOpts->ShowCategories == 1) 1187 OutStr += llvm::utostr(DiagCategory); 1188 else { 1189 assert(DiagOpts->ShowCategories == 2 && "Invalid ShowCategories value"); 1190 OutStr += DiagnosticIDs::getCategoryNameFromID(DiagCategory); 1191 } 1192 } 1193 1194 OutStr += "]"; 1195 } 1196 1197 1198 if (DiagOpts->ShowColors) { 1199 // Print warnings, errors and fatal errors in bold, no color 1200 switch (Level) { 1201 case Diagnostic::Warning: OS.changeColor(savedColor, true); break; 1202 case Diagnostic::Error: OS.changeColor(savedColor, true); break; 1203 case Diagnostic::Fatal: OS.changeColor(savedColor, true); break; 1204 default: break; //don't bold notes 1205 } 1206 } 1207 1208 if (DiagOpts->MessageLength) { 1209 // We will be word-wrapping the error message, so compute the 1210 // column number where we currently are (after printing the 1211 // location information). 1212 unsigned Column = OS.tell() - StartOfLocationInfo; 1213 PrintWordWrapped(OS, OutStr, DiagOpts->MessageLength, Column); 1214 } else { 1215 OS.write(OutStr.begin(), OutStr.size()); 1216 } 1217 OS << '\n'; 1218 if (DiagOpts->ShowColors) 1219 OS.resetColor(); 1220 1221 // If caret diagnostics are enabled and we have location, we want to 1222 // emit the caret. However, we only do this if the location moved 1223 // from the last diagnostic, if the last diagnostic was a note that 1224 // was part of a different warning or error diagnostic, or if the 1225 // diagnostic has ranges. We don't want to emit the same caret 1226 // multiple times if one loc has multiple diagnostics. 1227 if (DiagOpts->ShowCarets && Info.getLocation().isValid() && 1228 ((LastLoc != Info.getLocation()) || Info.getNumRanges() || 1229 (LastCaretDiagnosticWasNote && Level != Diagnostic::Note) || 1230 Info.getNumFixItHints())) { 1231 // Cache the LastLoc, it allows us to omit duplicate source/caret spewage. 1232 LastLoc = FullSourceLoc(Info.getLocation(), Info.getSourceManager()); 1233 LastCaretDiagnosticWasNote = (Level == Diagnostic::Note); 1234 1235 // Get the ranges into a local array we can hack on. 1236 SmallVector<CharSourceRange, 20> Ranges; 1237 Ranges.reserve(Info.getNumRanges()); 1238 for (unsigned i = 0, e = Info.getNumRanges(); i != e; ++i) 1239 Ranges.push_back(Info.getRange(i)); 1240 1241 for (unsigned i = 0, e = Info.getNumFixItHints(); i != e; ++i) { 1242 const FixItHint &Hint = Info.getFixItHint(i); 1243 if (Hint.RemoveRange.isValid()) 1244 Ranges.push_back(Hint.RemoveRange); 1245 } 1246 1247 EmitCaretDiagnostic(LastLoc, Ranges, LastLoc.getManager(), 1248 llvm::makeArrayRef(Info.getFixItHints(), 1249 Info.getNumFixItHints()), 1250 DiagOpts->MessageLength); 1251 } 1252 1253 OS.flush(); 1254} 1255