Diagnostic.h revision 4def70d3040e73707c738f7c366737a986135edf
1//===--- Diagnostic.h - C Language Family Diagnostic Handling ---*- C++ -*-===//
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/// \file
11/// \brief Defines the Diagnostic-related interfaces.
12///
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_CLANG_DIAGNOSTIC_H
16#define LLVM_CLANG_DIAGNOSTIC_H
17
18#include "clang/Basic/DiagnosticIDs.h"
19#include "clang/Basic/SourceLocation.h"
20#include "llvm/ADT/ArrayRef.h"
21#include "llvm/ADT/DenseMap.h"
22#include "llvm/ADT/IntrusiveRefCntPtr.h"
23#include "llvm/ADT/OwningPtr.h"
24#include "llvm/Support/type_traits.h"
25
26#include <vector>
27#include <list>
28
29namespace clang {
30  class DiagnosticConsumer;
31  class DiagnosticBuilder;
32  class IdentifierInfo;
33  class DeclContext;
34  class LangOptions;
35  class Preprocessor;
36  class DiagnosticErrorTrap;
37  class StoredDiagnostic;
38
39/// \brief Annotates a diagnostic with some code that should be
40/// inserted, removed, or replaced to fix the problem.
41///
42/// This kind of hint should be used when we are certain that the
43/// introduction, removal, or modification of a particular (small!)
44/// amount of code will correct a compilation error. The compiler
45/// should also provide full recovery from such errors, such that
46/// suppressing the diagnostic output can still result in successful
47/// compilation.
48class FixItHint {
49public:
50  /// \brief Code that should be replaced to correct the error. Empty for an
51  /// insertion hint.
52  CharSourceRange RemoveRange;
53
54  /// \brief Code in the specific range that should be inserted in the insertion
55  /// location.
56  CharSourceRange InsertFromRange;
57
58  /// \brief The actual code to insert at the insertion location, as a
59  /// string.
60  std::string CodeToInsert;
61
62  bool BeforePreviousInsertions;
63
64  /// \brief Empty code modification hint, indicating that no code
65  /// modification is known.
66  FixItHint() : BeforePreviousInsertions(false) { }
67
68  bool isNull() const {
69    return !RemoveRange.isValid();
70  }
71
72  /// \brief Create a code modification hint that inserts the given
73  /// code string at a specific location.
74  static FixItHint CreateInsertion(SourceLocation InsertionLoc,
75                                   StringRef Code,
76                                   bool BeforePreviousInsertions = false) {
77    FixItHint Hint;
78    Hint.RemoveRange =
79      CharSourceRange(SourceRange(InsertionLoc, InsertionLoc), false);
80    Hint.CodeToInsert = Code;
81    Hint.BeforePreviousInsertions = BeforePreviousInsertions;
82    return Hint;
83  }
84
85  /// \brief Create a code modification hint that inserts the given
86  /// code from \p FromRange at a specific location.
87  static FixItHint CreateInsertionFromRange(SourceLocation InsertionLoc,
88                                            CharSourceRange FromRange,
89                                        bool BeforePreviousInsertions = false) {
90    FixItHint Hint;
91    Hint.RemoveRange =
92      CharSourceRange(SourceRange(InsertionLoc, InsertionLoc), false);
93    Hint.InsertFromRange = FromRange;
94    Hint.BeforePreviousInsertions = BeforePreviousInsertions;
95    return Hint;
96  }
97
98  /// \brief Create a code modification hint that removes the given
99  /// source range.
100  static FixItHint CreateRemoval(CharSourceRange RemoveRange) {
101    FixItHint Hint;
102    Hint.RemoveRange = RemoveRange;
103    return Hint;
104  }
105  static FixItHint CreateRemoval(SourceRange RemoveRange) {
106    return CreateRemoval(CharSourceRange::getTokenRange(RemoveRange));
107  }
108
109  /// \brief Create a code modification hint that replaces the given
110  /// source range with the given code string.
111  static FixItHint CreateReplacement(CharSourceRange RemoveRange,
112                                     StringRef Code) {
113    FixItHint Hint;
114    Hint.RemoveRange = RemoveRange;
115    Hint.CodeToInsert = Code;
116    return Hint;
117  }
118
119  static FixItHint CreateReplacement(SourceRange RemoveRange,
120                                     StringRef Code) {
121    return CreateReplacement(CharSourceRange::getTokenRange(RemoveRange), Code);
122  }
123};
124
125/// \brief Concrete class used by the front-end to report problems and issues.
126///
127/// This massages the diagnostics (e.g. handling things like "report warnings
128/// as errors" and passes them off to the DiagnosticConsumer for reporting to
129/// the user. DiagnosticsEngine is tied to one translation unit and one
130/// SourceManager.
131class DiagnosticsEngine : public RefCountedBase<DiagnosticsEngine> {
132public:
133  /// \brief The level of the diagnostic, after it has been through mapping.
134  enum Level {
135    Ignored = DiagnosticIDs::Ignored,
136    Note = DiagnosticIDs::Note,
137    Warning = DiagnosticIDs::Warning,
138    Error = DiagnosticIDs::Error,
139    Fatal = DiagnosticIDs::Fatal
140  };
141
142  /// \brief How do we handle otherwise-unmapped extension?
143  ///
144  /// This is controlled by -pedantic and -pedantic-errors.
145  enum ExtensionHandling {
146    Ext_Ignore, Ext_Warn, Ext_Error
147  };
148
149  enum ArgumentKind {
150    ak_std_string,      ///< std::string
151    ak_c_string,        ///< const char *
152    ak_sint,            ///< int
153    ak_uint,            ///< unsigned
154    ak_identifierinfo,  ///< IdentifierInfo
155    ak_qualtype,        ///< QualType
156    ak_declarationname, ///< DeclarationName
157    ak_nameddecl,       ///< NamedDecl *
158    ak_nestednamespec,  ///< NestedNameSpecifier *
159    ak_declcontext,     ///< DeclContext *
160    ak_qualtype_pair    ///< pair<QualType, QualType>
161  };
162
163  /// \brief Specifies which overload candidates to display when overload
164  /// resolution fails.
165  enum OverloadsShown {
166    Ovl_All,  ///< Show all overloads.
167    Ovl_Best  ///< Show just the "best" overload candidates.
168  };
169
170  /// \brief Represents on argument value, which is a union discriminated
171  /// by ArgumentKind, with a value.
172  typedef std::pair<ArgumentKind, intptr_t> ArgumentValue;
173
174private:
175  unsigned char AllExtensionsSilenced; // Used by __extension__
176  bool IgnoreAllWarnings;        // Ignore all warnings: -w
177  bool WarningsAsErrors;         // Treat warnings like errors.
178  bool EnableAllWarnings;        // Enable all warnings.
179  bool ErrorsAsFatal;            // Treat errors like fatal errors.
180  bool SuppressSystemWarnings;   // Suppress warnings in system headers.
181  bool SuppressAllDiagnostics;   // Suppress all diagnostics.
182  bool ElideType;                // Elide common types of templates.
183  bool PrintTemplateTree;        // Print a tree when comparing templates.
184  bool ShowColors;               // Color printing is enabled.
185  OverloadsShown ShowOverloads;  // Which overload candidates to show.
186  unsigned ErrorLimit;           // Cap of # errors emitted, 0 -> no limit.
187  unsigned TemplateBacktraceLimit; // Cap on depth of template backtrace stack,
188                                   // 0 -> no limit.
189  unsigned ConstexprBacktraceLimit; // Cap on depth of constexpr evaluation
190                                    // backtrace stack, 0 -> no limit.
191  ExtensionHandling ExtBehavior; // Map extensions onto warnings or errors?
192  IntrusiveRefCntPtr<DiagnosticIDs> Diags;
193  DiagnosticConsumer *Client;
194  bool OwnsDiagClient;
195  SourceManager *SourceMgr;
196
197  /// \brief Mapping information for diagnostics.
198  ///
199  /// Mapping info is packed into four bits per diagnostic.  The low three
200  /// bits are the mapping (an instance of diag::Mapping), or zero if unset.
201  /// The high bit is set when the mapping was established as a user mapping.
202  /// If the high bit is clear, then the low bits are set to the default
203  /// value, and should be mapped with -pedantic, -Werror, etc.
204  ///
205  /// A new DiagState is created and kept around when diagnostic pragmas modify
206  /// the state so that we know what is the diagnostic state at any given
207  /// source location.
208  class DiagState {
209    llvm::DenseMap<unsigned, DiagnosticMappingInfo> DiagMap;
210
211  public:
212    typedef llvm::DenseMap<unsigned, DiagnosticMappingInfo>::iterator
213      iterator;
214    typedef llvm::DenseMap<unsigned, DiagnosticMappingInfo>::const_iterator
215      const_iterator;
216
217    void setMappingInfo(diag::kind Diag, DiagnosticMappingInfo Info) {
218      DiagMap[Diag] = Info;
219    }
220
221    DiagnosticMappingInfo &getOrAddMappingInfo(diag::kind Diag);
222
223    const_iterator begin() const { return DiagMap.begin(); }
224    const_iterator end() const { return DiagMap.end(); }
225  };
226
227  /// \brief Keeps and automatically disposes all DiagStates that we create.
228  std::list<DiagState> DiagStates;
229
230  /// \brief Represents a point in source where the diagnostic state was
231  /// modified because of a pragma.
232  ///
233  /// 'Loc' can be null if the point represents the diagnostic state
234  /// modifications done through the command-line.
235  struct DiagStatePoint {
236    DiagState *State;
237    FullSourceLoc Loc;
238    DiagStatePoint(DiagState *State, FullSourceLoc Loc)
239      : State(State), Loc(Loc) { }
240
241    bool operator<(const DiagStatePoint &RHS) const {
242      // If Loc is invalid it means it came from <command-line>, in which case
243      // we regard it as coming before any valid source location.
244      if (RHS.Loc.isInvalid())
245        return false;
246      if (Loc.isInvalid())
247        return true;
248      return Loc.isBeforeInTranslationUnitThan(RHS.Loc);
249    }
250  };
251
252  /// \brief A sorted vector of all DiagStatePoints representing changes in
253  /// diagnostic state due to diagnostic pragmas.
254  ///
255  /// The vector is always sorted according to the SourceLocation of the
256  /// DiagStatePoint.
257  typedef std::vector<DiagStatePoint> DiagStatePointsTy;
258  mutable DiagStatePointsTy DiagStatePoints;
259
260  /// \brief Keeps the DiagState that was active during each diagnostic 'push'
261  /// so we can get back at it when we 'pop'.
262  std::vector<DiagState *> DiagStateOnPushStack;
263
264  DiagState *GetCurDiagState() const {
265    assert(!DiagStatePoints.empty());
266    return DiagStatePoints.back().State;
267  }
268
269  void PushDiagStatePoint(DiagState *State, SourceLocation L) {
270    FullSourceLoc Loc(L, getSourceManager());
271    // Make sure that DiagStatePoints is always sorted according to Loc.
272    assert(Loc.isValid() && "Adding invalid loc point");
273    assert(!DiagStatePoints.empty() &&
274           (DiagStatePoints.back().Loc.isInvalid() ||
275            DiagStatePoints.back().Loc.isBeforeInTranslationUnitThan(Loc)) &&
276           "Previous point loc comes after or is the same as new one");
277    DiagStatePoints.push_back(DiagStatePoint(State, Loc));
278  }
279
280  /// \brief Finds the DiagStatePoint that contains the diagnostic state of
281  /// the given source location.
282  DiagStatePointsTy::iterator GetDiagStatePointForLoc(SourceLocation Loc) const;
283
284  /// \brief Sticky flag set to \c true when an error is emitted.
285  bool ErrorOccurred;
286
287  /// \brief Sticky flag set to \c true when a fatal error is emitted.
288  bool FatalErrorOccurred;
289
290  /// \brief Indicates that an unrecoverable error has occurred.
291  bool UnrecoverableErrorOccurred;
292
293  /// \brief Counts for DiagnosticErrorTrap to check whether an error occurred
294  /// during a parsing section, e.g. during parsing a function.
295  unsigned TrapNumErrorsOccurred;
296  unsigned TrapNumUnrecoverableErrorsOccurred;
297
298  /// \brief The level of the last diagnostic emitted.
299  ///
300  /// This is used to emit continuation diagnostics with the same level as the
301  /// diagnostic that they follow.
302  DiagnosticIDs::Level LastDiagLevel;
303
304  unsigned NumWarnings;         ///< Number of warnings reported
305  unsigned NumErrors;           ///< Number of errors reported
306  unsigned NumErrorsSuppressed; ///< Number of errors suppressed
307
308  /// \brief A function pointer that converts an opaque diagnostic
309  /// argument to a strings.
310  ///
311  /// This takes the modifiers and argument that was present in the diagnostic.
312  ///
313  /// The PrevArgs array (whose length is NumPrevArgs) indicates the previous
314  /// arguments formatted for this diagnostic.  Implementations of this function
315  /// can use this information to avoid redundancy across arguments.
316  ///
317  /// This is a hack to avoid a layering violation between libbasic and libsema.
318  typedef void (*ArgToStringFnTy)(
319      ArgumentKind Kind, intptr_t Val,
320      const char *Modifier, unsigned ModifierLen,
321      const char *Argument, unsigned ArgumentLen,
322      const ArgumentValue *PrevArgs,
323      unsigned NumPrevArgs,
324      SmallVectorImpl<char> &Output,
325      void *Cookie,
326      ArrayRef<intptr_t> QualTypeVals);
327  void *ArgToStringCookie;
328  ArgToStringFnTy ArgToStringFn;
329
330  /// \brief ID of the "delayed" diagnostic, which is a (typically
331  /// fatal) diagnostic that had to be delayed because it was found
332  /// while emitting another diagnostic.
333  unsigned DelayedDiagID;
334
335  /// \brief First string argument for the delayed diagnostic.
336  std::string DelayedDiagArg1;
337
338  /// \brief Second string argument for the delayed diagnostic.
339  std::string DelayedDiagArg2;
340
341public:
342  explicit DiagnosticsEngine(
343                      const IntrusiveRefCntPtr<DiagnosticIDs> &Diags,
344                      DiagnosticConsumer *client = 0,
345                      bool ShouldOwnClient = true);
346  ~DiagnosticsEngine();
347
348  const IntrusiveRefCntPtr<DiagnosticIDs> &getDiagnosticIDs() const {
349    return Diags;
350  }
351
352  DiagnosticConsumer *getClient() { return Client; }
353  const DiagnosticConsumer *getClient() const { return Client; }
354
355  /// \brief Determine whether this \c DiagnosticsEngine object own its client.
356  bool ownsClient() const { return OwnsDiagClient; }
357
358  /// \brief Return the current diagnostic client along with ownership of that
359  /// client.
360  DiagnosticConsumer *takeClient() {
361    OwnsDiagClient = false;
362    return Client;
363  }
364
365  bool hasSourceManager() const { return SourceMgr != 0; }
366  SourceManager &getSourceManager() const {
367    assert(SourceMgr && "SourceManager not set!");
368    return *SourceMgr;
369  }
370  void setSourceManager(SourceManager *SrcMgr) { SourceMgr = SrcMgr; }
371
372  //===--------------------------------------------------------------------===//
373  //  DiagnosticsEngine characterization methods, used by a client to customize
374  //  how diagnostics are emitted.
375  //
376
377  /// \brief Copies the current DiagMappings and pushes the new copy
378  /// onto the top of the stack.
379  void pushMappings(SourceLocation Loc);
380
381  /// \brief Pops the current DiagMappings off the top of the stack,
382  /// causing the new top of the stack to be the active mappings.
383  ///
384  /// \returns \c true if the pop happens, \c false if there is only one
385  /// DiagMapping on the stack.
386  bool popMappings(SourceLocation Loc);
387
388  /// \brief Set the diagnostic client associated with this diagnostic object.
389  ///
390  /// \param ShouldOwnClient true if the diagnostic object should take
391  /// ownership of \c client.
392  void setClient(DiagnosticConsumer *client, bool ShouldOwnClient = true);
393
394  /// \brief Specify a limit for the number of errors we should
395  /// emit before giving up.
396  ///
397  /// Zero disables the limit.
398  void setErrorLimit(unsigned Limit) { ErrorLimit = Limit; }
399
400  /// \brief Specify the maximum number of template instantiation
401  /// notes to emit along with a given diagnostic.
402  void setTemplateBacktraceLimit(unsigned Limit) {
403    TemplateBacktraceLimit = Limit;
404  }
405
406  /// \brief Retrieve the maximum number of template instantiation
407  /// notes to emit along with a given diagnostic.
408  unsigned getTemplateBacktraceLimit() const {
409    return TemplateBacktraceLimit;
410  }
411
412  /// \brief Specify the maximum number of constexpr evaluation
413  /// notes to emit along with a given diagnostic.
414  void setConstexprBacktraceLimit(unsigned Limit) {
415    ConstexprBacktraceLimit = Limit;
416  }
417
418  /// \brief Retrieve the maximum number of constexpr evaluation
419  /// notes to emit along with a given diagnostic.
420  unsigned getConstexprBacktraceLimit() const {
421    return ConstexprBacktraceLimit;
422  }
423
424  /// \brief When set to true, any unmapped warnings are ignored.
425  ///
426  /// If this and WarningsAsErrors are both set, then this one wins.
427  void setIgnoreAllWarnings(bool Val) { IgnoreAllWarnings = Val; }
428  bool getIgnoreAllWarnings() const { return IgnoreAllWarnings; }
429
430  /// \brief When set to true, any unmapped ignored warnings are no longer
431  /// ignored.
432  ///
433  /// If this and IgnoreAllWarnings are both set, then that one wins.
434  void setEnableAllWarnings(bool Val) { EnableAllWarnings = Val; }
435  bool getEnableAllWarnngs() const { return EnableAllWarnings; }
436
437  /// \brief When set to true, any warnings reported are issued as errors.
438  void setWarningsAsErrors(bool Val) { WarningsAsErrors = Val; }
439  bool getWarningsAsErrors() const { return WarningsAsErrors; }
440
441  /// \brief When set to true, any error reported is made a fatal error.
442  void setErrorsAsFatal(bool Val) { ErrorsAsFatal = Val; }
443  bool getErrorsAsFatal() const { return ErrorsAsFatal; }
444
445  /// \brief When set to true mask warnings that come from system headers.
446  void setSuppressSystemWarnings(bool Val) { SuppressSystemWarnings = Val; }
447  bool getSuppressSystemWarnings() const { return SuppressSystemWarnings; }
448
449  /// \brief Suppress all diagnostics, to silence the front end when we
450  /// know that we don't want any more diagnostics to be passed along to the
451  /// client
452  void setSuppressAllDiagnostics(bool Val = true) {
453    SuppressAllDiagnostics = Val;
454  }
455  bool getSuppressAllDiagnostics() const { return SuppressAllDiagnostics; }
456
457  /// \brief Set type eliding, to skip outputting same types occurring in
458  /// template types.
459  void setElideType(bool Val = true) { ElideType = Val; }
460  bool getElideType() { return ElideType; }
461
462  /// \brief Set tree printing, to outputting the template difference in a
463  /// tree format.
464  void setPrintTemplateTree(bool Val = false) { PrintTemplateTree = Val; }
465  bool getPrintTemplateTree() { return PrintTemplateTree; }
466
467  /// \brief Set color printing, so the type diffing will inject color markers
468  /// into the output.
469  void setShowColors(bool Val = false) { ShowColors = Val; }
470  bool getShowColors() { return ShowColors; }
471
472  /// \brief Specify which overload candidates to show when overload resolution
473  /// fails.
474  ///
475  /// By default, we show all candidates.
476  void setShowOverloads(OverloadsShown Val) {
477    ShowOverloads = Val;
478  }
479  OverloadsShown getShowOverloads() const { return ShowOverloads; }
480
481  /// \brief Pretend that the last diagnostic issued was ignored, so any
482  /// subsequent notes will be suppressed.
483  ///
484  /// This can be used by clients who suppress diagnostics themselves.
485  void setLastDiagnosticIgnored() {
486    if (LastDiagLevel == DiagnosticIDs::Fatal)
487      FatalErrorOccurred = true;
488    LastDiagLevel = DiagnosticIDs::Ignored;
489  }
490
491  /// \brief Controls whether otherwise-unmapped extension diagnostics are
492  /// mapped onto ignore/warning/error.
493  ///
494  /// This corresponds to the GCC -pedantic and -pedantic-errors option.
495  void setExtensionHandlingBehavior(ExtensionHandling H) {
496    ExtBehavior = H;
497  }
498  ExtensionHandling getExtensionHandlingBehavior() const { return ExtBehavior; }
499
500  /// \brief Counter bumped when an __extension__  block is/ encountered.
501  ///
502  /// When non-zero, all extension diagnostics are entirely silenced, no
503  /// matter how they are mapped.
504  void IncrementAllExtensionsSilenced() { ++AllExtensionsSilenced; }
505  void DecrementAllExtensionsSilenced() { --AllExtensionsSilenced; }
506  bool hasAllExtensionsSilenced() { return AllExtensionsSilenced != 0; }
507
508  /// \brief This allows the client to specify that certain warnings are
509  /// ignored.
510  ///
511  /// Notes can never be mapped, errors can only be mapped to fatal, and
512  /// WARNINGs and EXTENSIONs can be mapped arbitrarily.
513  ///
514  /// \param Loc The source location that this change of diagnostic state should
515  /// take affect. It can be null if we are setting the latest state.
516  void setDiagnosticMapping(diag::kind Diag, diag::Mapping Map,
517                            SourceLocation Loc);
518
519  /// \brief Change an entire diagnostic group (e.g. "unknown-pragmas") to
520  /// have the specified mapping.
521  ///
522  /// \returns true (and ignores the request) if "Group" was unknown, false
523  /// otherwise.
524  ///
525  /// \param Loc The source location that this change of diagnostic state should
526  /// take affect. It can be null if we are setting the state from command-line.
527  bool setDiagnosticGroupMapping(StringRef Group, diag::Mapping Map,
528                                 SourceLocation Loc = SourceLocation());
529
530  /// \brief Set the warning-as-error flag for the given diagnostic.
531  ///
532  /// This function always only operates on the current diagnostic state.
533  void setDiagnosticWarningAsError(diag::kind Diag, bool Enabled);
534
535  /// \brief Set the warning-as-error flag for the given diagnostic group.
536  ///
537  /// This function always only operates on the current diagnostic state.
538  ///
539  /// \returns True if the given group is unknown, false otherwise.
540  bool setDiagnosticGroupWarningAsError(StringRef Group, bool Enabled);
541
542  /// \brief Set the error-as-fatal flag for the given diagnostic.
543  ///
544  /// This function always only operates on the current diagnostic state.
545  void setDiagnosticErrorAsFatal(diag::kind Diag, bool Enabled);
546
547  /// \brief Set the error-as-fatal flag for the given diagnostic group.
548  ///
549  /// This function always only operates on the current diagnostic state.
550  ///
551  /// \returns True if the given group is unknown, false otherwise.
552  bool setDiagnosticGroupErrorAsFatal(StringRef Group, bool Enabled);
553
554  /// \brief Add the specified mapping to all diagnostics.
555  ///
556  /// Mainly to be used by -Wno-everything to disable all warnings but allow
557  /// subsequent -W options to enable specific warnings.
558  void setMappingToAllDiagnostics(diag::Mapping Map,
559                                  SourceLocation Loc = SourceLocation());
560
561  bool hasErrorOccurred() const { return ErrorOccurred; }
562  bool hasFatalErrorOccurred() const { return FatalErrorOccurred; }
563
564  /// \brief Determine whether any kind of unrecoverable error has occurred.
565  bool hasUnrecoverableErrorOccurred() const {
566    return FatalErrorOccurred || UnrecoverableErrorOccurred;
567  }
568
569  unsigned getNumWarnings() const { return NumWarnings; }
570
571  void setNumWarnings(unsigned NumWarnings) {
572    this->NumWarnings = NumWarnings;
573  }
574
575  /// \brief Return an ID for a diagnostic with the specified message and level.
576  ///
577  /// If this is the first request for this diagnosic, it is registered and
578  /// created, otherwise the existing ID is returned.
579  unsigned getCustomDiagID(Level L, StringRef Message) {
580    return Diags->getCustomDiagID((DiagnosticIDs::Level)L, Message);
581  }
582
583  /// \brief Converts a diagnostic argument (as an intptr_t) into the string
584  /// that represents it.
585  void ConvertArgToString(ArgumentKind Kind, intptr_t Val,
586                          const char *Modifier, unsigned ModLen,
587                          const char *Argument, unsigned ArgLen,
588                          const ArgumentValue *PrevArgs, unsigned NumPrevArgs,
589                          SmallVectorImpl<char> &Output,
590                          ArrayRef<intptr_t> QualTypeVals) const {
591    ArgToStringFn(Kind, Val, Modifier, ModLen, Argument, ArgLen,
592                  PrevArgs, NumPrevArgs, Output, ArgToStringCookie,
593                  QualTypeVals);
594  }
595
596  void SetArgToStringFn(ArgToStringFnTy Fn, void *Cookie) {
597    ArgToStringFn = Fn;
598    ArgToStringCookie = Cookie;
599  }
600
601  /// \brief Reset the state of the diagnostic object to its initial
602  /// configuration.
603  void Reset();
604
605  //===--------------------------------------------------------------------===//
606  // DiagnosticsEngine classification and reporting interfaces.
607  //
608
609  /// \brief Based on the way the client configured the DiagnosticsEngine
610  /// object, classify the specified diagnostic ID into a Level, consumable by
611  /// the DiagnosticConsumer.
612  ///
613  /// \param Loc The source location we are interested in finding out the
614  /// diagnostic state. Can be null in order to query the latest state.
615  Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc) const {
616    return (Level)Diags->getDiagnosticLevel(DiagID, Loc, *this);
617  }
618
619  /// \brief Issue the message to the client.
620  ///
621  /// This actually returns an instance of DiagnosticBuilder which emits the
622  /// diagnostics (through @c ProcessDiag) when it is destroyed.
623  ///
624  /// \param DiagID A member of the @c diag::kind enum.
625  /// \param Loc Represents the source location associated with the diagnostic,
626  /// which can be an invalid location if no position information is available.
627  inline DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID);
628  inline DiagnosticBuilder Report(unsigned DiagID);
629
630  void Report(const StoredDiagnostic &storedDiag);
631
632  /// \brief Determine whethere there is already a diagnostic in flight.
633  bool isDiagnosticInFlight() const { return CurDiagID != ~0U; }
634
635  /// \brief Set the "delayed" diagnostic that will be emitted once
636  /// the current diagnostic completes.
637  ///
638  ///  If a diagnostic is already in-flight but the front end must
639  ///  report a problem (e.g., with an inconsistent file system
640  ///  state), this routine sets a "delayed" diagnostic that will be
641  ///  emitted after the current diagnostic completes. This should
642  ///  only be used for fatal errors detected at inconvenient
643  ///  times. If emitting a delayed diagnostic causes a second delayed
644  ///  diagnostic to be introduced, that second delayed diagnostic
645  ///  will be ignored.
646  ///
647  /// \param DiagID The ID of the diagnostic being delayed.
648  ///
649  /// \param Arg1 A string argument that will be provided to the
650  /// diagnostic. A copy of this string will be stored in the
651  /// DiagnosticsEngine object itself.
652  ///
653  /// \param Arg2 A string argument that will be provided to the
654  /// diagnostic. A copy of this string will be stored in the
655  /// DiagnosticsEngine object itself.
656  void SetDelayedDiagnostic(unsigned DiagID, StringRef Arg1 = "",
657                            StringRef Arg2 = "");
658
659  /// \brief Clear out the current diagnostic.
660  void Clear() { CurDiagID = ~0U; }
661
662private:
663  /// \brief Report the delayed diagnostic.
664  void ReportDelayed();
665
666  // This is private state used by DiagnosticBuilder.  We put it here instead of
667  // in DiagnosticBuilder in order to keep DiagnosticBuilder a small lightweight
668  // object.  This implementation choice means that we can only have one
669  // diagnostic "in flight" at a time, but this seems to be a reasonable
670  // tradeoff to keep these objects small.  Assertions verify that only one
671  // diagnostic is in flight at a time.
672  friend class DiagnosticIDs;
673  friend class DiagnosticBuilder;
674  friend class Diagnostic;
675  friend class PartialDiagnostic;
676  friend class DiagnosticErrorTrap;
677
678  /// \brief The location of the current diagnostic that is in flight.
679  SourceLocation CurDiagLoc;
680
681  /// \brief The ID of the current diagnostic that is in flight.
682  ///
683  /// This is set to ~0U when there is no diagnostic in flight.
684  unsigned CurDiagID;
685
686  enum {
687    /// \brief The maximum number of arguments we can hold.
688    ///
689    /// We currently only support up to 10 arguments (%0-%9).  A single
690    /// diagnostic with more than that almost certainly has to be simplified
691    /// anyway.
692    MaxArguments = 10,
693
694    /// \brief The maximum number of ranges we can hold.
695    MaxRanges = 10,
696
697    /// \brief The maximum number of ranges we can hold.
698    MaxFixItHints = 10
699  };
700
701  /// \brief The number of entries in Arguments.
702  signed char NumDiagArgs;
703  /// \brief The number of ranges in the DiagRanges array.
704  unsigned char NumDiagRanges;
705  /// \brief The number of hints in the DiagFixItHints array.
706  unsigned char NumDiagFixItHints;
707
708  /// \brief Specifies whether an argument is in DiagArgumentsStr or
709  /// in DiagArguments.
710  ///
711  /// This is an array of ArgumentKind::ArgumentKind enum values, one for each
712  /// argument.
713  unsigned char DiagArgumentsKind[MaxArguments];
714
715  /// \brief Holds the values of each string argument for the current
716  /// diagnostic.
717  ///
718  /// This is only used when the corresponding ArgumentKind is ak_std_string.
719  std::string DiagArgumentsStr[MaxArguments];
720
721  /// \brief The values for the various substitution positions.
722  ///
723  /// This is used when the argument is not an std::string.  The specific
724  /// value is mangled into an intptr_t and the interpretation depends on
725  /// exactly what sort of argument kind it is.
726  intptr_t DiagArgumentsVal[MaxArguments];
727
728  /// \brief The list of ranges added to this diagnostic.
729  CharSourceRange DiagRanges[MaxRanges];
730
731  /// \brief If valid, provides a hint with some code to insert, remove,
732  /// or modify at a particular position.
733  FixItHint DiagFixItHints[MaxFixItHints];
734
735  DiagnosticMappingInfo makeMappingInfo(diag::Mapping Map, SourceLocation L) {
736    bool isPragma = L.isValid();
737    DiagnosticMappingInfo MappingInfo = DiagnosticMappingInfo::Make(
738      Map, /*IsUser=*/true, isPragma);
739
740    // If this is a pragma mapping, then set the diagnostic mapping flags so
741    // that we override command line options.
742    if (isPragma) {
743      MappingInfo.setNoWarningAsError(true);
744      MappingInfo.setNoErrorAsFatal(true);
745    }
746
747    return MappingInfo;
748  }
749
750  /// \brief Used to report a diagnostic that is finally fully formed.
751  ///
752  /// \returns true if the diagnostic was emitted, false if it was suppressed.
753  bool ProcessDiag() {
754    return Diags->ProcessDiag(*this);
755  }
756
757  /// @name Diagnostic Emission
758  /// @{
759protected:
760  // Sema requires access to the following functions because the current design
761  // of SFINAE requires it to use its own SemaDiagnosticBuilder, which needs to
762  // access us directly to ensure we minimize the emitted code for the common
763  // Sema::Diag() patterns.
764  friend class Sema;
765
766  /// \brief Emit the current diagnostic and clear the diagnostic state.
767  ///
768  /// \param Force Emit the diagnostic regardless of suppression settings.
769  bool EmitCurrentDiagnostic(bool Force = false);
770
771  unsigned getCurrentDiagID() const { return CurDiagID; }
772
773  SourceLocation getCurrentDiagLoc() const { return CurDiagLoc; }
774
775  /// @}
776
777  friend class ASTReader;
778  friend class ASTWriter;
779};
780
781/// \brief RAII class that determines when any errors have occurred
782/// between the time the instance was created and the time it was
783/// queried.
784class DiagnosticErrorTrap {
785  DiagnosticsEngine &Diag;
786  unsigned NumErrors;
787  unsigned NumUnrecoverableErrors;
788
789public:
790  explicit DiagnosticErrorTrap(DiagnosticsEngine &Diag)
791    : Diag(Diag) { reset(); }
792
793  /// \brief Determine whether any errors have occurred since this
794  /// object instance was created.
795  bool hasErrorOccurred() const {
796    return Diag.TrapNumErrorsOccurred > NumErrors;
797  }
798
799  /// \brief Determine whether any unrecoverable errors have occurred since this
800  /// object instance was created.
801  bool hasUnrecoverableErrorOccurred() const {
802    return Diag.TrapNumUnrecoverableErrorsOccurred > NumUnrecoverableErrors;
803  }
804
805  /// \brief Set to initial state of "no errors occurred".
806  void reset() {
807    NumErrors = Diag.TrapNumErrorsOccurred;
808    NumUnrecoverableErrors = Diag.TrapNumUnrecoverableErrorsOccurred;
809  }
810};
811
812//===----------------------------------------------------------------------===//
813// DiagnosticBuilder
814//===----------------------------------------------------------------------===//
815
816/// \brief A little helper class used to produce diagnostics.
817///
818/// This is constructed by the DiagnosticsEngine::Report method, and
819/// allows insertion of extra information (arguments and source ranges) into
820/// the currently "in flight" diagnostic.  When the temporary for the builder
821/// is destroyed, the diagnostic is issued.
822///
823/// Note that many of these will be created as temporary objects (many call
824/// sites), so we want them to be small and we never want their address taken.
825/// This ensures that compilers with somewhat reasonable optimizers will promote
826/// the common fields to registers, eliminating increments of the NumArgs field,
827/// for example.
828class DiagnosticBuilder {
829  mutable DiagnosticsEngine *DiagObj;
830  mutable unsigned NumArgs, NumRanges, NumFixits;
831
832  /// \brief Status variable indicating if this diagnostic is still active.
833  ///
834  // NOTE: This field is redundant with DiagObj (IsActive iff (DiagObj == 0)),
835  // but LLVM is not currently smart enough to eliminate the null check that
836  // Emit() would end up with if we used that as our status variable.
837  mutable bool IsActive;
838
839  /// \brief Flag indicating that this diagnostic is being emitted via a
840  /// call to ForceEmit.
841  mutable bool IsForceEmit;
842
843  void operator=(const DiagnosticBuilder &) LLVM_DELETED_FUNCTION;
844  friend class DiagnosticsEngine;
845
846  DiagnosticBuilder()
847    : DiagObj(0), NumArgs(0), NumRanges(0), NumFixits(0), IsActive(false),
848      IsForceEmit(false) { }
849
850  explicit DiagnosticBuilder(DiagnosticsEngine *diagObj)
851    : DiagObj(diagObj), NumArgs(0), NumRanges(0), NumFixits(0), IsActive(true),
852      IsForceEmit(false) {
853    assert(diagObj && "DiagnosticBuilder requires a valid DiagnosticsEngine!");
854  }
855
856  friend class PartialDiagnostic;
857
858protected:
859  void FlushCounts() {
860    DiagObj->NumDiagArgs = NumArgs;
861    DiagObj->NumDiagRanges = NumRanges;
862    DiagObj->NumDiagFixItHints = NumFixits;
863  }
864
865  /// \brief Clear out the current diagnostic.
866  void Clear() const {
867    DiagObj = 0;
868    IsActive = false;
869    IsForceEmit = false;
870  }
871
872  /// \brief Determine whether this diagnostic is still active.
873  bool isActive() const { return IsActive; }
874
875  /// \brief Force the diagnostic builder to emit the diagnostic now.
876  ///
877  /// Once this function has been called, the DiagnosticBuilder object
878  /// should not be used again before it is destroyed.
879  ///
880  /// \returns true if a diagnostic was emitted, false if the
881  /// diagnostic was suppressed.
882  bool Emit() {
883    // If this diagnostic is inactive, then its soul was stolen by the copy ctor
884    // (or by a subclass, as in SemaDiagnosticBuilder).
885    if (!isActive()) return false;
886
887    // When emitting diagnostics, we set the final argument count into
888    // the DiagnosticsEngine object.
889    FlushCounts();
890
891    // Process the diagnostic.
892    bool Result = DiagObj->EmitCurrentDiagnostic(IsForceEmit);
893
894    // This diagnostic is dead.
895    Clear();
896
897    return Result;
898  }
899
900public:
901  /// Copy constructor.  When copied, this "takes" the diagnostic info from the
902  /// input and neuters it.
903  DiagnosticBuilder(const DiagnosticBuilder &D) {
904    DiagObj = D.DiagObj;
905    IsActive = D.IsActive;
906    IsForceEmit = D.IsForceEmit;
907    D.Clear();
908    NumArgs = D.NumArgs;
909    NumRanges = D.NumRanges;
910    NumFixits = D.NumFixits;
911  }
912
913  /// \brief Retrieve an empty diagnostic builder.
914  static DiagnosticBuilder getEmpty() {
915    return DiagnosticBuilder();
916  }
917
918  /// \brief Emits the diagnostic.
919  ~DiagnosticBuilder() {
920    Emit();
921  }
922
923  /// \brief Forces the diagnostic to be emitted.
924  const DiagnosticBuilder &setForceEmit() const {
925    IsForceEmit = true;
926    return *this;
927  }
928
929  /// \brief Conversion of DiagnosticBuilder to bool always returns \c true.
930  ///
931  /// This allows is to be used in boolean error contexts (where \c true is
932  /// used to indicate that an error has occurred), like:
933  /// \code
934  /// return Diag(...);
935  /// \endcode
936  operator bool() const { return true; }
937
938  void AddString(StringRef S) const {
939    assert(isActive() && "Clients must not add to cleared diagnostic!");
940    assert(NumArgs < DiagnosticsEngine::MaxArguments &&
941           "Too many arguments to diagnostic!");
942    DiagObj->DiagArgumentsKind[NumArgs] = DiagnosticsEngine::ak_std_string;
943    DiagObj->DiagArgumentsStr[NumArgs++] = S;
944  }
945
946  void AddTaggedVal(intptr_t V, DiagnosticsEngine::ArgumentKind Kind) const {
947    assert(isActive() && "Clients must not add to cleared diagnostic!");
948    assert(NumArgs < DiagnosticsEngine::MaxArguments &&
949           "Too many arguments to diagnostic!");
950    DiagObj->DiagArgumentsKind[NumArgs] = Kind;
951    DiagObj->DiagArgumentsVal[NumArgs++] = V;
952  }
953
954  void AddSourceRange(const CharSourceRange &R) const {
955    assert(isActive() && "Clients must not add to cleared diagnostic!");
956    assert(NumRanges < DiagnosticsEngine::MaxRanges &&
957           "Too many arguments to diagnostic!");
958    DiagObj->DiagRanges[NumRanges++] = R;
959  }
960
961  void AddFixItHint(const FixItHint &Hint) const {
962    assert(isActive() && "Clients must not add to cleared diagnostic!");
963    assert(NumFixits < DiagnosticsEngine::MaxFixItHints &&
964           "Too many arguments to diagnostic!");
965    DiagObj->DiagFixItHints[NumFixits++] = Hint;
966  }
967};
968
969inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
970                                           StringRef S) {
971  DB.AddString(S);
972  return DB;
973}
974
975inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
976                                           const char *Str) {
977  DB.AddTaggedVal(reinterpret_cast<intptr_t>(Str),
978                  DiagnosticsEngine::ak_c_string);
979  return DB;
980}
981
982inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, int I) {
983  DB.AddTaggedVal(I, DiagnosticsEngine::ak_sint);
984  return DB;
985}
986
987inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,bool I) {
988  DB.AddTaggedVal(I, DiagnosticsEngine::ak_sint);
989  return DB;
990}
991
992inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
993                                           unsigned I) {
994  DB.AddTaggedVal(I, DiagnosticsEngine::ak_uint);
995  return DB;
996}
997
998inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
999                                           const IdentifierInfo *II) {
1000  DB.AddTaggedVal(reinterpret_cast<intptr_t>(II),
1001                  DiagnosticsEngine::ak_identifierinfo);
1002  return DB;
1003}
1004
1005// Adds a DeclContext to the diagnostic. The enable_if template magic is here
1006// so that we only match those arguments that are (statically) DeclContexts;
1007// other arguments that derive from DeclContext (e.g., RecordDecls) will not
1008// match.
1009template<typename T>
1010inline
1011typename llvm::enable_if<llvm::is_same<T, DeclContext>,
1012                         const DiagnosticBuilder &>::type
1013operator<<(const DiagnosticBuilder &DB, T *DC) {
1014  DB.AddTaggedVal(reinterpret_cast<intptr_t>(DC),
1015                  DiagnosticsEngine::ak_declcontext);
1016  return DB;
1017}
1018
1019inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1020                                           const SourceRange &R) {
1021  DB.AddSourceRange(CharSourceRange::getTokenRange(R));
1022  return DB;
1023}
1024
1025inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1026                                           const CharSourceRange &R) {
1027  DB.AddSourceRange(R);
1028  return DB;
1029}
1030
1031inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1032                                           const FixItHint &Hint) {
1033  if (!Hint.isNull())
1034    DB.AddFixItHint(Hint);
1035  return DB;
1036}
1037
1038inline DiagnosticBuilder DiagnosticsEngine::Report(SourceLocation Loc,
1039                                            unsigned DiagID){
1040  assert(CurDiagID == ~0U && "Multiple diagnostics in flight at once!");
1041  CurDiagLoc = Loc;
1042  CurDiagID = DiagID;
1043  return DiagnosticBuilder(this);
1044}
1045inline DiagnosticBuilder DiagnosticsEngine::Report(unsigned DiagID) {
1046  return Report(SourceLocation(), DiagID);
1047}
1048
1049//===----------------------------------------------------------------------===//
1050// Diagnostic
1051//===----------------------------------------------------------------------===//
1052
1053/// A little helper class (which is basically a smart pointer that forwards
1054/// info from DiagnosticsEngine) that allows clients to enquire about the
1055/// currently in-flight diagnostic.
1056class Diagnostic {
1057  const DiagnosticsEngine *DiagObj;
1058  StringRef StoredDiagMessage;
1059public:
1060  explicit Diagnostic(const DiagnosticsEngine *DO) : DiagObj(DO) {}
1061  Diagnostic(const DiagnosticsEngine *DO, StringRef storedDiagMessage)
1062    : DiagObj(DO), StoredDiagMessage(storedDiagMessage) {}
1063
1064  const DiagnosticsEngine *getDiags() const { return DiagObj; }
1065  unsigned getID() const { return DiagObj->CurDiagID; }
1066  const SourceLocation &getLocation() const { return DiagObj->CurDiagLoc; }
1067  bool hasSourceManager() const { return DiagObj->hasSourceManager(); }
1068  SourceManager &getSourceManager() const { return DiagObj->getSourceManager();}
1069
1070  unsigned getNumArgs() const { return DiagObj->NumDiagArgs; }
1071
1072  /// \brief Return the kind of the specified index.
1073  ///
1074  /// Based on the kind of argument, the accessors below can be used to get
1075  /// the value.
1076  ///
1077  /// \pre Idx < getNumArgs()
1078  DiagnosticsEngine::ArgumentKind getArgKind(unsigned Idx) const {
1079    assert(Idx < getNumArgs() && "Argument index out of range!");
1080    return (DiagnosticsEngine::ArgumentKind)DiagObj->DiagArgumentsKind[Idx];
1081  }
1082
1083  /// \brief Return the provided argument string specified by \p Idx.
1084  /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_std_string
1085  const std::string &getArgStdStr(unsigned Idx) const {
1086    assert(getArgKind(Idx) == DiagnosticsEngine::ak_std_string &&
1087           "invalid argument accessor!");
1088    return DiagObj->DiagArgumentsStr[Idx];
1089  }
1090
1091  /// \brief Return the specified C string argument.
1092  /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_c_string
1093  const char *getArgCStr(unsigned Idx) const {
1094    assert(getArgKind(Idx) == DiagnosticsEngine::ak_c_string &&
1095           "invalid argument accessor!");
1096    return reinterpret_cast<const char*>(DiagObj->DiagArgumentsVal[Idx]);
1097  }
1098
1099  /// \brief Return the specified signed integer argument.
1100  /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_sint
1101  int getArgSInt(unsigned Idx) const {
1102    assert(getArgKind(Idx) == DiagnosticsEngine::ak_sint &&
1103           "invalid argument accessor!");
1104    return (int)DiagObj->DiagArgumentsVal[Idx];
1105  }
1106
1107  /// \brief Return the specified unsigned integer argument.
1108  /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_uint
1109  unsigned getArgUInt(unsigned Idx) const {
1110    assert(getArgKind(Idx) == DiagnosticsEngine::ak_uint &&
1111           "invalid argument accessor!");
1112    return (unsigned)DiagObj->DiagArgumentsVal[Idx];
1113  }
1114
1115  /// \brief Return the specified IdentifierInfo argument.
1116  /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_identifierinfo
1117  const IdentifierInfo *getArgIdentifier(unsigned Idx) const {
1118    assert(getArgKind(Idx) == DiagnosticsEngine::ak_identifierinfo &&
1119           "invalid argument accessor!");
1120    return reinterpret_cast<IdentifierInfo*>(DiagObj->DiagArgumentsVal[Idx]);
1121  }
1122
1123  /// \brief Return the specified non-string argument in an opaque form.
1124  /// \pre getArgKind(Idx) != DiagnosticsEngine::ak_std_string
1125  intptr_t getRawArg(unsigned Idx) const {
1126    assert(getArgKind(Idx) != DiagnosticsEngine::ak_std_string &&
1127           "invalid argument accessor!");
1128    return DiagObj->DiagArgumentsVal[Idx];
1129  }
1130
1131  /// \brief Return the number of source ranges associated with this diagnostic.
1132  unsigned getNumRanges() const {
1133    return DiagObj->NumDiagRanges;
1134  }
1135
1136  /// \pre Idx < getNumRanges()
1137  const CharSourceRange &getRange(unsigned Idx) const {
1138    assert(Idx < DiagObj->NumDiagRanges && "Invalid diagnostic range index!");
1139    return DiagObj->DiagRanges[Idx];
1140  }
1141
1142  /// \brief Return an array reference for this diagnostic's ranges.
1143  ArrayRef<CharSourceRange> getRanges() const {
1144    return llvm::makeArrayRef(DiagObj->DiagRanges, DiagObj->NumDiagRanges);
1145  }
1146
1147  unsigned getNumFixItHints() const {
1148    return DiagObj->NumDiagFixItHints;
1149  }
1150
1151  const FixItHint &getFixItHint(unsigned Idx) const {
1152    assert(Idx < getNumFixItHints() && "Invalid index!");
1153    return DiagObj->DiagFixItHints[Idx];
1154  }
1155
1156  const FixItHint *getFixItHints() const {
1157    return getNumFixItHints()? DiagObj->DiagFixItHints : 0;
1158  }
1159
1160  /// \brief Format this diagnostic into a string, substituting the
1161  /// formal arguments into the %0 slots.
1162  ///
1163  /// The result is appended onto the \p OutStr array.
1164  void FormatDiagnostic(SmallVectorImpl<char> &OutStr) const;
1165
1166  /// \brief Format the given format-string into the output buffer using the
1167  /// arguments stored in this diagnostic.
1168  void FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
1169                        SmallVectorImpl<char> &OutStr) const;
1170};
1171
1172/**
1173 * \brief Represents a diagnostic in a form that can be retained until its
1174 * corresponding source manager is destroyed.
1175 */
1176class StoredDiagnostic {
1177  unsigned ID;
1178  DiagnosticsEngine::Level Level;
1179  FullSourceLoc Loc;
1180  std::string Message;
1181  std::vector<CharSourceRange> Ranges;
1182  std::vector<FixItHint> FixIts;
1183
1184public:
1185  StoredDiagnostic();
1186  StoredDiagnostic(DiagnosticsEngine::Level Level, const Diagnostic &Info);
1187  StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
1188                   StringRef Message);
1189  StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
1190                   StringRef Message, FullSourceLoc Loc,
1191                   ArrayRef<CharSourceRange> Ranges,
1192                   ArrayRef<FixItHint> Fixits);
1193  ~StoredDiagnostic();
1194
1195  /// \brief Evaluates true when this object stores a diagnostic.
1196  operator bool() const { return Message.size() > 0; }
1197
1198  unsigned getID() const { return ID; }
1199  DiagnosticsEngine::Level getLevel() const { return Level; }
1200  const FullSourceLoc &getLocation() const { return Loc; }
1201  StringRef getMessage() const { return Message; }
1202
1203  void setLocation(FullSourceLoc Loc) { this->Loc = Loc; }
1204
1205  typedef std::vector<CharSourceRange>::const_iterator range_iterator;
1206  range_iterator range_begin() const { return Ranges.begin(); }
1207  range_iterator range_end() const { return Ranges.end(); }
1208  unsigned range_size() const { return Ranges.size(); }
1209
1210  ArrayRef<CharSourceRange> getRanges() const {
1211    return llvm::makeArrayRef(Ranges);
1212  }
1213
1214
1215  typedef std::vector<FixItHint>::const_iterator fixit_iterator;
1216  fixit_iterator fixit_begin() const { return FixIts.begin(); }
1217  fixit_iterator fixit_end() const { return FixIts.end(); }
1218  unsigned fixit_size() const { return FixIts.size(); }
1219
1220  ArrayRef<FixItHint> getFixIts() const {
1221    return llvm::makeArrayRef(FixIts);
1222  }
1223};
1224
1225/// \brief Abstract interface, implemented by clients of the front-end, which
1226/// formats and prints fully processed diagnostics.
1227class DiagnosticConsumer {
1228protected:
1229  unsigned NumWarnings;       ///< Number of warnings reported
1230  unsigned NumErrors;         ///< Number of errors reported
1231
1232public:
1233  DiagnosticConsumer() : NumWarnings(0), NumErrors(0) { }
1234
1235  unsigned getNumErrors() const { return NumErrors; }
1236  unsigned getNumWarnings() const { return NumWarnings; }
1237  virtual void clear() { NumWarnings = NumErrors = 0; }
1238
1239  virtual ~DiagnosticConsumer();
1240
1241  /// \brief Callback to inform the diagnostic client that processing
1242  /// of a source file is beginning.
1243  ///
1244  /// Note that diagnostics may be emitted outside the processing of a source
1245  /// file, for example during the parsing of command line options. However,
1246  /// diagnostics with source range information are required to only be emitted
1247  /// in between BeginSourceFile() and EndSourceFile().
1248  ///
1249  /// \param LangOpts The language options for the source file being processed.
1250  /// \param PP The preprocessor object being used for the source; this is
1251  /// optional, e.g., it may not be present when processing AST source files.
1252  virtual void BeginSourceFile(const LangOptions &LangOpts,
1253                               const Preprocessor *PP = 0) {}
1254
1255  /// \brief Callback to inform the diagnostic client that processing
1256  /// of a source file has ended.
1257  ///
1258  /// The diagnostic client should assume that any objects made available via
1259  /// BeginSourceFile() are inaccessible.
1260  virtual void EndSourceFile() {}
1261
1262  /// \brief Callback to inform the diagnostic client that processing of all
1263  /// source files has ended.
1264  virtual void finish() {}
1265
1266  /// \brief Indicates whether the diagnostics handled by this
1267  /// DiagnosticConsumer should be included in the number of diagnostics
1268  /// reported by DiagnosticsEngine.
1269  ///
1270  /// The default implementation returns true.
1271  virtual bool IncludeInDiagnosticCounts() const;
1272
1273  /// \brief Handle this diagnostic, reporting it to the user or
1274  /// capturing it to a log as needed.
1275  ///
1276  /// The default implementation just keeps track of the total number of
1277  /// warnings and errors.
1278  virtual void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
1279                                const Diagnostic &Info);
1280
1281  /// \brief Clone the diagnostic consumer, producing an equivalent consumer
1282  /// that can be used in a different context.
1283  virtual DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const = 0;
1284};
1285
1286/// \brief A diagnostic client that ignores all diagnostics.
1287class IgnoringDiagConsumer : public DiagnosticConsumer {
1288  virtual void anchor();
1289  void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
1290                        const Diagnostic &Info) {
1291    // Just ignore it.
1292  }
1293  DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
1294    return new IgnoringDiagConsumer();
1295  }
1296};
1297
1298// Struct used for sending info about how a type should be printed.
1299struct TemplateDiffTypes {
1300  intptr_t FromType;
1301  intptr_t ToType;
1302  unsigned PrintTree : 1;
1303  unsigned PrintFromType : 1;
1304  unsigned ElideType : 1;
1305  unsigned ShowColors : 1;
1306  // The printer sets this variable to true if the template diff was used.
1307  unsigned TemplateDiffUsed : 1;
1308};
1309
1310/// Special character that the diagnostic printer will use to toggle the bold
1311/// attribute.  The character itself will be not be printed.
1312const char ToggleHighlight = 127;
1313
1314}  // end namespace clang
1315
1316#endif
1317