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