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