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