Diagnostic.cpp revision 176edba5311f6eff0cad2631449885ddf4fbc9ea
1//===--- Diagnostic.cpp - C Language Family Diagnostic Handling -----------===// 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 file implements the Diagnostic-related interfaces. 11// 12//===----------------------------------------------------------------------===// 13 14#include "clang/Basic/CharInfo.h" 15#include "clang/Basic/Diagnostic.h" 16#include "clang/Basic/DiagnosticOptions.h" 17#include "clang/Basic/IdentifierTable.h" 18#include "clang/Basic/PartialDiagnostic.h" 19#include "llvm/ADT/SmallString.h" 20#include "llvm/ADT/StringExtras.h" 21#include "llvm/Support/CrashRecoveryContext.h" 22#include "llvm/Support/raw_ostream.h" 23 24using namespace clang; 25 26static void DummyArgToStringFn(DiagnosticsEngine::ArgumentKind AK, intptr_t QT, 27 StringRef Modifier, StringRef Argument, 28 ArrayRef<DiagnosticsEngine::ArgumentValue> PrevArgs, 29 SmallVectorImpl<char> &Output, 30 void *Cookie, 31 ArrayRef<intptr_t> QualTypeVals) { 32 StringRef Str = "<can't format argument>"; 33 Output.append(Str.begin(), Str.end()); 34} 35 36DiagnosticsEngine::DiagnosticsEngine( 37 const IntrusiveRefCntPtr<DiagnosticIDs> &diags, DiagnosticOptions *DiagOpts, 38 DiagnosticConsumer *client, bool ShouldOwnClient) 39 : Diags(diags), DiagOpts(DiagOpts), Client(nullptr), SourceMgr(nullptr) { 40 setClient(client, ShouldOwnClient); 41 ArgToStringFn = DummyArgToStringFn; 42 ArgToStringCookie = nullptr; 43 44 AllExtensionsSilenced = 0; 45 IgnoreAllWarnings = false; 46 WarningsAsErrors = false; 47 EnableAllWarnings = false; 48 ErrorsAsFatal = false; 49 SuppressSystemWarnings = false; 50 SuppressAllDiagnostics = false; 51 ElideType = true; 52 PrintTemplateTree = false; 53 ShowColors = false; 54 ShowOverloads = Ovl_All; 55 ExtBehavior = diag::Severity::Ignored; 56 57 ErrorLimit = 0; 58 TemplateBacktraceLimit = 0; 59 ConstexprBacktraceLimit = 0; 60 61 Reset(); 62} 63 64void DiagnosticsEngine::setClient(DiagnosticConsumer *client, 65 bool ShouldOwnClient) { 66 Owner.reset(ShouldOwnClient ? client : nullptr); 67 Client = client; 68} 69 70void DiagnosticsEngine::pushMappings(SourceLocation Loc) { 71 DiagStateOnPushStack.push_back(GetCurDiagState()); 72} 73 74bool DiagnosticsEngine::popMappings(SourceLocation Loc) { 75 if (DiagStateOnPushStack.empty()) 76 return false; 77 78 if (DiagStateOnPushStack.back() != GetCurDiagState()) { 79 // State changed at some point between push/pop. 80 PushDiagStatePoint(DiagStateOnPushStack.back(), Loc); 81 } 82 DiagStateOnPushStack.pop_back(); 83 return true; 84} 85 86void DiagnosticsEngine::Reset() { 87 ErrorOccurred = false; 88 UncompilableErrorOccurred = false; 89 FatalErrorOccurred = false; 90 UnrecoverableErrorOccurred = false; 91 92 NumWarnings = 0; 93 NumErrors = 0; 94 TrapNumErrorsOccurred = 0; 95 TrapNumUnrecoverableErrorsOccurred = 0; 96 97 CurDiagID = ~0U; 98 LastDiagLevel = DiagnosticIDs::Ignored; 99 DelayedDiagID = 0; 100 101 // Clear state related to #pragma diagnostic. 102 DiagStates.clear(); 103 DiagStatePoints.clear(); 104 DiagStateOnPushStack.clear(); 105 106 // Create a DiagState and DiagStatePoint representing diagnostic changes 107 // through command-line. 108 DiagStates.push_back(DiagState()); 109 DiagStatePoints.push_back(DiagStatePoint(&DiagStates.back(), FullSourceLoc())); 110} 111 112void DiagnosticsEngine::SetDelayedDiagnostic(unsigned DiagID, StringRef Arg1, 113 StringRef Arg2) { 114 if (DelayedDiagID) 115 return; 116 117 DelayedDiagID = DiagID; 118 DelayedDiagArg1 = Arg1.str(); 119 DelayedDiagArg2 = Arg2.str(); 120} 121 122void DiagnosticsEngine::ReportDelayed() { 123 Report(DelayedDiagID) << DelayedDiagArg1 << DelayedDiagArg2; 124 DelayedDiagID = 0; 125 DelayedDiagArg1.clear(); 126 DelayedDiagArg2.clear(); 127} 128 129DiagnosticsEngine::DiagStatePointsTy::iterator 130DiagnosticsEngine::GetDiagStatePointForLoc(SourceLocation L) const { 131 assert(!DiagStatePoints.empty()); 132 assert(DiagStatePoints.front().Loc.isInvalid() && 133 "Should have created a DiagStatePoint for command-line"); 134 135 if (!SourceMgr) 136 return DiagStatePoints.end() - 1; 137 138 FullSourceLoc Loc(L, *SourceMgr); 139 if (Loc.isInvalid()) 140 return DiagStatePoints.end() - 1; 141 142 DiagStatePointsTy::iterator Pos = DiagStatePoints.end(); 143 FullSourceLoc LastStateChangePos = DiagStatePoints.back().Loc; 144 if (LastStateChangePos.isValid() && 145 Loc.isBeforeInTranslationUnitThan(LastStateChangePos)) 146 Pos = std::upper_bound(DiagStatePoints.begin(), DiagStatePoints.end(), 147 DiagStatePoint(nullptr, Loc)); 148 --Pos; 149 return Pos; 150} 151 152void DiagnosticsEngine::setSeverity(diag::kind Diag, diag::Severity Map, 153 SourceLocation L) { 154 assert(Diag < diag::DIAG_UPPER_LIMIT && 155 "Can only map builtin diagnostics"); 156 assert((Diags->isBuiltinWarningOrExtension(Diag) || 157 (Map == diag::Severity::Fatal || Map == diag::Severity::Error)) && 158 "Cannot map errors into warnings!"); 159 assert(!DiagStatePoints.empty()); 160 assert((L.isInvalid() || SourceMgr) && "No SourceMgr for valid location"); 161 162 FullSourceLoc Loc = SourceMgr? FullSourceLoc(L, *SourceMgr) : FullSourceLoc(); 163 FullSourceLoc LastStateChangePos = DiagStatePoints.back().Loc; 164 // Don't allow a mapping to a warning override an error/fatal mapping. 165 if (Map == diag::Severity::Warning) { 166 DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(Diag); 167 if (Info.getSeverity() == diag::Severity::Error || 168 Info.getSeverity() == diag::Severity::Fatal) 169 Map = Info.getSeverity(); 170 } 171 DiagnosticMapping Mapping = makeUserMapping(Map, L); 172 173 // Common case; setting all the diagnostics of a group in one place. 174 if (Loc.isInvalid() || Loc == LastStateChangePos) { 175 GetCurDiagState()->setMapping(Diag, Mapping); 176 return; 177 } 178 179 // Another common case; modifying diagnostic state in a source location 180 // after the previous one. 181 if ((Loc.isValid() && LastStateChangePos.isInvalid()) || 182 LastStateChangePos.isBeforeInTranslationUnitThan(Loc)) { 183 // A diagnostic pragma occurred, create a new DiagState initialized with 184 // the current one and a new DiagStatePoint to record at which location 185 // the new state became active. 186 DiagStates.push_back(*GetCurDiagState()); 187 PushDiagStatePoint(&DiagStates.back(), Loc); 188 GetCurDiagState()->setMapping(Diag, Mapping); 189 return; 190 } 191 192 // We allow setting the diagnostic state in random source order for 193 // completeness but it should not be actually happening in normal practice. 194 195 DiagStatePointsTy::iterator Pos = GetDiagStatePointForLoc(Loc); 196 assert(Pos != DiagStatePoints.end()); 197 198 // Update all diagnostic states that are active after the given location. 199 for (DiagStatePointsTy::iterator 200 I = Pos+1, E = DiagStatePoints.end(); I != E; ++I) { 201 GetCurDiagState()->setMapping(Diag, Mapping); 202 } 203 204 // If the location corresponds to an existing point, just update its state. 205 if (Pos->Loc == Loc) { 206 GetCurDiagState()->setMapping(Diag, Mapping); 207 return; 208 } 209 210 // Create a new state/point and fit it into the vector of DiagStatePoints 211 // so that the vector is always ordered according to location. 212 assert(Pos->Loc.isBeforeInTranslationUnitThan(Loc)); 213 DiagStates.push_back(*Pos->State); 214 DiagState *NewState = &DiagStates.back(); 215 GetCurDiagState()->setMapping(Diag, Mapping); 216 DiagStatePoints.insert(Pos+1, DiagStatePoint(NewState, 217 FullSourceLoc(Loc, *SourceMgr))); 218} 219 220bool DiagnosticsEngine::setSeverityForGroup(diag::Flavor Flavor, 221 StringRef Group, diag::Severity Map, 222 SourceLocation Loc) { 223 // Get the diagnostics in this group. 224 SmallVector<diag::kind, 256> GroupDiags; 225 if (Diags->getDiagnosticsInGroup(Flavor, Group, GroupDiags)) 226 return true; 227 228 // Set the mapping. 229 for (diag::kind Diag : GroupDiags) 230 setSeverity(Diag, Map, Loc); 231 232 return false; 233} 234 235bool DiagnosticsEngine::setDiagnosticGroupWarningAsError(StringRef Group, 236 bool Enabled) { 237 // If we are enabling this feature, just set the diagnostic mappings to map to 238 // errors. 239 if (Enabled) 240 return setSeverityForGroup(diag::Flavor::WarningOrError, Group, 241 diag::Severity::Error); 242 243 // Otherwise, we want to set the diagnostic mapping's "no Werror" bit, and 244 // potentially downgrade anything already mapped to be a warning. 245 246 // Get the diagnostics in this group. 247 SmallVector<diag::kind, 8> GroupDiags; 248 if (Diags->getDiagnosticsInGroup(diag::Flavor::WarningOrError, Group, 249 GroupDiags)) 250 return true; 251 252 // Perform the mapping change. 253 for (unsigned i = 0, e = GroupDiags.size(); i != e; ++i) { 254 DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(GroupDiags[i]); 255 256 if (Info.getSeverity() == diag::Severity::Error || 257 Info.getSeverity() == diag::Severity::Fatal) 258 Info.setSeverity(diag::Severity::Warning); 259 260 Info.setNoWarningAsError(true); 261 } 262 263 return false; 264} 265 266bool DiagnosticsEngine::setDiagnosticGroupErrorAsFatal(StringRef Group, 267 bool Enabled) { 268 // If we are enabling this feature, just set the diagnostic mappings to map to 269 // fatal errors. 270 if (Enabled) 271 return setSeverityForGroup(diag::Flavor::WarningOrError, Group, 272 diag::Severity::Fatal); 273 274 // Otherwise, we want to set the diagnostic mapping's "no Werror" bit, and 275 // potentially downgrade anything already mapped to be an error. 276 277 // Get the diagnostics in this group. 278 SmallVector<diag::kind, 8> GroupDiags; 279 if (Diags->getDiagnosticsInGroup(diag::Flavor::WarningOrError, Group, 280 GroupDiags)) 281 return true; 282 283 // Perform the mapping change. 284 for (unsigned i = 0, e = GroupDiags.size(); i != e; ++i) { 285 DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(GroupDiags[i]); 286 287 if (Info.getSeverity() == diag::Severity::Fatal) 288 Info.setSeverity(diag::Severity::Error); 289 290 Info.setNoErrorAsFatal(true); 291 } 292 293 return false; 294} 295 296void DiagnosticsEngine::setSeverityForAll(diag::Flavor Flavor, 297 diag::Severity Map, 298 SourceLocation Loc) { 299 // Get all the diagnostics. 300 SmallVector<diag::kind, 64> AllDiags; 301 Diags->getAllDiagnostics(Flavor, AllDiags); 302 303 // Set the mapping. 304 for (unsigned i = 0, e = AllDiags.size(); i != e; ++i) 305 if (Diags->isBuiltinWarningOrExtension(AllDiags[i])) 306 setSeverity(AllDiags[i], Map, Loc); 307} 308 309void DiagnosticsEngine::Report(const StoredDiagnostic &storedDiag) { 310 assert(CurDiagID == ~0U && "Multiple diagnostics in flight at once!"); 311 312 CurDiagLoc = storedDiag.getLocation(); 313 CurDiagID = storedDiag.getID(); 314 NumDiagArgs = 0; 315 316 DiagRanges.clear(); 317 DiagRanges.reserve(storedDiag.range_size()); 318 for (StoredDiagnostic::range_iterator 319 RI = storedDiag.range_begin(), 320 RE = storedDiag.range_end(); RI != RE; ++RI) 321 DiagRanges.push_back(*RI); 322 323 DiagFixItHints.clear(); 324 DiagFixItHints.reserve(storedDiag.fixit_size()); 325 for (StoredDiagnostic::fixit_iterator 326 FI = storedDiag.fixit_begin(), 327 FE = storedDiag.fixit_end(); FI != FE; ++FI) 328 DiagFixItHints.push_back(*FI); 329 330 assert(Client && "DiagnosticConsumer not set!"); 331 Level DiagLevel = storedDiag.getLevel(); 332 Diagnostic Info(this, storedDiag.getMessage()); 333 Client->HandleDiagnostic(DiagLevel, Info); 334 if (Client->IncludeInDiagnosticCounts()) { 335 if (DiagLevel == DiagnosticsEngine::Warning) 336 ++NumWarnings; 337 } 338 339 CurDiagID = ~0U; 340} 341 342bool DiagnosticsEngine::EmitCurrentDiagnostic(bool Force) { 343 assert(getClient() && "DiagnosticClient not set!"); 344 345 bool Emitted; 346 if (Force) { 347 Diagnostic Info(this); 348 349 // Figure out the diagnostic level of this message. 350 DiagnosticIDs::Level DiagLevel 351 = Diags->getDiagnosticLevel(Info.getID(), Info.getLocation(), *this); 352 353 Emitted = (DiagLevel != DiagnosticIDs::Ignored); 354 if (Emitted) { 355 // Emit the diagnostic regardless of suppression level. 356 Diags->EmitDiag(*this, DiagLevel); 357 } 358 } else { 359 // Process the diagnostic, sending the accumulated information to the 360 // DiagnosticConsumer. 361 Emitted = ProcessDiag(); 362 } 363 364 // Clear out the current diagnostic object. 365 unsigned DiagID = CurDiagID; 366 Clear(); 367 368 // If there was a delayed diagnostic, emit it now. 369 if (!Force && DelayedDiagID && DelayedDiagID != DiagID) 370 ReportDelayed(); 371 372 return Emitted; 373} 374 375 376DiagnosticConsumer::~DiagnosticConsumer() {} 377 378void DiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, 379 const Diagnostic &Info) { 380 if (!IncludeInDiagnosticCounts()) 381 return; 382 383 if (DiagLevel == DiagnosticsEngine::Warning) 384 ++NumWarnings; 385 else if (DiagLevel >= DiagnosticsEngine::Error) 386 ++NumErrors; 387} 388 389/// ModifierIs - Return true if the specified modifier matches specified string. 390template <std::size_t StrLen> 391static bool ModifierIs(const char *Modifier, unsigned ModifierLen, 392 const char (&Str)[StrLen]) { 393 return StrLen-1 == ModifierLen && !memcmp(Modifier, Str, StrLen-1); 394} 395 396/// ScanForward - Scans forward, looking for the given character, skipping 397/// nested clauses and escaped characters. 398static const char *ScanFormat(const char *I, const char *E, char Target) { 399 unsigned Depth = 0; 400 401 for ( ; I != E; ++I) { 402 if (Depth == 0 && *I == Target) return I; 403 if (Depth != 0 && *I == '}') Depth--; 404 405 if (*I == '%') { 406 I++; 407 if (I == E) break; 408 409 // Escaped characters get implicitly skipped here. 410 411 // Format specifier. 412 if (!isDigit(*I) && !isPunctuation(*I)) { 413 for (I++; I != E && !isDigit(*I) && *I != '{'; I++) ; 414 if (I == E) break; 415 if (*I == '{') 416 Depth++; 417 } 418 } 419 } 420 return E; 421} 422 423/// HandleSelectModifier - Handle the integer 'select' modifier. This is used 424/// like this: %select{foo|bar|baz}2. This means that the integer argument 425/// "%2" has a value from 0-2. If the value is 0, the diagnostic prints 'foo'. 426/// If the value is 1, it prints 'bar'. If it has the value 2, it prints 'baz'. 427/// This is very useful for certain classes of variant diagnostics. 428static void HandleSelectModifier(const Diagnostic &DInfo, unsigned ValNo, 429 const char *Argument, unsigned ArgumentLen, 430 SmallVectorImpl<char> &OutStr) { 431 const char *ArgumentEnd = Argument+ArgumentLen; 432 433 // Skip over 'ValNo' |'s. 434 while (ValNo) { 435 const char *NextVal = ScanFormat(Argument, ArgumentEnd, '|'); 436 assert(NextVal != ArgumentEnd && "Value for integer select modifier was" 437 " larger than the number of options in the diagnostic string!"); 438 Argument = NextVal+1; // Skip this string. 439 --ValNo; 440 } 441 442 // Get the end of the value. This is either the } or the |. 443 const char *EndPtr = ScanFormat(Argument, ArgumentEnd, '|'); 444 445 // Recursively format the result of the select clause into the output string. 446 DInfo.FormatDiagnostic(Argument, EndPtr, OutStr); 447} 448 449/// HandleIntegerSModifier - Handle the integer 's' modifier. This adds the 450/// letter 's' to the string if the value is not 1. This is used in cases like 451/// this: "you idiot, you have %4 parameter%s4!". 452static void HandleIntegerSModifier(unsigned ValNo, 453 SmallVectorImpl<char> &OutStr) { 454 if (ValNo != 1) 455 OutStr.push_back('s'); 456} 457 458/// HandleOrdinalModifier - Handle the integer 'ord' modifier. This 459/// prints the ordinal form of the given integer, with 1 corresponding 460/// to the first ordinal. Currently this is hard-coded to use the 461/// English form. 462static void HandleOrdinalModifier(unsigned ValNo, 463 SmallVectorImpl<char> &OutStr) { 464 assert(ValNo != 0 && "ValNo must be strictly positive!"); 465 466 llvm::raw_svector_ostream Out(OutStr); 467 468 // We could use text forms for the first N ordinals, but the numeric 469 // forms are actually nicer in diagnostics because they stand out. 470 Out << ValNo << llvm::getOrdinalSuffix(ValNo); 471} 472 473 474/// PluralNumber - Parse an unsigned integer and advance Start. 475static unsigned PluralNumber(const char *&Start, const char *End) { 476 // Programming 101: Parse a decimal number :-) 477 unsigned Val = 0; 478 while (Start != End && *Start >= '0' && *Start <= '9') { 479 Val *= 10; 480 Val += *Start - '0'; 481 ++Start; 482 } 483 return Val; 484} 485 486/// TestPluralRange - Test if Val is in the parsed range. Modifies Start. 487static bool TestPluralRange(unsigned Val, const char *&Start, const char *End) { 488 if (*Start != '[') { 489 unsigned Ref = PluralNumber(Start, End); 490 return Ref == Val; 491 } 492 493 ++Start; 494 unsigned Low = PluralNumber(Start, End); 495 assert(*Start == ',' && "Bad plural expression syntax: expected ,"); 496 ++Start; 497 unsigned High = PluralNumber(Start, End); 498 assert(*Start == ']' && "Bad plural expression syntax: expected )"); 499 ++Start; 500 return Low <= Val && Val <= High; 501} 502 503/// EvalPluralExpr - Actual expression evaluator for HandlePluralModifier. 504static bool EvalPluralExpr(unsigned ValNo, const char *Start, const char *End) { 505 // Empty condition? 506 if (*Start == ':') 507 return true; 508 509 while (1) { 510 char C = *Start; 511 if (C == '%') { 512 // Modulo expression 513 ++Start; 514 unsigned Arg = PluralNumber(Start, End); 515 assert(*Start == '=' && "Bad plural expression syntax: expected ="); 516 ++Start; 517 unsigned ValMod = ValNo % Arg; 518 if (TestPluralRange(ValMod, Start, End)) 519 return true; 520 } else { 521 assert((C == '[' || (C >= '0' && C <= '9')) && 522 "Bad plural expression syntax: unexpected character"); 523 // Range expression 524 if (TestPluralRange(ValNo, Start, End)) 525 return true; 526 } 527 528 // Scan for next or-expr part. 529 Start = std::find(Start, End, ','); 530 if (Start == End) 531 break; 532 ++Start; 533 } 534 return false; 535} 536 537/// HandlePluralModifier - Handle the integer 'plural' modifier. This is used 538/// for complex plural forms, or in languages where all plurals are complex. 539/// The syntax is: %plural{cond1:form1|cond2:form2|:form3}, where condn are 540/// conditions that are tested in order, the form corresponding to the first 541/// that applies being emitted. The empty condition is always true, making the 542/// last form a default case. 543/// Conditions are simple boolean expressions, where n is the number argument. 544/// Here are the rules. 545/// condition := expression | empty 546/// empty := -> always true 547/// expression := numeric [',' expression] -> logical or 548/// numeric := range -> true if n in range 549/// | '%' number '=' range -> true if n % number in range 550/// range := number 551/// | '[' number ',' number ']' -> ranges are inclusive both ends 552/// 553/// Here are some examples from the GNU gettext manual written in this form: 554/// English: 555/// {1:form0|:form1} 556/// Latvian: 557/// {0:form2|%100=11,%10=0,%10=[2,9]:form1|:form0} 558/// Gaeilge: 559/// {1:form0|2:form1|:form2} 560/// Romanian: 561/// {1:form0|0,%100=[1,19]:form1|:form2} 562/// Lithuanian: 563/// {%10=0,%100=[10,19]:form2|%10=1:form0|:form1} 564/// Russian (requires repeated form): 565/// {%100=[11,14]:form2|%10=1:form0|%10=[2,4]:form1|:form2} 566/// Slovak 567/// {1:form0|[2,4]:form1|:form2} 568/// Polish (requires repeated form): 569/// {1:form0|%100=[10,20]:form2|%10=[2,4]:form1|:form2} 570static void HandlePluralModifier(const Diagnostic &DInfo, unsigned ValNo, 571 const char *Argument, unsigned ArgumentLen, 572 SmallVectorImpl<char> &OutStr) { 573 const char *ArgumentEnd = Argument + ArgumentLen; 574 while (1) { 575 assert(Argument < ArgumentEnd && "Plural expression didn't match."); 576 const char *ExprEnd = Argument; 577 while (*ExprEnd != ':') { 578 assert(ExprEnd != ArgumentEnd && "Plural missing expression end"); 579 ++ExprEnd; 580 } 581 if (EvalPluralExpr(ValNo, Argument, ExprEnd)) { 582 Argument = ExprEnd + 1; 583 ExprEnd = ScanFormat(Argument, ArgumentEnd, '|'); 584 585 // Recursively format the result of the plural clause into the 586 // output string. 587 DInfo.FormatDiagnostic(Argument, ExprEnd, OutStr); 588 return; 589 } 590 Argument = ScanFormat(Argument, ArgumentEnd - 1, '|') + 1; 591 } 592} 593 594/// \brief Returns the friendly description for a token kind that will appear 595/// without quotes in diagnostic messages. These strings may be translatable in 596/// future. 597static const char *getTokenDescForDiagnostic(tok::TokenKind Kind) { 598 switch (Kind) { 599 case tok::identifier: 600 return "identifier"; 601 default: 602 return nullptr; 603 } 604} 605 606/// FormatDiagnostic - Format this diagnostic into a string, substituting the 607/// formal arguments into the %0 slots. The result is appended onto the Str 608/// array. 609void Diagnostic:: 610FormatDiagnostic(SmallVectorImpl<char> &OutStr) const { 611 if (!StoredDiagMessage.empty()) { 612 OutStr.append(StoredDiagMessage.begin(), StoredDiagMessage.end()); 613 return; 614 } 615 616 StringRef Diag = 617 getDiags()->getDiagnosticIDs()->getDescription(getID()); 618 619 FormatDiagnostic(Diag.begin(), Diag.end(), OutStr); 620} 621 622void Diagnostic:: 623FormatDiagnostic(const char *DiagStr, const char *DiagEnd, 624 SmallVectorImpl<char> &OutStr) const { 625 626 /// FormattedArgs - Keep track of all of the arguments formatted by 627 /// ConvertArgToString and pass them into subsequent calls to 628 /// ConvertArgToString, allowing the implementation to avoid redundancies in 629 /// obvious cases. 630 SmallVector<DiagnosticsEngine::ArgumentValue, 8> FormattedArgs; 631 632 /// QualTypeVals - Pass a vector of arrays so that QualType names can be 633 /// compared to see if more information is needed to be printed. 634 SmallVector<intptr_t, 2> QualTypeVals; 635 SmallVector<char, 64> Tree; 636 637 for (unsigned i = 0, e = getNumArgs(); i < e; ++i) 638 if (getArgKind(i) == DiagnosticsEngine::ak_qualtype) 639 QualTypeVals.push_back(getRawArg(i)); 640 641 while (DiagStr != DiagEnd) { 642 if (DiagStr[0] != '%') { 643 // Append non-%0 substrings to Str if we have one. 644 const char *StrEnd = std::find(DiagStr, DiagEnd, '%'); 645 OutStr.append(DiagStr, StrEnd); 646 DiagStr = StrEnd; 647 continue; 648 } else if (isPunctuation(DiagStr[1])) { 649 OutStr.push_back(DiagStr[1]); // %% -> %. 650 DiagStr += 2; 651 continue; 652 } 653 654 // Skip the %. 655 ++DiagStr; 656 657 // This must be a placeholder for a diagnostic argument. The format for a 658 // placeholder is one of "%0", "%modifier0", or "%modifier{arguments}0". 659 // The digit is a number from 0-9 indicating which argument this comes from. 660 // The modifier is a string of digits from the set [-a-z]+, arguments is a 661 // brace enclosed string. 662 const char *Modifier = nullptr, *Argument = nullptr; 663 unsigned ModifierLen = 0, ArgumentLen = 0; 664 665 // Check to see if we have a modifier. If so eat it. 666 if (!isDigit(DiagStr[0])) { 667 Modifier = DiagStr; 668 while (DiagStr[0] == '-' || 669 (DiagStr[0] >= 'a' && DiagStr[0] <= 'z')) 670 ++DiagStr; 671 ModifierLen = DiagStr-Modifier; 672 673 // If we have an argument, get it next. 674 if (DiagStr[0] == '{') { 675 ++DiagStr; // Skip {. 676 Argument = DiagStr; 677 678 DiagStr = ScanFormat(DiagStr, DiagEnd, '}'); 679 assert(DiagStr != DiagEnd && "Mismatched {}'s in diagnostic string!"); 680 ArgumentLen = DiagStr-Argument; 681 ++DiagStr; // Skip }. 682 } 683 } 684 685 assert(isDigit(*DiagStr) && "Invalid format for argument in diagnostic"); 686 unsigned ArgNo = *DiagStr++ - '0'; 687 688 // Only used for type diffing. 689 unsigned ArgNo2 = ArgNo; 690 691 DiagnosticsEngine::ArgumentKind Kind = getArgKind(ArgNo); 692 if (ModifierIs(Modifier, ModifierLen, "diff")) { 693 assert(*DiagStr == ',' && isDigit(*(DiagStr + 1)) && 694 "Invalid format for diff modifier"); 695 ++DiagStr; // Comma. 696 ArgNo2 = *DiagStr++ - '0'; 697 DiagnosticsEngine::ArgumentKind Kind2 = getArgKind(ArgNo2); 698 if (Kind == DiagnosticsEngine::ak_qualtype && 699 Kind2 == DiagnosticsEngine::ak_qualtype) 700 Kind = DiagnosticsEngine::ak_qualtype_pair; 701 else { 702 // %diff only supports QualTypes. For other kinds of arguments, 703 // use the default printing. For example, if the modifier is: 704 // "%diff{compare $ to $|other text}1,2" 705 // treat it as: 706 // "compare %1 to %2" 707 const char *Pipe = ScanFormat(Argument, Argument + ArgumentLen, '|'); 708 const char *FirstDollar = ScanFormat(Argument, Pipe, '$'); 709 const char *SecondDollar = ScanFormat(FirstDollar + 1, Pipe, '$'); 710 const char ArgStr1[] = { '%', static_cast<char>('0' + ArgNo) }; 711 const char ArgStr2[] = { '%', static_cast<char>('0' + ArgNo2) }; 712 FormatDiagnostic(Argument, FirstDollar, OutStr); 713 FormatDiagnostic(ArgStr1, ArgStr1 + 2, OutStr); 714 FormatDiagnostic(FirstDollar + 1, SecondDollar, OutStr); 715 FormatDiagnostic(ArgStr2, ArgStr2 + 2, OutStr); 716 FormatDiagnostic(SecondDollar + 1, Pipe, OutStr); 717 continue; 718 } 719 } 720 721 switch (Kind) { 722 // ---- STRINGS ---- 723 case DiagnosticsEngine::ak_std_string: { 724 const std::string &S = getArgStdStr(ArgNo); 725 assert(ModifierLen == 0 && "No modifiers for strings yet"); 726 OutStr.append(S.begin(), S.end()); 727 break; 728 } 729 case DiagnosticsEngine::ak_c_string: { 730 const char *S = getArgCStr(ArgNo); 731 assert(ModifierLen == 0 && "No modifiers for strings yet"); 732 733 // Don't crash if get passed a null pointer by accident. 734 if (!S) 735 S = "(null)"; 736 737 OutStr.append(S, S + strlen(S)); 738 break; 739 } 740 // ---- INTEGERS ---- 741 case DiagnosticsEngine::ak_sint: { 742 int Val = getArgSInt(ArgNo); 743 744 if (ModifierIs(Modifier, ModifierLen, "select")) { 745 HandleSelectModifier(*this, (unsigned)Val, Argument, ArgumentLen, 746 OutStr); 747 } else if (ModifierIs(Modifier, ModifierLen, "s")) { 748 HandleIntegerSModifier(Val, OutStr); 749 } else if (ModifierIs(Modifier, ModifierLen, "plural")) { 750 HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen, 751 OutStr); 752 } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) { 753 HandleOrdinalModifier((unsigned)Val, OutStr); 754 } else { 755 assert(ModifierLen == 0 && "Unknown integer modifier"); 756 llvm::raw_svector_ostream(OutStr) << Val; 757 } 758 break; 759 } 760 case DiagnosticsEngine::ak_uint: { 761 unsigned Val = getArgUInt(ArgNo); 762 763 if (ModifierIs(Modifier, ModifierLen, "select")) { 764 HandleSelectModifier(*this, Val, Argument, ArgumentLen, OutStr); 765 } else if (ModifierIs(Modifier, ModifierLen, "s")) { 766 HandleIntegerSModifier(Val, OutStr); 767 } else if (ModifierIs(Modifier, ModifierLen, "plural")) { 768 HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen, 769 OutStr); 770 } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) { 771 HandleOrdinalModifier(Val, OutStr); 772 } else { 773 assert(ModifierLen == 0 && "Unknown integer modifier"); 774 llvm::raw_svector_ostream(OutStr) << Val; 775 } 776 break; 777 } 778 // ---- TOKEN SPELLINGS ---- 779 case DiagnosticsEngine::ak_tokenkind: { 780 tok::TokenKind Kind = static_cast<tok::TokenKind>(getRawArg(ArgNo)); 781 assert(ModifierLen == 0 && "No modifiers for token kinds yet"); 782 783 llvm::raw_svector_ostream Out(OutStr); 784 if (const char *S = tok::getPunctuatorSpelling(Kind)) 785 // Quoted token spelling for punctuators. 786 Out << '\'' << S << '\''; 787 else if (const char *S = tok::getKeywordSpelling(Kind)) 788 // Unquoted token spelling for keywords. 789 Out << S; 790 else if (const char *S = getTokenDescForDiagnostic(Kind)) 791 // Unquoted translatable token name. 792 Out << S; 793 else if (const char *S = tok::getTokenName(Kind)) 794 // Debug name, shouldn't appear in user-facing diagnostics. 795 Out << '<' << S << '>'; 796 else 797 Out << "(null)"; 798 break; 799 } 800 // ---- NAMES and TYPES ---- 801 case DiagnosticsEngine::ak_identifierinfo: { 802 const IdentifierInfo *II = getArgIdentifier(ArgNo); 803 assert(ModifierLen == 0 && "No modifiers for strings yet"); 804 805 // Don't crash if get passed a null pointer by accident. 806 if (!II) { 807 const char *S = "(null)"; 808 OutStr.append(S, S + strlen(S)); 809 continue; 810 } 811 812 llvm::raw_svector_ostream(OutStr) << '\'' << II->getName() << '\''; 813 break; 814 } 815 case DiagnosticsEngine::ak_qualtype: 816 case DiagnosticsEngine::ak_declarationname: 817 case DiagnosticsEngine::ak_nameddecl: 818 case DiagnosticsEngine::ak_nestednamespec: 819 case DiagnosticsEngine::ak_declcontext: 820 case DiagnosticsEngine::ak_attr: 821 getDiags()->ConvertArgToString(Kind, getRawArg(ArgNo), 822 StringRef(Modifier, ModifierLen), 823 StringRef(Argument, ArgumentLen), 824 FormattedArgs, 825 OutStr, QualTypeVals); 826 break; 827 case DiagnosticsEngine::ak_qualtype_pair: 828 // Create a struct with all the info needed for printing. 829 TemplateDiffTypes TDT; 830 TDT.FromType = getRawArg(ArgNo); 831 TDT.ToType = getRawArg(ArgNo2); 832 TDT.ElideType = getDiags()->ElideType; 833 TDT.ShowColors = getDiags()->ShowColors; 834 TDT.TemplateDiffUsed = false; 835 intptr_t val = reinterpret_cast<intptr_t>(&TDT); 836 837 const char *ArgumentEnd = Argument + ArgumentLen; 838 const char *Pipe = ScanFormat(Argument, ArgumentEnd, '|'); 839 840 // Print the tree. If this diagnostic already has a tree, skip the 841 // second tree. 842 if (getDiags()->PrintTemplateTree && Tree.empty()) { 843 TDT.PrintFromType = true; 844 TDT.PrintTree = true; 845 getDiags()->ConvertArgToString(Kind, val, 846 StringRef(Modifier, ModifierLen), 847 StringRef(Argument, ArgumentLen), 848 FormattedArgs, 849 Tree, QualTypeVals); 850 // If there is no tree information, fall back to regular printing. 851 if (!Tree.empty()) { 852 FormatDiagnostic(Pipe + 1, ArgumentEnd, OutStr); 853 break; 854 } 855 } 856 857 // Non-tree printing, also the fall-back when tree printing fails. 858 // The fall-back is triggered when the types compared are not templates. 859 const char *FirstDollar = ScanFormat(Argument, ArgumentEnd, '$'); 860 const char *SecondDollar = ScanFormat(FirstDollar + 1, ArgumentEnd, '$'); 861 862 // Append before text 863 FormatDiagnostic(Argument, FirstDollar, OutStr); 864 865 // Append first type 866 TDT.PrintTree = false; 867 TDT.PrintFromType = true; 868 getDiags()->ConvertArgToString(Kind, val, 869 StringRef(Modifier, ModifierLen), 870 StringRef(Argument, ArgumentLen), 871 FormattedArgs, 872 OutStr, QualTypeVals); 873 if (!TDT.TemplateDiffUsed) 874 FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_qualtype, 875 TDT.FromType)); 876 877 // Append middle text 878 FormatDiagnostic(FirstDollar + 1, SecondDollar, OutStr); 879 880 // Append second type 881 TDT.PrintFromType = false; 882 getDiags()->ConvertArgToString(Kind, val, 883 StringRef(Modifier, ModifierLen), 884 StringRef(Argument, ArgumentLen), 885 FormattedArgs, 886 OutStr, QualTypeVals); 887 if (!TDT.TemplateDiffUsed) 888 FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_qualtype, 889 TDT.ToType)); 890 891 // Append end text 892 FormatDiagnostic(SecondDollar + 1, Pipe, OutStr); 893 break; 894 } 895 896 // Remember this argument info for subsequent formatting operations. Turn 897 // std::strings into a null terminated string to make it be the same case as 898 // all the other ones. 899 if (Kind == DiagnosticsEngine::ak_qualtype_pair) 900 continue; 901 else if (Kind != DiagnosticsEngine::ak_std_string) 902 FormattedArgs.push_back(std::make_pair(Kind, getRawArg(ArgNo))); 903 else 904 FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_c_string, 905 (intptr_t)getArgStdStr(ArgNo).c_str())); 906 907 } 908 909 // Append the type tree to the end of the diagnostics. 910 OutStr.append(Tree.begin(), Tree.end()); 911} 912 913StoredDiagnostic::StoredDiagnostic() { } 914 915StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID, 916 StringRef Message) 917 : ID(ID), Level(Level), Loc(), Message(Message) { } 918 919StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level, 920 const Diagnostic &Info) 921 : ID(Info.getID()), Level(Level) 922{ 923 assert((Info.getLocation().isInvalid() || Info.hasSourceManager()) && 924 "Valid source location without setting a source manager for diagnostic"); 925 if (Info.getLocation().isValid()) 926 Loc = FullSourceLoc(Info.getLocation(), Info.getSourceManager()); 927 SmallString<64> Message; 928 Info.FormatDiagnostic(Message); 929 this->Message.assign(Message.begin(), Message.end()); 930 931 Ranges.reserve(Info.getNumRanges()); 932 for (unsigned I = 0, N = Info.getNumRanges(); I != N; ++I) 933 Ranges.push_back(Info.getRange(I)); 934 935 FixIts.reserve(Info.getNumFixItHints()); 936 for (unsigned I = 0, N = Info.getNumFixItHints(); I != N; ++I) 937 FixIts.push_back(Info.getFixItHint(I)); 938} 939 940StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID, 941 StringRef Message, FullSourceLoc Loc, 942 ArrayRef<CharSourceRange> Ranges, 943 ArrayRef<FixItHint> FixIts) 944 : ID(ID), Level(Level), Loc(Loc), Message(Message), 945 Ranges(Ranges.begin(), Ranges.end()), FixIts(FixIts.begin(), FixIts.end()) 946{ 947} 948 949StoredDiagnostic::~StoredDiagnostic() { } 950 951/// IncludeInDiagnosticCounts - This method (whose default implementation 952/// returns true) indicates whether the diagnostics handled by this 953/// DiagnosticConsumer should be included in the number of diagnostics 954/// reported by DiagnosticsEngine. 955bool DiagnosticConsumer::IncludeInDiagnosticCounts() const { return true; } 956 957void IgnoringDiagConsumer::anchor() { } 958 959ForwardingDiagnosticConsumer::~ForwardingDiagnosticConsumer() {} 960 961void ForwardingDiagnosticConsumer::HandleDiagnostic( 962 DiagnosticsEngine::Level DiagLevel, 963 const Diagnostic &Info) { 964 Target.HandleDiagnostic(DiagLevel, Info); 965} 966 967void ForwardingDiagnosticConsumer::clear() { 968 DiagnosticConsumer::clear(); 969 Target.clear(); 970} 971 972bool ForwardingDiagnosticConsumer::IncludeInDiagnosticCounts() const { 973 return Target.IncludeInDiagnosticCounts(); 974} 975 976PartialDiagnostic::StorageAllocator::StorageAllocator() { 977 for (unsigned I = 0; I != NumCached; ++I) 978 FreeList[I] = Cached + I; 979 NumFreeListEntries = NumCached; 980} 981 982PartialDiagnostic::StorageAllocator::~StorageAllocator() { 983 // Don't assert if we are in a CrashRecovery context, as this invariant may 984 // be invalidated during a crash. 985 assert((NumFreeListEntries == NumCached || 986 llvm::CrashRecoveryContext::isRecoveringFromCrash()) && 987 "A partial is on the lamb"); 988} 989