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(is_terminal)]
9 #![feature(adt_const_params)]
10 #![feature(let_chains)]
11 #![feature(never_type)]
12 #![feature(result_option_inspect)]
13 #![feature(rustc_attrs)]
14 #![allow(incomplete_features)]
17 extern crate rustc_macros;
22 pub use emitter::ColorConfig;
24 use rustc_lint_defs::LintExpectationId;
27 use emitter::{is_case_difference, Emitter, EmitterWriter};
28 use registry::Registry;
29 use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet};
30 use rustc_data_structures::stable_hasher::StableHasher;
31 use rustc_data_structures::sync::{self, Lock, Lrc};
32 use rustc_data_structures::AtomicRef;
33 pub use rustc_error_messages::{
34 fallback_fluent_bundle, fluent, fluent_bundle, DelayDm, DiagnosticMessage, FluentBundle,
35 LanguageIdentifier, LazyFallbackBundle, MultiSpan, SpanLabel, SubdiagnosticMessage,
36 DEFAULT_LOCALE_RESOURCES,
38 pub use rustc_lint_defs::{pluralize, Applicability};
39 use rustc_span::source_map::SourceMap;
40 use rustc_span::HashStableContext;
41 use rustc_span::{Loc, Span};
45 use std::num::NonZeroUsize;
48 use std::{error, fmt};
50 use termcolor::{Color, ColorSpec};
52 pub mod annotate_snippet_emitter_writer;
54 mod diagnostic_builder;
64 pub use diagnostic_builder::IntoDiagnostic;
65 pub use snippet::Style;
67 pub type PErr<'a> = DiagnosticBuilder<'a, ErrorGuaranteed>;
68 pub type PResult<'a, T> = Result<T, PErr<'a>>;
70 // `PResult` is used a lot. Make sure it doesn't unintentionally get bigger.
71 // (See also the comment on `DiagnosticBuilderInner`'s `diagnostic` field.)
72 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
73 rustc_data_structures::static_assert_size!(PResult<'_, ()>, 16);
74 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
75 rustc_data_structures::static_assert_size!(PResult<'_, bool>, 16);
77 #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, Encodable, Decodable)]
78 pub enum SuggestionStyle {
79 /// Hide the suggested code when displaying this suggestion inline.
81 /// Always hide the suggested code but display the message.
83 /// Do not display this suggestion in the cli output, it is only meant for tools.
85 /// Always show the suggested code.
86 /// This will *not* show the code if the suggestion is inline *and* the suggested code is
89 /// Always show the suggested code independently.
93 impl SuggestionStyle {
94 fn hide_inline(&self) -> bool {
95 !matches!(*self, SuggestionStyle::ShowCode)
99 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
100 pub struct CodeSuggestion {
101 /// Each substitute can have multiple variants due to multiple
102 /// applicable suggestions
104 /// `foo.bar` might be replaced with `a.b` or `x.y` by replacing
105 /// `foo` and `bar` on their own:
107 /// ```ignore (illustrative)
109 /// Substitution { parts: vec![(0..3, "a"), (4..7, "b")] },
110 /// Substitution { parts: vec![(0..3, "x"), (4..7, "y")] },
114 /// or by replacing the entire span:
116 /// ```ignore (illustrative)
118 /// Substitution { parts: vec![(0..7, "a.b")] },
119 /// Substitution { parts: vec![(0..7, "x.y")] },
122 pub substitutions: Vec<Substitution>,
123 pub msg: DiagnosticMessage,
124 /// Visual representation of this suggestion.
125 pub style: SuggestionStyle,
126 /// Whether or not the suggestion is approximate
128 /// Sometimes we may show suggestions with placeholders,
129 /// which are useful for users but not useful for
130 /// tools like rustfix
131 pub applicability: Applicability,
134 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
135 /// See the docs on `CodeSuggestion::substitutions`
136 pub struct Substitution {
137 pub parts: Vec<SubstitutionPart>,
140 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
141 pub struct SubstitutionPart {
146 /// Used to translate between `Span`s and byte positions within a single output line in highlighted
147 /// code of structured suggestions.
148 #[derive(Debug, Clone, Copy)]
149 pub struct SubstitutionHighlight {
154 impl SubstitutionPart {
155 pub fn is_addition(&self, sm: &SourceMap) -> bool {
156 !self.snippet.is_empty() && !self.replaces_meaningful_content(sm)
159 pub fn is_deletion(&self, sm: &SourceMap) -> bool {
160 self.snippet.trim().is_empty() && self.replaces_meaningful_content(sm)
163 pub fn is_replacement(&self, sm: &SourceMap) -> bool {
164 !self.snippet.is_empty() && self.replaces_meaningful_content(sm)
167 fn replaces_meaningful_content(&self, sm: &SourceMap) -> bool {
168 sm.span_to_snippet(self.span)
169 .map_or(!self.span.is_empty(), |snippet| !snippet.trim().is_empty())
173 impl CodeSuggestion {
174 /// Returns the assembled code suggestions, whether they should be shown with an underline
175 /// and whether the substitution only differs in capitalization.
179 ) -> Vec<(String, Vec<SubstitutionPart>, Vec<Vec<SubstitutionHighlight>>, bool)> {
180 // For the `Vec<Vec<SubstitutionHighlight>>` value, the first level of the vector
181 // corresponds to the output snippet's lines, while the second level corresponds to the
182 // substrings within that line that should be highlighted.
184 use rustc_span::{CharPos, Pos};
186 /// Append to a buffer the remainder of the line of existing source code, and return the
187 /// count of lines that have been added for accurate highlighting.
190 line_opt: Option<&Cow<'_, str>>,
192 hi_opt: Option<&Loc>,
194 let mut line_count = 0;
195 let (lo, hi_opt) = (lo.col.to_usize(), hi_opt.map(|hi| hi.col.to_usize()));
196 if let Some(line) = line_opt {
197 if let Some(lo) = line.char_indices().map(|(i, _)| i).nth(lo) {
198 let hi_opt = hi_opt.and_then(|hi| line.char_indices().map(|(i, _)| i).nth(hi));
200 Some(hi) if hi > lo => {
201 line_count = line[lo..hi].matches('\n').count();
202 buf.push_str(&line[lo..hi])
206 line_count = line[lo..].matches('\n').count();
207 buf.push_str(&line[lo..])
211 if hi_opt.is_none() {
218 assert!(!self.substitutions.is_empty());
223 // Suggestions coming from macros can have malformed spans. This is a heavy
224 // handed approach to avoid ICEs by ignoring the suggestion outright.
225 let invalid = subst.parts.iter().any(|item| sm.is_valid_span(item.span).is_err());
227 debug!("splice_lines: suggestion contains an invalid span: {:?}", subst);
232 .filter_map(|mut substitution| {
233 // Assumption: all spans are in the same file, and all spans
234 // are disjoint. Sort in ascending order.
235 substitution.parts.sort_by_key(|part| part.span.lo());
237 // Find the bounding span.
238 let lo = substitution.parts.iter().map(|part| part.span.lo()).min()?;
239 let hi = substitution.parts.iter().map(|part| part.span.hi()).max()?;
240 let bounding_span = Span::with_root_ctxt(lo, hi);
241 // The different spans might belong to different contexts, if so ignore suggestion.
242 let lines = sm.span_to_lines(bounding_span).ok()?;
243 assert!(!lines.lines.is_empty() || bounding_span.is_dummy());
245 // We can't splice anything if the source is unavailable.
246 if !sm.ensure_source_file_source_present(lines.file.clone()) {
250 let mut highlights = vec![];
251 // To build up the result, we do this for each span:
252 // - push the line segment trailing the previous span
253 // (at the beginning a "phantom" span pointing at the start of the line)
254 // - push lines between the previous and current span (if any)
255 // - if the previous and current span are not on the same line
256 // push the line segment leading up to the current span
257 // - splice in the span substitution
259 // Finally push the trailing line segment of the last span
260 let sf = &lines.file;
261 let mut prev_hi = sm.lookup_char_pos(bounding_span.lo());
262 prev_hi.col = CharPos::from_usize(0);
264 lines.lines.get(0).and_then(|line0| sf.get_line(line0.line_index));
265 let mut buf = String::new();
267 let mut line_highlight = vec![];
268 // We need to keep track of the difference between the existing code and the added
269 // or deleted code in order to point at the correct column *after* substitution.
271 for part in &substitution.parts {
272 let cur_lo = sm.lookup_char_pos(part.span.lo());
273 if prev_hi.line == cur_lo.line {
275 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, Some(&cur_lo));
277 highlights.push(std::mem::take(&mut line_highlight));
283 highlights.push(std::mem::take(&mut line_highlight));
284 let mut count = push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
286 highlights.push(std::mem::take(&mut line_highlight));
289 // push lines between the previous and current span (if any)
290 for idx in prev_hi.line..(cur_lo.line - 1) {
291 if let Some(line) = sf.get_line(idx) {
292 buf.push_str(line.as_ref());
294 highlights.push(std::mem::take(&mut line_highlight));
297 if let Some(cur_line) = sf.get_line(cur_lo.line - 1) {
298 let end = match cur_line.char_indices().nth(cur_lo.col.to_usize()) {
300 None => cur_line.len(),
302 buf.push_str(&cur_line[..end]);
305 // Add a whole line highlight per line in the snippet.
306 let len: isize = part
310 .unwrap_or(&part.snippet)
317 line_highlight.push(SubstitutionHighlight {
318 start: (cur_lo.col.0 as isize + acc) as usize,
319 end: (cur_lo.col.0 as isize + acc + len) as usize,
321 buf.push_str(&part.snippet);
322 let cur_hi = sm.lookup_char_pos(part.span.hi());
323 if prev_hi.line == cur_lo.line && cur_hi.line == cur_lo.line {
324 // Account for the difference between the width of the current code and the
325 // snippet being suggested, so that the *later* suggestions are correctly
326 // aligned on the screen.
327 acc += len - (cur_hi.col.0 - cur_lo.col.0) as isize;
330 prev_line = sf.get_line(prev_hi.line - 1);
331 for line in part.snippet.split('\n').skip(1) {
333 highlights.push(std::mem::take(&mut line_highlight));
334 let end: usize = line
341 line_highlight.push(SubstitutionHighlight { start: 0, end });
344 highlights.push(std::mem::take(&mut line_highlight));
345 let only_capitalization = is_case_difference(sm, &buf, bounding_span);
346 // if the replacement already ends with a newline, don't print the next line
347 if !buf.ends_with('\n') {
348 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
350 // remove trailing newlines
351 while buf.ends_with('\n') {
354 Some((buf, substitution.parts, highlights, only_capitalization))
360 pub use rustc_span::fatal_error::{FatalError, FatalErrorMarker};
362 /// Signifies that the compiler died with an explicit call to `.bug`
363 /// or `.span_bug` rather than a failed assertion, etc.
364 #[derive(Copy, Clone, Debug)]
365 pub struct ExplicitBug;
367 impl fmt::Display for ExplicitBug {
368 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
369 write!(f, "parser internal bug")
373 impl error::Error for ExplicitBug {}
375 pub use diagnostic::{
376 AddToDiagnostic, DecorateLint, Diagnostic, DiagnosticArg, DiagnosticArgValue, DiagnosticId,
377 DiagnosticStyledString, IntoDiagnosticArg, SubDiagnostic,
379 pub use diagnostic_builder::{DiagnosticBuilder, EmissionGuarantee, Noted};
380 pub use diagnostic_impls::{DiagnosticArgFromDisplay, DiagnosticSymbolList};
381 use std::backtrace::Backtrace;
383 /// A handler deals with errors and other compiler output.
384 /// Certain errors (fatal, bug, unimpl) may cause immediate exit,
385 /// others log errors for later reporting.
388 inner: Lock<HandlerInner>,
391 /// This inner struct exists to keep it all behind a single lock;
392 /// this is done to prevent possible deadlocks in a multi-threaded compiler,
393 /// as well as inconsistent state observation.
394 struct HandlerInner {
396 /// The number of lint errors that have been emitted.
397 lint_err_count: usize,
398 /// The number of errors that have been emitted, including duplicates.
400 /// This is not necessarily the count that's reported to the user once
401 /// compilation ends.
404 deduplicated_err_count: usize,
405 emitter: Box<dyn Emitter + sync::Send>,
406 delayed_span_bugs: Vec<Diagnostic>,
407 delayed_good_path_bugs: Vec<DelayedDiagnostic>,
408 /// This flag indicates that an expected diagnostic was emitted and suppressed.
409 /// This is used for the `delayed_good_path_bugs` check.
410 suppressed_expected_diag: bool,
412 /// This set contains the `DiagnosticId` of all emitted diagnostics to avoid
413 /// emitting the same diagnostic with extended help (`--teach`) twice, which
414 /// would be unnecessary repetition.
415 taught_diagnostics: FxHashSet<DiagnosticId>,
417 /// Used to suggest rustc --explain `<error code>`
418 emitted_diagnostic_codes: FxIndexSet<DiagnosticId>,
420 /// This set contains a hash of every diagnostic that has been emitted by
421 /// this handler. These hashes is used to avoid emitting the same error
423 emitted_diagnostics: FxHashSet<u128>,
425 /// Stashed diagnostics emitted in one stage of the compiler that may be
426 /// stolen by other stages (e.g. to improve them and add more information).
427 /// The stashed diagnostics count towards the total error count.
428 /// When `.abort_if_errors()` is called, these are also emitted.
429 stashed_diagnostics: FxIndexMap<(Span, StashKey), Diagnostic>,
431 /// The warning count, used for a recap upon finishing
432 deduplicated_warn_count: usize,
434 future_breakage_diagnostics: Vec<Diagnostic>,
436 /// The [`Self::unstable_expect_diagnostics`] should be empty when this struct is
437 /// dropped. However, it can have values if the compilation is stopped early
438 /// or is only partially executed. To avoid ICEs, like in rust#94953 we only
439 /// check if [`Self::unstable_expect_diagnostics`] is empty, if the expectation ids
440 /// have been converted.
441 check_unstable_expect_diagnostics: bool,
443 /// Expected [`Diagnostic`][diagnostic::Diagnostic]s store a [`LintExpectationId`] as part of
444 /// the lint level. [`LintExpectationId`]s created early during the compilation
445 /// (before `HirId`s have been defined) are not stable and can therefore not be
446 /// stored on disk. This buffer stores these diagnostics until the ID has been
447 /// replaced by a stable [`LintExpectationId`]. The [`Diagnostic`][diagnostic::Diagnostic]s are the
448 /// submitted for storage and added to the list of fulfilled expectations.
449 unstable_expect_diagnostics: Vec<Diagnostic>,
451 /// expected diagnostic will have the level `Expect` which additionally
452 /// carries the [`LintExpectationId`] of the expectation that can be
453 /// marked as fulfilled. This is a collection of all [`LintExpectationId`]s
454 /// that have been marked as fulfilled this way.
456 /// [RFC-2383]: https://rust-lang.github.io/rfcs/2383-lint-reasons.html
457 fulfilled_expectations: FxHashSet<LintExpectationId>,
460 /// A key denoting where from a diagnostic was stashed.
461 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
464 UnderscoreForArrayLengths,
467 /// When an invalid lifetime e.g. `'2` should be reinterpreted
468 /// as a char literal in the parser
470 /// Maybe there was a typo where a comma was forgotten before
476 fn default_track_diagnostic(_: &Diagnostic) {}
478 pub static TRACK_DIAGNOSTICS: AtomicRef<fn(&Diagnostic)> =
479 AtomicRef::new(&(default_track_diagnostic as fn(&_)));
481 #[derive(Copy, Clone, Default)]
482 pub struct HandlerFlags {
483 /// If false, warning-level lints are suppressed.
484 /// (rustc: see `--allow warnings` and `--cap-lints`)
485 pub can_emit_warnings: bool,
486 /// If true, error-level diagnostics are upgraded to bug-level.
487 /// (rustc: see `-Z treat-err-as-bug`)
488 pub treat_err_as_bug: Option<NonZeroUsize>,
489 /// If true, immediately emit diagnostics that would otherwise be buffered.
490 /// (rustc: see `-Z dont-buffer-diagnostics` and `-Z treat-err-as-bug`)
491 pub dont_buffer_diagnostics: bool,
492 /// If true, immediately print bugs registered with `delay_span_bug`.
493 /// (rustc: see `-Z report-delayed-bugs`)
494 pub report_delayed_bugs: bool,
495 /// Show macro backtraces.
496 /// (rustc: see `-Z macro-backtrace`)
497 pub macro_backtrace: bool,
498 /// If true, identical diagnostics are reported only once.
499 pub deduplicate_diagnostics: bool,
500 /// Track where errors are created. Enabled with `-Ztrack-diagnostics`.
501 pub track_diagnostics: bool,
504 impl Drop for HandlerInner {
506 self.emit_stashed_diagnostics();
508 if !self.has_errors() {
509 let bugs = std::mem::replace(&mut self.delayed_span_bugs, Vec::new());
510 self.flush_delayed(bugs, "no errors encountered even though `delay_span_bug` issued");
513 // FIXME(eddyb) this explains what `delayed_good_path_bugs` are!
514 // They're `delayed_span_bugs` but for "require some diagnostic happened"
515 // instead of "require some error happened". Sadly that isn't ideal, as
516 // lints can be `#[allow]`'d, potentially leading to this triggering.
517 // Also, "good path" should be replaced with a better naming.
518 if !self.has_any_message() && !self.suppressed_expected_diag {
519 let bugs = std::mem::replace(&mut self.delayed_good_path_bugs, Vec::new());
521 bugs.into_iter().map(DelayedDiagnostic::decorate),
522 "no warnings or errors encountered even though `delayed_good_path_bugs` issued",
526 if self.check_unstable_expect_diagnostics {
528 self.unstable_expect_diagnostics.is_empty(),
529 "all diagnostics with unstable expectations should have been converted",
536 pub fn with_tty_emitter(
537 color_config: ColorConfig,
538 can_emit_warnings: bool,
539 treat_err_as_bug: Option<NonZeroUsize>,
540 sm: Option<Lrc<SourceMap>>,
541 fluent_bundle: Option<Lrc<FluentBundle>>,
542 fallback_bundle: LazyFallbackBundle,
544 Self::with_tty_emitter_and_flags(
549 HandlerFlags { can_emit_warnings, treat_err_as_bug, ..Default::default() },
553 pub fn with_tty_emitter_and_flags(
554 color_config: ColorConfig,
555 sm: Option<Lrc<SourceMap>>,
556 fluent_bundle: Option<Lrc<FluentBundle>>,
557 fallback_bundle: LazyFallbackBundle,
560 let emitter = Box::new(EmitterWriter::stderr(
568 flags.macro_backtrace,
569 flags.track_diagnostics,
571 Self::with_emitter_and_flags(emitter, flags)
575 can_emit_warnings: bool,
576 treat_err_as_bug: Option<NonZeroUsize>,
577 emitter: Box<dyn Emitter + sync::Send>,
579 Handler::with_emitter_and_flags(
581 HandlerFlags { can_emit_warnings, treat_err_as_bug, ..Default::default() },
585 pub fn with_emitter_and_flags(
586 emitter: Box<dyn Emitter + sync::Send>,
591 inner: Lock::new(HandlerInner {
596 deduplicated_err_count: 0,
597 deduplicated_warn_count: 0,
599 delayed_span_bugs: Vec::new(),
600 delayed_good_path_bugs: Vec::new(),
601 suppressed_expected_diag: false,
602 taught_diagnostics: Default::default(),
603 emitted_diagnostic_codes: Default::default(),
604 emitted_diagnostics: Default::default(),
605 stashed_diagnostics: Default::default(),
606 future_breakage_diagnostics: Vec::new(),
607 check_unstable_expect_diagnostics: false,
608 unstable_expect_diagnostics: Vec::new(),
609 fulfilled_expectations: Default::default(),
614 /// Translate `message` eagerly with `args`.
615 pub fn eagerly_translate<'a>(
617 message: DiagnosticMessage,
618 args: impl Iterator<Item = DiagnosticArg<'a, 'static>>,
619 ) -> SubdiagnosticMessage {
620 let inner = self.inner.borrow();
621 let args = crate::translation::to_fluent_args(args);
622 SubdiagnosticMessage::Eager(inner.emitter.translate_message(&message, &args).to_string())
625 // This is here to not allow mutation of flags;
626 // as of this writing it's only used in tests in librustc_middle.
627 pub fn can_emit_warnings(&self) -> bool {
628 self.flags.can_emit_warnings
631 /// Resets the diagnostic error count as well as the cached emitted diagnostics.
633 /// NOTE: *do not* call this function from rustc. It is only meant to be called from external
634 /// tools that want to reuse a `Parser` cleaning the previously emitted diagnostics as well as
635 /// the overall count of emitted error diagnostics.
636 pub fn reset_err_count(&self) {
637 let mut inner = self.inner.borrow_mut();
639 inner.warn_count = 0;
640 inner.deduplicated_err_count = 0;
641 inner.deduplicated_warn_count = 0;
643 // actually free the underlying memory (which `clear` would not do)
644 inner.delayed_span_bugs = Default::default();
645 inner.delayed_good_path_bugs = Default::default();
646 inner.taught_diagnostics = Default::default();
647 inner.emitted_diagnostic_codes = Default::default();
648 inner.emitted_diagnostics = Default::default();
649 inner.stashed_diagnostics = Default::default();
652 /// Stash a given diagnostic with the given `Span` and [`StashKey`] as the key.
653 /// Retrieve a stashed diagnostic with `steal_diagnostic`.
654 pub fn stash_diagnostic(&self, span: Span, key: StashKey, diag: Diagnostic) {
655 let mut inner = self.inner.borrow_mut();
656 inner.stash((span, key), diag);
659 /// Steal a previously stashed diagnostic with the given `Span` and [`StashKey`] as the key.
660 pub fn steal_diagnostic(&self, span: Span, key: StashKey) -> Option<DiagnosticBuilder<'_, ()>> {
661 let mut inner = self.inner.borrow_mut();
662 inner.steal((span, key)).map(|diag| DiagnosticBuilder::new_diagnostic(self, diag))
665 pub fn has_stashed_diagnostic(&self, span: Span, key: StashKey) -> bool {
666 self.inner.borrow().stashed_diagnostics.get(&(span, key)).is_some()
669 /// Emit all stashed diagnostics.
670 pub fn emit_stashed_diagnostics(&self) -> Option<ErrorGuaranteed> {
671 self.inner.borrow_mut().emit_stashed_diagnostics()
674 /// Construct a builder with the `msg` at the level appropriate for the specific `EmissionGuarantee`.
675 #[rustc_lint_diagnostics]
677 pub fn struct_diagnostic<G: EmissionGuarantee>(
679 msg: impl Into<DiagnosticMessage>,
680 ) -> DiagnosticBuilder<'_, G> {
681 G::make_diagnostic_builder(self, msg)
684 /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
686 /// Attempting to `.emit()` the builder will only emit if either:
687 /// * `can_emit_warnings` is `true`
688 /// * `is_force_warn` was set in `DiagnosticId::Lint`
689 #[rustc_lint_diagnostics]
691 pub fn struct_span_warn(
693 span: impl Into<MultiSpan>,
694 msg: impl Into<DiagnosticMessage>,
695 ) -> DiagnosticBuilder<'_, ()> {
696 let mut result = self.struct_warn(msg);
697 result.set_span(span);
701 /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
702 /// The `id` is used for lint emissions which should also fulfill a lint expectation.
704 /// Attempting to `.emit()` the builder will only emit if either:
705 /// * `can_emit_warnings` is `true`
706 /// * `is_force_warn` was set in `DiagnosticId::Lint`
708 pub fn struct_span_warn_with_expectation(
710 span: impl Into<MultiSpan>,
711 msg: impl Into<DiagnosticMessage>,
712 id: LintExpectationId,
713 ) -> DiagnosticBuilder<'_, ()> {
714 let mut result = self.struct_warn_with_expectation(msg, id);
715 result.set_span(span);
719 /// Construct a builder at the `Allow` level at the given `span` and with the `msg`.
720 #[rustc_lint_diagnostics]
722 pub fn struct_span_allow(
724 span: impl Into<MultiSpan>,
725 msg: impl Into<DiagnosticMessage>,
726 ) -> DiagnosticBuilder<'_, ()> {
727 let mut result = self.struct_allow(msg);
728 result.set_span(span);
732 /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
733 /// Also include a code.
734 #[rustc_lint_diagnostics]
736 pub fn struct_span_warn_with_code(
738 span: impl Into<MultiSpan>,
739 msg: impl Into<DiagnosticMessage>,
741 ) -> DiagnosticBuilder<'_, ()> {
742 let mut result = self.struct_span_warn(span, msg);
747 /// Construct a builder at the `Warning` level with the `msg`.
749 /// Attempting to `.emit()` the builder will only emit if either:
750 /// * `can_emit_warnings` is `true`
751 /// * `is_force_warn` was set in `DiagnosticId::Lint`
752 #[rustc_lint_diagnostics]
754 pub fn struct_warn(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> {
755 DiagnosticBuilder::new(self, Level::Warning(None), msg)
758 /// Construct a builder at the `Warning` level with the `msg`. The `id` is used for
759 /// lint emissions which should also fulfill a lint expectation.
761 /// Attempting to `.emit()` the builder will only emit if either:
762 /// * `can_emit_warnings` is `true`
763 /// * `is_force_warn` was set in `DiagnosticId::Lint`
765 pub fn struct_warn_with_expectation(
767 msg: impl Into<DiagnosticMessage>,
768 id: LintExpectationId,
769 ) -> DiagnosticBuilder<'_, ()> {
770 DiagnosticBuilder::new(self, Level::Warning(Some(id)), msg)
773 /// Construct a builder at the `Allow` level with the `msg`.
774 #[rustc_lint_diagnostics]
776 pub fn struct_allow(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> {
777 DiagnosticBuilder::new(self, Level::Allow, msg)
780 /// Construct a builder at the `Expect` level with the `msg`.
781 #[rustc_lint_diagnostics]
783 pub fn struct_expect(
785 msg: impl Into<DiagnosticMessage>,
786 id: LintExpectationId,
787 ) -> DiagnosticBuilder<'_, ()> {
788 DiagnosticBuilder::new(self, Level::Expect(id), msg)
791 /// Construct a builder at the `Error` level at the given `span` and with the `msg`.
792 #[rustc_lint_diagnostics]
794 pub fn struct_span_err(
796 span: impl Into<MultiSpan>,
797 msg: impl Into<DiagnosticMessage>,
798 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
799 let mut result = self.struct_err(msg);
800 result.set_span(span);
804 /// Construct a builder at the `Error` level at the given `span`, with the `msg`, and `code`.
805 #[rustc_lint_diagnostics]
807 pub fn struct_span_err_with_code(
809 span: impl Into<MultiSpan>,
810 msg: impl Into<DiagnosticMessage>,
812 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
813 let mut result = self.struct_span_err(span, msg);
818 /// Construct a builder at the `Error` level with the `msg`.
819 // FIXME: This method should be removed (every error should have an associated error code).
820 #[rustc_lint_diagnostics]
824 msg: impl Into<DiagnosticMessage>,
825 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
826 DiagnosticBuilder::new_guaranteeing_error::<_, { Level::Error { lint: false } }>(self, msg)
829 /// This should only be used by `rustc_middle::lint::struct_lint_level`. Do not use it for hard errors.
832 pub fn struct_err_lint(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> {
833 DiagnosticBuilder::new(self, Level::Error { lint: true }, msg)
836 /// Construct a builder at the `Error` level with the `msg` and the `code`.
837 #[rustc_lint_diagnostics]
839 pub fn struct_err_with_code(
841 msg: impl Into<DiagnosticMessage>,
843 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
844 let mut result = self.struct_err(msg);
849 /// Construct a builder at the `Warn` level with the `msg` and the `code`.
850 #[rustc_lint_diagnostics]
852 pub fn struct_warn_with_code(
854 msg: impl Into<DiagnosticMessage>,
856 ) -> DiagnosticBuilder<'_, ()> {
857 let mut result = self.struct_warn(msg);
862 /// Construct a builder at the `Fatal` level at the given `span` and with the `msg`.
863 #[rustc_lint_diagnostics]
865 pub fn struct_span_fatal(
867 span: impl Into<MultiSpan>,
868 msg: impl Into<DiagnosticMessage>,
869 ) -> DiagnosticBuilder<'_, !> {
870 let mut result = self.struct_fatal(msg);
871 result.set_span(span);
875 /// Construct a builder at the `Fatal` level at the given `span`, with the `msg`, and `code`.
876 #[rustc_lint_diagnostics]
878 pub fn struct_span_fatal_with_code(
880 span: impl Into<MultiSpan>,
881 msg: impl Into<DiagnosticMessage>,
883 ) -> DiagnosticBuilder<'_, !> {
884 let mut result = self.struct_span_fatal(span, msg);
889 /// Construct a builder at the `Error` level with the `msg`.
890 #[rustc_lint_diagnostics]
892 pub fn struct_fatal(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, !> {
893 DiagnosticBuilder::new_fatal(self, msg)
896 /// Construct a builder at the `Help` level with the `msg`.
897 #[rustc_lint_diagnostics]
898 pub fn struct_help(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> {
899 DiagnosticBuilder::new(self, Level::Help, msg)
902 /// Construct a builder at the `Note` level with the `msg`.
903 #[rustc_lint_diagnostics]
905 pub fn struct_note_without_error(
907 msg: impl Into<DiagnosticMessage>,
908 ) -> DiagnosticBuilder<'_, ()> {
909 DiagnosticBuilder::new(self, Level::Note, msg)
912 #[rustc_lint_diagnostics]
914 pub fn span_fatal(&self, span: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>) -> ! {
915 self.emit_diag_at_span(Diagnostic::new(Fatal, msg), span);
919 #[rustc_lint_diagnostics]
921 pub fn span_fatal_with_code(
923 span: impl Into<MultiSpan>,
924 msg: impl Into<DiagnosticMessage>,
927 self.emit_diag_at_span(Diagnostic::new_with_code(Fatal, Some(code), msg), span);
931 #[rustc_lint_diagnostics]
935 span: impl Into<MultiSpan>,
936 msg: impl Into<DiagnosticMessage>,
937 ) -> ErrorGuaranteed {
938 self.emit_diag_at_span(Diagnostic::new(Error { lint: false }, msg), span).unwrap()
941 #[rustc_lint_diagnostics]
943 pub fn span_err_with_code(
945 span: impl Into<MultiSpan>,
946 msg: impl Into<DiagnosticMessage>,
949 self.emit_diag_at_span(
950 Diagnostic::new_with_code(Error { lint: false }, Some(code), msg),
955 #[rustc_lint_diagnostics]
957 pub fn span_warn(&self, span: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>) {
958 self.emit_diag_at_span(Diagnostic::new(Warning(None), msg), span);
961 #[rustc_lint_diagnostics]
963 pub fn span_warn_with_code(
965 span: impl Into<MultiSpan>,
966 msg: impl Into<DiagnosticMessage>,
969 self.emit_diag_at_span(Diagnostic::new_with_code(Warning(None), Some(code), msg), span);
972 pub fn span_bug(&self, span: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>) -> ! {
973 self.inner.borrow_mut().span_bug(span, msg)
977 pub fn delay_span_bug(
979 span: impl Into<MultiSpan>,
980 msg: impl Into<DiagnosticMessage>,
981 ) -> ErrorGuaranteed {
982 self.inner.borrow_mut().delay_span_bug(span, msg)
985 // FIXME(eddyb) note the comment inside `impl Drop for HandlerInner`, that's
986 // where the explanation of what "good path" is (also, it should be renamed).
987 pub fn delay_good_path_bug(&self, msg: impl Into<DiagnosticMessage>) {
988 self.inner.borrow_mut().delay_good_path_bug(msg)
992 pub fn span_bug_no_panic(&self, span: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>) {
993 self.emit_diag_at_span(Diagnostic::new(Bug, msg), span);
997 pub fn span_note_without_error(
999 span: impl Into<MultiSpan>,
1000 msg: impl Into<DiagnosticMessage>,
1002 self.emit_diag_at_span(Diagnostic::new(Note, msg), span);
1006 pub fn span_note_diag(
1009 msg: impl Into<DiagnosticMessage>,
1010 ) -> DiagnosticBuilder<'_, ()> {
1011 let mut db = DiagnosticBuilder::new(self, Note, msg);
1016 // NOTE: intentionally doesn't raise an error so rustc_codegen_ssa only reports fatal errors in the main thread
1017 pub fn fatal(&self, msg: impl Into<DiagnosticMessage>) -> FatalError {
1018 self.inner.borrow_mut().fatal(msg)
1021 pub fn err(&self, msg: impl Into<DiagnosticMessage>) -> ErrorGuaranteed {
1022 self.inner.borrow_mut().err(msg)
1025 pub fn warn(&self, msg: impl Into<DiagnosticMessage>) {
1026 let mut db = DiagnosticBuilder::new(self, Warning(None), msg);
1030 pub fn note_without_error(&self, msg: impl Into<DiagnosticMessage>) {
1031 DiagnosticBuilder::new(self, Note, msg).emit();
1034 pub fn bug(&self, msg: impl Into<DiagnosticMessage>) -> ! {
1035 self.inner.borrow_mut().bug(msg)
1039 pub fn err_count(&self) -> usize {
1040 self.inner.borrow().err_count()
1043 pub fn has_errors(&self) -> Option<ErrorGuaranteed> {
1044 if self.inner.borrow().has_errors() { Some(ErrorGuaranteed(())) } else { None }
1046 pub fn has_errors_or_lint_errors(&self) -> Option<ErrorGuaranteed> {
1047 if self.inner.borrow().has_errors_or_lint_errors() {
1048 Some(ErrorGuaranteed::unchecked_claim_error_was_emitted())
1053 pub fn has_errors_or_delayed_span_bugs(&self) -> Option<ErrorGuaranteed> {
1054 if self.inner.borrow().has_errors_or_delayed_span_bugs() {
1055 Some(ErrorGuaranteed::unchecked_claim_error_was_emitted())
1060 pub fn is_compilation_going_to_fail(&self) -> Option<ErrorGuaranteed> {
1061 if self.inner.borrow().is_compilation_going_to_fail() {
1062 Some(ErrorGuaranteed::unchecked_claim_error_was_emitted())
1068 pub fn print_error_count(&self, registry: &Registry) {
1069 self.inner.borrow_mut().print_error_count(registry)
1072 pub fn take_future_breakage_diagnostics(&self) -> Vec<Diagnostic> {
1073 std::mem::take(&mut self.inner.borrow_mut().future_breakage_diagnostics)
1076 pub fn abort_if_errors(&self) {
1077 self.inner.borrow_mut().abort_if_errors()
1080 /// `true` if we haven't taught a diagnostic with this code already.
1081 /// The caller must then teach the user about such a diagnostic.
1083 /// Used to suppress emitting the same error multiple times with extended explanation when
1084 /// calling `-Zteach`.
1085 pub fn must_teach(&self, code: &DiagnosticId) -> bool {
1086 self.inner.borrow_mut().must_teach(code)
1089 pub fn force_print_diagnostic(&self, db: Diagnostic) {
1090 self.inner.borrow_mut().force_print_diagnostic(db)
1093 pub fn emit_diagnostic(&self, diagnostic: &mut Diagnostic) -> Option<ErrorGuaranteed> {
1094 self.inner.borrow_mut().emit_diagnostic(diagnostic)
1097 pub fn emit_err<'a>(&'a self, err: impl IntoDiagnostic<'a>) -> ErrorGuaranteed {
1098 self.create_err(err).emit()
1101 pub fn create_err<'a>(
1103 err: impl IntoDiagnostic<'a>,
1104 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
1105 err.into_diagnostic(self)
1108 pub fn create_warning<'a>(
1110 warning: impl IntoDiagnostic<'a, ()>,
1111 ) -> DiagnosticBuilder<'a, ()> {
1112 warning.into_diagnostic(self)
1115 pub fn emit_warning<'a>(&'a self, warning: impl IntoDiagnostic<'a, ()>) {
1116 self.create_warning(warning).emit()
1119 pub fn create_fatal<'a>(
1121 fatal: impl IntoDiagnostic<'a, !>,
1122 ) -> DiagnosticBuilder<'a, !> {
1123 fatal.into_diagnostic(self)
1126 pub fn emit_fatal<'a>(&'a self, fatal: impl IntoDiagnostic<'a, !>) -> ! {
1127 self.create_fatal(fatal).emit()
1130 pub fn create_bug<'a>(
1132 bug: impl IntoDiagnostic<'a, diagnostic_builder::Bug>,
1133 ) -> DiagnosticBuilder<'a, diagnostic_builder::Bug> {
1134 bug.into_diagnostic(self)
1137 pub fn emit_bug<'a>(
1139 bug: impl IntoDiagnostic<'a, diagnostic_builder::Bug>,
1140 ) -> diagnostic_builder::Bug {
1141 self.create_bug(bug).emit()
1144 fn emit_diag_at_span(
1146 mut diag: Diagnostic,
1147 sp: impl Into<MultiSpan>,
1148 ) -> Option<ErrorGuaranteed> {
1149 let mut inner = self.inner.borrow_mut();
1150 inner.emit_diagnostic(diag.set_span(sp))
1153 pub fn emit_artifact_notification(&self, path: &Path, artifact_type: &str) {
1154 self.inner.borrow_mut().emit_artifact_notification(path, artifact_type)
1157 pub fn emit_future_breakage_report(&self, diags: Vec<Diagnostic>) {
1158 self.inner.borrow_mut().emitter.emit_future_breakage_report(diags)
1161 pub fn emit_unused_externs(
1163 lint_level: rustc_lint_defs::Level,
1165 unused_externs: &[&str],
1167 let mut inner = self.inner.borrow_mut();
1169 if loud && lint_level.is_error() {
1170 inner.bump_err_count();
1173 inner.emit_unused_externs(lint_level, unused_externs)
1176 pub fn update_unstable_expectation_id(
1178 unstable_to_stable: &FxHashMap<LintExpectationId, LintExpectationId>,
1180 let mut inner = self.inner.borrow_mut();
1181 let diags = std::mem::take(&mut inner.unstable_expect_diagnostics);
1182 inner.check_unstable_expect_diagnostics = true;
1184 if !diags.is_empty() {
1185 inner.suppressed_expected_diag = true;
1186 for mut diag in diags.into_iter() {
1187 diag.update_unstable_expectation_id(unstable_to_stable);
1189 // Here the diagnostic is given back to `emit_diagnostic` where it was first
1190 // intercepted. Now it should be processed as usual, since the unstable expectation
1191 // id is now stable.
1192 inner.emit_diagnostic(&mut diag);
1197 .stashed_diagnostics
1199 .for_each(|diag| diag.update_unstable_expectation_id(unstable_to_stable));
1201 .future_breakage_diagnostics
1203 .for_each(|diag| diag.update_unstable_expectation_id(unstable_to_stable));
1206 /// This methods steals all [`LintExpectationId`]s that are stored inside
1207 /// [`HandlerInner`] and indicate that the linked expectation has been fulfilled.
1209 pub fn steal_fulfilled_expectation_ids(&self) -> FxHashSet<LintExpectationId> {
1211 self.inner.borrow().unstable_expect_diagnostics.is_empty(),
1212 "`HandlerInner::unstable_expect_diagnostics` should be empty at this point",
1214 std::mem::take(&mut self.inner.borrow_mut().fulfilled_expectations)
1217 pub fn flush_delayed(&self) {
1218 let mut inner = self.inner.lock();
1219 let bugs = std::mem::replace(&mut inner.delayed_span_bugs, Vec::new());
1220 inner.flush_delayed(bugs, "no errors encountered even though `delay_span_bug` issued");
1225 fn must_teach(&mut self, code: &DiagnosticId) -> bool {
1226 self.taught_diagnostics.insert(code.clone())
1229 fn force_print_diagnostic(&mut self, db: Diagnostic) {
1230 self.emitter.emit_diagnostic(&db);
1233 /// Emit all stashed diagnostics.
1234 fn emit_stashed_diagnostics(&mut self) -> Option<ErrorGuaranteed> {
1235 let has_errors = self.has_errors();
1236 let diags = self.stashed_diagnostics.drain(..).map(|x| x.1).collect::<Vec<_>>();
1237 let mut reported = None;
1238 for mut diag in diags {
1239 // Decrement the count tracking the stash; emitting will increment it.
1240 if diag.is_error() {
1241 if matches!(diag.level, Level::Error { lint: true }) {
1242 self.lint_err_count -= 1;
1244 self.err_count -= 1;
1247 if diag.is_force_warn() {
1248 self.warn_count -= 1;
1250 // Unless they're forced, don't flush stashed warnings when
1251 // there are errors, to avoid causing warning overload. The
1252 // stash would've been stolen already if it were important.
1258 let reported_this = self.emit_diagnostic(&mut diag);
1259 reported = reported.or(reported_this);
1264 // FIXME(eddyb) this should ideally take `diagnostic` by value.
1265 fn emit_diagnostic(&mut self, diagnostic: &mut Diagnostic) -> Option<ErrorGuaranteed> {
1266 // The `LintExpectationId` can be stable or unstable depending on when it was created.
1267 // Diagnostics created before the definition of `HirId`s are unstable and can not yet
1268 // be stored. Instead, they are buffered until the `LintExpectationId` is replaced by
1269 // a stable one by the `LintLevelsBuilder`.
1270 if let Some(LintExpectationId::Unstable { .. }) = diagnostic.level.get_expectation_id() {
1271 self.unstable_expect_diagnostics.push(diagnostic.clone());
1275 if diagnostic.level == Level::DelayedBug {
1276 // FIXME(eddyb) this should check for `has_errors` and stop pushing
1277 // once *any* errors were emitted (and truncate `delayed_span_bugs`
1278 // when an error is first emitted, also), but maybe there's a case
1279 // in which that's not sound? otherwise this is really inefficient.
1280 self.delayed_span_bugs.push(diagnostic.clone());
1282 if !self.flags.report_delayed_bugs {
1283 return Some(ErrorGuaranteed::unchecked_claim_error_was_emitted());
1287 if diagnostic.has_future_breakage() {
1288 // Future breakages aren't emitted if they're Level::Allowed,
1289 // but they still need to be constructed and stashed below,
1290 // so they'll trigger the good-path bug check.
1291 self.suppressed_expected_diag = true;
1292 self.future_breakage_diagnostics.push(diagnostic.clone());
1295 if let Some(expectation_id) = diagnostic.level.get_expectation_id() {
1296 self.suppressed_expected_diag = true;
1297 self.fulfilled_expectations.insert(expectation_id.normalize());
1300 if matches!(diagnostic.level, Warning(_))
1301 && !self.flags.can_emit_warnings
1302 && !diagnostic.is_force_warn()
1304 if diagnostic.has_future_breakage() {
1305 (*TRACK_DIAGNOSTICS)(diagnostic);
1310 (*TRACK_DIAGNOSTICS)(diagnostic);
1312 if matches!(diagnostic.level, Level::Expect(_) | Level::Allow) {
1316 if let Some(ref code) = diagnostic.code {
1317 self.emitted_diagnostic_codes.insert(code.clone());
1320 let already_emitted = |this: &mut Self| {
1321 let mut hasher = StableHasher::new();
1322 diagnostic.hash(&mut hasher);
1323 let diagnostic_hash = hasher.finish();
1324 !this.emitted_diagnostics.insert(diagnostic_hash)
1327 // Only emit the diagnostic if we've been asked to deduplicate or
1328 // haven't already emitted an equivalent diagnostic.
1329 if !(self.flags.deduplicate_diagnostics && already_emitted(self)) {
1330 debug!(?diagnostic);
1331 debug!(?self.emitted_diagnostics);
1332 let already_emitted_sub = |sub: &mut SubDiagnostic| {
1334 if sub.level != Level::OnceNote {
1337 let mut hasher = StableHasher::new();
1338 sub.hash(&mut hasher);
1339 let diagnostic_hash = hasher.finish();
1340 debug!(?diagnostic_hash);
1341 !self.emitted_diagnostics.insert(diagnostic_hash)
1344 diagnostic.children.drain_filter(already_emitted_sub).for_each(|_| {});
1346 self.emitter.emit_diagnostic(diagnostic);
1347 if diagnostic.is_error() {
1348 self.deduplicated_err_count += 1;
1349 } else if let Warning(_) = diagnostic.level {
1350 self.deduplicated_warn_count += 1;
1353 if diagnostic.is_error() {
1354 if matches!(diagnostic.level, Level::Error { lint: true }) {
1355 self.bump_lint_err_count();
1357 self.bump_err_count();
1360 Some(ErrorGuaranteed::unchecked_claim_error_was_emitted())
1362 self.bump_warn_count();
1368 fn emit_artifact_notification(&mut self, path: &Path, artifact_type: &str) {
1369 self.emitter.emit_artifact_notification(path, artifact_type);
1372 fn emit_unused_externs(&mut self, lint_level: rustc_lint_defs::Level, unused_externs: &[&str]) {
1373 self.emitter.emit_unused_externs(lint_level, unused_externs);
1376 fn treat_err_as_bug(&self) -> bool {
1377 self.flags.treat_err_as_bug.map_or(false, |c| {
1378 self.err_count() + self.lint_err_count + self.delayed_bug_count() >= c.get()
1382 fn delayed_bug_count(&self) -> usize {
1383 self.delayed_span_bugs.len() + self.delayed_good_path_bugs.len()
1386 fn print_error_count(&mut self, registry: &Registry) {
1387 self.emit_stashed_diagnostics();
1389 let warnings = match self.deduplicated_warn_count {
1391 1 => "1 warning emitted".to_string(),
1392 count => format!("{count} warnings emitted"),
1394 let errors = match self.deduplicated_err_count {
1396 1 => "aborting due to previous error".to_string(),
1397 count => format!("aborting due to {count} previous errors"),
1399 if self.treat_err_as_bug() {
1403 match (errors.len(), warnings.len()) {
1405 (0, _) => self.emitter.emit_diagnostic(&Diagnostic::new(
1406 Level::Warning(None),
1407 DiagnosticMessage::Str(warnings),
1410 let _ = self.fatal(&errors);
1413 let _ = self.fatal(&format!("{}; {}", &errors, &warnings));
1417 let can_show_explain = self.emitter.should_show_explain();
1418 let are_there_diagnostics = !self.emitted_diagnostic_codes.is_empty();
1419 if can_show_explain && are_there_diagnostics {
1420 let mut error_codes = self
1421 .emitted_diagnostic_codes
1423 .filter_map(|x| match &x {
1424 DiagnosticId::Error(s)
1425 if registry.try_find_description(s).map_or(false, |o| o.is_some()) =>
1431 .collect::<Vec<_>>();
1432 if !error_codes.is_empty() {
1434 if error_codes.len() > 1 {
1435 let limit = if error_codes.len() > 9 { 9 } else { error_codes.len() };
1436 self.failure(&format!(
1437 "Some errors have detailed explanations: {}{}",
1438 error_codes[..limit].join(", "),
1439 if error_codes.len() > 9 { "..." } else { "." }
1441 self.failure(&format!(
1442 "For more information about an error, try \
1443 `rustc --explain {}`.",
1447 self.failure(&format!(
1448 "For more information about this error, try \
1449 `rustc --explain {}`.",
1457 fn stash(&mut self, key: (Span, StashKey), diagnostic: Diagnostic) {
1458 // Track the diagnostic for counts, but don't panic-if-treat-err-as-bug
1459 // yet; that happens when we actually emit the diagnostic.
1460 if diagnostic.is_error() {
1461 if matches!(diagnostic.level, Level::Error { lint: true }) {
1462 self.lint_err_count += 1;
1464 self.err_count += 1;
1467 // Warnings are only automatically flushed if they're forced.
1468 if diagnostic.is_force_warn() {
1469 self.warn_count += 1;
1473 // FIXME(Centril, #69537): Consider reintroducing panic on overwriting a stashed diagnostic
1474 // if/when we have a more robust macro-friendly replacement for `(span, key)` as a key.
1475 // See the PR for a discussion.
1476 self.stashed_diagnostics.insert(key, diagnostic);
1479 fn steal(&mut self, key: (Span, StashKey)) -> Option<Diagnostic> {
1480 let diagnostic = self.stashed_diagnostics.remove(&key)?;
1481 if diagnostic.is_error() {
1482 if matches!(diagnostic.level, Level::Error { lint: true }) {
1483 self.lint_err_count -= 1;
1485 self.err_count -= 1;
1488 if diagnostic.is_force_warn() {
1489 self.warn_count -= 1;
1496 fn err_count(&self) -> usize {
1500 fn has_errors(&self) -> bool {
1501 self.err_count() > 0
1503 fn has_errors_or_lint_errors(&self) -> bool {
1504 self.has_errors() || self.lint_err_count > 0
1506 fn has_errors_or_delayed_span_bugs(&self) -> bool {
1507 self.has_errors() || !self.delayed_span_bugs.is_empty()
1509 fn has_any_message(&self) -> bool {
1510 self.err_count() > 0 || self.lint_err_count > 0 || self.warn_count > 0
1513 fn is_compilation_going_to_fail(&self) -> bool {
1514 self.has_errors() || self.lint_err_count > 0 || !self.delayed_span_bugs.is_empty()
1517 fn abort_if_errors(&mut self) {
1518 self.emit_stashed_diagnostics();
1520 if self.has_errors() {
1526 fn span_bug(&mut self, sp: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>) -> ! {
1527 self.emit_diag_at_span(Diagnostic::new(Bug, msg), sp);
1528 panic::panic_any(ExplicitBug);
1531 fn emit_diag_at_span(&mut self, mut diag: Diagnostic, sp: impl Into<MultiSpan>) {
1532 self.emit_diagnostic(diag.set_span(sp));
1538 sp: impl Into<MultiSpan>,
1539 msg: impl Into<DiagnosticMessage>,
1540 ) -> ErrorGuaranteed {
1541 // This is technically `self.treat_err_as_bug()` but `delay_span_bug` is called before
1542 // incrementing `err_count` by one, so we need to +1 the comparing.
1543 // FIXME: Would be nice to increment err_count in a more coherent way.
1544 if self.flags.treat_err_as_bug.map_or(false, |c| {
1545 self.err_count() + self.lint_err_count + self.delayed_bug_count() + 1 >= c.get()
1547 // FIXME: don't abort here if report_delayed_bugs is off
1548 self.span_bug(sp, msg);
1550 let mut diagnostic = Diagnostic::new(Level::DelayedBug, msg);
1551 diagnostic.set_span(sp.into());
1552 diagnostic.note(&format!("delayed at {}", std::panic::Location::caller()));
1553 self.emit_diagnostic(&mut diagnostic).unwrap()
1556 // FIXME(eddyb) note the comment inside `impl Drop for HandlerInner`, that's
1557 // where the explanation of what "good path" is (also, it should be renamed).
1558 fn delay_good_path_bug(&mut self, msg: impl Into<DiagnosticMessage>) {
1559 let mut diagnostic = Diagnostic::new(Level::DelayedBug, msg);
1560 if self.flags.report_delayed_bugs {
1561 self.emit_diagnostic(&mut diagnostic);
1563 let backtrace = std::backtrace::Backtrace::force_capture();
1564 self.delayed_good_path_bugs.push(DelayedDiagnostic::with_backtrace(diagnostic, backtrace));
1567 fn failure(&mut self, msg: impl Into<DiagnosticMessage>) {
1568 self.emit_diagnostic(&mut Diagnostic::new(FailureNote, msg));
1571 fn fatal(&mut self, msg: impl Into<DiagnosticMessage>) -> FatalError {
1572 self.emit(Fatal, msg);
1576 fn err(&mut self, msg: impl Into<DiagnosticMessage>) -> ErrorGuaranteed {
1577 self.emit(Error { lint: false }, msg)
1580 /// Emit an error; level should be `Error` or `Fatal`.
1581 fn emit(&mut self, level: Level, msg: impl Into<DiagnosticMessage>) -> ErrorGuaranteed {
1582 if self.treat_err_as_bug() {
1585 self.emit_diagnostic(&mut Diagnostic::new(level, msg)).unwrap()
1588 fn bug(&mut self, msg: impl Into<DiagnosticMessage>) -> ! {
1589 self.emit_diagnostic(&mut Diagnostic::new(Bug, msg));
1590 panic::panic_any(ExplicitBug);
1595 bugs: impl IntoIterator<Item = Diagnostic>,
1596 explanation: impl Into<DiagnosticMessage> + Copy,
1598 let mut no_bugs = true;
1599 for mut bug in bugs {
1601 // Put the overall explanation before the `DelayedBug`s, to
1602 // frame them better (e.g. separate warnings from them).
1603 self.emit_diagnostic(&mut Diagnostic::new(Bug, explanation));
1607 // "Undelay" the `DelayedBug`s (into plain `Bug`s).
1608 if bug.level != Level::DelayedBug {
1609 // NOTE(eddyb) not panicking here because we're already producing
1610 // an ICE, and the more information the merrier.
1612 "`flushed_delayed` got diagnostic with level {:?}, \
1613 instead of the expected `DelayedBug`",
1617 bug.level = Level::Bug;
1619 self.emit_diagnostic(&mut bug);
1622 // Panic with `ExplicitBug` to avoid "unexpected panic" messages.
1624 panic::panic_any(ExplicitBug);
1628 fn bump_lint_err_count(&mut self) {
1629 self.lint_err_count += 1;
1630 self.panic_if_treat_err_as_bug();
1633 fn bump_err_count(&mut self) {
1634 self.err_count += 1;
1635 self.panic_if_treat_err_as_bug();
1638 fn bump_warn_count(&mut self) {
1639 self.warn_count += 1;
1642 fn panic_if_treat_err_as_bug(&self) {
1643 if self.treat_err_as_bug() {
1645 self.err_count() + self.lint_err_count,
1646 self.delayed_bug_count(),
1647 self.flags.treat_err_as_bug.map(|c| c.get()).unwrap_or(0),
1649 (1, 0, 1) => panic!("aborting due to `-Z treat-err-as-bug=1`"),
1650 (0, 1, 1) => panic!("aborting due delayed bug with `-Z treat-err-as-bug=1`"),
1651 (count, delayed_count, as_bug) => {
1652 if delayed_count > 0 {
1654 "aborting after {} errors and {} delayed bugs due to `-Z treat-err-as-bug={}`",
1655 count, delayed_count, as_bug,
1659 "aborting after {} errors due to `-Z treat-err-as-bug={}`",
1669 struct DelayedDiagnostic {
1674 impl DelayedDiagnostic {
1675 fn with_backtrace(diagnostic: Diagnostic, backtrace: Backtrace) -> Self {
1676 DelayedDiagnostic { inner: diagnostic, note: backtrace }
1679 fn decorate(mut self) -> Diagnostic {
1680 self.inner.note(&format!("delayed at {}", self.note));
1685 #[derive(Copy, PartialEq, Eq, Clone, Hash, Debug, Encodable, Decodable)]
1691 /// If this error comes from a lint, don't abort compilation even when abort_if_errors() is called.
1694 /// This [`LintExpectationId`] is used for expected lint diagnostics, which should
1695 /// also emit a warning due to the `force-warn` flag. In all other cases this should
1697 Warning(Option<LintExpectationId>),
1699 /// A note that is only emitted once.
1704 Expect(LintExpectationId),
1707 impl fmt::Display for Level {
1708 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1709 self.to_str().fmt(f)
1714 fn color(self) -> ColorSpec {
1715 let mut spec = ColorSpec::new();
1717 Bug | DelayedBug | Fatal | Error { .. } => {
1718 spec.set_fg(Some(Color::Red)).set_intense(true);
1721 spec.set_fg(Some(Color::Yellow)).set_intense(cfg!(windows));
1723 Note | OnceNote => {
1724 spec.set_fg(Some(Color::Green)).set_intense(true);
1727 spec.set_fg(Some(Color::Cyan)).set_intense(true);
1730 Allow | Expect(_) => unreachable!(),
1735 pub fn to_str(self) -> &'static str {
1737 Bug | DelayedBug => "error: internal compiler error",
1738 Fatal | Error { .. } => "error",
1739 Warning(_) => "warning",
1740 Note | OnceNote => "note",
1742 FailureNote => "failure-note",
1743 Allow => panic!("Shouldn't call on allowed error"),
1744 Expect(_) => panic!("Shouldn't call on expected error"),
1748 pub fn is_failure_note(&self) -> bool {
1749 matches!(*self, FailureNote)
1752 pub fn get_expectation_id(&self) -> Option<LintExpectationId> {
1754 Level::Expect(id) | Level::Warning(Some(id)) => Some(*id),
1760 // FIXME(eddyb) this doesn't belong here AFAICT, should be moved to callsite.
1761 pub fn add_elided_lifetime_in_path_suggestion(
1762 source_map: &SourceMap,
1763 diag: &mut Diagnostic,
1766 incl_angl_brckt: bool,
1767 insertion_span: Span,
1769 diag.span_label(path_span, format!("expected lifetime parameter{}", pluralize!(n)));
1770 if !source_map.is_span_accessible(insertion_span) {
1771 // Do not try to suggest anything if generated by a proc-macro.
1774 let anon_lts = vec!["'_"; n].join(", ");
1776 if incl_angl_brckt { format!("<{}>", anon_lts) } else { format!("{}, ", anon_lts) };
1777 diag.span_suggestion_verbose(
1778 insertion_span.shrink_to_hi(),
1779 &format!("indicate the anonymous lifetime{}", pluralize!(n)),
1781 Applicability::MachineApplicable,
1785 /// Useful type to use with `Result<>` indicate that an error has already
1786 /// been reported to the user, so no need to continue checking.
1787 #[derive(Clone, Copy, Debug, Encodable, Decodable, Hash, PartialEq, Eq, PartialOrd, Ord)]
1788 #[derive(HashStable_Generic)]
1789 pub struct ErrorGuaranteed(());
1791 impl ErrorGuaranteed {
1792 /// To be used only if you really know what you are doing... ideally, we would find a way to
1793 /// eliminate all calls to this method.
1794 pub fn unchecked_claim_error_was_emitted() -> Self {