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