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