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