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 #![feature(yeet_expr)]
15 #![feature(try_blocks)]
16 #![feature(box_patterns)]
17 #![feature(error_reporter)]
18 #![allow(incomplete_features)]
21 extern crate rustc_macros;
26 pub use emitter::ColorConfig;
28 use rustc_lint_defs::LintExpectationId;
31 use emitter::{is_case_difference, Emitter, EmitterWriter};
32 use registry::Registry;
33 use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet};
34 use rustc_data_structures::stable_hasher::StableHasher;
35 use rustc_data_structures::sync::{self, Lock, Lrc};
36 use rustc_data_structures::AtomicRef;
37 pub use rustc_error_messages::{
38 fallback_fluent_bundle, fluent, fluent_bundle, DelayDm, DiagnosticMessage, FluentBundle,
39 LanguageIdentifier, LazyFallbackBundle, MultiSpan, SpanLabel, SubdiagnosticMessage,
40 DEFAULT_LOCALE_RESOURCES,
42 pub use rustc_lint_defs::{pluralize, Applicability};
43 use rustc_span::source_map::SourceMap;
44 use rustc_span::HashStableContext;
45 use rustc_span::{Loc, Span};
48 use std::error::Report;
51 use std::num::NonZeroUsize;
55 use termcolor::{Color, ColorSpec};
57 pub mod annotate_snippet_emitter_writer;
59 mod diagnostic_builder;
72 pub use diagnostic_builder::IntoDiagnostic;
73 pub use snippet::Style;
75 pub type PErr<'a> = DiagnosticBuilder<'a, ErrorGuaranteed>;
76 pub type PResult<'a, T> = Result<T, PErr<'a>>;
78 // `PResult` is used a lot. Make sure it doesn't unintentionally get bigger.
79 // (See also the comment on `DiagnosticBuilderInner`'s `diagnostic` field.)
80 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
81 rustc_data_structures::static_assert_size!(PResult<'_, ()>, 16);
82 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
83 rustc_data_structures::static_assert_size!(PResult<'_, bool>, 16);
85 #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, Encodable, Decodable)]
86 pub enum SuggestionStyle {
87 /// Hide the suggested code when displaying this suggestion inline.
89 /// Always hide the suggested code but display the message.
91 /// Do not display this suggestion in the cli output, it is only meant for tools.
93 /// Always show the suggested code.
94 /// This will *not* show the code if the suggestion is inline *and* the suggested code is
97 /// Always show the suggested code independently.
101 impl SuggestionStyle {
102 fn hide_inline(&self) -> bool {
103 !matches!(*self, SuggestionStyle::ShowCode)
107 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
108 pub struct CodeSuggestion {
109 /// Each substitute can have multiple variants due to multiple
110 /// applicable suggestions
112 /// `foo.bar` might be replaced with `a.b` or `x.y` by replacing
113 /// `foo` and `bar` on their own:
115 /// ```ignore (illustrative)
117 /// Substitution { parts: vec![(0..3, "a"), (4..7, "b")] },
118 /// Substitution { parts: vec![(0..3, "x"), (4..7, "y")] },
122 /// or by replacing the entire span:
124 /// ```ignore (illustrative)
126 /// Substitution { parts: vec![(0..7, "a.b")] },
127 /// Substitution { parts: vec![(0..7, "x.y")] },
130 pub substitutions: Vec<Substitution>,
131 pub msg: DiagnosticMessage,
132 /// Visual representation of this suggestion.
133 pub style: SuggestionStyle,
134 /// Whether or not the suggestion is approximate
136 /// Sometimes we may show suggestions with placeholders,
137 /// which are useful for users but not useful for
138 /// tools like rustfix
139 pub applicability: Applicability,
142 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
143 /// See the docs on `CodeSuggestion::substitutions`
144 pub struct Substitution {
145 pub parts: Vec<SubstitutionPart>,
148 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
149 pub struct SubstitutionPart {
154 /// Used to translate between `Span`s and byte positions within a single output line in highlighted
155 /// code of structured suggestions.
156 #[derive(Debug, Clone, Copy)]
157 pub struct SubstitutionHighlight {
162 impl SubstitutionPart {
163 pub fn is_addition(&self, sm: &SourceMap) -> bool {
164 !self.snippet.is_empty() && !self.replaces_meaningful_content(sm)
167 pub fn is_deletion(&self, sm: &SourceMap) -> bool {
168 self.snippet.trim().is_empty() && self.replaces_meaningful_content(sm)
171 pub fn is_replacement(&self, sm: &SourceMap) -> bool {
172 !self.snippet.is_empty() && self.replaces_meaningful_content(sm)
175 fn replaces_meaningful_content(&self, sm: &SourceMap) -> bool {
176 sm.span_to_snippet(self.span)
177 .map_or(!self.span.is_empty(), |snippet| !snippet.trim().is_empty())
181 impl CodeSuggestion {
182 /// Returns the assembled code suggestions, whether they should be shown with an underline
183 /// and whether the substitution only differs in capitalization.
187 ) -> Vec<(String, Vec<SubstitutionPart>, Vec<Vec<SubstitutionHighlight>>, bool)> {
188 // For the `Vec<Vec<SubstitutionHighlight>>` value, the first level of the vector
189 // corresponds to the output snippet's lines, while the second level corresponds to the
190 // substrings within that line that should be highlighted.
192 use rustc_span::{CharPos, Pos};
194 /// Append to a buffer the remainder of the line of existing source code, and return the
195 /// count of lines that have been added for accurate highlighting.
198 line_opt: Option<&Cow<'_, str>>,
200 hi_opt: Option<&Loc>,
202 let mut line_count = 0;
203 let (lo, hi_opt) = (lo.col.to_usize(), hi_opt.map(|hi| hi.col.to_usize()));
204 if let Some(line) = line_opt {
205 if let Some(lo) = line.char_indices().map(|(i, _)| i).nth(lo) {
206 let hi_opt = hi_opt.and_then(|hi| line.char_indices().map(|(i, _)| i).nth(hi));
208 Some(hi) if hi > lo => {
209 line_count = line[lo..hi].matches('\n').count();
210 buf.push_str(&line[lo..hi])
214 line_count = line[lo..].matches('\n').count();
215 buf.push_str(&line[lo..])
219 if hi_opt.is_none() {
226 assert!(!self.substitutions.is_empty());
231 // Suggestions coming from macros can have malformed spans. This is a heavy
232 // handed approach to avoid ICEs by ignoring the suggestion outright.
233 let invalid = subst.parts.iter().any(|item| sm.is_valid_span(item.span).is_err());
235 debug!("splice_lines: suggestion contains an invalid span: {:?}", subst);
240 .filter_map(|mut substitution| {
241 // Assumption: all spans are in the same file, and all spans
242 // are disjoint. Sort in ascending order.
243 substitution.parts.sort_by_key(|part| part.span.lo());
245 // Find the bounding span.
246 let lo = substitution.parts.iter().map(|part| part.span.lo()).min()?;
247 let hi = substitution.parts.iter().map(|part| part.span.hi()).max()?;
248 let bounding_span = Span::with_root_ctxt(lo, hi);
249 // The different spans might belong to different contexts, if so ignore suggestion.
250 let lines = sm.span_to_lines(bounding_span).ok()?;
251 assert!(!lines.lines.is_empty() || bounding_span.is_dummy());
253 // We can't splice anything if the source is unavailable.
254 if !sm.ensure_source_file_source_present(lines.file.clone()) {
258 let mut highlights = vec![];
259 // To build up the result, we do this for each span:
260 // - push the line segment trailing the previous span
261 // (at the beginning a "phantom" span pointing at the start of the line)
262 // - push lines between the previous and current span (if any)
263 // - if the previous and current span are not on the same line
264 // push the line segment leading up to the current span
265 // - splice in the span substitution
267 // Finally push the trailing line segment of the last span
268 let sf = &lines.file;
269 let mut prev_hi = sm.lookup_char_pos(bounding_span.lo());
270 prev_hi.col = CharPos::from_usize(0);
272 lines.lines.get(0).and_then(|line0| sf.get_line(line0.line_index));
273 let mut buf = String::new();
275 let mut line_highlight = vec![];
276 // We need to keep track of the difference between the existing code and the added
277 // or deleted code in order to point at the correct column *after* substitution.
279 for part in &substitution.parts {
280 let cur_lo = sm.lookup_char_pos(part.span.lo());
281 if prev_hi.line == cur_lo.line {
283 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, Some(&cur_lo));
285 highlights.push(std::mem::take(&mut line_highlight));
291 highlights.push(std::mem::take(&mut line_highlight));
292 let mut count = push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
294 highlights.push(std::mem::take(&mut line_highlight));
297 // push lines between the previous and current span (if any)
298 for idx in prev_hi.line..(cur_lo.line - 1) {
299 if let Some(line) = sf.get_line(idx) {
300 buf.push_str(line.as_ref());
302 highlights.push(std::mem::take(&mut line_highlight));
305 if let Some(cur_line) = sf.get_line(cur_lo.line - 1) {
306 let end = match cur_line.char_indices().nth(cur_lo.col.to_usize()) {
308 None => cur_line.len(),
310 buf.push_str(&cur_line[..end]);
313 // Add a whole line highlight per line in the snippet.
314 let len: isize = part
318 .unwrap_or(&part.snippet)
325 line_highlight.push(SubstitutionHighlight {
326 start: (cur_lo.col.0 as isize + acc) as usize,
327 end: (cur_lo.col.0 as isize + acc + len) as usize,
329 buf.push_str(&part.snippet);
330 let cur_hi = sm.lookup_char_pos(part.span.hi());
331 if prev_hi.line == cur_lo.line && cur_hi.line == cur_lo.line {
332 // Account for the difference between the width of the current code and the
333 // snippet being suggested, so that the *later* suggestions are correctly
334 // aligned on the screen.
335 acc += len - (cur_hi.col.0 - cur_lo.col.0) as isize;
338 prev_line = sf.get_line(prev_hi.line - 1);
339 for line in part.snippet.split('\n').skip(1) {
341 highlights.push(std::mem::take(&mut line_highlight));
342 let end: usize = line
349 line_highlight.push(SubstitutionHighlight { start: 0, end });
352 highlights.push(std::mem::take(&mut line_highlight));
353 let only_capitalization = is_case_difference(sm, &buf, bounding_span);
354 // if the replacement already ends with a newline, don't print the next line
355 if !buf.ends_with('\n') {
356 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
358 // remove trailing newlines
359 while buf.ends_with('\n') {
362 Some((buf, substitution.parts, highlights, only_capitalization))
368 pub use rustc_span::fatal_error::{FatalError, FatalErrorMarker};
370 /// Signifies that the compiler died with an explicit call to `.bug`
371 /// or `.span_bug` rather than a failed assertion, etc.
372 pub struct ExplicitBug;
374 /// Signifies that the compiler died with an explicit call to `.delay_*_bug`
375 /// rather than a failed assertion, etc.
376 pub struct DelayedBugPanic;
378 pub use diagnostic::{
379 AddToDiagnostic, DecorateLint, Diagnostic, DiagnosticArg, DiagnosticArgValue, DiagnosticId,
380 DiagnosticStyledString, IntoDiagnosticArg, SubDiagnostic,
382 pub use diagnostic_builder::{DiagnosticBuilder, EmissionGuarantee, Noted};
383 pub use diagnostic_impls::{DiagnosticArgFromDisplay, DiagnosticSymbolList};
384 use std::backtrace::Backtrace;
386 /// A handler deals with errors and other compiler output.
387 /// Certain errors (fatal, bug, unimpl) may cause immediate exit,
388 /// others log errors for later reporting.
391 inner: Lock<HandlerInner>,
394 /// This inner struct exists to keep it all behind a single lock;
395 /// this is done to prevent possible deadlocks in a multi-threaded compiler,
396 /// as well as inconsistent state observation.
397 struct HandlerInner {
399 /// The number of lint errors that have been emitted.
400 lint_err_count: usize,
401 /// The number of errors that have been emitted, including duplicates.
403 /// This is not necessarily the count that's reported to the user once
404 /// compilation ends.
407 deduplicated_err_count: usize,
408 emitter: Box<dyn Emitter + sync::Send>,
409 delayed_span_bugs: Vec<DelayedDiagnostic>,
410 delayed_good_path_bugs: Vec<DelayedDiagnostic>,
411 /// This flag indicates that an expected diagnostic was emitted and suppressed.
412 /// This is used for the `delayed_good_path_bugs` check.
413 suppressed_expected_diag: bool,
415 /// This set contains the `DiagnosticId` of all emitted diagnostics to avoid
416 /// emitting the same diagnostic with extended help (`--teach`) twice, which
417 /// would be unnecessary repetition.
418 taught_diagnostics: FxHashSet<DiagnosticId>,
420 /// Used to suggest rustc --explain `<error code>`
421 emitted_diagnostic_codes: FxIndexSet<DiagnosticId>,
423 /// This set contains a hash of every diagnostic that has been emitted by
424 /// this handler. These hashes is used to avoid emitting the same error
426 emitted_diagnostics: FxHashSet<u128>,
428 /// Stashed diagnostics emitted in one stage of the compiler that may be
429 /// stolen by other stages (e.g. to improve them and add more information).
430 /// The stashed diagnostics count towards the total error count.
431 /// When `.abort_if_errors()` is called, these are also emitted.
432 stashed_diagnostics: FxIndexMap<(Span, StashKey), Diagnostic>,
434 /// The warning count, used for a recap upon finishing
435 deduplicated_warn_count: usize,
437 future_breakage_diagnostics: Vec<Diagnostic>,
439 /// The [`Self::unstable_expect_diagnostics`] should be empty when this struct is
440 /// dropped. However, it can have values if the compilation is stopped early
441 /// or is only partially executed. To avoid ICEs, like in rust#94953 we only
442 /// check if [`Self::unstable_expect_diagnostics`] is empty, if the expectation ids
443 /// have been converted.
444 check_unstable_expect_diagnostics: bool,
446 /// Expected [`Diagnostic`][diagnostic::Diagnostic]s store a [`LintExpectationId`] as part of
447 /// the lint level. [`LintExpectationId`]s created early during the compilation
448 /// (before `HirId`s have been defined) are not stable and can therefore not be
449 /// stored on disk. This buffer stores these diagnostics until the ID has been
450 /// replaced by a stable [`LintExpectationId`]. The [`Diagnostic`][diagnostic::Diagnostic]s are the
451 /// submitted for storage and added to the list of fulfilled expectations.
452 unstable_expect_diagnostics: Vec<Diagnostic>,
454 /// expected diagnostic will have the level `Expect` which additionally
455 /// carries the [`LintExpectationId`] of the expectation that can be
456 /// marked as fulfilled. This is a collection of all [`LintExpectationId`]s
457 /// that have been marked as fulfilled this way.
459 /// [RFC-2383]: https://rust-lang.github.io/rfcs/2383-lint-reasons.html
460 fulfilled_expectations: FxHashSet<LintExpectationId>,
463 /// A key denoting where from a diagnostic was stashed.
464 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
467 UnderscoreForArrayLengths,
470 /// When an invalid lifetime e.g. `'2` should be reinterpreted
471 /// as a char literal in the parser
473 /// Maybe there was a typo where a comma was forgotten before
479 fn default_track_diagnostic(d: &mut Diagnostic, f: &mut dyn FnMut(&mut Diagnostic)) {
483 pub static TRACK_DIAGNOSTICS: AtomicRef<fn(&mut Diagnostic, &mut dyn FnMut(&mut Diagnostic))> =
484 AtomicRef::new(&(default_track_diagnostic as _));
486 #[derive(Copy, Clone, Default)]
487 pub struct HandlerFlags {
488 /// If false, warning-level lints are suppressed.
489 /// (rustc: see `--allow warnings` and `--cap-lints`)
490 pub can_emit_warnings: bool,
491 /// If true, error-level diagnostics are upgraded to bug-level.
492 /// (rustc: see `-Z treat-err-as-bug`)
493 pub treat_err_as_bug: Option<NonZeroUsize>,
494 /// If true, immediately emit diagnostics that would otherwise be buffered.
495 /// (rustc: see `-Z dont-buffer-diagnostics` and `-Z treat-err-as-bug`)
496 pub dont_buffer_diagnostics: bool,
497 /// If true, immediately print bugs registered with `delay_span_bug`.
498 /// (rustc: see `-Z report-delayed-bugs`)
499 pub report_delayed_bugs: bool,
500 /// Show macro backtraces.
501 /// (rustc: see `-Z macro-backtrace`)
502 pub macro_backtrace: bool,
503 /// If true, identical diagnostics are reported only once.
504 pub deduplicate_diagnostics: bool,
505 /// Track where errors are created. Enabled with `-Ztrack-diagnostics`.
506 pub track_diagnostics: bool,
509 impl Drop for HandlerInner {
511 self.emit_stashed_diagnostics();
513 if !self.has_errors() {
514 let bugs = std::mem::replace(&mut self.delayed_span_bugs, Vec::new());
515 self.flush_delayed(bugs, "no errors encountered even though `delay_span_bug` issued");
518 // FIXME(eddyb) this explains what `delayed_good_path_bugs` are!
519 // They're `delayed_span_bugs` but for "require some diagnostic happened"
520 // instead of "require some error happened". Sadly that isn't ideal, as
521 // lints can be `#[allow]`'d, potentially leading to this triggering.
522 // Also, "good path" should be replaced with a better naming.
523 if !self.has_any_message() && !self.suppressed_expected_diag {
524 let bugs = std::mem::replace(&mut self.delayed_good_path_bugs, Vec::new());
527 "no warnings or errors encountered even though `delayed_good_path_bugs` issued",
531 if self.check_unstable_expect_diagnostics {
533 self.unstable_expect_diagnostics.is_empty(),
534 "all diagnostics with unstable expectations should have been converted",
541 pub fn with_tty_emitter(
542 color_config: ColorConfig,
543 can_emit_warnings: bool,
544 treat_err_as_bug: Option<NonZeroUsize>,
545 sm: Option<Lrc<SourceMap>>,
546 fluent_bundle: Option<Lrc<FluentBundle>>,
547 fallback_bundle: LazyFallbackBundle,
549 Self::with_tty_emitter_and_flags(
554 HandlerFlags { can_emit_warnings, treat_err_as_bug, ..Default::default() },
558 pub fn with_tty_emitter_and_flags(
559 color_config: ColorConfig,
560 sm: Option<Lrc<SourceMap>>,
561 fluent_bundle: Option<Lrc<FluentBundle>>,
562 fallback_bundle: LazyFallbackBundle,
565 let emitter = Box::new(EmitterWriter::stderr(
573 flags.macro_backtrace,
574 flags.track_diagnostics,
576 Self::with_emitter_and_flags(emitter, flags)
580 can_emit_warnings: bool,
581 treat_err_as_bug: Option<NonZeroUsize>,
582 emitter: Box<dyn Emitter + sync::Send>,
584 Handler::with_emitter_and_flags(
586 HandlerFlags { can_emit_warnings, treat_err_as_bug, ..Default::default() },
590 pub fn with_emitter_and_flags(
591 emitter: Box<dyn Emitter + sync::Send>,
596 inner: Lock::new(HandlerInner {
601 deduplicated_err_count: 0,
602 deduplicated_warn_count: 0,
604 delayed_span_bugs: Vec::new(),
605 delayed_good_path_bugs: Vec::new(),
606 suppressed_expected_diag: false,
607 taught_diagnostics: Default::default(),
608 emitted_diagnostic_codes: Default::default(),
609 emitted_diagnostics: Default::default(),
610 stashed_diagnostics: Default::default(),
611 future_breakage_diagnostics: Vec::new(),
612 check_unstable_expect_diagnostics: false,
613 unstable_expect_diagnostics: Vec::new(),
614 fulfilled_expectations: Default::default(),
619 /// Translate `message` eagerly with `args`.
620 pub fn eagerly_translate<'a>(
622 message: DiagnosticMessage,
623 args: impl Iterator<Item = DiagnosticArg<'a, 'static>>,
624 ) -> SubdiagnosticMessage {
625 let inner = self.inner.borrow();
626 let args = crate::translation::to_fluent_args(args);
627 SubdiagnosticMessage::Eager(
630 .translate_message(&message, &args)
631 .map_err(Report::new)
637 // This is here to not allow mutation of flags;
638 // as of this writing it's only used in tests in librustc_middle.
639 pub fn can_emit_warnings(&self) -> bool {
640 self.flags.can_emit_warnings
643 /// Resets the diagnostic error count as well as the cached emitted diagnostics.
645 /// NOTE: *do not* call this function from rustc. It is only meant to be called from external
646 /// tools that want to reuse a `Parser` cleaning the previously emitted diagnostics as well as
647 /// the overall count of emitted error diagnostics.
648 pub fn reset_err_count(&self) {
649 let mut inner = self.inner.borrow_mut();
651 inner.warn_count = 0;
652 inner.deduplicated_err_count = 0;
653 inner.deduplicated_warn_count = 0;
655 // actually free the underlying memory (which `clear` would not do)
656 inner.delayed_span_bugs = Default::default();
657 inner.delayed_good_path_bugs = Default::default();
658 inner.taught_diagnostics = Default::default();
659 inner.emitted_diagnostic_codes = Default::default();
660 inner.emitted_diagnostics = Default::default();
661 inner.stashed_diagnostics = Default::default();
664 /// Stash a given diagnostic with the given `Span` and [`StashKey`] as the key.
665 /// Retrieve a stashed diagnostic with `steal_diagnostic`.
666 pub fn stash_diagnostic(&self, span: Span, key: StashKey, diag: Diagnostic) {
667 let mut inner = self.inner.borrow_mut();
668 inner.stash((span.with_parent(None), key), diag);
671 /// Steal a previously stashed diagnostic with the given `Span` and [`StashKey`] as the key.
672 pub fn steal_diagnostic(&self, span: Span, key: StashKey) -> Option<DiagnosticBuilder<'_, ()>> {
673 let mut inner = self.inner.borrow_mut();
675 .steal((span.with_parent(None), key))
676 .map(|diag| DiagnosticBuilder::new_diagnostic(self, diag))
679 pub fn has_stashed_diagnostic(&self, span: Span, key: StashKey) -> bool {
680 self.inner.borrow().stashed_diagnostics.get(&(span.with_parent(None), key)).is_some()
683 /// Emit all stashed diagnostics.
684 pub fn emit_stashed_diagnostics(&self) -> Option<ErrorGuaranteed> {
685 self.inner.borrow_mut().emit_stashed_diagnostics()
688 /// Construct a builder with the `msg` at the level appropriate for the specific `EmissionGuarantee`.
689 #[rustc_lint_diagnostics]
691 pub fn struct_diagnostic<G: EmissionGuarantee>(
693 msg: impl Into<DiagnosticMessage>,
694 ) -> DiagnosticBuilder<'_, G> {
695 G::make_diagnostic_builder(self, msg)
698 /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
700 /// Attempting to `.emit()` the builder will only emit if either:
701 /// * `can_emit_warnings` is `true`
702 /// * `is_force_warn` was set in `DiagnosticId::Lint`
703 #[rustc_lint_diagnostics]
705 pub fn struct_span_warn(
707 span: impl Into<MultiSpan>,
708 msg: impl Into<DiagnosticMessage>,
709 ) -> DiagnosticBuilder<'_, ()> {
710 let mut result = self.struct_warn(msg);
711 result.set_span(span);
715 /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
716 /// The `id` is used for lint emissions which should also fulfill a lint expectation.
718 /// Attempting to `.emit()` the builder will only emit if either:
719 /// * `can_emit_warnings` is `true`
720 /// * `is_force_warn` was set in `DiagnosticId::Lint`
722 pub fn struct_span_warn_with_expectation(
724 span: impl Into<MultiSpan>,
725 msg: impl Into<DiagnosticMessage>,
726 id: LintExpectationId,
727 ) -> DiagnosticBuilder<'_, ()> {
728 let mut result = self.struct_warn_with_expectation(msg, id);
729 result.set_span(span);
733 /// Construct a builder at the `Allow` level at the given `span` and with the `msg`.
734 #[rustc_lint_diagnostics]
736 pub fn struct_span_allow(
738 span: impl Into<MultiSpan>,
739 msg: impl Into<DiagnosticMessage>,
740 ) -> DiagnosticBuilder<'_, ()> {
741 let mut result = self.struct_allow(msg);
742 result.set_span(span);
746 /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
747 /// Also include a code.
748 #[rustc_lint_diagnostics]
750 pub fn struct_span_warn_with_code(
752 span: impl Into<MultiSpan>,
753 msg: impl Into<DiagnosticMessage>,
755 ) -> DiagnosticBuilder<'_, ()> {
756 let mut result = self.struct_span_warn(span, msg);
761 /// Construct a builder at the `Warning` level with the `msg`.
763 /// Attempting to `.emit()` the builder will only emit if either:
764 /// * `can_emit_warnings` is `true`
765 /// * `is_force_warn` was set in `DiagnosticId::Lint`
766 #[rustc_lint_diagnostics]
768 pub fn struct_warn(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> {
769 DiagnosticBuilder::new(self, Level::Warning(None), msg)
772 /// Construct a builder at the `Warning` level with the `msg`. The `id` is used for
773 /// lint emissions which should also fulfill a lint expectation.
775 /// Attempting to `.emit()` the builder will only emit if either:
776 /// * `can_emit_warnings` is `true`
777 /// * `is_force_warn` was set in `DiagnosticId::Lint`
779 pub fn struct_warn_with_expectation(
781 msg: impl Into<DiagnosticMessage>,
782 id: LintExpectationId,
783 ) -> DiagnosticBuilder<'_, ()> {
784 DiagnosticBuilder::new(self, Level::Warning(Some(id)), msg)
787 /// Construct a builder at the `Allow` level with the `msg`.
788 #[rustc_lint_diagnostics]
790 pub fn struct_allow(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> {
791 DiagnosticBuilder::new(self, Level::Allow, msg)
794 /// Construct a builder at the `Expect` level with the `msg`.
795 #[rustc_lint_diagnostics]
797 pub fn struct_expect(
799 msg: impl Into<DiagnosticMessage>,
800 id: LintExpectationId,
801 ) -> DiagnosticBuilder<'_, ()> {
802 DiagnosticBuilder::new(self, Level::Expect(id), msg)
805 /// Construct a builder at the `Error` level at the given `span` and with the `msg`.
806 #[rustc_lint_diagnostics]
808 pub fn struct_span_err(
810 span: impl Into<MultiSpan>,
811 msg: impl Into<DiagnosticMessage>,
812 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
813 let mut result = self.struct_err(msg);
814 result.set_span(span);
818 /// Construct a builder at the `Error` level at the given `span`, with the `msg`, and `code`.
819 #[rustc_lint_diagnostics]
821 pub fn struct_span_err_with_code(
823 span: impl Into<MultiSpan>,
824 msg: impl Into<DiagnosticMessage>,
826 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
827 let mut result = self.struct_span_err(span, msg);
832 /// Construct a builder at the `Error` level with the `msg`.
833 // FIXME: This method should be removed (every error should have an associated error code).
834 #[rustc_lint_diagnostics]
838 msg: impl Into<DiagnosticMessage>,
839 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
840 DiagnosticBuilder::new_guaranteeing_error::<_, { Level::Error { lint: false } }>(self, msg)
843 /// This should only be used by `rustc_middle::lint::struct_lint_level`. Do not use it for hard errors.
846 pub fn struct_err_lint(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> {
847 DiagnosticBuilder::new(self, Level::Error { lint: true }, msg)
850 /// Construct a builder at the `Error` level with the `msg` and the `code`.
851 #[rustc_lint_diagnostics]
853 pub fn struct_err_with_code(
855 msg: impl Into<DiagnosticMessage>,
857 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
858 let mut result = self.struct_err(msg);
863 /// Construct a builder at the `Warn` level with the `msg` and the `code`.
864 #[rustc_lint_diagnostics]
866 pub fn struct_warn_with_code(
868 msg: impl Into<DiagnosticMessage>,
870 ) -> DiagnosticBuilder<'_, ()> {
871 let mut result = self.struct_warn(msg);
876 /// Construct a builder at the `Fatal` level at the given `span` and with the `msg`.
877 #[rustc_lint_diagnostics]
879 pub fn struct_span_fatal(
881 span: impl Into<MultiSpan>,
882 msg: impl Into<DiagnosticMessage>,
883 ) -> DiagnosticBuilder<'_, !> {
884 let mut result = self.struct_fatal(msg);
885 result.set_span(span);
889 /// Construct a builder at the `Fatal` level at the given `span`, with the `msg`, and `code`.
890 #[rustc_lint_diagnostics]
892 pub fn struct_span_fatal_with_code(
894 span: impl Into<MultiSpan>,
895 msg: impl Into<DiagnosticMessage>,
897 ) -> DiagnosticBuilder<'_, !> {
898 let mut result = self.struct_span_fatal(span, msg);
903 /// Construct a builder at the `Error` level with the `msg`.
904 #[rustc_lint_diagnostics]
906 pub fn struct_fatal(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, !> {
907 DiagnosticBuilder::new_fatal(self, msg)
910 /// Construct a builder at the `Help` level with the `msg`.
911 #[rustc_lint_diagnostics]
912 pub fn struct_help(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> {
913 DiagnosticBuilder::new(self, Level::Help, msg)
916 /// Construct a builder at the `Note` level with the `msg`.
917 #[rustc_lint_diagnostics]
919 pub fn struct_note_without_error(
921 msg: impl Into<DiagnosticMessage>,
922 ) -> DiagnosticBuilder<'_, ()> {
923 DiagnosticBuilder::new(self, Level::Note, msg)
926 #[rustc_lint_diagnostics]
928 pub fn span_fatal(&self, span: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>) -> ! {
929 self.emit_diag_at_span(Diagnostic::new(Fatal, msg), span);
933 #[rustc_lint_diagnostics]
935 pub fn span_fatal_with_code(
937 span: impl Into<MultiSpan>,
938 msg: impl Into<DiagnosticMessage>,
941 self.emit_diag_at_span(Diagnostic::new_with_code(Fatal, Some(code), msg), span);
945 #[rustc_lint_diagnostics]
949 span: impl Into<MultiSpan>,
950 msg: impl Into<DiagnosticMessage>,
951 ) -> ErrorGuaranteed {
952 self.emit_diag_at_span(Diagnostic::new(Error { lint: false }, msg), span).unwrap()
955 #[rustc_lint_diagnostics]
957 pub fn span_err_with_code(
959 span: impl Into<MultiSpan>,
960 msg: impl Into<DiagnosticMessage>,
963 self.emit_diag_at_span(
964 Diagnostic::new_with_code(Error { lint: false }, Some(code), msg),
969 #[rustc_lint_diagnostics]
971 pub fn span_warn(&self, span: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>) {
972 self.emit_diag_at_span(Diagnostic::new(Warning(None), msg), span);
975 #[rustc_lint_diagnostics]
977 pub fn span_warn_with_code(
979 span: impl Into<MultiSpan>,
980 msg: impl Into<DiagnosticMessage>,
983 self.emit_diag_at_span(Diagnostic::new_with_code(Warning(None), Some(code), msg), span);
986 pub fn span_bug(&self, span: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>) -> ! {
987 self.inner.borrow_mut().span_bug(span, msg)
990 /// For documentation on this, see `Session::delay_span_bug`.
992 pub fn delay_span_bug(
994 span: impl Into<MultiSpan>,
995 msg: impl Into<DiagnosticMessage>,
996 ) -> ErrorGuaranteed {
997 self.inner.borrow_mut().delay_span_bug(span, msg)
1000 // FIXME(eddyb) note the comment inside `impl Drop for HandlerInner`, that's
1001 // where the explanation of what "good path" is (also, it should be renamed).
1002 pub fn delay_good_path_bug(&self, msg: impl Into<DiagnosticMessage>) {
1003 self.inner.borrow_mut().delay_good_path_bug(msg)
1007 pub fn span_bug_no_panic(&self, span: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>) {
1008 self.emit_diag_at_span(Diagnostic::new(Bug, msg), span);
1012 pub fn span_note_without_error(
1014 span: impl Into<MultiSpan>,
1015 msg: impl Into<DiagnosticMessage>,
1017 self.emit_diag_at_span(Diagnostic::new(Note, msg), span);
1021 pub fn span_note_diag(
1024 msg: impl Into<DiagnosticMessage>,
1025 ) -> DiagnosticBuilder<'_, ()> {
1026 let mut db = DiagnosticBuilder::new(self, Note, msg);
1031 // NOTE: intentionally doesn't raise an error so rustc_codegen_ssa only reports fatal errors in the main thread
1032 pub fn fatal(&self, msg: impl Into<DiagnosticMessage>) -> FatalError {
1033 self.inner.borrow_mut().fatal(msg)
1036 pub fn err(&self, msg: impl Into<DiagnosticMessage>) -> ErrorGuaranteed {
1037 self.inner.borrow_mut().err(msg)
1040 pub fn warn(&self, msg: impl Into<DiagnosticMessage>) {
1041 let mut db = DiagnosticBuilder::new(self, Warning(None), msg);
1045 pub fn note_without_error(&self, msg: impl Into<DiagnosticMessage>) {
1046 DiagnosticBuilder::new(self, Note, msg).emit();
1049 pub fn bug(&self, msg: impl Into<DiagnosticMessage>) -> ! {
1050 self.inner.borrow_mut().bug(msg)
1054 pub fn err_count(&self) -> usize {
1055 self.inner.borrow().err_count()
1058 pub fn has_errors(&self) -> Option<ErrorGuaranteed> {
1059 if self.inner.borrow().has_errors() { Some(ErrorGuaranteed(())) } else { None }
1061 pub fn has_errors_or_lint_errors(&self) -> Option<ErrorGuaranteed> {
1062 if self.inner.borrow().has_errors_or_lint_errors() {
1063 Some(ErrorGuaranteed::unchecked_claim_error_was_emitted())
1068 pub fn has_errors_or_delayed_span_bugs(&self) -> Option<ErrorGuaranteed> {
1069 if self.inner.borrow().has_errors_or_delayed_span_bugs() {
1070 Some(ErrorGuaranteed::unchecked_claim_error_was_emitted())
1075 pub fn is_compilation_going_to_fail(&self) -> Option<ErrorGuaranteed> {
1076 if self.inner.borrow().is_compilation_going_to_fail() {
1077 Some(ErrorGuaranteed::unchecked_claim_error_was_emitted())
1083 pub fn print_error_count(&self, registry: &Registry) {
1084 self.inner.borrow_mut().print_error_count(registry)
1087 pub fn take_future_breakage_diagnostics(&self) -> Vec<Diagnostic> {
1088 std::mem::take(&mut self.inner.borrow_mut().future_breakage_diagnostics)
1091 pub fn abort_if_errors(&self) {
1092 self.inner.borrow_mut().abort_if_errors()
1095 /// `true` if we haven't taught a diagnostic with this code already.
1096 /// The caller must then teach the user about such a diagnostic.
1098 /// Used to suppress emitting the same error multiple times with extended explanation when
1099 /// calling `-Zteach`.
1100 pub fn must_teach(&self, code: &DiagnosticId) -> bool {
1101 self.inner.borrow_mut().must_teach(code)
1104 pub fn force_print_diagnostic(&self, db: Diagnostic) {
1105 self.inner.borrow_mut().force_print_diagnostic(db)
1108 pub fn emit_diagnostic(&self, diagnostic: &mut Diagnostic) -> Option<ErrorGuaranteed> {
1109 self.inner.borrow_mut().emit_diagnostic(diagnostic)
1112 pub fn emit_err<'a>(&'a self, err: impl IntoDiagnostic<'a>) -> ErrorGuaranteed {
1113 self.create_err(err).emit()
1116 pub fn create_err<'a>(
1118 err: impl IntoDiagnostic<'a>,
1119 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
1120 err.into_diagnostic(self)
1123 pub fn create_warning<'a>(
1125 warning: impl IntoDiagnostic<'a, ()>,
1126 ) -> DiagnosticBuilder<'a, ()> {
1127 warning.into_diagnostic(self)
1130 pub fn emit_warning<'a>(&'a self, warning: impl IntoDiagnostic<'a, ()>) {
1131 self.create_warning(warning).emit()
1134 pub fn create_fatal<'a>(
1136 fatal: impl IntoDiagnostic<'a, !>,
1137 ) -> DiagnosticBuilder<'a, !> {
1138 fatal.into_diagnostic(self)
1141 pub fn emit_fatal<'a>(&'a self, fatal: impl IntoDiagnostic<'a, !>) -> ! {
1142 self.create_fatal(fatal).emit()
1145 pub fn create_bug<'a>(
1147 bug: impl IntoDiagnostic<'a, diagnostic_builder::Bug>,
1148 ) -> DiagnosticBuilder<'a, diagnostic_builder::Bug> {
1149 bug.into_diagnostic(self)
1152 pub fn emit_bug<'a>(
1154 bug: impl IntoDiagnostic<'a, diagnostic_builder::Bug>,
1155 ) -> diagnostic_builder::Bug {
1156 self.create_bug(bug).emit()
1159 fn emit_diag_at_span(
1161 mut diag: Diagnostic,
1162 sp: impl Into<MultiSpan>,
1163 ) -> Option<ErrorGuaranteed> {
1164 let mut inner = self.inner.borrow_mut();
1165 inner.emit_diagnostic(diag.set_span(sp))
1168 pub fn emit_artifact_notification(&self, path: &Path, artifact_type: &str) {
1169 self.inner.borrow_mut().emit_artifact_notification(path, artifact_type)
1172 pub fn emit_future_breakage_report(&self, diags: Vec<Diagnostic>) {
1173 self.inner.borrow_mut().emitter.emit_future_breakage_report(diags)
1176 pub fn emit_unused_externs(
1178 lint_level: rustc_lint_defs::Level,
1180 unused_externs: &[&str],
1182 let mut inner = self.inner.borrow_mut();
1184 if loud && lint_level.is_error() {
1185 inner.bump_err_count();
1188 inner.emit_unused_externs(lint_level, unused_externs)
1191 pub fn update_unstable_expectation_id(
1193 unstable_to_stable: &FxHashMap<LintExpectationId, LintExpectationId>,
1195 let mut inner = self.inner.borrow_mut();
1196 let diags = std::mem::take(&mut inner.unstable_expect_diagnostics);
1197 inner.check_unstable_expect_diagnostics = true;
1199 if !diags.is_empty() {
1200 inner.suppressed_expected_diag = true;
1201 for mut diag in diags.into_iter() {
1202 diag.update_unstable_expectation_id(unstable_to_stable);
1204 // Here the diagnostic is given back to `emit_diagnostic` where it was first
1205 // intercepted. Now it should be processed as usual, since the unstable expectation
1206 // id is now stable.
1207 inner.emit_diagnostic(&mut diag);
1212 .stashed_diagnostics
1214 .for_each(|diag| diag.update_unstable_expectation_id(unstable_to_stable));
1216 .future_breakage_diagnostics
1218 .for_each(|diag| diag.update_unstable_expectation_id(unstable_to_stable));
1221 /// This methods steals all [`LintExpectationId`]s that are stored inside
1222 /// [`HandlerInner`] and indicate that the linked expectation has been fulfilled.
1224 pub fn steal_fulfilled_expectation_ids(&self) -> FxHashSet<LintExpectationId> {
1226 self.inner.borrow().unstable_expect_diagnostics.is_empty(),
1227 "`HandlerInner::unstable_expect_diagnostics` should be empty at this point",
1229 std::mem::take(&mut self.inner.borrow_mut().fulfilled_expectations)
1232 pub fn flush_delayed(&self) {
1233 let mut inner = self.inner.lock();
1234 let bugs = std::mem::replace(&mut inner.delayed_span_bugs, Vec::new());
1235 inner.flush_delayed(bugs, "no errors encountered even though `delay_span_bug` issued");
1240 fn must_teach(&mut self, code: &DiagnosticId) -> bool {
1241 self.taught_diagnostics.insert(code.clone())
1244 fn force_print_diagnostic(&mut self, db: Diagnostic) {
1245 self.emitter.emit_diagnostic(&db);
1248 /// Emit all stashed diagnostics.
1249 fn emit_stashed_diagnostics(&mut self) -> Option<ErrorGuaranteed> {
1250 let has_errors = self.has_errors();
1251 let diags = self.stashed_diagnostics.drain(..).map(|x| x.1).collect::<Vec<_>>();
1252 let mut reported = None;
1253 for mut diag in diags {
1254 // Decrement the count tracking the stash; emitting will increment it.
1255 if diag.is_error() {
1256 if matches!(diag.level, Level::Error { lint: true }) {
1257 self.lint_err_count -= 1;
1259 self.err_count -= 1;
1262 if diag.is_force_warn() {
1263 self.warn_count -= 1;
1265 // Unless they're forced, don't flush stashed warnings when
1266 // there are errors, to avoid causing warning overload. The
1267 // stash would've been stolen already if it were important.
1273 let reported_this = self.emit_diagnostic(&mut diag);
1274 reported = reported.or(reported_this);
1279 // FIXME(eddyb) this should ideally take `diagnostic` by value.
1280 fn emit_diagnostic(&mut self, diagnostic: &mut Diagnostic) -> Option<ErrorGuaranteed> {
1281 // The `LintExpectationId` can be stable or unstable depending on when it was created.
1282 // Diagnostics created before the definition of `HirId`s are unstable and can not yet
1283 // be stored. Instead, they are buffered until the `LintExpectationId` is replaced by
1284 // a stable one by the `LintLevelsBuilder`.
1285 if let Some(LintExpectationId::Unstable { .. }) = diagnostic.level.get_expectation_id() {
1286 self.unstable_expect_diagnostics.push(diagnostic.clone());
1290 if diagnostic.level == Level::DelayedBug {
1291 // FIXME(eddyb) this should check for `has_errors` and stop pushing
1292 // once *any* errors were emitted (and truncate `delayed_span_bugs`
1293 // when an error is first emitted, also), but maybe there's a case
1294 // in which that's not sound? otherwise this is really inefficient.
1295 let backtrace = std::backtrace::Backtrace::force_capture();
1296 self.delayed_span_bugs
1297 .push(DelayedDiagnostic::with_backtrace(diagnostic.clone(), backtrace));
1299 if !self.flags.report_delayed_bugs {
1300 return Some(ErrorGuaranteed::unchecked_claim_error_was_emitted());
1304 if diagnostic.has_future_breakage() {
1305 // Future breakages aren't emitted if they're Level::Allowed,
1306 // but they still need to be constructed and stashed below,
1307 // so they'll trigger the good-path bug check.
1308 self.suppressed_expected_diag = true;
1309 self.future_breakage_diagnostics.push(diagnostic.clone());
1312 if let Some(expectation_id) = diagnostic.level.get_expectation_id() {
1313 self.suppressed_expected_diag = true;
1314 self.fulfilled_expectations.insert(expectation_id.normalize());
1317 if matches!(diagnostic.level, Warning(_))
1318 && !self.flags.can_emit_warnings
1319 && !diagnostic.is_force_warn()
1321 if diagnostic.has_future_breakage() {
1322 (*TRACK_DIAGNOSTICS)(diagnostic, &mut |_| {});
1327 if matches!(diagnostic.level, Level::Expect(_) | Level::Allow) {
1328 (*TRACK_DIAGNOSTICS)(diagnostic, &mut |_| {});
1332 let mut guaranteed = None;
1333 (*TRACK_DIAGNOSTICS)(diagnostic, &mut |diagnostic| {
1334 if let Some(ref code) = diagnostic.code {
1335 self.emitted_diagnostic_codes.insert(code.clone());
1338 let already_emitted = |this: &mut Self| {
1339 let mut hasher = StableHasher::new();
1340 diagnostic.hash(&mut hasher);
1341 let diagnostic_hash = hasher.finish();
1342 !this.emitted_diagnostics.insert(diagnostic_hash)
1345 // Only emit the diagnostic if we've been asked to deduplicate or
1346 // haven't already emitted an equivalent diagnostic.
1347 if !(self.flags.deduplicate_diagnostics && already_emitted(self)) {
1348 debug!(?diagnostic);
1349 debug!(?self.emitted_diagnostics);
1350 let already_emitted_sub = |sub: &mut SubDiagnostic| {
1352 if sub.level != Level::OnceNote {
1355 let mut hasher = StableHasher::new();
1356 sub.hash(&mut hasher);
1357 let diagnostic_hash = hasher.finish();
1358 debug!(?diagnostic_hash);
1359 !self.emitted_diagnostics.insert(diagnostic_hash)
1362 diagnostic.children.drain_filter(already_emitted_sub).for_each(|_| {});
1364 self.emitter.emit_diagnostic(diagnostic);
1365 if diagnostic.is_error() {
1366 self.deduplicated_err_count += 1;
1367 } else if let Warning(_) = diagnostic.level {
1368 self.deduplicated_warn_count += 1;
1371 if diagnostic.is_error() {
1372 if matches!(diagnostic.level, Level::Error { lint: true }) {
1373 self.bump_lint_err_count();
1375 self.bump_err_count();
1378 guaranteed = Some(ErrorGuaranteed::unchecked_claim_error_was_emitted());
1380 self.bump_warn_count();
1387 fn emit_artifact_notification(&mut self, path: &Path, artifact_type: &str) {
1388 self.emitter.emit_artifact_notification(path, artifact_type);
1391 fn emit_unused_externs(&mut self, lint_level: rustc_lint_defs::Level, unused_externs: &[&str]) {
1392 self.emitter.emit_unused_externs(lint_level, unused_externs);
1395 fn treat_err_as_bug(&self) -> bool {
1396 self.flags.treat_err_as_bug.map_or(false, |c| {
1397 self.err_count() + self.lint_err_count + self.delayed_bug_count() >= c.get()
1401 fn delayed_bug_count(&self) -> usize {
1402 self.delayed_span_bugs.len() + self.delayed_good_path_bugs.len()
1405 fn print_error_count(&mut self, registry: &Registry) {
1406 self.emit_stashed_diagnostics();
1408 let warnings = match self.deduplicated_warn_count {
1410 1 => "1 warning emitted".to_string(),
1411 count => format!("{count} warnings emitted"),
1413 let errors = match self.deduplicated_err_count {
1415 1 => "aborting due to previous error".to_string(),
1416 count => format!("aborting due to {count} previous errors"),
1418 if self.treat_err_as_bug() {
1422 match (errors.len(), warnings.len()) {
1424 (0, _) => self.emitter.emit_diagnostic(&Diagnostic::new(
1425 Level::Warning(None),
1426 DiagnosticMessage::Str(warnings),
1429 let _ = self.fatal(&errors);
1432 let _ = self.fatal(&format!("{}; {}", &errors, &warnings));
1436 let can_show_explain = self.emitter.should_show_explain();
1437 let are_there_diagnostics = !self.emitted_diagnostic_codes.is_empty();
1438 if can_show_explain && are_there_diagnostics {
1439 let mut error_codes = self
1440 .emitted_diagnostic_codes
1442 .filter_map(|x| match &x {
1443 DiagnosticId::Error(s)
1444 if registry.try_find_description(s).map_or(false, |o| o.is_some()) =>
1450 .collect::<Vec<_>>();
1451 if !error_codes.is_empty() {
1453 if error_codes.len() > 1 {
1454 let limit = if error_codes.len() > 9 { 9 } else { error_codes.len() };
1455 self.failure(&format!(
1456 "Some errors have detailed explanations: {}{}",
1457 error_codes[..limit].join(", "),
1458 if error_codes.len() > 9 { "..." } else { "." }
1460 self.failure(&format!(
1461 "For more information about an error, try \
1462 `rustc --explain {}`.",
1466 self.failure(&format!(
1467 "For more information about this error, try \
1468 `rustc --explain {}`.",
1476 fn stash(&mut self, key: (Span, StashKey), diagnostic: Diagnostic) {
1477 // Track the diagnostic for counts, but don't panic-if-treat-err-as-bug
1478 // yet; that happens when we actually emit the diagnostic.
1479 if diagnostic.is_error() {
1480 if matches!(diagnostic.level, Level::Error { lint: true }) {
1481 self.lint_err_count += 1;
1483 self.err_count += 1;
1486 // Warnings are only automatically flushed if they're forced.
1487 if diagnostic.is_force_warn() {
1488 self.warn_count += 1;
1492 // FIXME(Centril, #69537): Consider reintroducing panic on overwriting a stashed diagnostic
1493 // if/when we have a more robust macro-friendly replacement for `(span, key)` as a key.
1494 // See the PR for a discussion.
1495 self.stashed_diagnostics.insert(key, diagnostic);
1498 fn steal(&mut self, key: (Span, StashKey)) -> Option<Diagnostic> {
1499 let diagnostic = self.stashed_diagnostics.remove(&key)?;
1500 if diagnostic.is_error() {
1501 if matches!(diagnostic.level, Level::Error { lint: true }) {
1502 self.lint_err_count -= 1;
1504 self.err_count -= 1;
1507 if diagnostic.is_force_warn() {
1508 self.warn_count -= 1;
1515 fn err_count(&self) -> usize {
1519 fn has_errors(&self) -> bool {
1520 self.err_count() > 0
1522 fn has_errors_or_lint_errors(&self) -> bool {
1523 self.has_errors() || self.lint_err_count > 0
1525 fn has_errors_or_delayed_span_bugs(&self) -> bool {
1526 self.has_errors() || !self.delayed_span_bugs.is_empty()
1528 fn has_any_message(&self) -> bool {
1529 self.err_count() > 0 || self.lint_err_count > 0 || self.warn_count > 0
1532 fn is_compilation_going_to_fail(&self) -> bool {
1533 self.has_errors() || self.lint_err_count > 0 || !self.delayed_span_bugs.is_empty()
1536 fn abort_if_errors(&mut self) {
1537 self.emit_stashed_diagnostics();
1539 if self.has_errors() {
1545 fn span_bug(&mut self, sp: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>) -> ! {
1546 self.emit_diag_at_span(Diagnostic::new(Bug, msg), sp);
1547 panic::panic_any(ExplicitBug);
1550 fn emit_diag_at_span(&mut self, mut diag: Diagnostic, sp: impl Into<MultiSpan>) {
1551 self.emit_diagnostic(diag.set_span(sp));
1554 /// For documentation on this, see `Session::delay_span_bug`.
1558 sp: impl Into<MultiSpan>,
1559 msg: impl Into<DiagnosticMessage>,
1560 ) -> ErrorGuaranteed {
1561 // This is technically `self.treat_err_as_bug()` but `delay_span_bug` is called before
1562 // incrementing `err_count` by one, so we need to +1 the comparing.
1563 // FIXME: Would be nice to increment err_count in a more coherent way.
1564 if self.flags.treat_err_as_bug.map_or(false, |c| {
1565 self.err_count() + self.lint_err_count + self.delayed_bug_count() + 1 >= c.get()
1567 // FIXME: don't abort here if report_delayed_bugs is off
1568 self.span_bug(sp, msg);
1570 let mut diagnostic = Diagnostic::new(Level::DelayedBug, msg);
1571 diagnostic.set_span(sp.into());
1572 self.emit_diagnostic(&mut diagnostic).unwrap()
1575 // FIXME(eddyb) note the comment inside `impl Drop for HandlerInner`, that's
1576 // where the explanation of what "good path" is (also, it should be renamed).
1577 fn delay_good_path_bug(&mut self, msg: impl Into<DiagnosticMessage>) {
1578 let mut diagnostic = Diagnostic::new(Level::DelayedBug, msg);
1579 if self.flags.report_delayed_bugs {
1580 self.emit_diagnostic(&mut diagnostic);
1582 let backtrace = std::backtrace::Backtrace::force_capture();
1583 self.delayed_good_path_bugs.push(DelayedDiagnostic::with_backtrace(diagnostic, backtrace));
1586 fn failure(&mut self, msg: impl Into<DiagnosticMessage>) {
1587 self.emit_diagnostic(&mut Diagnostic::new(FailureNote, msg));
1590 fn fatal(&mut self, msg: impl Into<DiagnosticMessage>) -> FatalError {
1591 self.emit(Fatal, msg);
1595 fn err(&mut self, msg: impl Into<DiagnosticMessage>) -> ErrorGuaranteed {
1596 self.emit(Error { lint: false }, msg)
1599 /// Emit an error; level should be `Error` or `Fatal`.
1600 fn emit(&mut self, level: Level, msg: impl Into<DiagnosticMessage>) -> ErrorGuaranteed {
1601 if self.treat_err_as_bug() {
1604 self.emit_diagnostic(&mut Diagnostic::new(level, msg)).unwrap()
1607 fn bug(&mut self, msg: impl Into<DiagnosticMessage>) -> ! {
1608 self.emit_diagnostic(&mut Diagnostic::new(Bug, msg));
1609 panic::panic_any(ExplicitBug);
1614 bugs: impl IntoIterator<Item = DelayedDiagnostic>,
1615 explanation: impl Into<DiagnosticMessage> + Copy,
1617 let mut no_bugs = true;
1619 let mut bug = bug.decorate();
1622 // Put the overall explanation before the `DelayedBug`s, to
1623 // frame them better (e.g. separate warnings from them).
1624 self.emit_diagnostic(&mut Diagnostic::new(Bug, explanation));
1628 // "Undelay" the `DelayedBug`s (into plain `Bug`s).
1629 if bug.level != Level::DelayedBug {
1630 // NOTE(eddyb) not panicking here because we're already producing
1631 // an ICE, and the more information the merrier.
1633 "`flushed_delayed` got diagnostic with level {:?}, \
1634 instead of the expected `DelayedBug`",
1638 bug.level = Level::Bug;
1640 self.emit_diagnostic(&mut bug);
1643 // Panic with `DelayedBugPanic` to avoid "unexpected panic" messages.
1645 panic::panic_any(DelayedBugPanic);
1649 fn bump_lint_err_count(&mut self) {
1650 self.lint_err_count += 1;
1651 self.panic_if_treat_err_as_bug();
1654 fn bump_err_count(&mut self) {
1655 self.err_count += 1;
1656 self.panic_if_treat_err_as_bug();
1659 fn bump_warn_count(&mut self) {
1660 self.warn_count += 1;
1663 fn panic_if_treat_err_as_bug(&self) {
1664 if self.treat_err_as_bug() {
1666 self.err_count() + self.lint_err_count,
1667 self.delayed_bug_count(),
1668 self.flags.treat_err_as_bug.map(|c| c.get()).unwrap_or(0),
1670 (1, 0, 1) => panic!("aborting due to `-Z treat-err-as-bug=1`"),
1671 (0, 1, 1) => panic!("aborting due delayed bug with `-Z treat-err-as-bug=1`"),
1672 (count, delayed_count, as_bug) => {
1673 if delayed_count > 0 {
1675 "aborting after {} errors and {} delayed bugs due to `-Z treat-err-as-bug={}`",
1676 count, delayed_count, as_bug,
1680 "aborting after {} errors due to `-Z treat-err-as-bug={}`",
1690 struct DelayedDiagnostic {
1695 impl DelayedDiagnostic {
1696 fn with_backtrace(diagnostic: Diagnostic, backtrace: Backtrace) -> Self {
1697 DelayedDiagnostic { inner: diagnostic, note: backtrace }
1700 fn decorate(mut self) -> Diagnostic {
1701 self.inner.note(&format!("delayed at {}", self.note));
1706 #[derive(Copy, PartialEq, Eq, Clone, Hash, Debug, Encodable, Decodable)]
1712 /// If this error comes from a lint, don't abort compilation even when abort_if_errors() is called.
1715 /// This [`LintExpectationId`] is used for expected lint diagnostics, which should
1716 /// also emit a warning due to the `force-warn` flag. In all other cases this should
1718 Warning(Option<LintExpectationId>),
1720 /// A note that is only emitted once.
1725 Expect(LintExpectationId),
1728 impl fmt::Display for Level {
1729 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1730 self.to_str().fmt(f)
1735 fn color(self) -> ColorSpec {
1736 let mut spec = ColorSpec::new();
1738 Bug | DelayedBug | Fatal | Error { .. } => {
1739 spec.set_fg(Some(Color::Red)).set_intense(true);
1742 spec.set_fg(Some(Color::Yellow)).set_intense(cfg!(windows));
1744 Note | OnceNote => {
1745 spec.set_fg(Some(Color::Green)).set_intense(true);
1748 spec.set_fg(Some(Color::Cyan)).set_intense(true);
1751 Allow | Expect(_) => unreachable!(),
1756 pub fn to_str(self) -> &'static str {
1758 Bug | DelayedBug => "error: internal compiler error",
1759 Fatal | Error { .. } => "error",
1760 Warning(_) => "warning",
1761 Note | OnceNote => "note",
1763 FailureNote => "failure-note",
1764 Allow => panic!("Shouldn't call on allowed error"),
1765 Expect(_) => panic!("Shouldn't call on expected error"),
1769 pub fn is_failure_note(&self) -> bool {
1770 matches!(*self, FailureNote)
1773 pub fn get_expectation_id(&self) -> Option<LintExpectationId> {
1775 Level::Expect(id) | Level::Warning(Some(id)) => Some(*id),
1781 // FIXME(eddyb) this doesn't belong here AFAICT, should be moved to callsite.
1782 pub fn add_elided_lifetime_in_path_suggestion(
1783 source_map: &SourceMap,
1784 diag: &mut Diagnostic,
1787 incl_angl_brckt: bool,
1788 insertion_span: Span,
1790 diag.span_label(path_span, format!("expected lifetime parameter{}", pluralize!(n)));
1791 if !source_map.is_span_accessible(insertion_span) {
1792 // Do not try to suggest anything if generated by a proc-macro.
1795 let anon_lts = vec!["'_"; n].join(", ");
1797 if incl_angl_brckt { format!("<{}>", anon_lts) } else { format!("{}, ", anon_lts) };
1798 diag.span_suggestion_verbose(
1799 insertion_span.shrink_to_hi(),
1800 &format!("indicate the anonymous lifetime{}", pluralize!(n)),
1802 Applicability::MachineApplicable,
1806 /// Useful type to use with `Result<>` indicate that an error has already
1807 /// been reported to the user, so no need to continue checking.
1808 #[derive(Clone, Copy, Debug, Encodable, Decodable, Hash, PartialEq, Eq, PartialOrd, Ord)]
1809 #[derive(HashStable_Generic)]
1810 pub struct ErrorGuaranteed(());
1812 impl ErrorGuaranteed {
1813 /// To be used only if you really know what you are doing... ideally, we would find a way to
1814 /// eliminate all calls to this method.
1815 pub fn unchecked_claim_error_was_emitted() -> Self {