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