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