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