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