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