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