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