clang API Documentation
00001 //===--- Diagnostic.cpp - C Language Family Diagnostic Handling -----------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file implements the Diagnostic-related interfaces. 00011 // 00012 //===----------------------------------------------------------------------===// 00013 00014 #include "clang/Basic/CharInfo.h" 00015 #include "clang/Basic/Diagnostic.h" 00016 #include "clang/Basic/DiagnosticOptions.h" 00017 #include "clang/Basic/IdentifierTable.h" 00018 #include "clang/Basic/PartialDiagnostic.h" 00019 #include "llvm/ADT/SmallString.h" 00020 #include "llvm/ADT/StringExtras.h" 00021 #include "llvm/Support/CrashRecoveryContext.h" 00022 #include "llvm/Support/raw_ostream.h" 00023 00024 using namespace clang; 00025 00026 static void DummyArgToStringFn(DiagnosticsEngine::ArgumentKind AK, intptr_t QT, 00027 StringRef Modifier, StringRef Argument, 00028 ArrayRef<DiagnosticsEngine::ArgumentValue> PrevArgs, 00029 SmallVectorImpl<char> &Output, 00030 void *Cookie, 00031 ArrayRef<intptr_t> QualTypeVals) { 00032 StringRef Str = "<can't format argument>"; 00033 Output.append(Str.begin(), Str.end()); 00034 } 00035 00036 DiagnosticsEngine::DiagnosticsEngine( 00037 const IntrusiveRefCntPtr<DiagnosticIDs> &diags, DiagnosticOptions *DiagOpts, 00038 DiagnosticConsumer *client, bool ShouldOwnClient) 00039 : Diags(diags), DiagOpts(DiagOpts), Client(nullptr), SourceMgr(nullptr) { 00040 setClient(client, ShouldOwnClient); 00041 ArgToStringFn = DummyArgToStringFn; 00042 ArgToStringCookie = nullptr; 00043 00044 AllExtensionsSilenced = 0; 00045 IgnoreAllWarnings = false; 00046 WarningsAsErrors = false; 00047 EnableAllWarnings = false; 00048 ErrorsAsFatal = false; 00049 SuppressSystemWarnings = false; 00050 SuppressAllDiagnostics = false; 00051 ElideType = true; 00052 PrintTemplateTree = false; 00053 ShowColors = false; 00054 ShowOverloads = Ovl_All; 00055 ExtBehavior = diag::Severity::Ignored; 00056 00057 ErrorLimit = 0; 00058 TemplateBacktraceLimit = 0; 00059 ConstexprBacktraceLimit = 0; 00060 00061 Reset(); 00062 } 00063 00064 void DiagnosticsEngine::setClient(DiagnosticConsumer *client, 00065 bool ShouldOwnClient) { 00066 Owner.reset(ShouldOwnClient ? client : nullptr); 00067 Client = client; 00068 } 00069 00070 void DiagnosticsEngine::pushMappings(SourceLocation Loc) { 00071 DiagStateOnPushStack.push_back(GetCurDiagState()); 00072 } 00073 00074 bool DiagnosticsEngine::popMappings(SourceLocation Loc) { 00075 if (DiagStateOnPushStack.empty()) 00076 return false; 00077 00078 if (DiagStateOnPushStack.back() != GetCurDiagState()) { 00079 // State changed at some point between push/pop. 00080 PushDiagStatePoint(DiagStateOnPushStack.back(), Loc); 00081 } 00082 DiagStateOnPushStack.pop_back(); 00083 return true; 00084 } 00085 00086 void DiagnosticsEngine::Reset() { 00087 ErrorOccurred = false; 00088 UncompilableErrorOccurred = false; 00089 FatalErrorOccurred = false; 00090 UnrecoverableErrorOccurred = false; 00091 00092 NumWarnings = 0; 00093 NumErrors = 0; 00094 TrapNumErrorsOccurred = 0; 00095 TrapNumUnrecoverableErrorsOccurred = 0; 00096 00097 CurDiagID = ~0U; 00098 LastDiagLevel = DiagnosticIDs::Ignored; 00099 DelayedDiagID = 0; 00100 00101 // Clear state related to #pragma diagnostic. 00102 DiagStates.clear(); 00103 DiagStatePoints.clear(); 00104 DiagStateOnPushStack.clear(); 00105 00106 // Create a DiagState and DiagStatePoint representing diagnostic changes 00107 // through command-line. 00108 DiagStates.push_back(DiagState()); 00109 DiagStatePoints.push_back(DiagStatePoint(&DiagStates.back(), FullSourceLoc())); 00110 } 00111 00112 void DiagnosticsEngine::SetDelayedDiagnostic(unsigned DiagID, StringRef Arg1, 00113 StringRef Arg2) { 00114 if (DelayedDiagID) 00115 return; 00116 00117 DelayedDiagID = DiagID; 00118 DelayedDiagArg1 = Arg1.str(); 00119 DelayedDiagArg2 = Arg2.str(); 00120 } 00121 00122 void DiagnosticsEngine::ReportDelayed() { 00123 Report(DelayedDiagID) << DelayedDiagArg1 << DelayedDiagArg2; 00124 DelayedDiagID = 0; 00125 DelayedDiagArg1.clear(); 00126 DelayedDiagArg2.clear(); 00127 } 00128 00129 DiagnosticsEngine::DiagStatePointsTy::iterator 00130 DiagnosticsEngine::GetDiagStatePointForLoc(SourceLocation L) const { 00131 assert(!DiagStatePoints.empty()); 00132 assert(DiagStatePoints.front().Loc.isInvalid() && 00133 "Should have created a DiagStatePoint for command-line"); 00134 00135 if (!SourceMgr) 00136 return DiagStatePoints.end() - 1; 00137 00138 FullSourceLoc Loc(L, *SourceMgr); 00139 if (Loc.isInvalid()) 00140 return DiagStatePoints.end() - 1; 00141 00142 DiagStatePointsTy::iterator Pos = DiagStatePoints.end(); 00143 FullSourceLoc LastStateChangePos = DiagStatePoints.back().Loc; 00144 if (LastStateChangePos.isValid() && 00145 Loc.isBeforeInTranslationUnitThan(LastStateChangePos)) 00146 Pos = std::upper_bound(DiagStatePoints.begin(), DiagStatePoints.end(), 00147 DiagStatePoint(nullptr, Loc)); 00148 --Pos; 00149 return Pos; 00150 } 00151 00152 void DiagnosticsEngine::setSeverity(diag::kind Diag, diag::Severity Map, 00153 SourceLocation L) { 00154 assert(Diag < diag::DIAG_UPPER_LIMIT && 00155 "Can only map builtin diagnostics"); 00156 assert((Diags->isBuiltinWarningOrExtension(Diag) || 00157 (Map == diag::Severity::Fatal || Map == diag::Severity::Error)) && 00158 "Cannot map errors into warnings!"); 00159 assert(!DiagStatePoints.empty()); 00160 assert((L.isInvalid() || SourceMgr) && "No SourceMgr for valid location"); 00161 00162 FullSourceLoc Loc = SourceMgr? FullSourceLoc(L, *SourceMgr) : FullSourceLoc(); 00163 FullSourceLoc LastStateChangePos = DiagStatePoints.back().Loc; 00164 // Don't allow a mapping to a warning override an error/fatal mapping. 00165 if (Map == diag::Severity::Warning) { 00166 DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(Diag); 00167 if (Info.getSeverity() == diag::Severity::Error || 00168 Info.getSeverity() == diag::Severity::Fatal) 00169 Map = Info.getSeverity(); 00170 } 00171 DiagnosticMapping Mapping = makeUserMapping(Map, L); 00172 00173 // Common case; setting all the diagnostics of a group in one place. 00174 if (Loc.isInvalid() || Loc == LastStateChangePos) { 00175 GetCurDiagState()->setMapping(Diag, Mapping); 00176 return; 00177 } 00178 00179 // Another common case; modifying diagnostic state in a source location 00180 // after the previous one. 00181 if ((Loc.isValid() && LastStateChangePos.isInvalid()) || 00182 LastStateChangePos.isBeforeInTranslationUnitThan(Loc)) { 00183 // A diagnostic pragma occurred, create a new DiagState initialized with 00184 // the current one and a new DiagStatePoint to record at which location 00185 // the new state became active. 00186 DiagStates.push_back(*GetCurDiagState()); 00187 PushDiagStatePoint(&DiagStates.back(), Loc); 00188 GetCurDiagState()->setMapping(Diag, Mapping); 00189 return; 00190 } 00191 00192 // We allow setting the diagnostic state in random source order for 00193 // completeness but it should not be actually happening in normal practice. 00194 00195 DiagStatePointsTy::iterator Pos = GetDiagStatePointForLoc(Loc); 00196 assert(Pos != DiagStatePoints.end()); 00197 00198 // Update all diagnostic states that are active after the given location. 00199 for (DiagStatePointsTy::iterator 00200 I = Pos+1, E = DiagStatePoints.end(); I != E; ++I) { 00201 GetCurDiagState()->setMapping(Diag, Mapping); 00202 } 00203 00204 // If the location corresponds to an existing point, just update its state. 00205 if (Pos->Loc == Loc) { 00206 GetCurDiagState()->setMapping(Diag, Mapping); 00207 return; 00208 } 00209 00210 // Create a new state/point and fit it into the vector of DiagStatePoints 00211 // so that the vector is always ordered according to location. 00212 assert(Pos->Loc.isBeforeInTranslationUnitThan(Loc)); 00213 DiagStates.push_back(*Pos->State); 00214 DiagState *NewState = &DiagStates.back(); 00215 GetCurDiagState()->setMapping(Diag, Mapping); 00216 DiagStatePoints.insert(Pos+1, DiagStatePoint(NewState, 00217 FullSourceLoc(Loc, *SourceMgr))); 00218 } 00219 00220 bool DiagnosticsEngine::setSeverityForGroup(diag::Flavor Flavor, 00221 StringRef Group, diag::Severity Map, 00222 SourceLocation Loc) { 00223 // Get the diagnostics in this group. 00224 SmallVector<diag::kind, 256> GroupDiags; 00225 if (Diags->getDiagnosticsInGroup(Flavor, Group, GroupDiags)) 00226 return true; 00227 00228 // Set the mapping. 00229 for (diag::kind Diag : GroupDiags) 00230 setSeverity(Diag, Map, Loc); 00231 00232 return false; 00233 } 00234 00235 bool DiagnosticsEngine::setDiagnosticGroupWarningAsError(StringRef Group, 00236 bool Enabled) { 00237 // If we are enabling this feature, just set the diagnostic mappings to map to 00238 // errors. 00239 if (Enabled) 00240 return setSeverityForGroup(diag::Flavor::WarningOrError, Group, 00241 diag::Severity::Error); 00242 00243 // Otherwise, we want to set the diagnostic mapping's "no Werror" bit, and 00244 // potentially downgrade anything already mapped to be a warning. 00245 00246 // Get the diagnostics in this group. 00247 SmallVector<diag::kind, 8> GroupDiags; 00248 if (Diags->getDiagnosticsInGroup(diag::Flavor::WarningOrError, Group, 00249 GroupDiags)) 00250 return true; 00251 00252 // Perform the mapping change. 00253 for (unsigned i = 0, e = GroupDiags.size(); i != e; ++i) { 00254 DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(GroupDiags[i]); 00255 00256 if (Info.getSeverity() == diag::Severity::Error || 00257 Info.getSeverity() == diag::Severity::Fatal) 00258 Info.setSeverity(diag::Severity::Warning); 00259 00260 Info.setNoWarningAsError(true); 00261 } 00262 00263 return false; 00264 } 00265 00266 bool DiagnosticsEngine::setDiagnosticGroupErrorAsFatal(StringRef Group, 00267 bool Enabled) { 00268 // If we are enabling this feature, just set the diagnostic mappings to map to 00269 // fatal errors. 00270 if (Enabled) 00271 return setSeverityForGroup(diag::Flavor::WarningOrError, Group, 00272 diag::Severity::Fatal); 00273 00274 // Otherwise, we want to set the diagnostic mapping's "no Werror" bit, and 00275 // potentially downgrade anything already mapped to be an error. 00276 00277 // Get the diagnostics in this group. 00278 SmallVector<diag::kind, 8> GroupDiags; 00279 if (Diags->getDiagnosticsInGroup(diag::Flavor::WarningOrError, Group, 00280 GroupDiags)) 00281 return true; 00282 00283 // Perform the mapping change. 00284 for (unsigned i = 0, e = GroupDiags.size(); i != e; ++i) { 00285 DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(GroupDiags[i]); 00286 00287 if (Info.getSeverity() == diag::Severity::Fatal) 00288 Info.setSeverity(diag::Severity::Error); 00289 00290 Info.setNoErrorAsFatal(true); 00291 } 00292 00293 return false; 00294 } 00295 00296 void DiagnosticsEngine::setSeverityForAll(diag::Flavor Flavor, 00297 diag::Severity Map, 00298 SourceLocation Loc) { 00299 // Get all the diagnostics. 00300 SmallVector<diag::kind, 64> AllDiags; 00301 Diags->getAllDiagnostics(Flavor, AllDiags); 00302 00303 // Set the mapping. 00304 for (unsigned i = 0, e = AllDiags.size(); i != e; ++i) 00305 if (Diags->isBuiltinWarningOrExtension(AllDiags[i])) 00306 setSeverity(AllDiags[i], Map, Loc); 00307 } 00308 00309 void DiagnosticsEngine::Report(const StoredDiagnostic &storedDiag) { 00310 assert(CurDiagID == ~0U && "Multiple diagnostics in flight at once!"); 00311 00312 CurDiagLoc = storedDiag.getLocation(); 00313 CurDiagID = storedDiag.getID(); 00314 NumDiagArgs = 0; 00315 00316 DiagRanges.clear(); 00317 DiagRanges.reserve(storedDiag.range_size()); 00318 for (StoredDiagnostic::range_iterator 00319 RI = storedDiag.range_begin(), 00320 RE = storedDiag.range_end(); RI != RE; ++RI) 00321 DiagRanges.push_back(*RI); 00322 00323 DiagFixItHints.clear(); 00324 DiagFixItHints.reserve(storedDiag.fixit_size()); 00325 for (StoredDiagnostic::fixit_iterator 00326 FI = storedDiag.fixit_begin(), 00327 FE = storedDiag.fixit_end(); FI != FE; ++FI) 00328 DiagFixItHints.push_back(*FI); 00329 00330 assert(Client && "DiagnosticConsumer not set!"); 00331 Level DiagLevel = storedDiag.getLevel(); 00332 Diagnostic Info(this, storedDiag.getMessage()); 00333 Client->HandleDiagnostic(DiagLevel, Info); 00334 if (Client->IncludeInDiagnosticCounts()) { 00335 if (DiagLevel == DiagnosticsEngine::Warning) 00336 ++NumWarnings; 00337 } 00338 00339 CurDiagID = ~0U; 00340 } 00341 00342 bool DiagnosticsEngine::EmitCurrentDiagnostic(bool Force) { 00343 assert(getClient() && "DiagnosticClient not set!"); 00344 00345 bool Emitted; 00346 if (Force) { 00347 Diagnostic Info(this); 00348 00349 // Figure out the diagnostic level of this message. 00350 DiagnosticIDs::Level DiagLevel 00351 = Diags->getDiagnosticLevel(Info.getID(), Info.getLocation(), *this); 00352 00353 Emitted = (DiagLevel != DiagnosticIDs::Ignored); 00354 if (Emitted) { 00355 // Emit the diagnostic regardless of suppression level. 00356 Diags->EmitDiag(*this, DiagLevel); 00357 } 00358 } else { 00359 // Process the diagnostic, sending the accumulated information to the 00360 // DiagnosticConsumer. 00361 Emitted = ProcessDiag(); 00362 } 00363 00364 // Clear out the current diagnostic object. 00365 unsigned DiagID = CurDiagID; 00366 Clear(); 00367 00368 // If there was a delayed diagnostic, emit it now. 00369 if (!Force && DelayedDiagID && DelayedDiagID != DiagID) 00370 ReportDelayed(); 00371 00372 return Emitted; 00373 } 00374 00375 00376 DiagnosticConsumer::~DiagnosticConsumer() {} 00377 00378 void DiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, 00379 const Diagnostic &Info) { 00380 if (!IncludeInDiagnosticCounts()) 00381 return; 00382 00383 if (DiagLevel == DiagnosticsEngine::Warning) 00384 ++NumWarnings; 00385 else if (DiagLevel >= DiagnosticsEngine::Error) 00386 ++NumErrors; 00387 } 00388 00389 /// ModifierIs - Return true if the specified modifier matches specified string. 00390 template <std::size_t StrLen> 00391 static bool ModifierIs(const char *Modifier, unsigned ModifierLen, 00392 const char (&Str)[StrLen]) { 00393 return StrLen-1 == ModifierLen && !memcmp(Modifier, Str, StrLen-1); 00394 } 00395 00396 /// ScanForward - Scans forward, looking for the given character, skipping 00397 /// nested clauses and escaped characters. 00398 static const char *ScanFormat(const char *I, const char *E, char Target) { 00399 unsigned Depth = 0; 00400 00401 for ( ; I != E; ++I) { 00402 if (Depth == 0 && *I == Target) return I; 00403 if (Depth != 0 && *I == '}') Depth--; 00404 00405 if (*I == '%') { 00406 I++; 00407 if (I == E) break; 00408 00409 // Escaped characters get implicitly skipped here. 00410 00411 // Format specifier. 00412 if (!isDigit(*I) && !isPunctuation(*I)) { 00413 for (I++; I != E && !isDigit(*I) && *I != '{'; I++) ; 00414 if (I == E) break; 00415 if (*I == '{') 00416 Depth++; 00417 } 00418 } 00419 } 00420 return E; 00421 } 00422 00423 /// HandleSelectModifier - Handle the integer 'select' modifier. This is used 00424 /// like this: %select{foo|bar|baz}2. This means that the integer argument 00425 /// "%2" has a value from 0-2. If the value is 0, the diagnostic prints 'foo'. 00426 /// If the value is 1, it prints 'bar'. If it has the value 2, it prints 'baz'. 00427 /// This is very useful for certain classes of variant diagnostics. 00428 static void HandleSelectModifier(const Diagnostic &DInfo, unsigned ValNo, 00429 const char *Argument, unsigned ArgumentLen, 00430 SmallVectorImpl<char> &OutStr) { 00431 const char *ArgumentEnd = Argument+ArgumentLen; 00432 00433 // Skip over 'ValNo' |'s. 00434 while (ValNo) { 00435 const char *NextVal = ScanFormat(Argument, ArgumentEnd, '|'); 00436 assert(NextVal != ArgumentEnd && "Value for integer select modifier was" 00437 " larger than the number of options in the diagnostic string!"); 00438 Argument = NextVal+1; // Skip this string. 00439 --ValNo; 00440 } 00441 00442 // Get the end of the value. This is either the } or the |. 00443 const char *EndPtr = ScanFormat(Argument, ArgumentEnd, '|'); 00444 00445 // Recursively format the result of the select clause into the output string. 00446 DInfo.FormatDiagnostic(Argument, EndPtr, OutStr); 00447 } 00448 00449 /// HandleIntegerSModifier - Handle the integer 's' modifier. This adds the 00450 /// letter 's' to the string if the value is not 1. This is used in cases like 00451 /// this: "you idiot, you have %4 parameter%s4!". 00452 static void HandleIntegerSModifier(unsigned ValNo, 00453 SmallVectorImpl<char> &OutStr) { 00454 if (ValNo != 1) 00455 OutStr.push_back('s'); 00456 } 00457 00458 /// HandleOrdinalModifier - Handle the integer 'ord' modifier. This 00459 /// prints the ordinal form of the given integer, with 1 corresponding 00460 /// to the first ordinal. Currently this is hard-coded to use the 00461 /// English form. 00462 static void HandleOrdinalModifier(unsigned ValNo, 00463 SmallVectorImpl<char> &OutStr) { 00464 assert(ValNo != 0 && "ValNo must be strictly positive!"); 00465 00466 llvm::raw_svector_ostream Out(OutStr); 00467 00468 // We could use text forms for the first N ordinals, but the numeric 00469 // forms are actually nicer in diagnostics because they stand out. 00470 Out << ValNo << llvm::getOrdinalSuffix(ValNo); 00471 } 00472 00473 00474 /// PluralNumber - Parse an unsigned integer and advance Start. 00475 static unsigned PluralNumber(const char *&Start, const char *End) { 00476 // Programming 101: Parse a decimal number :-) 00477 unsigned Val = 0; 00478 while (Start != End && *Start >= '0' && *Start <= '9') { 00479 Val *= 10; 00480 Val += *Start - '0'; 00481 ++Start; 00482 } 00483 return Val; 00484 } 00485 00486 /// TestPluralRange - Test if Val is in the parsed range. Modifies Start. 00487 static bool TestPluralRange(unsigned Val, const char *&Start, const char *End) { 00488 if (*Start != '[') { 00489 unsigned Ref = PluralNumber(Start, End); 00490 return Ref == Val; 00491 } 00492 00493 ++Start; 00494 unsigned Low = PluralNumber(Start, End); 00495 assert(*Start == ',' && "Bad plural expression syntax: expected ,"); 00496 ++Start; 00497 unsigned High = PluralNumber(Start, End); 00498 assert(*Start == ']' && "Bad plural expression syntax: expected )"); 00499 ++Start; 00500 return Low <= Val && Val <= High; 00501 } 00502 00503 /// EvalPluralExpr - Actual expression evaluator for HandlePluralModifier. 00504 static bool EvalPluralExpr(unsigned ValNo, const char *Start, const char *End) { 00505 // Empty condition? 00506 if (*Start == ':') 00507 return true; 00508 00509 while (1) { 00510 char C = *Start; 00511 if (C == '%') { 00512 // Modulo expression 00513 ++Start; 00514 unsigned Arg = PluralNumber(Start, End); 00515 assert(*Start == '=' && "Bad plural expression syntax: expected ="); 00516 ++Start; 00517 unsigned ValMod = ValNo % Arg; 00518 if (TestPluralRange(ValMod, Start, End)) 00519 return true; 00520 } else { 00521 assert((C == '[' || (C >= '0' && C <= '9')) && 00522 "Bad plural expression syntax: unexpected character"); 00523 // Range expression 00524 if (TestPluralRange(ValNo, Start, End)) 00525 return true; 00526 } 00527 00528 // Scan for next or-expr part. 00529 Start = std::find(Start, End, ','); 00530 if (Start == End) 00531 break; 00532 ++Start; 00533 } 00534 return false; 00535 } 00536 00537 /// HandlePluralModifier - Handle the integer 'plural' modifier. This is used 00538 /// for complex plural forms, or in languages where all plurals are complex. 00539 /// The syntax is: %plural{cond1:form1|cond2:form2|:form3}, where condn are 00540 /// conditions that are tested in order, the form corresponding to the first 00541 /// that applies being emitted. The empty condition is always true, making the 00542 /// last form a default case. 00543 /// Conditions are simple boolean expressions, where n is the number argument. 00544 /// Here are the rules. 00545 /// condition := expression | empty 00546 /// empty := -> always true 00547 /// expression := numeric [',' expression] -> logical or 00548 /// numeric := range -> true if n in range 00549 /// | '%' number '=' range -> true if n % number in range 00550 /// range := number 00551 /// | '[' number ',' number ']' -> ranges are inclusive both ends 00552 /// 00553 /// Here are some examples from the GNU gettext manual written in this form: 00554 /// English: 00555 /// {1:form0|:form1} 00556 /// Latvian: 00557 /// {0:form2|%100=11,%10=0,%10=[2,9]:form1|:form0} 00558 /// Gaeilge: 00559 /// {1:form0|2:form1|:form2} 00560 /// Romanian: 00561 /// {1:form0|0,%100=[1,19]:form1|:form2} 00562 /// Lithuanian: 00563 /// {%10=0,%100=[10,19]:form2|%10=1:form0|:form1} 00564 /// Russian (requires repeated form): 00565 /// {%100=[11,14]:form2|%10=1:form0|%10=[2,4]:form1|:form2} 00566 /// Slovak 00567 /// {1:form0|[2,4]:form1|:form2} 00568 /// Polish (requires repeated form): 00569 /// {1:form0|%100=[10,20]:form2|%10=[2,4]:form1|:form2} 00570 static void HandlePluralModifier(const Diagnostic &DInfo, unsigned ValNo, 00571 const char *Argument, unsigned ArgumentLen, 00572 SmallVectorImpl<char> &OutStr) { 00573 const char *ArgumentEnd = Argument + ArgumentLen; 00574 while (1) { 00575 assert(Argument < ArgumentEnd && "Plural expression didn't match."); 00576 const char *ExprEnd = Argument; 00577 while (*ExprEnd != ':') { 00578 assert(ExprEnd != ArgumentEnd && "Plural missing expression end"); 00579 ++ExprEnd; 00580 } 00581 if (EvalPluralExpr(ValNo, Argument, ExprEnd)) { 00582 Argument = ExprEnd + 1; 00583 ExprEnd = ScanFormat(Argument, ArgumentEnd, '|'); 00584 00585 // Recursively format the result of the plural clause into the 00586 // output string. 00587 DInfo.FormatDiagnostic(Argument, ExprEnd, OutStr); 00588 return; 00589 } 00590 Argument = ScanFormat(Argument, ArgumentEnd - 1, '|') + 1; 00591 } 00592 } 00593 00594 /// \brief Returns the friendly description for a token kind that will appear 00595 /// without quotes in diagnostic messages. These strings may be translatable in 00596 /// future. 00597 static const char *getTokenDescForDiagnostic(tok::TokenKind Kind) { 00598 switch (Kind) { 00599 case tok::identifier: 00600 return "identifier"; 00601 default: 00602 return nullptr; 00603 } 00604 } 00605 00606 /// FormatDiagnostic - Format this diagnostic into a string, substituting the 00607 /// formal arguments into the %0 slots. The result is appended onto the Str 00608 /// array. 00609 void Diagnostic:: 00610 FormatDiagnostic(SmallVectorImpl<char> &OutStr) const { 00611 if (!StoredDiagMessage.empty()) { 00612 OutStr.append(StoredDiagMessage.begin(), StoredDiagMessage.end()); 00613 return; 00614 } 00615 00616 StringRef Diag = 00617 getDiags()->getDiagnosticIDs()->getDescription(getID()); 00618 00619 FormatDiagnostic(Diag.begin(), Diag.end(), OutStr); 00620 } 00621 00622 void Diagnostic:: 00623 FormatDiagnostic(const char *DiagStr, const char *DiagEnd, 00624 SmallVectorImpl<char> &OutStr) const { 00625 00626 /// FormattedArgs - Keep track of all of the arguments formatted by 00627 /// ConvertArgToString and pass them into subsequent calls to 00628 /// ConvertArgToString, allowing the implementation to avoid redundancies in 00629 /// obvious cases. 00630 SmallVector<DiagnosticsEngine::ArgumentValue, 8> FormattedArgs; 00631 00632 /// QualTypeVals - Pass a vector of arrays so that QualType names can be 00633 /// compared to see if more information is needed to be printed. 00634 SmallVector<intptr_t, 2> QualTypeVals; 00635 SmallVector<char, 64> Tree; 00636 00637 for (unsigned i = 0, e = getNumArgs(); i < e; ++i) 00638 if (getArgKind(i) == DiagnosticsEngine::ak_qualtype) 00639 QualTypeVals.push_back(getRawArg(i)); 00640 00641 while (DiagStr != DiagEnd) { 00642 if (DiagStr[0] != '%') { 00643 // Append non-%0 substrings to Str if we have one. 00644 const char *StrEnd = std::find(DiagStr, DiagEnd, '%'); 00645 OutStr.append(DiagStr, StrEnd); 00646 DiagStr = StrEnd; 00647 continue; 00648 } else if (isPunctuation(DiagStr[1])) { 00649 OutStr.push_back(DiagStr[1]); // %% -> %. 00650 DiagStr += 2; 00651 continue; 00652 } 00653 00654 // Skip the %. 00655 ++DiagStr; 00656 00657 // This must be a placeholder for a diagnostic argument. The format for a 00658 // placeholder is one of "%0", "%modifier0", or "%modifier{arguments}0". 00659 // The digit is a number from 0-9 indicating which argument this comes from. 00660 // The modifier is a string of digits from the set [-a-z]+, arguments is a 00661 // brace enclosed string. 00662 const char *Modifier = nullptr, *Argument = nullptr; 00663 unsigned ModifierLen = 0, ArgumentLen = 0; 00664 00665 // Check to see if we have a modifier. If so eat it. 00666 if (!isDigit(DiagStr[0])) { 00667 Modifier = DiagStr; 00668 while (DiagStr[0] == '-' || 00669 (DiagStr[0] >= 'a' && DiagStr[0] <= 'z')) 00670 ++DiagStr; 00671 ModifierLen = DiagStr-Modifier; 00672 00673 // If we have an argument, get it next. 00674 if (DiagStr[0] == '{') { 00675 ++DiagStr; // Skip {. 00676 Argument = DiagStr; 00677 00678 DiagStr = ScanFormat(DiagStr, DiagEnd, '}'); 00679 assert(DiagStr != DiagEnd && "Mismatched {}'s in diagnostic string!"); 00680 ArgumentLen = DiagStr-Argument; 00681 ++DiagStr; // Skip }. 00682 } 00683 } 00684 00685 assert(isDigit(*DiagStr) && "Invalid format for argument in diagnostic"); 00686 unsigned ArgNo = *DiagStr++ - '0'; 00687 00688 // Only used for type diffing. 00689 unsigned ArgNo2 = ArgNo; 00690 00691 DiagnosticsEngine::ArgumentKind Kind = getArgKind(ArgNo); 00692 if (ModifierIs(Modifier, ModifierLen, "diff")) { 00693 assert(*DiagStr == ',' && isDigit(*(DiagStr + 1)) && 00694 "Invalid format for diff modifier"); 00695 ++DiagStr; // Comma. 00696 ArgNo2 = *DiagStr++ - '0'; 00697 DiagnosticsEngine::ArgumentKind Kind2 = getArgKind(ArgNo2); 00698 if (Kind == DiagnosticsEngine::ak_qualtype && 00699 Kind2 == DiagnosticsEngine::ak_qualtype) 00700 Kind = DiagnosticsEngine::ak_qualtype_pair; 00701 else { 00702 // %diff only supports QualTypes. For other kinds of arguments, 00703 // use the default printing. For example, if the modifier is: 00704 // "%diff{compare $ to $|other text}1,2" 00705 // treat it as: 00706 // "compare %1 to %2" 00707 const char *Pipe = ScanFormat(Argument, Argument + ArgumentLen, '|'); 00708 const char *FirstDollar = ScanFormat(Argument, Pipe, '$'); 00709 const char *SecondDollar = ScanFormat(FirstDollar + 1, Pipe, '$'); 00710 const char ArgStr1[] = { '%', static_cast<char>('0' + ArgNo) }; 00711 const char ArgStr2[] = { '%', static_cast<char>('0' + ArgNo2) }; 00712 FormatDiagnostic(Argument, FirstDollar, OutStr); 00713 FormatDiagnostic(ArgStr1, ArgStr1 + 2, OutStr); 00714 FormatDiagnostic(FirstDollar + 1, SecondDollar, OutStr); 00715 FormatDiagnostic(ArgStr2, ArgStr2 + 2, OutStr); 00716 FormatDiagnostic(SecondDollar + 1, Pipe, OutStr); 00717 continue; 00718 } 00719 } 00720 00721 switch (Kind) { 00722 // ---- STRINGS ---- 00723 case DiagnosticsEngine::ak_std_string: { 00724 const std::string &S = getArgStdStr(ArgNo); 00725 assert(ModifierLen == 0 && "No modifiers for strings yet"); 00726 OutStr.append(S.begin(), S.end()); 00727 break; 00728 } 00729 case DiagnosticsEngine::ak_c_string: { 00730 const char *S = getArgCStr(ArgNo); 00731 assert(ModifierLen == 0 && "No modifiers for strings yet"); 00732 00733 // Don't crash if get passed a null pointer by accident. 00734 if (!S) 00735 S = "(null)"; 00736 00737 OutStr.append(S, S + strlen(S)); 00738 break; 00739 } 00740 // ---- INTEGERS ---- 00741 case DiagnosticsEngine::ak_sint: { 00742 int Val = getArgSInt(ArgNo); 00743 00744 if (ModifierIs(Modifier, ModifierLen, "select")) { 00745 HandleSelectModifier(*this, (unsigned)Val, Argument, ArgumentLen, 00746 OutStr); 00747 } else if (ModifierIs(Modifier, ModifierLen, "s")) { 00748 HandleIntegerSModifier(Val, OutStr); 00749 } else if (ModifierIs(Modifier, ModifierLen, "plural")) { 00750 HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen, 00751 OutStr); 00752 } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) { 00753 HandleOrdinalModifier((unsigned)Val, OutStr); 00754 } else { 00755 assert(ModifierLen == 0 && "Unknown integer modifier"); 00756 llvm::raw_svector_ostream(OutStr) << Val; 00757 } 00758 break; 00759 } 00760 case DiagnosticsEngine::ak_uint: { 00761 unsigned Val = getArgUInt(ArgNo); 00762 00763 if (ModifierIs(Modifier, ModifierLen, "select")) { 00764 HandleSelectModifier(*this, Val, Argument, ArgumentLen, OutStr); 00765 } else if (ModifierIs(Modifier, ModifierLen, "s")) { 00766 HandleIntegerSModifier(Val, OutStr); 00767 } else if (ModifierIs(Modifier, ModifierLen, "plural")) { 00768 HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen, 00769 OutStr); 00770 } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) { 00771 HandleOrdinalModifier(Val, OutStr); 00772 } else { 00773 assert(ModifierLen == 0 && "Unknown integer modifier"); 00774 llvm::raw_svector_ostream(OutStr) << Val; 00775 } 00776 break; 00777 } 00778 // ---- TOKEN SPELLINGS ---- 00779 case DiagnosticsEngine::ak_tokenkind: { 00780 tok::TokenKind Kind = static_cast<tok::TokenKind>(getRawArg(ArgNo)); 00781 assert(ModifierLen == 0 && "No modifiers for token kinds yet"); 00782 00783 llvm::raw_svector_ostream Out(OutStr); 00784 if (const char *S = tok::getPunctuatorSpelling(Kind)) 00785 // Quoted token spelling for punctuators. 00786 Out << '\'' << S << '\''; 00787 else if (const char *S = tok::getKeywordSpelling(Kind)) 00788 // Unquoted token spelling for keywords. 00789 Out << S; 00790 else if (const char *S = getTokenDescForDiagnostic(Kind)) 00791 // Unquoted translatable token name. 00792 Out << S; 00793 else if (const char *S = tok::getTokenName(Kind)) 00794 // Debug name, shouldn't appear in user-facing diagnostics. 00795 Out << '<' << S << '>'; 00796 else 00797 Out << "(null)"; 00798 break; 00799 } 00800 // ---- NAMES and TYPES ---- 00801 case DiagnosticsEngine::ak_identifierinfo: { 00802 const IdentifierInfo *II = getArgIdentifier(ArgNo); 00803 assert(ModifierLen == 0 && "No modifiers for strings yet"); 00804 00805 // Don't crash if get passed a null pointer by accident. 00806 if (!II) { 00807 const char *S = "(null)"; 00808 OutStr.append(S, S + strlen(S)); 00809 continue; 00810 } 00811 00812 llvm::raw_svector_ostream(OutStr) << '\'' << II->getName() << '\''; 00813 break; 00814 } 00815 case DiagnosticsEngine::ak_qualtype: 00816 case DiagnosticsEngine::ak_declarationname: 00817 case DiagnosticsEngine::ak_nameddecl: 00818 case DiagnosticsEngine::ak_nestednamespec: 00819 case DiagnosticsEngine::ak_declcontext: 00820 case DiagnosticsEngine::ak_attr: 00821 getDiags()->ConvertArgToString(Kind, getRawArg(ArgNo), 00822 StringRef(Modifier, ModifierLen), 00823 StringRef(Argument, ArgumentLen), 00824 FormattedArgs, 00825 OutStr, QualTypeVals); 00826 break; 00827 case DiagnosticsEngine::ak_qualtype_pair: 00828 // Create a struct with all the info needed for printing. 00829 TemplateDiffTypes TDT; 00830 TDT.FromType = getRawArg(ArgNo); 00831 TDT.ToType = getRawArg(ArgNo2); 00832 TDT.ElideType = getDiags()->ElideType; 00833 TDT.ShowColors = getDiags()->ShowColors; 00834 TDT.TemplateDiffUsed = false; 00835 intptr_t val = reinterpret_cast<intptr_t>(&TDT); 00836 00837 const char *ArgumentEnd = Argument + ArgumentLen; 00838 const char *Pipe = ScanFormat(Argument, ArgumentEnd, '|'); 00839 00840 // Print the tree. If this diagnostic already has a tree, skip the 00841 // second tree. 00842 if (getDiags()->PrintTemplateTree && Tree.empty()) { 00843 TDT.PrintFromType = true; 00844 TDT.PrintTree = true; 00845 getDiags()->ConvertArgToString(Kind, val, 00846 StringRef(Modifier, ModifierLen), 00847 StringRef(Argument, ArgumentLen), 00848 FormattedArgs, 00849 Tree, QualTypeVals); 00850 // If there is no tree information, fall back to regular printing. 00851 if (!Tree.empty()) { 00852 FormatDiagnostic(Pipe + 1, ArgumentEnd, OutStr); 00853 break; 00854 } 00855 } 00856 00857 // Non-tree printing, also the fall-back when tree printing fails. 00858 // The fall-back is triggered when the types compared are not templates. 00859 const char *FirstDollar = ScanFormat(Argument, ArgumentEnd, '$'); 00860 const char *SecondDollar = ScanFormat(FirstDollar + 1, ArgumentEnd, '$'); 00861 00862 // Append before text 00863 FormatDiagnostic(Argument, FirstDollar, OutStr); 00864 00865 // Append first type 00866 TDT.PrintTree = false; 00867 TDT.PrintFromType = true; 00868 getDiags()->ConvertArgToString(Kind, val, 00869 StringRef(Modifier, ModifierLen), 00870 StringRef(Argument, ArgumentLen), 00871 FormattedArgs, 00872 OutStr, QualTypeVals); 00873 if (!TDT.TemplateDiffUsed) 00874 FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_qualtype, 00875 TDT.FromType)); 00876 00877 // Append middle text 00878 FormatDiagnostic(FirstDollar + 1, SecondDollar, OutStr); 00879 00880 // Append second type 00881 TDT.PrintFromType = false; 00882 getDiags()->ConvertArgToString(Kind, val, 00883 StringRef(Modifier, ModifierLen), 00884 StringRef(Argument, ArgumentLen), 00885 FormattedArgs, 00886 OutStr, QualTypeVals); 00887 if (!TDT.TemplateDiffUsed) 00888 FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_qualtype, 00889 TDT.ToType)); 00890 00891 // Append end text 00892 FormatDiagnostic(SecondDollar + 1, Pipe, OutStr); 00893 break; 00894 } 00895 00896 // Remember this argument info for subsequent formatting operations. Turn 00897 // std::strings into a null terminated string to make it be the same case as 00898 // all the other ones. 00899 if (Kind == DiagnosticsEngine::ak_qualtype_pair) 00900 continue; 00901 else if (Kind != DiagnosticsEngine::ak_std_string) 00902 FormattedArgs.push_back(std::make_pair(Kind, getRawArg(ArgNo))); 00903 else 00904 FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_c_string, 00905 (intptr_t)getArgStdStr(ArgNo).c_str())); 00906 00907 } 00908 00909 // Append the type tree to the end of the diagnostics. 00910 OutStr.append(Tree.begin(), Tree.end()); 00911 } 00912 00913 StoredDiagnostic::StoredDiagnostic() { } 00914 00915 StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID, 00916 StringRef Message) 00917 : ID(ID), Level(Level), Loc(), Message(Message) { } 00918 00919 StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level, 00920 const Diagnostic &Info) 00921 : ID(Info.getID()), Level(Level) 00922 { 00923 assert((Info.getLocation().isInvalid() || Info.hasSourceManager()) && 00924 "Valid source location without setting a source manager for diagnostic"); 00925 if (Info.getLocation().isValid()) 00926 Loc = FullSourceLoc(Info.getLocation(), Info.getSourceManager()); 00927 SmallString<64> Message; 00928 Info.FormatDiagnostic(Message); 00929 this->Message.assign(Message.begin(), Message.end()); 00930 00931 Ranges.reserve(Info.getNumRanges()); 00932 for (unsigned I = 0, N = Info.getNumRanges(); I != N; ++I) 00933 Ranges.push_back(Info.getRange(I)); 00934 00935 FixIts.reserve(Info.getNumFixItHints()); 00936 for (unsigned I = 0, N = Info.getNumFixItHints(); I != N; ++I) 00937 FixIts.push_back(Info.getFixItHint(I)); 00938 } 00939 00940 StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID, 00941 StringRef Message, FullSourceLoc Loc, 00942 ArrayRef<CharSourceRange> Ranges, 00943 ArrayRef<FixItHint> FixIts) 00944 : ID(ID), Level(Level), Loc(Loc), Message(Message), 00945 Ranges(Ranges.begin(), Ranges.end()), FixIts(FixIts.begin(), FixIts.end()) 00946 { 00947 } 00948 00949 StoredDiagnostic::~StoredDiagnostic() { } 00950 00951 /// IncludeInDiagnosticCounts - This method (whose default implementation 00952 /// returns true) indicates whether the diagnostics handled by this 00953 /// DiagnosticConsumer should be included in the number of diagnostics 00954 /// reported by DiagnosticsEngine. 00955 bool DiagnosticConsumer::IncludeInDiagnosticCounts() const { return true; } 00956 00957 void IgnoringDiagConsumer::anchor() { } 00958 00959 ForwardingDiagnosticConsumer::~ForwardingDiagnosticConsumer() {} 00960 00961 void ForwardingDiagnosticConsumer::HandleDiagnostic( 00962 DiagnosticsEngine::Level DiagLevel, 00963 const Diagnostic &Info) { 00964 Target.HandleDiagnostic(DiagLevel, Info); 00965 } 00966 00967 void ForwardingDiagnosticConsumer::clear() { 00968 DiagnosticConsumer::clear(); 00969 Target.clear(); 00970 } 00971 00972 bool ForwardingDiagnosticConsumer::IncludeInDiagnosticCounts() const { 00973 return Target.IncludeInDiagnosticCounts(); 00974 } 00975 00976 PartialDiagnostic::StorageAllocator::StorageAllocator() { 00977 for (unsigned I = 0; I != NumCached; ++I) 00978 FreeList[I] = Cached + I; 00979 NumFreeListEntries = NumCached; 00980 } 00981 00982 PartialDiagnostic::StorageAllocator::~StorageAllocator() { 00983 // Don't assert if we are in a CrashRecovery context, as this invariant may 00984 // be invalidated during a crash. 00985 assert((NumFreeListEntries == NumCached || 00986 llvm::CrashRecoveryContext::isRecoveringFromCrash()) && 00987 "A partial is on the lamb"); 00988 }