Diagnostic.cpp revision 651f13cea278ec967336033dd032faef0e9fc2ec
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/CharInfo.h" 15#include "clang/Basic/Diagnostic.h" 16#include "clang/Basic/DiagnosticOptions.h" 17#include "clang/Basic/IdentifierTable.h" 18#include "clang/Basic/PartialDiagnostic.h" 19#include "llvm/ADT/SmallString.h" 20#include "llvm/ADT/StringExtras.h" 21#include "llvm/Support/CrashRecoveryContext.h" 22#include "llvm/Support/raw_ostream.h" 23 24using namespace clang; 25 26static void DummyArgToStringFn(DiagnosticsEngine::ArgumentKind AK, intptr_t QT, 27 const char *Modifier, unsigned ML, 28 const char *Argument, unsigned ArgLen, 29 const DiagnosticsEngine::ArgumentValue *PrevArgs, 30 unsigned NumPrevArgs, 31 SmallVectorImpl<char> &Output, 32 void *Cookie, 33 ArrayRef<intptr_t> QualTypeVals) { 34 const char *Str = "<can't format argument>"; 35 Output.append(Str, Str+strlen(Str)); 36} 37 38 39DiagnosticsEngine::DiagnosticsEngine( 40 const IntrusiveRefCntPtr<DiagnosticIDs> &diags, 41 DiagnosticOptions *DiagOpts, 42 DiagnosticConsumer *client, bool ShouldOwnClient) 43 : Diags(diags), DiagOpts(DiagOpts), Client(client), 44 OwnsDiagClient(ShouldOwnClient), SourceMgr(0) { 45 ArgToStringFn = DummyArgToStringFn; 46 ArgToStringCookie = 0; 47 48 AllExtensionsSilenced = 0; 49 IgnoreAllWarnings = false; 50 WarningsAsErrors = false; 51 EnableAllWarnings = false; 52 ErrorsAsFatal = false; 53 SuppressSystemWarnings = false; 54 SuppressAllDiagnostics = false; 55 ElideType = true; 56 PrintTemplateTree = false; 57 ShowColors = false; 58 ShowOverloads = Ovl_All; 59 ExtBehavior = Ext_Ignore; 60 61 ErrorLimit = 0; 62 TemplateBacktraceLimit = 0; 63 ConstexprBacktraceLimit = 0; 64 65 Reset(); 66} 67 68DiagnosticsEngine::~DiagnosticsEngine() { 69 if (OwnsDiagClient) 70 delete Client; 71} 72 73void DiagnosticsEngine::setClient(DiagnosticConsumer *client, 74 bool ShouldOwnClient) { 75 if (OwnsDiagClient && Client) 76 delete Client; 77 78 Client = client; 79 OwnsDiagClient = ShouldOwnClient; 80} 81 82void DiagnosticsEngine::pushMappings(SourceLocation Loc) { 83 DiagStateOnPushStack.push_back(GetCurDiagState()); 84} 85 86bool DiagnosticsEngine::popMappings(SourceLocation Loc) { 87 if (DiagStateOnPushStack.empty()) 88 return false; 89 90 if (DiagStateOnPushStack.back() != GetCurDiagState()) { 91 // State changed at some point between push/pop. 92 PushDiagStatePoint(DiagStateOnPushStack.back(), Loc); 93 } 94 DiagStateOnPushStack.pop_back(); 95 return true; 96} 97 98void DiagnosticsEngine::Reset() { 99 ErrorOccurred = false; 100 UncompilableErrorOccurred = false; 101 FatalErrorOccurred = false; 102 UnrecoverableErrorOccurred = false; 103 104 NumWarnings = 0; 105 NumErrors = 0; 106 NumErrorsSuppressed = 0; 107 TrapNumErrorsOccurred = 0; 108 TrapNumUnrecoverableErrorsOccurred = 0; 109 110 CurDiagID = ~0U; 111 LastDiagLevel = DiagnosticIDs::Ignored; 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 assert(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 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 248bool DiagnosticsEngine::setDiagnosticGroupWarningAsError(StringRef Group, 249 bool Enabled) { 250 // If we are enabling this feature, just set the diagnostic mappings to map to 251 // errors. 252 if (Enabled) 253 return setDiagnosticGroupMapping(Group, diag::MAP_ERROR); 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 258 // Get the diagnostics in this group. 259 SmallVector<diag::kind, 8> GroupDiags; 260 if (Diags->getDiagnosticsInGroup(Group, GroupDiags)) 261 return true; 262 263 // Perform the mapping change. 264 for (unsigned i = 0, e = GroupDiags.size(); i != e; ++i) { 265 DiagnosticMappingInfo &Info = GetCurDiagState()->getOrAddMappingInfo( 266 GroupDiags[i]); 267 268 if (Info.getMapping() == diag::MAP_ERROR || 269 Info.getMapping() == diag::MAP_FATAL) 270 Info.setMapping(diag::MAP_WARNING); 271 272 Info.setNoWarningAsError(true); 273 } 274 275 return false; 276} 277 278bool DiagnosticsEngine::setDiagnosticGroupErrorAsFatal(StringRef Group, 279 bool Enabled) { 280 // If we are enabling this feature, just set the diagnostic mappings to map to 281 // fatal errors. 282 if (Enabled) 283 return setDiagnosticGroupMapping(Group, diag::MAP_FATAL); 284 285 // Otherwise, we want to set the diagnostic mapping's "no Werror" bit, and 286 // potentially downgrade anything already mapped to be an error. 287 288 // Get the diagnostics in this group. 289 SmallVector<diag::kind, 8> GroupDiags; 290 if (Diags->getDiagnosticsInGroup(Group, GroupDiags)) 291 return true; 292 293 // Perform the mapping change. 294 for (unsigned i = 0, e = GroupDiags.size(); i != e; ++i) { 295 DiagnosticMappingInfo &Info = GetCurDiagState()->getOrAddMappingInfo( 296 GroupDiags[i]); 297 298 if (Info.getMapping() == diag::MAP_FATAL) 299 Info.setMapping(diag::MAP_ERROR); 300 301 Info.setNoErrorAsFatal(true); 302 } 303 304 return false; 305} 306 307void DiagnosticsEngine::setMappingToAllDiagnostics(diag::Mapping Map, 308 SourceLocation Loc) { 309 // Get all the diagnostics. 310 SmallVector<diag::kind, 64> AllDiags; 311 Diags->getAllDiagnostics(AllDiags); 312 313 // Set the mapping. 314 for (unsigned i = 0, e = AllDiags.size(); i != e; ++i) 315 if (Diags->isBuiltinWarningOrExtension(AllDiags[i])) 316 setDiagnosticMapping(AllDiags[i], Map, Loc); 317} 318 319void DiagnosticsEngine::Report(const StoredDiagnostic &storedDiag) { 320 assert(CurDiagID == ~0U && "Multiple diagnostics in flight at once!"); 321 322 CurDiagLoc = storedDiag.getLocation(); 323 CurDiagID = storedDiag.getID(); 324 NumDiagArgs = 0; 325 326 NumDiagRanges = storedDiag.range_size(); 327 assert(NumDiagRanges < DiagnosticsEngine::MaxRanges && 328 "Too many arguments to diagnostic!"); 329 unsigned i = 0; 330 for (StoredDiagnostic::range_iterator 331 RI = storedDiag.range_begin(), 332 RE = storedDiag.range_end(); RI != RE; ++RI) 333 DiagRanges[i++] = *RI; 334 335 assert(NumDiagRanges < DiagnosticsEngine::MaxFixItHints && 336 "Too many arguments to diagnostic!"); 337 NumDiagFixItHints = 0; 338 for (StoredDiagnostic::fixit_iterator 339 FI = storedDiag.fixit_begin(), 340 FE = storedDiag.fixit_end(); FI != FE; ++FI) 341 DiagFixItHints[NumDiagFixItHints++] = *FI; 342 343 assert(Client && "DiagnosticConsumer not set!"); 344 Level DiagLevel = storedDiag.getLevel(); 345 Diagnostic Info(this, storedDiag.getMessage()); 346 Client->HandleDiagnostic(DiagLevel, Info); 347 if (Client->IncludeInDiagnosticCounts()) { 348 if (DiagLevel == DiagnosticsEngine::Warning) 349 ++NumWarnings; 350 } 351 352 CurDiagID = ~0U; 353} 354 355bool DiagnosticsEngine::EmitCurrentDiagnostic(bool Force) { 356 assert(getClient() && "DiagnosticClient not set!"); 357 358 bool Emitted; 359 if (Force) { 360 Diagnostic Info(this); 361 362 // Figure out the diagnostic level of this message. 363 DiagnosticIDs::Level DiagLevel 364 = Diags->getDiagnosticLevel(Info.getID(), Info.getLocation(), *this); 365 366 Emitted = (DiagLevel != DiagnosticIDs::Ignored); 367 if (Emitted) { 368 // Emit the diagnostic regardless of suppression level. 369 Diags->EmitDiag(*this, DiagLevel); 370 } 371 } else { 372 // Process the diagnostic, sending the accumulated information to the 373 // DiagnosticConsumer. 374 Emitted = ProcessDiag(); 375 } 376 377 // Clear out the current diagnostic object. 378 unsigned DiagID = CurDiagID; 379 Clear(); 380 381 // If there was a delayed diagnostic, emit it now. 382 if (!Force && DelayedDiagID && DelayedDiagID != DiagID) 383 ReportDelayed(); 384 385 return Emitted; 386} 387 388 389DiagnosticConsumer::~DiagnosticConsumer() {} 390 391void DiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, 392 const Diagnostic &Info) { 393 if (!IncludeInDiagnosticCounts()) 394 return; 395 396 if (DiagLevel == DiagnosticsEngine::Warning) 397 ++NumWarnings; 398 else if (DiagLevel >= DiagnosticsEngine::Error) 399 ++NumErrors; 400} 401 402/// ModifierIs - Return true if the specified modifier matches specified string. 403template <std::size_t StrLen> 404static bool ModifierIs(const char *Modifier, unsigned ModifierLen, 405 const char (&Str)[StrLen]) { 406 return StrLen-1 == ModifierLen && !memcmp(Modifier, Str, StrLen-1); 407} 408 409/// ScanForward - Scans forward, looking for the given character, skipping 410/// nested clauses and escaped characters. 411static const char *ScanFormat(const char *I, const char *E, char Target) { 412 unsigned Depth = 0; 413 414 for ( ; I != E; ++I) { 415 if (Depth == 0 && *I == Target) return I; 416 if (Depth != 0 && *I == '}') Depth--; 417 418 if (*I == '%') { 419 I++; 420 if (I == E) break; 421 422 // Escaped characters get implicitly skipped here. 423 424 // Format specifier. 425 if (!isDigit(*I) && !isPunctuation(*I)) { 426 for (I++; I != E && !isDigit(*I) && *I != '{'; I++) ; 427 if (I == E) break; 428 if (*I == '{') 429 Depth++; 430 } 431 } 432 } 433 return E; 434} 435 436/// HandleSelectModifier - Handle the integer 'select' modifier. This is used 437/// like this: %select{foo|bar|baz}2. This means that the integer argument 438/// "%2" has a value from 0-2. If the value is 0, the diagnostic prints 'foo'. 439/// If the value is 1, it prints 'bar'. If it has the value 2, it prints 'baz'. 440/// This is very useful for certain classes of variant diagnostics. 441static void HandleSelectModifier(const Diagnostic &DInfo, unsigned ValNo, 442 const char *Argument, unsigned ArgumentLen, 443 SmallVectorImpl<char> &OutStr) { 444 const char *ArgumentEnd = Argument+ArgumentLen; 445 446 // Skip over 'ValNo' |'s. 447 while (ValNo) { 448 const char *NextVal = ScanFormat(Argument, ArgumentEnd, '|'); 449 assert(NextVal != ArgumentEnd && "Value for integer select modifier was" 450 " larger than the number of options in the diagnostic string!"); 451 Argument = NextVal+1; // Skip this string. 452 --ValNo; 453 } 454 455 // Get the end of the value. This is either the } or the |. 456 const char *EndPtr = ScanFormat(Argument, ArgumentEnd, '|'); 457 458 // Recursively format the result of the select clause into the output string. 459 DInfo.FormatDiagnostic(Argument, EndPtr, OutStr); 460} 461 462/// HandleIntegerSModifier - Handle the integer 's' modifier. This adds the 463/// letter 's' to the string if the value is not 1. This is used in cases like 464/// this: "you idiot, you have %4 parameter%s4!". 465static void HandleIntegerSModifier(unsigned ValNo, 466 SmallVectorImpl<char> &OutStr) { 467 if (ValNo != 1) 468 OutStr.push_back('s'); 469} 470 471/// HandleOrdinalModifier - Handle the integer 'ord' modifier. This 472/// prints the ordinal form of the given integer, with 1 corresponding 473/// to the first ordinal. Currently this is hard-coded to use the 474/// English form. 475static void HandleOrdinalModifier(unsigned ValNo, 476 SmallVectorImpl<char> &OutStr) { 477 assert(ValNo != 0 && "ValNo must be strictly positive!"); 478 479 llvm::raw_svector_ostream Out(OutStr); 480 481 // We could use text forms for the first N ordinals, but the numeric 482 // forms are actually nicer in diagnostics because they stand out. 483 Out << ValNo << llvm::getOrdinalSuffix(ValNo); 484} 485 486 487/// PluralNumber - Parse an unsigned integer and advance Start. 488static unsigned PluralNumber(const char *&Start, const char *End) { 489 // Programming 101: Parse a decimal number :-) 490 unsigned Val = 0; 491 while (Start != End && *Start >= '0' && *Start <= '9') { 492 Val *= 10; 493 Val += *Start - '0'; 494 ++Start; 495 } 496 return Val; 497} 498 499/// TestPluralRange - Test if Val is in the parsed range. Modifies Start. 500static bool TestPluralRange(unsigned Val, const char *&Start, const char *End) { 501 if (*Start != '[') { 502 unsigned Ref = PluralNumber(Start, End); 503 return Ref == Val; 504 } 505 506 ++Start; 507 unsigned Low = PluralNumber(Start, End); 508 assert(*Start == ',' && "Bad plural expression syntax: expected ,"); 509 ++Start; 510 unsigned High = PluralNumber(Start, End); 511 assert(*Start == ']' && "Bad plural expression syntax: expected )"); 512 ++Start; 513 return Low <= Val && Val <= High; 514} 515 516/// EvalPluralExpr - Actual expression evaluator for HandlePluralModifier. 517static bool EvalPluralExpr(unsigned ValNo, const char *Start, const char *End) { 518 // Empty condition? 519 if (*Start == ':') 520 return true; 521 522 while (1) { 523 char C = *Start; 524 if (C == '%') { 525 // Modulo expression 526 ++Start; 527 unsigned Arg = PluralNumber(Start, End); 528 assert(*Start == '=' && "Bad plural expression syntax: expected ="); 529 ++Start; 530 unsigned ValMod = ValNo % Arg; 531 if (TestPluralRange(ValMod, Start, End)) 532 return true; 533 } else { 534 assert((C == '[' || (C >= '0' && C <= '9')) && 535 "Bad plural expression syntax: unexpected character"); 536 // Range expression 537 if (TestPluralRange(ValNo, Start, End)) 538 return true; 539 } 540 541 // Scan for next or-expr part. 542 Start = std::find(Start, End, ','); 543 if (Start == End) 544 break; 545 ++Start; 546 } 547 return false; 548} 549 550/// HandlePluralModifier - Handle the integer 'plural' modifier. This is used 551/// for complex plural forms, or in languages where all plurals are complex. 552/// The syntax is: %plural{cond1:form1|cond2:form2|:form3}, where condn are 553/// conditions that are tested in order, the form corresponding to the first 554/// that applies being emitted. The empty condition is always true, making the 555/// last form a default case. 556/// Conditions are simple boolean expressions, where n is the number argument. 557/// Here are the rules. 558/// condition := expression | empty 559/// empty := -> always true 560/// expression := numeric [',' expression] -> logical or 561/// numeric := range -> true if n in range 562/// | '%' number '=' range -> true if n % number in range 563/// range := number 564/// | '[' number ',' number ']' -> ranges are inclusive both ends 565/// 566/// Here are some examples from the GNU gettext manual written in this form: 567/// English: 568/// {1:form0|:form1} 569/// Latvian: 570/// {0:form2|%100=11,%10=0,%10=[2,9]:form1|:form0} 571/// Gaeilge: 572/// {1:form0|2:form1|:form2} 573/// Romanian: 574/// {1:form0|0,%100=[1,19]:form1|:form2} 575/// Lithuanian: 576/// {%10=0,%100=[10,19]:form2|%10=1:form0|:form1} 577/// Russian (requires repeated form): 578/// {%100=[11,14]:form2|%10=1:form0|%10=[2,4]:form1|:form2} 579/// Slovak 580/// {1:form0|[2,4]:form1|:form2} 581/// Polish (requires repeated form): 582/// {1:form0|%100=[10,20]:form2|%10=[2,4]:form1|:form2} 583static void HandlePluralModifier(const Diagnostic &DInfo, unsigned ValNo, 584 const char *Argument, unsigned ArgumentLen, 585 SmallVectorImpl<char> &OutStr) { 586 const char *ArgumentEnd = Argument + ArgumentLen; 587 while (1) { 588 assert(Argument < ArgumentEnd && "Plural expression didn't match."); 589 const char *ExprEnd = Argument; 590 while (*ExprEnd != ':') { 591 assert(ExprEnd != ArgumentEnd && "Plural missing expression end"); 592 ++ExprEnd; 593 } 594 if (EvalPluralExpr(ValNo, Argument, ExprEnd)) { 595 Argument = ExprEnd + 1; 596 ExprEnd = ScanFormat(Argument, ArgumentEnd, '|'); 597 598 // Recursively format the result of the plural clause into the 599 // output string. 600 DInfo.FormatDiagnostic(Argument, ExprEnd, OutStr); 601 return; 602 } 603 Argument = ScanFormat(Argument, ArgumentEnd - 1, '|') + 1; 604 } 605} 606 607/// \brief Returns the friendly description for a token kind that will appear 608/// without quotes in diagnostic messages. These strings may be translatable in 609/// future. 610static const char *getTokenDescForDiagnostic(tok::TokenKind Kind) { 611 switch (Kind) { 612 case tok::identifier: 613 return "identifier"; 614 default: 615 return 0; 616 } 617} 618 619/// FormatDiagnostic - Format this diagnostic into a string, substituting the 620/// formal arguments into the %0 slots. The result is appended onto the Str 621/// array. 622void Diagnostic:: 623FormatDiagnostic(SmallVectorImpl<char> &OutStr) const { 624 if (!StoredDiagMessage.empty()) { 625 OutStr.append(StoredDiagMessage.begin(), StoredDiagMessage.end()); 626 return; 627 } 628 629 StringRef Diag = 630 getDiags()->getDiagnosticIDs()->getDescription(getID()); 631 632 FormatDiagnostic(Diag.begin(), Diag.end(), OutStr); 633} 634 635void Diagnostic:: 636FormatDiagnostic(const char *DiagStr, const char *DiagEnd, 637 SmallVectorImpl<char> &OutStr) const { 638 639 /// FormattedArgs - Keep track of all of the arguments formatted by 640 /// ConvertArgToString and pass them into subsequent calls to 641 /// ConvertArgToString, allowing the implementation to avoid redundancies in 642 /// obvious cases. 643 SmallVector<DiagnosticsEngine::ArgumentValue, 8> FormattedArgs; 644 645 /// QualTypeVals - Pass a vector of arrays so that QualType names can be 646 /// compared to see if more information is needed to be printed. 647 SmallVector<intptr_t, 2> QualTypeVals; 648 SmallVector<char, 64> Tree; 649 650 for (unsigned i = 0, e = getNumArgs(); i < e; ++i) 651 if (getArgKind(i) == DiagnosticsEngine::ak_qualtype) 652 QualTypeVals.push_back(getRawArg(i)); 653 654 while (DiagStr != DiagEnd) { 655 if (DiagStr[0] != '%') { 656 // Append non-%0 substrings to Str if we have one. 657 const char *StrEnd = std::find(DiagStr, DiagEnd, '%'); 658 OutStr.append(DiagStr, StrEnd); 659 DiagStr = StrEnd; 660 continue; 661 } else if (isPunctuation(DiagStr[1])) { 662 OutStr.push_back(DiagStr[1]); // %% -> %. 663 DiagStr += 2; 664 continue; 665 } 666 667 // Skip the %. 668 ++DiagStr; 669 670 // This must be a placeholder for a diagnostic argument. The format for a 671 // placeholder is one of "%0", "%modifier0", or "%modifier{arguments}0". 672 // The digit is a number from 0-9 indicating which argument this comes from. 673 // The modifier is a string of digits from the set [-a-z]+, arguments is a 674 // brace enclosed string. 675 const char *Modifier = 0, *Argument = 0; 676 unsigned ModifierLen = 0, ArgumentLen = 0; 677 678 // Check to see if we have a modifier. If so eat it. 679 if (!isDigit(DiagStr[0])) { 680 Modifier = DiagStr; 681 while (DiagStr[0] == '-' || 682 (DiagStr[0] >= 'a' && DiagStr[0] <= 'z')) 683 ++DiagStr; 684 ModifierLen = DiagStr-Modifier; 685 686 // If we have an argument, get it next. 687 if (DiagStr[0] == '{') { 688 ++DiagStr; // Skip {. 689 Argument = DiagStr; 690 691 DiagStr = ScanFormat(DiagStr, DiagEnd, '}'); 692 assert(DiagStr != DiagEnd && "Mismatched {}'s in diagnostic string!"); 693 ArgumentLen = DiagStr-Argument; 694 ++DiagStr; // Skip }. 695 } 696 } 697 698 assert(isDigit(*DiagStr) && "Invalid format for argument in diagnostic"); 699 unsigned ArgNo = *DiagStr++ - '0'; 700 701 // Only used for type diffing. 702 unsigned ArgNo2 = ArgNo; 703 704 DiagnosticsEngine::ArgumentKind Kind = getArgKind(ArgNo); 705 if (ModifierIs(Modifier, ModifierLen, "diff")) { 706 assert(*DiagStr == ',' && isDigit(*(DiagStr + 1)) && 707 "Invalid format for diff modifier"); 708 ++DiagStr; // Comma. 709 ArgNo2 = *DiagStr++ - '0'; 710 DiagnosticsEngine::ArgumentKind Kind2 = getArgKind(ArgNo2); 711 if (Kind == DiagnosticsEngine::ak_qualtype && 712 Kind2 == DiagnosticsEngine::ak_qualtype) 713 Kind = DiagnosticsEngine::ak_qualtype_pair; 714 else { 715 // %diff only supports QualTypes. For other kinds of arguments, 716 // use the default printing. For example, if the modifier is: 717 // "%diff{compare $ to $|other text}1,2" 718 // treat it as: 719 // "compare %1 to %2" 720 const char *Pipe = ScanFormat(Argument, Argument + ArgumentLen, '|'); 721 const char *FirstDollar = ScanFormat(Argument, Pipe, '$'); 722 const char *SecondDollar = ScanFormat(FirstDollar + 1, Pipe, '$'); 723 const char ArgStr1[] = { '%', static_cast<char>('0' + ArgNo) }; 724 const char ArgStr2[] = { '%', static_cast<char>('0' + ArgNo2) }; 725 FormatDiagnostic(Argument, FirstDollar, OutStr); 726 FormatDiagnostic(ArgStr1, ArgStr1 + 2, OutStr); 727 FormatDiagnostic(FirstDollar + 1, SecondDollar, OutStr); 728 FormatDiagnostic(ArgStr2, ArgStr2 + 2, OutStr); 729 FormatDiagnostic(SecondDollar + 1, Pipe, OutStr); 730 continue; 731 } 732 } 733 734 switch (Kind) { 735 // ---- STRINGS ---- 736 case DiagnosticsEngine::ak_std_string: { 737 const std::string &S = getArgStdStr(ArgNo); 738 assert(ModifierLen == 0 && "No modifiers for strings yet"); 739 OutStr.append(S.begin(), S.end()); 740 break; 741 } 742 case DiagnosticsEngine::ak_c_string: { 743 const char *S = getArgCStr(ArgNo); 744 assert(ModifierLen == 0 && "No modifiers for strings yet"); 745 746 // Don't crash if get passed a null pointer by accident. 747 if (!S) 748 S = "(null)"; 749 750 OutStr.append(S, S + strlen(S)); 751 break; 752 } 753 // ---- INTEGERS ---- 754 case DiagnosticsEngine::ak_sint: { 755 int Val = getArgSInt(ArgNo); 756 757 if (ModifierIs(Modifier, ModifierLen, "select")) { 758 HandleSelectModifier(*this, (unsigned)Val, Argument, ArgumentLen, 759 OutStr); 760 } else if (ModifierIs(Modifier, ModifierLen, "s")) { 761 HandleIntegerSModifier(Val, OutStr); 762 } else if (ModifierIs(Modifier, ModifierLen, "plural")) { 763 HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen, 764 OutStr); 765 } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) { 766 HandleOrdinalModifier((unsigned)Val, OutStr); 767 } else { 768 assert(ModifierLen == 0 && "Unknown integer modifier"); 769 llvm::raw_svector_ostream(OutStr) << Val; 770 } 771 break; 772 } 773 case DiagnosticsEngine::ak_uint: { 774 unsigned Val = getArgUInt(ArgNo); 775 776 if (ModifierIs(Modifier, ModifierLen, "select")) { 777 HandleSelectModifier(*this, Val, Argument, ArgumentLen, OutStr); 778 } else if (ModifierIs(Modifier, ModifierLen, "s")) { 779 HandleIntegerSModifier(Val, OutStr); 780 } else if (ModifierIs(Modifier, ModifierLen, "plural")) { 781 HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen, 782 OutStr); 783 } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) { 784 HandleOrdinalModifier(Val, OutStr); 785 } else { 786 assert(ModifierLen == 0 && "Unknown integer modifier"); 787 llvm::raw_svector_ostream(OutStr) << Val; 788 } 789 break; 790 } 791 // ---- TOKEN SPELLINGS ---- 792 case DiagnosticsEngine::ak_tokenkind: { 793 tok::TokenKind Kind = static_cast<tok::TokenKind>(getRawArg(ArgNo)); 794 assert(ModifierLen == 0 && "No modifiers for token kinds yet"); 795 796 llvm::raw_svector_ostream Out(OutStr); 797 if (const char *S = tok::getPunctuatorSpelling(Kind)) 798 // Quoted token spelling for punctuators. 799 Out << '\'' << S << '\''; 800 else if (const char *S = tok::getKeywordSpelling(Kind)) 801 // Unquoted token spelling for keywords. 802 Out << S; 803 else if (const char *S = getTokenDescForDiagnostic(Kind)) 804 // Unquoted translatable token name. 805 Out << S; 806 else if (const char *S = tok::getTokenName(Kind)) 807 // Debug name, shouldn't appear in user-facing diagnostics. 808 Out << '<' << S << '>'; 809 else 810 Out << "(null)"; 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 case DiagnosticsEngine::ak_attr: 834 getDiags()->ConvertArgToString(Kind, getRawArg(ArgNo), 835 Modifier, ModifierLen, 836 Argument, ArgumentLen, 837 FormattedArgs.data(), FormattedArgs.size(), 838 OutStr, QualTypeVals); 839 break; 840 case DiagnosticsEngine::ak_qualtype_pair: 841 // Create a struct with all the info needed for printing. 842 TemplateDiffTypes TDT; 843 TDT.FromType = getRawArg(ArgNo); 844 TDT.ToType = getRawArg(ArgNo2); 845 TDT.ElideType = getDiags()->ElideType; 846 TDT.ShowColors = getDiags()->ShowColors; 847 TDT.TemplateDiffUsed = false; 848 intptr_t val = reinterpret_cast<intptr_t>(&TDT); 849 850 const char *ArgumentEnd = Argument + ArgumentLen; 851 const char *Pipe = ScanFormat(Argument, ArgumentEnd, '|'); 852 853 // Print the tree. If this diagnostic already has a tree, skip the 854 // second tree. 855 if (getDiags()->PrintTemplateTree && Tree.empty()) { 856 TDT.PrintFromType = true; 857 TDT.PrintTree = true; 858 getDiags()->ConvertArgToString(Kind, val, 859 Modifier, ModifierLen, 860 Argument, ArgumentLen, 861 FormattedArgs.data(), 862 FormattedArgs.size(), 863 Tree, QualTypeVals); 864 // If there is no tree information, fall back to regular printing. 865 if (!Tree.empty()) { 866 FormatDiagnostic(Pipe + 1, ArgumentEnd, OutStr); 867 break; 868 } 869 } 870 871 // Non-tree printing, also the fall-back when tree printing fails. 872 // The fall-back is triggered when the types compared are not templates. 873 const char *FirstDollar = ScanFormat(Argument, ArgumentEnd, '$'); 874 const char *SecondDollar = ScanFormat(FirstDollar + 1, ArgumentEnd, '$'); 875 876 // Append before text 877 FormatDiagnostic(Argument, FirstDollar, OutStr); 878 879 // Append first type 880 TDT.PrintTree = false; 881 TDT.PrintFromType = true; 882 getDiags()->ConvertArgToString(Kind, val, 883 Modifier, ModifierLen, 884 Argument, ArgumentLen, 885 FormattedArgs.data(), FormattedArgs.size(), 886 OutStr, QualTypeVals); 887 if (!TDT.TemplateDiffUsed) 888 FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_qualtype, 889 TDT.FromType)); 890 891 // Append middle text 892 FormatDiagnostic(FirstDollar + 1, SecondDollar, OutStr); 893 894 // Append second type 895 TDT.PrintFromType = false; 896 getDiags()->ConvertArgToString(Kind, val, 897 Modifier, ModifierLen, 898 Argument, ArgumentLen, 899 FormattedArgs.data(), FormattedArgs.size(), 900 OutStr, QualTypeVals); 901 if (!TDT.TemplateDiffUsed) 902 FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_qualtype, 903 TDT.ToType)); 904 905 // Append end text 906 FormatDiagnostic(SecondDollar + 1, Pipe, OutStr); 907 break; 908 } 909 910 // Remember this argument info for subsequent formatting operations. Turn 911 // std::strings into a null terminated string to make it be the same case as 912 // all the other ones. 913 if (Kind == DiagnosticsEngine::ak_qualtype_pair) 914 continue; 915 else if (Kind != DiagnosticsEngine::ak_std_string) 916 FormattedArgs.push_back(std::make_pair(Kind, getRawArg(ArgNo))); 917 else 918 FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_c_string, 919 (intptr_t)getArgStdStr(ArgNo).c_str())); 920 921 } 922 923 // Append the type tree to the end of the diagnostics. 924 OutStr.append(Tree.begin(), Tree.end()); 925} 926 927StoredDiagnostic::StoredDiagnostic() { } 928 929StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID, 930 StringRef Message) 931 : ID(ID), Level(Level), Loc(), Message(Message) { } 932 933StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level, 934 const Diagnostic &Info) 935 : ID(Info.getID()), Level(Level) 936{ 937 assert((Info.getLocation().isInvalid() || Info.hasSourceManager()) && 938 "Valid source location without setting a source manager for diagnostic"); 939 if (Info.getLocation().isValid()) 940 Loc = FullSourceLoc(Info.getLocation(), Info.getSourceManager()); 941 SmallString<64> Message; 942 Info.FormatDiagnostic(Message); 943 this->Message.assign(Message.begin(), Message.end()); 944 945 Ranges.reserve(Info.getNumRanges()); 946 for (unsigned I = 0, N = Info.getNumRanges(); I != N; ++I) 947 Ranges.push_back(Info.getRange(I)); 948 949 FixIts.reserve(Info.getNumFixItHints()); 950 for (unsigned I = 0, N = Info.getNumFixItHints(); I != N; ++I) 951 FixIts.push_back(Info.getFixItHint(I)); 952} 953 954StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID, 955 StringRef Message, FullSourceLoc Loc, 956 ArrayRef<CharSourceRange> Ranges, 957 ArrayRef<FixItHint> FixIts) 958 : ID(ID), Level(Level), Loc(Loc), Message(Message), 959 Ranges(Ranges.begin(), Ranges.end()), FixIts(FixIts.begin(), FixIts.end()) 960{ 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 973ForwardingDiagnosticConsumer::~ForwardingDiagnosticConsumer() {} 974 975void ForwardingDiagnosticConsumer::HandleDiagnostic( 976 DiagnosticsEngine::Level DiagLevel, 977 const Diagnostic &Info) { 978 Target.HandleDiagnostic(DiagLevel, Info); 979} 980 981void ForwardingDiagnosticConsumer::clear() { 982 DiagnosticConsumer::clear(); 983 Target.clear(); 984} 985 986bool ForwardingDiagnosticConsumer::IncludeInDiagnosticCounts() const { 987 return Target.IncludeInDiagnosticCounts(); 988} 989 990PartialDiagnostic::StorageAllocator::StorageAllocator() { 991 for (unsigned I = 0; I != NumCached; ++I) 992 FreeList[I] = Cached + I; 993 NumFreeListEntries = NumCached; 994} 995 996PartialDiagnostic::StorageAllocator::~StorageAllocator() { 997 // Don't assert if we are in a CrashRecovery context, as this invariant may 998 // be invalidated during a crash. 999 assert((NumFreeListEntries == NumCached || 1000 llvm::CrashRecoveryContext::isRecoveringFromCrash()) && 1001 "A partial is on the lamb"); 1002} 1003