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