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