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