Diagnostic.cpp revision a6a32e295379570b489cc041053d2cd53bcafd1c
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" 19using namespace clang; 20 21static void DummyArgToStringFn(Diagnostic::ArgumentKind AK, intptr_t QT, 22 const char *Modifier, unsigned ML, 23 const char *Argument, unsigned ArgLen, 24 const Diagnostic::ArgumentValue *PrevArgs, 25 unsigned NumPrevArgs, 26 llvm::SmallVectorImpl<char> &Output, 27 void *Cookie) { 28 const char *Str = "<can't format argument>"; 29 Output.append(Str, Str+strlen(Str)); 30} 31 32 33Diagnostic::Diagnostic(const llvm::IntrusiveRefCntPtr<DiagnosticIDs> &diags, 34 DiagnosticClient *client, bool ShouldOwnClient) 35 : Diags(diags), Client(client), OwnsDiagClient(ShouldOwnClient), 36 SourceMgr(0) { 37 ArgToStringFn = DummyArgToStringFn; 38 ArgToStringCookie = 0; 39 40 AllExtensionsSilenced = 0; 41 IgnoreAllWarnings = false; 42 WarningsAsErrors = false; 43 ErrorsAsFatal = false; 44 SuppressSystemWarnings = false; 45 SuppressAllDiagnostics = false; 46 ShowOverloads = Ovl_All; 47 ExtBehavior = Ext_Ignore; 48 49 ErrorLimit = 0; 50 TemplateBacktraceLimit = 0; 51 52 // Set all mappings to 'unset'. 53 DiagMappingsStack.clear(); 54 DiagMappingsStack.push_back(DiagMappings()); 55 56 Reset(); 57} 58 59Diagnostic::~Diagnostic() { 60 if (OwnsDiagClient) 61 delete Client; 62} 63 64 65void Diagnostic::pushMappings() { 66 // Avoids undefined behavior when the stack has to resize. 67 DiagMappingsStack.reserve(DiagMappingsStack.size() + 1); 68 DiagMappingsStack.push_back(DiagMappingsStack.back()); 69} 70 71bool Diagnostic::popMappings() { 72 if (DiagMappingsStack.size() == 1) 73 return false; 74 75 DiagMappingsStack.pop_back(); 76 return true; 77} 78 79void Diagnostic::Reset() { 80 ErrorOccurred = false; 81 FatalErrorOccurred = false; 82 83 NumWarnings = 0; 84 NumErrors = 0; 85 NumErrorsSuppressed = 0; 86 CurDiagID = ~0U; 87 // Set LastDiagLevel to an "unset" state. If we set it to 'Ignored', notes 88 // using a Diagnostic associated to a translation unit that follow 89 // diagnostics from a Diagnostic associated to anoter t.u. will not be 90 // displayed. 91 LastDiagLevel = (DiagnosticIDs::Level)-1; 92 DelayedDiagID = 0; 93} 94 95void Diagnostic::SetDelayedDiagnostic(unsigned DiagID, llvm::StringRef Arg1, 96 llvm::StringRef Arg2) { 97 if (DelayedDiagID) 98 return; 99 100 DelayedDiagID = DiagID; 101 DelayedDiagArg1 = Arg1.str(); 102 DelayedDiagArg2 = Arg2.str(); 103} 104 105void Diagnostic::ReportDelayed() { 106 Report(DelayedDiagID) << DelayedDiagArg1 << DelayedDiagArg2; 107 DelayedDiagID = 0; 108 DelayedDiagArg1.clear(); 109 DelayedDiagArg2.clear(); 110} 111 112void DiagnosticBuilder::FlushCounts() { 113 DiagObj->NumDiagArgs = NumArgs; 114 DiagObj->NumDiagRanges = NumRanges; 115 DiagObj->NumFixItHints = NumFixItHints; 116} 117 118bool DiagnosticBuilder::Emit() { 119 // If DiagObj is null, then its soul was stolen by the copy ctor 120 // or the user called Emit(). 121 if (DiagObj == 0) return false; 122 123 // When emitting diagnostics, we set the final argument count into 124 // the Diagnostic object. 125 FlushCounts(); 126 127 // Process the diagnostic, sending the accumulated information to the 128 // DiagnosticClient. 129 bool Emitted = DiagObj->ProcessDiag(); 130 131 // Clear out the current diagnostic object. 132 unsigned DiagID = DiagObj->CurDiagID; 133 DiagObj->Clear(); 134 135 // If there was a delayed diagnostic, emit it now. 136 if (DiagObj->DelayedDiagID && DiagObj->DelayedDiagID != DiagID) 137 DiagObj->ReportDelayed(); 138 139 // This diagnostic is dead. 140 DiagObj = 0; 141 142 return Emitted; 143} 144 145 146DiagnosticClient::~DiagnosticClient() {} 147 148void DiagnosticClient::HandleDiagnostic(Diagnostic::Level DiagLevel, 149 const DiagnosticInfo &Info) { 150 if (!IncludeInDiagnosticCounts()) 151 return; 152 153 if (DiagLevel == Diagnostic::Warning) 154 ++NumWarnings; 155 else if (DiagLevel >= Diagnostic::Error) 156 ++NumErrors; 157} 158 159/// ModifierIs - Return true if the specified modifier matches specified string. 160template <std::size_t StrLen> 161static bool ModifierIs(const char *Modifier, unsigned ModifierLen, 162 const char (&Str)[StrLen]) { 163 return StrLen-1 == ModifierLen && !memcmp(Modifier, Str, StrLen-1); 164} 165 166/// ScanForward - Scans forward, looking for the given character, skipping 167/// nested clauses and escaped characters. 168static const char *ScanFormat(const char *I, const char *E, char Target) { 169 unsigned Depth = 0; 170 171 for ( ; I != E; ++I) { 172 if (Depth == 0 && *I == Target) return I; 173 if (Depth != 0 && *I == '}') Depth--; 174 175 if (*I == '%') { 176 I++; 177 if (I == E) break; 178 179 // Escaped characters get implicitly skipped here. 180 181 // Format specifier. 182 if (!isdigit(*I) && !ispunct(*I)) { 183 for (I++; I != E && !isdigit(*I) && *I != '{'; I++) ; 184 if (I == E) break; 185 if (*I == '{') 186 Depth++; 187 } 188 } 189 } 190 return E; 191} 192 193/// HandleSelectModifier - Handle the integer 'select' modifier. This is used 194/// like this: %select{foo|bar|baz}2. This means that the integer argument 195/// "%2" has a value from 0-2. If the value is 0, the diagnostic prints 'foo'. 196/// If the value is 1, it prints 'bar'. If it has the value 2, it prints 'baz'. 197/// This is very useful for certain classes of variant diagnostics. 198static void HandleSelectModifier(const DiagnosticInfo &DInfo, unsigned ValNo, 199 const char *Argument, unsigned ArgumentLen, 200 llvm::SmallVectorImpl<char> &OutStr) { 201 const char *ArgumentEnd = Argument+ArgumentLen; 202 203 // Skip over 'ValNo' |'s. 204 while (ValNo) { 205 const char *NextVal = ScanFormat(Argument, ArgumentEnd, '|'); 206 assert(NextVal != ArgumentEnd && "Value for integer select modifier was" 207 " larger than the number of options in the diagnostic string!"); 208 Argument = NextVal+1; // Skip this string. 209 --ValNo; 210 } 211 212 // Get the end of the value. This is either the } or the |. 213 const char *EndPtr = ScanFormat(Argument, ArgumentEnd, '|'); 214 215 // Recursively format the result of the select clause into the output string. 216 DInfo.FormatDiagnostic(Argument, EndPtr, OutStr); 217} 218 219/// HandleIntegerSModifier - Handle the integer 's' modifier. This adds the 220/// letter 's' to the string if the value is not 1. This is used in cases like 221/// this: "you idiot, you have %4 parameter%s4!". 222static void HandleIntegerSModifier(unsigned ValNo, 223 llvm::SmallVectorImpl<char> &OutStr) { 224 if (ValNo != 1) 225 OutStr.push_back('s'); 226} 227 228/// HandleOrdinalModifier - Handle the integer 'ord' modifier. This 229/// prints the ordinal form of the given integer, with 1 corresponding 230/// to the first ordinal. Currently this is hard-coded to use the 231/// English form. 232static void HandleOrdinalModifier(unsigned ValNo, 233 llvm::SmallVectorImpl<char> &OutStr) { 234 assert(ValNo != 0 && "ValNo must be strictly positive!"); 235 236 llvm::raw_svector_ostream Out(OutStr); 237 238 // We could use text forms for the first N ordinals, but the numeric 239 // forms are actually nicer in diagnostics because they stand out. 240 Out << ValNo; 241 242 // It is critically important that we do this perfectly for 243 // user-written sequences with over 100 elements. 244 switch (ValNo % 100) { 245 case 11: 246 case 12: 247 case 13: 248 Out << "th"; return; 249 default: 250 switch (ValNo % 10) { 251 case 1: Out << "st"; return; 252 case 2: Out << "nd"; return; 253 case 3: Out << "rd"; return; 254 default: Out << "th"; return; 255 } 256 } 257} 258 259 260/// PluralNumber - Parse an unsigned integer and advance Start. 261static unsigned PluralNumber(const char *&Start, const char *End) { 262 // Programming 101: Parse a decimal number :-) 263 unsigned Val = 0; 264 while (Start != End && *Start >= '0' && *Start <= '9') { 265 Val *= 10; 266 Val += *Start - '0'; 267 ++Start; 268 } 269 return Val; 270} 271 272/// TestPluralRange - Test if Val is in the parsed range. Modifies Start. 273static bool TestPluralRange(unsigned Val, const char *&Start, const char *End) { 274 if (*Start != '[') { 275 unsigned Ref = PluralNumber(Start, End); 276 return Ref == Val; 277 } 278 279 ++Start; 280 unsigned Low = PluralNumber(Start, End); 281 assert(*Start == ',' && "Bad plural expression syntax: expected ,"); 282 ++Start; 283 unsigned High = PluralNumber(Start, End); 284 assert(*Start == ']' && "Bad plural expression syntax: expected )"); 285 ++Start; 286 return Low <= Val && Val <= High; 287} 288 289/// EvalPluralExpr - Actual expression evaluator for HandlePluralModifier. 290static bool EvalPluralExpr(unsigned ValNo, const char *Start, const char *End) { 291 // Empty condition? 292 if (*Start == ':') 293 return true; 294 295 while (1) { 296 char C = *Start; 297 if (C == '%') { 298 // Modulo expression 299 ++Start; 300 unsigned Arg = PluralNumber(Start, End); 301 assert(*Start == '=' && "Bad plural expression syntax: expected ="); 302 ++Start; 303 unsigned ValMod = ValNo % Arg; 304 if (TestPluralRange(ValMod, Start, End)) 305 return true; 306 } else { 307 assert((C == '[' || (C >= '0' && C <= '9')) && 308 "Bad plural expression syntax: unexpected character"); 309 // Range expression 310 if (TestPluralRange(ValNo, Start, End)) 311 return true; 312 } 313 314 // Scan for next or-expr part. 315 Start = std::find(Start, End, ','); 316 if (Start == End) 317 break; 318 ++Start; 319 } 320 return false; 321} 322 323/// HandlePluralModifier - Handle the integer 'plural' modifier. This is used 324/// for complex plural forms, or in languages where all plurals are complex. 325/// The syntax is: %plural{cond1:form1|cond2:form2|:form3}, where condn are 326/// conditions that are tested in order, the form corresponding to the first 327/// that applies being emitted. The empty condition is always true, making the 328/// last form a default case. 329/// Conditions are simple boolean expressions, where n is the number argument. 330/// Here are the rules. 331/// condition := expression | empty 332/// empty := -> always true 333/// expression := numeric [',' expression] -> logical or 334/// numeric := range -> true if n in range 335/// | '%' number '=' range -> true if n % number in range 336/// range := number 337/// | '[' number ',' number ']' -> ranges are inclusive both ends 338/// 339/// Here are some examples from the GNU gettext manual written in this form: 340/// English: 341/// {1:form0|:form1} 342/// Latvian: 343/// {0:form2|%100=11,%10=0,%10=[2,9]:form1|:form0} 344/// Gaeilge: 345/// {1:form0|2:form1|:form2} 346/// Romanian: 347/// {1:form0|0,%100=[1,19]:form1|:form2} 348/// Lithuanian: 349/// {%10=0,%100=[10,19]:form2|%10=1:form0|:form1} 350/// Russian (requires repeated form): 351/// {%100=[11,14]:form2|%10=1:form0|%10=[2,4]:form1|:form2} 352/// Slovak 353/// {1:form0|[2,4]:form1|:form2} 354/// Polish (requires repeated form): 355/// {1:form0|%100=[10,20]:form2|%10=[2,4]:form1|:form2} 356static void HandlePluralModifier(const DiagnosticInfo &DInfo, unsigned ValNo, 357 const char *Argument, unsigned ArgumentLen, 358 llvm::SmallVectorImpl<char> &OutStr) { 359 const char *ArgumentEnd = Argument + ArgumentLen; 360 while (1) { 361 assert(Argument < ArgumentEnd && "Plural expression didn't match."); 362 const char *ExprEnd = Argument; 363 while (*ExprEnd != ':') { 364 assert(ExprEnd != ArgumentEnd && "Plural missing expression end"); 365 ++ExprEnd; 366 } 367 if (EvalPluralExpr(ValNo, Argument, ExprEnd)) { 368 Argument = ExprEnd + 1; 369 ExprEnd = ScanFormat(Argument, ArgumentEnd, '|'); 370 371 // Recursively format the result of the plural clause into the 372 // output string. 373 DInfo.FormatDiagnostic(Argument, ExprEnd, OutStr); 374 return; 375 } 376 Argument = ScanFormat(Argument, ArgumentEnd - 1, '|') + 1; 377 } 378} 379 380 381/// FormatDiagnostic - Format this diagnostic into a string, substituting the 382/// formal arguments into the %0 slots. The result is appended onto the Str 383/// array. 384void DiagnosticInfo:: 385FormatDiagnostic(llvm::SmallVectorImpl<char> &OutStr) const { 386 const char *DiagStr = getDiags()->getDiagnosticIDs()->getDescription(getID()); 387 const char *DiagEnd = DiagStr+strlen(DiagStr); 388 389 FormatDiagnostic(DiagStr, DiagEnd, OutStr); 390} 391 392void DiagnosticInfo:: 393FormatDiagnostic(const char *DiagStr, const char *DiagEnd, 394 llvm::SmallVectorImpl<char> &OutStr) const { 395 396 /// FormattedArgs - Keep track of all of the arguments formatted by 397 /// ConvertArgToString and pass them into subsequent calls to 398 /// ConvertArgToString, allowing the implementation to avoid redundancies in 399 /// obvious cases. 400 llvm::SmallVector<Diagnostic::ArgumentValue, 8> FormattedArgs; 401 402 while (DiagStr != DiagEnd) { 403 if (DiagStr[0] != '%') { 404 // Append non-%0 substrings to Str if we have one. 405 const char *StrEnd = std::find(DiagStr, DiagEnd, '%'); 406 OutStr.append(DiagStr, StrEnd); 407 DiagStr = StrEnd; 408 continue; 409 } else if (ispunct(DiagStr[1])) { 410 OutStr.push_back(DiagStr[1]); // %% -> %. 411 DiagStr += 2; 412 continue; 413 } 414 415 // Skip the %. 416 ++DiagStr; 417 418 // This must be a placeholder for a diagnostic argument. The format for a 419 // placeholder is one of "%0", "%modifier0", or "%modifier{arguments}0". 420 // The digit is a number from 0-9 indicating which argument this comes from. 421 // The modifier is a string of digits from the set [-a-z]+, arguments is a 422 // brace enclosed string. 423 const char *Modifier = 0, *Argument = 0; 424 unsigned ModifierLen = 0, ArgumentLen = 0; 425 426 // Check to see if we have a modifier. If so eat it. 427 if (!isdigit(DiagStr[0])) { 428 Modifier = DiagStr; 429 while (DiagStr[0] == '-' || 430 (DiagStr[0] >= 'a' && DiagStr[0] <= 'z')) 431 ++DiagStr; 432 ModifierLen = DiagStr-Modifier; 433 434 // If we have an argument, get it next. 435 if (DiagStr[0] == '{') { 436 ++DiagStr; // Skip {. 437 Argument = DiagStr; 438 439 DiagStr = ScanFormat(DiagStr, DiagEnd, '}'); 440 assert(DiagStr != DiagEnd && "Mismatched {}'s in diagnostic string!"); 441 ArgumentLen = DiagStr-Argument; 442 ++DiagStr; // Skip }. 443 } 444 } 445 446 assert(isdigit(*DiagStr) && "Invalid format for argument in diagnostic"); 447 unsigned ArgNo = *DiagStr++ - '0'; 448 449 Diagnostic::ArgumentKind Kind = getArgKind(ArgNo); 450 451 switch (Kind) { 452 // ---- STRINGS ---- 453 case Diagnostic::ak_std_string: { 454 const std::string &S = getArgStdStr(ArgNo); 455 assert(ModifierLen == 0 && "No modifiers for strings yet"); 456 OutStr.append(S.begin(), S.end()); 457 break; 458 } 459 case Diagnostic::ak_c_string: { 460 const char *S = getArgCStr(ArgNo); 461 assert(ModifierLen == 0 && "No modifiers for strings yet"); 462 463 // Don't crash if get passed a null pointer by accident. 464 if (!S) 465 S = "(null)"; 466 467 OutStr.append(S, S + strlen(S)); 468 break; 469 } 470 // ---- INTEGERS ---- 471 case Diagnostic::ak_sint: { 472 int Val = getArgSInt(ArgNo); 473 474 if (ModifierIs(Modifier, ModifierLen, "select")) { 475 HandleSelectModifier(*this, (unsigned)Val, Argument, ArgumentLen, 476 OutStr); 477 } else if (ModifierIs(Modifier, ModifierLen, "s")) { 478 HandleIntegerSModifier(Val, OutStr); 479 } else if (ModifierIs(Modifier, ModifierLen, "plural")) { 480 HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen, 481 OutStr); 482 } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) { 483 HandleOrdinalModifier((unsigned)Val, OutStr); 484 } else { 485 assert(ModifierLen == 0 && "Unknown integer modifier"); 486 llvm::raw_svector_ostream(OutStr) << Val; 487 } 488 break; 489 } 490 case Diagnostic::ak_uint: { 491 unsigned Val = getArgUInt(ArgNo); 492 493 if (ModifierIs(Modifier, ModifierLen, "select")) { 494 HandleSelectModifier(*this, Val, Argument, ArgumentLen, OutStr); 495 } else if (ModifierIs(Modifier, ModifierLen, "s")) { 496 HandleIntegerSModifier(Val, OutStr); 497 } else if (ModifierIs(Modifier, ModifierLen, "plural")) { 498 HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen, 499 OutStr); 500 } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) { 501 HandleOrdinalModifier(Val, OutStr); 502 } else { 503 assert(ModifierLen == 0 && "Unknown integer modifier"); 504 llvm::raw_svector_ostream(OutStr) << Val; 505 } 506 break; 507 } 508 // ---- NAMES and TYPES ---- 509 case Diagnostic::ak_identifierinfo: { 510 const IdentifierInfo *II = getArgIdentifier(ArgNo); 511 assert(ModifierLen == 0 && "No modifiers for strings yet"); 512 513 // Don't crash if get passed a null pointer by accident. 514 if (!II) { 515 const char *S = "(null)"; 516 OutStr.append(S, S + strlen(S)); 517 continue; 518 } 519 520 llvm::raw_svector_ostream(OutStr) << '\'' << II->getName() << '\''; 521 break; 522 } 523 case Diagnostic::ak_qualtype: 524 case Diagnostic::ak_declarationname: 525 case Diagnostic::ak_nameddecl: 526 case Diagnostic::ak_nestednamespec: 527 case Diagnostic::ak_declcontext: 528 getDiags()->ConvertArgToString(Kind, getRawArg(ArgNo), 529 Modifier, ModifierLen, 530 Argument, ArgumentLen, 531 FormattedArgs.data(), FormattedArgs.size(), 532 OutStr); 533 break; 534 } 535 536 // Remember this argument info for subsequent formatting operations. Turn 537 // std::strings into a null terminated string to make it be the same case as 538 // all the other ones. 539 if (Kind != Diagnostic::ak_std_string) 540 FormattedArgs.push_back(std::make_pair(Kind, getRawArg(ArgNo))); 541 else 542 FormattedArgs.push_back(std::make_pair(Diagnostic::ak_c_string, 543 (intptr_t)getArgStdStr(ArgNo).c_str())); 544 545 } 546} 547 548StoredDiagnostic::StoredDiagnostic() { } 549 550StoredDiagnostic::StoredDiagnostic(Diagnostic::Level Level, unsigned ID, 551 llvm::StringRef Message) 552 : ID(ID), Level(Level), Loc(), Message(Message) { } 553 554StoredDiagnostic::StoredDiagnostic(Diagnostic::Level Level, 555 const DiagnosticInfo &Info) 556 : ID(Info.getID()), Level(Level) 557{ 558 assert((Info.getLocation().isInvalid() || Info.hasSourceManager()) && 559 "Valid source location without setting a source manager for diagnostic"); 560 if (Info.getLocation().isValid()) 561 Loc = FullSourceLoc(Info.getLocation(), Info.getSourceManager()); 562 llvm::SmallString<64> Message; 563 Info.FormatDiagnostic(Message); 564 this->Message.assign(Message.begin(), Message.end()); 565 566 Ranges.reserve(Info.getNumRanges()); 567 for (unsigned I = 0, N = Info.getNumRanges(); I != N; ++I) 568 Ranges.push_back(Info.getRange(I)); 569 570 FixIts.reserve(Info.getNumFixItHints()); 571 for (unsigned I = 0, N = Info.getNumFixItHints(); I != N; ++I) 572 FixIts.push_back(Info.getFixItHint(I)); 573} 574 575StoredDiagnostic::~StoredDiagnostic() { } 576 577/// IncludeInDiagnosticCounts - This method (whose default implementation 578/// returns true) indicates whether the diagnostics handled by this 579/// DiagnosticClient should be included in the number of diagnostics 580/// reported by Diagnostic. 581bool DiagnosticClient::IncludeInDiagnosticCounts() const { return true; } 582 583PartialDiagnostic::StorageAllocator::StorageAllocator() { 584 for (unsigned I = 0; I != NumCached; ++I) 585 FreeList[I] = Cached + I; 586 NumFreeListEntries = NumCached; 587} 588 589PartialDiagnostic::StorageAllocator::~StorageAllocator() { 590 assert(NumFreeListEntries == NumCached && "A partial is on the lamb"); 591} 592