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