Diagnostic.cpp revision 32d4d80c26e8c4c1922cff4661e0b9f44a3aabfc
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 16#include "clang/Lex/LexDiagnostic.h" 17#include "clang/Parse/ParseDiagnostic.h" 18#include "clang/AST/ASTDiagnostic.h" 19#include "clang/Sema/SemaDiagnostic.h" 20#include "clang/Frontend/FrontendDiagnostic.h" 21#include "clang/Analysis/AnalysisDiagnostic.h" 22#include "clang/Driver/DriverDiagnostic.h" 23 24#include "clang/Basic/IdentifierTable.h" 25#include "clang/Basic/SourceLocation.h" 26#include "llvm/ADT/SmallVector.h" 27#include "llvm/ADT/StringExtras.h" 28#include "llvm/Support/raw_ostream.h" 29#include <vector> 30#include <map> 31#include <cstring> 32using namespace clang; 33 34//===----------------------------------------------------------------------===// 35// Builtin Diagnostic information 36//===----------------------------------------------------------------------===// 37 38// Diagnostic classes. 39enum { 40 CLASS_NOTE = 0x01, 41 CLASS_WARNING = 0x02, 42 CLASS_EXTENSION = 0x03, 43 CLASS_ERROR = 0x04 44}; 45 46struct StaticDiagInfoRec { 47 unsigned short DiagID; 48 unsigned Mapping : 3; 49 unsigned Class : 3; 50 bool SFINAE : 1; 51 const char *Description; 52 const char *OptionGroup; 53 54 bool operator<(const StaticDiagInfoRec &RHS) const { 55 return DiagID < RHS.DiagID; 56 } 57 bool operator>(const StaticDiagInfoRec &RHS) const { 58 return DiagID > RHS.DiagID; 59 } 60}; 61 62static const StaticDiagInfoRec StaticDiagInfo[] = { 63#define DIAG(ENUM,CLASS,DEFAULT_MAPPING,DESC,GROUP,SFINAE) \ 64 { diag::ENUM, DEFAULT_MAPPING, CLASS, SFINAE, DESC, GROUP }, 65#include "clang/Basic/DiagnosticCommonKinds.inc" 66#include "clang/Basic/DiagnosticDriverKinds.inc" 67#include "clang/Basic/DiagnosticFrontendKinds.inc" 68#include "clang/Basic/DiagnosticLexKinds.inc" 69#include "clang/Basic/DiagnosticParseKinds.inc" 70#include "clang/Basic/DiagnosticASTKinds.inc" 71#include "clang/Basic/DiagnosticSemaKinds.inc" 72#include "clang/Basic/DiagnosticAnalysisKinds.inc" 73 { 0, 0, 0, 0, 0, 0} 74}; 75#undef DIAG 76 77/// GetDiagInfo - Return the StaticDiagInfoRec entry for the specified DiagID, 78/// or null if the ID is invalid. 79static const StaticDiagInfoRec *GetDiagInfo(unsigned DiagID) { 80 unsigned NumDiagEntries = sizeof(StaticDiagInfo)/sizeof(StaticDiagInfo[0])-1; 81 82 // If assertions are enabled, verify that the StaticDiagInfo array is sorted. 83#ifndef NDEBUG 84 static bool IsFirst = true; 85 if (IsFirst) { 86 for (unsigned i = 1; i != NumDiagEntries; ++i) { 87 assert(StaticDiagInfo[i-1].DiagID != StaticDiagInfo[i].DiagID && 88 "Diag ID conflict, the enums at the start of clang::diag (in " 89 "Diagnostic.h) probably need to be increased"); 90 91 assert(StaticDiagInfo[i-1] < StaticDiagInfo[i] && 92 "Improperly sorted diag info"); 93 } 94 IsFirst = false; 95 } 96#endif 97 98 // Search the diagnostic table with a binary search. 99 StaticDiagInfoRec Find = { DiagID, 0, 0, 0, 0, 0 }; 100 101 const StaticDiagInfoRec *Found = 102 std::lower_bound(StaticDiagInfo, StaticDiagInfo + NumDiagEntries, Find); 103 if (Found == StaticDiagInfo + NumDiagEntries || 104 Found->DiagID != DiagID) 105 return 0; 106 107 return Found; 108} 109 110static unsigned GetDefaultDiagMapping(unsigned DiagID) { 111 if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID)) 112 return Info->Mapping; 113 return diag::MAP_FATAL; 114} 115 116/// getWarningOptionForDiag - Return the lowest-level warning option that 117/// enables the specified diagnostic. If there is no -Wfoo flag that controls 118/// the diagnostic, this returns null. 119const char *Diagnostic::getWarningOptionForDiag(unsigned DiagID) { 120 if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID)) 121 return Info->OptionGroup; 122 return 0; 123} 124 125bool Diagnostic::isBuiltinSFINAEDiag(unsigned DiagID) { 126 if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID)) 127 return Info->SFINAE && Info->Class == CLASS_ERROR; 128 return false; 129} 130 131/// getDiagClass - Return the class field of the diagnostic. 132/// 133static unsigned getBuiltinDiagClass(unsigned DiagID) { 134 if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID)) 135 return Info->Class; 136 return ~0U; 137} 138 139//===----------------------------------------------------------------------===// 140// Custom Diagnostic information 141//===----------------------------------------------------------------------===// 142 143namespace clang { 144 namespace diag { 145 class CustomDiagInfo { 146 typedef std::pair<Diagnostic::Level, std::string> DiagDesc; 147 std::vector<DiagDesc> DiagInfo; 148 std::map<DiagDesc, unsigned> DiagIDs; 149 public: 150 151 /// getDescription - Return the description of the specified custom 152 /// diagnostic. 153 const char *getDescription(unsigned DiagID) const { 154 assert(this && DiagID-DIAG_UPPER_LIMIT < DiagInfo.size() && 155 "Invalid diagnosic ID"); 156 return DiagInfo[DiagID-DIAG_UPPER_LIMIT].second.c_str(); 157 } 158 159 /// getLevel - Return the level of the specified custom diagnostic. 160 Diagnostic::Level getLevel(unsigned DiagID) const { 161 assert(this && DiagID-DIAG_UPPER_LIMIT < DiagInfo.size() && 162 "Invalid diagnosic ID"); 163 return DiagInfo[DiagID-DIAG_UPPER_LIMIT].first; 164 } 165 166 unsigned getOrCreateDiagID(Diagnostic::Level L, llvm::StringRef Message, 167 Diagnostic &Diags) { 168 DiagDesc D(L, Message); 169 // Check to see if it already exists. 170 std::map<DiagDesc, unsigned>::iterator I = DiagIDs.lower_bound(D); 171 if (I != DiagIDs.end() && I->first == D) 172 return I->second; 173 174 // If not, assign a new ID. 175 unsigned ID = DiagInfo.size()+DIAG_UPPER_LIMIT; 176 DiagIDs.insert(std::make_pair(D, ID)); 177 DiagInfo.push_back(D); 178 return ID; 179 } 180 }; 181 182 } // end diag namespace 183} // end clang namespace 184 185 186//===----------------------------------------------------------------------===// 187// Common Diagnostic implementation 188//===----------------------------------------------------------------------===// 189 190static void DummyArgToStringFn(Diagnostic::ArgumentKind AK, intptr_t QT, 191 const char *Modifier, unsigned ML, 192 const char *Argument, unsigned ArgLen, 193 const Diagnostic::ArgumentValue *PrevArgs, 194 unsigned NumPrevArgs, 195 llvm::SmallVectorImpl<char> &Output, 196 void *Cookie) { 197 const char *Str = "<can't format argument>"; 198 Output.append(Str, Str+strlen(Str)); 199} 200 201 202Diagnostic::Diagnostic(DiagnosticClient *client) : Client(client) { 203 AllExtensionsSilenced = 0; 204 IgnoreAllWarnings = false; 205 WarningsAsErrors = false; 206 SuppressSystemWarnings = false; 207 SuppressAllDiagnostics = false; 208 ExtBehavior = Ext_Ignore; 209 210 ErrorOccurred = false; 211 FatalErrorOccurred = false; 212 NumDiagnostics = 0; 213 214 NumErrors = 0; 215 CustomDiagInfo = 0; 216 CurDiagID = ~0U; 217 LastDiagLevel = Ignored; 218 219 ArgToStringFn = DummyArgToStringFn; 220 ArgToStringCookie = 0; 221 222 // Set all mappings to 'unset'. 223 DiagMappings BlankDiags(diag::DIAG_UPPER_LIMIT/2, 0); 224 DiagMappingsStack.push_back(BlankDiags); 225} 226 227Diagnostic::~Diagnostic() { 228 delete CustomDiagInfo; 229} 230 231 232void Diagnostic::pushMappings() { 233 // Avoids undefined behavior when the stack has to resize. 234 DiagMappingsStack.reserve(DiagMappingsStack.size() + 1); 235 DiagMappingsStack.push_back(DiagMappingsStack.back()); 236} 237 238bool Diagnostic::popMappings() { 239 if (DiagMappingsStack.size() == 1) 240 return false; 241 242 DiagMappingsStack.pop_back(); 243 return true; 244} 245 246/// getCustomDiagID - Return an ID for a diagnostic with the specified message 247/// and level. If this is the first request for this diagnosic, it is 248/// registered and created, otherwise the existing ID is returned. 249unsigned Diagnostic::getCustomDiagID(Level L, llvm::StringRef Message) { 250 if (CustomDiagInfo == 0) 251 CustomDiagInfo = new diag::CustomDiagInfo(); 252 return CustomDiagInfo->getOrCreateDiagID(L, Message, *this); 253} 254 255 256/// isBuiltinWarningOrExtension - Return true if the unmapped diagnostic 257/// level of the specified diagnostic ID is a Warning or Extension. 258/// This only works on builtin diagnostics, not custom ones, and is not legal to 259/// call on NOTEs. 260bool Diagnostic::isBuiltinWarningOrExtension(unsigned DiagID) { 261 return DiagID < diag::DIAG_UPPER_LIMIT && 262 getBuiltinDiagClass(DiagID) != CLASS_ERROR; 263} 264 265/// \brief Determine whether the given built-in diagnostic ID is a 266/// Note. 267bool Diagnostic::isBuiltinNote(unsigned DiagID) { 268 return DiagID < diag::DIAG_UPPER_LIMIT && 269 getBuiltinDiagClass(DiagID) == CLASS_NOTE; 270} 271 272/// isBuiltinExtensionDiag - Determine whether the given built-in diagnostic 273/// ID is for an extension of some sort. 274/// 275bool Diagnostic::isBuiltinExtensionDiag(unsigned DiagID) { 276 return DiagID < diag::DIAG_UPPER_LIMIT && 277 getBuiltinDiagClass(DiagID) == CLASS_EXTENSION; 278} 279 280 281/// getDescription - Given a diagnostic ID, return a description of the 282/// issue. 283const char *Diagnostic::getDescription(unsigned DiagID) const { 284 if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID)) 285 return Info->Description; 286 return CustomDiagInfo->getDescription(DiagID); 287} 288 289/// getDiagnosticLevel - Based on the way the client configured the Diagnostic 290/// object, classify the specified diagnostic ID into a Level, consumable by 291/// the DiagnosticClient. 292Diagnostic::Level Diagnostic::getDiagnosticLevel(unsigned DiagID) const { 293 // Handle custom diagnostics, which cannot be mapped. 294 if (DiagID >= diag::DIAG_UPPER_LIMIT) 295 return CustomDiagInfo->getLevel(DiagID); 296 297 unsigned DiagClass = getBuiltinDiagClass(DiagID); 298 assert(DiagClass != CLASS_NOTE && "Cannot get diagnostic level of a note!"); 299 return getDiagnosticLevel(DiagID, DiagClass); 300} 301 302/// getDiagnosticLevel - Based on the way the client configured the Diagnostic 303/// object, classify the specified diagnostic ID into a Level, consumable by 304/// the DiagnosticClient. 305Diagnostic::Level 306Diagnostic::getDiagnosticLevel(unsigned DiagID, unsigned DiagClass) const { 307 // Specific non-error diagnostics may be mapped to various levels from ignored 308 // to error. Errors can only be mapped to fatal. 309 Diagnostic::Level Result = Diagnostic::Fatal; 310 311 // Get the mapping information, if unset, compute it lazily. 312 unsigned MappingInfo = getDiagnosticMappingInfo((diag::kind)DiagID); 313 if (MappingInfo == 0) { 314 MappingInfo = GetDefaultDiagMapping(DiagID); 315 setDiagnosticMappingInternal(DiagID, MappingInfo, false); 316 } 317 318 switch (MappingInfo & 7) { 319 default: assert(0 && "Unknown mapping!"); 320 case diag::MAP_IGNORE: 321 // Ignore this, unless this is an extension diagnostic and we're mapping 322 // them onto warnings or errors. 323 if (!isBuiltinExtensionDiag(DiagID) || // Not an extension 324 ExtBehavior == Ext_Ignore || // Extensions ignored anyway 325 (MappingInfo & 8) != 0) // User explicitly mapped it. 326 return Diagnostic::Ignored; 327 Result = Diagnostic::Warning; 328 if (ExtBehavior == Ext_Error) Result = Diagnostic::Error; 329 break; 330 case diag::MAP_ERROR: 331 Result = Diagnostic::Error; 332 break; 333 case diag::MAP_FATAL: 334 Result = Diagnostic::Fatal; 335 break; 336 case diag::MAP_WARNING: 337 // If warnings are globally mapped to ignore or error, do it. 338 if (IgnoreAllWarnings) 339 return Diagnostic::Ignored; 340 341 Result = Diagnostic::Warning; 342 343 // If this is an extension diagnostic and we're in -pedantic-error mode, and 344 // if the user didn't explicitly map it, upgrade to an error. 345 if (ExtBehavior == Ext_Error && 346 (MappingInfo & 8) == 0 && 347 isBuiltinExtensionDiag(DiagID)) 348 Result = Diagnostic::Error; 349 350 if (WarningsAsErrors) 351 Result = Diagnostic::Error; 352 break; 353 354 case diag::MAP_WARNING_NO_WERROR: 355 // Diagnostics specified with -Wno-error=foo should be set to warnings, but 356 // not be adjusted by -Werror or -pedantic-errors. 357 Result = Diagnostic::Warning; 358 359 // If warnings are globally mapped to ignore or error, do it. 360 if (IgnoreAllWarnings) 361 return Diagnostic::Ignored; 362 363 break; 364 } 365 366 // Okay, we're about to return this as a "diagnostic to emit" one last check: 367 // if this is any sort of extension warning, and if we're in an __extension__ 368 // block, silence it. 369 if (AllExtensionsSilenced && isBuiltinExtensionDiag(DiagID)) 370 return Diagnostic::Ignored; 371 372 return Result; 373} 374 375struct WarningOption { 376 const char *Name; 377 const short *Members; 378 const char *SubGroups; 379}; 380 381#define GET_DIAG_ARRAYS 382#include "clang/Basic/DiagnosticGroups.inc" 383#undef GET_DIAG_ARRAYS 384 385// Second the table of options, sorted by name for fast binary lookup. 386static const WarningOption OptionTable[] = { 387#define GET_DIAG_TABLE 388#include "clang/Basic/DiagnosticGroups.inc" 389#undef GET_DIAG_TABLE 390}; 391static const size_t OptionTableSize = 392sizeof(OptionTable) / sizeof(OptionTable[0]); 393 394static bool WarningOptionCompare(const WarningOption &LHS, 395 const WarningOption &RHS) { 396 return strcmp(LHS.Name, RHS.Name) < 0; 397} 398 399static void MapGroupMembers(const WarningOption *Group, diag::Mapping Mapping, 400 Diagnostic &Diags) { 401 // Option exists, poke all the members of its diagnostic set. 402 if (const short *Member = Group->Members) { 403 for (; *Member != -1; ++Member) 404 Diags.setDiagnosticMapping(*Member, Mapping); 405 } 406 407 // Enable/disable all subgroups along with this one. 408 if (const char *SubGroups = Group->SubGroups) { 409 for (; *SubGroups != (char)-1; ++SubGroups) 410 MapGroupMembers(&OptionTable[(unsigned char)*SubGroups], Mapping, Diags); 411 } 412} 413 414/// setDiagnosticGroupMapping - Change an entire diagnostic group (e.g. 415/// "unknown-pragmas" to have the specified mapping. This returns true and 416/// ignores the request if "Group" was unknown, false otherwise. 417bool Diagnostic::setDiagnosticGroupMapping(const char *Group, 418 diag::Mapping Map) { 419 420 WarningOption Key = { Group, 0, 0 }; 421 const WarningOption *Found = 422 std::lower_bound(OptionTable, OptionTable + OptionTableSize, Key, 423 WarningOptionCompare); 424 if (Found == OptionTable + OptionTableSize || 425 strcmp(Found->Name, Group) != 0) 426 return true; // Option not found. 427 428 MapGroupMembers(Found, Map, *this); 429 return false; 430} 431 432 433/// ProcessDiag - This is the method used to report a diagnostic that is 434/// finally fully formed. 435bool Diagnostic::ProcessDiag() { 436 DiagnosticInfo Info(this); 437 438 if (SuppressAllDiagnostics) 439 return false; 440 441 // Figure out the diagnostic level of this message. 442 Diagnostic::Level DiagLevel; 443 unsigned DiagID = Info.getID(); 444 445 // ShouldEmitInSystemHeader - True if this diagnostic should be produced even 446 // in a system header. 447 bool ShouldEmitInSystemHeader; 448 449 if (DiagID >= diag::DIAG_UPPER_LIMIT) { 450 // Handle custom diagnostics, which cannot be mapped. 451 DiagLevel = CustomDiagInfo->getLevel(DiagID); 452 453 // Custom diagnostics always are emitted in system headers. 454 ShouldEmitInSystemHeader = true; 455 } else { 456 // Get the class of the diagnostic. If this is a NOTE, map it onto whatever 457 // the diagnostic level was for the previous diagnostic so that it is 458 // filtered the same as the previous diagnostic. 459 unsigned DiagClass = getBuiltinDiagClass(DiagID); 460 if (DiagClass == CLASS_NOTE) { 461 DiagLevel = Diagnostic::Note; 462 ShouldEmitInSystemHeader = false; // extra consideration is needed 463 } else { 464 // If this is not an error and we are in a system header, we ignore it. 465 // Check the original Diag ID here, because we also want to ignore 466 // extensions and warnings in -Werror and -pedantic-errors modes, which 467 // *map* warnings/extensions to errors. 468 ShouldEmitInSystemHeader = DiagClass == CLASS_ERROR; 469 470 DiagLevel = getDiagnosticLevel(DiagID, DiagClass); 471 } 472 } 473 474 if (DiagLevel != Diagnostic::Note) { 475 // Record that a fatal error occurred only when we see a second 476 // non-note diagnostic. This allows notes to be attached to the 477 // fatal error, but suppresses any diagnostics that follow those 478 // notes. 479 if (LastDiagLevel == Diagnostic::Fatal) 480 FatalErrorOccurred = true; 481 482 LastDiagLevel = DiagLevel; 483 } 484 485 // If a fatal error has already been emitted, silence all subsequent 486 // diagnostics. 487 if (FatalErrorOccurred) 488 return false; 489 490 // If the client doesn't care about this message, don't issue it. If this is 491 // a note and the last real diagnostic was ignored, ignore it too. 492 if (DiagLevel == Diagnostic::Ignored || 493 (DiagLevel == Diagnostic::Note && LastDiagLevel == Diagnostic::Ignored)) 494 return false; 495 496 // If this diagnostic is in a system header and is not a clang error, suppress 497 // it. 498 if (SuppressSystemWarnings && !ShouldEmitInSystemHeader && 499 Info.getLocation().isValid() && 500 Info.getLocation().getSpellingLoc().isInSystemHeader() && 501 (DiagLevel != Diagnostic::Note || LastDiagLevel == Diagnostic::Ignored)) { 502 LastDiagLevel = Diagnostic::Ignored; 503 return false; 504 } 505 506 if (DiagLevel >= Diagnostic::Error) { 507 ErrorOccurred = true; 508 ++NumErrors; 509 } 510 511 // Finally, report it. 512 Client->HandleDiagnostic(DiagLevel, Info); 513 if (Client->IncludeInDiagnosticCounts()) ++NumDiagnostics; 514 515 CurDiagID = ~0U; 516 517 return true; 518} 519 520 521DiagnosticClient::~DiagnosticClient() {} 522 523 524/// ModifierIs - Return true if the specified modifier matches specified string. 525template <std::size_t StrLen> 526static bool ModifierIs(const char *Modifier, unsigned ModifierLen, 527 const char (&Str)[StrLen]) { 528 return StrLen-1 == ModifierLen && !memcmp(Modifier, Str, StrLen-1); 529} 530 531/// HandleSelectModifier - Handle the integer 'select' modifier. This is used 532/// like this: %select{foo|bar|baz}2. This means that the integer argument 533/// "%2" has a value from 0-2. If the value is 0, the diagnostic prints 'foo'. 534/// If the value is 1, it prints 'bar'. If it has the value 2, it prints 'baz'. 535/// This is very useful for certain classes of variant diagnostics. 536static void HandleSelectModifier(unsigned ValNo, 537 const char *Argument, unsigned ArgumentLen, 538 llvm::SmallVectorImpl<char> &OutStr) { 539 const char *ArgumentEnd = Argument+ArgumentLen; 540 541 // Skip over 'ValNo' |'s. 542 while (ValNo) { 543 const char *NextVal = std::find(Argument, ArgumentEnd, '|'); 544 assert(NextVal != ArgumentEnd && "Value for integer select modifier was" 545 " larger than the number of options in the diagnostic string!"); 546 Argument = NextVal+1; // Skip this string. 547 --ValNo; 548 } 549 550 // Get the end of the value. This is either the } or the |. 551 const char *EndPtr = std::find(Argument, ArgumentEnd, '|'); 552 // Add the value to the output string. 553 OutStr.append(Argument, EndPtr); 554} 555 556/// HandleIntegerSModifier - Handle the integer 's' modifier. This adds the 557/// letter 's' to the string if the value is not 1. This is used in cases like 558/// this: "you idiot, you have %4 parameter%s4!". 559static void HandleIntegerSModifier(unsigned ValNo, 560 llvm::SmallVectorImpl<char> &OutStr) { 561 if (ValNo != 1) 562 OutStr.push_back('s'); 563} 564 565 566/// PluralNumber - Parse an unsigned integer and advance Start. 567static unsigned PluralNumber(const char *&Start, const char *End) { 568 // Programming 101: Parse a decimal number :-) 569 unsigned Val = 0; 570 while (Start != End && *Start >= '0' && *Start <= '9') { 571 Val *= 10; 572 Val += *Start - '0'; 573 ++Start; 574 } 575 return Val; 576} 577 578/// TestPluralRange - Test if Val is in the parsed range. Modifies Start. 579static bool TestPluralRange(unsigned Val, const char *&Start, const char *End) { 580 if (*Start != '[') { 581 unsigned Ref = PluralNumber(Start, End); 582 return Ref == Val; 583 } 584 585 ++Start; 586 unsigned Low = PluralNumber(Start, End); 587 assert(*Start == ',' && "Bad plural expression syntax: expected ,"); 588 ++Start; 589 unsigned High = PluralNumber(Start, End); 590 assert(*Start == ']' && "Bad plural expression syntax: expected )"); 591 ++Start; 592 return Low <= Val && Val <= High; 593} 594 595/// EvalPluralExpr - Actual expression evaluator for HandlePluralModifier. 596static bool EvalPluralExpr(unsigned ValNo, const char *Start, const char *End) { 597 // Empty condition? 598 if (*Start == ':') 599 return true; 600 601 while (1) { 602 char C = *Start; 603 if (C == '%') { 604 // Modulo expression 605 ++Start; 606 unsigned Arg = PluralNumber(Start, End); 607 assert(*Start == '=' && "Bad plural expression syntax: expected ="); 608 ++Start; 609 unsigned ValMod = ValNo % Arg; 610 if (TestPluralRange(ValMod, Start, End)) 611 return true; 612 } else { 613 assert((C == '[' || (C >= '0' && C <= '9')) && 614 "Bad plural expression syntax: unexpected character"); 615 // Range expression 616 if (TestPluralRange(ValNo, Start, End)) 617 return true; 618 } 619 620 // Scan for next or-expr part. 621 Start = std::find(Start, End, ','); 622 if (Start == End) 623 break; 624 ++Start; 625 } 626 return false; 627} 628 629/// HandlePluralModifier - Handle the integer 'plural' modifier. This is used 630/// for complex plural forms, or in languages where all plurals are complex. 631/// The syntax is: %plural{cond1:form1|cond2:form2|:form3}, where condn are 632/// conditions that are tested in order, the form corresponding to the first 633/// that applies being emitted. The empty condition is always true, making the 634/// last form a default case. 635/// Conditions are simple boolean expressions, where n is the number argument. 636/// Here are the rules. 637/// condition := expression | empty 638/// empty := -> always true 639/// expression := numeric [',' expression] -> logical or 640/// numeric := range -> true if n in range 641/// | '%' number '=' range -> true if n % number in range 642/// range := number 643/// | '[' number ',' number ']' -> ranges are inclusive both ends 644/// 645/// Here are some examples from the GNU gettext manual written in this form: 646/// English: 647/// {1:form0|:form1} 648/// Latvian: 649/// {0:form2|%100=11,%10=0,%10=[2,9]:form1|:form0} 650/// Gaeilge: 651/// {1:form0|2:form1|:form2} 652/// Romanian: 653/// {1:form0|0,%100=[1,19]:form1|:form2} 654/// Lithuanian: 655/// {%10=0,%100=[10,19]:form2|%10=1:form0|:form1} 656/// Russian (requires repeated form): 657/// {%100=[11,14]:form2|%10=1:form0|%10=[2,4]:form1|:form2} 658/// Slovak 659/// {1:form0|[2,4]:form1|:form2} 660/// Polish (requires repeated form): 661/// {1:form0|%100=[10,20]:form2|%10=[2,4]:form1|:form2} 662static void HandlePluralModifier(unsigned ValNo, 663 const char *Argument, unsigned ArgumentLen, 664 llvm::SmallVectorImpl<char> &OutStr) { 665 const char *ArgumentEnd = Argument + ArgumentLen; 666 while (1) { 667 assert(Argument < ArgumentEnd && "Plural expression didn't match."); 668 const char *ExprEnd = Argument; 669 while (*ExprEnd != ':') { 670 assert(ExprEnd != ArgumentEnd && "Plural missing expression end"); 671 ++ExprEnd; 672 } 673 if (EvalPluralExpr(ValNo, Argument, ExprEnd)) { 674 Argument = ExprEnd + 1; 675 ExprEnd = std::find(Argument, ArgumentEnd, '|'); 676 OutStr.append(Argument, ExprEnd); 677 return; 678 } 679 Argument = std::find(Argument, ArgumentEnd - 1, '|') + 1; 680 } 681} 682 683 684/// FormatDiagnostic - Format this diagnostic into a string, substituting the 685/// formal arguments into the %0 slots. The result is appended onto the Str 686/// array. 687void DiagnosticInfo:: 688FormatDiagnostic(llvm::SmallVectorImpl<char> &OutStr) const { 689 const char *DiagStr = getDiags()->getDescription(getID()); 690 const char *DiagEnd = DiagStr+strlen(DiagStr); 691 692 /// FormattedArgs - Keep track of all of the arguments formatted by 693 /// ConvertArgToString and pass them into subsequent calls to 694 /// ConvertArgToString, allowing the implementation to avoid redundancies in 695 /// obvious cases. 696 llvm::SmallVector<Diagnostic::ArgumentValue, 8> FormattedArgs; 697 698 while (DiagStr != DiagEnd) { 699 if (DiagStr[0] != '%') { 700 // Append non-%0 substrings to Str if we have one. 701 const char *StrEnd = std::find(DiagStr, DiagEnd, '%'); 702 OutStr.append(DiagStr, StrEnd); 703 DiagStr = StrEnd; 704 continue; 705 } else if (DiagStr[1] == '%') { 706 OutStr.push_back('%'); // %% -> %. 707 DiagStr += 2; 708 continue; 709 } 710 711 // Skip the %. 712 ++DiagStr; 713 714 // This must be a placeholder for a diagnostic argument. The format for a 715 // placeholder is one of "%0", "%modifier0", or "%modifier{arguments}0". 716 // The digit is a number from 0-9 indicating which argument this comes from. 717 // The modifier is a string of digits from the set [-a-z]+, arguments is a 718 // brace enclosed string. 719 const char *Modifier = 0, *Argument = 0; 720 unsigned ModifierLen = 0, ArgumentLen = 0; 721 722 // Check to see if we have a modifier. If so eat it. 723 if (!isdigit(DiagStr[0])) { 724 Modifier = DiagStr; 725 while (DiagStr[0] == '-' || 726 (DiagStr[0] >= 'a' && DiagStr[0] <= 'z')) 727 ++DiagStr; 728 ModifierLen = DiagStr-Modifier; 729 730 // If we have an argument, get it next. 731 if (DiagStr[0] == '{') { 732 ++DiagStr; // Skip {. 733 Argument = DiagStr; 734 735 for (; DiagStr[0] != '}'; ++DiagStr) 736 assert(DiagStr[0] && "Mismatched {}'s in diagnostic string!"); 737 ArgumentLen = DiagStr-Argument; 738 ++DiagStr; // Skip }. 739 } 740 } 741 742 assert(isdigit(*DiagStr) && "Invalid format for argument in diagnostic"); 743 unsigned ArgNo = *DiagStr++ - '0'; 744 745 Diagnostic::ArgumentKind Kind = getArgKind(ArgNo); 746 747 switch (Kind) { 748 // ---- STRINGS ---- 749 case Diagnostic::ak_std_string: { 750 const std::string &S = getArgStdStr(ArgNo); 751 assert(ModifierLen == 0 && "No modifiers for strings yet"); 752 OutStr.append(S.begin(), S.end()); 753 break; 754 } 755 case Diagnostic::ak_c_string: { 756 const char *S = getArgCStr(ArgNo); 757 assert(ModifierLen == 0 && "No modifiers for strings yet"); 758 759 // Don't crash if get passed a null pointer by accident. 760 if (!S) 761 S = "(null)"; 762 763 OutStr.append(S, S + strlen(S)); 764 break; 765 } 766 // ---- INTEGERS ---- 767 case Diagnostic::ak_sint: { 768 int Val = getArgSInt(ArgNo); 769 770 if (ModifierIs(Modifier, ModifierLen, "select")) { 771 HandleSelectModifier((unsigned)Val, Argument, ArgumentLen, OutStr); 772 } else if (ModifierIs(Modifier, ModifierLen, "s")) { 773 HandleIntegerSModifier(Val, OutStr); 774 } else if (ModifierIs(Modifier, ModifierLen, "plural")) { 775 HandlePluralModifier((unsigned)Val, Argument, ArgumentLen, OutStr); 776 } else { 777 assert(ModifierLen == 0 && "Unknown integer modifier"); 778 llvm::raw_svector_ostream(OutStr) << Val; 779 } 780 break; 781 } 782 case Diagnostic::ak_uint: { 783 unsigned Val = getArgUInt(ArgNo); 784 785 if (ModifierIs(Modifier, ModifierLen, "select")) { 786 HandleSelectModifier(Val, Argument, ArgumentLen, OutStr); 787 } else if (ModifierIs(Modifier, ModifierLen, "s")) { 788 HandleIntegerSModifier(Val, OutStr); 789 } else if (ModifierIs(Modifier, ModifierLen, "plural")) { 790 HandlePluralModifier((unsigned)Val, Argument, ArgumentLen, OutStr); 791 } else { 792 assert(ModifierLen == 0 && "Unknown integer modifier"); 793 llvm::raw_svector_ostream(OutStr) << Val; 794 } 795 break; 796 } 797 // ---- NAMES and TYPES ---- 798 case Diagnostic::ak_identifierinfo: { 799 const IdentifierInfo *II = getArgIdentifier(ArgNo); 800 assert(ModifierLen == 0 && "No modifiers for strings yet"); 801 802 // Don't crash if get passed a null pointer by accident. 803 if (!II) { 804 const char *S = "(null)"; 805 OutStr.append(S, S + strlen(S)); 806 continue; 807 } 808 809 llvm::raw_svector_ostream(OutStr) << '\'' << II->getName() << '\''; 810 break; 811 } 812 case Diagnostic::ak_qualtype: 813 case Diagnostic::ak_declarationname: 814 case Diagnostic::ak_nameddecl: 815 case Diagnostic::ak_nestednamespec: 816 case Diagnostic::ak_declcontext: 817 getDiags()->ConvertArgToString(Kind, getRawArg(ArgNo), 818 Modifier, ModifierLen, 819 Argument, ArgumentLen, 820 FormattedArgs.data(), FormattedArgs.size(), 821 OutStr); 822 break; 823 } 824 825 // Remember this argument info for subsequent formatting operations. Turn 826 // std::strings into a null terminated string to make it be the same case as 827 // all the other ones. 828 if (Kind != Diagnostic::ak_std_string) 829 FormattedArgs.push_back(std::make_pair(Kind, getRawArg(ArgNo))); 830 else 831 FormattedArgs.push_back(std::make_pair(Diagnostic::ak_c_string, 832 (intptr_t)getArgStdStr(ArgNo).c_str())); 833 834 } 835} 836 837/// IncludeInDiagnosticCounts - This method (whose default implementation 838/// returns true) indicates whether the diagnostics handled by this 839/// DiagnosticClient should be included in the number of diagnostics 840/// reported by Diagnostic. 841bool DiagnosticClient::IncludeInDiagnosticCounts() const { return true; } 842