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