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