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