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