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