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