Diagnostic.cpp revision dc0a2da1038cc725ad23d070e6a0d03078b7300d
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 occured, 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 DiagnosticBuilder::FlushCounts() {
216  DiagObj->NumDiagArgs = NumArgs;
217  DiagObj->NumDiagRanges = NumRanges;
218  DiagObj->NumFixItHints = NumFixItHints;
219}
220
221bool DiagnosticBuilder::Emit() {
222  // If DiagObj is null, then its soul was stolen by the copy ctor
223  // or the user called Emit().
224  if (DiagObj == 0) return false;
225
226  // When emitting diagnostics, we set the final argument count into
227  // the Diagnostic object.
228  FlushCounts();
229
230  // Process the diagnostic, sending the accumulated information to the
231  // DiagnosticClient.
232  bool Emitted = DiagObj->ProcessDiag();
233
234  // Clear out the current diagnostic object.
235  unsigned DiagID = DiagObj->CurDiagID;
236  DiagObj->Clear();
237
238  // If there was a delayed diagnostic, emit it now.
239  if (DiagObj->DelayedDiagID && DiagObj->DelayedDiagID != DiagID)
240    DiagObj->ReportDelayed();
241
242  // This diagnostic is dead.
243  DiagObj = 0;
244
245  return Emitted;
246}
247
248
249DiagnosticClient::~DiagnosticClient() {}
250
251void DiagnosticClient::HandleDiagnostic(Diagnostic::Level DiagLevel,
252                                        const DiagnosticInfo &Info) {
253  if (!IncludeInDiagnosticCounts())
254    return;
255
256  if (DiagLevel == Diagnostic::Warning)
257    ++NumWarnings;
258  else if (DiagLevel >= Diagnostic::Error)
259    ++NumErrors;
260}
261
262/// ModifierIs - Return true if the specified modifier matches specified string.
263template <std::size_t StrLen>
264static bool ModifierIs(const char *Modifier, unsigned ModifierLen,
265                       const char (&Str)[StrLen]) {
266  return StrLen-1 == ModifierLen && !memcmp(Modifier, Str, StrLen-1);
267}
268
269/// ScanForward - Scans forward, looking for the given character, skipping
270/// nested clauses and escaped characters.
271static const char *ScanFormat(const char *I, const char *E, char Target) {
272  unsigned Depth = 0;
273
274  for ( ; I != E; ++I) {
275    if (Depth == 0 && *I == Target) return I;
276    if (Depth != 0 && *I == '}') Depth--;
277
278    if (*I == '%') {
279      I++;
280      if (I == E) break;
281
282      // Escaped characters get implicitly skipped here.
283
284      // Format specifier.
285      if (!isdigit(*I) && !ispunct(*I)) {
286        for (I++; I != E && !isdigit(*I) && *I != '{'; I++) ;
287        if (I == E) break;
288        if (*I == '{')
289          Depth++;
290      }
291    }
292  }
293  return E;
294}
295
296/// HandleSelectModifier - Handle the integer 'select' modifier.  This is used
297/// like this:  %select{foo|bar|baz}2.  This means that the integer argument
298/// "%2" has a value from 0-2.  If the value is 0, the diagnostic prints 'foo'.
299/// If the value is 1, it prints 'bar'.  If it has the value 2, it prints 'baz'.
300/// This is very useful for certain classes of variant diagnostics.
301static void HandleSelectModifier(const DiagnosticInfo &DInfo, unsigned ValNo,
302                                 const char *Argument, unsigned ArgumentLen,
303                                 llvm::SmallVectorImpl<char> &OutStr) {
304  const char *ArgumentEnd = Argument+ArgumentLen;
305
306  // Skip over 'ValNo' |'s.
307  while (ValNo) {
308    const char *NextVal = ScanFormat(Argument, ArgumentEnd, '|');
309    assert(NextVal != ArgumentEnd && "Value for integer select modifier was"
310           " larger than the number of options in the diagnostic string!");
311    Argument = NextVal+1;  // Skip this string.
312    --ValNo;
313  }
314
315  // Get the end of the value.  This is either the } or the |.
316  const char *EndPtr = ScanFormat(Argument, ArgumentEnd, '|');
317
318  // Recursively format the result of the select clause into the output string.
319  DInfo.FormatDiagnostic(Argument, EndPtr, OutStr);
320}
321
322/// HandleIntegerSModifier - Handle the integer 's' modifier.  This adds the
323/// letter 's' to the string if the value is not 1.  This is used in cases like
324/// this:  "you idiot, you have %4 parameter%s4!".
325static void HandleIntegerSModifier(unsigned ValNo,
326                                   llvm::SmallVectorImpl<char> &OutStr) {
327  if (ValNo != 1)
328    OutStr.push_back('s');
329}
330
331/// HandleOrdinalModifier - Handle the integer 'ord' modifier.  This
332/// prints the ordinal form of the given integer, with 1 corresponding
333/// to the first ordinal.  Currently this is hard-coded to use the
334/// English form.
335static void HandleOrdinalModifier(unsigned ValNo,
336                                  llvm::SmallVectorImpl<char> &OutStr) {
337  assert(ValNo != 0 && "ValNo must be strictly positive!");
338
339  llvm::raw_svector_ostream Out(OutStr);
340
341  // We could use text forms for the first N ordinals, but the numeric
342  // forms are actually nicer in diagnostics because they stand out.
343  Out << ValNo;
344
345  // It is critically important that we do this perfectly for
346  // user-written sequences with over 100 elements.
347  switch (ValNo % 100) {
348  case 11:
349  case 12:
350  case 13:
351    Out << "th"; return;
352  default:
353    switch (ValNo % 10) {
354    case 1: Out << "st"; return;
355    case 2: Out << "nd"; return;
356    case 3: Out << "rd"; return;
357    default: Out << "th"; return;
358    }
359  }
360}
361
362
363/// PluralNumber - Parse an unsigned integer and advance Start.
364static unsigned PluralNumber(const char *&Start, const char *End) {
365  // Programming 101: Parse a decimal number :-)
366  unsigned Val = 0;
367  while (Start != End && *Start >= '0' && *Start <= '9') {
368    Val *= 10;
369    Val += *Start - '0';
370    ++Start;
371  }
372  return Val;
373}
374
375/// TestPluralRange - Test if Val is in the parsed range. Modifies Start.
376static bool TestPluralRange(unsigned Val, const char *&Start, const char *End) {
377  if (*Start != '[') {
378    unsigned Ref = PluralNumber(Start, End);
379    return Ref == Val;
380  }
381
382  ++Start;
383  unsigned Low = PluralNumber(Start, End);
384  assert(*Start == ',' && "Bad plural expression syntax: expected ,");
385  ++Start;
386  unsigned High = PluralNumber(Start, End);
387  assert(*Start == ']' && "Bad plural expression syntax: expected )");
388  ++Start;
389  return Low <= Val && Val <= High;
390}
391
392/// EvalPluralExpr - Actual expression evaluator for HandlePluralModifier.
393static bool EvalPluralExpr(unsigned ValNo, const char *Start, const char *End) {
394  // Empty condition?
395  if (*Start == ':')
396    return true;
397
398  while (1) {
399    char C = *Start;
400    if (C == '%') {
401      // Modulo expression
402      ++Start;
403      unsigned Arg = PluralNumber(Start, End);
404      assert(*Start == '=' && "Bad plural expression syntax: expected =");
405      ++Start;
406      unsigned ValMod = ValNo % Arg;
407      if (TestPluralRange(ValMod, Start, End))
408        return true;
409    } else {
410      assert((C == '[' || (C >= '0' && C <= '9')) &&
411             "Bad plural expression syntax: unexpected character");
412      // Range expression
413      if (TestPluralRange(ValNo, Start, End))
414        return true;
415    }
416
417    // Scan for next or-expr part.
418    Start = std::find(Start, End, ',');
419    if (Start == End)
420      break;
421    ++Start;
422  }
423  return false;
424}
425
426/// HandlePluralModifier - Handle the integer 'plural' modifier. This is used
427/// for complex plural forms, or in languages where all plurals are complex.
428/// The syntax is: %plural{cond1:form1|cond2:form2|:form3}, where condn are
429/// conditions that are tested in order, the form corresponding to the first
430/// that applies being emitted. The empty condition is always true, making the
431/// last form a default case.
432/// Conditions are simple boolean expressions, where n is the number argument.
433/// Here are the rules.
434/// condition  := expression | empty
435/// empty      :=                             -> always true
436/// expression := numeric [',' expression]    -> logical or
437/// numeric    := range                       -> true if n in range
438///             | '%' number '=' range        -> true if n % number in range
439/// range      := number
440///             | '[' number ',' number ']'   -> ranges are inclusive both ends
441///
442/// Here are some examples from the GNU gettext manual written in this form:
443/// English:
444/// {1:form0|:form1}
445/// Latvian:
446/// {0:form2|%100=11,%10=0,%10=[2,9]:form1|:form0}
447/// Gaeilge:
448/// {1:form0|2:form1|:form2}
449/// Romanian:
450/// {1:form0|0,%100=[1,19]:form1|:form2}
451/// Lithuanian:
452/// {%10=0,%100=[10,19]:form2|%10=1:form0|:form1}
453/// Russian (requires repeated form):
454/// {%100=[11,14]:form2|%10=1:form0|%10=[2,4]:form1|:form2}
455/// Slovak
456/// {1:form0|[2,4]:form1|:form2}
457/// Polish (requires repeated form):
458/// {1:form0|%100=[10,20]:form2|%10=[2,4]:form1|:form2}
459static void HandlePluralModifier(const DiagnosticInfo &DInfo, unsigned ValNo,
460                                 const char *Argument, unsigned ArgumentLen,
461                                 llvm::SmallVectorImpl<char> &OutStr) {
462  const char *ArgumentEnd = Argument + ArgumentLen;
463  while (1) {
464    assert(Argument < ArgumentEnd && "Plural expression didn't match.");
465    const char *ExprEnd = Argument;
466    while (*ExprEnd != ':') {
467      assert(ExprEnd != ArgumentEnd && "Plural missing expression end");
468      ++ExprEnd;
469    }
470    if (EvalPluralExpr(ValNo, Argument, ExprEnd)) {
471      Argument = ExprEnd + 1;
472      ExprEnd = ScanFormat(Argument, ArgumentEnd, '|');
473
474      // Recursively format the result of the plural clause into the
475      // output string.
476      DInfo.FormatDiagnostic(Argument, ExprEnd, OutStr);
477      return;
478    }
479    Argument = ScanFormat(Argument, ArgumentEnd - 1, '|') + 1;
480  }
481}
482
483
484/// FormatDiagnostic - Format this diagnostic into a string, substituting the
485/// formal arguments into the %0 slots.  The result is appended onto the Str
486/// array.
487void DiagnosticInfo::
488FormatDiagnostic(llvm::SmallVectorImpl<char> &OutStr) const {
489  const char *DiagStr = getDiags()->getDiagnosticIDs()->getDescription(getID());
490  const char *DiagEnd = DiagStr+strlen(DiagStr);
491
492  FormatDiagnostic(DiagStr, DiagEnd, OutStr);
493}
494
495void DiagnosticInfo::
496FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
497                 llvm::SmallVectorImpl<char> &OutStr) const {
498
499  /// FormattedArgs - Keep track of all of the arguments formatted by
500  /// ConvertArgToString and pass them into subsequent calls to
501  /// ConvertArgToString, allowing the implementation to avoid redundancies in
502  /// obvious cases.
503  llvm::SmallVector<Diagnostic::ArgumentValue, 8> FormattedArgs;
504
505  while (DiagStr != DiagEnd) {
506    if (DiagStr[0] != '%') {
507      // Append non-%0 substrings to Str if we have one.
508      const char *StrEnd = std::find(DiagStr, DiagEnd, '%');
509      OutStr.append(DiagStr, StrEnd);
510      DiagStr = StrEnd;
511      continue;
512    } else if (ispunct(DiagStr[1])) {
513      OutStr.push_back(DiagStr[1]);  // %% -> %.
514      DiagStr += 2;
515      continue;
516    }
517
518    // Skip the %.
519    ++DiagStr;
520
521    // This must be a placeholder for a diagnostic argument.  The format for a
522    // placeholder is one of "%0", "%modifier0", or "%modifier{arguments}0".
523    // The digit is a number from 0-9 indicating which argument this comes from.
524    // The modifier is a string of digits from the set [-a-z]+, arguments is a
525    // brace enclosed string.
526    const char *Modifier = 0, *Argument = 0;
527    unsigned ModifierLen = 0, ArgumentLen = 0;
528
529    // Check to see if we have a modifier.  If so eat it.
530    if (!isdigit(DiagStr[0])) {
531      Modifier = DiagStr;
532      while (DiagStr[0] == '-' ||
533             (DiagStr[0] >= 'a' && DiagStr[0] <= 'z'))
534        ++DiagStr;
535      ModifierLen = DiagStr-Modifier;
536
537      // If we have an argument, get it next.
538      if (DiagStr[0] == '{') {
539        ++DiagStr; // Skip {.
540        Argument = DiagStr;
541
542        DiagStr = ScanFormat(DiagStr, DiagEnd, '}');
543        assert(DiagStr != DiagEnd && "Mismatched {}'s in diagnostic string!");
544        ArgumentLen = DiagStr-Argument;
545        ++DiagStr;  // Skip }.
546      }
547    }
548
549    assert(isdigit(*DiagStr) && "Invalid format for argument in diagnostic");
550    unsigned ArgNo = *DiagStr++ - '0';
551
552    Diagnostic::ArgumentKind Kind = getArgKind(ArgNo);
553
554    switch (Kind) {
555    // ---- STRINGS ----
556    case Diagnostic::ak_std_string: {
557      const std::string &S = getArgStdStr(ArgNo);
558      assert(ModifierLen == 0 && "No modifiers for strings yet");
559      OutStr.append(S.begin(), S.end());
560      break;
561    }
562    case Diagnostic::ak_c_string: {
563      const char *S = getArgCStr(ArgNo);
564      assert(ModifierLen == 0 && "No modifiers for strings yet");
565
566      // Don't crash if get passed a null pointer by accident.
567      if (!S)
568        S = "(null)";
569
570      OutStr.append(S, S + strlen(S));
571      break;
572    }
573    // ---- INTEGERS ----
574    case Diagnostic::ak_sint: {
575      int Val = getArgSInt(ArgNo);
576
577      if (ModifierIs(Modifier, ModifierLen, "select")) {
578        HandleSelectModifier(*this, (unsigned)Val, Argument, ArgumentLen,
579                             OutStr);
580      } else if (ModifierIs(Modifier, ModifierLen, "s")) {
581        HandleIntegerSModifier(Val, OutStr);
582      } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
583        HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen,
584                             OutStr);
585      } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
586        HandleOrdinalModifier((unsigned)Val, OutStr);
587      } else {
588        assert(ModifierLen == 0 && "Unknown integer modifier");
589        llvm::raw_svector_ostream(OutStr) << Val;
590      }
591      break;
592    }
593    case Diagnostic::ak_uint: {
594      unsigned Val = getArgUInt(ArgNo);
595
596      if (ModifierIs(Modifier, ModifierLen, "select")) {
597        HandleSelectModifier(*this, Val, Argument, ArgumentLen, OutStr);
598      } else if (ModifierIs(Modifier, ModifierLen, "s")) {
599        HandleIntegerSModifier(Val, OutStr);
600      } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
601        HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen,
602                             OutStr);
603      } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
604        HandleOrdinalModifier(Val, OutStr);
605      } else {
606        assert(ModifierLen == 0 && "Unknown integer modifier");
607        llvm::raw_svector_ostream(OutStr) << Val;
608      }
609      break;
610    }
611    // ---- NAMES and TYPES ----
612    case Diagnostic::ak_identifierinfo: {
613      const IdentifierInfo *II = getArgIdentifier(ArgNo);
614      assert(ModifierLen == 0 && "No modifiers for strings yet");
615
616      // Don't crash if get passed a null pointer by accident.
617      if (!II) {
618        const char *S = "(null)";
619        OutStr.append(S, S + strlen(S));
620        continue;
621      }
622
623      llvm::raw_svector_ostream(OutStr) << '\'' << II->getName() << '\'';
624      break;
625    }
626    case Diagnostic::ak_qualtype:
627    case Diagnostic::ak_declarationname:
628    case Diagnostic::ak_nameddecl:
629    case Diagnostic::ak_nestednamespec:
630    case Diagnostic::ak_declcontext:
631      getDiags()->ConvertArgToString(Kind, getRawArg(ArgNo),
632                                     Modifier, ModifierLen,
633                                     Argument, ArgumentLen,
634                                     FormattedArgs.data(), FormattedArgs.size(),
635                                     OutStr);
636      break;
637    }
638
639    // Remember this argument info for subsequent formatting operations.  Turn
640    // std::strings into a null terminated string to make it be the same case as
641    // all the other ones.
642    if (Kind != Diagnostic::ak_std_string)
643      FormattedArgs.push_back(std::make_pair(Kind, getRawArg(ArgNo)));
644    else
645      FormattedArgs.push_back(std::make_pair(Diagnostic::ak_c_string,
646                                        (intptr_t)getArgStdStr(ArgNo).c_str()));
647
648  }
649}
650
651StoredDiagnostic::StoredDiagnostic() { }
652
653StoredDiagnostic::StoredDiagnostic(Diagnostic::Level Level, unsigned ID,
654                                   llvm::StringRef Message)
655  : ID(ID), Level(Level), Loc(), Message(Message) { }
656
657StoredDiagnostic::StoredDiagnostic(Diagnostic::Level Level,
658                                   const DiagnosticInfo &Info)
659  : ID(Info.getID()), Level(Level)
660{
661  assert((Info.getLocation().isInvalid() || Info.hasSourceManager()) &&
662       "Valid source location without setting a source manager for diagnostic");
663  if (Info.getLocation().isValid())
664    Loc = FullSourceLoc(Info.getLocation(), Info.getSourceManager());
665  llvm::SmallString<64> Message;
666  Info.FormatDiagnostic(Message);
667  this->Message.assign(Message.begin(), Message.end());
668
669  Ranges.reserve(Info.getNumRanges());
670  for (unsigned I = 0, N = Info.getNumRanges(); I != N; ++I)
671    Ranges.push_back(Info.getRange(I));
672
673  FixIts.reserve(Info.getNumFixItHints());
674  for (unsigned I = 0, N = Info.getNumFixItHints(); I != N; ++I)
675    FixIts.push_back(Info.getFixItHint(I));
676}
677
678StoredDiagnostic::~StoredDiagnostic() { }
679
680/// IncludeInDiagnosticCounts - This method (whose default implementation
681///  returns true) indicates whether the diagnostics handled by this
682///  DiagnosticClient should be included in the number of diagnostics
683///  reported by Diagnostic.
684bool DiagnosticClient::IncludeInDiagnosticCounts() const { return true; }
685
686PartialDiagnostic::StorageAllocator::StorageAllocator() {
687  for (unsigned I = 0; I != NumCached; ++I)
688    FreeList[I] = Cached + I;
689  NumFreeListEntries = NumCached;
690}
691
692PartialDiagnostic::StorageAllocator::~StorageAllocator() {
693  // Don't assert if we are in a CrashRecovery context, as this
694  // invariant may be invalidated during a crash.
695  assert((NumFreeListEntries == NumCached || llvm::CrashRecoveryContext::isRecoveringFromCrash()) && "A partial is on the lamb");
696}
697