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