1 //===--- Diagnostic.cpp - C Language Family Diagnostic Handling -----------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the Diagnostic-related interfaces. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Basic/Diagnostic.h" 15 #include "clang/Basic/IdentifierTable.h" 16 #include "clang/Basic/PartialDiagnostic.h" 17 #include "llvm/ADT/SmallVector.h" 18 #include "llvm/Support/raw_ostream.h" 19 #include "llvm/Support/CrashRecoveryContext.h" 20 21 using namespace clang; 22 23 static void DummyArgToStringFn(Diagnostic::ArgumentKind AK, intptr_t QT, 24 const char *Modifier, unsigned ML, 25 const char *Argument, unsigned ArgLen, 26 const Diagnostic::ArgumentValue *PrevArgs, 27 unsigned NumPrevArgs, 28 SmallVectorImpl<char> &Output, 29 void *Cookie, 30 SmallVectorImpl<intptr_t> &QualTypeVals) { 31 const char *Str = "<can't format argument>"; 32 Output.append(Str, Str+strlen(Str)); 33 } 34 35 36 Diagnostic::Diagnostic(const llvm::IntrusiveRefCntPtr<DiagnosticIDs> &diags, 37 DiagnosticClient *client, bool ShouldOwnClient) 38 : Diags(diags), Client(client), OwnsDiagClient(ShouldOwnClient), 39 SourceMgr(0) { 40 ArgToStringFn = DummyArgToStringFn; 41 ArgToStringCookie = 0; 42 43 AllExtensionsSilenced = 0; 44 IgnoreAllWarnings = false; 45 WarningsAsErrors = false; 46 EnableAllWarnings = false; 47 ErrorsAsFatal = false; 48 SuppressSystemWarnings = false; 49 SuppressAllDiagnostics = false; 50 ShowOverloads = Ovl_All; 51 ExtBehavior = Ext_Ignore; 52 53 ErrorLimit = 0; 54 TemplateBacktraceLimit = 0; 55 56 Reset(); 57 } 58 59 Diagnostic::~Diagnostic() { 60 if (OwnsDiagClient) 61 delete Client; 62 } 63 64 void Diagnostic::setClient(DiagnosticClient *client, bool ShouldOwnClient) { 65 if (OwnsDiagClient && Client) 66 delete Client; 67 68 Client = client; 69 OwnsDiagClient = ShouldOwnClient; 70 } 71 72 void Diagnostic::pushMappings(SourceLocation Loc) { 73 DiagStateOnPushStack.push_back(GetCurDiagState()); 74 } 75 76 bool Diagnostic::popMappings(SourceLocation Loc) { 77 if (DiagStateOnPushStack.empty()) 78 return false; 79 80 if (DiagStateOnPushStack.back() != GetCurDiagState()) { 81 // State changed at some point between push/pop. 82 PushDiagStatePoint(DiagStateOnPushStack.back(), Loc); 83 } 84 DiagStateOnPushStack.pop_back(); 85 return true; 86 } 87 88 void Diagnostic::Reset() { 89 ErrorOccurred = false; 90 FatalErrorOccurred = false; 91 UnrecoverableErrorOccurred = false; 92 93 NumWarnings = 0; 94 NumErrors = 0; 95 NumErrorsSuppressed = 0; 96 TrapNumErrorsOccurred = 0; 97 TrapNumUnrecoverableErrorsOccurred = 0; 98 99 CurDiagID = ~0U; 100 // Set LastDiagLevel to an "unset" state. If we set it to 'Ignored', notes 101 // using a Diagnostic associated to a translation unit that follow 102 // diagnostics from a Diagnostic associated to anoter t.u. will not be 103 // displayed. 104 LastDiagLevel = (DiagnosticIDs::Level)-1; 105 DelayedDiagID = 0; 106 107 // Clear state related to #pragma diagnostic. 108 DiagStates.clear(); 109 DiagStatePoints.clear(); 110 DiagStateOnPushStack.clear(); 111 112 // Create a DiagState and DiagStatePoint representing diagnostic changes 113 // through command-line. 114 DiagStates.push_back(DiagState()); 115 PushDiagStatePoint(&DiagStates.back(), SourceLocation()); 116 } 117 118 void Diagnostic::SetDelayedDiagnostic(unsigned DiagID, StringRef Arg1, 119 StringRef Arg2) { 120 if (DelayedDiagID) 121 return; 122 123 DelayedDiagID = DiagID; 124 DelayedDiagArg1 = Arg1.str(); 125 DelayedDiagArg2 = Arg2.str(); 126 } 127 128 void Diagnostic::ReportDelayed() { 129 Report(DelayedDiagID) << DelayedDiagArg1 << DelayedDiagArg2; 130 DelayedDiagID = 0; 131 DelayedDiagArg1.clear(); 132 DelayedDiagArg2.clear(); 133 } 134 135 Diagnostic::DiagStatePointsTy::iterator 136 Diagnostic::GetDiagStatePointForLoc(SourceLocation L) const { 137 assert(!DiagStatePoints.empty()); 138 assert(DiagStatePoints.front().Loc.isInvalid() && 139 "Should have created a DiagStatePoint for command-line"); 140 141 FullSourceLoc Loc(L, *SourceMgr); 142 if (Loc.isInvalid()) 143 return DiagStatePoints.end() - 1; 144 145 DiagStatePointsTy::iterator Pos = DiagStatePoints.end(); 146 FullSourceLoc LastStateChangePos = DiagStatePoints.back().Loc; 147 if (LastStateChangePos.isValid() && 148 Loc.isBeforeInTranslationUnitThan(LastStateChangePos)) 149 Pos = std::upper_bound(DiagStatePoints.begin(), DiagStatePoints.end(), 150 DiagStatePoint(0, Loc)); 151 --Pos; 152 return Pos; 153 } 154 155 /// \brief This allows the client to specify that certain 156 /// warnings are ignored. Notes can never be mapped, errors can only be 157 /// mapped to fatal, and WARNINGs and EXTENSIONs can be mapped arbitrarily. 158 /// 159 /// \param The source location that this change of diagnostic state should 160 /// take affect. It can be null if we are setting the latest state. 161 void Diagnostic::setDiagnosticMapping(diag::kind Diag, diag::Mapping Map, 162 SourceLocation L) { 163 assert(Diag < diag::DIAG_UPPER_LIMIT && 164 "Can only map builtin diagnostics"); 165 assert((Diags->isBuiltinWarningOrExtension(Diag) || 166 (Map == diag::MAP_FATAL || Map == diag::MAP_ERROR)) && 167 "Cannot map errors into warnings!"); 168 assert(!DiagStatePoints.empty()); 169 170 bool isPragma = L.isValid(); 171 FullSourceLoc Loc(L, *SourceMgr); 172 FullSourceLoc LastStateChangePos = DiagStatePoints.back().Loc; 173 174 // Common case; setting all the diagnostics of a group in one place. 175 if (Loc.isInvalid() || Loc == LastStateChangePos) { 176 setDiagnosticMappingInternal(Diag, Map, GetCurDiagState(), true, isPragma); 177 return; 178 } 179 180 // Another common case; modifying diagnostic state in a source location 181 // after the previous one. 182 if ((Loc.isValid() && LastStateChangePos.isInvalid()) || 183 LastStateChangePos.isBeforeInTranslationUnitThan(Loc)) { 184 // A diagnostic pragma occurred, create a new DiagState initialized with 185 // the current one and a new DiagStatePoint to record at which location 186 // the new state became active. 187 DiagStates.push_back(*GetCurDiagState()); 188 PushDiagStatePoint(&DiagStates.back(), Loc); 189 setDiagnosticMappingInternal(Diag, Map, GetCurDiagState(), true, isPragma); 190 return; 191 } 192 193 // We allow setting the diagnostic state in random source order for 194 // completeness but it should not be actually happening in normal practice. 195 196 DiagStatePointsTy::iterator Pos = GetDiagStatePointForLoc(Loc); 197 assert(Pos != DiagStatePoints.end()); 198 199 // Update all diagnostic states that are active after the given location. 200 for (DiagStatePointsTy::iterator 201 I = Pos+1, E = DiagStatePoints.end(); I != E; ++I) { 202 setDiagnosticMappingInternal(Diag, Map, I->State, true, isPragma); 203 } 204 205 // If the location corresponds to an existing point, just update its state. 206 if (Pos->Loc == Loc) { 207 setDiagnosticMappingInternal(Diag, Map, Pos->State, true, isPragma); 208 return; 209 } 210 211 // Create a new state/point and fit it into the vector of DiagStatePoints 212 // so that the vector is always ordered according to location. 213 Pos->Loc.isBeforeInTranslationUnitThan(Loc); 214 DiagStates.push_back(*Pos->State); 215 DiagState *NewState = &DiagStates.back(); 216 setDiagnosticMappingInternal(Diag, Map, NewState, true, isPragma); 217 DiagStatePoints.insert(Pos+1, DiagStatePoint(NewState, 218 FullSourceLoc(Loc, *SourceMgr))); 219 } 220 221 void Diagnostic::Report(const StoredDiagnostic &storedDiag) { 222 assert(CurDiagID == ~0U && "Multiple diagnostics in flight at once!"); 223 224 CurDiagLoc = storedDiag.getLocation(); 225 CurDiagID = storedDiag.getID(); 226 NumDiagArgs = 0; 227 228 NumDiagRanges = storedDiag.range_size(); 229 assert(NumDiagRanges < sizeof(DiagRanges)/sizeof(DiagRanges[0]) && 230 "Too many arguments to diagnostic!"); 231 unsigned i = 0; 232 for (StoredDiagnostic::range_iterator 233 RI = storedDiag.range_begin(), 234 RE = storedDiag.range_end(); RI != RE; ++RI) 235 DiagRanges[i++] = *RI; 236 237 NumFixItHints = storedDiag.fixit_size(); 238 assert(NumFixItHints < Diagnostic::MaxFixItHints && "Too many fix-it hints!"); 239 i = 0; 240 for (StoredDiagnostic::fixit_iterator 241 FI = storedDiag.fixit_begin(), 242 FE = storedDiag.fixit_end(); FI != FE; ++FI) 243 FixItHints[i++] = *FI; 244 245 assert(Client && "DiagnosticClient not set!"); 246 Level DiagLevel = storedDiag.getLevel(); 247 DiagnosticInfo Info(this, storedDiag.getMessage()); 248 Client->HandleDiagnostic(DiagLevel, Info); 249 if (Client->IncludeInDiagnosticCounts()) { 250 if (DiagLevel == Diagnostic::Warning) 251 ++NumWarnings; 252 } 253 254 CurDiagID = ~0U; 255 } 256 257 void DiagnosticBuilder::FlushCounts() { 258 DiagObj->NumDiagArgs = NumArgs; 259 DiagObj->NumDiagRanges = NumRanges; 260 DiagObj->NumFixItHints = NumFixItHints; 261 } 262 263 bool DiagnosticBuilder::Emit() { 264 // If DiagObj is null, then its soul was stolen by the copy ctor 265 // or the user called Emit(). 266 if (DiagObj == 0) return false; 267 268 // When emitting diagnostics, we set the final argument count into 269 // the Diagnostic object. 270 FlushCounts(); 271 272 // Process the diagnostic, sending the accumulated information to the 273 // DiagnosticClient. 274 bool Emitted = DiagObj->ProcessDiag(); 275 276 // Clear out the current diagnostic object. 277 unsigned DiagID = DiagObj->CurDiagID; 278 DiagObj->Clear(); 279 280 // If there was a delayed diagnostic, emit it now. 281 if (DiagObj->DelayedDiagID && DiagObj->DelayedDiagID != DiagID) 282 DiagObj->ReportDelayed(); 283 284 // This diagnostic is dead. 285 DiagObj = 0; 286 287 return Emitted; 288 } 289 290 291 DiagnosticClient::~DiagnosticClient() {} 292 293 void DiagnosticClient::HandleDiagnostic(Diagnostic::Level DiagLevel, 294 const DiagnosticInfo &Info) { 295 if (!IncludeInDiagnosticCounts()) 296 return; 297 298 if (DiagLevel == Diagnostic::Warning) 299 ++NumWarnings; 300 else if (DiagLevel >= Diagnostic::Error) 301 ++NumErrors; 302 } 303 304 /// ModifierIs - Return true if the specified modifier matches specified string. 305 template <std::size_t StrLen> 306 static bool ModifierIs(const char *Modifier, unsigned ModifierLen, 307 const char (&Str)[StrLen]) { 308 return StrLen-1 == ModifierLen && !memcmp(Modifier, Str, StrLen-1); 309 } 310 311 /// ScanForward - Scans forward, looking for the given character, skipping 312 /// nested clauses and escaped characters. 313 static const char *ScanFormat(const char *I, const char *E, char Target) { 314 unsigned Depth = 0; 315 316 for ( ; I != E; ++I) { 317 if (Depth == 0 && *I == Target) return I; 318 if (Depth != 0 && *I == '}') Depth--; 319 320 if (*I == '%') { 321 I++; 322 if (I == E) break; 323 324 // Escaped characters get implicitly skipped here. 325 326 // Format specifier. 327 if (!isdigit(*I) && !ispunct(*I)) { 328 for (I++; I != E && !isdigit(*I) && *I != '{'; I++) ; 329 if (I == E) break; 330 if (*I == '{') 331 Depth++; 332 } 333 } 334 } 335 return E; 336 } 337 338 /// HandleSelectModifier - Handle the integer 'select' modifier. This is used 339 /// like this: %select{foo|bar|baz}2. This means that the integer argument 340 /// "%2" has a value from 0-2. If the value is 0, the diagnostic prints 'foo'. 341 /// If the value is 1, it prints 'bar'. If it has the value 2, it prints 'baz'. 342 /// This is very useful for certain classes of variant diagnostics. 343 static void HandleSelectModifier(const DiagnosticInfo &DInfo, unsigned ValNo, 344 const char *Argument, unsigned ArgumentLen, 345 SmallVectorImpl<char> &OutStr) { 346 const char *ArgumentEnd = Argument+ArgumentLen; 347 348 // Skip over 'ValNo' |'s. 349 while (ValNo) { 350 const char *NextVal = ScanFormat(Argument, ArgumentEnd, '|'); 351 assert(NextVal != ArgumentEnd && "Value for integer select modifier was" 352 " larger than the number of options in the diagnostic string!"); 353 Argument = NextVal+1; // Skip this string. 354 --ValNo; 355 } 356 357 // Get the end of the value. This is either the } or the |. 358 const char *EndPtr = ScanFormat(Argument, ArgumentEnd, '|'); 359 360 // Recursively format the result of the select clause into the output string. 361 DInfo.FormatDiagnostic(Argument, EndPtr, OutStr); 362 } 363 364 /// HandleIntegerSModifier - Handle the integer 's' modifier. This adds the 365 /// letter 's' to the string if the value is not 1. This is used in cases like 366 /// this: "you idiot, you have %4 parameter%s4!". 367 static void HandleIntegerSModifier(unsigned ValNo, 368 SmallVectorImpl<char> &OutStr) { 369 if (ValNo != 1) 370 OutStr.push_back('s'); 371 } 372 373 /// HandleOrdinalModifier - Handle the integer 'ord' modifier. This 374 /// prints the ordinal form of the given integer, with 1 corresponding 375 /// to the first ordinal. Currently this is hard-coded to use the 376 /// English form. 377 static void HandleOrdinalModifier(unsigned ValNo, 378 SmallVectorImpl<char> &OutStr) { 379 assert(ValNo != 0 && "ValNo must be strictly positive!"); 380 381 llvm::raw_svector_ostream Out(OutStr); 382 383 // We could use text forms for the first N ordinals, but the numeric 384 // forms are actually nicer in diagnostics because they stand out. 385 Out << ValNo; 386 387 // It is critically important that we do this perfectly for 388 // user-written sequences with over 100 elements. 389 switch (ValNo % 100) { 390 case 11: 391 case 12: 392 case 13: 393 Out << "th"; return; 394 default: 395 switch (ValNo % 10) { 396 case 1: Out << "st"; return; 397 case 2: Out << "nd"; return; 398 case 3: Out << "rd"; return; 399 default: Out << "th"; return; 400 } 401 } 402 } 403 404 405 /// PluralNumber - Parse an unsigned integer and advance Start. 406 static unsigned PluralNumber(const char *&Start, const char *End) { 407 // Programming 101: Parse a decimal number :-) 408 unsigned Val = 0; 409 while (Start != End && *Start >= '0' && *Start <= '9') { 410 Val *= 10; 411 Val += *Start - '0'; 412 ++Start; 413 } 414 return Val; 415 } 416 417 /// TestPluralRange - Test if Val is in the parsed range. Modifies Start. 418 static bool TestPluralRange(unsigned Val, const char *&Start, const char *End) { 419 if (*Start != '[') { 420 unsigned Ref = PluralNumber(Start, End); 421 return Ref == Val; 422 } 423 424 ++Start; 425 unsigned Low = PluralNumber(Start, End); 426 assert(*Start == ',' && "Bad plural expression syntax: expected ,"); 427 ++Start; 428 unsigned High = PluralNumber(Start, End); 429 assert(*Start == ']' && "Bad plural expression syntax: expected )"); 430 ++Start; 431 return Low <= Val && Val <= High; 432 } 433 434 /// EvalPluralExpr - Actual expression evaluator for HandlePluralModifier. 435 static bool EvalPluralExpr(unsigned ValNo, const char *Start, const char *End) { 436 // Empty condition? 437 if (*Start == ':') 438 return true; 439 440 while (1) { 441 char C = *Start; 442 if (C == '%') { 443 // Modulo expression 444 ++Start; 445 unsigned Arg = PluralNumber(Start, End); 446 assert(*Start == '=' && "Bad plural expression syntax: expected ="); 447 ++Start; 448 unsigned ValMod = ValNo % Arg; 449 if (TestPluralRange(ValMod, Start, End)) 450 return true; 451 } else { 452 assert((C == '[' || (C >= '0' && C <= '9')) && 453 "Bad plural expression syntax: unexpected character"); 454 // Range expression 455 if (TestPluralRange(ValNo, Start, End)) 456 return true; 457 } 458 459 // Scan for next or-expr part. 460 Start = std::find(Start, End, ','); 461 if (Start == End) 462 break; 463 ++Start; 464 } 465 return false; 466 } 467 468 /// HandlePluralModifier - Handle the integer 'plural' modifier. This is used 469 /// for complex plural forms, or in languages where all plurals are complex. 470 /// The syntax is: %plural{cond1:form1|cond2:form2|:form3}, where condn are 471 /// conditions that are tested in order, the form corresponding to the first 472 /// that applies being emitted. The empty condition is always true, making the 473 /// last form a default case. 474 /// Conditions are simple boolean expressions, where n is the number argument. 475 /// Here are the rules. 476 /// condition := expression | empty 477 /// empty := -> always true 478 /// expression := numeric [',' expression] -> logical or 479 /// numeric := range -> true if n in range 480 /// | '%' number '=' range -> true if n % number in range 481 /// range := number 482 /// | '[' number ',' number ']' -> ranges are inclusive both ends 483 /// 484 /// Here are some examples from the GNU gettext manual written in this form: 485 /// English: 486 /// {1:form0|:form1} 487 /// Latvian: 488 /// {0:form2|%100=11,%10=0,%10=[2,9]:form1|:form0} 489 /// Gaeilge: 490 /// {1:form0|2:form1|:form2} 491 /// Romanian: 492 /// {1:form0|0,%100=[1,19]:form1|:form2} 493 /// Lithuanian: 494 /// {%10=0,%100=[10,19]:form2|%10=1:form0|:form1} 495 /// Russian (requires repeated form): 496 /// {%100=[11,14]:form2|%10=1:form0|%10=[2,4]:form1|:form2} 497 /// Slovak 498 /// {1:form0|[2,4]:form1|:form2} 499 /// Polish (requires repeated form): 500 /// {1:form0|%100=[10,20]:form2|%10=[2,4]:form1|:form2} 501 static void HandlePluralModifier(const DiagnosticInfo &DInfo, unsigned ValNo, 502 const char *Argument, unsigned ArgumentLen, 503 SmallVectorImpl<char> &OutStr) { 504 const char *ArgumentEnd = Argument + ArgumentLen; 505 while (1) { 506 assert(Argument < ArgumentEnd && "Plural expression didn't match."); 507 const char *ExprEnd = Argument; 508 while (*ExprEnd != ':') { 509 assert(ExprEnd != ArgumentEnd && "Plural missing expression end"); 510 ++ExprEnd; 511 } 512 if (EvalPluralExpr(ValNo, Argument, ExprEnd)) { 513 Argument = ExprEnd + 1; 514 ExprEnd = ScanFormat(Argument, ArgumentEnd, '|'); 515 516 // Recursively format the result of the plural clause into the 517 // output string. 518 DInfo.FormatDiagnostic(Argument, ExprEnd, OutStr); 519 return; 520 } 521 Argument = ScanFormat(Argument, ArgumentEnd - 1, '|') + 1; 522 } 523 } 524 525 526 /// FormatDiagnostic - Format this diagnostic into a string, substituting the 527 /// formal arguments into the %0 slots. The result is appended onto the Str 528 /// array. 529 void DiagnosticInfo:: 530 FormatDiagnostic(SmallVectorImpl<char> &OutStr) const { 531 if (!StoredDiagMessage.empty()) { 532 OutStr.append(StoredDiagMessage.begin(), StoredDiagMessage.end()); 533 return; 534 } 535 536 StringRef Diag = 537 getDiags()->getDiagnosticIDs()->getDescription(getID()); 538 539 FormatDiagnostic(Diag.begin(), Diag.end(), OutStr); 540 } 541 542 void DiagnosticInfo:: 543 FormatDiagnostic(const char *DiagStr, const char *DiagEnd, 544 SmallVectorImpl<char> &OutStr) const { 545 546 /// FormattedArgs - Keep track of all of the arguments formatted by 547 /// ConvertArgToString and pass them into subsequent calls to 548 /// ConvertArgToString, allowing the implementation to avoid redundancies in 549 /// obvious cases. 550 SmallVector<Diagnostic::ArgumentValue, 8> FormattedArgs; 551 552 /// QualTypeVals - Pass a vector of arrays so that QualType names can be 553 /// compared to see if more information is needed to be printed. 554 SmallVector<intptr_t, 2> QualTypeVals; 555 for (unsigned i = 0, e = getNumArgs(); i < e; ++i) 556 if (getArgKind(i) == Diagnostic::ak_qualtype) 557 QualTypeVals.push_back(getRawArg(i)); 558 559 while (DiagStr != DiagEnd) { 560 if (DiagStr[0] != '%') { 561 // Append non-%0 substrings to Str if we have one. 562 const char *StrEnd = std::find(DiagStr, DiagEnd, '%'); 563 OutStr.append(DiagStr, StrEnd); 564 DiagStr = StrEnd; 565 continue; 566 } else if (ispunct(DiagStr[1])) { 567 OutStr.push_back(DiagStr[1]); // %% -> %. 568 DiagStr += 2; 569 continue; 570 } 571 572 // Skip the %. 573 ++DiagStr; 574 575 // This must be a placeholder for a diagnostic argument. The format for a 576 // placeholder is one of "%0", "%modifier0", or "%modifier{arguments}0". 577 // The digit is a number from 0-9 indicating which argument this comes from. 578 // The modifier is a string of digits from the set [-a-z]+, arguments is a 579 // brace enclosed string. 580 const char *Modifier = 0, *Argument = 0; 581 unsigned ModifierLen = 0, ArgumentLen = 0; 582 583 // Check to see if we have a modifier. If so eat it. 584 if (!isdigit(DiagStr[0])) { 585 Modifier = DiagStr; 586 while (DiagStr[0] == '-' || 587 (DiagStr[0] >= 'a' && DiagStr[0] <= 'z')) 588 ++DiagStr; 589 ModifierLen = DiagStr-Modifier; 590 591 // If we have an argument, get it next. 592 if (DiagStr[0] == '{') { 593 ++DiagStr; // Skip {. 594 Argument = DiagStr; 595 596 DiagStr = ScanFormat(DiagStr, DiagEnd, '}'); 597 assert(DiagStr != DiagEnd && "Mismatched {}'s in diagnostic string!"); 598 ArgumentLen = DiagStr-Argument; 599 ++DiagStr; // Skip }. 600 } 601 } 602 603 assert(isdigit(*DiagStr) && "Invalid format for argument in diagnostic"); 604 unsigned ArgNo = *DiagStr++ - '0'; 605 606 Diagnostic::ArgumentKind Kind = getArgKind(ArgNo); 607 608 switch (Kind) { 609 // ---- STRINGS ---- 610 case Diagnostic::ak_std_string: { 611 const std::string &S = getArgStdStr(ArgNo); 612 assert(ModifierLen == 0 && "No modifiers for strings yet"); 613 OutStr.append(S.begin(), S.end()); 614 break; 615 } 616 case Diagnostic::ak_c_string: { 617 const char *S = getArgCStr(ArgNo); 618 assert(ModifierLen == 0 && "No modifiers for strings yet"); 619 620 // Don't crash if get passed a null pointer by accident. 621 if (!S) 622 S = "(null)"; 623 624 OutStr.append(S, S + strlen(S)); 625 break; 626 } 627 // ---- INTEGERS ---- 628 case Diagnostic::ak_sint: { 629 int Val = getArgSInt(ArgNo); 630 631 if (ModifierIs(Modifier, ModifierLen, "select")) { 632 HandleSelectModifier(*this, (unsigned)Val, Argument, ArgumentLen, 633 OutStr); 634 } else if (ModifierIs(Modifier, ModifierLen, "s")) { 635 HandleIntegerSModifier(Val, OutStr); 636 } else if (ModifierIs(Modifier, ModifierLen, "plural")) { 637 HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen, 638 OutStr); 639 } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) { 640 HandleOrdinalModifier((unsigned)Val, OutStr); 641 } else { 642 assert(ModifierLen == 0 && "Unknown integer modifier"); 643 llvm::raw_svector_ostream(OutStr) << Val; 644 } 645 break; 646 } 647 case Diagnostic::ak_uint: { 648 unsigned Val = getArgUInt(ArgNo); 649 650 if (ModifierIs(Modifier, ModifierLen, "select")) { 651 HandleSelectModifier(*this, Val, Argument, ArgumentLen, OutStr); 652 } else if (ModifierIs(Modifier, ModifierLen, "s")) { 653 HandleIntegerSModifier(Val, OutStr); 654 } else if (ModifierIs(Modifier, ModifierLen, "plural")) { 655 HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen, 656 OutStr); 657 } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) { 658 HandleOrdinalModifier(Val, OutStr); 659 } else { 660 assert(ModifierLen == 0 && "Unknown integer modifier"); 661 llvm::raw_svector_ostream(OutStr) << Val; 662 } 663 break; 664 } 665 // ---- NAMES and TYPES ---- 666 case Diagnostic::ak_identifierinfo: { 667 const IdentifierInfo *II = getArgIdentifier(ArgNo); 668 assert(ModifierLen == 0 && "No modifiers for strings yet"); 669 670 // Don't crash if get passed a null pointer by accident. 671 if (!II) { 672 const char *S = "(null)"; 673 OutStr.append(S, S + strlen(S)); 674 continue; 675 } 676 677 llvm::raw_svector_ostream(OutStr) << '\'' << II->getName() << '\''; 678 break; 679 } 680 case Diagnostic::ak_qualtype: 681 case Diagnostic::ak_declarationname: 682 case Diagnostic::ak_nameddecl: 683 case Diagnostic::ak_nestednamespec: 684 case Diagnostic::ak_declcontext: 685 getDiags()->ConvertArgToString(Kind, getRawArg(ArgNo), 686 Modifier, ModifierLen, 687 Argument, ArgumentLen, 688 FormattedArgs.data(), FormattedArgs.size(), 689 OutStr, QualTypeVals); 690 break; 691 } 692 693 // Remember this argument info for subsequent formatting operations. Turn 694 // std::strings into a null terminated string to make it be the same case as 695 // all the other ones. 696 if (Kind != Diagnostic::ak_std_string) 697 FormattedArgs.push_back(std::make_pair(Kind, getRawArg(ArgNo))); 698 else 699 FormattedArgs.push_back(std::make_pair(Diagnostic::ak_c_string, 700 (intptr_t)getArgStdStr(ArgNo).c_str())); 701 702 } 703 } 704 705 StoredDiagnostic::StoredDiagnostic() { } 706 707 StoredDiagnostic::StoredDiagnostic(Diagnostic::Level Level, unsigned ID, 708 StringRef Message) 709 : ID(ID), Level(Level), Loc(), Message(Message) { } 710 711 StoredDiagnostic::StoredDiagnostic(Diagnostic::Level Level, 712 const DiagnosticInfo &Info) 713 : ID(Info.getID()), Level(Level) 714 { 715 assert((Info.getLocation().isInvalid() || Info.hasSourceManager()) && 716 "Valid source location without setting a source manager for diagnostic"); 717 if (Info.getLocation().isValid()) 718 Loc = FullSourceLoc(Info.getLocation(), Info.getSourceManager()); 719 llvm::SmallString<64> Message; 720 Info.FormatDiagnostic(Message); 721 this->Message.assign(Message.begin(), Message.end()); 722 723 Ranges.reserve(Info.getNumRanges()); 724 for (unsigned I = 0, N = Info.getNumRanges(); I != N; ++I) 725 Ranges.push_back(Info.getRange(I)); 726 727 FixIts.reserve(Info.getNumFixItHints()); 728 for (unsigned I = 0, N = Info.getNumFixItHints(); I != N; ++I) 729 FixIts.push_back(Info.getFixItHint(I)); 730 } 731 732 StoredDiagnostic::StoredDiagnostic(Diagnostic::Level Level, unsigned ID, 733 StringRef Message, FullSourceLoc Loc, 734 ArrayRef<CharSourceRange> Ranges, 735 ArrayRef<FixItHint> Fixits) 736 : ID(ID), Level(Level), Loc(Loc), Message(Message) 737 { 738 this->Ranges.assign(Ranges.begin(), Ranges.end()); 739 this->FixIts.assign(FixIts.begin(), FixIts.end()); 740 } 741 742 StoredDiagnostic::~StoredDiagnostic() { } 743 744 /// IncludeInDiagnosticCounts - This method (whose default implementation 745 /// returns true) indicates whether the diagnostics handled by this 746 /// DiagnosticClient should be included in the number of diagnostics 747 /// reported by Diagnostic. 748 bool DiagnosticClient::IncludeInDiagnosticCounts() const { return true; } 749 750 PartialDiagnostic::StorageAllocator::StorageAllocator() { 751 for (unsigned I = 0; I != NumCached; ++I) 752 FreeList[I] = Cached + I; 753 NumFreeListEntries = NumCached; 754 } 755 756 PartialDiagnostic::StorageAllocator::~StorageAllocator() { 757 // Don't assert if we are in a CrashRecovery context, as this 758 // invariant may be invalidated during a crash. 759 assert((NumFreeListEntries == NumCached || llvm::CrashRecoveryContext::isRecoveringFromCrash()) && "A partial is on the lamb"); 760 } 761