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