1 //! Diagnostics creation and emission for `rustc`.
3 //! This module contains the code for creating and emitting diagnostics.
5 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
6 #![feature(drain_filter)]
7 #![feature(if_let_guard)]
8 #![feature(adt_const_params)]
9 #![feature(let_chains)]
10 #![feature(never_type)]
11 #![feature(result_option_inspect)]
12 #![feature(rustc_attrs)]
13 #![allow(incomplete_features)]
16 extern crate rustc_macros;
21 pub use emitter::ColorConfig;
23 use rustc_lint_defs::LintExpectationId;
26 use emitter::{is_case_difference, Emitter, EmitterWriter};
27 use registry::Registry;
28 use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet};
29 use rustc_data_structures::stable_hasher::StableHasher;
30 use rustc_data_structures::sync::{self, Lock, Lrc};
31 use rustc_data_structures::AtomicRef;
32 pub use rustc_error_messages::{
33 fallback_fluent_bundle, fluent, fluent_bundle, DelayDm, DiagnosticMessage, FluentBundle,
34 LanguageIdentifier, LazyFallbackBundle, MultiSpan, SpanLabel, SubdiagnosticMessage,
35 DEFAULT_LOCALE_RESOURCES,
37 pub use rustc_lint_defs::{pluralize, Applicability};
38 use rustc_span::source_map::SourceMap;
39 use rustc_span::HashStableContext;
40 use rustc_span::{Loc, Span};
44 use std::num::NonZeroUsize;
47 use std::{error, fmt};
49 use termcolor::{Color, ColorSpec};
51 pub mod annotate_snippet_emitter_writer;
53 mod diagnostic_builder;
63 pub use diagnostic_builder::IntoDiagnostic;
64 pub use snippet::Style;
66 pub type PErr<'a> = DiagnosticBuilder<'a, ErrorGuaranteed>;
67 pub type PResult<'a, T> = Result<T, PErr<'a>>;
69 // `PResult` is used a lot. Make sure it doesn't unintentionally get bigger.
70 // (See also the comment on `DiagnosticBuilderInner`'s `diagnostic` field.)
71 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
72 rustc_data_structures::static_assert_size!(PResult<'_, ()>, 16);
73 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
74 rustc_data_structures::static_assert_size!(PResult<'_, bool>, 16);
76 #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, Encodable, Decodable)]
77 pub enum SuggestionStyle {
78 /// Hide the suggested code when displaying this suggestion inline.
80 /// Always hide the suggested code but display the message.
82 /// Do not display this suggestion in the cli output, it is only meant for tools.
84 /// Always show the suggested code.
85 /// This will *not* show the code if the suggestion is inline *and* the suggested code is
88 /// Always show the suggested code independently.
92 impl SuggestionStyle {
93 fn hide_inline(&self) -> bool {
94 !matches!(*self, SuggestionStyle::ShowCode)
98 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
99 pub struct CodeSuggestion {
100 /// Each substitute can have multiple variants due to multiple
101 /// applicable suggestions
103 /// `foo.bar` might be replaced with `a.b` or `x.y` by replacing
104 /// `foo` and `bar` on their own:
106 /// ```ignore (illustrative)
108 /// Substitution { parts: vec![(0..3, "a"), (4..7, "b")] },
109 /// Substitution { parts: vec![(0..3, "x"), (4..7, "y")] },
113 /// or by replacing the entire span:
115 /// ```ignore (illustrative)
117 /// Substitution { parts: vec![(0..7, "a.b")] },
118 /// Substitution { parts: vec![(0..7, "x.y")] },
121 pub substitutions: Vec<Substitution>,
122 pub msg: DiagnosticMessage,
123 /// Visual representation of this suggestion.
124 pub style: SuggestionStyle,
125 /// Whether or not the suggestion is approximate
127 /// Sometimes we may show suggestions with placeholders,
128 /// which are useful for users but not useful for
129 /// tools like rustfix
130 pub applicability: Applicability,
133 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
134 /// See the docs on `CodeSuggestion::substitutions`
135 pub struct Substitution {
136 pub parts: Vec<SubstitutionPart>,
139 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
140 pub struct SubstitutionPart {
145 /// Used to translate between `Span`s and byte positions within a single output line in highlighted
146 /// code of structured suggestions.
147 #[derive(Debug, Clone, Copy)]
148 pub struct SubstitutionHighlight {
153 impl SubstitutionPart {
154 pub fn is_addition(&self, sm: &SourceMap) -> bool {
155 !self.snippet.is_empty() && !self.replaces_meaningful_content(sm)
158 pub fn is_deletion(&self, sm: &SourceMap) -> bool {
159 self.snippet.trim().is_empty() && self.replaces_meaningful_content(sm)
162 pub fn is_replacement(&self, sm: &SourceMap) -> bool {
163 !self.snippet.is_empty() && self.replaces_meaningful_content(sm)
166 fn replaces_meaningful_content(&self, sm: &SourceMap) -> bool {
167 sm.span_to_snippet(self.span)
168 .map_or(!self.span.is_empty(), |snippet| !snippet.trim().is_empty())
172 impl CodeSuggestion {
173 /// Returns the assembled code suggestions, whether they should be shown with an underline
174 /// and whether the substitution only differs in capitalization.
178 ) -> Vec<(String, Vec<SubstitutionPart>, Vec<Vec<SubstitutionHighlight>>, bool)> {
179 // For the `Vec<Vec<SubstitutionHighlight>>` value, the first level of the vector
180 // corresponds to the output snippet's lines, while the second level corresponds to the
181 // substrings within that line that should be highlighted.
183 use rustc_span::{CharPos, Pos};
185 /// Append to a buffer the remainder of the line of existing source code, and return the
186 /// count of lines that have been added for accurate highlighting.
189 line_opt: Option<&Cow<'_, str>>,
191 hi_opt: Option<&Loc>,
193 let mut line_count = 0;
194 let (lo, hi_opt) = (lo.col.to_usize(), hi_opt.map(|hi| hi.col.to_usize()));
195 if let Some(line) = line_opt {
196 if let Some(lo) = line.char_indices().map(|(i, _)| i).nth(lo) {
197 let hi_opt = hi_opt.and_then(|hi| line.char_indices().map(|(i, _)| i).nth(hi));
199 Some(hi) if hi > lo => {
200 line_count = line[lo..hi].matches('\n').count();
201 buf.push_str(&line[lo..hi])
205 line_count = line[lo..].matches('\n').count();
206 buf.push_str(&line[lo..])
210 if hi_opt.is_none() {
217 assert!(!self.substitutions.is_empty());
222 // Suggestions coming from macros can have malformed spans. This is a heavy
223 // handed approach to avoid ICEs by ignoring the suggestion outright.
224 let invalid = subst.parts.iter().any(|item| sm.is_valid_span(item.span).is_err());
226 debug!("splice_lines: suggestion contains an invalid span: {:?}", subst);
231 .filter_map(|mut substitution| {
232 // Assumption: all spans are in the same file, and all spans
233 // are disjoint. Sort in ascending order.
234 substitution.parts.sort_by_key(|part| part.span.lo());
236 // Find the bounding span.
237 let lo = substitution.parts.iter().map(|part| part.span.lo()).min()?;
238 let hi = substitution.parts.iter().map(|part| part.span.hi()).max()?;
239 let bounding_span = Span::with_root_ctxt(lo, hi);
240 // The different spans might belong to different contexts, if so ignore suggestion.
241 let lines = sm.span_to_lines(bounding_span).ok()?;
242 assert!(!lines.lines.is_empty() || bounding_span.is_dummy());
244 // We can't splice anything if the source is unavailable.
245 if !sm.ensure_source_file_source_present(lines.file.clone()) {
249 let mut highlights = vec![];
250 // To build up the result, we do this for each span:
251 // - push the line segment trailing the previous span
252 // (at the beginning a "phantom" span pointing at the start of the line)
253 // - push lines between the previous and current span (if any)
254 // - if the previous and current span are not on the same line
255 // push the line segment leading up to the current span
256 // - splice in the span substitution
258 // Finally push the trailing line segment of the last span
259 let sf = &lines.file;
260 let mut prev_hi = sm.lookup_char_pos(bounding_span.lo());
261 prev_hi.col = CharPos::from_usize(0);
263 lines.lines.get(0).and_then(|line0| sf.get_line(line0.line_index));
264 let mut buf = String::new();
266 let mut line_highlight = vec![];
267 // We need to keep track of the difference between the existing code and the added
268 // or deleted code in order to point at the correct column *after* substitution.
270 for part in &substitution.parts {
271 let cur_lo = sm.lookup_char_pos(part.span.lo());
272 if prev_hi.line == cur_lo.line {
274 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, Some(&cur_lo));
276 highlights.push(std::mem::take(&mut line_highlight));
282 highlights.push(std::mem::take(&mut line_highlight));
283 let mut count = push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
285 highlights.push(std::mem::take(&mut line_highlight));
288 // push lines between the previous and current span (if any)
289 for idx in prev_hi.line..(cur_lo.line - 1) {
290 if let Some(line) = sf.get_line(idx) {
291 buf.push_str(line.as_ref());
293 highlights.push(std::mem::take(&mut line_highlight));
296 if let Some(cur_line) = sf.get_line(cur_lo.line - 1) {
297 let end = match cur_line.char_indices().nth(cur_lo.col.to_usize()) {
299 None => cur_line.len(),
301 buf.push_str(&cur_line[..end]);
304 // Add a whole line highlight per line in the snippet.
305 let len: isize = part
309 .unwrap_or(&part.snippet)
316 line_highlight.push(SubstitutionHighlight {
317 start: (cur_lo.col.0 as isize + acc) as usize,
318 end: (cur_lo.col.0 as isize + acc + len) as usize,
320 buf.push_str(&part.snippet);
321 let cur_hi = sm.lookup_char_pos(part.span.hi());
322 if prev_hi.line == cur_lo.line && cur_hi.line == cur_lo.line {
323 // Account for the difference between the width of the current code and the
324 // snippet being suggested, so that the *later* suggestions are correctly
325 // aligned on the screen.
326 acc += len as isize - (cur_hi.col.0 - cur_lo.col.0) as isize;
329 prev_line = sf.get_line(prev_hi.line - 1);
330 for line in part.snippet.split('\n').skip(1) {
332 highlights.push(std::mem::take(&mut line_highlight));
333 let end: usize = line
340 line_highlight.push(SubstitutionHighlight { start: 0, end });
343 highlights.push(std::mem::take(&mut line_highlight));
344 let only_capitalization = is_case_difference(sm, &buf, bounding_span);
345 // if the replacement already ends with a newline, don't print the next line
346 if !buf.ends_with('\n') {
347 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
349 // remove trailing newlines
350 while buf.ends_with('\n') {
353 Some((buf, substitution.parts, highlights, only_capitalization))
359 pub use rustc_span::fatal_error::{FatalError, FatalErrorMarker};
361 /// Signifies that the compiler died with an explicit call to `.bug`
362 /// or `.span_bug` rather than a failed assertion, etc.
363 #[derive(Copy, Clone, Debug)]
364 pub struct ExplicitBug;
366 impl fmt::Display for ExplicitBug {
367 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
368 write!(f, "parser internal bug")
372 impl error::Error for ExplicitBug {}
374 pub use diagnostic::{
375 AddToDiagnostic, DecorateLint, Diagnostic, DiagnosticArg, DiagnosticArgValue, DiagnosticId,
376 DiagnosticStyledString, IntoDiagnosticArg, SubDiagnostic,
378 pub use diagnostic_builder::{DiagnosticBuilder, EmissionGuarantee, Noted};
379 pub use diagnostic_impls::DiagnosticArgFromDisplay;
380 use std::backtrace::Backtrace;
382 /// A handler deals with errors and other compiler output.
383 /// Certain errors (fatal, bug, unimpl) may cause immediate exit,
384 /// others log errors for later reporting.
387 inner: Lock<HandlerInner>,
390 /// This inner struct exists to keep it all behind a single lock;
391 /// this is done to prevent possible deadlocks in a multi-threaded compiler,
392 /// as well as inconsistent state observation.
393 struct HandlerInner {
395 /// The number of lint errors that have been emitted.
396 lint_err_count: usize,
397 /// The number of errors that have been emitted, including duplicates.
399 /// This is not necessarily the count that's reported to the user once
400 /// compilation ends.
403 deduplicated_err_count: usize,
404 emitter: Box<dyn Emitter + sync::Send>,
405 delayed_span_bugs: Vec<Diagnostic>,
406 delayed_good_path_bugs: Vec<DelayedDiagnostic>,
407 /// This flag indicates that an expected diagnostic was emitted and suppressed.
408 /// This is used for the `delayed_good_path_bugs` check.
409 suppressed_expected_diag: bool,
411 /// This set contains the `DiagnosticId` of all emitted diagnostics to avoid
412 /// emitting the same diagnostic with extended help (`--teach`) twice, which
413 /// would be unnecessary repetition.
414 taught_diagnostics: FxHashSet<DiagnosticId>,
416 /// Used to suggest rustc --explain `<error code>`
417 emitted_diagnostic_codes: FxIndexSet<DiagnosticId>,
419 /// This set contains a hash of every diagnostic that has been emitted by
420 /// this handler. These hashes is used to avoid emitting the same error
422 emitted_diagnostics: FxHashSet<u128>,
424 /// Stashed diagnostics emitted in one stage of the compiler that may be
425 /// stolen by other stages (e.g. to improve them and add more information).
426 /// The stashed diagnostics count towards the total error count.
427 /// When `.abort_if_errors()` is called, these are also emitted.
428 stashed_diagnostics: FxIndexMap<(Span, StashKey), Diagnostic>,
430 /// The warning count, used for a recap upon finishing
431 deduplicated_warn_count: usize,
433 future_breakage_diagnostics: Vec<Diagnostic>,
435 /// The [`Self::unstable_expect_diagnostics`] should be empty when this struct is
436 /// dropped. However, it can have values if the compilation is stopped early
437 /// or is only partially executed. To avoid ICEs, like in rust#94953 we only
438 /// check if [`Self::unstable_expect_diagnostics`] is empty, if the expectation ids
439 /// have been converted.
440 check_unstable_expect_diagnostics: bool,
442 /// Expected [`Diagnostic`][diagnostic::Diagnostic]s store a [`LintExpectationId`] as part of
443 /// the lint level. [`LintExpectationId`]s created early during the compilation
444 /// (before `HirId`s have been defined) are not stable and can therefore not be
445 /// stored on disk. This buffer stores these diagnostics until the ID has been
446 /// replaced by a stable [`LintExpectationId`]. The [`Diagnostic`][diagnostic::Diagnostic]s are the
447 /// submitted for storage and added to the list of fulfilled expectations.
448 unstable_expect_diagnostics: Vec<Diagnostic>,
450 /// expected diagnostic will have the level `Expect` which additionally
451 /// carries the [`LintExpectationId`] of the expectation that can be
452 /// marked as fulfilled. This is a collection of all [`LintExpectationId`]s
453 /// that have been marked as fulfilled this way.
455 /// [RFC-2383]: https://rust-lang.github.io/rfcs/2383-lint-reasons.html
456 fulfilled_expectations: FxHashSet<LintExpectationId>,
459 /// A key denoting where from a diagnostic was stashed.
460 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
463 UnderscoreForArrayLengths,
468 fn default_track_diagnostic(_: &Diagnostic) {}
470 pub static TRACK_DIAGNOSTICS: AtomicRef<fn(&Diagnostic)> =
471 AtomicRef::new(&(default_track_diagnostic as fn(&_)));
473 #[derive(Copy, Clone, Default)]
474 pub struct HandlerFlags {
475 /// If false, warning-level lints are suppressed.
476 /// (rustc: see `--allow warnings` and `--cap-lints`)
477 pub can_emit_warnings: bool,
478 /// If true, error-level diagnostics are upgraded to bug-level.
479 /// (rustc: see `-Z treat-err-as-bug`)
480 pub treat_err_as_bug: Option<NonZeroUsize>,
481 /// If true, immediately emit diagnostics that would otherwise be buffered.
482 /// (rustc: see `-Z dont-buffer-diagnostics` and `-Z treat-err-as-bug`)
483 pub dont_buffer_diagnostics: bool,
484 /// If true, immediately print bugs registered with `delay_span_bug`.
485 /// (rustc: see `-Z report-delayed-bugs`)
486 pub report_delayed_bugs: bool,
487 /// Show macro backtraces.
488 /// (rustc: see `-Z macro-backtrace`)
489 pub macro_backtrace: bool,
490 /// If true, identical diagnostics are reported only once.
491 pub deduplicate_diagnostics: bool,
492 /// Track where errors are created. Enabled with `-Ztrack-diagnostics`.
493 pub track_diagnostics: bool,
496 impl Drop for HandlerInner {
498 self.emit_stashed_diagnostics();
500 if !self.has_errors() {
501 let bugs = std::mem::replace(&mut self.delayed_span_bugs, Vec::new());
502 self.flush_delayed(bugs, "no errors encountered even though `delay_span_bug` issued");
505 // FIXME(eddyb) this explains what `delayed_good_path_bugs` are!
506 // They're `delayed_span_bugs` but for "require some diagnostic happened"
507 // instead of "require some error happened". Sadly that isn't ideal, as
508 // lints can be `#[allow]`'d, potentially leading to this triggering.
509 // Also, "good path" should be replaced with a better naming.
510 if !self.has_any_message() && !self.suppressed_expected_diag {
511 let bugs = std::mem::replace(&mut self.delayed_good_path_bugs, Vec::new());
513 bugs.into_iter().map(DelayedDiagnostic::decorate),
514 "no warnings or errors encountered even though `delayed_good_path_bugs` issued",
518 if self.check_unstable_expect_diagnostics {
520 self.unstable_expect_diagnostics.is_empty(),
521 "all diagnostics with unstable expectations should have been converted",
528 pub fn with_tty_emitter(
529 color_config: ColorConfig,
530 can_emit_warnings: bool,
531 treat_err_as_bug: Option<NonZeroUsize>,
532 sm: Option<Lrc<SourceMap>>,
533 fluent_bundle: Option<Lrc<FluentBundle>>,
534 fallback_bundle: LazyFallbackBundle,
536 Self::with_tty_emitter_and_flags(
541 HandlerFlags { can_emit_warnings, treat_err_as_bug, ..Default::default() },
545 pub fn with_tty_emitter_and_flags(
546 color_config: ColorConfig,
547 sm: Option<Lrc<SourceMap>>,
548 fluent_bundle: Option<Lrc<FluentBundle>>,
549 fallback_bundle: LazyFallbackBundle,
552 let emitter = Box::new(EmitterWriter::stderr(
560 flags.macro_backtrace,
561 flags.track_diagnostics,
563 Self::with_emitter_and_flags(emitter, flags)
567 can_emit_warnings: bool,
568 treat_err_as_bug: Option<NonZeroUsize>,
569 emitter: Box<dyn Emitter + sync::Send>,
571 Handler::with_emitter_and_flags(
573 HandlerFlags { can_emit_warnings, treat_err_as_bug, ..Default::default() },
577 pub fn with_emitter_and_flags(
578 emitter: Box<dyn Emitter + sync::Send>,
583 inner: Lock::new(HandlerInner {
588 deduplicated_err_count: 0,
589 deduplicated_warn_count: 0,
591 delayed_span_bugs: Vec::new(),
592 delayed_good_path_bugs: Vec::new(),
593 suppressed_expected_diag: false,
594 taught_diagnostics: Default::default(),
595 emitted_diagnostic_codes: Default::default(),
596 emitted_diagnostics: Default::default(),
597 stashed_diagnostics: Default::default(),
598 future_breakage_diagnostics: Vec::new(),
599 check_unstable_expect_diagnostics: false,
600 unstable_expect_diagnostics: Vec::new(),
601 fulfilled_expectations: Default::default(),
606 /// Translate `message` eagerly with `args`.
607 pub fn eagerly_translate<'a>(
609 message: DiagnosticMessage,
610 args: impl Iterator<Item = DiagnosticArg<'a, 'static>>,
611 ) -> SubdiagnosticMessage {
612 let inner = self.inner.borrow();
613 let args = crate::translation::to_fluent_args(args);
614 SubdiagnosticMessage::Eager(inner.emitter.translate_message(&message, &args).to_string())
617 // This is here to not allow mutation of flags;
618 // as of this writing it's only used in tests in librustc_middle.
619 pub fn can_emit_warnings(&self) -> bool {
620 self.flags.can_emit_warnings
623 /// Resets the diagnostic error count as well as the cached emitted diagnostics.
625 /// NOTE: *do not* call this function from rustc. It is only meant to be called from external
626 /// tools that want to reuse a `Parser` cleaning the previously emitted diagnostics as well as
627 /// the overall count of emitted error diagnostics.
628 pub fn reset_err_count(&self) {
629 let mut inner = self.inner.borrow_mut();
631 inner.warn_count = 0;
632 inner.deduplicated_err_count = 0;
633 inner.deduplicated_warn_count = 0;
635 // actually free the underlying memory (which `clear` would not do)
636 inner.delayed_span_bugs = Default::default();
637 inner.delayed_good_path_bugs = Default::default();
638 inner.taught_diagnostics = Default::default();
639 inner.emitted_diagnostic_codes = Default::default();
640 inner.emitted_diagnostics = Default::default();
641 inner.stashed_diagnostics = Default::default();
644 /// Stash a given diagnostic with the given `Span` and `StashKey` as the key for later stealing.
645 pub fn stash_diagnostic(&self, span: Span, key: StashKey, diag: Diagnostic) {
646 let mut inner = self.inner.borrow_mut();
647 inner.stash((span, key), diag);
650 /// Steal a previously stashed diagnostic with the given `Span` and `StashKey` as the key.
651 pub fn steal_diagnostic(&self, span: Span, key: StashKey) -> Option<DiagnosticBuilder<'_, ()>> {
652 let mut inner = self.inner.borrow_mut();
653 inner.steal((span, key)).map(|diag| DiagnosticBuilder::new_diagnostic(self, diag))
656 pub fn has_stashed_diagnostic(&self, span: Span, key: StashKey) -> bool {
657 self.inner.borrow().stashed_diagnostics.get(&(span, key)).is_some()
660 /// Emit all stashed diagnostics.
661 pub fn emit_stashed_diagnostics(&self) -> Option<ErrorGuaranteed> {
662 self.inner.borrow_mut().emit_stashed_diagnostics()
665 /// Construct a builder with the `msg` at the level appropriate for the specific `EmissionGuarantee`.
666 #[rustc_lint_diagnostics]
668 pub fn struct_diagnostic<G: EmissionGuarantee>(
670 msg: impl Into<DiagnosticMessage>,
671 ) -> DiagnosticBuilder<'_, G> {
672 G::make_diagnostic_builder(self, msg)
675 /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
677 /// Attempting to `.emit()` the builder will only emit if either:
678 /// * `can_emit_warnings` is `true`
679 /// * `is_force_warn` was set in `DiagnosticId::Lint`
680 #[rustc_lint_diagnostics]
682 pub fn struct_span_warn(
684 span: impl Into<MultiSpan>,
685 msg: impl Into<DiagnosticMessage>,
686 ) -> DiagnosticBuilder<'_, ()> {
687 let mut result = self.struct_warn(msg);
688 result.set_span(span);
692 /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
693 /// The `id` is used for lint emissions which should also fulfill a lint expectation.
695 /// Attempting to `.emit()` the builder will only emit if either:
696 /// * `can_emit_warnings` is `true`
697 /// * `is_force_warn` was set in `DiagnosticId::Lint`
699 pub fn struct_span_warn_with_expectation(
701 span: impl Into<MultiSpan>,
702 msg: impl Into<DiagnosticMessage>,
703 id: LintExpectationId,
704 ) -> DiagnosticBuilder<'_, ()> {
705 let mut result = self.struct_warn_with_expectation(msg, id);
706 result.set_span(span);
710 /// Construct a builder at the `Allow` level at the given `span` and with the `msg`.
711 #[rustc_lint_diagnostics]
713 pub fn struct_span_allow(
715 span: impl Into<MultiSpan>,
716 msg: impl Into<DiagnosticMessage>,
717 ) -> DiagnosticBuilder<'_, ()> {
718 let mut result = self.struct_allow(msg);
719 result.set_span(span);
723 /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
724 /// Also include a code.
725 #[rustc_lint_diagnostics]
727 pub fn struct_span_warn_with_code(
729 span: impl Into<MultiSpan>,
730 msg: impl Into<DiagnosticMessage>,
732 ) -> DiagnosticBuilder<'_, ()> {
733 let mut result = self.struct_span_warn(span, msg);
738 /// Construct a builder at the `Warning` level with the `msg`.
740 /// Attempting to `.emit()` the builder will only emit if either:
741 /// * `can_emit_warnings` is `true`
742 /// * `is_force_warn` was set in `DiagnosticId::Lint`
743 #[rustc_lint_diagnostics]
745 pub fn struct_warn(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> {
746 DiagnosticBuilder::new(self, Level::Warning(None), msg)
749 /// Construct a builder at the `Warning` level with the `msg`. The `id` is used for
750 /// lint emissions which should also fulfill a lint expectation.
752 /// Attempting to `.emit()` the builder will only emit if either:
753 /// * `can_emit_warnings` is `true`
754 /// * `is_force_warn` was set in `DiagnosticId::Lint`
756 pub fn struct_warn_with_expectation(
758 msg: impl Into<DiagnosticMessage>,
759 id: LintExpectationId,
760 ) -> DiagnosticBuilder<'_, ()> {
761 DiagnosticBuilder::new(self, Level::Warning(Some(id)), msg)
764 /// Construct a builder at the `Allow` level with the `msg`.
765 #[rustc_lint_diagnostics]
766 pub fn struct_allow(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> {
767 DiagnosticBuilder::new(self, Level::Allow, msg)
770 /// Construct a builder at the `Expect` level with the `msg`.
771 #[rustc_lint_diagnostics]
773 pub fn struct_expect(
775 msg: impl Into<DiagnosticMessage>,
776 id: LintExpectationId,
777 ) -> DiagnosticBuilder<'_, ()> {
778 DiagnosticBuilder::new(self, Level::Expect(id), msg)
781 /// Construct a builder at the `Error` level at the given `span` and with the `msg`.
782 #[rustc_lint_diagnostics]
784 pub fn struct_span_err(
786 span: impl Into<MultiSpan>,
787 msg: impl Into<DiagnosticMessage>,
788 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
789 let mut result = self.struct_err(msg);
790 result.set_span(span);
794 /// Construct a builder at the `Error` level at the given `span`, with the `msg`, and `code`.
795 #[rustc_lint_diagnostics]
797 pub fn struct_span_err_with_code(
799 span: impl Into<MultiSpan>,
800 msg: impl Into<DiagnosticMessage>,
802 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
803 let mut result = self.struct_span_err(span, msg);
808 /// Construct a builder at the `Error` level with the `msg`.
809 // FIXME: This method should be removed (every error should have an associated error code).
810 #[rustc_lint_diagnostics]
814 msg: impl Into<DiagnosticMessage>,
815 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
816 DiagnosticBuilder::new_guaranteeing_error::<_, { Level::Error { lint: false } }>(self, msg)
819 /// This should only be used by `rustc_middle::lint::struct_lint_level`. Do not use it for hard errors.
822 pub fn struct_err_lint(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> {
823 DiagnosticBuilder::new(self, Level::Error { lint: true }, msg)
826 /// Construct a builder at the `Error` level with the `msg` and the `code`.
827 #[rustc_lint_diagnostics]
829 pub fn struct_err_with_code(
831 msg: impl Into<DiagnosticMessage>,
833 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
834 let mut result = self.struct_err(msg);
839 /// Construct a builder at the `Warn` level with the `msg` and the `code`.
840 #[rustc_lint_diagnostics]
842 pub fn struct_warn_with_code(
844 msg: impl Into<DiagnosticMessage>,
846 ) -> DiagnosticBuilder<'_, ()> {
847 let mut result = self.struct_warn(msg);
852 /// Construct a builder at the `Fatal` level at the given `span` and with the `msg`.
853 #[rustc_lint_diagnostics]
855 pub fn struct_span_fatal(
857 span: impl Into<MultiSpan>,
858 msg: impl Into<DiagnosticMessage>,
859 ) -> DiagnosticBuilder<'_, !> {
860 let mut result = self.struct_fatal(msg);
861 result.set_span(span);
865 /// Construct a builder at the `Fatal` level at the given `span`, with the `msg`, and `code`.
866 #[rustc_lint_diagnostics]
867 pub fn struct_span_fatal_with_code(
869 span: impl Into<MultiSpan>,
870 msg: impl Into<DiagnosticMessage>,
872 ) -> DiagnosticBuilder<'_, !> {
873 let mut result = self.struct_span_fatal(span, msg);
878 /// Construct a builder at the `Error` level with the `msg`.
879 #[rustc_lint_diagnostics]
880 pub fn struct_fatal(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, !> {
881 DiagnosticBuilder::new_fatal(self, msg)
884 /// Construct a builder at the `Help` level with the `msg`.
885 #[rustc_lint_diagnostics]
886 pub fn struct_help(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> {
887 DiagnosticBuilder::new(self, Level::Help, msg)
890 /// Construct a builder at the `Note` level with the `msg`.
891 #[rustc_lint_diagnostics]
893 pub fn struct_note_without_error(
895 msg: impl Into<DiagnosticMessage>,
896 ) -> DiagnosticBuilder<'_, ()> {
897 DiagnosticBuilder::new(self, Level::Note, msg)
900 #[rustc_lint_diagnostics]
901 pub fn span_fatal(&self, span: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>) -> ! {
902 self.emit_diag_at_span(Diagnostic::new(Fatal, msg), span);
906 #[rustc_lint_diagnostics]
908 pub fn span_fatal_with_code(
910 span: impl Into<MultiSpan>,
911 msg: impl Into<DiagnosticMessage>,
914 self.emit_diag_at_span(Diagnostic::new_with_code(Fatal, Some(code), msg), span);
918 #[rustc_lint_diagnostics]
922 span: impl Into<MultiSpan>,
923 msg: impl Into<DiagnosticMessage>,
924 ) -> ErrorGuaranteed {
925 self.emit_diag_at_span(Diagnostic::new(Error { lint: false }, msg), span).unwrap()
928 #[rustc_lint_diagnostics]
930 pub fn span_err_with_code(
932 span: impl Into<MultiSpan>,
933 msg: impl Into<DiagnosticMessage>,
936 self.emit_diag_at_span(
937 Diagnostic::new_with_code(Error { lint: false }, Some(code), msg),
942 #[rustc_lint_diagnostics]
944 pub fn span_warn(&self, span: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>) {
945 self.emit_diag_at_span(Diagnostic::new(Warning(None), msg), span);
948 #[rustc_lint_diagnostics]
950 pub fn span_warn_with_code(
952 span: impl Into<MultiSpan>,
953 msg: impl Into<DiagnosticMessage>,
956 self.emit_diag_at_span(Diagnostic::new_with_code(Warning(None), Some(code), msg), span);
960 pub fn span_bug(&self, span: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>) -> ! {
961 self.inner.borrow_mut().span_bug(span, msg)
965 pub fn delay_span_bug(
967 span: impl Into<MultiSpan>,
968 msg: impl Into<DiagnosticMessage>,
969 ) -> ErrorGuaranteed {
970 self.inner.borrow_mut().delay_span_bug(span, msg)
973 // FIXME(eddyb) note the comment inside `impl Drop for HandlerInner`, that's
974 // where the explanation of what "good path" is (also, it should be renamed).
976 pub fn delay_good_path_bug(&self, msg: impl Into<DiagnosticMessage>) {
977 self.inner.borrow_mut().delay_good_path_bug(msg)
981 pub fn span_bug_no_panic(&self, span: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>) {
982 self.emit_diag_at_span(Diagnostic::new(Bug, msg), span);
986 pub fn span_note_without_error(
988 span: impl Into<MultiSpan>,
989 msg: impl Into<DiagnosticMessage>,
991 self.emit_diag_at_span(Diagnostic::new(Note, msg), span);
995 pub fn span_note_diag(
998 msg: impl Into<DiagnosticMessage>,
999 ) -> DiagnosticBuilder<'_, ()> {
1000 let mut db = DiagnosticBuilder::new(self, Note, msg);
1005 // NOTE: intentionally doesn't raise an error so rustc_codegen_ssa only reports fatal errors in the main thread
1006 pub fn fatal(&self, msg: impl Into<DiagnosticMessage>) -> FatalError {
1007 self.inner.borrow_mut().fatal(msg)
1010 pub fn err(&self, msg: impl Into<DiagnosticMessage>) -> ErrorGuaranteed {
1011 self.inner.borrow_mut().err(msg)
1014 pub fn warn(&self, msg: impl Into<DiagnosticMessage>) {
1015 let mut db = DiagnosticBuilder::new(self, Warning(None), msg);
1019 pub fn note_without_error(&self, msg: impl Into<DiagnosticMessage>) {
1020 DiagnosticBuilder::new(self, Note, msg).emit();
1023 pub fn bug(&self, msg: impl Into<DiagnosticMessage>) -> ! {
1024 self.inner.borrow_mut().bug(msg)
1028 pub fn err_count(&self) -> usize {
1029 self.inner.borrow().err_count()
1032 pub fn has_errors(&self) -> Option<ErrorGuaranteed> {
1033 if self.inner.borrow().has_errors() { Some(ErrorGuaranteed(())) } else { None }
1035 pub fn has_errors_or_lint_errors(&self) -> Option<ErrorGuaranteed> {
1036 if self.inner.borrow().has_errors_or_lint_errors() {
1037 Some(ErrorGuaranteed(()))
1042 pub fn has_errors_or_delayed_span_bugs(&self) -> bool {
1043 self.inner.borrow().has_errors_or_delayed_span_bugs()
1046 pub fn print_error_count(&self, registry: &Registry) {
1047 self.inner.borrow_mut().print_error_count(registry)
1050 pub fn take_future_breakage_diagnostics(&self) -> Vec<Diagnostic> {
1051 std::mem::take(&mut self.inner.borrow_mut().future_breakage_diagnostics)
1054 pub fn abort_if_errors(&self) {
1055 self.inner.borrow_mut().abort_if_errors()
1058 /// `true` if we haven't taught a diagnostic with this code already.
1059 /// The caller must then teach the user about such a diagnostic.
1061 /// Used to suppress emitting the same error multiple times with extended explanation when
1062 /// calling `-Zteach`.
1063 pub fn must_teach(&self, code: &DiagnosticId) -> bool {
1064 self.inner.borrow_mut().must_teach(code)
1067 pub fn force_print_diagnostic(&self, db: Diagnostic) {
1068 self.inner.borrow_mut().force_print_diagnostic(db)
1071 pub fn emit_diagnostic(&self, diagnostic: &mut Diagnostic) -> Option<ErrorGuaranteed> {
1072 self.inner.borrow_mut().emit_diagnostic(diagnostic)
1075 pub fn emit_err<'a>(&'a self, err: impl IntoDiagnostic<'a>) -> ErrorGuaranteed {
1076 self.create_err(err).emit()
1079 pub fn create_err<'a>(
1081 err: impl IntoDiagnostic<'a>,
1082 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
1083 err.into_diagnostic(self)
1086 pub fn create_warning<'a>(
1088 warning: impl IntoDiagnostic<'a, ()>,
1089 ) -> DiagnosticBuilder<'a, ()> {
1090 warning.into_diagnostic(self)
1093 pub fn emit_warning<'a>(&'a self, warning: impl IntoDiagnostic<'a, ()>) {
1094 self.create_warning(warning).emit()
1097 pub fn create_fatal<'a>(
1099 fatal: impl IntoDiagnostic<'a, !>,
1100 ) -> DiagnosticBuilder<'a, !> {
1101 fatal.into_diagnostic(self)
1104 pub fn emit_fatal<'a>(&'a self, fatal: impl IntoDiagnostic<'a, !>) -> ! {
1105 self.create_fatal(fatal).emit()
1108 fn emit_diag_at_span(
1110 mut diag: Diagnostic,
1111 sp: impl Into<MultiSpan>,
1112 ) -> Option<ErrorGuaranteed> {
1113 let mut inner = self.inner.borrow_mut();
1114 inner.emit_diagnostic(diag.set_span(sp))
1117 pub fn emit_artifact_notification(&self, path: &Path, artifact_type: &str) {
1118 self.inner.borrow_mut().emit_artifact_notification(path, artifact_type)
1121 pub fn emit_future_breakage_report(&self, diags: Vec<Diagnostic>) {
1122 self.inner.borrow_mut().emitter.emit_future_breakage_report(diags)
1125 pub fn emit_unused_externs(
1127 lint_level: rustc_lint_defs::Level,
1129 unused_externs: &[&str],
1131 let mut inner = self.inner.borrow_mut();
1133 if loud && lint_level.is_error() {
1134 inner.bump_err_count();
1137 inner.emit_unused_externs(lint_level, unused_externs)
1140 pub fn update_unstable_expectation_id(
1142 unstable_to_stable: &FxHashMap<LintExpectationId, LintExpectationId>,
1144 let mut inner = self.inner.borrow_mut();
1145 let diags = std::mem::take(&mut inner.unstable_expect_diagnostics);
1146 inner.check_unstable_expect_diagnostics = true;
1148 if !diags.is_empty() {
1149 inner.suppressed_expected_diag = true;
1150 for mut diag in diags.into_iter() {
1151 diag.update_unstable_expectation_id(unstable_to_stable);
1153 // Here the diagnostic is given back to `emit_diagnostic` where it was first
1154 // intercepted. Now it should be processed as usual, since the unstable expectation
1155 // id is now stable.
1156 inner.emit_diagnostic(&mut diag);
1161 .stashed_diagnostics
1163 .for_each(|diag| diag.update_unstable_expectation_id(unstable_to_stable));
1165 .future_breakage_diagnostics
1167 .for_each(|diag| diag.update_unstable_expectation_id(unstable_to_stable));
1170 /// This methods steals all [`LintExpectationId`]s that are stored inside
1171 /// [`HandlerInner`] and indicate that the linked expectation has been fulfilled.
1173 pub fn steal_fulfilled_expectation_ids(&self) -> FxHashSet<LintExpectationId> {
1175 self.inner.borrow().unstable_expect_diagnostics.is_empty(),
1176 "`HandlerInner::unstable_expect_diagnostics` should be empty at this point",
1178 std::mem::take(&mut self.inner.borrow_mut().fulfilled_expectations)
1181 pub fn flush_delayed(&self) {
1182 let mut inner = self.inner.lock();
1183 let bugs = std::mem::replace(&mut inner.delayed_span_bugs, Vec::new());
1184 inner.flush_delayed(bugs, "no errors encountered even though `delay_span_bug` issued");
1189 fn must_teach(&mut self, code: &DiagnosticId) -> bool {
1190 self.taught_diagnostics.insert(code.clone())
1193 fn force_print_diagnostic(&mut self, mut db: Diagnostic) {
1194 self.emitter.emit_diagnostic(&mut db);
1197 /// Emit all stashed diagnostics.
1198 fn emit_stashed_diagnostics(&mut self) -> Option<ErrorGuaranteed> {
1199 let has_errors = self.has_errors();
1200 let diags = self.stashed_diagnostics.drain(..).map(|x| x.1).collect::<Vec<_>>();
1201 let mut reported = None;
1202 for mut diag in diags {
1203 // Decrement the count tracking the stash; emitting will increment it.
1204 if diag.is_error() {
1205 if matches!(diag.level, Level::Error { lint: true }) {
1206 self.lint_err_count -= 1;
1208 self.err_count -= 1;
1211 if diag.is_force_warn() {
1212 self.warn_count -= 1;
1214 // Unless they're forced, don't flush stashed warnings when
1215 // there are errors, to avoid causing warning overload. The
1216 // stash would've been stolen already if it were important.
1222 let reported_this = self.emit_diagnostic(&mut diag);
1223 reported = reported.or(reported_this);
1228 // FIXME(eddyb) this should ideally take `diagnostic` by value.
1229 fn emit_diagnostic(&mut self, diagnostic: &mut Diagnostic) -> Option<ErrorGuaranteed> {
1230 // The `LintExpectationId` can be stable or unstable depending on when it was created.
1231 // Diagnostics created before the definition of `HirId`s are unstable and can not yet
1232 // be stored. Instead, they are buffered until the `LintExpectationId` is replaced by
1233 // a stable one by the `LintLevelsBuilder`.
1234 if let Some(LintExpectationId::Unstable { .. }) = diagnostic.level.get_expectation_id() {
1235 self.unstable_expect_diagnostics.push(diagnostic.clone());
1239 if diagnostic.level == Level::DelayedBug {
1240 // FIXME(eddyb) this should check for `has_errors` and stop pushing
1241 // once *any* errors were emitted (and truncate `delayed_span_bugs`
1242 // when an error is first emitted, also), but maybe there's a case
1243 // in which that's not sound? otherwise this is really inefficient.
1244 self.delayed_span_bugs.push(diagnostic.clone());
1246 if !self.flags.report_delayed_bugs {
1247 return Some(ErrorGuaranteed::unchecked_claim_error_was_emitted());
1251 if diagnostic.has_future_breakage() {
1252 self.future_breakage_diagnostics.push(diagnostic.clone());
1255 if let Some(expectation_id) = diagnostic.level.get_expectation_id() {
1256 self.suppressed_expected_diag = true;
1257 self.fulfilled_expectations.insert(expectation_id.normalize());
1260 if matches!(diagnostic.level, Warning(_))
1261 && !self.flags.can_emit_warnings
1262 && !diagnostic.is_force_warn()
1264 if diagnostic.has_future_breakage() {
1265 (*TRACK_DIAGNOSTICS)(diagnostic);
1270 (*TRACK_DIAGNOSTICS)(diagnostic);
1272 if matches!(diagnostic.level, Level::Expect(_) | Level::Allow) {
1276 if let Some(ref code) = diagnostic.code {
1277 self.emitted_diagnostic_codes.insert(code.clone());
1280 let already_emitted = |this: &mut Self| {
1281 let mut hasher = StableHasher::new();
1282 diagnostic.hash(&mut hasher);
1283 let diagnostic_hash = hasher.finish();
1284 !this.emitted_diagnostics.insert(diagnostic_hash)
1287 // Only emit the diagnostic if we've been asked to deduplicate or
1288 // haven't already emitted an equivalent diagnostic.
1289 if !(self.flags.deduplicate_diagnostics && already_emitted(self)) {
1290 debug!(?diagnostic);
1291 debug!(?self.emitted_diagnostics);
1292 let already_emitted_sub = |sub: &mut SubDiagnostic| {
1294 if sub.level != Level::OnceNote {
1297 let mut hasher = StableHasher::new();
1298 sub.hash(&mut hasher);
1299 let diagnostic_hash = hasher.finish();
1300 debug!(?diagnostic_hash);
1301 !self.emitted_diagnostics.insert(diagnostic_hash)
1304 diagnostic.children.drain_filter(already_emitted_sub).for_each(|_| {});
1306 self.emitter.emit_diagnostic(&diagnostic);
1307 if diagnostic.is_error() {
1308 self.deduplicated_err_count += 1;
1309 } else if let Warning(_) = diagnostic.level {
1310 self.deduplicated_warn_count += 1;
1313 if diagnostic.is_error() {
1314 if matches!(diagnostic.level, Level::Error { lint: true }) {
1315 self.bump_lint_err_count();
1317 self.bump_err_count();
1320 Some(ErrorGuaranteed::unchecked_claim_error_was_emitted())
1322 self.bump_warn_count();
1328 fn emit_artifact_notification(&mut self, path: &Path, artifact_type: &str) {
1329 self.emitter.emit_artifact_notification(path, artifact_type);
1332 fn emit_unused_externs(&mut self, lint_level: rustc_lint_defs::Level, unused_externs: &[&str]) {
1333 self.emitter.emit_unused_externs(lint_level, unused_externs);
1336 fn treat_err_as_bug(&self) -> bool {
1337 self.flags.treat_err_as_bug.map_or(false, |c| {
1338 self.err_count() + self.lint_err_count + self.delayed_bug_count() >= c.get()
1342 fn delayed_bug_count(&self) -> usize {
1343 self.delayed_span_bugs.len() + self.delayed_good_path_bugs.len()
1346 fn print_error_count(&mut self, registry: &Registry) {
1347 self.emit_stashed_diagnostics();
1349 let warnings = match self.deduplicated_warn_count {
1351 1 => "1 warning emitted".to_string(),
1352 count => format!("{count} warnings emitted"),
1354 let errors = match self.deduplicated_err_count {
1356 1 => "aborting due to previous error".to_string(),
1357 count => format!("aborting due to {count} previous errors"),
1359 if self.treat_err_as_bug() {
1363 match (errors.len(), warnings.len()) {
1365 (0, _) => self.emitter.emit_diagnostic(&Diagnostic::new(
1366 Level::Warning(None),
1367 DiagnosticMessage::Str(warnings),
1370 let _ = self.fatal(&errors);
1373 let _ = self.fatal(&format!("{}; {}", &errors, &warnings));
1377 let can_show_explain = self.emitter.should_show_explain();
1378 let are_there_diagnostics = !self.emitted_diagnostic_codes.is_empty();
1379 if can_show_explain && are_there_diagnostics {
1380 let mut error_codes = self
1381 .emitted_diagnostic_codes
1383 .filter_map(|x| match &x {
1384 DiagnosticId::Error(s)
1385 if registry.try_find_description(s).map_or(false, |o| o.is_some()) =>
1391 .collect::<Vec<_>>();
1392 if !error_codes.is_empty() {
1394 if error_codes.len() > 1 {
1395 let limit = if error_codes.len() > 9 { 9 } else { error_codes.len() };
1396 self.failure(&format!(
1397 "Some errors have detailed explanations: {}{}",
1398 error_codes[..limit].join(", "),
1399 if error_codes.len() > 9 { "..." } else { "." }
1401 self.failure(&format!(
1402 "For more information about an error, try \
1403 `rustc --explain {}`.",
1407 self.failure(&format!(
1408 "For more information about this error, try \
1409 `rustc --explain {}`.",
1417 fn stash(&mut self, key: (Span, StashKey), diagnostic: Diagnostic) {
1418 // Track the diagnostic for counts, but don't panic-if-treat-err-as-bug
1419 // yet; that happens when we actually emit the diagnostic.
1420 if diagnostic.is_error() {
1421 if matches!(diagnostic.level, Level::Error { lint: true }) {
1422 self.lint_err_count += 1;
1424 self.err_count += 1;
1427 // Warnings are only automatically flushed if they're forced.
1428 if diagnostic.is_force_warn() {
1429 self.warn_count += 1;
1433 // FIXME(Centril, #69537): Consider reintroducing panic on overwriting a stashed diagnostic
1434 // if/when we have a more robust macro-friendly replacement for `(span, key)` as a key.
1435 // See the PR for a discussion.
1436 self.stashed_diagnostics.insert(key, diagnostic);
1439 fn steal(&mut self, key: (Span, StashKey)) -> Option<Diagnostic> {
1440 let diagnostic = self.stashed_diagnostics.remove(&key)?;
1441 if diagnostic.is_error() {
1442 if matches!(diagnostic.level, Level::Error { lint: true }) {
1443 self.lint_err_count -= 1;
1445 self.err_count -= 1;
1448 if diagnostic.is_force_warn() {
1449 self.warn_count -= 1;
1456 fn err_count(&self) -> usize {
1460 fn has_errors(&self) -> bool {
1461 self.err_count() > 0
1463 fn has_errors_or_lint_errors(&self) -> bool {
1464 self.has_errors() || self.lint_err_count > 0
1466 fn has_errors_or_delayed_span_bugs(&self) -> bool {
1467 self.has_errors() || !self.delayed_span_bugs.is_empty()
1469 fn has_any_message(&self) -> bool {
1470 self.err_count() > 0 || self.lint_err_count > 0 || self.warn_count > 0
1473 fn abort_if_errors(&mut self) {
1474 self.emit_stashed_diagnostics();
1476 if self.has_errors() {
1482 fn span_bug(&mut self, sp: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>) -> ! {
1483 self.emit_diag_at_span(Diagnostic::new(Bug, msg), sp);
1484 panic::panic_any(ExplicitBug);
1487 fn emit_diag_at_span(&mut self, mut diag: Diagnostic, sp: impl Into<MultiSpan>) {
1488 self.emit_diagnostic(diag.set_span(sp));
1494 sp: impl Into<MultiSpan>,
1495 msg: impl Into<DiagnosticMessage>,
1496 ) -> ErrorGuaranteed {
1497 // This is technically `self.treat_err_as_bug()` but `delay_span_bug` is called before
1498 // incrementing `err_count` by one, so we need to +1 the comparing.
1499 // FIXME: Would be nice to increment err_count in a more coherent way.
1500 if self.flags.treat_err_as_bug.map_or(false, |c| {
1501 self.err_count() + self.lint_err_count + self.delayed_bug_count() + 1 >= c.get()
1503 // FIXME: don't abort here if report_delayed_bugs is off
1504 self.span_bug(sp, msg);
1506 let mut diagnostic = Diagnostic::new(Level::DelayedBug, msg);
1507 diagnostic.set_span(sp.into());
1508 diagnostic.note(&format!("delayed at {}", std::panic::Location::caller()));
1509 self.emit_diagnostic(&mut diagnostic).unwrap()
1512 // FIXME(eddyb) note the comment inside `impl Drop for HandlerInner`, that's
1513 // where the explanation of what "good path" is (also, it should be renamed).
1514 fn delay_good_path_bug(&mut self, msg: impl Into<DiagnosticMessage>) {
1515 let mut diagnostic = Diagnostic::new(Level::DelayedBug, msg);
1516 if self.flags.report_delayed_bugs {
1517 self.emit_diagnostic(&mut diagnostic);
1519 let backtrace = std::backtrace::Backtrace::force_capture();
1520 self.delayed_good_path_bugs.push(DelayedDiagnostic::with_backtrace(diagnostic, backtrace));
1523 fn failure(&mut self, msg: impl Into<DiagnosticMessage>) {
1524 self.emit_diagnostic(&mut Diagnostic::new(FailureNote, msg));
1527 fn fatal(&mut self, msg: impl Into<DiagnosticMessage>) -> FatalError {
1528 self.emit(Fatal, msg);
1532 fn err(&mut self, msg: impl Into<DiagnosticMessage>) -> ErrorGuaranteed {
1533 self.emit(Error { lint: false }, msg)
1536 /// Emit an error; level should be `Error` or `Fatal`.
1537 fn emit(&mut self, level: Level, msg: impl Into<DiagnosticMessage>) -> ErrorGuaranteed {
1538 if self.treat_err_as_bug() {
1541 self.emit_diagnostic(&mut Diagnostic::new(level, msg)).unwrap()
1544 fn bug(&mut self, msg: impl Into<DiagnosticMessage>) -> ! {
1545 self.emit_diagnostic(&mut Diagnostic::new(Bug, msg));
1546 panic::panic_any(ExplicitBug);
1551 bugs: impl IntoIterator<Item = Diagnostic>,
1552 explanation: impl Into<DiagnosticMessage> + Copy,
1554 let mut no_bugs = true;
1555 for mut bug in bugs {
1557 // Put the overall explanation before the `DelayedBug`s, to
1558 // frame them better (e.g. separate warnings from them).
1559 self.emit_diagnostic(&mut Diagnostic::new(Bug, explanation));
1563 // "Undelay" the `DelayedBug`s (into plain `Bug`s).
1564 if bug.level != Level::DelayedBug {
1565 // NOTE(eddyb) not panicking here because we're already producing
1566 // an ICE, and the more information the merrier.
1568 "`flushed_delayed` got diagnostic with level {:?}, \
1569 instead of the expected `DelayedBug`",
1573 bug.level = Level::Bug;
1575 self.emit_diagnostic(&mut bug);
1578 // Panic with `ExplicitBug` to avoid "unexpected panic" messages.
1580 panic::panic_any(ExplicitBug);
1584 fn bump_lint_err_count(&mut self) {
1585 self.lint_err_count += 1;
1586 self.panic_if_treat_err_as_bug();
1589 fn bump_err_count(&mut self) {
1590 self.err_count += 1;
1591 self.panic_if_treat_err_as_bug();
1594 fn bump_warn_count(&mut self) {
1595 self.warn_count += 1;
1598 fn panic_if_treat_err_as_bug(&self) {
1599 if self.treat_err_as_bug() {
1601 self.err_count() + self.lint_err_count,
1602 self.delayed_bug_count(),
1603 self.flags.treat_err_as_bug.map(|c| c.get()).unwrap_or(0),
1605 (1, 0, 1) => panic!("aborting due to `-Z treat-err-as-bug=1`"),
1606 (0, 1, 1) => panic!("aborting due delayed bug with `-Z treat-err-as-bug=1`"),
1607 (count, delayed_count, as_bug) => {
1608 if delayed_count > 0 {
1610 "aborting after {} errors and {} delayed bugs due to `-Z treat-err-as-bug={}`",
1611 count, delayed_count, as_bug,
1615 "aborting after {} errors due to `-Z treat-err-as-bug={}`",
1625 struct DelayedDiagnostic {
1630 impl DelayedDiagnostic {
1631 fn with_backtrace(diagnostic: Diagnostic, backtrace: Backtrace) -> Self {
1632 DelayedDiagnostic { inner: diagnostic, note: backtrace }
1635 fn decorate(mut self) -> Diagnostic {
1636 self.inner.note(&format!("delayed at {}", self.note));
1641 #[derive(Copy, PartialEq, Eq, Clone, Hash, Debug, Encodable, Decodable)]
1647 /// If this error comes from a lint, don't abort compilation even when abort_if_errors() is called.
1650 /// This [`LintExpectationId`] is used for expected lint diagnostics, which should
1651 /// also emit a warning due to the `force-warn` flag. In all other cases this should
1653 Warning(Option<LintExpectationId>),
1655 /// A note that is only emitted once.
1660 Expect(LintExpectationId),
1663 impl fmt::Display for Level {
1664 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1665 self.to_str().fmt(f)
1670 fn color(self) -> ColorSpec {
1671 let mut spec = ColorSpec::new();
1673 Bug | DelayedBug | Fatal | Error { .. } => {
1674 spec.set_fg(Some(Color::Red)).set_intense(true);
1677 spec.set_fg(Some(Color::Yellow)).set_intense(cfg!(windows));
1679 Note | OnceNote => {
1680 spec.set_fg(Some(Color::Green)).set_intense(true);
1683 spec.set_fg(Some(Color::Cyan)).set_intense(true);
1686 Allow | Expect(_) => unreachable!(),
1691 pub fn to_str(self) -> &'static str {
1693 Bug | DelayedBug => "error: internal compiler error",
1694 Fatal | Error { .. } => "error",
1695 Warning(_) => "warning",
1696 Note | OnceNote => "note",
1698 FailureNote => "failure-note",
1699 Allow => panic!("Shouldn't call on allowed error"),
1700 Expect(_) => panic!("Shouldn't call on expected error"),
1704 pub fn is_failure_note(&self) -> bool {
1705 matches!(*self, FailureNote)
1708 pub fn get_expectation_id(&self) -> Option<LintExpectationId> {
1710 Level::Expect(id) | Level::Warning(Some(id)) => Some(*id),
1716 // FIXME(eddyb) this doesn't belong here AFAICT, should be moved to callsite.
1717 pub fn add_elided_lifetime_in_path_suggestion(
1718 source_map: &SourceMap,
1719 diag: &mut Diagnostic,
1722 incl_angl_brckt: bool,
1723 insertion_span: Span,
1725 diag.span_label(path_span, format!("expected lifetime parameter{}", pluralize!(n)));
1726 if !source_map.is_span_accessible(insertion_span) {
1727 // Do not try to suggest anything if generated by a proc-macro.
1730 let anon_lts = vec!["'_"; n].join(", ");
1732 if incl_angl_brckt { format!("<{}>", anon_lts) } else { format!("{}, ", anon_lts) };
1733 diag.span_suggestion_verbose(
1734 insertion_span.shrink_to_hi(),
1735 &format!("indicate the anonymous lifetime{}", pluralize!(n)),
1737 Applicability::MachineApplicable,
1741 /// Useful type to use with `Result<>` indicate that an error has already
1742 /// been reported to the user, so no need to continue checking.
1743 #[derive(Clone, Copy, Debug, Encodable, Decodable, Hash, PartialEq, Eq, PartialOrd, Ord)]
1744 #[derive(HashStable_Generic)]
1745 pub struct ErrorGuaranteed(());
1747 impl ErrorGuaranteed {
1748 /// To be used only if you really know what you are doing... ideally, we would find a way to
1749 /// eliminate all calls to this method.
1750 pub fn unchecked_claim_error_was_emitted() -> Self {