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