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