Diagnostic.h revision bdbb004f38978da0c4a75af3294d1c7b5ff84af1
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
589  /// CurDiagLoc - This is the location of the current diagnostic that is in
590  /// flight.
591  FullSourceLoc CurDiagLoc;
592
593  /// CurDiagID - This is the ID of the current diagnostic that is in flight.
594  /// This is set to ~0U when there is no diagnostic in flight.
595  unsigned CurDiagID;
596
597  enum {
598    /// MaxArguments - The maximum number of arguments we can hold. We currently
599    /// only support up to 10 arguments (%0-%9).  A single diagnostic with more
600    /// than that almost certainly has to be simplified anyway.
601    MaxArguments = 10
602  };
603
604  /// NumDiagArgs - This contains the number of entries in Arguments.
605  signed char NumDiagArgs;
606  /// NumRanges - This is the number of ranges in the DiagRanges array.
607  unsigned char NumDiagRanges;
608  /// \brief The number of code modifications hints in the
609  /// FixItHints array.
610  unsigned char NumFixItHints;
611
612  /// DiagArgumentsKind - This is an array of ArgumentKind::ArgumentKind enum
613  /// values, with one for each argument.  This specifies whether the argument
614  /// is in DiagArgumentsStr or in DiagArguments.
615  unsigned char DiagArgumentsKind[MaxArguments];
616
617  /// DiagArgumentsStr - This holds the values of each string argument for the
618  /// current diagnostic.  This value is only used when the corresponding
619  /// ArgumentKind is ak_std_string.
620  std::string DiagArgumentsStr[MaxArguments];
621
622  /// DiagArgumentsVal - The values for the various substitution positions. This
623  /// is used when the argument is not an std::string.  The specific value is
624  /// mangled into an intptr_t and the intepretation depends on exactly what
625  /// sort of argument kind it is.
626  intptr_t DiagArgumentsVal[MaxArguments];
627
628  /// DiagRanges - The list of ranges added to this diagnostic.  It currently
629  /// only support 10 ranges, could easily be extended if needed.
630  CharSourceRange DiagRanges[10];
631
632  enum { MaxFixItHints = 3 };
633
634  /// FixItHints - If valid, provides a hint with some code
635  /// to insert, remove, or modify at a particular position.
636  FixItHint FixItHints[MaxFixItHints];
637
638  /// ProcessDiag - This is the method used to report a diagnostic that is
639  /// finally fully formed.
640  ///
641  /// \returns true if the diagnostic was emitted, false if it was
642  /// suppressed.
643  bool ProcessDiag();
644};
645
646//===----------------------------------------------------------------------===//
647// DiagnosticBuilder
648//===----------------------------------------------------------------------===//
649
650/// DiagnosticBuilder - This is a little helper class used to produce
651/// diagnostics.  This is constructed by the Diagnostic::Report method, and
652/// allows insertion of extra information (arguments and source ranges) into the
653/// currently "in flight" diagnostic.  When the temporary for the builder is
654/// destroyed, the diagnostic is issued.
655///
656/// Note that many of these will be created as temporary objects (many call
657/// sites), so we want them to be small and we never want their address taken.
658/// This ensures that compilers with somewhat reasonable optimizers will promote
659/// the common fields to registers, eliminating increments of the NumArgs field,
660/// for example.
661class DiagnosticBuilder {
662  mutable Diagnostic *DiagObj;
663  mutable unsigned NumArgs, NumRanges, NumFixItHints;
664
665  void operator=(const DiagnosticBuilder&); // DO NOT IMPLEMENT
666  friend class Diagnostic;
667  explicit DiagnosticBuilder(Diagnostic *diagObj)
668    : DiagObj(diagObj), NumArgs(0), NumRanges(0), NumFixItHints(0) {}
669
670public:
671  /// Copy constructor.  When copied, this "takes" the diagnostic info from the
672  /// input and neuters it.
673  DiagnosticBuilder(const DiagnosticBuilder &D) {
674    DiagObj = D.DiagObj;
675    D.DiagObj = 0;
676    NumArgs = D.NumArgs;
677    NumRanges = D.NumRanges;
678    NumFixItHints = D.NumFixItHints;
679  }
680
681  /// \brief Simple enumeration value used to give a name to the
682  /// suppress-diagnostic constructor.
683  enum SuppressKind { Suppress };
684
685  /// \brief Create an empty DiagnosticBuilder object that represents
686  /// no actual diagnostic.
687  explicit DiagnosticBuilder(SuppressKind)
688    : DiagObj(0), NumArgs(0), NumRanges(0), NumFixItHints(0) { }
689
690  /// \brief Force the diagnostic builder to emit the diagnostic now.
691  ///
692  /// Once this function has been called, the DiagnosticBuilder object
693  /// should not be used again before it is destroyed.
694  ///
695  /// \returns true if a diagnostic was emitted, false if the
696  /// diagnostic was suppressed.
697  bool Emit();
698
699  /// Destructor - The dtor emits the diagnostic if it hasn't already
700  /// been emitted.
701  ~DiagnosticBuilder() { Emit(); }
702
703  /// isActive - Determine whether this diagnostic is still active.
704  bool isActive() const { return DiagObj != 0; }
705
706  /// Operator bool: conversion of DiagnosticBuilder to bool always returns
707  /// true.  This allows is to be used in boolean error contexts like:
708  /// return Diag(...);
709  operator bool() const { return true; }
710
711  void AddString(llvm::StringRef S) const {
712    assert(NumArgs < Diagnostic::MaxArguments &&
713           "Too many arguments to diagnostic!");
714    if (DiagObj) {
715      DiagObj->DiagArgumentsKind[NumArgs] = Diagnostic::ak_std_string;
716      DiagObj->DiagArgumentsStr[NumArgs++] = S;
717    }
718  }
719
720  void AddTaggedVal(intptr_t V, Diagnostic::ArgumentKind Kind) const {
721    assert(NumArgs < Diagnostic::MaxArguments &&
722           "Too many arguments to diagnostic!");
723    if (DiagObj) {
724      DiagObj->DiagArgumentsKind[NumArgs] = Kind;
725      DiagObj->DiagArgumentsVal[NumArgs++] = V;
726    }
727  }
728
729  void AddSourceRange(const CharSourceRange &R) const {
730    assert(NumRanges <
731           sizeof(DiagObj->DiagRanges)/sizeof(DiagObj->DiagRanges[0]) &&
732           "Too many arguments to diagnostic!");
733    if (DiagObj)
734      DiagObj->DiagRanges[NumRanges++] = R;
735  }
736
737  void AddFixItHint(const FixItHint &Hint) const {
738    if (Hint.isNull())
739      return;
740
741    assert(NumFixItHints < Diagnostic::MaxFixItHints &&
742           "Too many fix-it hints!");
743    if (DiagObj)
744      DiagObj->FixItHints[NumFixItHints++] = Hint;
745  }
746};
747
748inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
749                                           llvm::StringRef S) {
750  DB.AddString(S);
751  return DB;
752}
753
754inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
755                                           const char *Str) {
756  DB.AddTaggedVal(reinterpret_cast<intptr_t>(Str),
757                  Diagnostic::ak_c_string);
758  return DB;
759}
760
761inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, int I) {
762  DB.AddTaggedVal(I, Diagnostic::ak_sint);
763  return DB;
764}
765
766inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,bool I) {
767  DB.AddTaggedVal(I, Diagnostic::ak_sint);
768  return DB;
769}
770
771inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
772                                           unsigned I) {
773  DB.AddTaggedVal(I, Diagnostic::ak_uint);
774  return DB;
775}
776
777inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
778                                           const IdentifierInfo *II) {
779  DB.AddTaggedVal(reinterpret_cast<intptr_t>(II),
780                  Diagnostic::ak_identifierinfo);
781  return DB;
782}
783
784// Adds a DeclContext to the diagnostic. The enable_if template magic is here
785// so that we only match those arguments that are (statically) DeclContexts;
786// other arguments that derive from DeclContext (e.g., RecordDecls) will not
787// match.
788template<typename T>
789inline
790typename llvm::enable_if<llvm::is_same<T, DeclContext>,
791                         const DiagnosticBuilder &>::type
792operator<<(const DiagnosticBuilder &DB, T *DC) {
793  DB.AddTaggedVal(reinterpret_cast<intptr_t>(DC),
794                  Diagnostic::ak_declcontext);
795  return DB;
796}
797
798inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
799                                           const SourceRange &R) {
800  DB.AddSourceRange(CharSourceRange::getTokenRange(R));
801  return DB;
802}
803
804inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
805                                           const CharSourceRange &R) {
806  DB.AddSourceRange(R);
807  return DB;
808}
809
810inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
811                                           const FixItHint &Hint) {
812  DB.AddFixItHint(Hint);
813  return DB;
814}
815
816/// Report - Issue the message to the client.  DiagID is a member of the
817/// diag::kind enum.  This actually returns a new instance of DiagnosticBuilder
818/// which emits the diagnostics (through ProcessDiag) when it is destroyed.
819inline DiagnosticBuilder Diagnostic::Report(FullSourceLoc Loc, unsigned DiagID){
820  assert(CurDiagID == ~0U && "Multiple diagnostics in flight at once!");
821  CurDiagLoc = Loc;
822  CurDiagID = DiagID;
823  return DiagnosticBuilder(this);
824}
825inline DiagnosticBuilder Diagnostic::Report(unsigned DiagID) {
826  return Report(FullSourceLoc(), DiagID);
827}
828
829//===----------------------------------------------------------------------===//
830// DiagnosticInfo
831//===----------------------------------------------------------------------===//
832
833/// DiagnosticInfo - This is a little helper class (which is basically a smart
834/// pointer that forward info from Diagnostic) that allows clients to enquire
835/// about the currently in-flight diagnostic.
836class DiagnosticInfo {
837  const Diagnostic *DiagObj;
838public:
839  explicit DiagnosticInfo(const Diagnostic *DO) : DiagObj(DO) {}
840
841  const Diagnostic *getDiags() const { return DiagObj; }
842  unsigned getID() const { return DiagObj->CurDiagID; }
843  const FullSourceLoc &getLocation() const { return DiagObj->CurDiagLoc; }
844
845  unsigned getNumArgs() const { return DiagObj->NumDiagArgs; }
846
847  /// getArgKind - Return the kind of the specified index.  Based on the kind
848  /// of argument, the accessors below can be used to get the value.
849  Diagnostic::ArgumentKind getArgKind(unsigned Idx) const {
850    assert(Idx < getNumArgs() && "Argument index out of range!");
851    return (Diagnostic::ArgumentKind)DiagObj->DiagArgumentsKind[Idx];
852  }
853
854  /// getArgStdStr - Return the provided argument string specified by Idx.
855  const std::string &getArgStdStr(unsigned Idx) const {
856    assert(getArgKind(Idx) == Diagnostic::ak_std_string &&
857           "invalid argument accessor!");
858    return DiagObj->DiagArgumentsStr[Idx];
859  }
860
861  /// getArgCStr - Return the specified C string argument.
862  const char *getArgCStr(unsigned Idx) const {
863    assert(getArgKind(Idx) == Diagnostic::ak_c_string &&
864           "invalid argument accessor!");
865    return reinterpret_cast<const char*>(DiagObj->DiagArgumentsVal[Idx]);
866  }
867
868  /// getArgSInt - Return the specified signed integer argument.
869  int getArgSInt(unsigned Idx) const {
870    assert(getArgKind(Idx) == Diagnostic::ak_sint &&
871           "invalid argument accessor!");
872    return (int)DiagObj->DiagArgumentsVal[Idx];
873  }
874
875  /// getArgUInt - Return the specified unsigned integer argument.
876  unsigned getArgUInt(unsigned Idx) const {
877    assert(getArgKind(Idx) == Diagnostic::ak_uint &&
878           "invalid argument accessor!");
879    return (unsigned)DiagObj->DiagArgumentsVal[Idx];
880  }
881
882  /// getArgIdentifier - Return the specified IdentifierInfo argument.
883  const IdentifierInfo *getArgIdentifier(unsigned Idx) const {
884    assert(getArgKind(Idx) == Diagnostic::ak_identifierinfo &&
885           "invalid argument accessor!");
886    return reinterpret_cast<IdentifierInfo*>(DiagObj->DiagArgumentsVal[Idx]);
887  }
888
889  /// getRawArg - Return the specified non-string argument in an opaque form.
890  intptr_t getRawArg(unsigned Idx) const {
891    assert(getArgKind(Idx) != Diagnostic::ak_std_string &&
892           "invalid argument accessor!");
893    return DiagObj->DiagArgumentsVal[Idx];
894  }
895
896
897  /// getNumRanges - Return the number of source ranges associated with this
898  /// diagnostic.
899  unsigned getNumRanges() const {
900    return DiagObj->NumDiagRanges;
901  }
902
903  const CharSourceRange &getRange(unsigned Idx) const {
904    assert(Idx < DiagObj->NumDiagRanges && "Invalid diagnostic range index!");
905    return DiagObj->DiagRanges[Idx];
906  }
907
908  unsigned getNumFixItHints() const {
909    return DiagObj->NumFixItHints;
910  }
911
912  const FixItHint &getFixItHint(unsigned Idx) const {
913    return DiagObj->FixItHints[Idx];
914  }
915
916  const FixItHint *getFixItHints() const {
917    return DiagObj->NumFixItHints?
918             &DiagObj->FixItHints[0] : 0;
919  }
920
921  /// FormatDiagnostic - Format this diagnostic into a string, substituting the
922  /// formal arguments into the %0 slots.  The result is appended onto the Str
923  /// array.
924  void FormatDiagnostic(llvm::SmallVectorImpl<char> &OutStr) const;
925
926  /// FormatDiagnostic - Format the given format-string into the
927  /// output buffer using the arguments stored in this diagnostic.
928  void FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
929                        llvm::SmallVectorImpl<char> &OutStr) const;
930};
931
932/**
933 * \brief Represents a diagnostic in a form that can be serialized and
934 * deserialized.
935 */
936class StoredDiagnostic {
937  Diagnostic::Level Level;
938  FullSourceLoc Loc;
939  std::string Message;
940  std::vector<CharSourceRange> Ranges;
941  std::vector<FixItHint> FixIts;
942
943public:
944  StoredDiagnostic();
945  StoredDiagnostic(Diagnostic::Level Level, const DiagnosticInfo &Info);
946  StoredDiagnostic(Diagnostic::Level Level, llvm::StringRef Message);
947  ~StoredDiagnostic();
948
949  /// \brief Evaluates true when this object stores a diagnostic.
950  operator bool() const { return Message.size() > 0; }
951
952  Diagnostic::Level getLevel() const { return Level; }
953  const FullSourceLoc &getLocation() const { return Loc; }
954  llvm::StringRef getMessage() const { return Message; }
955
956  void setLocation(FullSourceLoc Loc) { this->Loc = Loc; }
957
958  typedef std::vector<CharSourceRange>::const_iterator range_iterator;
959  range_iterator range_begin() const { return Ranges.begin(); }
960  range_iterator range_end() const { return Ranges.end(); }
961  unsigned range_size() const { return Ranges.size(); }
962
963  typedef std::vector<FixItHint>::const_iterator fixit_iterator;
964  fixit_iterator fixit_begin() const { return FixIts.begin(); }
965  fixit_iterator fixit_end() const { return FixIts.end(); }
966  unsigned fixit_size() const { return FixIts.size(); }
967
968  /// Serialize - Serialize the given diagnostic (with its diagnostic
969  /// level) to the given stream. Serialization is a lossy operation,
970  /// since the specific diagnostic ID and any macro-instantiation
971  /// information is lost.
972  void Serialize(llvm::raw_ostream &OS) const;
973
974  /// Deserialize - Deserialize the first diagnostic within the memory
975  /// [Memory, MemoryEnd), producing a new diagnostic builder describing the
976  /// deserialized diagnostic. If the memory does not contain a
977  /// diagnostic, returns a diagnostic builder with no diagnostic ID.
978  static StoredDiagnostic Deserialize(FileManager &FM, SourceManager &SM,
979                                   const char *&Memory, const char *MemoryEnd);
980};
981
982/// DiagnosticClient - This is an abstract interface implemented by clients of
983/// the front-end, which formats and prints fully processed diagnostics.
984class DiagnosticClient {
985public:
986  virtual ~DiagnosticClient();
987
988  /// BeginSourceFile - Callback to inform the diagnostic client that processing
989  /// of a source file is beginning.
990  ///
991  /// Note that diagnostics may be emitted outside the processing of a source
992  /// file, for example during the parsing of command line options. However,
993  /// diagnostics with source range information are required to only be emitted
994  /// in between BeginSourceFile() and EndSourceFile().
995  ///
996  /// \arg LO - The language options for the source file being processed.
997  /// \arg PP - The preprocessor object being used for the source; this optional
998  /// and may not be present, for example when processing AST source files.
999  virtual void BeginSourceFile(const LangOptions &LangOpts,
1000                               const Preprocessor *PP = 0) {}
1001
1002  /// EndSourceFile - Callback to inform the diagnostic client that processing
1003  /// of a source file has ended. The diagnostic client should assume that any
1004  /// objects made available via \see BeginSourceFile() are inaccessible.
1005  virtual void EndSourceFile() {}
1006
1007  /// IncludeInDiagnosticCounts - This method (whose default implementation
1008  /// returns true) indicates whether the diagnostics handled by this
1009  /// DiagnosticClient should be included in the number of diagnostics reported
1010  /// by Diagnostic.
1011  virtual bool IncludeInDiagnosticCounts() const;
1012
1013  /// HandleDiagnostic - Handle this diagnostic, reporting it to the user or
1014  /// capturing it to a log as needed.
1015  virtual void HandleDiagnostic(Diagnostic::Level DiagLevel,
1016                                const DiagnosticInfo &Info) = 0;
1017};
1018
1019}  // end namespace clang
1020
1021#endif
1022