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