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