Diagnostic.cpp revision 234353
167754Smsmith//===--- Diagnostic.cpp - C Language Family Diagnostic Handling -----------===// 267754Smsmith// 367754Smsmith// The LLVM Compiler Infrastructure 477424Smsmith// 567754Smsmith// This file is distributed under the University of Illinois Open Source 667754Smsmith// License. See LICENSE.TXT for details. 767754Smsmith// 867754Smsmith//===----------------------------------------------------------------------===// 967754Smsmith// 1067754Smsmith// This file implements the Diagnostic-related interfaces. 1167754Smsmith// 12193267Sjkim//===----------------------------------------------------------------------===// 1370243Smsmith 1467754Smsmith#include "clang/Basic/Diagnostic.h" 1567754Smsmith#include "clang/Basic/IdentifierTable.h" 1667754Smsmith#include "clang/Basic/PartialDiagnostic.h" 1767754Smsmith#include "llvm/ADT/SmallString.h" 1867754Smsmith#include "llvm/Support/raw_ostream.h" 1967754Smsmith#include "llvm/Support/CrashRecoveryContext.h" 2067754Smsmith 2167754Smsmithusing namespace clang; 2267754Smsmith 2367754Smsmithstatic void DummyArgToStringFn(DiagnosticsEngine::ArgumentKind AK, intptr_t QT, 2467754Smsmith const char *Modifier, unsigned ML, 2567754Smsmith const char *Argument, unsigned ArgLen, 2667754Smsmith const DiagnosticsEngine::ArgumentValue *PrevArgs, 2767754Smsmith unsigned NumPrevArgs, 2867754Smsmith SmallVectorImpl<char> &Output, 2967754Smsmith void *Cookie, 3067754Smsmith ArrayRef<intptr_t> QualTypeVals) { 3167754Smsmith const char *Str = "<can't format argument>"; 3267754Smsmith Output.append(Str, Str+strlen(Str)); 3367754Smsmith} 3467754Smsmith 3567754Smsmith 3667754SmsmithDiagnosticsEngine::DiagnosticsEngine( 3767754Smsmith const IntrusiveRefCntPtr<DiagnosticIDs> &diags, 3867754Smsmith DiagnosticConsumer *client, bool ShouldOwnClient) 3967754Smsmith : Diags(diags), Client(client), OwnsDiagClient(ShouldOwnClient), 4067754Smsmith SourceMgr(0) { 4167754Smsmith ArgToStringFn = DummyArgToStringFn; 4267754Smsmith ArgToStringCookie = 0; 4367754Smsmith 4467754Smsmith AllExtensionsSilenced = 0; 4567754Smsmith IgnoreAllWarnings = false; 4667754Smsmith WarningsAsErrors = false; 4767754Smsmith EnableAllWarnings = false; 4867754Smsmith ErrorsAsFatal = false; 4967754Smsmith SuppressSystemWarnings = false; 5067754Smsmith SuppressAllDiagnostics = false; 5167754Smsmith ShowOverloads = Ovl_All; 5267754Smsmith ExtBehavior = Ext_Ignore; 5367754Smsmith 5467754Smsmith ErrorLimit = 0; 5567754Smsmith TemplateBacktraceLimit = 0; 5667754Smsmith ConstexprBacktraceLimit = 0; 5767754Smsmith 5867754Smsmith Reset(); 5967754Smsmith} 6067754Smsmith 6167754SmsmithDiagnosticsEngine::~DiagnosticsEngine() { 6267754Smsmith if (OwnsDiagClient) 6367754Smsmith delete Client; 6467754Smsmith} 6567754Smsmith 6667754Smsmithvoid DiagnosticsEngine::setClient(DiagnosticConsumer *client, 6767754Smsmith bool ShouldOwnClient) { 6867754Smsmith if (OwnsDiagClient && Client) 6967754Smsmith delete Client; 7067754Smsmith 7167754Smsmith Client = client; 7267754Smsmith OwnsDiagClient = ShouldOwnClient; 7367754Smsmith} 7467754Smsmith 7567754Smsmithvoid DiagnosticsEngine::pushMappings(SourceLocation Loc) { 7667754Smsmith DiagStateOnPushStack.push_back(GetCurDiagState()); 7767754Smsmith} 7867754Smsmith 7967754Smsmithbool DiagnosticsEngine::popMappings(SourceLocation Loc) { 8067754Smsmith if (DiagStateOnPushStack.empty()) 8167754Smsmith return false; 8267754Smsmith 8367754Smsmith if (DiagStateOnPushStack.back() != GetCurDiagState()) { 8467754Smsmith // State changed at some point between push/pop. 8567754Smsmith PushDiagStatePoint(DiagStateOnPushStack.back(), Loc); 8667754Smsmith } 8767754Smsmith DiagStateOnPushStack.pop_back(); 8867754Smsmith return true; 8967754Smsmith} 9067754Smsmith 9167754Smsmithvoid DiagnosticsEngine::Reset() { 9267754Smsmith ErrorOccurred = false; 9367754Smsmith FatalErrorOccurred = false; 9467754Smsmith UnrecoverableErrorOccurred = false; 9567754Smsmith 9667754Smsmith NumWarnings = 0; 9767754Smsmith NumErrors = 0; 9867754Smsmith NumErrorsSuppressed = 0; 9967754Smsmith TrapNumErrorsOccurred = 0; 10067754Smsmith TrapNumUnrecoverableErrorsOccurred = 0; 10167754Smsmith 10267754Smsmith CurDiagID = ~0U; 10367754Smsmith // Set LastDiagLevel to an "unset" state. If we set it to 'Ignored', notes 10467754Smsmith // using a DiagnosticsEngine associated to a translation unit that follow 10567754Smsmith // diagnostics from a DiagnosticsEngine associated to anoter t.u. will not be 10667754Smsmith // displayed. 10767754Smsmith LastDiagLevel = (DiagnosticIDs::Level)-1; 10867754Smsmith DelayedDiagID = 0; 10967754Smsmith 11067754Smsmith // Clear state related to #pragma diagnostic. 11167754Smsmith DiagStates.clear(); 11267754Smsmith DiagStatePoints.clear(); 11367754Smsmith DiagStateOnPushStack.clear(); 11467754Smsmith 11567754Smsmith // Create a DiagState and DiagStatePoint representing diagnostic changes 11667754Smsmith // through command-line. 11777424Smsmith DiagStates.push_back(DiagState()); 11867754Smsmith PushDiagStatePoint(&DiagStates.back(), SourceLocation()); 119193341Sjkim} 120193341Sjkim 121193341Sjkimvoid DiagnosticsEngine::SetDelayedDiagnostic(unsigned DiagID, StringRef Arg1, 122193341Sjkim StringRef Arg2) { 123193341Sjkim if (DelayedDiagID) 124193341Sjkim return; 12567754Smsmith 12667754Smsmith DelayedDiagID = DiagID; 12777424Smsmith DelayedDiagArg1 = Arg1.str(); 12891116Smsmith DelayedDiagArg2 = Arg2.str(); 12967754Smsmith} 130151937Sjkim 13167754Smsmithvoid DiagnosticsEngine::ReportDelayed() { 132151937Sjkim Report(DelayedDiagID) << DelayedDiagArg1 << DelayedDiagArg2; 133151937Sjkim DelayedDiagID = 0; 134151937Sjkim DelayedDiagArg1.clear(); 135151937Sjkim DelayedDiagArg2.clear(); 136151937Sjkim} 137151937Sjkim 13867754SmsmithDiagnosticsEngine::DiagStatePointsTy::iterator 13967754SmsmithDiagnosticsEngine::GetDiagStatePointForLoc(SourceLocation L) const { 14077424Smsmith assert(!DiagStatePoints.empty()); 14167754Smsmith assert(DiagStatePoints.front().Loc.isInvalid() && 14267754Smsmith "Should have created a DiagStatePoint for command-line"); 14377424Smsmith 14467754Smsmith FullSourceLoc Loc(L, *SourceMgr); 14577424Smsmith if (Loc.isInvalid()) 14667754Smsmith return DiagStatePoints.end() - 1; 14767754Smsmith 14867754Smsmith DiagStatePointsTy::iterator Pos = DiagStatePoints.end(); 14971867Smsmith FullSourceLoc LastStateChangePos = DiagStatePoints.back().Loc; 15067754Smsmith if (LastStateChangePos.isValid() && 15167754Smsmith Loc.isBeforeInTranslationUnitThan(LastStateChangePos)) 15267754Smsmith Pos = std::upper_bound(DiagStatePoints.begin(), DiagStatePoints.end(), 15367754Smsmith DiagStatePoint(0, Loc)); 15477424Smsmith --Pos; 15567754Smsmith return Pos; 15667754Smsmith} 15767754Smsmith 15877424Smsmith/// \brief This allows the client to specify that certain 15967754Smsmith/// warnings are ignored. Notes can never be mapped, errors can only be 16067754Smsmith/// mapped to fatal, and WARNINGs and EXTENSIONs can be mapped arbitrarily. 161167802Sjkim/// 16267754Smsmith/// \param The source location that this change of diagnostic state should 16367754Smsmith/// take affect. It can be null if we are setting the latest state. 16467754Smsmithvoid DiagnosticsEngine::setDiagnosticMapping(diag::kind Diag, diag::Mapping Map, 16567754Smsmith SourceLocation L) { 166167802Sjkim assert(Diag < diag::DIAG_UPPER_LIMIT && 16767754Smsmith "Can only map builtin diagnostics"); 16867754Smsmith assert((Diags->isBuiltinWarningOrExtension(Diag) || 16967754Smsmith (Map == diag::MAP_FATAL || Map == diag::MAP_ERROR)) && 17067754Smsmith "Cannot map errors into warnings!"); 17167754Smsmith assert(!DiagStatePoints.empty()); 17267754Smsmith 17367754Smsmith FullSourceLoc Loc(L, *SourceMgr); 17467754Smsmith FullSourceLoc LastStateChangePos = DiagStatePoints.back().Loc; 17599679Siwasaki // Don't allow a mapping to a warning override an error/fatal mapping. 17667754Smsmith if (Map == diag::MAP_WARNING) { 17777424Smsmith DiagnosticMappingInfo &Info = GetCurDiagState()->getOrAddMappingInfo(Diag); 17867754Smsmith if (Info.getMapping() == diag::MAP_ERROR || 17967754Smsmith Info.getMapping() == diag::MAP_FATAL) 18067754Smsmith Map = Info.getMapping(); 18167754Smsmith } 182151937Sjkim DiagnosticMappingInfo MappingInfo = makeMappingInfo(Map, L); 183151937Sjkim 184151937Sjkim // Common case; setting all the diagnostics of a group in one place. 185167802Sjkim if (Loc.isInvalid() || Loc == LastStateChangePos) { 186151937Sjkim GetCurDiagState()->setMappingInfo(Diag, MappingInfo); 187151937Sjkim return; 18867754Smsmith } 18967754Smsmith 19067754Smsmith // Another common case; modifying diagnostic state in a source location 19177424Smsmith // after the previous one. 19267754Smsmith if ((Loc.isValid() && LastStateChangePos.isInvalid()) || 19367754Smsmith LastStateChangePos.isBeforeInTranslationUnitThan(Loc)) { 19491116Smsmith // A diagnostic pragma occurred, create a new DiagState initialized with 19567754Smsmith // the current one and a new DiagStatePoint to record at which location 19699679Siwasaki // the new state became active. 19799679Siwasaki DiagStates.push_back(*GetCurDiagState()); 19877424Smsmith PushDiagStatePoint(&DiagStates.back(), Loc); 19977424Smsmith GetCurDiagState()->setMappingInfo(Diag, MappingInfo); 20077424Smsmith return; 20177424Smsmith } 20277424Smsmith 20367754Smsmith // We allow setting the diagnostic state in random source order for 20467754Smsmith // completeness but it should not be actually happening in normal practice. 20599146Siwasaki 20677424Smsmith DiagStatePointsTy::iterator Pos = GetDiagStatePointForLoc(Loc); 20767754Smsmith assert(Pos != DiagStatePoints.end()); 20867754Smsmith 20967754Smsmith // Update all diagnostic states that are active after the given location. 21067754Smsmith for (DiagStatePointsTy::iterator 21167754Smsmith I = Pos+1, E = DiagStatePoints.end(); I != E; ++I) { 21277424Smsmith GetCurDiagState()->setMappingInfo(Diag, MappingInfo); 21367754Smsmith } 214151937Sjkim 21577424Smsmith // If the location corresponds to an existing point, just update its state. 21667754Smsmith if (Pos->Loc == Loc) { 21767754Smsmith GetCurDiagState()->setMappingInfo(Diag, MappingInfo); 21867754Smsmith return; 219151937Sjkim } 22067754Smsmith 22167754Smsmith // Create a new state/point and fit it into the vector of DiagStatePoints 22267754Smsmith // so that the vector is always ordered according to location. 22367754Smsmith Pos->Loc.isBeforeInTranslationUnitThan(Loc); 224151937Sjkim DiagStates.push_back(*Pos->State); 22577424Smsmith DiagState *NewState = &DiagStates.back(); 22667754Smsmith GetCurDiagState()->setMappingInfo(Diag, MappingInfo); 22767754Smsmith DiagStatePoints.insert(Pos+1, DiagStatePoint(NewState, 22867754Smsmith FullSourceLoc(Loc, *SourceMgr))); 22977424Smsmith} 23067754Smsmith 231167802Sjkimbool DiagnosticsEngine::setDiagnosticGroupMapping( 232193267Sjkim StringRef Group, diag::Mapping Map, SourceLocation Loc) 23367754Smsmith{ 23467754Smsmith // Get the diagnostics in this group. 235167802Sjkim llvm::SmallVector<diag::kind, 8> GroupDiags; 23667754Smsmith if (Diags->getDiagnosticsInGroup(Group, GroupDiags)) 23767754Smsmith return true; 23867754Smsmith 23967754Smsmith // Set the mapping. 24067754Smsmith for (unsigned i = 0, e = GroupDiags.size(); i != e; ++i) 24167754Smsmith setDiagnosticMapping(GroupDiags[i], Map, Loc); 242193267Sjkim 24367754Smsmith return false; 244107325Siwasaki} 24567754Smsmith 246193267Sjkimvoid DiagnosticsEngine::setDiagnosticWarningAsError(diag::kind Diag, 24767754Smsmith bool Enabled) { 248193267Sjkim // If we are enabling this feature, just set the diagnostic mappings to map to 24967754Smsmith // errors. 250193267Sjkim if (Enabled) 251193267Sjkim setDiagnosticMapping(Diag, diag::MAP_ERROR, SourceLocation()); 25267754Smsmith 25367754Smsmith // Otherwise, we want to set the diagnostic mapping's "no Werror" bit, and 25467754Smsmith // potentially downgrade anything already mapped to be a warning. 25567754Smsmith DiagnosticMappingInfo &Info = GetCurDiagState()->getOrAddMappingInfo(Diag); 25667754Smsmith 257193267Sjkim if (Info.getMapping() == diag::MAP_ERROR || 258193267Sjkim Info.getMapping() == diag::MAP_FATAL) 25967754Smsmith Info.setMapping(diag::MAP_WARNING); 26067754Smsmith 26167754Smsmith Info.setNoWarningAsError(true); 26267754Smsmith} 26367754Smsmith 264129684Snjlbool DiagnosticsEngine::setDiagnosticGroupWarningAsError(StringRef Group, 265193267Sjkim bool Enabled) { 266129684Snjl // If we are enabling this feature, just set the diagnostic mappings to map to 26767754Smsmith // errors. 26867754Smsmith if (Enabled) 269129684Snjl return setDiagnosticGroupMapping(Group, diag::MAP_ERROR); 27067754Smsmith 27177424Smsmith // Otherwise, we want to set the diagnostic mapping's "no Werror" bit, and 27267754Smsmith // potentially downgrade anything already mapped to be a warning. 27367754Smsmith 27467754Smsmith // Get the diagnostics in this group. 27567754Smsmith llvm::SmallVector<diag::kind, 8> GroupDiags; 276193267Sjkim if (Diags->getDiagnosticsInGroup(Group, GroupDiags)) 27767754Smsmith return true; 27867754Smsmith 27967754Smsmith // Perform the mapping change. 28067754Smsmith for (unsigned i = 0, e = GroupDiags.size(); i != e; ++i) { 28167754Smsmith DiagnosticMappingInfo &Info = GetCurDiagState()->getOrAddMappingInfo( 282193267Sjkim GroupDiags[i]); 28367754Smsmith 28467754Smsmith if (Info.getMapping() == diag::MAP_ERROR || 28567754Smsmith Info.getMapping() == diag::MAP_FATAL) 28667754Smsmith Info.setMapping(diag::MAP_WARNING); 28799679Siwasaki 288193267Sjkim Info.setNoWarningAsError(true); 289193267Sjkim } 290193267Sjkim 291193267Sjkim return false; 292193267Sjkim} 293193267Sjkim 294193267Sjkimvoid DiagnosticsEngine::setDiagnosticErrorAsFatal(diag::kind Diag, 295193267Sjkim bool Enabled) { 296193267Sjkim // If we are enabling this feature, just set the diagnostic mappings to map to 297193267Sjkim // errors. 29867754Smsmith if (Enabled) 29967754Smsmith setDiagnosticMapping(Diag, diag::MAP_FATAL, SourceLocation()); 30067754Smsmith 30167754Smsmith // Otherwise, we want to set the diagnostic mapping's "no Werror" bit, and 302193267Sjkim // potentially downgrade anything already mapped to be a warning. 30367754Smsmith DiagnosticMappingInfo &Info = GetCurDiagState()->getOrAddMappingInfo(Diag); 30467754Smsmith 30567754Smsmith if (Info.getMapping() == diag::MAP_FATAL) 30677424Smsmith Info.setMapping(diag::MAP_ERROR); 30777424Smsmith 30867754Smsmith Info.setNoErrorAsFatal(true); 30967754Smsmith} 31067754Smsmith 31167754Smsmithbool DiagnosticsEngine::setDiagnosticGroupErrorAsFatal(StringRef Group, 31267754Smsmith bool Enabled) { 313193267Sjkim // If we are enabling this feature, just set the diagnostic mappings to map to 31477424Smsmith // fatal errors. 31567754Smsmith if (Enabled) 316167802Sjkim return setDiagnosticGroupMapping(Group, diag::MAP_FATAL); 317193267Sjkim 31877424Smsmith // Otherwise, we want to set the diagnostic mapping's "no Werror" bit, and 31967754Smsmith // potentially downgrade anything already mapped to be an error. 32067754Smsmith 32167754Smsmith // Get the diagnostics in this group. 32267754Smsmith llvm::SmallVector<diag::kind, 8> GroupDiags; 32399679Siwasaki if (Diags->getDiagnosticsInGroup(Group, GroupDiags)) 32467754Smsmith return true; 32599679Siwasaki 32677424Smsmith // Perform the mapping change. 32767754Smsmith for (unsigned i = 0, e = GroupDiags.size(); i != e; ++i) { 328167802Sjkim DiagnosticMappingInfo &Info = GetCurDiagState()->getOrAddMappingInfo( 329193267Sjkim GroupDiags[i]); 33067754Smsmith 33167754Smsmith if (Info.getMapping() == diag::MAP_FATAL) 33267754Smsmith Info.setMapping(diag::MAP_ERROR); 33367754Smsmith 33467754Smsmith Info.setNoErrorAsFatal(true); 33567754Smsmith } 33667754Smsmith 337193267Sjkim return false; 338193267Sjkim} 339193267Sjkim 34067754Smsmithvoid DiagnosticsEngine::setMappingToAllDiagnostics(diag::Mapping Map, 341193267Sjkim SourceLocation Loc) { 342100966Siwasaki // Get all the diagnostics. 34367754Smsmith llvm::SmallVector<diag::kind, 64> AllDiags; 34467754Smsmith Diags->getAllDiagnostics(AllDiags); 345193267Sjkim 34667754Smsmith // Set the mapping. 347167802Sjkim for (unsigned i = 0, e = AllDiags.size(); i != e; ++i) 348151937Sjkim if (Diags->isBuiltinWarningOrExtension(AllDiags[i])) 349167802Sjkim setDiagnosticMapping(AllDiags[i], Map, Loc); 350167802Sjkim} 351167802Sjkim 352167802Sjkimvoid DiagnosticsEngine::Report(const StoredDiagnostic &storedDiag) { 353167802Sjkim assert(CurDiagID == ~0U && "Multiple diagnostics in flight at once!"); 354167802Sjkim 355167802Sjkim CurDiagLoc = storedDiag.getLocation(); 356167802Sjkim CurDiagID = storedDiag.getID(); 357167802Sjkim NumDiagArgs = 0; 358167802Sjkim 359167802Sjkim NumDiagRanges = storedDiag.range_size(); 360167802Sjkim assert(NumDiagRanges < DiagnosticsEngine::MaxRanges && 361167802Sjkim "Too many arguments to diagnostic!"); 362167802Sjkim unsigned i = 0; 363167802Sjkim for (StoredDiagnostic::range_iterator 364151937Sjkim RI = storedDiag.range_begin(), 365151937Sjkim RE = storedDiag.range_end(); RI != RE; ++RI) 366151937Sjkim DiagRanges[i++] = *RI; 36767754Smsmith 36867754Smsmith assert(NumDiagRanges < DiagnosticsEngine::MaxFixItHints && 369167802Sjkim "Too many arguments to diagnostic!"); 370193267Sjkim NumDiagFixItHints = 0; 37167754Smsmith for (StoredDiagnostic::fixit_iterator 37277424Smsmith FI = storedDiag.fixit_begin(), 37399679Siwasaki FE = storedDiag.fixit_end(); FI != FE; ++FI) 37499679Siwasaki DiagFixItHints[NumDiagFixItHints++] = *FI; 37567754Smsmith 37667754Smsmith assert(Client && "DiagnosticConsumer not set!"); 37799146Siwasaki Level DiagLevel = storedDiag.getLevel(); 37899146Siwasaki Diagnostic Info(this, storedDiag.getMessage()); 37999146Siwasaki Client->HandleDiagnostic(DiagLevel, Info); 38099146Siwasaki if (Client->IncludeInDiagnosticCounts()) { 38199146Siwasaki if (DiagLevel == DiagnosticsEngine::Warning) 38299146Siwasaki ++NumWarnings; 38399146Siwasaki } 38499146Siwasaki 38599146Siwasaki CurDiagID = ~0U; 38699146Siwasaki} 38799146Siwasaki 38899146Siwasakibool DiagnosticsEngine::EmitCurrentDiagnostic() { 38977424Smsmith // Process the diagnostic, sending the accumulated information to the 390107325Siwasaki // DiagnosticConsumer. 391107325Siwasaki bool Emitted = ProcessDiag(); 392107325Siwasaki 39367754Smsmith // Clear out the current diagnostic object. 39487031Smsmith unsigned DiagID = CurDiagID; 395193267Sjkim Clear(); 39667754Smsmith 39799146Siwasaki // If there was a delayed diagnostic, emit it now. 398167802Sjkim if (DelayedDiagID && DelayedDiagID != DiagID) 399167802Sjkim ReportDelayed(); 400167802Sjkim 401167802Sjkim return Emitted; 40267754Smsmith} 40367754Smsmith 40467754Smsmith 40567754SmsmithDiagnosticConsumer::~DiagnosticConsumer() {} 40667754Smsmith 40787031Smsmithvoid DiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, 40867754Smsmith const Diagnostic &Info) { 40967754Smsmith if (!IncludeInDiagnosticCounts()) 41067754Smsmith return; 41167754Smsmith 41267754Smsmith if (DiagLevel == DiagnosticsEngine::Warning) 413104470Siwasaki ++NumWarnings; 414104470Siwasaki else if (DiagLevel >= DiagnosticsEngine::Error) 415104470Siwasaki ++NumErrors; 416104470Siwasaki} 417104470Siwasaki 418104470Siwasaki/// ModifierIs - Return true if the specified modifier matches specified string. 419104470Siwasakitemplate <std::size_t StrLen> 420104470Siwasakistatic bool ModifierIs(const char *Modifier, unsigned ModifierLen, 421104470Siwasaki const char (&Str)[StrLen]) { 422104470Siwasaki return StrLen-1 == ModifierLen && !memcmp(Modifier, Str, StrLen-1); 423104470Siwasaki} 424104470Siwasaki 425104470Siwasaki/// ScanForward - Scans forward, looking for the given character, skipping 426104470Siwasaki/// nested clauses and escaped characters. 427104470Siwasakistatic const char *ScanFormat(const char *I, const char *E, char Target) { 428104470Siwasaki unsigned Depth = 0; 429104470Siwasaki 430104470Siwasaki for ( ; I != E; ++I) { 431104470Siwasaki if (Depth == 0 && *I == Target) return I; 432104470Siwasaki if (Depth != 0 && *I == '}') Depth--; 433104470Siwasaki 434104470Siwasaki if (*I == '%') { 435104470Siwasaki I++; 436104470Siwasaki if (I == E) break; 437104470Siwasaki 438104470Siwasaki // Escaped characters get implicitly skipped here. 439138287Smarks 440104470Siwasaki // Format specifier. 441104470Siwasaki if (!isdigit(*I) && !ispunct(*I)) { 442167802Sjkim for (I++; I != E && !isdigit(*I) && *I != '{'; I++) ; 443104470Siwasaki if (I == E) break; 444104470Siwasaki if (*I == '{') 445151937Sjkim Depth++; 446138287Smarks } 447138287Smarks } 448138287Smarks } 449138287Smarks return E; 450138287Smarks} 451138287Smarks 452138287Smarks/// HandleSelectModifier - Handle the integer 'select' modifier. This is used 453138287Smarks/// like this: %select{foo|bar|baz}2. This means that the integer argument 454138287Smarks/// "%2" has a value from 0-2. If the value is 0, the diagnostic prints 'foo'. 455138287Smarks/// If the value is 1, it prints 'bar'. If it has the value 2, it prints 'baz'. 456138287Smarks/// This is very useful for certain classes of variant diagnostics. 457138287Smarksstatic void HandleSelectModifier(const Diagnostic &DInfo, unsigned ValNo, 458138287Smarks const char *Argument, unsigned ArgumentLen, 459138287Smarks SmallVectorImpl<char> &OutStr) { 460138287Smarks const char *ArgumentEnd = Argument+ArgumentLen; 461138287Smarks 462138287Smarks // Skip over 'ValNo' |'s. 463138287Smarks while (ValNo) { 464138287Smarks const char *NextVal = ScanFormat(Argument, ArgumentEnd, '|'); 465138287Smarks assert(NextVal != ArgumentEnd && "Value for integer select modifier was" 466138287Smarks " larger than the number of options in the diagnostic string!"); 467138287Smarks Argument = NextVal+1; // Skip this string. 468138287Smarks --ValNo; 469138287Smarks } 470151937Sjkim 471138287Smarks // Get the end of the value. This is either the } or the |. 472138287Smarks const char *EndPtr = ScanFormat(Argument, ArgumentEnd, '|'); 473138287Smarks 474138287Smarks // Recursively format the result of the select clause into the output string. 475138287Smarks DInfo.FormatDiagnostic(Argument, EndPtr, OutStr); 476138287Smarks} 477138287Smarks 478193267Sjkim/// HandleIntegerSModifier - Handle the integer 's' modifier. This adds the 479193267Sjkim/// letter 's' to the string if the value is not 1. This is used in cases like 480193267Sjkim/// this: "you idiot, you have %4 parameter%s4!". 481193267Sjkimstatic void HandleIntegerSModifier(unsigned ValNo, 482104470Siwasaki SmallVectorImpl<char> &OutStr) { 483193267Sjkim if (ValNo != 1) 484104470Siwasaki OutStr.push_back('s'); 485193267Sjkim} 486104470Siwasaki 487193267Sjkim/// HandleOrdinalModifier - Handle the integer 'ord' modifier. This 488193267Sjkim/// prints the ordinal form of the given integer, with 1 corresponding 489104470Siwasaki/// to the first ordinal. Currently this is hard-coded to use the 490104470Siwasaki/// English form. 491104470Siwasakistatic void HandleOrdinalModifier(unsigned ValNo, 492193267Sjkim SmallVectorImpl<char> &OutStr) { 493167802Sjkim assert(ValNo != 0 && "ValNo must be strictly positive!"); 494167802Sjkim 495167802Sjkim llvm::raw_svector_ostream Out(OutStr); 496167802Sjkim 497167802Sjkim // We could use text forms for the first N ordinals, but the numeric 498167802Sjkim // forms are actually nicer in diagnostics because they stand out. 499167802Sjkim Out << ValNo; 500104470Siwasaki 501104470Siwasaki // It is critically important that we do this perfectly for 502104470Siwasaki // user-written sequences with over 100 elements. 503104470Siwasaki switch (ValNo % 100) { 504104470Siwasaki case 11: 505167802Sjkim case 12: 506167802Sjkim case 13: 507151937Sjkim Out << "th"; return; 508104470Siwasaki default: 509104470Siwasaki switch (ValNo % 10) { 510104470Siwasaki case 1: Out << "st"; return; 511104470Siwasaki case 2: Out << "nd"; return; 512104470Siwasaki case 3: Out << "rd"; return; 513104470Siwasaki default: Out << "th"; return; 514104470Siwasaki } 515104470Siwasaki } 516104470Siwasaki} 517104470Siwasaki 518104470Siwasaki 519104470Siwasaki/// PluralNumber - Parse an unsigned integer and advance Start. 520104470Siwasakistatic unsigned PluralNumber(const char *&Start, const char *End) { 521104470Siwasaki // Programming 101: Parse a decimal number :-) 522104470Siwasaki unsigned Val = 0; 523104470Siwasaki while (Start != End && *Start >= '0' && *Start <= '9') { 524104470Siwasaki Val *= 10; 525104470Siwasaki Val += *Start - '0'; 526104470Siwasaki ++Start; 527104470Siwasaki } 528104470Siwasaki return Val; 529104470Siwasaki} 530104470Siwasaki 531193267Sjkim/// TestPluralRange - Test if Val is in the parsed range. Modifies Start. 532104470Siwasakistatic bool TestPluralRange(unsigned Val, const char *&Start, const char *End) { 533104470Siwasaki if (*Start != '[') { 534104470Siwasaki unsigned Ref = PluralNumber(Start, End); 535104470Siwasaki return Ref == Val; 536104470Siwasaki } 537104470Siwasaki 538104470Siwasaki ++Start; 539104470Siwasaki unsigned Low = PluralNumber(Start, End); 540104470Siwasaki assert(*Start == ',' && "Bad plural expression syntax: expected ,"); 541104470Siwasaki ++Start; 542104470Siwasaki unsigned High = PluralNumber(Start, End); 543104470Siwasaki assert(*Start == ']' && "Bad plural expression syntax: expected )"); 544104470Siwasaki ++Start; 545104470Siwasaki return Low <= Val && Val <= High; 546104470Siwasaki} 547104470Siwasaki 548104470Siwasaki/// EvalPluralExpr - Actual expression evaluator for HandlePluralModifier. 549151937Sjkimstatic bool EvalPluralExpr(unsigned ValNo, const char *Start, const char *End) { 550151937Sjkim // Empty condition? 551151937Sjkim if (*Start == ':') 552151937Sjkim return true; 553151937Sjkim 554151937Sjkim while (1) { 555151937Sjkim char C = *Start; 556104470Siwasaki if (C == '%') { 557104470Siwasaki // Modulo expression 558104470Siwasaki ++Start; 559193267Sjkim unsigned Arg = PluralNumber(Start, End); 560138287Smarks assert(*Start == '=' && "Bad plural expression syntax: expected ="); 561193267Sjkim ++Start; 562193267Sjkim unsigned ValMod = ValNo % Arg; 563193267Sjkim if (TestPluralRange(ValMod, Start, End)) 564193267Sjkim return true; 565193267Sjkim } else { 566193267Sjkim assert((C == '[' || (C >= '0' && C <= '9')) && 567193267Sjkim "Bad plural expression syntax: unexpected character"); 568138287Smarks // Range expression 569138287Smarks if (TestPluralRange(ValNo, Start, End)) 570193267Sjkim return true; 571193267Sjkim } 572138287Smarks 573138287Smarks // Scan for next or-expr part. 574138287Smarks Start = std::find(Start, End, ','); 575138287Smarks if (Start == End) 576138287Smarks break; 577138287Smarks ++Start; 578138287Smarks } 579138287Smarks return false; 580193267Sjkim} 581193267Sjkim 582138287Smarks/// HandlePluralModifier - Handle the integer 'plural' modifier. This is used 583138287Smarks/// for complex plural forms, or in languages where all plurals are complex. 584138287Smarks/// The syntax is: %plural{cond1:form1|cond2:form2|:form3}, where condn are 585138287Smarks/// conditions that are tested in order, the form corresponding to the first 586138287Smarks/// that applies being emitted. The empty condition is always true, making the 587138287Smarks/// last form a default case. 588138287Smarks/// Conditions are simple boolean expressions, where n is the number argument. 589138287Smarks/// Here are the rules. 590138287Smarks/// condition := expression | empty 591138287Smarks/// empty := -> always true 592138287Smarks/// expression := numeric [',' expression] -> logical or 593138287Smarks/// numeric := range -> true if n in range 594138287Smarks/// | '%' number '=' range -> true if n % number in range 595138287Smarks/// range := number 596138287Smarks/// | '[' number ',' number ']' -> ranges are inclusive both ends 597193267Sjkim/// 598104470Siwasaki/// Here are some examples from the GNU gettext manual written in this form: 599104470Siwasaki/// English: 600104470Siwasaki/// {1:form0|:form1} 601104470Siwasaki/// Latvian: 602104470Siwasaki/// {0:form2|%100=11,%10=0,%10=[2,9]:form1|:form0} 603104470Siwasaki/// Gaeilge: 604104470Siwasaki/// {1:form0|2:form1|:form2} 605104470Siwasaki/// Romanian: 606104470Siwasaki/// {1:form0|0,%100=[1,19]:form1|:form2} 607167802Sjkim/// Lithuanian: 608193267Sjkim/// {%10=0,%100=[10,19]:form2|%10=1:form0|:form1} 609104470Siwasaki/// Russian (requires repeated form): 610104470Siwasaki/// {%100=[11,14]:form2|%10=1:form0|%10=[2,4]:form1|:form2} 611104470Siwasaki/// Slovak 612104470Siwasaki/// {1:form0|[2,4]:form1|:form2} 613104470Siwasaki/// Polish (requires repeated form): 614104470Siwasaki/// {1:form0|%100=[10,20]:form2|%10=[2,4]:form1|:form2} 615104470Siwasakistatic void HandlePluralModifier(const Diagnostic &DInfo, unsigned ValNo, 616104470Siwasaki const char *Argument, unsigned ArgumentLen, 617193267Sjkim SmallVectorImpl<char> &OutStr) { 618104470Siwasaki const char *ArgumentEnd = Argument + ArgumentLen; 619104470Siwasaki while (1) { 620104470Siwasaki assert(Argument < ArgumentEnd && "Plural expression didn't match."); 621104470Siwasaki const char *ExprEnd = Argument; 622104470Siwasaki while (*ExprEnd != ':') { 623104470Siwasaki assert(ExprEnd != ArgumentEnd && "Plural missing expression end"); 624104470Siwasaki ++ExprEnd; 625107325Siwasaki } 626107325Siwasaki if (EvalPluralExpr(ValNo, Argument, ExprEnd)) { 627107325Siwasaki Argument = ExprEnd + 1; 628104470Siwasaki ExprEnd = ScanFormat(Argument, ArgumentEnd, '|'); 629104470Siwasaki 630104470Siwasaki // Recursively format the result of the plural clause into the 631104470Siwasaki // output string. 632107325Siwasaki DInfo.FormatDiagnostic(Argument, ExprEnd, OutStr); 633107325Siwasaki return; 634107325Siwasaki } 635107325Siwasaki Argument = ScanFormat(Argument, ArgumentEnd - 1, '|') + 1; 636107325Siwasaki } 637107325Siwasaki} 638107325Siwasaki 639104470Siwasaki 640104470Siwasaki/// FormatDiagnostic - Format this diagnostic into a string, substituting the 641104470Siwasaki/// formal arguments into the %0 slots. The result is appended onto the Str 642104470Siwasaki/// array. 643104470Siwasakivoid Diagnostic:: 644104470SiwasakiFormatDiagnostic(SmallVectorImpl<char> &OutStr) const { 645104470Siwasaki if (!StoredDiagMessage.empty()) { 646104470Siwasaki OutStr.append(StoredDiagMessage.begin(), StoredDiagMessage.end()); 647104470Siwasaki return; 648104470Siwasaki } 649104470Siwasaki 650104470Siwasaki StringRef Diag = 651104470Siwasaki getDiags()->getDiagnosticIDs()->getDescription(getID()); 652104470Siwasaki 653 FormatDiagnostic(Diag.begin(), Diag.end(), OutStr); 654} 655 656void Diagnostic:: 657FormatDiagnostic(const char *DiagStr, const char *DiagEnd, 658 SmallVectorImpl<char> &OutStr) const { 659 660 /// FormattedArgs - Keep track of all of the arguments formatted by 661 /// ConvertArgToString and pass them into subsequent calls to 662 /// ConvertArgToString, allowing the implementation to avoid redundancies in 663 /// obvious cases. 664 SmallVector<DiagnosticsEngine::ArgumentValue, 8> FormattedArgs; 665 666 /// QualTypeVals - Pass a vector of arrays so that QualType names can be 667 /// compared to see if more information is needed to be printed. 668 SmallVector<intptr_t, 2> QualTypeVals; 669 for (unsigned i = 0, e = getNumArgs(); i < e; ++i) 670 if (getArgKind(i) == DiagnosticsEngine::ak_qualtype) 671 QualTypeVals.push_back(getRawArg(i)); 672 673 while (DiagStr != DiagEnd) { 674 if (DiagStr[0] != '%') { 675 // Append non-%0 substrings to Str if we have one. 676 const char *StrEnd = std::find(DiagStr, DiagEnd, '%'); 677 OutStr.append(DiagStr, StrEnd); 678 DiagStr = StrEnd; 679 continue; 680 } else if (ispunct(DiagStr[1])) { 681 OutStr.push_back(DiagStr[1]); // %% -> %. 682 DiagStr += 2; 683 continue; 684 } 685 686 // Skip the %. 687 ++DiagStr; 688 689 // This must be a placeholder for a diagnostic argument. The format for a 690 // placeholder is one of "%0", "%modifier0", or "%modifier{arguments}0". 691 // The digit is a number from 0-9 indicating which argument this comes from. 692 // The modifier is a string of digits from the set [-a-z]+, arguments is a 693 // brace enclosed string. 694 const char *Modifier = 0, *Argument = 0; 695 unsigned ModifierLen = 0, ArgumentLen = 0; 696 697 // Check to see if we have a modifier. If so eat it. 698 if (!isdigit(DiagStr[0])) { 699 Modifier = DiagStr; 700 while (DiagStr[0] == '-' || 701 (DiagStr[0] >= 'a' && DiagStr[0] <= 'z')) 702 ++DiagStr; 703 ModifierLen = DiagStr-Modifier; 704 705 // If we have an argument, get it next. 706 if (DiagStr[0] == '{') { 707 ++DiagStr; // Skip {. 708 Argument = DiagStr; 709 710 DiagStr = ScanFormat(DiagStr, DiagEnd, '}'); 711 assert(DiagStr != DiagEnd && "Mismatched {}'s in diagnostic string!"); 712 ArgumentLen = DiagStr-Argument; 713 ++DiagStr; // Skip }. 714 } 715 } 716 717 assert(isdigit(*DiagStr) && "Invalid format for argument in diagnostic"); 718 unsigned ArgNo = *DiagStr++ - '0'; 719 720 DiagnosticsEngine::ArgumentKind Kind = getArgKind(ArgNo); 721 722 switch (Kind) { 723 // ---- STRINGS ---- 724 case DiagnosticsEngine::ak_std_string: { 725 const std::string &S = getArgStdStr(ArgNo); 726 assert(ModifierLen == 0 && "No modifiers for strings yet"); 727 OutStr.append(S.begin(), S.end()); 728 break; 729 } 730 case DiagnosticsEngine::ak_c_string: { 731 const char *S = getArgCStr(ArgNo); 732 assert(ModifierLen == 0 && "No modifiers for strings yet"); 733 734 // Don't crash if get passed a null pointer by accident. 735 if (!S) 736 S = "(null)"; 737 738 OutStr.append(S, S + strlen(S)); 739 break; 740 } 741 // ---- INTEGERS ---- 742 case DiagnosticsEngine::ak_sint: { 743 int Val = getArgSInt(ArgNo); 744 745 if (ModifierIs(Modifier, ModifierLen, "select")) { 746 HandleSelectModifier(*this, (unsigned)Val, Argument, ArgumentLen, 747 OutStr); 748 } else if (ModifierIs(Modifier, ModifierLen, "s")) { 749 HandleIntegerSModifier(Val, OutStr); 750 } else if (ModifierIs(Modifier, ModifierLen, "plural")) { 751 HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen, 752 OutStr); 753 } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) { 754 HandleOrdinalModifier((unsigned)Val, OutStr); 755 } else { 756 assert(ModifierLen == 0 && "Unknown integer modifier"); 757 llvm::raw_svector_ostream(OutStr) << Val; 758 } 759 break; 760 } 761 case DiagnosticsEngine::ak_uint: { 762 unsigned Val = getArgUInt(ArgNo); 763 764 if (ModifierIs(Modifier, ModifierLen, "select")) { 765 HandleSelectModifier(*this, Val, Argument, ArgumentLen, OutStr); 766 } else if (ModifierIs(Modifier, ModifierLen, "s")) { 767 HandleIntegerSModifier(Val, OutStr); 768 } else if (ModifierIs(Modifier, ModifierLen, "plural")) { 769 HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen, 770 OutStr); 771 } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) { 772 HandleOrdinalModifier(Val, OutStr); 773 } else { 774 assert(ModifierLen == 0 && "Unknown integer modifier"); 775 llvm::raw_svector_ostream(OutStr) << Val; 776 } 777 break; 778 } 779 // ---- NAMES and TYPES ---- 780 case DiagnosticsEngine::ak_identifierinfo: { 781 const IdentifierInfo *II = getArgIdentifier(ArgNo); 782 assert(ModifierLen == 0 && "No modifiers for strings yet"); 783 784 // Don't crash if get passed a null pointer by accident. 785 if (!II) { 786 const char *S = "(null)"; 787 OutStr.append(S, S + strlen(S)); 788 continue; 789 } 790 791 llvm::raw_svector_ostream(OutStr) << '\'' << II->getName() << '\''; 792 break; 793 } 794 case DiagnosticsEngine::ak_qualtype: 795 case DiagnosticsEngine::ak_declarationname: 796 case DiagnosticsEngine::ak_nameddecl: 797 case DiagnosticsEngine::ak_nestednamespec: 798 case DiagnosticsEngine::ak_declcontext: 799 getDiags()->ConvertArgToString(Kind, getRawArg(ArgNo), 800 Modifier, ModifierLen, 801 Argument, ArgumentLen, 802 FormattedArgs.data(), FormattedArgs.size(), 803 OutStr, QualTypeVals); 804 break; 805 } 806 807 // Remember this argument info for subsequent formatting operations. Turn 808 // std::strings into a null terminated string to make it be the same case as 809 // all the other ones. 810 if (Kind != DiagnosticsEngine::ak_std_string) 811 FormattedArgs.push_back(std::make_pair(Kind, getRawArg(ArgNo))); 812 else 813 FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_c_string, 814 (intptr_t)getArgStdStr(ArgNo).c_str())); 815 816 } 817} 818 819StoredDiagnostic::StoredDiagnostic() { } 820 821StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID, 822 StringRef Message) 823 : ID(ID), Level(Level), Loc(), Message(Message) { } 824 825StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level, 826 const Diagnostic &Info) 827 : ID(Info.getID()), Level(Level) 828{ 829 assert((Info.getLocation().isInvalid() || Info.hasSourceManager()) && 830 "Valid source location without setting a source manager for diagnostic"); 831 if (Info.getLocation().isValid()) 832 Loc = FullSourceLoc(Info.getLocation(), Info.getSourceManager()); 833 SmallString<64> Message; 834 Info.FormatDiagnostic(Message); 835 this->Message.assign(Message.begin(), Message.end()); 836 837 Ranges.reserve(Info.getNumRanges()); 838 for (unsigned I = 0, N = Info.getNumRanges(); I != N; ++I) 839 Ranges.push_back(Info.getRange(I)); 840 841 FixIts.reserve(Info.getNumFixItHints()); 842 for (unsigned I = 0, N = Info.getNumFixItHints(); I != N; ++I) 843 FixIts.push_back(Info.getFixItHint(I)); 844} 845 846StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID, 847 StringRef Message, FullSourceLoc Loc, 848 ArrayRef<CharSourceRange> Ranges, 849 ArrayRef<FixItHint> Fixits) 850 : ID(ID), Level(Level), Loc(Loc), Message(Message) 851{ 852 this->Ranges.assign(Ranges.begin(), Ranges.end()); 853 this->FixIts.assign(FixIts.begin(), FixIts.end()); 854} 855 856StoredDiagnostic::~StoredDiagnostic() { } 857 858/// IncludeInDiagnosticCounts - This method (whose default implementation 859/// returns true) indicates whether the diagnostics handled by this 860/// DiagnosticConsumer should be included in the number of diagnostics 861/// reported by DiagnosticsEngine. 862bool DiagnosticConsumer::IncludeInDiagnosticCounts() const { return true; } 863 864void IgnoringDiagConsumer::anchor() { } 865 866PartialDiagnostic::StorageAllocator::StorageAllocator() { 867 for (unsigned I = 0; I != NumCached; ++I) 868 FreeList[I] = Cached + I; 869 NumFreeListEntries = NumCached; 870} 871 872PartialDiagnostic::StorageAllocator::~StorageAllocator() { 873 // Don't assert if we are in a CrashRecovery context, as this invariant may 874 // be invalidated during a crash. 875 assert((NumFreeListEntries == NumCached || 876 llvm::CrashRecoveryContext::isRecoveringFromCrash()) && 877 "A partial is on the lamb"); 878} 879