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