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