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