Home | History | Annotate | Download | only in Basic
      1 //===--- Diagnostic.cpp - C Language Family Diagnostic Handling -----------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 //  This file implements the Diagnostic-related interfaces.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #include "clang/Basic/Diagnostic.h"
     15 #include "clang/Basic/IdentifierTable.h"
     16 #include "clang/Basic/PartialDiagnostic.h"
     17 #include "llvm/ADT/SmallString.h"
     18 #include "llvm/Support/raw_ostream.h"
     19 #include "llvm/Support/CrashRecoveryContext.h"
     20 
     21 using namespace clang;
     22 
     23 static void DummyArgToStringFn(DiagnosticsEngine::ArgumentKind AK, intptr_t QT,
     24                                const char *Modifier, unsigned ML,
     25                                const char *Argument, unsigned ArgLen,
     26                                const DiagnosticsEngine::ArgumentValue *PrevArgs,
     27                                unsigned NumPrevArgs,
     28                                SmallVectorImpl<char> &Output,
     29                                void *Cookie,
     30                                ArrayRef<intptr_t> QualTypeVals) {
     31   const char *Str = "<can't format argument>";
     32   Output.append(Str, Str+strlen(Str));
     33 }
     34 
     35 
     36 DiagnosticsEngine::DiagnosticsEngine(
     37                        const IntrusiveRefCntPtr<DiagnosticIDs> &diags,
     38                        DiagnosticConsumer *client, bool ShouldOwnClient)
     39   : Diags(diags), Client(client), OwnsDiagClient(ShouldOwnClient),
     40     SourceMgr(0) {
     41   ArgToStringFn = DummyArgToStringFn;
     42   ArgToStringCookie = 0;
     43 
     44   AllExtensionsSilenced = 0;
     45   IgnoreAllWarnings = false;
     46   WarningsAsErrors = false;
     47   EnableAllWarnings = false;
     48   ErrorsAsFatal = false;
     49   SuppressSystemWarnings = false;
     50   SuppressAllDiagnostics = false;
     51   ShowOverloads = Ovl_All;
     52   ExtBehavior = Ext_Ignore;
     53 
     54   ErrorLimit = 0;
     55   TemplateBacktraceLimit = 0;
     56   ConstexprBacktraceLimit = 0;
     57 
     58   Reset();
     59 }
     60 
     61 DiagnosticsEngine::~DiagnosticsEngine() {
     62   if (OwnsDiagClient)
     63     delete Client;
     64 }
     65 
     66 void DiagnosticsEngine::setClient(DiagnosticConsumer *client,
     67                                   bool ShouldOwnClient) {
     68   if (OwnsDiagClient && Client)
     69     delete Client;
     70 
     71   Client = client;
     72   OwnsDiagClient = ShouldOwnClient;
     73 }
     74 
     75 void DiagnosticsEngine::pushMappings(SourceLocation Loc) {
     76   DiagStateOnPushStack.push_back(GetCurDiagState());
     77 }
     78 
     79 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 
     91 void 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 
    121 void 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 
    131 void DiagnosticsEngine::ReportDelayed() {
    132   Report(DelayedDiagID) << DelayedDiagArg1 << DelayedDiagArg2;
    133   DelayedDiagID = 0;
    134   DelayedDiagArg1.clear();
    135   DelayedDiagArg2.clear();
    136 }
    137 
    138 DiagnosticsEngine::DiagStatePointsTy::iterator
    139 DiagnosticsEngine::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.
    164 void 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 
    231 bool 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 
    246 void DiagnosticsEngine::setDiagnosticWarningAsError(diag::kind Diag,
    247                                                     bool Enabled) {
    248   // If we are enabling this feature, just set the diagnostic mappings to map to
    249   // errors.
    250   if (Enabled)
    251     setDiagnosticMapping(Diag, diag::MAP_ERROR, SourceLocation());
    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   DiagnosticMappingInfo &Info = GetCurDiagState()->getOrAddMappingInfo(Diag);
    256 
    257   if (Info.getMapping() == diag::MAP_ERROR ||
    258       Info.getMapping() == diag::MAP_FATAL)
    259     Info.setMapping(diag::MAP_WARNING);
    260 
    261   Info.setNoWarningAsError(true);
    262 }
    263 
    264 bool DiagnosticsEngine::setDiagnosticGroupWarningAsError(StringRef Group,
    265                                                          bool Enabled) {
    266   // If we are enabling this feature, just set the diagnostic mappings to map to
    267   // errors.
    268   if (Enabled)
    269     return setDiagnosticGroupMapping(Group, diag::MAP_ERROR);
    270 
    271   // Otherwise, we want to set the diagnostic mapping's "no Werror" bit, and
    272   // potentially downgrade anything already mapped to be a warning.
    273 
    274   // Get the diagnostics in this group.
    275   llvm::SmallVector<diag::kind, 8> GroupDiags;
    276   if (Diags->getDiagnosticsInGroup(Group, GroupDiags))
    277     return true;
    278 
    279   // Perform the mapping change.
    280   for (unsigned i = 0, e = GroupDiags.size(); i != e; ++i) {
    281     DiagnosticMappingInfo &Info = GetCurDiagState()->getOrAddMappingInfo(
    282       GroupDiags[i]);
    283 
    284     if (Info.getMapping() == diag::MAP_ERROR ||
    285         Info.getMapping() == diag::MAP_FATAL)
    286       Info.setMapping(diag::MAP_WARNING);
    287 
    288     Info.setNoWarningAsError(true);
    289   }
    290 
    291   return false;
    292 }
    293 
    294 void DiagnosticsEngine::setDiagnosticErrorAsFatal(diag::kind Diag,
    295                                                   bool Enabled) {
    296   // If we are enabling this feature, just set the diagnostic mappings to map to
    297   // errors.
    298   if (Enabled)
    299     setDiagnosticMapping(Diag, diag::MAP_FATAL, SourceLocation());
    300 
    301   // Otherwise, we want to set the diagnostic mapping's "no Werror" bit, and
    302   // potentially downgrade anything already mapped to be a warning.
    303   DiagnosticMappingInfo &Info = GetCurDiagState()->getOrAddMappingInfo(Diag);
    304 
    305   if (Info.getMapping() == diag::MAP_FATAL)
    306     Info.setMapping(diag::MAP_ERROR);
    307 
    308   Info.setNoErrorAsFatal(true);
    309 }
    310 
    311 bool DiagnosticsEngine::setDiagnosticGroupErrorAsFatal(StringRef Group,
    312                                                        bool Enabled) {
    313   // If we are enabling this feature, just set the diagnostic mappings to map to
    314   // fatal errors.
    315   if (Enabled)
    316     return setDiagnosticGroupMapping(Group, diag::MAP_FATAL);
    317 
    318   // Otherwise, we want to set the diagnostic mapping's "no Werror" bit, and
    319   // potentially downgrade anything already mapped to be an error.
    320 
    321   // Get the diagnostics in this group.
    322   llvm::SmallVector<diag::kind, 8> GroupDiags;
    323   if (Diags->getDiagnosticsInGroup(Group, GroupDiags))
    324     return true;
    325 
    326   // Perform the mapping change.
    327   for (unsigned i = 0, e = GroupDiags.size(); i != e; ++i) {
    328     DiagnosticMappingInfo &Info = GetCurDiagState()->getOrAddMappingInfo(
    329       GroupDiags[i]);
    330 
    331     if (Info.getMapping() == diag::MAP_FATAL)
    332       Info.setMapping(diag::MAP_ERROR);
    333 
    334     Info.setNoErrorAsFatal(true);
    335   }
    336 
    337   return false;
    338 }
    339 
    340 void DiagnosticsEngine::setMappingToAllDiagnostics(diag::Mapping Map,
    341                                                    SourceLocation Loc) {
    342   // Get all the diagnostics.
    343   llvm::SmallVector<diag::kind, 64> AllDiags;
    344   Diags->getAllDiagnostics(AllDiags);
    345 
    346   // Set the mapping.
    347   for (unsigned i = 0, e = AllDiags.size(); i != e; ++i)
    348     if (Diags->isBuiltinWarningOrExtension(AllDiags[i]))
    349       setDiagnosticMapping(AllDiags[i], Map, Loc);
    350 }
    351 
    352 void DiagnosticsEngine::Report(const StoredDiagnostic &storedDiag) {
    353   assert(CurDiagID == ~0U && "Multiple diagnostics in flight at once!");
    354 
    355   CurDiagLoc = storedDiag.getLocation();
    356   CurDiagID = storedDiag.getID();
    357   NumDiagArgs = 0;
    358 
    359   NumDiagRanges = storedDiag.range_size();
    360   assert(NumDiagRanges < DiagnosticsEngine::MaxRanges &&
    361          "Too many arguments to diagnostic!");
    362   unsigned i = 0;
    363   for (StoredDiagnostic::range_iterator
    364          RI = storedDiag.range_begin(),
    365          RE = storedDiag.range_end(); RI != RE; ++RI)
    366     DiagRanges[i++] = *RI;
    367 
    368   assert(NumDiagRanges < DiagnosticsEngine::MaxFixItHints &&
    369          "Too many arguments to diagnostic!");
    370   NumDiagFixItHints = 0;
    371   for (StoredDiagnostic::fixit_iterator
    372          FI = storedDiag.fixit_begin(),
    373          FE = storedDiag.fixit_end(); FI != FE; ++FI)
    374     DiagFixItHints[NumDiagFixItHints++] = *FI;
    375 
    376   assert(Client && "DiagnosticConsumer not set!");
    377   Level DiagLevel = storedDiag.getLevel();
    378   Diagnostic Info(this, storedDiag.getMessage());
    379   Client->HandleDiagnostic(DiagLevel, Info);
    380   if (Client->IncludeInDiagnosticCounts()) {
    381     if (DiagLevel == DiagnosticsEngine::Warning)
    382       ++NumWarnings;
    383   }
    384 
    385   CurDiagID = ~0U;
    386 }
    387 
    388 bool DiagnosticsEngine::EmitCurrentDiagnostic() {
    389   // Process the diagnostic, sending the accumulated information to the
    390   // DiagnosticConsumer.
    391   bool Emitted = ProcessDiag();
    392 
    393   // Clear out the current diagnostic object.
    394   unsigned DiagID = CurDiagID;
    395   Clear();
    396 
    397   // If there was a delayed diagnostic, emit it now.
    398   if (DelayedDiagID && DelayedDiagID != DiagID)
    399     ReportDelayed();
    400 
    401   return Emitted;
    402 }
    403 
    404 
    405 DiagnosticConsumer::~DiagnosticConsumer() {}
    406 
    407 void DiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
    408                                         const Diagnostic &Info) {
    409   if (!IncludeInDiagnosticCounts())
    410     return;
    411 
    412   if (DiagLevel == DiagnosticsEngine::Warning)
    413     ++NumWarnings;
    414   else if (DiagLevel >= DiagnosticsEngine::Error)
    415     ++NumErrors;
    416 }
    417 
    418 /// ModifierIs - Return true if the specified modifier matches specified string.
    419 template <std::size_t StrLen>
    420 static bool ModifierIs(const char *Modifier, unsigned ModifierLen,
    421                        const char (&Str)[StrLen]) {
    422   return StrLen-1 == ModifierLen && !memcmp(Modifier, Str, StrLen-1);
    423 }
    424 
    425 /// ScanForward - Scans forward, looking for the given character, skipping
    426 /// nested clauses and escaped characters.
    427 static const char *ScanFormat(const char *I, const char *E, char Target) {
    428   unsigned Depth = 0;
    429 
    430   for ( ; I != E; ++I) {
    431     if (Depth == 0 && *I == Target) return I;
    432     if (Depth != 0 && *I == '}') Depth--;
    433 
    434     if (*I == '%') {
    435       I++;
    436       if (I == E) break;
    437 
    438       // Escaped characters get implicitly skipped here.
    439 
    440       // Format specifier.
    441       if (!isdigit(*I) && !ispunct(*I)) {
    442         for (I++; I != E && !isdigit(*I) && *I != '{'; I++) ;
    443         if (I == E) break;
    444         if (*I == '{')
    445           Depth++;
    446       }
    447     }
    448   }
    449   return E;
    450 }
    451 
    452 /// HandleSelectModifier - Handle the integer 'select' modifier.  This is used
    453 /// like this:  %select{foo|bar|baz}2.  This means that the integer argument
    454 /// "%2" has a value from 0-2.  If the value is 0, the diagnostic prints 'foo'.
    455 /// If the value is 1, it prints 'bar'.  If it has the value 2, it prints 'baz'.
    456 /// This is very useful for certain classes of variant diagnostics.
    457 static void HandleSelectModifier(const Diagnostic &DInfo, unsigned ValNo,
    458                                  const char *Argument, unsigned ArgumentLen,
    459                                  SmallVectorImpl<char> &OutStr) {
    460   const char *ArgumentEnd = Argument+ArgumentLen;
    461 
    462   // Skip over 'ValNo' |'s.
    463   while (ValNo) {
    464     const char *NextVal = ScanFormat(Argument, ArgumentEnd, '|');
    465     assert(NextVal != ArgumentEnd && "Value for integer select modifier was"
    466            " larger than the number of options in the diagnostic string!");
    467     Argument = NextVal+1;  // Skip this string.
    468     --ValNo;
    469   }
    470 
    471   // Get the end of the value.  This is either the } or the |.
    472   const char *EndPtr = ScanFormat(Argument, ArgumentEnd, '|');
    473 
    474   // Recursively format the result of the select clause into the output string.
    475   DInfo.FormatDiagnostic(Argument, EndPtr, OutStr);
    476 }
    477 
    478 /// HandleIntegerSModifier - Handle the integer 's' modifier.  This adds the
    479 /// letter 's' to the string if the value is not 1.  This is used in cases like
    480 /// this:  "you idiot, you have %4 parameter%s4!".
    481 static void HandleIntegerSModifier(unsigned ValNo,
    482                                    SmallVectorImpl<char> &OutStr) {
    483   if (ValNo != 1)
    484     OutStr.push_back('s');
    485 }
    486 
    487 /// HandleOrdinalModifier - Handle the integer 'ord' modifier.  This
    488 /// prints the ordinal form of the given integer, with 1 corresponding
    489 /// to the first ordinal.  Currently this is hard-coded to use the
    490 /// English form.
    491 static void HandleOrdinalModifier(unsigned ValNo,
    492                                   SmallVectorImpl<char> &OutStr) {
    493   assert(ValNo != 0 && "ValNo must be strictly positive!");
    494 
    495   llvm::raw_svector_ostream Out(OutStr);
    496 
    497   // We could use text forms for the first N ordinals, but the numeric
    498   // forms are actually nicer in diagnostics because they stand out.
    499   Out << ValNo;
    500 
    501   // It is critically important that we do this perfectly for
    502   // user-written sequences with over 100 elements.
    503   switch (ValNo % 100) {
    504   case 11:
    505   case 12:
    506   case 13:
    507     Out << "th"; return;
    508   default:
    509     switch (ValNo % 10) {
    510     case 1: Out << "st"; return;
    511     case 2: Out << "nd"; return;
    512     case 3: Out << "rd"; return;
    513     default: Out << "th"; return;
    514     }
    515   }
    516 }
    517 
    518 
    519 /// PluralNumber - Parse an unsigned integer and advance Start.
    520 static unsigned PluralNumber(const char *&Start, const char *End) {
    521   // Programming 101: Parse a decimal number :-)
    522   unsigned Val = 0;
    523   while (Start != End && *Start >= '0' && *Start <= '9') {
    524     Val *= 10;
    525     Val += *Start - '0';
    526     ++Start;
    527   }
    528   return Val;
    529 }
    530 
    531 /// TestPluralRange - Test if Val is in the parsed range. Modifies Start.
    532 static bool TestPluralRange(unsigned Val, const char *&Start, const char *End) {
    533   if (*Start != '[') {
    534     unsigned Ref = PluralNumber(Start, End);
    535     return Ref == Val;
    536   }
    537 
    538   ++Start;
    539   unsigned Low = PluralNumber(Start, End);
    540   assert(*Start == ',' && "Bad plural expression syntax: expected ,");
    541   ++Start;
    542   unsigned High = PluralNumber(Start, End);
    543   assert(*Start == ']' && "Bad plural expression syntax: expected )");
    544   ++Start;
    545   return Low <= Val && Val <= High;
    546 }
    547 
    548 /// EvalPluralExpr - Actual expression evaluator for HandlePluralModifier.
    549 static bool EvalPluralExpr(unsigned ValNo, const char *Start, const char *End) {
    550   // Empty condition?
    551   if (*Start == ':')
    552     return true;
    553 
    554   while (1) {
    555     char C = *Start;
    556     if (C == '%') {
    557       // Modulo expression
    558       ++Start;
    559       unsigned Arg = PluralNumber(Start, End);
    560       assert(*Start == '=' && "Bad plural expression syntax: expected =");
    561       ++Start;
    562       unsigned ValMod = ValNo % Arg;
    563       if (TestPluralRange(ValMod, Start, End))
    564         return true;
    565     } else {
    566       assert((C == '[' || (C >= '0' && C <= '9')) &&
    567              "Bad plural expression syntax: unexpected character");
    568       // Range expression
    569       if (TestPluralRange(ValNo, Start, End))
    570         return true;
    571     }
    572 
    573     // Scan for next or-expr part.
    574     Start = std::find(Start, End, ',');
    575     if (Start == End)
    576       break;
    577     ++Start;
    578   }
    579   return false;
    580 }
    581 
    582 /// HandlePluralModifier - Handle the integer 'plural' modifier. This is used
    583 /// for complex plural forms, or in languages where all plurals are complex.
    584 /// The syntax is: %plural{cond1:form1|cond2:form2|:form3}, where condn are
    585 /// conditions that are tested in order, the form corresponding to the first
    586 /// that applies being emitted. The empty condition is always true, making the
    587 /// last form a default case.
    588 /// Conditions are simple boolean expressions, where n is the number argument.
    589 /// Here are the rules.
    590 /// condition  := expression | empty
    591 /// empty      :=                             -> always true
    592 /// expression := numeric [',' expression]    -> logical or
    593 /// numeric    := range                       -> true if n in range
    594 ///             | '%' number '=' range        -> true if n % number in range
    595 /// range      := number
    596 ///             | '[' number ',' number ']'   -> ranges are inclusive both ends
    597 ///
    598 /// Here are some examples from the GNU gettext manual written in this form:
    599 /// English:
    600 /// {1:form0|:form1}
    601 /// Latvian:
    602 /// {0:form2|%100=11,%10=0,%10=[2,9]:form1|:form0}
    603 /// Gaeilge:
    604 /// {1:form0|2:form1|:form2}
    605 /// Romanian:
    606 /// {1:form0|0,%100=[1,19]:form1|:form2}
    607 /// Lithuanian:
    608 /// {%10=0,%100=[10,19]:form2|%10=1:form0|:form1}
    609 /// Russian (requires repeated form):
    610 /// {%100=[11,14]:form2|%10=1:form0|%10=[2,4]:form1|:form2}
    611 /// Slovak
    612 /// {1:form0|[2,4]:form1|:form2}
    613 /// Polish (requires repeated form):
    614 /// {1:form0|%100=[10,20]:form2|%10=[2,4]:form1|:form2}
    615 static void HandlePluralModifier(const Diagnostic &DInfo, unsigned ValNo,
    616                                  const char *Argument, unsigned ArgumentLen,
    617                                  SmallVectorImpl<char> &OutStr) {
    618   const char *ArgumentEnd = Argument + ArgumentLen;
    619   while (1) {
    620     assert(Argument < ArgumentEnd && "Plural expression didn't match.");
    621     const char *ExprEnd = Argument;
    622     while (*ExprEnd != ':') {
    623       assert(ExprEnd != ArgumentEnd && "Plural missing expression end");
    624       ++ExprEnd;
    625     }
    626     if (EvalPluralExpr(ValNo, Argument, ExprEnd)) {
    627       Argument = ExprEnd + 1;
    628       ExprEnd = ScanFormat(Argument, ArgumentEnd, '|');
    629 
    630       // Recursively format the result of the plural clause into the
    631       // output string.
    632       DInfo.FormatDiagnostic(Argument, ExprEnd, OutStr);
    633       return;
    634     }
    635     Argument = ScanFormat(Argument, ArgumentEnd - 1, '|') + 1;
    636   }
    637 }
    638 
    639 
    640 /// FormatDiagnostic - Format this diagnostic into a string, substituting the
    641 /// formal arguments into the %0 slots.  The result is appended onto the Str
    642 /// array.
    643 void Diagnostic::
    644 FormatDiagnostic(SmallVectorImpl<char> &OutStr) const {
    645   if (!StoredDiagMessage.empty()) {
    646     OutStr.append(StoredDiagMessage.begin(), StoredDiagMessage.end());
    647     return;
    648   }
    649 
    650   StringRef Diag =
    651     getDiags()->getDiagnosticIDs()->getDescription(getID());
    652 
    653   FormatDiagnostic(Diag.begin(), Diag.end(), OutStr);
    654 }
    655 
    656 void Diagnostic::
    657 FormatDiagnostic(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 
    819 StoredDiagnostic::StoredDiagnostic() { }
    820 
    821 StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
    822                                    StringRef Message)
    823   : ID(ID), Level(Level), Loc(), Message(Message) { }
    824 
    825 StoredDiagnostic::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 
    846 StoredDiagnostic::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 
    856 StoredDiagnostic::~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.
    862 bool DiagnosticConsumer::IncludeInDiagnosticCounts() const { return true; }
    863 
    864 void IgnoringDiagConsumer::anchor() { }
    865 
    866 PartialDiagnostic::StorageAllocator::StorageAllocator() {
    867   for (unsigned I = 0; I != NumCached; ++I)
    868     FreeList[I] = Cached + I;
    869   NumFreeListEntries = NumCached;
    870 }
    871 
    872 PartialDiagnostic::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