Diagnostic.h revision dde5557e87e1163ad792471e0bdbb2cd17894576
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
340  /// setErrorLimit - Specify a limit for the number of errors we should
341  /// emit before giving up.  Zero disables the limit.
342  void setErrorLimit(unsigned Limit) { ErrorLimit = Limit; }
343
344  /// \brief Specify the maximum number of template instantiation
345  /// notes to emit along with a given diagnostic.
346  void setTemplateBacktraceLimit(unsigned Limit) {
347    TemplateBacktraceLimit = Limit;
348  }
349
350  /// \brief Retrieve the maximum number of template instantiation
351  /// nodes to emit along with a given diagnostic.
352  unsigned getTemplateBacktraceLimit() const {
353    return TemplateBacktraceLimit;
354  }
355
356  /// setIgnoreAllWarnings - When set to true, any unmapped warnings are
357  /// ignored.  If this and WarningsAsErrors are both set, then this one wins.
358  void setIgnoreAllWarnings(bool Val) { IgnoreAllWarnings = Val; }
359  bool getIgnoreAllWarnings() const { return IgnoreAllWarnings; }
360
361  /// setWarningsAsErrors - When set to true, any warnings reported are issued
362  /// as errors.
363  void setWarningsAsErrors(bool Val) { WarningsAsErrors = Val; }
364  bool getWarningsAsErrors() const { return WarningsAsErrors; }
365
366  /// setErrorsAsFatal - When set to true, any error reported is made a
367  /// fatal error.
368  void setErrorsAsFatal(bool Val) { ErrorsAsFatal = Val; }
369  bool getErrorsAsFatal() const { return ErrorsAsFatal; }
370
371  /// setSuppressSystemWarnings - When set to true mask warnings that
372  /// come from system headers.
373  void setSuppressSystemWarnings(bool Val) { SuppressSystemWarnings = Val; }
374  bool getSuppressSystemWarnings() const { return SuppressSystemWarnings; }
375
376  /// \brief Suppress all diagnostics, to silence the front end when we
377  /// know that we don't want any more diagnostics to be passed along to the
378  /// client
379  void setSuppressAllDiagnostics(bool Val = true) {
380    SuppressAllDiagnostics = Val;
381  }
382  bool getSuppressAllDiagnostics() const { return SuppressAllDiagnostics; }
383
384  /// \brief Specify which overload candidates to show when overload resolution
385  /// fails.  By default, we show all candidates.
386  void setShowOverloads(OverloadsShown Val) {
387    ShowOverloads = Val;
388  }
389  OverloadsShown getShowOverloads() const { return ShowOverloads; }
390
391  /// \brief Pretend that the last diagnostic issued was ignored. This can
392  /// be used by clients who suppress diagnostics themselves.
393  void setLastDiagnosticIgnored() {
394    LastDiagLevel = DiagnosticIDs::Ignored;
395  }
396
397  /// setExtensionHandlingBehavior - This controls whether otherwise-unmapped
398  /// extension diagnostics are mapped onto ignore/warning/error.  This
399  /// corresponds to the GCC -pedantic and -pedantic-errors option.
400  void setExtensionHandlingBehavior(ExtensionHandling H) {
401    ExtBehavior = H;
402  }
403
404  /// AllExtensionsSilenced - This is a counter bumped when an __extension__
405  /// block is encountered.  When non-zero, all extension diagnostics are
406  /// entirely silenced, no matter how they are mapped.
407  void IncrementAllExtensionsSilenced() { ++AllExtensionsSilenced; }
408  void DecrementAllExtensionsSilenced() { --AllExtensionsSilenced; }
409  bool hasAllExtensionsSilenced() { return AllExtensionsSilenced != 0; }
410
411  /// \brief This allows the client to specify that certain
412  /// warnings are ignored.  Notes can never be mapped, errors can only be
413  /// mapped to fatal, and WARNINGs and EXTENSIONs can be mapped arbitrarily.
414  ///
415  /// \param Loc The source location that this change of diagnostic state should
416  /// take affect. It can be null if we are setting the latest state.
417  void setDiagnosticMapping(diag::kind Diag, diag::Mapping Map,
418                            SourceLocation Loc);
419
420  /// setDiagnosticGroupMapping - Change an entire diagnostic group (e.g.
421  /// "unknown-pragmas" to have the specified mapping.  This returns true and
422  /// ignores the request if "Group" was unknown, false otherwise.
423  ///
424  /// 'Loc' is the source location that this change of diagnostic state should
425  /// take affect. It can be null if we are setting the state from command-line.
426  bool setDiagnosticGroupMapping(const char *Group, diag::Mapping Map,
427                                 SourceLocation Loc = SourceLocation()) {
428    return Diags->setDiagnosticGroupMapping(Group, Map, Loc, *this);
429  }
430
431  bool hasErrorOccurred() const { return ErrorOccurred; }
432  bool hasFatalErrorOccurred() const { return FatalErrorOccurred; }
433
434  unsigned getNumWarnings() const { return NumWarnings; }
435
436  void setNumWarnings(unsigned NumWarnings) {
437    this->NumWarnings = NumWarnings;
438  }
439
440  /// getCustomDiagID - Return an ID for a diagnostic with the specified message
441  /// and level.  If this is the first request for this diagnosic, it is
442  /// registered and created, otherwise the existing ID is returned.
443  unsigned getCustomDiagID(Level L, llvm::StringRef Message) {
444    return Diags->getCustomDiagID((DiagnosticIDs::Level)L, Message);
445  }
446
447  /// ConvertArgToString - This method converts a diagnostic argument (as an
448  /// intptr_t) into the string that represents it.
449  void ConvertArgToString(ArgumentKind Kind, intptr_t Val,
450                          const char *Modifier, unsigned ModLen,
451                          const char *Argument, unsigned ArgLen,
452                          const ArgumentValue *PrevArgs, unsigned NumPrevArgs,
453                          llvm::SmallVectorImpl<char> &Output) const {
454    ArgToStringFn(Kind, Val, Modifier, ModLen, Argument, ArgLen,
455                  PrevArgs, NumPrevArgs, Output, ArgToStringCookie);
456  }
457
458  void SetArgToStringFn(ArgToStringFnTy Fn, void *Cookie) {
459    ArgToStringFn = Fn;
460    ArgToStringCookie = Cookie;
461  }
462
463  /// \brief Reset the state of the diagnostic object to its initial
464  /// configuration.
465  void Reset();
466
467  //===--------------------------------------------------------------------===//
468  // Diagnostic classification and reporting interfaces.
469  //
470
471  /// \brief Based on the way the client configured the Diagnostic
472  /// object, classify the specified diagnostic ID into a Level, consumable by
473  /// the DiagnosticClient.
474  ///
475  /// \param Loc The source location we are interested in finding out the
476  /// diagnostic state. Can be null in order to query the latest state.
477  Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc,
478                           diag::Mapping *mapping = 0) const {
479    return (Level)Diags->getDiagnosticLevel(DiagID, Loc, *this, mapping);
480  }
481
482  /// Report - Issue the message to the client.  @c DiagID is a member of the
483  /// @c diag::kind enum.  This actually returns aninstance of DiagnosticBuilder
484  /// which emits the diagnostics (through @c ProcessDiag) when it is destroyed.
485  /// @c Pos represents the source location associated with the diagnostic,
486  /// which can be an invalid location if no position information is available.
487  inline DiagnosticBuilder Report(SourceLocation Pos, unsigned DiagID);
488  inline DiagnosticBuilder Report(unsigned DiagID);
489
490  /// \brief Determine whethere there is already a diagnostic in flight.
491  bool isDiagnosticInFlight() const { return CurDiagID != ~0U; }
492
493  /// \brief Set the "delayed" diagnostic that will be emitted once
494  /// the current diagnostic completes.
495  ///
496  ///  If a diagnostic is already in-flight but the front end must
497  ///  report a problem (e.g., with an inconsistent file system
498  ///  state), this routine sets a "delayed" diagnostic that will be
499  ///  emitted after the current diagnostic completes. This should
500  ///  only be used for fatal errors detected at inconvenient
501  ///  times. If emitting a delayed diagnostic causes a second delayed
502  ///  diagnostic to be introduced, that second delayed diagnostic
503  ///  will be ignored.
504  ///
505  /// \param DiagID The ID of the diagnostic being delayed.
506  ///
507  /// \param Arg1 A string argument that will be provided to the
508  /// diagnostic. A copy of this string will be stored in the
509  /// Diagnostic object itself.
510  ///
511  /// \param Arg2 A string argument that will be provided to the
512  /// diagnostic. A copy of this string will be stored in the
513  /// Diagnostic object itself.
514  void SetDelayedDiagnostic(unsigned DiagID, llvm::StringRef Arg1 = "",
515                            llvm::StringRef Arg2 = "");
516
517  /// \brief Clear out the current diagnostic.
518  void Clear() { CurDiagID = ~0U; }
519
520private:
521  /// \brief Report the delayed diagnostic.
522  void ReportDelayed();
523
524
525  /// getDiagnosticMappingInfo - Return the mapping info currently set for the
526  /// specified builtin diagnostic.  This returns the high bit encoding, or zero
527  /// if the field is completely uninitialized.
528  diag::Mapping getDiagnosticMappingInfo(diag::kind Diag,
529                                         DiagState *State) const {
530    return State->getMapping(Diag);
531  }
532
533  void setDiagnosticMappingInternal(unsigned DiagId, unsigned Map,
534                                    DiagState *State,
535                                    bool isUser, bool isPragma) const {
536    if (isUser) Map |= 8;  // Set the high bit for user mappings.
537    if (isPragma) Map |= 0x10;  // Set the bit for diagnostic pragma mappings.
538    State->setMapping((diag::kind)DiagId, Map);
539  }
540
541  // This is private state used by DiagnosticBuilder.  We put it here instead of
542  // in DiagnosticBuilder in order to keep DiagnosticBuilder a small lightweight
543  // object.  This implementation choice means that we can only have one
544  // diagnostic "in flight" at a time, but this seems to be a reasonable
545  // tradeoff to keep these objects small.  Assertions verify that only one
546  // diagnostic is in flight at a time.
547  friend class DiagnosticIDs;
548  friend class DiagnosticBuilder;
549  friend class DiagnosticInfo;
550  friend class PartialDiagnostic;
551  friend class DiagnosticErrorTrap;
552
553  /// CurDiagLoc - This is the location of the current diagnostic that is in
554  /// flight.
555  SourceLocation CurDiagLoc;
556
557  /// CurDiagID - This is the ID of the current diagnostic that is in flight.
558  /// This is set to ~0U when there is no diagnostic in flight.
559  unsigned CurDiagID;
560
561  enum {
562    /// MaxArguments - The maximum number of arguments we can hold. We currently
563    /// only support up to 10 arguments (%0-%9).  A single diagnostic with more
564    /// than that almost certainly has to be simplified anyway.
565    MaxArguments = 10
566  };
567
568  /// NumDiagArgs - This contains the number of entries in Arguments.
569  signed char NumDiagArgs;
570  /// NumRanges - This is the number of ranges in the DiagRanges array.
571  unsigned char NumDiagRanges;
572  /// \brief The number of code modifications hints in the
573  /// FixItHints array.
574  unsigned char NumFixItHints;
575
576  /// DiagArgumentsKind - This is an array of ArgumentKind::ArgumentKind enum
577  /// values, with one for each argument.  This specifies whether the argument
578  /// is in DiagArgumentsStr or in DiagArguments.
579  unsigned char DiagArgumentsKind[MaxArguments];
580
581  /// DiagArgumentsStr - This holds the values of each string argument for the
582  /// current diagnostic.  This value is only used when the corresponding
583  /// ArgumentKind is ak_std_string.
584  std::string DiagArgumentsStr[MaxArguments];
585
586  /// DiagArgumentsVal - The values for the various substitution positions. This
587  /// is used when the argument is not an std::string.  The specific value is
588  /// mangled into an intptr_t and the intepretation depends on exactly what
589  /// sort of argument kind it is.
590  intptr_t DiagArgumentsVal[MaxArguments];
591
592  /// DiagRanges - The list of ranges added to this diagnostic.  It currently
593  /// only support 10 ranges, could easily be extended if needed.
594  CharSourceRange DiagRanges[10];
595
596  enum { MaxFixItHints = 3 };
597
598  /// FixItHints - If valid, provides a hint with some code
599  /// to insert, remove, or modify at a particular position.
600  FixItHint FixItHints[MaxFixItHints];
601
602  /// ProcessDiag - This is the method used to report a diagnostic that is
603  /// finally fully formed.
604  ///
605  /// \returns true if the diagnostic was emitted, false if it was
606  /// suppressed.
607  bool ProcessDiag() {
608    return Diags->ProcessDiag(*this);
609  }
610
611  friend class ASTReader;
612  friend class ASTWriter;
613};
614
615/// \brief RAII class that determines when any errors have occurred
616/// between the time the instance was created and the time it was
617/// queried.
618class DiagnosticErrorTrap {
619  Diagnostic &Diag;
620  unsigned PrevErrors;
621
622public:
623  explicit DiagnosticErrorTrap(Diagnostic &Diag)
624    : Diag(Diag), PrevErrors(Diag.NumErrors) {}
625
626  /// \brief Determine whether any errors have occurred since this
627  /// object instance was created.
628  bool hasErrorOccurred() const {
629    return Diag.NumErrors > PrevErrors;
630  }
631
632  // Set to initial state of "no errors occurred".
633  void reset() { PrevErrors = Diag.NumErrors; }
634};
635
636//===----------------------------------------------------------------------===//
637// DiagnosticBuilder
638//===----------------------------------------------------------------------===//
639
640/// DiagnosticBuilder - This is a little helper class used to produce
641/// diagnostics.  This is constructed by the Diagnostic::Report method, and
642/// allows insertion of extra information (arguments and source ranges) into the
643/// currently "in flight" diagnostic.  When the temporary for the builder is
644/// destroyed, the diagnostic is issued.
645///
646/// Note that many of these will be created as temporary objects (many call
647/// sites), so we want them to be small and we never want their address taken.
648/// This ensures that compilers with somewhat reasonable optimizers will promote
649/// the common fields to registers, eliminating increments of the NumArgs field,
650/// for example.
651class DiagnosticBuilder {
652  mutable Diagnostic *DiagObj;
653  mutable unsigned NumArgs, NumRanges, NumFixItHints;
654
655  void operator=(const DiagnosticBuilder&); // DO NOT IMPLEMENT
656  friend class Diagnostic;
657  explicit DiagnosticBuilder(Diagnostic *diagObj)
658    : DiagObj(diagObj), NumArgs(0), NumRanges(0), NumFixItHints(0) {}
659
660  friend class PartialDiagnostic;
661
662protected:
663  void FlushCounts();
664
665public:
666  /// Copy constructor.  When copied, this "takes" the diagnostic info from the
667  /// input and neuters it.
668  DiagnosticBuilder(const DiagnosticBuilder &D) {
669    DiagObj = D.DiagObj;
670    D.DiagObj = 0;
671    NumArgs = D.NumArgs;
672    NumRanges = D.NumRanges;
673    NumFixItHints = D.NumFixItHints;
674  }
675
676  /// \brief Simple enumeration value used to give a name to the
677  /// suppress-diagnostic constructor.
678  enum SuppressKind { Suppress };
679
680  /// \brief Create an empty DiagnosticBuilder object that represents
681  /// no actual diagnostic.
682  explicit DiagnosticBuilder(SuppressKind)
683    : DiagObj(0), NumArgs(0), NumRanges(0), NumFixItHints(0) { }
684
685  /// \brief Force the diagnostic builder to emit the diagnostic now.
686  ///
687  /// Once this function has been called, the DiagnosticBuilder object
688  /// should not be used again before it is destroyed.
689  ///
690  /// \returns true if a diagnostic was emitted, false if the
691  /// diagnostic was suppressed.
692  bool Emit();
693
694  /// Destructor - The dtor emits the diagnostic if it hasn't already
695  /// been emitted.
696  ~DiagnosticBuilder() { Emit(); }
697
698  /// isActive - Determine whether this diagnostic is still active.
699  bool isActive() const { return DiagObj != 0; }
700
701  /// \brief Retrieve the active diagnostic ID.
702  ///
703  /// \pre \c isActive()
704  unsigned getDiagID() const {
705    assert(isActive() && "Diagnostic is inactive");
706    return DiagObj->CurDiagID;
707  }
708
709  /// \brief Clear out the current diagnostic.
710  void Clear() { DiagObj = 0; }
711
712  /// Operator bool: conversion of DiagnosticBuilder to bool always returns
713  /// true.  This allows is to be used in boolean error contexts like:
714  /// return Diag(...);
715  operator bool() const { return true; }
716
717  void AddString(llvm::StringRef S) const {
718    assert(NumArgs < Diagnostic::MaxArguments &&
719           "Too many arguments to diagnostic!");
720    if (DiagObj) {
721      DiagObj->DiagArgumentsKind[NumArgs] = Diagnostic::ak_std_string;
722      DiagObj->DiagArgumentsStr[NumArgs++] = S;
723    }
724  }
725
726  void AddTaggedVal(intptr_t V, Diagnostic::ArgumentKind Kind) const {
727    assert(NumArgs < Diagnostic::MaxArguments &&
728           "Too many arguments to diagnostic!");
729    if (DiagObj) {
730      DiagObj->DiagArgumentsKind[NumArgs] = Kind;
731      DiagObj->DiagArgumentsVal[NumArgs++] = V;
732    }
733  }
734
735  void AddSourceRange(const CharSourceRange &R) const {
736    assert(NumRanges <
737           sizeof(DiagObj->DiagRanges)/sizeof(DiagObj->DiagRanges[0]) &&
738           "Too many arguments to diagnostic!");
739    if (DiagObj)
740      DiagObj->DiagRanges[NumRanges++] = R;
741  }
742
743  void AddFixItHint(const FixItHint &Hint) const {
744    assert(NumFixItHints < Diagnostic::MaxFixItHints &&
745           "Too many fix-it hints!");
746    if (DiagObj)
747      DiagObj->FixItHints[NumFixItHints++] = Hint;
748  }
749};
750
751inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
752                                           llvm::StringRef S) {
753  DB.AddString(S);
754  return DB;
755}
756
757inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
758                                           const char *Str) {
759  DB.AddTaggedVal(reinterpret_cast<intptr_t>(Str),
760                  Diagnostic::ak_c_string);
761  return DB;
762}
763
764inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, int I) {
765  DB.AddTaggedVal(I, Diagnostic::ak_sint);
766  return DB;
767}
768
769inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,bool I) {
770  DB.AddTaggedVal(I, Diagnostic::ak_sint);
771  return DB;
772}
773
774inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
775                                           unsigned I) {
776  DB.AddTaggedVal(I, Diagnostic::ak_uint);
777  return DB;
778}
779
780inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
781                                           const IdentifierInfo *II) {
782  DB.AddTaggedVal(reinterpret_cast<intptr_t>(II),
783                  Diagnostic::ak_identifierinfo);
784  return DB;
785}
786
787// Adds a DeclContext to the diagnostic. The enable_if template magic is here
788// so that we only match those arguments that are (statically) DeclContexts;
789// other arguments that derive from DeclContext (e.g., RecordDecls) will not
790// match.
791template<typename T>
792inline
793typename llvm::enable_if<llvm::is_same<T, DeclContext>,
794                         const DiagnosticBuilder &>::type
795operator<<(const DiagnosticBuilder &DB, T *DC) {
796  DB.AddTaggedVal(reinterpret_cast<intptr_t>(DC),
797                  Diagnostic::ak_declcontext);
798  return DB;
799}
800
801inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
802                                           const SourceRange &R) {
803  DB.AddSourceRange(CharSourceRange::getTokenRange(R));
804  return DB;
805}
806
807inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
808                                           const CharSourceRange &R) {
809  DB.AddSourceRange(R);
810  return DB;
811}
812
813inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
814                                           const FixItHint &Hint) {
815  DB.AddFixItHint(Hint);
816  return DB;
817}
818
819/// Report - Issue the message to the client.  DiagID is a member of the
820/// diag::kind enum.  This actually returns a new instance of DiagnosticBuilder
821/// which emits the diagnostics (through ProcessDiag) when it is destroyed.
822inline DiagnosticBuilder Diagnostic::Report(SourceLocation Loc,
823                                            unsigned DiagID){
824  assert(CurDiagID == ~0U && "Multiple diagnostics in flight at once!");
825  CurDiagLoc = Loc;
826  CurDiagID = DiagID;
827  return DiagnosticBuilder(this);
828}
829inline DiagnosticBuilder Diagnostic::Report(unsigned DiagID) {
830  return Report(SourceLocation(), DiagID);
831}
832
833//===----------------------------------------------------------------------===//
834// DiagnosticInfo
835//===----------------------------------------------------------------------===//
836
837/// DiagnosticInfo - This is a little helper class (which is basically a smart
838/// pointer that forward info from Diagnostic) that allows clients to enquire
839/// about the currently in-flight diagnostic.
840class DiagnosticInfo {
841  const Diagnostic *DiagObj;
842public:
843  explicit DiagnosticInfo(const Diagnostic *DO) : DiagObj(DO) {}
844
845  const Diagnostic *getDiags() const { return DiagObj; }
846  unsigned getID() const { return DiagObj->CurDiagID; }
847  const SourceLocation &getLocation() const { return DiagObj->CurDiagLoc; }
848  bool hasSourceManager() const { return DiagObj->hasSourceManager(); }
849  SourceManager &getSourceManager() const { return DiagObj->getSourceManager();}
850
851  unsigned getNumArgs() const { return DiagObj->NumDiagArgs; }
852
853  /// getArgKind - Return the kind of the specified index.  Based on the kind
854  /// of argument, the accessors below can be used to get the value.
855  Diagnostic::ArgumentKind getArgKind(unsigned Idx) const {
856    assert(Idx < getNumArgs() && "Argument index out of range!");
857    return (Diagnostic::ArgumentKind)DiagObj->DiagArgumentsKind[Idx];
858  }
859
860  /// getArgStdStr - Return the provided argument string specified by Idx.
861  const std::string &getArgStdStr(unsigned Idx) const {
862    assert(getArgKind(Idx) == Diagnostic::ak_std_string &&
863           "invalid argument accessor!");
864    return DiagObj->DiagArgumentsStr[Idx];
865  }
866
867  /// getArgCStr - Return the specified C string argument.
868  const char *getArgCStr(unsigned Idx) const {
869    assert(getArgKind(Idx) == Diagnostic::ak_c_string &&
870           "invalid argument accessor!");
871    return reinterpret_cast<const char*>(DiagObj->DiagArgumentsVal[Idx]);
872  }
873
874  /// getArgSInt - Return the specified signed integer argument.
875  int getArgSInt(unsigned Idx) const {
876    assert(getArgKind(Idx) == Diagnostic::ak_sint &&
877           "invalid argument accessor!");
878    return (int)DiagObj->DiagArgumentsVal[Idx];
879  }
880
881  /// getArgUInt - Return the specified unsigned integer argument.
882  unsigned getArgUInt(unsigned Idx) const {
883    assert(getArgKind(Idx) == Diagnostic::ak_uint &&
884           "invalid argument accessor!");
885    return (unsigned)DiagObj->DiagArgumentsVal[Idx];
886  }
887
888  /// getArgIdentifier - Return the specified IdentifierInfo argument.
889  const IdentifierInfo *getArgIdentifier(unsigned Idx) const {
890    assert(getArgKind(Idx) == Diagnostic::ak_identifierinfo &&
891           "invalid argument accessor!");
892    return reinterpret_cast<IdentifierInfo*>(DiagObj->DiagArgumentsVal[Idx]);
893  }
894
895  /// getRawArg - Return the specified non-string argument in an opaque form.
896  intptr_t getRawArg(unsigned Idx) const {
897    assert(getArgKind(Idx) != Diagnostic::ak_std_string &&
898           "invalid argument accessor!");
899    return DiagObj->DiagArgumentsVal[Idx];
900  }
901
902
903  /// getNumRanges - Return the number of source ranges associated with this
904  /// diagnostic.
905  unsigned getNumRanges() const {
906    return DiagObj->NumDiagRanges;
907  }
908
909  const CharSourceRange &getRange(unsigned Idx) const {
910    assert(Idx < DiagObj->NumDiagRanges && "Invalid diagnostic range index!");
911    return DiagObj->DiagRanges[Idx];
912  }
913
914  unsigned getNumFixItHints() const {
915    return DiagObj->NumFixItHints;
916  }
917
918  const FixItHint &getFixItHint(unsigned Idx) const {
919    return DiagObj->FixItHints[Idx];
920  }
921
922  const FixItHint *getFixItHints() const {
923    return DiagObj->NumFixItHints?
924             &DiagObj->FixItHints[0] : 0;
925  }
926
927  /// FormatDiagnostic - Format this diagnostic into a string, substituting the
928  /// formal arguments into the %0 slots.  The result is appended onto the Str
929  /// array.
930  void FormatDiagnostic(llvm::SmallVectorImpl<char> &OutStr) const;
931
932  /// FormatDiagnostic - Format the given format-string into the
933  /// output buffer using the arguments stored in this diagnostic.
934  void FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
935                        llvm::SmallVectorImpl<char> &OutStr) const;
936};
937
938/**
939 * \brief Represents a diagnostic in a form that can be retained until its
940 * corresponding source manager is destroyed.
941 */
942class StoredDiagnostic {
943  unsigned ID;
944  Diagnostic::Level Level;
945  FullSourceLoc Loc;
946  std::string Message;
947  std::vector<CharSourceRange> Ranges;
948  std::vector<FixItHint> FixIts;
949
950public:
951  StoredDiagnostic();
952  StoredDiagnostic(Diagnostic::Level Level, const DiagnosticInfo &Info);
953  StoredDiagnostic(Diagnostic::Level Level, unsigned ID,
954                   llvm::StringRef Message);
955  ~StoredDiagnostic();
956
957  /// \brief Evaluates true when this object stores a diagnostic.
958  operator bool() const { return Message.size() > 0; }
959
960  unsigned getID() const { return ID; }
961  Diagnostic::Level getLevel() const { return Level; }
962  const FullSourceLoc &getLocation() const { return Loc; }
963  llvm::StringRef getMessage() const { return Message; }
964
965  void setLocation(FullSourceLoc Loc) { this->Loc = Loc; }
966
967  typedef std::vector<CharSourceRange>::const_iterator range_iterator;
968  range_iterator range_begin() const { return Ranges.begin(); }
969  range_iterator range_end() const { return Ranges.end(); }
970  unsigned range_size() const { return Ranges.size(); }
971
972  typedef std::vector<FixItHint>::const_iterator fixit_iterator;
973  fixit_iterator fixit_begin() const { return FixIts.begin(); }
974  fixit_iterator fixit_end() const { return FixIts.end(); }
975  unsigned fixit_size() const { return FixIts.size(); }
976};
977
978/// DiagnosticClient - This is an abstract interface implemented by clients of
979/// the front-end, which formats and prints fully processed diagnostics.
980class DiagnosticClient {
981protected:
982  unsigned NumWarnings;       // Number of warnings reported
983  unsigned NumErrors;         // Number of errors reported
984
985public:
986  DiagnosticClient() : NumWarnings(0), NumErrors(0) { }
987
988  unsigned getNumErrors() const { return NumErrors; }
989  unsigned getNumWarnings() const { return NumWarnings; }
990
991  virtual ~DiagnosticClient();
992
993  /// BeginSourceFile - Callback to inform the diagnostic client that processing
994  /// of a source file is beginning.
995  ///
996  /// Note that diagnostics may be emitted outside the processing of a source
997  /// file, for example during the parsing of command line options. However,
998  /// diagnostics with source range information are required to only be emitted
999  /// in between BeginSourceFile() and EndSourceFile().
1000  ///
1001  /// \arg LO - The language options for the source file being processed.
1002  /// \arg PP - The preprocessor object being used for the source; this optional
1003  /// and may not be present, for example when processing AST source files.
1004  virtual void BeginSourceFile(const LangOptions &LangOpts,
1005                               const Preprocessor *PP = 0) {}
1006
1007  /// EndSourceFile - Callback to inform the diagnostic client that processing
1008  /// of a source file has ended. The diagnostic client should assume that any
1009  /// objects made available via \see BeginSourceFile() are inaccessible.
1010  virtual void EndSourceFile() {}
1011
1012  /// IncludeInDiagnosticCounts - This method (whose default implementation
1013  /// returns true) indicates whether the diagnostics handled by this
1014  /// DiagnosticClient should be included in the number of diagnostics reported
1015  /// by Diagnostic.
1016  virtual bool IncludeInDiagnosticCounts() const;
1017
1018  /// HandleDiagnostic - Handle this diagnostic, reporting it to the user or
1019  /// capturing it to a log as needed.
1020  ///
1021  /// Default implementation just keeps track of the total number of warnings
1022  /// and errors.
1023  virtual void HandleDiagnostic(Diagnostic::Level DiagLevel,
1024                                const DiagnosticInfo &Info);
1025};
1026
1027}  // end namespace clang
1028
1029#endif
1030