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/// \file
11/// \brief Defines the Diagnostic-related interfaces.
12///
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_CLANG_BASIC_DIAGNOSTIC_H
16#define LLVM_CLANG_BASIC_DIAGNOSTIC_H
17
18#include "clang/Basic/DiagnosticIDs.h"
19#include "clang/Basic/DiagnosticOptions.h"
20#include "clang/Basic/SourceLocation.h"
21#include "clang/Basic/Specifiers.h"
22#include "llvm/ADT/ArrayRef.h"
23#include "llvm/ADT/DenseMap.h"
24#include "llvm/ADT/IntrusiveRefCntPtr.h"
25#include "llvm/ADT/iterator_range.h"
26#include "llvm/ADT/SmallVector.h"
27#include "llvm/ADT/StringRef.h"
28#include <algorithm>
29#include <cassert>
30#include <cstdint>
31#include <list>
32#include <map>
33#include <memory>
34#include <string>
35#include <type_traits>
36#include <utility>
37#include <vector>
38
39namespace clang {
40
41class DeclContext;
42class DiagnosticBuilder;
43class DiagnosticConsumer;
44class IdentifierInfo;
45class LangOptions;
46class Preprocessor;
47class StoredDiagnostic;
48
49namespace tok {
50
51  enum TokenKind : unsigned short;
52
53} // end namespace tok
54
55/// \brief Annotates a diagnostic with some code that should be
56/// inserted, removed, or replaced to fix the problem.
57///
58/// This kind of hint should be used when we are certain that the
59/// introduction, removal, or modification of a particular (small!)
60/// amount of code will correct a compilation error. The compiler
61/// should also provide full recovery from such errors, such that
62/// suppressing the diagnostic output can still result in successful
63/// compilation.
64class FixItHint {
65public:
66  /// \brief Code that should be replaced to correct the error. Empty for an
67  /// insertion hint.
68  CharSourceRange RemoveRange;
69
70  /// \brief Code in the specific range that should be inserted in the insertion
71  /// location.
72  CharSourceRange InsertFromRange;
73
74  /// \brief The actual code to insert at the insertion location, as a
75  /// string.
76  std::string CodeToInsert;
77
78  bool BeforePreviousInsertions;
79
80  /// \brief Empty code modification hint, indicating that no code
81  /// modification is known.
82  FixItHint() : BeforePreviousInsertions(false) { }
83
84  bool isNull() const {
85    return !RemoveRange.isValid();
86  }
87
88  /// \brief Create a code modification hint that inserts the given
89  /// code string at a specific location.
90  static FixItHint CreateInsertion(SourceLocation InsertionLoc,
91                                   StringRef Code,
92                                   bool BeforePreviousInsertions = false) {
93    FixItHint Hint;
94    Hint.RemoveRange =
95      CharSourceRange::getCharRange(InsertionLoc, InsertionLoc);
96    Hint.CodeToInsert = Code;
97    Hint.BeforePreviousInsertions = BeforePreviousInsertions;
98    return Hint;
99  }
100
101  /// \brief Create a code modification hint that inserts the given
102  /// code from \p FromRange at a specific location.
103  static FixItHint CreateInsertionFromRange(SourceLocation InsertionLoc,
104                                            CharSourceRange FromRange,
105                                        bool BeforePreviousInsertions = false) {
106    FixItHint Hint;
107    Hint.RemoveRange =
108      CharSourceRange::getCharRange(InsertionLoc, InsertionLoc);
109    Hint.InsertFromRange = FromRange;
110    Hint.BeforePreviousInsertions = BeforePreviousInsertions;
111    return Hint;
112  }
113
114  /// \brief Create a code modification hint that removes the given
115  /// source range.
116  static FixItHint CreateRemoval(CharSourceRange RemoveRange) {
117    FixItHint Hint;
118    Hint.RemoveRange = RemoveRange;
119    return Hint;
120  }
121  static FixItHint CreateRemoval(SourceRange RemoveRange) {
122    return CreateRemoval(CharSourceRange::getTokenRange(RemoveRange));
123  }
124
125  /// \brief Create a code modification hint that replaces the given
126  /// source range with the given code string.
127  static FixItHint CreateReplacement(CharSourceRange RemoveRange,
128                                     StringRef Code) {
129    FixItHint Hint;
130    Hint.RemoveRange = RemoveRange;
131    Hint.CodeToInsert = Code;
132    return Hint;
133  }
134
135  static FixItHint CreateReplacement(SourceRange RemoveRange,
136                                     StringRef Code) {
137    return CreateReplacement(CharSourceRange::getTokenRange(RemoveRange), Code);
138  }
139};
140
141/// \brief Concrete class used by the front-end to report problems and issues.
142///
143/// This massages the diagnostics (e.g. handling things like "report warnings
144/// as errors" and passes them off to the DiagnosticConsumer for reporting to
145/// the user. DiagnosticsEngine is tied to one translation unit and one
146/// SourceManager.
147class DiagnosticsEngine : public RefCountedBase<DiagnosticsEngine> {
148public:
149  /// \brief The level of the diagnostic, after it has been through mapping.
150  enum Level {
151    Ignored = DiagnosticIDs::Ignored,
152    Note = DiagnosticIDs::Note,
153    Remark = DiagnosticIDs::Remark,
154    Warning = DiagnosticIDs::Warning,
155    Error = DiagnosticIDs::Error,
156    Fatal = DiagnosticIDs::Fatal
157  };
158
159  enum ArgumentKind {
160    ak_std_string,      ///< std::string
161    ak_c_string,        ///< const char *
162    ak_sint,            ///< int
163    ak_uint,            ///< unsigned
164    ak_tokenkind,       ///< enum TokenKind : 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    ak_qualtype_pair,   ///< pair<QualType, QualType>
172    ak_attr             ///< Attr *
173  };
174
175  /// \brief Represents on argument value, which is a union discriminated
176  /// by ArgumentKind, with a value.
177  typedef std::pair<ArgumentKind, intptr_t> ArgumentValue;
178
179private:
180  unsigned char AllExtensionsSilenced; // Used by __extension__
181  bool SuppressAfterFatalError;  // Suppress diagnostics after a fatal error?
182  bool SuppressAllDiagnostics;   // Suppress all diagnostics.
183  bool ElideType;                // Elide common types of templates.
184  bool PrintTemplateTree;        // Print a tree when comparing templates.
185  bool ShowColors;               // Color printing is enabled.
186  OverloadsShown ShowOverloads;  // Which overload candidates to show.
187  unsigned ErrorLimit;           // Cap of # errors emitted, 0 -> no limit.
188  unsigned TemplateBacktraceLimit; // Cap on depth of template backtrace stack,
189                                   // 0 -> no limit.
190  unsigned ConstexprBacktraceLimit; // Cap on depth of constexpr evaluation
191                                    // backtrace stack, 0 -> no limit.
192  IntrusiveRefCntPtr<DiagnosticIDs> Diags;
193  IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts;
194  DiagnosticConsumer *Client;
195  std::unique_ptr<DiagnosticConsumer> Owner;
196  SourceManager *SourceMgr;
197
198  /// \brief Mapping information for diagnostics.
199  ///
200  /// Mapping info is packed into four bits per diagnostic.  The low three
201  /// bits are the mapping (an instance of diag::Severity), or zero if unset.
202  /// The high bit is set when the mapping was established as a user mapping.
203  /// If the high bit is clear, then the low bits are set to the default
204  /// value, and should be mapped with -pedantic, -Werror, etc.
205  ///
206  /// A new DiagState is created and kept around when diagnostic pragmas modify
207  /// the state so that we know what is the diagnostic state at any given
208  /// source location.
209  class DiagState {
210    llvm::DenseMap<unsigned, DiagnosticMapping> DiagMap;
211
212  public:
213    // "Global" configuration state that can actually vary between modules.
214    unsigned IgnoreAllWarnings : 1;      // Ignore all warnings: -w
215    unsigned EnableAllWarnings : 1;      // Enable all warnings.
216    unsigned WarningsAsErrors : 1;       // Treat warnings like errors.
217    unsigned ErrorsAsFatal : 1;          // Treat errors like fatal errors.
218    unsigned SuppressSystemWarnings : 1; // Suppress warnings in system headers.
219    diag::Severity ExtBehavior;         // Map extensions to warnings or errors?
220
221    DiagState()
222        : IgnoreAllWarnings(false), EnableAllWarnings(false),
223          WarningsAsErrors(false), ErrorsAsFatal(false),
224          SuppressSystemWarnings(false), ExtBehavior(diag::Severity::Ignored) {}
225
226    typedef llvm::DenseMap<unsigned, DiagnosticMapping>::iterator iterator;
227    typedef llvm::DenseMap<unsigned, DiagnosticMapping>::const_iterator
228    const_iterator;
229
230    void setMapping(diag::kind Diag, DiagnosticMapping Info) {
231      DiagMap[Diag] = Info;
232    }
233    DiagnosticMapping lookupMapping(diag::kind Diag) const {
234      return DiagMap.lookup(Diag);
235    }
236
237    DiagnosticMapping &getOrAddMapping(diag::kind Diag);
238
239    const_iterator begin() const { return DiagMap.begin(); }
240    const_iterator end() const { return DiagMap.end(); }
241  };
242
243  /// \brief Keeps and automatically disposes all DiagStates that we create.
244  std::list<DiagState> DiagStates;
245
246  /// A mapping from files to the diagnostic states for those files. Lazily
247  /// built on demand for files in which the diagnostic state has not changed.
248  class DiagStateMap {
249  public:
250    /// Add an initial diagnostic state.
251    void appendFirst(DiagState *State);
252    /// Add a new latest state point.
253    void append(SourceManager &SrcMgr, SourceLocation Loc, DiagState *State);
254    /// Look up the diagnostic state at a given source location.
255    DiagState *lookup(SourceManager &SrcMgr, SourceLocation Loc) const;
256    /// Determine whether this map is empty.
257    bool empty() const { return Files.empty(); }
258    /// Clear out this map.
259    void clear() {
260      Files.clear();
261      FirstDiagState = CurDiagState = nullptr;
262      CurDiagStateLoc = SourceLocation();
263    }
264
265    /// Grab the most-recently-added state point.
266    DiagState *getCurDiagState() const { return CurDiagState; }
267    /// Get the location at which a diagnostic state was last added.
268    SourceLocation getCurDiagStateLoc() const { return CurDiagStateLoc; }
269
270  private:
271    /// \brief Represents a point in source where the diagnostic state was
272    /// modified because of a pragma.
273    ///
274    /// 'Loc' can be null if the point represents the diagnostic state
275    /// modifications done through the command-line.
276    struct DiagStatePoint {
277      DiagState *State;
278      unsigned Offset;
279      DiagStatePoint(DiagState *State, unsigned Offset)
280        : State(State), Offset(Offset) { }
281    };
282
283    /// Description of the diagnostic states and state transitions for a
284    /// particular FileID.
285    struct File {
286      /// The diagnostic state for the parent file. This is strictly redundant,
287      /// as looking up the DecomposedIncludedLoc for the FileID in the Files
288      /// map would give us this, but we cache it here for performance.
289      File *Parent = nullptr;
290      /// The offset of this file within its parent.
291      unsigned ParentOffset = 0;
292      /// Whether this file has any local (not imported from an AST file)
293      /// diagnostic state transitions.
294      bool HasLocalTransitions = false;
295      /// The points within the file where the state changes. There will always
296      /// be at least one of these (the state on entry to the file).
297      llvm::SmallVector<DiagStatePoint, 4> StateTransitions;
298
299      DiagState *lookup(unsigned Offset) const;
300    };
301
302    /// The diagnostic states for each file.
303    mutable std::map<FileID, File> Files;
304
305    /// The initial diagnostic state.
306    DiagState *FirstDiagState;
307    /// The current diagnostic state.
308    DiagState *CurDiagState;
309    /// The location at which the current diagnostic state was established.
310    SourceLocation CurDiagStateLoc;
311
312    /// Get the diagnostic state information for a file.
313    File *getFile(SourceManager &SrcMgr, FileID ID) const;
314
315    friend class ASTReader;
316    friend class ASTWriter;
317  };
318
319  DiagStateMap DiagStatesByLoc;
320
321  /// \brief Keeps the DiagState that was active during each diagnostic 'push'
322  /// so we can get back at it when we 'pop'.
323  std::vector<DiagState *> DiagStateOnPushStack;
324
325  DiagState *GetCurDiagState() const {
326    return DiagStatesByLoc.getCurDiagState();
327  }
328
329  void PushDiagStatePoint(DiagState *State, SourceLocation L);
330
331  /// \brief Finds the DiagStatePoint that contains the diagnostic state of
332  /// the given source location.
333  DiagState *GetDiagStateForLoc(SourceLocation Loc) const {
334    return SourceMgr ? DiagStatesByLoc.lookup(*SourceMgr, Loc)
335                     : DiagStatesByLoc.getCurDiagState();
336  }
337
338  /// \brief Sticky flag set to \c true when an error is emitted.
339  bool ErrorOccurred;
340
341  /// \brief Sticky flag set to \c true when an "uncompilable error" occurs.
342  /// I.e. an error that was not upgraded from a warning by -Werror.
343  bool UncompilableErrorOccurred;
344
345  /// \brief Sticky flag set to \c true when a fatal error is emitted.
346  bool FatalErrorOccurred;
347
348  /// \brief Indicates that an unrecoverable error has occurred.
349  bool UnrecoverableErrorOccurred;
350
351  /// \brief Counts for DiagnosticErrorTrap to check whether an error occurred
352  /// during a parsing section, e.g. during parsing a function.
353  unsigned TrapNumErrorsOccurred;
354  unsigned TrapNumUnrecoverableErrorsOccurred;
355
356  /// \brief The level of the last diagnostic emitted.
357  ///
358  /// This is used to emit continuation diagnostics with the same level as the
359  /// diagnostic that they follow.
360  DiagnosticIDs::Level LastDiagLevel;
361
362  unsigned NumWarnings;         ///< Number of warnings reported
363  unsigned NumErrors;           ///< Number of errors reported
364
365  /// \brief A function pointer that converts an opaque diagnostic
366  /// argument to a strings.
367  ///
368  /// This takes the modifiers and argument that was present in the diagnostic.
369  ///
370  /// The PrevArgs array indicates the previous arguments formatted for this
371  /// diagnostic.  Implementations of this function can use this information to
372  /// avoid redundancy across arguments.
373  ///
374  /// This is a hack to avoid a layering violation between libbasic and libsema.
375  typedef void (*ArgToStringFnTy)(
376      ArgumentKind Kind, intptr_t Val,
377      StringRef Modifier, StringRef Argument,
378      ArrayRef<ArgumentValue> PrevArgs,
379      SmallVectorImpl<char> &Output,
380      void *Cookie,
381      ArrayRef<intptr_t> QualTypeVals);
382  void *ArgToStringCookie;
383  ArgToStringFnTy ArgToStringFn;
384
385  /// \brief ID of the "delayed" diagnostic, which is a (typically
386  /// fatal) diagnostic that had to be delayed because it was found
387  /// while emitting another diagnostic.
388  unsigned DelayedDiagID;
389
390  /// \brief First string argument for the delayed diagnostic.
391  std::string DelayedDiagArg1;
392
393  /// \brief Second string argument for the delayed diagnostic.
394  std::string DelayedDiagArg2;
395
396  /// \brief Optional flag value.
397  ///
398  /// Some flags accept values, for instance: -Wframe-larger-than=<value> and
399  /// -Rpass=<value>. The content of this string is emitted after the flag name
400  /// and '='.
401  std::string FlagValue;
402
403public:
404  explicit DiagnosticsEngine(IntrusiveRefCntPtr<DiagnosticIDs> Diags,
405                             DiagnosticOptions *DiagOpts,
406                             DiagnosticConsumer *client = nullptr,
407                             bool ShouldOwnClient = true);
408  DiagnosticsEngine(const DiagnosticsEngine &) = delete;
409  DiagnosticsEngine &operator=(const DiagnosticsEngine &) = delete;
410  ~DiagnosticsEngine();
411
412  const IntrusiveRefCntPtr<DiagnosticIDs> &getDiagnosticIDs() const {
413    return Diags;
414  }
415
416  /// \brief Retrieve the diagnostic options.
417  DiagnosticOptions &getDiagnosticOptions() const { return *DiagOpts; }
418
419  typedef llvm::iterator_range<DiagState::const_iterator> diag_mapping_range;
420
421  /// \brief Get the current set of diagnostic mappings.
422  diag_mapping_range getDiagnosticMappings() const {
423    const DiagState &DS = *GetCurDiagState();
424    return diag_mapping_range(DS.begin(), DS.end());
425  }
426
427  DiagnosticConsumer *getClient() { return Client; }
428  const DiagnosticConsumer *getClient() const { return Client; }
429
430  /// \brief Determine whether this \c DiagnosticsEngine object own its client.
431  bool ownsClient() const { return Owner != nullptr; }
432
433  /// \brief Return the current diagnostic client along with ownership of that
434  /// client.
435  std::unique_ptr<DiagnosticConsumer> takeClient() { return std::move(Owner); }
436
437  bool hasSourceManager() const { return SourceMgr != nullptr; }
438  SourceManager &getSourceManager() const {
439    assert(SourceMgr && "SourceManager not set!");
440    return *SourceMgr;
441  }
442  void setSourceManager(SourceManager *SrcMgr) {
443    assert(DiagStatesByLoc.empty() &&
444           "Leftover diag state from a different SourceManager.");
445    SourceMgr = SrcMgr;
446  }
447
448  //===--------------------------------------------------------------------===//
449  //  DiagnosticsEngine characterization methods, used by a client to customize
450  //  how diagnostics are emitted.
451  //
452
453  /// \brief Copies the current DiagMappings and pushes the new copy
454  /// onto the top of the stack.
455  void pushMappings(SourceLocation Loc);
456
457  /// \brief Pops the current DiagMappings off the top of the stack,
458  /// causing the new top of the stack to be the active mappings.
459  ///
460  /// \returns \c true if the pop happens, \c false if there is only one
461  /// DiagMapping on the stack.
462  bool popMappings(SourceLocation Loc);
463
464  /// \brief Set the diagnostic client associated with this diagnostic object.
465  ///
466  /// \param ShouldOwnClient true if the diagnostic object should take
467  /// ownership of \c client.
468  void setClient(DiagnosticConsumer *client, bool ShouldOwnClient = true);
469
470  /// \brief Specify a limit for the number of errors we should
471  /// emit before giving up.
472  ///
473  /// Zero disables the limit.
474  void setErrorLimit(unsigned Limit) { ErrorLimit = Limit; }
475
476  /// \brief Specify the maximum number of template instantiation
477  /// notes to emit along with a given diagnostic.
478  void setTemplateBacktraceLimit(unsigned Limit) {
479    TemplateBacktraceLimit = Limit;
480  }
481
482  /// \brief Retrieve the maximum number of template instantiation
483  /// notes to emit along with a given diagnostic.
484  unsigned getTemplateBacktraceLimit() const {
485    return TemplateBacktraceLimit;
486  }
487
488  /// \brief Specify the maximum number of constexpr evaluation
489  /// notes to emit along with a given diagnostic.
490  void setConstexprBacktraceLimit(unsigned Limit) {
491    ConstexprBacktraceLimit = Limit;
492  }
493
494  /// \brief Retrieve the maximum number of constexpr evaluation
495  /// notes to emit along with a given diagnostic.
496  unsigned getConstexprBacktraceLimit() const {
497    return ConstexprBacktraceLimit;
498  }
499
500  /// \brief When set to true, any unmapped warnings are ignored.
501  ///
502  /// If this and WarningsAsErrors are both set, then this one wins.
503  void setIgnoreAllWarnings(bool Val) {
504    GetCurDiagState()->IgnoreAllWarnings = Val;
505  }
506  bool getIgnoreAllWarnings() const {
507    return GetCurDiagState()->IgnoreAllWarnings;
508  }
509
510  /// \brief When set to true, any unmapped ignored warnings are no longer
511  /// ignored.
512  ///
513  /// If this and IgnoreAllWarnings are both set, then that one wins.
514  void setEnableAllWarnings(bool Val) {
515    GetCurDiagState()->EnableAllWarnings = Val;
516  }
517  bool getEnableAllWarnings() const {
518    return GetCurDiagState()->EnableAllWarnings;
519  }
520
521  /// \brief When set to true, any warnings reported are issued as errors.
522  void setWarningsAsErrors(bool Val) {
523    GetCurDiagState()->WarningsAsErrors = Val;
524  }
525  bool getWarningsAsErrors() const {
526    return GetCurDiagState()->WarningsAsErrors;
527  }
528
529  /// \brief When set to true, any error reported is made a fatal error.
530  void setErrorsAsFatal(bool Val) { GetCurDiagState()->ErrorsAsFatal = Val; }
531  bool getErrorsAsFatal() const { return GetCurDiagState()->ErrorsAsFatal; }
532
533  /// \brief When set to true (the default), suppress further diagnostics after
534  /// a fatal error.
535  void setSuppressAfterFatalError(bool Val) { SuppressAfterFatalError = Val; }
536
537  /// \brief When set to true mask warnings that come from system headers.
538  void setSuppressSystemWarnings(bool Val) {
539    GetCurDiagState()->SuppressSystemWarnings = Val;
540  }
541  bool getSuppressSystemWarnings() const {
542    return GetCurDiagState()->SuppressSystemWarnings;
543  }
544
545  /// \brief Suppress all diagnostics, to silence the front end when we
546  /// know that we don't want any more diagnostics to be passed along to the
547  /// client
548  void setSuppressAllDiagnostics(bool Val = true) {
549    SuppressAllDiagnostics = Val;
550  }
551  bool getSuppressAllDiagnostics() const { return SuppressAllDiagnostics; }
552
553  /// \brief Set type eliding, to skip outputting same types occurring in
554  /// template types.
555  void setElideType(bool Val = true) { ElideType = Val; }
556  bool getElideType() { return ElideType; }
557
558  /// \brief Set tree printing, to outputting the template difference in a
559  /// tree format.
560  void setPrintTemplateTree(bool Val = false) { PrintTemplateTree = Val; }
561  bool getPrintTemplateTree() { return PrintTemplateTree; }
562
563  /// \brief Set color printing, so the type diffing will inject color markers
564  /// into the output.
565  void setShowColors(bool Val = false) { ShowColors = Val; }
566  bool getShowColors() { return ShowColors; }
567
568  /// \brief Specify which overload candidates to show when overload resolution
569  /// fails.
570  ///
571  /// By default, we show all candidates.
572  void setShowOverloads(OverloadsShown Val) {
573    ShowOverloads = Val;
574  }
575  OverloadsShown getShowOverloads() const { return ShowOverloads; }
576
577  /// \brief Pretend that the last diagnostic issued was ignored, so any
578  /// subsequent notes will be suppressed.
579  ///
580  /// This can be used by clients who suppress diagnostics themselves.
581  void setLastDiagnosticIgnored() {
582    if (LastDiagLevel == DiagnosticIDs::Fatal)
583      FatalErrorOccurred = true;
584    LastDiagLevel = DiagnosticIDs::Ignored;
585  }
586
587  /// \brief Determine whether the previous diagnostic was ignored. This can
588  /// be used by clients that want to determine whether notes attached to a
589  /// diagnostic will be suppressed.
590  bool isLastDiagnosticIgnored() const {
591    return LastDiagLevel == DiagnosticIDs::Ignored;
592  }
593
594  /// \brief Controls whether otherwise-unmapped extension diagnostics are
595  /// mapped onto ignore/warning/error.
596  ///
597  /// This corresponds to the GCC -pedantic and -pedantic-errors option.
598  void setExtensionHandlingBehavior(diag::Severity H) {
599    GetCurDiagState()->ExtBehavior = H;
600  }
601  diag::Severity getExtensionHandlingBehavior() const {
602    return GetCurDiagState()->ExtBehavior;
603  }
604
605  /// \brief Counter bumped when an __extension__  block is/ encountered.
606  ///
607  /// When non-zero, all extension diagnostics are entirely silenced, no
608  /// matter how they are mapped.
609  void IncrementAllExtensionsSilenced() { ++AllExtensionsSilenced; }
610  void DecrementAllExtensionsSilenced() { --AllExtensionsSilenced; }
611  bool hasAllExtensionsSilenced() { return AllExtensionsSilenced != 0; }
612
613  /// \brief This allows the client to specify that certain warnings are
614  /// ignored.
615  ///
616  /// Notes can never be mapped, errors can only be mapped to fatal, and
617  /// WARNINGs and EXTENSIONs can be mapped arbitrarily.
618  ///
619  /// \param Loc The source location that this change of diagnostic state should
620  /// take affect. It can be null if we are setting the latest state.
621  void setSeverity(diag::kind Diag, diag::Severity Map, SourceLocation Loc);
622
623  /// \brief Change an entire diagnostic group (e.g. "unknown-pragmas") to
624  /// have the specified mapping.
625  ///
626  /// \returns true (and ignores the request) if "Group" was unknown, false
627  /// otherwise.
628  ///
629  /// \param Flavor The flavor of group to affect. -Rfoo does not affect the
630  /// state of the -Wfoo group and vice versa.
631  ///
632  /// \param Loc The source location that this change of diagnostic state should
633  /// take affect. It can be null if we are setting the state from command-line.
634  bool setSeverityForGroup(diag::Flavor Flavor, StringRef Group,
635                           diag::Severity Map,
636                           SourceLocation Loc = SourceLocation());
637
638  /// \brief Set the warning-as-error flag for the given diagnostic group.
639  ///
640  /// This function always only operates on the current diagnostic state.
641  ///
642  /// \returns True if the given group is unknown, false otherwise.
643  bool setDiagnosticGroupWarningAsError(StringRef Group, bool Enabled);
644
645  /// \brief Set the error-as-fatal flag for the given diagnostic group.
646  ///
647  /// This function always only operates on the current diagnostic state.
648  ///
649  /// \returns True if the given group is unknown, false otherwise.
650  bool setDiagnosticGroupErrorAsFatal(StringRef Group, bool Enabled);
651
652  /// \brief Add the specified mapping to all diagnostics of the specified
653  /// flavor.
654  ///
655  /// Mainly to be used by -Wno-everything to disable all warnings but allow
656  /// subsequent -W options to enable specific warnings.
657  void setSeverityForAll(diag::Flavor Flavor, diag::Severity Map,
658                         SourceLocation Loc = SourceLocation());
659
660  bool hasErrorOccurred() const { return ErrorOccurred; }
661
662  /// \brief Errors that actually prevent compilation, not those that are
663  /// upgraded from a warning by -Werror.
664  bool hasUncompilableErrorOccurred() const {
665    return UncompilableErrorOccurred;
666  }
667  bool hasFatalErrorOccurred() const { return FatalErrorOccurred; }
668
669  /// \brief Determine whether any kind of unrecoverable error has occurred.
670  bool hasUnrecoverableErrorOccurred() const {
671    return FatalErrorOccurred || UnrecoverableErrorOccurred;
672  }
673
674  unsigned getNumWarnings() const { return NumWarnings; }
675
676  void setNumWarnings(unsigned NumWarnings) {
677    this->NumWarnings = NumWarnings;
678  }
679
680  /// \brief Return an ID for a diagnostic with the specified format string and
681  /// level.
682  ///
683  /// If this is the first request for this diagnostic, it is registered and
684  /// created, otherwise the existing ID is returned.
685  ///
686  /// \param FormatString A fixed diagnostic format string that will be hashed
687  /// and mapped to a unique DiagID.
688  template <unsigned N>
689  unsigned getCustomDiagID(Level L, const char (&FormatString)[N]) {
690    return Diags->getCustomDiagID((DiagnosticIDs::Level)L,
691                                  StringRef(FormatString, N - 1));
692  }
693
694  /// \brief Converts a diagnostic argument (as an intptr_t) into the string
695  /// that represents it.
696  void ConvertArgToString(ArgumentKind Kind, intptr_t Val,
697                          StringRef Modifier, StringRef Argument,
698                          ArrayRef<ArgumentValue> PrevArgs,
699                          SmallVectorImpl<char> &Output,
700                          ArrayRef<intptr_t> QualTypeVals) const {
701    ArgToStringFn(Kind, Val, Modifier, Argument, PrevArgs, Output,
702                  ArgToStringCookie, QualTypeVals);
703  }
704
705  void SetArgToStringFn(ArgToStringFnTy Fn, void *Cookie) {
706    ArgToStringFn = Fn;
707    ArgToStringCookie = Cookie;
708  }
709
710  /// \brief Note that the prior diagnostic was emitted by some other
711  /// \c DiagnosticsEngine, and we may be attaching a note to that diagnostic.
712  void notePriorDiagnosticFrom(const DiagnosticsEngine &Other) {
713    LastDiagLevel = Other.LastDiagLevel;
714  }
715
716  /// \brief Reset the state of the diagnostic object to its initial
717  /// configuration.
718  void Reset();
719
720  //===--------------------------------------------------------------------===//
721  // DiagnosticsEngine classification and reporting interfaces.
722  //
723
724  /// \brief Determine whether the diagnostic is known to be ignored.
725  ///
726  /// This can be used to opportunistically avoid expensive checks when it's
727  /// known for certain that the diagnostic has been suppressed at the
728  /// specified location \p Loc.
729  ///
730  /// \param Loc The source location we are interested in finding out the
731  /// diagnostic state. Can be null in order to query the latest state.
732  bool isIgnored(unsigned DiagID, SourceLocation Loc) const {
733    return Diags->getDiagnosticSeverity(DiagID, Loc, *this) ==
734           diag::Severity::Ignored;
735  }
736
737  /// \brief Based on the way the client configured the DiagnosticsEngine
738  /// object, classify the specified diagnostic ID into a Level, consumable by
739  /// the DiagnosticConsumer.
740  ///
741  /// To preserve invariant assumptions, this function should not be used to
742  /// influence parse or semantic analysis actions. Instead consider using
743  /// \c isIgnored().
744  ///
745  /// \param Loc The source location we are interested in finding out the
746  /// diagnostic state. Can be null in order to query the latest state.
747  Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc) const {
748    return (Level)Diags->getDiagnosticLevel(DiagID, Loc, *this);
749  }
750
751  /// \brief Issue the message to the client.
752  ///
753  /// This actually returns an instance of DiagnosticBuilder which emits the
754  /// diagnostics (through @c ProcessDiag) when it is destroyed.
755  ///
756  /// \param DiagID A member of the @c diag::kind enum.
757  /// \param Loc Represents the source location associated with the diagnostic,
758  /// which can be an invalid location if no position information is available.
759  inline DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID);
760  inline DiagnosticBuilder Report(unsigned DiagID);
761
762  void Report(const StoredDiagnostic &storedDiag);
763
764  /// \brief Determine whethere there is already a diagnostic in flight.
765  bool isDiagnosticInFlight() const { return CurDiagID != ~0U; }
766
767  /// \brief Set the "delayed" diagnostic that will be emitted once
768  /// the current diagnostic completes.
769  ///
770  ///  If a diagnostic is already in-flight but the front end must
771  ///  report a problem (e.g., with an inconsistent file system
772  ///  state), this routine sets a "delayed" diagnostic that will be
773  ///  emitted after the current diagnostic completes. This should
774  ///  only be used for fatal errors detected at inconvenient
775  ///  times. If emitting a delayed diagnostic causes a second delayed
776  ///  diagnostic to be introduced, that second delayed diagnostic
777  ///  will be ignored.
778  ///
779  /// \param DiagID The ID of the diagnostic being delayed.
780  ///
781  /// \param Arg1 A string argument that will be provided to the
782  /// diagnostic. A copy of this string will be stored in the
783  /// DiagnosticsEngine object itself.
784  ///
785  /// \param Arg2 A string argument that will be provided to the
786  /// diagnostic. A copy of this string will be stored in the
787  /// DiagnosticsEngine object itself.
788  void SetDelayedDiagnostic(unsigned DiagID, StringRef Arg1 = "",
789                            StringRef Arg2 = "");
790
791  /// \brief Clear out the current diagnostic.
792  void Clear() { CurDiagID = ~0U; }
793
794  /// \brief Return the value associated with this diagnostic flag.
795  StringRef getFlagValue() const { return FlagValue; }
796
797private:
798  /// \brief Report the delayed diagnostic.
799  void ReportDelayed();
800
801  // This is private state used by DiagnosticBuilder.  We put it here instead of
802  // in DiagnosticBuilder in order to keep DiagnosticBuilder a small lightweight
803  // object.  This implementation choice means that we can only have one
804  // diagnostic "in flight" at a time, but this seems to be a reasonable
805  // tradeoff to keep these objects small.  Assertions verify that only one
806  // diagnostic is in flight at a time.
807  friend class DiagnosticIDs;
808  friend class DiagnosticBuilder;
809  friend class Diagnostic;
810  friend class PartialDiagnostic;
811  friend class DiagnosticErrorTrap;
812
813  /// \brief The location of the current diagnostic that is in flight.
814  SourceLocation CurDiagLoc;
815
816  /// \brief The ID of the current diagnostic that is in flight.
817  ///
818  /// This is set to ~0U when there is no diagnostic in flight.
819  unsigned CurDiagID;
820
821  enum {
822    /// \brief The maximum number of arguments we can hold.
823    ///
824    /// We currently only support up to 10 arguments (%0-%9).  A single
825    /// diagnostic with more than that almost certainly has to be simplified
826    /// anyway.
827    MaxArguments = 10,
828  };
829
830  /// \brief The number of entries in Arguments.
831  signed char NumDiagArgs;
832
833  /// \brief Specifies whether an argument is in DiagArgumentsStr or
834  /// in DiagArguments.
835  ///
836  /// This is an array of ArgumentKind::ArgumentKind enum values, one for each
837  /// argument.
838  unsigned char DiagArgumentsKind[MaxArguments];
839
840  /// \brief Holds the values of each string argument for the current
841  /// diagnostic.
842  ///
843  /// This is only used when the corresponding ArgumentKind is ak_std_string.
844  std::string DiagArgumentsStr[MaxArguments];
845
846  /// \brief The values for the various substitution positions.
847  ///
848  /// This is used when the argument is not an std::string.  The specific
849  /// value is mangled into an intptr_t and the interpretation depends on
850  /// exactly what sort of argument kind it is.
851  intptr_t DiagArgumentsVal[MaxArguments];
852
853  /// \brief The list of ranges added to this diagnostic.
854  SmallVector<CharSourceRange, 8> DiagRanges;
855
856  /// \brief If valid, provides a hint with some code to insert, remove,
857  /// or modify at a particular position.
858  SmallVector<FixItHint, 8> DiagFixItHints;
859
860  DiagnosticMapping makeUserMapping(diag::Severity Map, SourceLocation L) {
861    bool isPragma = L.isValid();
862    DiagnosticMapping Mapping =
863        DiagnosticMapping::Make(Map, /*IsUser=*/true, isPragma);
864
865    // If this is a pragma mapping, then set the diagnostic mapping flags so
866    // that we override command line options.
867    if (isPragma) {
868      Mapping.setNoWarningAsError(true);
869      Mapping.setNoErrorAsFatal(true);
870    }
871
872    return Mapping;
873  }
874
875  /// \brief Used to report a diagnostic that is finally fully formed.
876  ///
877  /// \returns true if the diagnostic was emitted, false if it was suppressed.
878  bool ProcessDiag() {
879    return Diags->ProcessDiag(*this);
880  }
881
882  /// @name Diagnostic Emission
883  /// @{
884protected:
885  // Sema requires access to the following functions because the current design
886  // of SFINAE requires it to use its own SemaDiagnosticBuilder, which needs to
887  // access us directly to ensure we minimize the emitted code for the common
888  // Sema::Diag() patterns.
889  friend class Sema;
890
891  /// \brief Emit the current diagnostic and clear the diagnostic state.
892  ///
893  /// \param Force Emit the diagnostic regardless of suppression settings.
894  bool EmitCurrentDiagnostic(bool Force = false);
895
896  unsigned getCurrentDiagID() const { return CurDiagID; }
897
898  SourceLocation getCurrentDiagLoc() const { return CurDiagLoc; }
899
900  /// @}
901
902  friend class ASTReader;
903  friend class ASTWriter;
904};
905
906/// \brief RAII class that determines when any errors have occurred
907/// between the time the instance was created and the time it was
908/// queried.
909class DiagnosticErrorTrap {
910  DiagnosticsEngine &Diag;
911  unsigned NumErrors;
912  unsigned NumUnrecoverableErrors;
913
914public:
915  explicit DiagnosticErrorTrap(DiagnosticsEngine &Diag)
916    : Diag(Diag) { reset(); }
917
918  /// \brief Determine whether any errors have occurred since this
919  /// object instance was created.
920  bool hasErrorOccurred() const {
921    return Diag.TrapNumErrorsOccurred > NumErrors;
922  }
923
924  /// \brief Determine whether any unrecoverable errors have occurred since this
925  /// object instance was created.
926  bool hasUnrecoverableErrorOccurred() const {
927    return Diag.TrapNumUnrecoverableErrorsOccurred > NumUnrecoverableErrors;
928  }
929
930  /// \brief Set to initial state of "no errors occurred".
931  void reset() {
932    NumErrors = Diag.TrapNumErrorsOccurred;
933    NumUnrecoverableErrors = Diag.TrapNumUnrecoverableErrorsOccurred;
934  }
935};
936
937//===----------------------------------------------------------------------===//
938// DiagnosticBuilder
939//===----------------------------------------------------------------------===//
940
941/// \brief A little helper class used to produce diagnostics.
942///
943/// This is constructed by the DiagnosticsEngine::Report method, and
944/// allows insertion of extra information (arguments and source ranges) into
945/// the currently "in flight" diagnostic.  When the temporary for the builder
946/// is destroyed, the diagnostic is issued.
947///
948/// Note that many of these will be created as temporary objects (many call
949/// sites), so we want them to be small and we never want their address taken.
950/// This ensures that compilers with somewhat reasonable optimizers will promote
951/// the common fields to registers, eliminating increments of the NumArgs field,
952/// for example.
953class DiagnosticBuilder {
954  mutable DiagnosticsEngine *DiagObj = nullptr;
955  mutable unsigned NumArgs = 0;
956
957  /// \brief Status variable indicating if this diagnostic is still active.
958  ///
959  // NOTE: This field is redundant with DiagObj (IsActive iff (DiagObj == 0)),
960  // but LLVM is not currently smart enough to eliminate the null check that
961  // Emit() would end up with if we used that as our status variable.
962  mutable bool IsActive = false;
963
964  /// \brief Flag indicating that this diagnostic is being emitted via a
965  /// call to ForceEmit.
966  mutable bool IsForceEmit = false;
967
968  friend class DiagnosticsEngine;
969
970  DiagnosticBuilder() = default;
971
972  explicit DiagnosticBuilder(DiagnosticsEngine *diagObj)
973      : DiagObj(diagObj), IsActive(true) {
974    assert(diagObj && "DiagnosticBuilder requires a valid DiagnosticsEngine!");
975    diagObj->DiagRanges.clear();
976    diagObj->DiagFixItHints.clear();
977  }
978
979  friend class PartialDiagnostic;
980
981protected:
982  void FlushCounts() {
983    DiagObj->NumDiagArgs = NumArgs;
984  }
985
986  /// \brief Clear out the current diagnostic.
987  void Clear() const {
988    DiagObj = nullptr;
989    IsActive = false;
990    IsForceEmit = false;
991  }
992
993  /// \brief Determine whether this diagnostic is still active.
994  bool isActive() const { return IsActive; }
995
996  /// \brief Force the diagnostic builder to emit the diagnostic now.
997  ///
998  /// Once this function has been called, the DiagnosticBuilder object
999  /// should not be used again before it is destroyed.
1000  ///
1001  /// \returns true if a diagnostic was emitted, false if the
1002  /// diagnostic was suppressed.
1003  bool Emit() {
1004    // If this diagnostic is inactive, then its soul was stolen by the copy ctor
1005    // (or by a subclass, as in SemaDiagnosticBuilder).
1006    if (!isActive()) return false;
1007
1008    // When emitting diagnostics, we set the final argument count into
1009    // the DiagnosticsEngine object.
1010    FlushCounts();
1011
1012    // Process the diagnostic.
1013    bool Result = DiagObj->EmitCurrentDiagnostic(IsForceEmit);
1014
1015    // This diagnostic is dead.
1016    Clear();
1017
1018    return Result;
1019  }
1020
1021public:
1022  /// Copy constructor.  When copied, this "takes" the diagnostic info from the
1023  /// input and neuters it.
1024  DiagnosticBuilder(const DiagnosticBuilder &D) {
1025    DiagObj = D.DiagObj;
1026    IsActive = D.IsActive;
1027    IsForceEmit = D.IsForceEmit;
1028    D.Clear();
1029    NumArgs = D.NumArgs;
1030  }
1031
1032  DiagnosticBuilder &operator=(const DiagnosticBuilder &) = delete;
1033
1034  /// \brief Emits the diagnostic.
1035  ~DiagnosticBuilder() {
1036    Emit();
1037  }
1038
1039  /// \brief Retrieve an empty diagnostic builder.
1040  static DiagnosticBuilder getEmpty() {
1041    return DiagnosticBuilder();
1042  }
1043
1044  /// \brief Forces the diagnostic to be emitted.
1045  const DiagnosticBuilder &setForceEmit() const {
1046    IsForceEmit = true;
1047    return *this;
1048  }
1049
1050  /// \brief Conversion of DiagnosticBuilder to bool always returns \c true.
1051  ///
1052  /// This allows is to be used in boolean error contexts (where \c true is
1053  /// used to indicate that an error has occurred), like:
1054  /// \code
1055  /// return Diag(...);
1056  /// \endcode
1057  operator bool() const { return true; }
1058
1059  void AddString(StringRef S) const {
1060    assert(isActive() && "Clients must not add to cleared diagnostic!");
1061    assert(NumArgs < DiagnosticsEngine::MaxArguments &&
1062           "Too many arguments to diagnostic!");
1063    DiagObj->DiagArgumentsKind[NumArgs] = DiagnosticsEngine::ak_std_string;
1064    DiagObj->DiagArgumentsStr[NumArgs++] = S;
1065  }
1066
1067  void AddTaggedVal(intptr_t V, DiagnosticsEngine::ArgumentKind Kind) const {
1068    assert(isActive() && "Clients must not add to cleared diagnostic!");
1069    assert(NumArgs < DiagnosticsEngine::MaxArguments &&
1070           "Too many arguments to diagnostic!");
1071    DiagObj->DiagArgumentsKind[NumArgs] = Kind;
1072    DiagObj->DiagArgumentsVal[NumArgs++] = V;
1073  }
1074
1075  void AddSourceRange(const CharSourceRange &R) const {
1076    assert(isActive() && "Clients must not add to cleared diagnostic!");
1077    DiagObj->DiagRanges.push_back(R);
1078  }
1079
1080  void AddFixItHint(const FixItHint &Hint) const {
1081    assert(isActive() && "Clients must not add to cleared diagnostic!");
1082    if (!Hint.isNull())
1083      DiagObj->DiagFixItHints.push_back(Hint);
1084  }
1085
1086  void addFlagValue(StringRef V) const { DiagObj->FlagValue = V; }
1087};
1088
1089struct AddFlagValue {
1090  explicit AddFlagValue(StringRef V) : Val(V) {}
1091  StringRef Val;
1092};
1093
1094/// \brief Register a value for the flag in the current diagnostic. This
1095/// value will be shown as the suffix "=value" after the flag name. It is
1096/// useful in cases where the diagnostic flag accepts values (e.g.,
1097/// -Rpass or -Wframe-larger-than).
1098inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1099                                           const AddFlagValue V) {
1100  DB.addFlagValue(V.Val);
1101  return DB;
1102}
1103
1104inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1105                                           StringRef S) {
1106  DB.AddString(S);
1107  return DB;
1108}
1109
1110inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1111                                           const char *Str) {
1112  DB.AddTaggedVal(reinterpret_cast<intptr_t>(Str),
1113                  DiagnosticsEngine::ak_c_string);
1114  return DB;
1115}
1116
1117inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, int I) {
1118  DB.AddTaggedVal(I, DiagnosticsEngine::ak_sint);
1119  return DB;
1120}
1121
1122// We use enable_if here to prevent that this overload is selected for
1123// pointers or other arguments that are implicitly convertible to bool.
1124template <typename T>
1125inline
1126typename std::enable_if<std::is_same<T, bool>::value,
1127                        const DiagnosticBuilder &>::type
1128operator<<(const DiagnosticBuilder &DB, T I) {
1129  DB.AddTaggedVal(I, DiagnosticsEngine::ak_sint);
1130  return DB;
1131}
1132
1133inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1134                                           unsigned I) {
1135  DB.AddTaggedVal(I, DiagnosticsEngine::ak_uint);
1136  return DB;
1137}
1138
1139inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1140                                           tok::TokenKind I) {
1141  DB.AddTaggedVal(static_cast<unsigned>(I), DiagnosticsEngine::ak_tokenkind);
1142  return DB;
1143}
1144
1145inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1146                                           const IdentifierInfo *II) {
1147  DB.AddTaggedVal(reinterpret_cast<intptr_t>(II),
1148                  DiagnosticsEngine::ak_identifierinfo);
1149  return DB;
1150}
1151
1152// Adds a DeclContext to the diagnostic. The enable_if template magic is here
1153// so that we only match those arguments that are (statically) DeclContexts;
1154// other arguments that derive from DeclContext (e.g., RecordDecls) will not
1155// match.
1156template <typename T>
1157inline typename std::enable_if<
1158    std::is_same<typename std::remove_const<T>::type, DeclContext>::value,
1159    const DiagnosticBuilder &>::type
1160operator<<(const DiagnosticBuilder &DB, T *DC) {
1161  DB.AddTaggedVal(reinterpret_cast<intptr_t>(DC),
1162                  DiagnosticsEngine::ak_declcontext);
1163  return DB;
1164}
1165
1166inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1167                                           SourceRange R) {
1168  DB.AddSourceRange(CharSourceRange::getTokenRange(R));
1169  return DB;
1170}
1171
1172inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1173                                           ArrayRef<SourceRange> Ranges) {
1174  for (SourceRange R : Ranges)
1175    DB.AddSourceRange(CharSourceRange::getTokenRange(R));
1176  return DB;
1177}
1178
1179inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1180                                           const CharSourceRange &R) {
1181  DB.AddSourceRange(R);
1182  return DB;
1183}
1184
1185inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1186                                           const FixItHint &Hint) {
1187  DB.AddFixItHint(Hint);
1188  return DB;
1189}
1190
1191inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1192                                           ArrayRef<FixItHint> Hints) {
1193  for (const FixItHint &Hint : Hints)
1194    DB.AddFixItHint(Hint);
1195  return DB;
1196}
1197
1198/// A nullability kind paired with a bit indicating whether it used a
1199/// context-sensitive keyword.
1200typedef std::pair<NullabilityKind, bool> DiagNullabilityKind;
1201
1202const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1203                                    DiagNullabilityKind nullability);
1204
1205inline DiagnosticBuilder DiagnosticsEngine::Report(SourceLocation Loc,
1206                                                   unsigned DiagID) {
1207  assert(CurDiagID == ~0U && "Multiple diagnostics in flight at once!");
1208  CurDiagLoc = Loc;
1209  CurDiagID = DiagID;
1210  FlagValue.clear();
1211  return DiagnosticBuilder(this);
1212}
1213
1214inline DiagnosticBuilder DiagnosticsEngine::Report(unsigned DiagID) {
1215  return Report(SourceLocation(), DiagID);
1216}
1217
1218//===----------------------------------------------------------------------===//
1219// Diagnostic
1220//===----------------------------------------------------------------------===//
1221
1222/// A little helper class (which is basically a smart pointer that forwards
1223/// info from DiagnosticsEngine) that allows clients to enquire about the
1224/// currently in-flight diagnostic.
1225class Diagnostic {
1226  const DiagnosticsEngine *DiagObj;
1227  StringRef StoredDiagMessage;
1228
1229public:
1230  explicit Diagnostic(const DiagnosticsEngine *DO) : DiagObj(DO) {}
1231  Diagnostic(const DiagnosticsEngine *DO, StringRef storedDiagMessage)
1232    : DiagObj(DO), StoredDiagMessage(storedDiagMessage) {}
1233
1234  const DiagnosticsEngine *getDiags() const { return DiagObj; }
1235  unsigned getID() const { return DiagObj->CurDiagID; }
1236  const SourceLocation &getLocation() const { return DiagObj->CurDiagLoc; }
1237  bool hasSourceManager() const { return DiagObj->hasSourceManager(); }
1238  SourceManager &getSourceManager() const { return DiagObj->getSourceManager();}
1239
1240  unsigned getNumArgs() const { return DiagObj->NumDiagArgs; }
1241
1242  /// \brief Return the kind of the specified index.
1243  ///
1244  /// Based on the kind of argument, the accessors below can be used to get
1245  /// the value.
1246  ///
1247  /// \pre Idx < getNumArgs()
1248  DiagnosticsEngine::ArgumentKind getArgKind(unsigned Idx) const {
1249    assert(Idx < getNumArgs() && "Argument index out of range!");
1250    return (DiagnosticsEngine::ArgumentKind)DiagObj->DiagArgumentsKind[Idx];
1251  }
1252
1253  /// \brief Return the provided argument string specified by \p Idx.
1254  /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_std_string
1255  const std::string &getArgStdStr(unsigned Idx) const {
1256    assert(getArgKind(Idx) == DiagnosticsEngine::ak_std_string &&
1257           "invalid argument accessor!");
1258    return DiagObj->DiagArgumentsStr[Idx];
1259  }
1260
1261  /// \brief Return the specified C string argument.
1262  /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_c_string
1263  const char *getArgCStr(unsigned Idx) const {
1264    assert(getArgKind(Idx) == DiagnosticsEngine::ak_c_string &&
1265           "invalid argument accessor!");
1266    return reinterpret_cast<const char*>(DiagObj->DiagArgumentsVal[Idx]);
1267  }
1268
1269  /// \brief Return the specified signed integer argument.
1270  /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_sint
1271  int getArgSInt(unsigned Idx) const {
1272    assert(getArgKind(Idx) == DiagnosticsEngine::ak_sint &&
1273           "invalid argument accessor!");
1274    return (int)DiagObj->DiagArgumentsVal[Idx];
1275  }
1276
1277  /// \brief Return the specified unsigned integer argument.
1278  /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_uint
1279  unsigned getArgUInt(unsigned Idx) const {
1280    assert(getArgKind(Idx) == DiagnosticsEngine::ak_uint &&
1281           "invalid argument accessor!");
1282    return (unsigned)DiagObj->DiagArgumentsVal[Idx];
1283  }
1284
1285  /// \brief Return the specified IdentifierInfo argument.
1286  /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_identifierinfo
1287  const IdentifierInfo *getArgIdentifier(unsigned Idx) const {
1288    assert(getArgKind(Idx) == DiagnosticsEngine::ak_identifierinfo &&
1289           "invalid argument accessor!");
1290    return reinterpret_cast<IdentifierInfo*>(DiagObj->DiagArgumentsVal[Idx]);
1291  }
1292
1293  /// \brief Return the specified non-string argument in an opaque form.
1294  /// \pre getArgKind(Idx) != DiagnosticsEngine::ak_std_string
1295  intptr_t getRawArg(unsigned Idx) const {
1296    assert(getArgKind(Idx) != DiagnosticsEngine::ak_std_string &&
1297           "invalid argument accessor!");
1298    return DiagObj->DiagArgumentsVal[Idx];
1299  }
1300
1301  /// \brief Return the number of source ranges associated with this diagnostic.
1302  unsigned getNumRanges() const {
1303    return DiagObj->DiagRanges.size();
1304  }
1305
1306  /// \pre Idx < getNumRanges()
1307  const CharSourceRange &getRange(unsigned Idx) const {
1308    assert(Idx < getNumRanges() && "Invalid diagnostic range index!");
1309    return DiagObj->DiagRanges[Idx];
1310  }
1311
1312  /// \brief Return an array reference for this diagnostic's ranges.
1313  ArrayRef<CharSourceRange> getRanges() const {
1314    return DiagObj->DiagRanges;
1315  }
1316
1317  unsigned getNumFixItHints() const {
1318    return DiagObj->DiagFixItHints.size();
1319  }
1320
1321  const FixItHint &getFixItHint(unsigned Idx) const {
1322    assert(Idx < getNumFixItHints() && "Invalid index!");
1323    return DiagObj->DiagFixItHints[Idx];
1324  }
1325
1326  ArrayRef<FixItHint> getFixItHints() const {
1327    return DiagObj->DiagFixItHints;
1328  }
1329
1330  /// \brief Format this diagnostic into a string, substituting the
1331  /// formal arguments into the %0 slots.
1332  ///
1333  /// The result is appended onto the \p OutStr array.
1334  void FormatDiagnostic(SmallVectorImpl<char> &OutStr) const;
1335
1336  /// \brief Format the given format-string into the output buffer using the
1337  /// arguments stored in this diagnostic.
1338  void FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
1339                        SmallVectorImpl<char> &OutStr) const;
1340};
1341
1342/**
1343 * \brief Represents a diagnostic in a form that can be retained until its
1344 * corresponding source manager is destroyed.
1345 */
1346class StoredDiagnostic {
1347  unsigned ID;
1348  DiagnosticsEngine::Level Level;
1349  FullSourceLoc Loc;
1350  std::string Message;
1351  std::vector<CharSourceRange> Ranges;
1352  std::vector<FixItHint> FixIts;
1353
1354public:
1355  StoredDiagnostic() = default;
1356  StoredDiagnostic(DiagnosticsEngine::Level Level, const Diagnostic &Info);
1357  StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
1358                   StringRef Message);
1359  StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
1360                   StringRef Message, FullSourceLoc Loc,
1361                   ArrayRef<CharSourceRange> Ranges,
1362                   ArrayRef<FixItHint> Fixits);
1363
1364  /// \brief Evaluates true when this object stores a diagnostic.
1365  explicit operator bool() const { return !Message.empty(); }
1366
1367  unsigned getID() const { return ID; }
1368  DiagnosticsEngine::Level getLevel() const { return Level; }
1369  const FullSourceLoc &getLocation() const { return Loc; }
1370  StringRef getMessage() const { return Message; }
1371
1372  void setLocation(FullSourceLoc Loc) { this->Loc = Loc; }
1373
1374  typedef std::vector<CharSourceRange>::const_iterator range_iterator;
1375  range_iterator range_begin() const { return Ranges.begin(); }
1376  range_iterator range_end() const { return Ranges.end(); }
1377  unsigned range_size() const { return Ranges.size(); }
1378
1379  ArrayRef<CharSourceRange> getRanges() const {
1380    return llvm::makeArrayRef(Ranges);
1381  }
1382
1383  typedef std::vector<FixItHint>::const_iterator fixit_iterator;
1384  fixit_iterator fixit_begin() const { return FixIts.begin(); }
1385  fixit_iterator fixit_end() const { return FixIts.end(); }
1386  unsigned fixit_size() const { return FixIts.size(); }
1387
1388  ArrayRef<FixItHint> getFixIts() const {
1389    return llvm::makeArrayRef(FixIts);
1390  }
1391};
1392
1393/// \brief Abstract interface, implemented by clients of the front-end, which
1394/// formats and prints fully processed diagnostics.
1395class DiagnosticConsumer {
1396protected:
1397  unsigned NumWarnings = 0;       ///< Number of warnings reported
1398  unsigned NumErrors = 0;         ///< Number of errors reported
1399
1400public:
1401  DiagnosticConsumer() = default;
1402
1403  virtual ~DiagnosticConsumer();
1404
1405  unsigned getNumErrors() const { return NumErrors; }
1406  unsigned getNumWarnings() const { return NumWarnings; }
1407  virtual void clear() { NumWarnings = NumErrors = 0; }
1408
1409  /// \brief Callback to inform the diagnostic client that processing
1410  /// of a source file is beginning.
1411  ///
1412  /// Note that diagnostics may be emitted outside the processing of a source
1413  /// file, for example during the parsing of command line options. However,
1414  /// diagnostics with source range information are required to only be emitted
1415  /// in between BeginSourceFile() and EndSourceFile().
1416  ///
1417  /// \param LangOpts The language options for the source file being processed.
1418  /// \param PP The preprocessor object being used for the source; this is
1419  /// optional, e.g., it may not be present when processing AST source files.
1420  virtual void BeginSourceFile(const LangOptions &LangOpts,
1421                               const Preprocessor *PP = nullptr) {}
1422
1423  /// \brief Callback to inform the diagnostic client that processing
1424  /// of a source file has ended.
1425  ///
1426  /// The diagnostic client should assume that any objects made available via
1427  /// BeginSourceFile() are inaccessible.
1428  virtual void EndSourceFile() {}
1429
1430  /// \brief Callback to inform the diagnostic client that processing of all
1431  /// source files has ended.
1432  virtual void finish() {}
1433
1434  /// \brief Indicates whether the diagnostics handled by this
1435  /// DiagnosticConsumer should be included in the number of diagnostics
1436  /// reported by DiagnosticsEngine.
1437  ///
1438  /// The default implementation returns true.
1439  virtual bool IncludeInDiagnosticCounts() const;
1440
1441  /// \brief Handle this diagnostic, reporting it to the user or
1442  /// capturing it to a log as needed.
1443  ///
1444  /// The default implementation just keeps track of the total number of
1445  /// warnings and errors.
1446  virtual void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
1447                                const Diagnostic &Info);
1448};
1449
1450/// \brief A diagnostic client that ignores all diagnostics.
1451class IgnoringDiagConsumer : public DiagnosticConsumer {
1452  virtual void anchor();
1453
1454  void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
1455                        const Diagnostic &Info) override {
1456    // Just ignore it.
1457  }
1458};
1459
1460/// \brief Diagnostic consumer that forwards diagnostics along to an
1461/// existing, already-initialized diagnostic consumer.
1462///
1463class ForwardingDiagnosticConsumer : public DiagnosticConsumer {
1464  DiagnosticConsumer &Target;
1465
1466public:
1467  ForwardingDiagnosticConsumer(DiagnosticConsumer &Target) : Target(Target) {}
1468
1469  ~ForwardingDiagnosticConsumer() override;
1470
1471  void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
1472                        const Diagnostic &Info) override;
1473  void clear() override;
1474
1475  bool IncludeInDiagnosticCounts() const override;
1476};
1477
1478// Struct used for sending info about how a type should be printed.
1479struct TemplateDiffTypes {
1480  intptr_t FromType;
1481  intptr_t ToType;
1482  unsigned PrintTree : 1;
1483  unsigned PrintFromType : 1;
1484  unsigned ElideType : 1;
1485  unsigned ShowColors : 1;
1486  // The printer sets this variable to true if the template diff was used.
1487  unsigned TemplateDiffUsed : 1;
1488};
1489
1490/// Special character that the diagnostic printer will use to toggle the bold
1491/// attribute.  The character itself will be not be printed.
1492const char ToggleHighlight = 127;
1493
1494
1495/// ProcessWarningOptions - Initialize the diagnostic client and process the
1496/// warning options specified on the command line.
1497void ProcessWarningOptions(DiagnosticsEngine &Diags,
1498                           const DiagnosticOptions &Opts,
1499                           bool ReportDiags = true);
1500
1501} // end namespace clang
1502
1503#endif // LLVM_CLANG_BASIC_DIAGNOSTIC_H
1504