Diagnostic.h revision 3efd52cf8f4e57c5571bd8cc3168264c3bc46a1e
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//  This file defines the Diagnostic-related interfaces.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_DIAGNOSTIC_H
15#define LLVM_CLANG_DIAGNOSTIC_H
16
17#include "clang/Basic/DiagnosticIDs.h"
18#include "clang/Basic/SourceLocation.h"
19#include "llvm/ADT/DenseMap.h"
20#include "llvm/ADT/IntrusiveRefCntPtr.h"
21#include "llvm/ADT/OwningPtr.h"
22#include "llvm/Support/type_traits.h"
23
24#include <vector>
25#include <list>
26
27namespace clang {
28  class DiagnosticClient;
29  class DiagnosticBuilder;
30  class IdentifierInfo;
31  class DeclContext;
32  class LangOptions;
33  class Preprocessor;
34  class DiagnosticErrorTrap;
35
36/// \brief Annotates a diagnostic with some code that should be
37/// inserted, removed, or replaced to fix the problem.
38///
39/// This kind of hint should be used when we are certain that the
40/// introduction, removal, or modification of a particular (small!)
41/// amount of code will correct a compilation error. The compiler
42/// should also provide full recovery from such errors, such that
43/// suppressing the diagnostic output can still result in successful
44/// compilation.
45class FixItHint {
46public:
47  /// \brief Code that should be replaced to correct the error. Empty for an
48  /// insertion hint.
49  CharSourceRange RemoveRange;
50
51  /// \brief The actual code to insert at the insertion location, as a
52  /// string.
53  std::string CodeToInsert;
54
55  /// \brief Empty code modification hint, indicating that no code
56  /// modification is known.
57  FixItHint() : RemoveRange() { }
58
59  bool isNull() const {
60    return !RemoveRange.isValid();
61  }
62
63  /// \brief Create a code modification hint that inserts the given
64  /// code string at a specific location.
65  static FixItHint CreateInsertion(SourceLocation InsertionLoc,
66                                   llvm::StringRef Code) {
67    FixItHint Hint;
68    Hint.RemoveRange =
69      CharSourceRange(SourceRange(InsertionLoc, InsertionLoc), false);
70    Hint.CodeToInsert = Code;
71    return Hint;
72  }
73
74  /// \brief Create a code modification hint that removes the given
75  /// source range.
76  static FixItHint CreateRemoval(CharSourceRange RemoveRange) {
77    FixItHint Hint;
78    Hint.RemoveRange = RemoveRange;
79    return Hint;
80  }
81  static FixItHint CreateRemoval(SourceRange RemoveRange) {
82    return CreateRemoval(CharSourceRange::getTokenRange(RemoveRange));
83  }
84
85  /// \brief Create a code modification hint that replaces the given
86  /// source range with the given code string.
87  static FixItHint CreateReplacement(CharSourceRange RemoveRange,
88                                     llvm::StringRef Code) {
89    FixItHint Hint;
90    Hint.RemoveRange = RemoveRange;
91    Hint.CodeToInsert = Code;
92    return Hint;
93  }
94
95  static FixItHint CreateReplacement(SourceRange RemoveRange,
96                                     llvm::StringRef Code) {
97    return CreateReplacement(CharSourceRange::getTokenRange(RemoveRange), Code);
98  }
99};
100
101/// Diagnostic - This concrete class is used by the front-end to report
102/// problems and issues.  It massages the diagnostics (e.g. handling things like
103/// "report warnings as errors" and passes them off to the DiagnosticClient for
104/// reporting to the user. Diagnostic is tied to one translation unit and
105/// one SourceManager.
106class Diagnostic : public llvm::RefCountedBase<Diagnostic> {
107public:
108  /// Level - The level of the diagnostic, after it has been through mapping.
109  enum Level {
110    Ignored = DiagnosticIDs::Ignored,
111    Note = DiagnosticIDs::Note,
112    Warning = DiagnosticIDs::Warning,
113    Error = DiagnosticIDs::Error,
114    Fatal = DiagnosticIDs::Fatal
115  };
116
117  /// ExtensionHandling - How do we handle otherwise-unmapped extension?  This
118  /// is controlled by -pedantic and -pedantic-errors.
119  enum ExtensionHandling {
120    Ext_Ignore, Ext_Warn, Ext_Error
121  };
122
123  enum ArgumentKind {
124    ak_std_string,      // std::string
125    ak_c_string,        // const char *
126    ak_sint,            // int
127    ak_uint,            // unsigned
128    ak_identifierinfo,  // IdentifierInfo
129    ak_qualtype,        // QualType
130    ak_declarationname, // DeclarationName
131    ak_nameddecl,       // NamedDecl *
132    ak_nestednamespec,  // NestedNameSpecifier *
133    ak_declcontext      // DeclContext *
134  };
135
136  /// Specifies which overload candidates to display when overload resolution
137  /// fails.
138  enum OverloadsShown {
139    Ovl_All,  ///< Show all overloads.
140    Ovl_Best  ///< Show just the "best" overload candidates.
141  };
142
143  /// ArgumentValue - This typedef represents on argument value, which is a
144  /// union discriminated by ArgumentKind, with a value.
145  typedef std::pair<ArgumentKind, intptr_t> ArgumentValue;
146
147private:
148  unsigned char AllExtensionsSilenced; // Used by __extension__
149  bool IgnoreAllWarnings;        // Ignore all warnings: -w
150  bool WarningsAsErrors;         // Treat warnings like errors:
151  bool ErrorsAsFatal;            // Treat errors like fatal errors.
152  bool SuppressSystemWarnings;   // Suppress warnings in system headers.
153  bool SuppressAllDiagnostics;   // Suppress all diagnostics.
154  OverloadsShown ShowOverloads;  // Which overload candidates to show.
155  unsigned ErrorLimit;           // Cap of # errors emitted, 0 -> no limit.
156  unsigned TemplateBacktraceLimit; // Cap on depth of template backtrace stack,
157                                   // 0 -> no limit.
158  ExtensionHandling ExtBehavior; // Map extensions onto warnings or errors?
159  llvm::IntrusiveRefCntPtr<DiagnosticIDs> Diags;
160  DiagnosticClient *Client;
161  bool OwnsDiagClient;
162  SourceManager *SourceMgr;
163
164  /// \brief Mapping information for diagnostics.  Mapping info is
165  /// packed into four bits per diagnostic.  The low three bits are the mapping
166  /// (an instance of diag::Mapping), or zero if unset.  The high bit is set
167  /// when the mapping was established as a user mapping.  If the high bit is
168  /// clear, then the low bits are set to the default value, and should be
169  /// mapped with -pedantic, -Werror, etc.
170  ///
171  /// A new DiagState is created and kept around when diagnostic pragmas modify
172  /// the state so that we know what is the diagnostic state at any given
173  /// source location.
174  class DiagState {
175    llvm::DenseMap<unsigned, unsigned> DiagMap;
176
177  public:
178    typedef llvm::DenseMap<unsigned, unsigned>::const_iterator iterator;
179
180    void setMapping(diag::kind Diag, unsigned Map) { DiagMap[Diag] = Map; }
181
182    diag::Mapping getMapping(diag::kind Diag) const {
183      iterator I = DiagMap.find(Diag);
184      if (I != DiagMap.end())
185        return (diag::Mapping)I->second;
186      return diag::Mapping();
187    }
188
189    iterator begin() const { return DiagMap.begin(); }
190    iterator end() const { return DiagMap.end(); }
191  };
192
193  /// \brief Keeps and automatically disposes all DiagStates that we create.
194  std::list<DiagState> DiagStates;
195
196  /// \brief Represents a point in source where the diagnostic state was
197  /// modified because of a pragma. 'Loc' can be null if the point represents
198  /// the diagnostic state modifications done through the command-line.
199  struct DiagStatePoint {
200    DiagState *State;
201    FullSourceLoc Loc;
202    DiagStatePoint(DiagState *State, FullSourceLoc Loc)
203      : State(State), Loc(Loc) { }
204
205    bool operator<(const DiagStatePoint &RHS) const {
206      // If Loc is invalid it means it came from <command-line>, in which case
207      // we regard it as coming before any valid source location.
208      if (RHS.Loc.isInvalid())
209        return false;
210      if (Loc.isInvalid())
211        return true;
212      return Loc.isBeforeInTranslationUnitThan(RHS.Loc);
213    }
214  };
215
216  /// \brief A vector of all DiagStatePoints representing changes in diagnostic
217  /// state due to diagnostic pragmas. The vector is always sorted according to
218  /// the SourceLocation of the DiagStatePoint.
219  typedef std::vector<DiagStatePoint> DiagStatePointsTy;
220  mutable DiagStatePointsTy DiagStatePoints;
221
222  /// \brief Keeps the DiagState that was active during each diagnostic 'push'
223  /// so we can get back at it when we 'pop'.
224  std::vector<DiagState *> DiagStateOnPushStack;
225
226  DiagState *GetCurDiagState() const {
227    assert(!DiagStatePoints.empty());
228    return DiagStatePoints.back().State;
229  }
230
231  void PushDiagStatePoint(DiagState *State, SourceLocation L) {
232    FullSourceLoc Loc(L, *SourceMgr);
233    // Make sure that DiagStatePoints is always sorted according to Loc.
234    assert((Loc.isValid() || DiagStatePoints.empty()) &&
235           "Adding invalid loc point after another point");
236    assert((Loc.isInvalid() || DiagStatePoints.empty() ||
237            DiagStatePoints.back().Loc.isInvalid() ||
238            DiagStatePoints.back().Loc.isBeforeInTranslationUnitThan(Loc)) &&
239           "Previous point loc comes after or is the same as new one");
240    DiagStatePoints.push_back(DiagStatePoint(State,
241                                             FullSourceLoc(Loc, *SourceMgr)));
242  }
243
244  /// \brief Finds the DiagStatePoint that contains the diagnostic state of
245  /// the given source location.
246  DiagStatePointsTy::iterator GetDiagStatePointForLoc(SourceLocation Loc) const;
247
248  /// ErrorOccurred / FatalErrorOccurred - This is set to true when an error or
249  /// fatal error is emitted, and is sticky.
250  bool ErrorOccurred;
251  bool FatalErrorOccurred;
252
253  /// LastDiagLevel - This is the level of the last diagnostic emitted.  This is
254  /// used to emit continuation diagnostics with the same level as the
255  /// diagnostic that they follow.
256  DiagnosticIDs::Level LastDiagLevel;
257
258  unsigned NumWarnings;       // Number of warnings reported
259  unsigned NumErrors;         // Number of errors reported
260  unsigned NumErrorsSuppressed; // Number of errors suppressed
261
262  /// ArgToStringFn - A function pointer that converts an opaque diagnostic
263  /// argument to a strings.  This takes the modifiers and argument that was
264  /// present in the diagnostic.
265  ///
266  /// The PrevArgs array (whose length is NumPrevArgs) indicates the previous
267  /// arguments formatted for this diagnostic.  Implementations of this function
268  /// can use this information to avoid redundancy across arguments.
269  ///
270  /// This is a hack to avoid a layering violation between libbasic and libsema.
271  typedef void (*ArgToStringFnTy)(ArgumentKind Kind, intptr_t Val,
272                                  const char *Modifier, unsigned ModifierLen,
273                                  const char *Argument, unsigned ArgumentLen,
274                                  const ArgumentValue *PrevArgs,
275                                  unsigned NumPrevArgs,
276                                  llvm::SmallVectorImpl<char> &Output,
277                                  void *Cookie);
278  void *ArgToStringCookie;
279  ArgToStringFnTy ArgToStringFn;
280
281  /// \brief ID of the "delayed" diagnostic, which is a (typically
282  /// fatal) diagnostic that had to be delayed because it was found
283  /// while emitting another diagnostic.
284  unsigned DelayedDiagID;
285
286  /// \brief First string argument for the delayed diagnostic.
287  std::string DelayedDiagArg1;
288
289  /// \brief Second string argument for the delayed diagnostic.
290  std::string DelayedDiagArg2;
291
292public:
293  explicit Diagnostic(const llvm::IntrusiveRefCntPtr<DiagnosticIDs> &Diags,
294                      DiagnosticClient *client = 0,
295                      bool ShouldOwnClient = true);
296  ~Diagnostic();
297
298  const llvm::IntrusiveRefCntPtr<DiagnosticIDs> &getDiagnosticIDs() const {
299    return Diags;
300  }
301
302  DiagnosticClient *getClient() { return Client; }
303  const DiagnosticClient *getClient() const { return Client; }
304
305  /// \brief Return the current diagnostic client along with ownership of that
306  /// client.
307  DiagnosticClient *takeClient() {
308    OwnsDiagClient = false;
309    return Client;
310  }
311
312  bool hasSourceManager() const { return SourceMgr != 0; }
313  SourceManager &getSourceManager() const {
314    assert(SourceMgr && "SourceManager not set!");
315    return *SourceMgr;
316  }
317  void setSourceManager(SourceManager *SrcMgr) { SourceMgr = SrcMgr; }
318
319  //===--------------------------------------------------------------------===//
320  //  Diagnostic characterization methods, used by a client to customize how
321  //  diagnostics are emitted.
322  //
323
324  /// pushMappings - Copies the current DiagMappings and pushes the new copy
325  /// onto the top of the stack.
326  void pushMappings(SourceLocation Loc);
327
328  /// popMappings - Pops the current DiagMappings off the top of the stack
329  /// causing the new top of the stack to be the active mappings. Returns
330  /// true if the pop happens, false if there is only one DiagMapping on the
331  /// stack.
332  bool popMappings(SourceLocation Loc);
333
334  /// \brief Set the diagnostic client associated with this diagnostic object.
335  ///
336  /// \param ShouldOwnClient true if the diagnostic object should take
337  /// ownership of \c client.
338  void setClient(DiagnosticClient *client, bool ShouldOwnClient = true) {
339    Client = client;
340    OwnsDiagClient = ShouldOwnClient;
341  }
342
343  /// setErrorLimit - Specify a limit for the number of errors we should
344  /// emit before giving up.  Zero disables the limit.
345  void setErrorLimit(unsigned Limit) { ErrorLimit = Limit; }
346
347  /// \brief Specify the maximum number of template instantiation
348  /// notes to emit along with a given diagnostic.
349  void setTemplateBacktraceLimit(unsigned Limit) {
350    TemplateBacktraceLimit = Limit;
351  }
352
353  /// \brief Retrieve the maximum number of template instantiation
354  /// nodes to emit along with a given diagnostic.
355  unsigned getTemplateBacktraceLimit() const {
356    return TemplateBacktraceLimit;
357  }
358
359  /// setIgnoreAllWarnings - When set to true, any unmapped warnings are
360  /// ignored.  If this and WarningsAsErrors are both set, then this one wins.
361  void setIgnoreAllWarnings(bool Val) { IgnoreAllWarnings = Val; }
362  bool getIgnoreAllWarnings() const { return IgnoreAllWarnings; }
363
364  /// setWarningsAsErrors - When set to true, any warnings reported are issued
365  /// as errors.
366  void setWarningsAsErrors(bool Val) { WarningsAsErrors = Val; }
367  bool getWarningsAsErrors() const { return WarningsAsErrors; }
368
369  /// setErrorsAsFatal - When set to true, any error reported is made a
370  /// fatal error.
371  void setErrorsAsFatal(bool Val) { ErrorsAsFatal = Val; }
372  bool getErrorsAsFatal() const { return ErrorsAsFatal; }
373
374  /// setSuppressSystemWarnings - When set to true mask warnings that
375  /// come from system headers.
376  void setSuppressSystemWarnings(bool Val) { SuppressSystemWarnings = Val; }
377  bool getSuppressSystemWarnings() const { return SuppressSystemWarnings; }
378
379  /// \brief Suppress all diagnostics, to silence the front end when we
380  /// know that we don't want any more diagnostics to be passed along to the
381  /// client
382  void setSuppressAllDiagnostics(bool Val = true) {
383    SuppressAllDiagnostics = Val;
384  }
385  bool getSuppressAllDiagnostics() const { return SuppressAllDiagnostics; }
386
387  /// \brief Specify which overload candidates to show when overload resolution
388  /// fails.  By default, we show all candidates.
389  void setShowOverloads(OverloadsShown Val) {
390    ShowOverloads = Val;
391  }
392  OverloadsShown getShowOverloads() const { return ShowOverloads; }
393
394  /// \brief Pretend that the last diagnostic issued was ignored. This can
395  /// be used by clients who suppress diagnostics themselves.
396  void setLastDiagnosticIgnored() {
397    LastDiagLevel = DiagnosticIDs::Ignored;
398  }
399
400  /// setExtensionHandlingBehavior - This controls whether otherwise-unmapped
401  /// extension diagnostics are mapped onto ignore/warning/error.  This
402  /// corresponds to the GCC -pedantic and -pedantic-errors option.
403  void setExtensionHandlingBehavior(ExtensionHandling H) {
404    ExtBehavior = H;
405  }
406
407  /// AllExtensionsSilenced - This is a counter bumped when an __extension__
408  /// block is encountered.  When non-zero, all extension diagnostics are
409  /// entirely silenced, no matter how they are mapped.
410  void IncrementAllExtensionsSilenced() { ++AllExtensionsSilenced; }
411  void DecrementAllExtensionsSilenced() { --AllExtensionsSilenced; }
412  bool hasAllExtensionsSilenced() { return AllExtensionsSilenced != 0; }
413
414  /// \brief This allows the client to specify that certain
415  /// warnings are ignored.  Notes can never be mapped, errors can only be
416  /// mapped to fatal, and WARNINGs and EXTENSIONs can be mapped arbitrarily.
417  ///
418  /// \param Loc The source location that this change of diagnostic state should
419  /// take affect. It can be null if we are setting the latest state.
420  void setDiagnosticMapping(diag::kind Diag, diag::Mapping Map,
421                            SourceLocation Loc);
422
423  /// setDiagnosticGroupMapping - Change an entire diagnostic group (e.g.
424  /// "unknown-pragmas" to have the specified mapping.  This returns true and
425  /// ignores the request if "Group" was unknown, false otherwise.
426  ///
427  /// 'Loc' is the source location that this change of diagnostic state should
428  /// take affect. It can be null if we are setting the state from command-line.
429  bool setDiagnosticGroupMapping(const char *Group, diag::Mapping Map,
430                                 SourceLocation Loc = SourceLocation()) {
431    return Diags->setDiagnosticGroupMapping(Group, Map, Loc, *this);
432  }
433
434  bool hasErrorOccurred() const { return ErrorOccurred; }
435  bool hasFatalErrorOccurred() const { return FatalErrorOccurred; }
436
437  unsigned getNumWarnings() const { return NumWarnings; }
438
439  void setNumWarnings(unsigned NumWarnings) {
440    this->NumWarnings = NumWarnings;
441  }
442
443  /// getCustomDiagID - Return an ID for a diagnostic with the specified message
444  /// and level.  If this is the first request for this diagnosic, it is
445  /// registered and created, otherwise the existing ID is returned.
446  unsigned getCustomDiagID(Level L, llvm::StringRef Message) {
447    return Diags->getCustomDiagID((DiagnosticIDs::Level)L, Message);
448  }
449
450  /// ConvertArgToString - This method converts a diagnostic argument (as an
451  /// intptr_t) into the string that represents it.
452  void ConvertArgToString(ArgumentKind Kind, intptr_t Val,
453                          const char *Modifier, unsigned ModLen,
454                          const char *Argument, unsigned ArgLen,
455                          const ArgumentValue *PrevArgs, unsigned NumPrevArgs,
456                          llvm::SmallVectorImpl<char> &Output) const {
457    ArgToStringFn(Kind, Val, Modifier, ModLen, Argument, ArgLen,
458                  PrevArgs, NumPrevArgs, Output, ArgToStringCookie);
459  }
460
461  void SetArgToStringFn(ArgToStringFnTy Fn, void *Cookie) {
462    ArgToStringFn = Fn;
463    ArgToStringCookie = Cookie;
464  }
465
466  /// \brief Reset the state of the diagnostic object to its initial
467  /// configuration.
468  void Reset();
469
470  //===--------------------------------------------------------------------===//
471  // Diagnostic classification and reporting interfaces.
472  //
473
474  /// \brief Based on the way the client configured the Diagnostic
475  /// object, classify the specified diagnostic ID into a Level, consumable by
476  /// the DiagnosticClient.
477  ///
478  /// \param Loc The source location we are interested in finding out the
479  /// diagnostic state. Can be null in order to query the latest state.
480  Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc) const {
481    return (Level)Diags->getDiagnosticLevel(DiagID, Loc, *this);
482  }
483
484  /// Report - Issue the message to the client.  @c DiagID is a member of the
485  /// @c diag::kind enum.  This actually returns aninstance of DiagnosticBuilder
486  /// which emits the diagnostics (through @c ProcessDiag) when it is destroyed.
487  /// @c Pos represents the source location associated with the diagnostic,
488  /// which can be an invalid location if no position information is available.
489  inline DiagnosticBuilder Report(SourceLocation Pos, unsigned DiagID);
490  inline DiagnosticBuilder Report(unsigned DiagID);
491
492  /// \brief Determine whethere there is already a diagnostic in flight.
493  bool isDiagnosticInFlight() const { return CurDiagID != ~0U; }
494
495  /// \brief Set the "delayed" diagnostic that will be emitted once
496  /// the current diagnostic completes.
497  ///
498  ///  If a diagnostic is already in-flight but the front end must
499  ///  report a problem (e.g., with an inconsistent file system
500  ///  state), this routine sets a "delayed" diagnostic that will be
501  ///  emitted after the current diagnostic completes. This should
502  ///  only be used for fatal errors detected at inconvenient
503  ///  times. If emitting a delayed diagnostic causes a second delayed
504  ///  diagnostic to be introduced, that second delayed diagnostic
505  ///  will be ignored.
506  ///
507  /// \param DiagID The ID of the diagnostic being delayed.
508  ///
509  /// \param Arg1 A string argument that will be provided to the
510  /// diagnostic. A copy of this string will be stored in the
511  /// Diagnostic object itself.
512  ///
513  /// \param Arg2 A string argument that will be provided to the
514  /// diagnostic. A copy of this string will be stored in the
515  /// Diagnostic object itself.
516  void SetDelayedDiagnostic(unsigned DiagID, llvm::StringRef Arg1 = "",
517                            llvm::StringRef Arg2 = "");
518
519  /// \brief Clear out the current diagnostic.
520  void Clear() { CurDiagID = ~0U; }
521
522private:
523  /// \brief Report the delayed diagnostic.
524  void ReportDelayed();
525
526
527  /// getDiagnosticMappingInfo - Return the mapping info currently set for the
528  /// specified builtin diagnostic.  This returns the high bit encoding, or zero
529  /// if the field is completely uninitialized.
530  diag::Mapping getDiagnosticMappingInfo(diag::kind Diag,
531                                         DiagState *State) const {
532    return State->getMapping(Diag);
533  }
534
535  void setDiagnosticMappingInternal(unsigned DiagId, unsigned Map,
536                                    DiagState *State,
537                                    bool isUser, bool isPragma) const {
538    if (isUser) Map |= 8;  // Set the high bit for user mappings.
539    if (isPragma) Map |= 0x10;  // Set the bit for diagnostic pragma mappings.
540    State->setMapping((diag::kind)DiagId, Map);
541  }
542
543  // This is private state used by DiagnosticBuilder.  We put it here instead of
544  // in DiagnosticBuilder in order to keep DiagnosticBuilder a small lightweight
545  // object.  This implementation choice means that we can only have one
546  // diagnostic "in flight" at a time, but this seems to be a reasonable
547  // tradeoff to keep these objects small.  Assertions verify that only one
548  // diagnostic is in flight at a time.
549  friend class DiagnosticIDs;
550  friend class DiagnosticBuilder;
551  friend class DiagnosticInfo;
552  friend class PartialDiagnostic;
553  friend class DiagnosticErrorTrap;
554
555  /// CurDiagLoc - This is the location of the current diagnostic that is in
556  /// flight.
557  SourceLocation CurDiagLoc;
558
559  /// CurDiagID - This is the ID of the current diagnostic that is in flight.
560  /// This is set to ~0U when there is no diagnostic in flight.
561  unsigned CurDiagID;
562
563  enum {
564    /// MaxArguments - The maximum number of arguments we can hold. We currently
565    /// only support up to 10 arguments (%0-%9).  A single diagnostic with more
566    /// than that almost certainly has to be simplified anyway.
567    MaxArguments = 10
568  };
569
570  /// NumDiagArgs - This contains the number of entries in Arguments.
571  signed char NumDiagArgs;
572  /// NumRanges - This is the number of ranges in the DiagRanges array.
573  unsigned char NumDiagRanges;
574  /// \brief The number of code modifications hints in the
575  /// FixItHints array.
576  unsigned char NumFixItHints;
577
578  /// DiagArgumentsKind - This is an array of ArgumentKind::ArgumentKind enum
579  /// values, with one for each argument.  This specifies whether the argument
580  /// is in DiagArgumentsStr or in DiagArguments.
581  unsigned char DiagArgumentsKind[MaxArguments];
582
583  /// DiagArgumentsStr - This holds the values of each string argument for the
584  /// current diagnostic.  This value is only used when the corresponding
585  /// ArgumentKind is ak_std_string.
586  std::string DiagArgumentsStr[MaxArguments];
587
588  /// DiagArgumentsVal - The values for the various substitution positions. This
589  /// is used when the argument is not an std::string.  The specific value is
590  /// mangled into an intptr_t and the intepretation depends on exactly what
591  /// sort of argument kind it is.
592  intptr_t DiagArgumentsVal[MaxArguments];
593
594  /// DiagRanges - The list of ranges added to this diagnostic.  It currently
595  /// only support 10 ranges, could easily be extended if needed.
596  CharSourceRange DiagRanges[10];
597
598  enum { MaxFixItHints = 3 };
599
600  /// FixItHints - If valid, provides a hint with some code
601  /// to insert, remove, or modify at a particular position.
602  FixItHint FixItHints[MaxFixItHints];
603
604  /// ProcessDiag - This is the method used to report a diagnostic that is
605  /// finally fully formed.
606  ///
607  /// \returns true if the diagnostic was emitted, false if it was
608  /// suppressed.
609  bool ProcessDiag() {
610    return Diags->ProcessDiag(*this);
611  }
612
613  friend class ASTReader;
614  friend class ASTWriter;
615};
616
617/// \brief RAII class that determines when any errors have occurred
618/// between the time the instance was created and the time it was
619/// queried.
620class DiagnosticErrorTrap {
621  Diagnostic &Diag;
622  unsigned PrevErrors;
623
624public:
625  explicit DiagnosticErrorTrap(Diagnostic &Diag)
626    : Diag(Diag), PrevErrors(Diag.NumErrors) {}
627
628  /// \brief Determine whether any errors have occurred since this
629  /// object instance was created.
630  bool hasErrorOccurred() const {
631    return Diag.NumErrors > PrevErrors;
632  }
633
634  // Set to initial state of "no errors occurred".
635  void reset() { PrevErrors = Diag.NumErrors; }
636};
637
638//===----------------------------------------------------------------------===//
639// DiagnosticBuilder
640//===----------------------------------------------------------------------===//
641
642/// DiagnosticBuilder - This is a little helper class used to produce
643/// diagnostics.  This is constructed by the Diagnostic::Report method, and
644/// allows insertion of extra information (arguments and source ranges) into the
645/// currently "in flight" diagnostic.  When the temporary for the builder is
646/// destroyed, the diagnostic is issued.
647///
648/// Note that many of these will be created as temporary objects (many call
649/// sites), so we want them to be small and we never want their address taken.
650/// This ensures that compilers with somewhat reasonable optimizers will promote
651/// the common fields to registers, eliminating increments of the NumArgs field,
652/// for example.
653class DiagnosticBuilder {
654  mutable Diagnostic *DiagObj;
655  mutable unsigned NumArgs, NumRanges, NumFixItHints;
656
657  void operator=(const DiagnosticBuilder&); // DO NOT IMPLEMENT
658  friend class Diagnostic;
659  explicit DiagnosticBuilder(Diagnostic *diagObj)
660    : DiagObj(diagObj), NumArgs(0), NumRanges(0), NumFixItHints(0) {}
661
662  friend class PartialDiagnostic;
663
664protected:
665  void FlushCounts();
666
667public:
668  /// Copy constructor.  When copied, this "takes" the diagnostic info from the
669  /// input and neuters it.
670  DiagnosticBuilder(const DiagnosticBuilder &D) {
671    DiagObj = D.DiagObj;
672    D.DiagObj = 0;
673    NumArgs = D.NumArgs;
674    NumRanges = D.NumRanges;
675    NumFixItHints = D.NumFixItHints;
676  }
677
678  /// \brief Simple enumeration value used to give a name to the
679  /// suppress-diagnostic constructor.
680  enum SuppressKind { Suppress };
681
682  /// \brief Create an empty DiagnosticBuilder object that represents
683  /// no actual diagnostic.
684  explicit DiagnosticBuilder(SuppressKind)
685    : DiagObj(0), NumArgs(0), NumRanges(0), NumFixItHints(0) { }
686
687  /// \brief Force the diagnostic builder to emit the diagnostic now.
688  ///
689  /// Once this function has been called, the DiagnosticBuilder object
690  /// should not be used again before it is destroyed.
691  ///
692  /// \returns true if a diagnostic was emitted, false if the
693  /// diagnostic was suppressed.
694  bool Emit();
695
696  /// Destructor - The dtor emits the diagnostic if it hasn't already
697  /// been emitted.
698  ~DiagnosticBuilder() { Emit(); }
699
700  /// isActive - Determine whether this diagnostic is still active.
701  bool isActive() const { return DiagObj != 0; }
702
703  /// \brief Retrieve the active diagnostic ID.
704  ///
705  /// \pre \c isActive()
706  unsigned getDiagID() const {
707    assert(isActive() && "Diagnostic is inactive");
708    return DiagObj->CurDiagID;
709  }
710
711  /// \brief Clear out the current diagnostic.
712  void Clear() { DiagObj = 0; }
713
714  /// Operator bool: conversion of DiagnosticBuilder to bool always returns
715  /// true.  This allows is to be used in boolean error contexts like:
716  /// return Diag(...);
717  operator bool() const { return true; }
718
719  void AddString(llvm::StringRef S) const {
720    assert(NumArgs < Diagnostic::MaxArguments &&
721           "Too many arguments to diagnostic!");
722    if (DiagObj) {
723      DiagObj->DiagArgumentsKind[NumArgs] = Diagnostic::ak_std_string;
724      DiagObj->DiagArgumentsStr[NumArgs++] = S;
725    }
726  }
727
728  void AddTaggedVal(intptr_t V, Diagnostic::ArgumentKind Kind) const {
729    assert(NumArgs < Diagnostic::MaxArguments &&
730           "Too many arguments to diagnostic!");
731    if (DiagObj) {
732      DiagObj->DiagArgumentsKind[NumArgs] = Kind;
733      DiagObj->DiagArgumentsVal[NumArgs++] = V;
734    }
735  }
736
737  void AddSourceRange(const CharSourceRange &R) const {
738    assert(NumRanges <
739           sizeof(DiagObj->DiagRanges)/sizeof(DiagObj->DiagRanges[0]) &&
740           "Too many arguments to diagnostic!");
741    if (DiagObj)
742      DiagObj->DiagRanges[NumRanges++] = R;
743  }
744
745  void AddFixItHint(const FixItHint &Hint) const {
746    if (Hint.isNull())
747      return;
748
749    assert(NumFixItHints < Diagnostic::MaxFixItHints &&
750           "Too many fix-it hints!");
751    if (DiagObj)
752      DiagObj->FixItHints[NumFixItHints++] = Hint;
753  }
754};
755
756inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
757                                           llvm::StringRef S) {
758  DB.AddString(S);
759  return DB;
760}
761
762inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
763                                           const char *Str) {
764  DB.AddTaggedVal(reinterpret_cast<intptr_t>(Str),
765                  Diagnostic::ak_c_string);
766  return DB;
767}
768
769inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, int I) {
770  DB.AddTaggedVal(I, Diagnostic::ak_sint);
771  return DB;
772}
773
774inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,bool I) {
775  DB.AddTaggedVal(I, Diagnostic::ak_sint);
776  return DB;
777}
778
779inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
780                                           unsigned I) {
781  DB.AddTaggedVal(I, Diagnostic::ak_uint);
782  return DB;
783}
784
785inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
786                                           const IdentifierInfo *II) {
787  DB.AddTaggedVal(reinterpret_cast<intptr_t>(II),
788                  Diagnostic::ak_identifierinfo);
789  return DB;
790}
791
792// Adds a DeclContext to the diagnostic. The enable_if template magic is here
793// so that we only match those arguments that are (statically) DeclContexts;
794// other arguments that derive from DeclContext (e.g., RecordDecls) will not
795// match.
796template<typename T>
797inline
798typename llvm::enable_if<llvm::is_same<T, DeclContext>,
799                         const DiagnosticBuilder &>::type
800operator<<(const DiagnosticBuilder &DB, T *DC) {
801  DB.AddTaggedVal(reinterpret_cast<intptr_t>(DC),
802                  Diagnostic::ak_declcontext);
803  return DB;
804}
805
806inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
807                                           const SourceRange &R) {
808  DB.AddSourceRange(CharSourceRange::getTokenRange(R));
809  return DB;
810}
811
812inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
813                                           const CharSourceRange &R) {
814  DB.AddSourceRange(R);
815  return DB;
816}
817
818inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
819                                           const FixItHint &Hint) {
820  DB.AddFixItHint(Hint);
821  return DB;
822}
823
824/// Report - Issue the message to the client.  DiagID is a member of the
825/// diag::kind enum.  This actually returns a new instance of DiagnosticBuilder
826/// which emits the diagnostics (through ProcessDiag) when it is destroyed.
827inline DiagnosticBuilder Diagnostic::Report(SourceLocation Loc,
828                                            unsigned DiagID){
829  assert(CurDiagID == ~0U && "Multiple diagnostics in flight at once!");
830  CurDiagLoc = Loc;
831  CurDiagID = DiagID;
832  return DiagnosticBuilder(this);
833}
834inline DiagnosticBuilder Diagnostic::Report(unsigned DiagID) {
835  return Report(SourceLocation(), DiagID);
836}
837
838//===----------------------------------------------------------------------===//
839// DiagnosticInfo
840//===----------------------------------------------------------------------===//
841
842/// DiagnosticInfo - This is a little helper class (which is basically a smart
843/// pointer that forward info from Diagnostic) that allows clients to enquire
844/// about the currently in-flight diagnostic.
845class DiagnosticInfo {
846  const Diagnostic *DiagObj;
847public:
848  explicit DiagnosticInfo(const Diagnostic *DO) : DiagObj(DO) {}
849
850  const Diagnostic *getDiags() const { return DiagObj; }
851  unsigned getID() const { return DiagObj->CurDiagID; }
852  const SourceLocation &getLocation() const { return DiagObj->CurDiagLoc; }
853  bool hasSourceManager() const { return DiagObj->hasSourceManager(); }
854  SourceManager &getSourceManager() const { return DiagObj->getSourceManager();}
855
856  unsigned getNumArgs() const { return DiagObj->NumDiagArgs; }
857
858  /// getArgKind - Return the kind of the specified index.  Based on the kind
859  /// of argument, the accessors below can be used to get the value.
860  Diagnostic::ArgumentKind getArgKind(unsigned Idx) const {
861    assert(Idx < getNumArgs() && "Argument index out of range!");
862    return (Diagnostic::ArgumentKind)DiagObj->DiagArgumentsKind[Idx];
863  }
864
865  /// getArgStdStr - Return the provided argument string specified by Idx.
866  const std::string &getArgStdStr(unsigned Idx) const {
867    assert(getArgKind(Idx) == Diagnostic::ak_std_string &&
868           "invalid argument accessor!");
869    return DiagObj->DiagArgumentsStr[Idx];
870  }
871
872  /// getArgCStr - Return the specified C string argument.
873  const char *getArgCStr(unsigned Idx) const {
874    assert(getArgKind(Idx) == Diagnostic::ak_c_string &&
875           "invalid argument accessor!");
876    return reinterpret_cast<const char*>(DiagObj->DiagArgumentsVal[Idx]);
877  }
878
879  /// getArgSInt - Return the specified signed integer argument.
880  int getArgSInt(unsigned Idx) const {
881    assert(getArgKind(Idx) == Diagnostic::ak_sint &&
882           "invalid argument accessor!");
883    return (int)DiagObj->DiagArgumentsVal[Idx];
884  }
885
886  /// getArgUInt - Return the specified unsigned integer argument.
887  unsigned getArgUInt(unsigned Idx) const {
888    assert(getArgKind(Idx) == Diagnostic::ak_uint &&
889           "invalid argument accessor!");
890    return (unsigned)DiagObj->DiagArgumentsVal[Idx];
891  }
892
893  /// getArgIdentifier - Return the specified IdentifierInfo argument.
894  const IdentifierInfo *getArgIdentifier(unsigned Idx) const {
895    assert(getArgKind(Idx) == Diagnostic::ak_identifierinfo &&
896           "invalid argument accessor!");
897    return reinterpret_cast<IdentifierInfo*>(DiagObj->DiagArgumentsVal[Idx]);
898  }
899
900  /// getRawArg - Return the specified non-string argument in an opaque form.
901  intptr_t getRawArg(unsigned Idx) const {
902    assert(getArgKind(Idx) != Diagnostic::ak_std_string &&
903           "invalid argument accessor!");
904    return DiagObj->DiagArgumentsVal[Idx];
905  }
906
907
908  /// getNumRanges - Return the number of source ranges associated with this
909  /// diagnostic.
910  unsigned getNumRanges() const {
911    return DiagObj->NumDiagRanges;
912  }
913
914  const CharSourceRange &getRange(unsigned Idx) const {
915    assert(Idx < DiagObj->NumDiagRanges && "Invalid diagnostic range index!");
916    return DiagObj->DiagRanges[Idx];
917  }
918
919  unsigned getNumFixItHints() const {
920    return DiagObj->NumFixItHints;
921  }
922
923  const FixItHint &getFixItHint(unsigned Idx) const {
924    return DiagObj->FixItHints[Idx];
925  }
926
927  const FixItHint *getFixItHints() const {
928    return DiagObj->NumFixItHints?
929             &DiagObj->FixItHints[0] : 0;
930  }
931
932  /// FormatDiagnostic - Format this diagnostic into a string, substituting the
933  /// formal arguments into the %0 slots.  The result is appended onto the Str
934  /// array.
935  void FormatDiagnostic(llvm::SmallVectorImpl<char> &OutStr) const;
936
937  /// FormatDiagnostic - Format the given format-string into the
938  /// output buffer using the arguments stored in this diagnostic.
939  void FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
940                        llvm::SmallVectorImpl<char> &OutStr) const;
941};
942
943/**
944 * \brief Represents a diagnostic in a form that can be retained until its
945 * corresponding source manager is destroyed.
946 */
947class StoredDiagnostic {
948  unsigned ID;
949  Diagnostic::Level Level;
950  FullSourceLoc Loc;
951  std::string Message;
952  std::vector<CharSourceRange> Ranges;
953  std::vector<FixItHint> FixIts;
954
955public:
956  StoredDiagnostic();
957  StoredDiagnostic(Diagnostic::Level Level, const DiagnosticInfo &Info);
958  StoredDiagnostic(Diagnostic::Level Level, unsigned ID,
959                   llvm::StringRef Message);
960  ~StoredDiagnostic();
961
962  /// \brief Evaluates true when this object stores a diagnostic.
963  operator bool() const { return Message.size() > 0; }
964
965  unsigned getID() const { return ID; }
966  Diagnostic::Level getLevel() const { return Level; }
967  const FullSourceLoc &getLocation() const { return Loc; }
968  llvm::StringRef getMessage() const { return Message; }
969
970  void setLocation(FullSourceLoc Loc) { this->Loc = Loc; }
971
972  typedef std::vector<CharSourceRange>::const_iterator range_iterator;
973  range_iterator range_begin() const { return Ranges.begin(); }
974  range_iterator range_end() const { return Ranges.end(); }
975  unsigned range_size() const { return Ranges.size(); }
976
977  typedef std::vector<FixItHint>::const_iterator fixit_iterator;
978  fixit_iterator fixit_begin() const { return FixIts.begin(); }
979  fixit_iterator fixit_end() const { return FixIts.end(); }
980  unsigned fixit_size() const { return FixIts.size(); }
981};
982
983/// DiagnosticClient - This is an abstract interface implemented by clients of
984/// the front-end, which formats and prints fully processed diagnostics.
985class DiagnosticClient {
986protected:
987  unsigned NumWarnings;       // Number of warnings reported
988  unsigned NumErrors;         // Number of errors reported
989
990public:
991  DiagnosticClient() : NumWarnings(0), NumErrors(0) { }
992
993  unsigned getNumErrors() const { return NumErrors; }
994  unsigned getNumWarnings() const { return NumWarnings; }
995
996  virtual ~DiagnosticClient();
997
998  /// BeginSourceFile - Callback to inform the diagnostic client that processing
999  /// of a source file is beginning.
1000  ///
1001  /// Note that diagnostics may be emitted outside the processing of a source
1002  /// file, for example during the parsing of command line options. However,
1003  /// diagnostics with source range information are required to only be emitted
1004  /// in between BeginSourceFile() and EndSourceFile().
1005  ///
1006  /// \arg LO - The language options for the source file being processed.
1007  /// \arg PP - The preprocessor object being used for the source; this optional
1008  /// and may not be present, for example when processing AST source files.
1009  virtual void BeginSourceFile(const LangOptions &LangOpts,
1010                               const Preprocessor *PP = 0) {}
1011
1012  /// EndSourceFile - Callback to inform the diagnostic client that processing
1013  /// of a source file has ended. The diagnostic client should assume that any
1014  /// objects made available via \see BeginSourceFile() are inaccessible.
1015  virtual void EndSourceFile() {}
1016
1017  /// IncludeInDiagnosticCounts - This method (whose default implementation
1018  /// returns true) indicates whether the diagnostics handled by this
1019  /// DiagnosticClient should be included in the number of diagnostics reported
1020  /// by Diagnostic.
1021  virtual bool IncludeInDiagnosticCounts() const;
1022
1023  /// HandleDiagnostic - Handle this diagnostic, reporting it to the user or
1024  /// capturing it to a log as needed.
1025  ///
1026  /// Default implementation just keeps track of the total number of warnings
1027  /// and errors.
1028  virtual void HandleDiagnostic(Diagnostic::Level DiagLevel,
1029                                const DiagnosticInfo &Info);
1030};
1031
1032}  // end namespace clang
1033
1034#endif
1035