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