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(array_windows)]
7 #![feature(drain_filter)]
8 #![feature(if_let_guard)]
9 #![feature(is_terminal)]
10 #![feature(adt_const_params)]
11 #![feature(let_chains)]
12 #![feature(never_type)]
13 #![feature(result_option_inspect)]
14 #![feature(rustc_attrs)]
15 #![feature(yeet_expr)]
16 #![feature(try_blocks)]
17 #![feature(box_patterns)]
18 #![feature(error_reporter)]
19 #![allow(incomplete_features)]
22 extern crate rustc_macros;
27 pub use emitter::ColorConfig;
29 use rustc_lint_defs::LintExpectationId;
32 use emitter::{is_case_difference, Emitter, EmitterWriter};
33 use registry::Registry;
34 use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet};
35 use rustc_data_structures::stable_hasher::StableHasher;
36 use rustc_data_structures::sync::{self, Lock, Lrc};
37 use rustc_data_structures::AtomicRef;
38 pub use rustc_error_messages::{
39 fallback_fluent_bundle, fluent, fluent_bundle, DelayDm, DiagnosticMessage, FluentBundle,
40 LanguageIdentifier, LazyFallbackBundle, MultiSpan, SpanLabel, SubdiagnosticMessage,
41 DEFAULT_LOCALE_RESOURCES,
43 pub use rustc_lint_defs::{pluralize, Applicability};
44 use rustc_span::source_map::SourceMap;
45 use rustc_span::HashStableContext;
46 use rustc_span::{Loc, Span};
49 use std::error::Report;
52 use std::num::NonZeroUsize;
56 use termcolor::{Color, ColorSpec};
58 pub mod annotate_snippet_emitter_writer;
60 mod diagnostic_builder;
73 pub use diagnostic_builder::IntoDiagnostic;
74 pub use snippet::Style;
76 pub type PErr<'a> = DiagnosticBuilder<'a, ErrorGuaranteed>;
77 pub type PResult<'a, T> = Result<T, PErr<'a>>;
79 // `PResult` is used a lot. Make sure it doesn't unintentionally get bigger.
80 // (See also the comment on `DiagnosticBuilderInner`'s `diagnostic` field.)
81 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
82 rustc_data_structures::static_assert_size!(PResult<'_, ()>, 16);
83 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
84 rustc_data_structures::static_assert_size!(PResult<'_, bool>, 16);
86 #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, Encodable, Decodable)]
87 pub enum SuggestionStyle {
88 /// Hide the suggested code when displaying this suggestion inline.
90 /// Always hide the suggested code but display the message.
92 /// Do not display this suggestion in the cli output, it is only meant for tools.
94 /// Always show the suggested code.
95 /// This will *not* show the code if the suggestion is inline *and* the suggested code is
98 /// Always show the suggested code independently.
102 impl SuggestionStyle {
103 fn hide_inline(&self) -> bool {
104 !matches!(*self, SuggestionStyle::ShowCode)
108 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
109 pub struct CodeSuggestion {
110 /// Each substitute can have multiple variants due to multiple
111 /// applicable suggestions
113 /// `foo.bar` might be replaced with `a.b` or `x.y` by replacing
114 /// `foo` and `bar` on their own:
116 /// ```ignore (illustrative)
118 /// Substitution { parts: vec![(0..3, "a"), (4..7, "b")] },
119 /// Substitution { parts: vec![(0..3, "x"), (4..7, "y")] },
123 /// or by replacing the entire span:
125 /// ```ignore (illustrative)
127 /// Substitution { parts: vec![(0..7, "a.b")] },
128 /// Substitution { parts: vec![(0..7, "x.y")] },
131 pub substitutions: Vec<Substitution>,
132 pub msg: DiagnosticMessage,
133 /// Visual representation of this suggestion.
134 pub style: SuggestionStyle,
135 /// Whether or not the suggestion is approximate
137 /// Sometimes we may show suggestions with placeholders,
138 /// which are useful for users but not useful for
139 /// tools like rustfix
140 pub applicability: Applicability,
143 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
144 /// See the docs on `CodeSuggestion::substitutions`
145 pub struct Substitution {
146 pub parts: Vec<SubstitutionPart>,
149 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
150 pub struct SubstitutionPart {
155 /// Used to translate between `Span`s and byte positions within a single output line in highlighted
156 /// code of structured suggestions.
157 #[derive(Debug, Clone, Copy)]
158 pub struct SubstitutionHighlight {
163 impl SubstitutionPart {
164 pub fn is_addition(&self, sm: &SourceMap) -> bool {
165 !self.snippet.is_empty() && !self.replaces_meaningful_content(sm)
168 pub fn is_deletion(&self, sm: &SourceMap) -> bool {
169 self.snippet.trim().is_empty() && self.replaces_meaningful_content(sm)
172 pub fn is_replacement(&self, sm: &SourceMap) -> bool {
173 !self.snippet.is_empty() && self.replaces_meaningful_content(sm)
176 fn replaces_meaningful_content(&self, sm: &SourceMap) -> bool {
177 sm.span_to_snippet(self.span)
178 .map_or(!self.span.is_empty(), |snippet| !snippet.trim().is_empty())
182 impl CodeSuggestion {
183 /// Returns the assembled code suggestions, whether they should be shown with an underline
184 /// and whether the substitution only differs in capitalization.
188 ) -> Vec<(String, Vec<SubstitutionPart>, Vec<Vec<SubstitutionHighlight>>, bool)> {
189 // For the `Vec<Vec<SubstitutionHighlight>>` value, the first level of the vector
190 // corresponds to the output snippet's lines, while the second level corresponds to the
191 // substrings within that line that should be highlighted.
193 use rustc_span::{CharPos, Pos};
195 /// Append to a buffer the remainder of the line of existing source code, and return the
196 /// count of lines that have been added for accurate highlighting.
199 line_opt: Option<&Cow<'_, str>>,
201 hi_opt: Option<&Loc>,
203 let mut line_count = 0;
204 let (lo, hi_opt) = (lo.col.to_usize(), hi_opt.map(|hi| hi.col.to_usize()));
205 if let Some(line) = line_opt {
206 if let Some(lo) = line.char_indices().map(|(i, _)| i).nth(lo) {
207 let hi_opt = hi_opt.and_then(|hi| line.char_indices().map(|(i, _)| i).nth(hi));
209 Some(hi) if hi > lo => {
210 line_count = line[lo..hi].matches('\n').count();
211 buf.push_str(&line[lo..hi])
215 line_count = line[lo..].matches('\n').count();
216 buf.push_str(&line[lo..])
220 if hi_opt.is_none() {
227 assert!(!self.substitutions.is_empty());
232 // Suggestions coming from macros can have malformed spans. This is a heavy
233 // handed approach to avoid ICEs by ignoring the suggestion outright.
234 let invalid = subst.parts.iter().any(|item| sm.is_valid_span(item.span).is_err());
236 debug!("splice_lines: suggestion contains an invalid span: {:?}", subst);
241 .filter_map(|mut substitution| {
242 // Assumption: all spans are in the same file, and all spans
243 // are disjoint. Sort in ascending order.
244 substitution.parts.sort_by_key(|part| part.span.lo());
246 // Find the bounding span.
247 let lo = substitution.parts.iter().map(|part| part.span.lo()).min()?;
248 let hi = substitution.parts.iter().map(|part| part.span.hi()).max()?;
249 let bounding_span = Span::with_root_ctxt(lo, hi);
250 // The different spans might belong to different contexts, if so ignore suggestion.
251 let lines = sm.span_to_lines(bounding_span).ok()?;
252 assert!(!lines.lines.is_empty() || bounding_span.is_dummy());
254 // We can't splice anything if the source is unavailable.
255 if !sm.ensure_source_file_source_present(lines.file.clone()) {
259 let mut highlights = vec![];
260 // To build up the result, we do this for each span:
261 // - push the line segment trailing the previous span
262 // (at the beginning a "phantom" span pointing at the start of the line)
263 // - push lines between the previous and current span (if any)
264 // - if the previous and current span are not on the same line
265 // push the line segment leading up to the current span
266 // - splice in the span substitution
268 // Finally push the trailing line segment of the last span
269 let sf = &lines.file;
270 let mut prev_hi = sm.lookup_char_pos(bounding_span.lo());
271 prev_hi.col = CharPos::from_usize(0);
273 lines.lines.get(0).and_then(|line0| sf.get_line(line0.line_index));
274 let mut buf = String::new();
276 let mut line_highlight = vec![];
277 // We need to keep track of the difference between the existing code and the added
278 // or deleted code in order to point at the correct column *after* substitution.
280 for part in &substitution.parts {
281 let cur_lo = sm.lookup_char_pos(part.span.lo());
282 if prev_hi.line == cur_lo.line {
284 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, Some(&cur_lo));
286 highlights.push(std::mem::take(&mut line_highlight));
292 highlights.push(std::mem::take(&mut line_highlight));
293 let mut count = push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
295 highlights.push(std::mem::take(&mut line_highlight));
298 // push lines between the previous and current span (if any)
299 for idx in prev_hi.line..(cur_lo.line - 1) {
300 if let Some(line) = sf.get_line(idx) {
301 buf.push_str(line.as_ref());
303 highlights.push(std::mem::take(&mut line_highlight));
306 if let Some(cur_line) = sf.get_line(cur_lo.line - 1) {
307 let end = match cur_line.char_indices().nth(cur_lo.col.to_usize()) {
309 None => cur_line.len(),
311 buf.push_str(&cur_line[..end]);
314 // Add a whole line highlight per line in the snippet.
315 let len: isize = part
319 .unwrap_or(&part.snippet)
326 line_highlight.push(SubstitutionHighlight {
327 start: (cur_lo.col.0 as isize + acc) as usize,
328 end: (cur_lo.col.0 as isize + acc + len) as usize,
330 buf.push_str(&part.snippet);
331 let cur_hi = sm.lookup_char_pos(part.span.hi());
332 if prev_hi.line == cur_lo.line && cur_hi.line == cur_lo.line {
333 // Account for the difference between the width of the current code and the
334 // snippet being suggested, so that the *later* suggestions are correctly
335 // aligned on the screen.
336 acc += len - (cur_hi.col.0 - cur_lo.col.0) as isize;
339 prev_line = sf.get_line(prev_hi.line - 1);
340 for line in part.snippet.split('\n').skip(1) {
342 highlights.push(std::mem::take(&mut line_highlight));
343 let end: usize = line
350 line_highlight.push(SubstitutionHighlight { start: 0, end });
353 highlights.push(std::mem::take(&mut line_highlight));
354 let only_capitalization = is_case_difference(sm, &buf, bounding_span);
355 // if the replacement already ends with a newline, don't print the next line
356 if !buf.ends_with('\n') {
357 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
359 // remove trailing newlines
360 while buf.ends_with('\n') {
363 Some((buf, substitution.parts, highlights, only_capitalization))
369 pub use rustc_span::fatal_error::{FatalError, FatalErrorMarker};
371 /// Signifies that the compiler died with an explicit call to `.bug`
372 /// or `.span_bug` rather than a failed assertion, etc.
373 pub struct ExplicitBug;
375 /// Signifies that the compiler died with an explicit call to `.delay_*_bug`
376 /// rather than a failed assertion, etc.
377 pub struct DelayedBugPanic;
379 pub use diagnostic::{
380 AddToDiagnostic, DecorateLint, Diagnostic, DiagnosticArg, DiagnosticArgValue, DiagnosticId,
381 DiagnosticStyledString, IntoDiagnosticArg, SubDiagnostic,
383 pub use diagnostic_builder::{DiagnosticBuilder, EmissionGuarantee, Noted};
384 pub use diagnostic_impls::{DiagnosticArgFromDisplay, DiagnosticSymbolList};
385 use std::backtrace::Backtrace;
387 /// A handler deals with errors and other compiler output.
388 /// Certain errors (fatal, bug, unimpl) may cause immediate exit,
389 /// others log errors for later reporting.
392 inner: Lock<HandlerInner>,
395 /// This inner struct exists to keep it all behind a single lock;
396 /// this is done to prevent possible deadlocks in a multi-threaded compiler,
397 /// as well as inconsistent state observation.
398 struct HandlerInner {
400 /// The number of lint errors that have been emitted.
401 lint_err_count: usize,
402 /// The number of errors that have been emitted, including duplicates.
404 /// This is not necessarily the count that's reported to the user once
405 /// compilation ends.
408 deduplicated_err_count: usize,
409 emitter: Box<dyn Emitter + sync::Send>,
410 delayed_span_bugs: Vec<DelayedDiagnostic>,
411 delayed_good_path_bugs: Vec<DelayedDiagnostic>,
412 /// This flag indicates that an expected diagnostic was emitted and suppressed.
413 /// This is used for the `delayed_good_path_bugs` check.
414 suppressed_expected_diag: bool,
416 /// This set contains the `DiagnosticId` of all emitted diagnostics to avoid
417 /// emitting the same diagnostic with extended help (`--teach`) twice, which
418 /// would be unnecessary repetition.
419 taught_diagnostics: FxHashSet<DiagnosticId>,
421 /// Used to suggest rustc --explain `<error code>`
422 emitted_diagnostic_codes: FxIndexSet<DiagnosticId>,
424 /// This set contains a hash of every diagnostic that has been emitted by
425 /// this handler. These hashes is used to avoid emitting the same error
427 emitted_diagnostics: FxHashSet<u128>,
429 /// Stashed diagnostics emitted in one stage of the compiler that may be
430 /// stolen by other stages (e.g. to improve them and add more information).
431 /// The stashed diagnostics count towards the total error count.
432 /// When `.abort_if_errors()` is called, these are also emitted.
433 stashed_diagnostics: FxIndexMap<(Span, StashKey), Diagnostic>,
435 /// The warning count, used for a recap upon finishing
436 deduplicated_warn_count: usize,
438 future_breakage_diagnostics: Vec<Diagnostic>,
440 /// The [`Self::unstable_expect_diagnostics`] should be empty when this struct is
441 /// dropped. However, it can have values if the compilation is stopped early
442 /// or is only partially executed. To avoid ICEs, like in rust#94953 we only
443 /// check if [`Self::unstable_expect_diagnostics`] is empty, if the expectation ids
444 /// have been converted.
445 check_unstable_expect_diagnostics: bool,
447 /// Expected [`Diagnostic`][diagnostic::Diagnostic]s store a [`LintExpectationId`] as part of
448 /// the lint level. [`LintExpectationId`]s created early during the compilation
449 /// (before `HirId`s have been defined) are not stable and can therefore not be
450 /// stored on disk. This buffer stores these diagnostics until the ID has been
451 /// replaced by a stable [`LintExpectationId`]. The [`Diagnostic`][diagnostic::Diagnostic]s are the
452 /// submitted for storage and added to the list of fulfilled expectations.
453 unstable_expect_diagnostics: Vec<Diagnostic>,
455 /// expected diagnostic will have the level `Expect` which additionally
456 /// carries the [`LintExpectationId`] of the expectation that can be
457 /// marked as fulfilled. This is a collection of all [`LintExpectationId`]s
458 /// that have been marked as fulfilled this way.
460 /// [RFC-2383]: https://rust-lang.github.io/rfcs/2383-lint-reasons.html
461 fulfilled_expectations: FxHashSet<LintExpectationId>,
464 /// A key denoting where from a diagnostic was stashed.
465 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
468 UnderscoreForArrayLengths,
471 /// When an invalid lifetime e.g. `'2` should be reinterpreted
472 /// as a char literal in the parser
474 /// Maybe there was a typo where a comma was forgotten before
480 fn default_track_diagnostic(d: &mut Diagnostic, f: &mut dyn FnMut(&mut Diagnostic)) {
484 pub static TRACK_DIAGNOSTICS: AtomicRef<fn(&mut Diagnostic, &mut dyn FnMut(&mut Diagnostic))> =
485 AtomicRef::new(&(default_track_diagnostic as _));
487 #[derive(Copy, Clone, Default)]
488 pub struct HandlerFlags {
489 /// If false, warning-level lints are suppressed.
490 /// (rustc: see `--allow warnings` and `--cap-lints`)
491 pub can_emit_warnings: bool,
492 /// If true, error-level diagnostics are upgraded to bug-level.
493 /// (rustc: see `-Z treat-err-as-bug`)
494 pub treat_err_as_bug: Option<NonZeroUsize>,
495 /// If true, immediately emit diagnostics that would otherwise be buffered.
496 /// (rustc: see `-Z dont-buffer-diagnostics` and `-Z treat-err-as-bug`)
497 pub dont_buffer_diagnostics: bool,
498 /// If true, immediately print bugs registered with `delay_span_bug`.
499 /// (rustc: see `-Z report-delayed-bugs`)
500 pub report_delayed_bugs: bool,
501 /// Show macro backtraces.
502 /// (rustc: see `-Z macro-backtrace`)
503 pub macro_backtrace: bool,
504 /// If true, identical diagnostics are reported only once.
505 pub deduplicate_diagnostics: bool,
506 /// Track where errors are created. Enabled with `-Ztrack-diagnostics`.
507 pub track_diagnostics: bool,
510 impl Drop for HandlerInner {
512 self.emit_stashed_diagnostics();
514 if !self.has_errors() {
515 let bugs = std::mem::replace(&mut self.delayed_span_bugs, Vec::new());
516 self.flush_delayed(bugs, "no errors encountered even though `delay_span_bug` issued");
519 // FIXME(eddyb) this explains what `delayed_good_path_bugs` are!
520 // They're `delayed_span_bugs` but for "require some diagnostic happened"
521 // instead of "require some error happened". Sadly that isn't ideal, as
522 // lints can be `#[allow]`'d, potentially leading to this triggering.
523 // Also, "good path" should be replaced with a better naming.
524 if !self.has_any_message() && !self.suppressed_expected_diag {
525 let bugs = std::mem::replace(&mut self.delayed_good_path_bugs, Vec::new());
528 "no warnings or errors encountered even though `delayed_good_path_bugs` issued",
532 if self.check_unstable_expect_diagnostics {
534 self.unstable_expect_diagnostics.is_empty(),
535 "all diagnostics with unstable expectations should have been converted",
542 pub fn with_tty_emitter(
543 color_config: ColorConfig,
544 can_emit_warnings: bool,
545 treat_err_as_bug: Option<NonZeroUsize>,
546 sm: Option<Lrc<SourceMap>>,
547 fluent_bundle: Option<Lrc<FluentBundle>>,
548 fallback_bundle: LazyFallbackBundle,
550 Self::with_tty_emitter_and_flags(
555 HandlerFlags { can_emit_warnings, treat_err_as_bug, ..Default::default() },
559 pub fn with_tty_emitter_and_flags(
560 color_config: ColorConfig,
561 sm: Option<Lrc<SourceMap>>,
562 fluent_bundle: Option<Lrc<FluentBundle>>,
563 fallback_bundle: LazyFallbackBundle,
566 let emitter = Box::new(EmitterWriter::stderr(
574 flags.macro_backtrace,
575 flags.track_diagnostics,
577 Self::with_emitter_and_flags(emitter, flags)
581 can_emit_warnings: bool,
582 treat_err_as_bug: Option<NonZeroUsize>,
583 emitter: Box<dyn Emitter + sync::Send>,
585 Handler::with_emitter_and_flags(
587 HandlerFlags { can_emit_warnings, treat_err_as_bug, ..Default::default() },
591 pub fn with_emitter_and_flags(
592 emitter: Box<dyn Emitter + sync::Send>,
597 inner: Lock::new(HandlerInner {
602 deduplicated_err_count: 0,
603 deduplicated_warn_count: 0,
605 delayed_span_bugs: Vec::new(),
606 delayed_good_path_bugs: Vec::new(),
607 suppressed_expected_diag: false,
608 taught_diagnostics: Default::default(),
609 emitted_diagnostic_codes: Default::default(),
610 emitted_diagnostics: Default::default(),
611 stashed_diagnostics: Default::default(),
612 future_breakage_diagnostics: Vec::new(),
613 check_unstable_expect_diagnostics: false,
614 unstable_expect_diagnostics: Vec::new(),
615 fulfilled_expectations: Default::default(),
620 /// Translate `message` eagerly with `args`.
621 pub fn eagerly_translate<'a>(
623 message: DiagnosticMessage,
624 args: impl Iterator<Item = DiagnosticArg<'a, 'static>>,
625 ) -> SubdiagnosticMessage {
626 let inner = self.inner.borrow();
627 let args = crate::translation::to_fluent_args(args);
628 SubdiagnosticMessage::Eager(
631 .translate_message(&message, &args)
632 .map_err(Report::new)
638 // This is here to not allow mutation of flags;
639 // as of this writing it's only used in tests in librustc_middle.
640 pub fn can_emit_warnings(&self) -> bool {
641 self.flags.can_emit_warnings
644 /// Resets the diagnostic error count as well as the cached emitted diagnostics.
646 /// NOTE: *do not* call this function from rustc. It is only meant to be called from external
647 /// tools that want to reuse a `Parser` cleaning the previously emitted diagnostics as well as
648 /// the overall count of emitted error diagnostics.
649 pub fn reset_err_count(&self) {
650 let mut inner = self.inner.borrow_mut();
652 inner.warn_count = 0;
653 inner.deduplicated_err_count = 0;
654 inner.deduplicated_warn_count = 0;
656 // actually free the underlying memory (which `clear` would not do)
657 inner.delayed_span_bugs = Default::default();
658 inner.delayed_good_path_bugs = Default::default();
659 inner.taught_diagnostics = Default::default();
660 inner.emitted_diagnostic_codes = Default::default();
661 inner.emitted_diagnostics = Default::default();
662 inner.stashed_diagnostics = Default::default();
665 /// Stash a given diagnostic with the given `Span` and [`StashKey`] as the key.
666 /// Retrieve a stashed diagnostic with `steal_diagnostic`.
667 pub fn stash_diagnostic(&self, span: Span, key: StashKey, diag: Diagnostic) {
668 let mut inner = self.inner.borrow_mut();
669 inner.stash((span.with_parent(None), key), diag);
672 /// Steal a previously stashed diagnostic with the given `Span` and [`StashKey`] as the key.
673 pub fn steal_diagnostic(&self, span: Span, key: StashKey) -> Option<DiagnosticBuilder<'_, ()>> {
674 let mut inner = self.inner.borrow_mut();
676 .steal((span.with_parent(None), key))
677 .map(|diag| DiagnosticBuilder::new_diagnostic(self, diag))
680 pub fn has_stashed_diagnostic(&self, span: Span, key: StashKey) -> bool {
681 self.inner.borrow().stashed_diagnostics.get(&(span.with_parent(None), key)).is_some()
684 /// Emit all stashed diagnostics.
685 pub fn emit_stashed_diagnostics(&self) -> Option<ErrorGuaranteed> {
686 self.inner.borrow_mut().emit_stashed_diagnostics()
689 /// Construct a builder with the `msg` at the level appropriate for the specific `EmissionGuarantee`.
690 #[rustc_lint_diagnostics]
692 pub fn struct_diagnostic<G: EmissionGuarantee>(
694 msg: impl Into<DiagnosticMessage>,
695 ) -> DiagnosticBuilder<'_, G> {
696 G::make_diagnostic_builder(self, msg)
699 /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
701 /// Attempting to `.emit()` the builder will only emit if either:
702 /// * `can_emit_warnings` is `true`
703 /// * `is_force_warn` was set in `DiagnosticId::Lint`
704 #[rustc_lint_diagnostics]
706 pub fn struct_span_warn(
708 span: impl Into<MultiSpan>,
709 msg: impl Into<DiagnosticMessage>,
710 ) -> DiagnosticBuilder<'_, ()> {
711 let mut result = self.struct_warn(msg);
712 result.set_span(span);
716 /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
717 /// The `id` is used for lint emissions which should also fulfill a lint expectation.
719 /// Attempting to `.emit()` the builder will only emit if either:
720 /// * `can_emit_warnings` is `true`
721 /// * `is_force_warn` was set in `DiagnosticId::Lint`
723 pub fn struct_span_warn_with_expectation(
725 span: impl Into<MultiSpan>,
726 msg: impl Into<DiagnosticMessage>,
727 id: LintExpectationId,
728 ) -> DiagnosticBuilder<'_, ()> {
729 let mut result = self.struct_warn_with_expectation(msg, id);
730 result.set_span(span);
734 /// Construct a builder at the `Allow` level at the given `span` and with the `msg`.
735 #[rustc_lint_diagnostics]
737 pub fn struct_span_allow(
739 span: impl Into<MultiSpan>,
740 msg: impl Into<DiagnosticMessage>,
741 ) -> DiagnosticBuilder<'_, ()> {
742 let mut result = self.struct_allow(msg);
743 result.set_span(span);
747 /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
748 /// Also include a code.
749 #[rustc_lint_diagnostics]
751 pub fn struct_span_warn_with_code(
753 span: impl Into<MultiSpan>,
754 msg: impl Into<DiagnosticMessage>,
756 ) -> DiagnosticBuilder<'_, ()> {
757 let mut result = self.struct_span_warn(span, msg);
762 /// Construct a builder at the `Warning` level with the `msg`.
764 /// Attempting to `.emit()` the builder will only emit if either:
765 /// * `can_emit_warnings` is `true`
766 /// * `is_force_warn` was set in `DiagnosticId::Lint`
767 #[rustc_lint_diagnostics]
769 pub fn struct_warn(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> {
770 DiagnosticBuilder::new(self, Level::Warning(None), msg)
773 /// Construct a builder at the `Warning` level with the `msg`. The `id` is used for
774 /// lint emissions which should also fulfill a lint expectation.
776 /// Attempting to `.emit()` the builder will only emit if either:
777 /// * `can_emit_warnings` is `true`
778 /// * `is_force_warn` was set in `DiagnosticId::Lint`
780 pub fn struct_warn_with_expectation(
782 msg: impl Into<DiagnosticMessage>,
783 id: LintExpectationId,
784 ) -> DiagnosticBuilder<'_, ()> {
785 DiagnosticBuilder::new(self, Level::Warning(Some(id)), msg)
788 /// Construct a builder at the `Allow` level with the `msg`.
789 #[rustc_lint_diagnostics]
791 pub fn struct_allow(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> {
792 DiagnosticBuilder::new(self, Level::Allow, msg)
795 /// Construct a builder at the `Expect` level with the `msg`.
796 #[rustc_lint_diagnostics]
798 pub fn struct_expect(
800 msg: impl Into<DiagnosticMessage>,
801 id: LintExpectationId,
802 ) -> DiagnosticBuilder<'_, ()> {
803 DiagnosticBuilder::new(self, Level::Expect(id), msg)
806 /// Construct a builder at the `Error` level at the given `span` and with the `msg`.
807 #[rustc_lint_diagnostics]
809 pub fn struct_span_err(
811 span: impl Into<MultiSpan>,
812 msg: impl Into<DiagnosticMessage>,
813 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
814 let mut result = self.struct_err(msg);
815 result.set_span(span);
819 /// Construct a builder at the `Error` level at the given `span`, with the `msg`, and `code`.
820 #[rustc_lint_diagnostics]
822 pub fn struct_span_err_with_code(
824 span: impl Into<MultiSpan>,
825 msg: impl Into<DiagnosticMessage>,
827 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
828 let mut result = self.struct_span_err(span, msg);
833 /// Construct a builder at the `Error` level with the `msg`.
834 // FIXME: This method should be removed (every error should have an associated error code).
835 #[rustc_lint_diagnostics]
839 msg: impl Into<DiagnosticMessage>,
840 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
841 DiagnosticBuilder::new_guaranteeing_error::<_, { Level::Error { lint: false } }>(self, msg)
844 /// This should only be used by `rustc_middle::lint::struct_lint_level`. Do not use it for hard errors.
847 pub fn struct_err_lint(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> {
848 DiagnosticBuilder::new(self, Level::Error { lint: true }, msg)
851 /// Construct a builder at the `Error` level with the `msg` and the `code`.
852 #[rustc_lint_diagnostics]
854 pub fn struct_err_with_code(
856 msg: impl Into<DiagnosticMessage>,
858 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
859 let mut result = self.struct_err(msg);
864 /// Construct a builder at the `Warn` level with the `msg` and the `code`.
865 #[rustc_lint_diagnostics]
867 pub fn struct_warn_with_code(
869 msg: impl Into<DiagnosticMessage>,
871 ) -> DiagnosticBuilder<'_, ()> {
872 let mut result = self.struct_warn(msg);
877 /// Construct a builder at the `Fatal` level at the given `span` and with the `msg`.
878 #[rustc_lint_diagnostics]
880 pub fn struct_span_fatal(
882 span: impl Into<MultiSpan>,
883 msg: impl Into<DiagnosticMessage>,
884 ) -> DiagnosticBuilder<'_, !> {
885 let mut result = self.struct_fatal(msg);
886 result.set_span(span);
890 /// Construct a builder at the `Fatal` level at the given `span`, with the `msg`, and `code`.
891 #[rustc_lint_diagnostics]
893 pub fn struct_span_fatal_with_code(
895 span: impl Into<MultiSpan>,
896 msg: impl Into<DiagnosticMessage>,
898 ) -> DiagnosticBuilder<'_, !> {
899 let mut result = self.struct_span_fatal(span, msg);
904 /// Construct a builder at the `Error` level with the `msg`.
905 #[rustc_lint_diagnostics]
907 pub fn struct_fatal(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, !> {
908 DiagnosticBuilder::new_fatal(self, msg)
911 /// Construct a builder at the `Help` level with the `msg`.
912 #[rustc_lint_diagnostics]
913 pub fn struct_help(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> {
914 DiagnosticBuilder::new(self, Level::Help, msg)
917 /// Construct a builder at the `Note` level with the `msg`.
918 #[rustc_lint_diagnostics]
920 pub fn struct_note_without_error(
922 msg: impl Into<DiagnosticMessage>,
923 ) -> DiagnosticBuilder<'_, ()> {
924 DiagnosticBuilder::new(self, Level::Note, msg)
927 #[rustc_lint_diagnostics]
929 pub fn span_fatal(&self, span: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>) -> ! {
930 self.emit_diag_at_span(Diagnostic::new(Fatal, msg), span);
934 #[rustc_lint_diagnostics]
936 pub fn span_fatal_with_code(
938 span: impl Into<MultiSpan>,
939 msg: impl Into<DiagnosticMessage>,
942 self.emit_diag_at_span(Diagnostic::new_with_code(Fatal, Some(code), msg), span);
946 #[rustc_lint_diagnostics]
950 span: impl Into<MultiSpan>,
951 msg: impl Into<DiagnosticMessage>,
952 ) -> ErrorGuaranteed {
953 self.emit_diag_at_span(Diagnostic::new(Error { lint: false }, msg), span).unwrap()
956 #[rustc_lint_diagnostics]
958 pub fn span_err_with_code(
960 span: impl Into<MultiSpan>,
961 msg: impl Into<DiagnosticMessage>,
964 self.emit_diag_at_span(
965 Diagnostic::new_with_code(Error { lint: false }, Some(code), msg),
970 #[rustc_lint_diagnostics]
972 pub fn span_warn(&self, span: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>) {
973 self.emit_diag_at_span(Diagnostic::new(Warning(None), msg), span);
976 #[rustc_lint_diagnostics]
978 pub fn span_warn_with_code(
980 span: impl Into<MultiSpan>,
981 msg: impl Into<DiagnosticMessage>,
984 self.emit_diag_at_span(Diagnostic::new_with_code(Warning(None), Some(code), msg), span);
987 pub fn span_bug(&self, span: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>) -> ! {
988 self.inner.borrow_mut().span_bug(span, msg)
991 /// For documentation on this, see `Session::delay_span_bug`.
993 pub fn delay_span_bug(
995 span: impl Into<MultiSpan>,
996 msg: impl Into<DiagnosticMessage>,
997 ) -> ErrorGuaranteed {
998 self.inner.borrow_mut().delay_span_bug(span, msg)
1001 // FIXME(eddyb) note the comment inside `impl Drop for HandlerInner`, that's
1002 // where the explanation of what "good path" is (also, it should be renamed).
1003 pub fn delay_good_path_bug(&self, msg: impl Into<DiagnosticMessage>) {
1004 self.inner.borrow_mut().delay_good_path_bug(msg)
1008 pub fn span_bug_no_panic(&self, span: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>) {
1009 self.emit_diag_at_span(Diagnostic::new(Bug, msg), span);
1013 pub fn span_note_without_error(
1015 span: impl Into<MultiSpan>,
1016 msg: impl Into<DiagnosticMessage>,
1018 self.emit_diag_at_span(Diagnostic::new(Note, msg), span);
1022 pub fn span_note_diag(
1025 msg: impl Into<DiagnosticMessage>,
1026 ) -> DiagnosticBuilder<'_, ()> {
1027 let mut db = DiagnosticBuilder::new(self, Note, msg);
1032 // NOTE: intentionally doesn't raise an error so rustc_codegen_ssa only reports fatal errors in the main thread
1033 pub fn fatal(&self, msg: impl Into<DiagnosticMessage>) -> FatalError {
1034 self.inner.borrow_mut().fatal(msg)
1037 pub fn err(&self, msg: impl Into<DiagnosticMessage>) -> ErrorGuaranteed {
1038 self.inner.borrow_mut().err(msg)
1041 pub fn warn(&self, msg: impl Into<DiagnosticMessage>) {
1042 let mut db = DiagnosticBuilder::new(self, Warning(None), msg);
1046 pub fn note_without_error(&self, msg: impl Into<DiagnosticMessage>) {
1047 DiagnosticBuilder::new(self, Note, msg).emit();
1050 pub fn bug(&self, msg: impl Into<DiagnosticMessage>) -> ! {
1051 self.inner.borrow_mut().bug(msg)
1055 pub fn err_count(&self) -> usize {
1056 self.inner.borrow().err_count()
1059 pub fn has_errors(&self) -> Option<ErrorGuaranteed> {
1060 if self.inner.borrow().has_errors() { Some(ErrorGuaranteed(())) } else { None }
1062 pub fn has_errors_or_lint_errors(&self) -> Option<ErrorGuaranteed> {
1063 if self.inner.borrow().has_errors_or_lint_errors() {
1064 Some(ErrorGuaranteed::unchecked_claim_error_was_emitted())
1069 pub fn has_errors_or_delayed_span_bugs(&self) -> Option<ErrorGuaranteed> {
1070 if self.inner.borrow().has_errors_or_delayed_span_bugs() {
1071 Some(ErrorGuaranteed::unchecked_claim_error_was_emitted())
1076 pub fn is_compilation_going_to_fail(&self) -> Option<ErrorGuaranteed> {
1077 if self.inner.borrow().is_compilation_going_to_fail() {
1078 Some(ErrorGuaranteed::unchecked_claim_error_was_emitted())
1084 pub fn print_error_count(&self, registry: &Registry) {
1085 self.inner.borrow_mut().print_error_count(registry)
1088 pub fn take_future_breakage_diagnostics(&self) -> Vec<Diagnostic> {
1089 std::mem::take(&mut self.inner.borrow_mut().future_breakage_diagnostics)
1092 pub fn abort_if_errors(&self) {
1093 self.inner.borrow_mut().abort_if_errors()
1096 /// `true` if we haven't taught a diagnostic with this code already.
1097 /// The caller must then teach the user about such a diagnostic.
1099 /// Used to suppress emitting the same error multiple times with extended explanation when
1100 /// calling `-Zteach`.
1101 pub fn must_teach(&self, code: &DiagnosticId) -> bool {
1102 self.inner.borrow_mut().must_teach(code)
1105 pub fn force_print_diagnostic(&self, db: Diagnostic) {
1106 self.inner.borrow_mut().force_print_diagnostic(db)
1109 pub fn emit_diagnostic(&self, diagnostic: &mut Diagnostic) -> Option<ErrorGuaranteed> {
1110 self.inner.borrow_mut().emit_diagnostic(diagnostic)
1113 pub fn emit_err<'a>(&'a self, err: impl IntoDiagnostic<'a>) -> ErrorGuaranteed {
1114 self.create_err(err).emit()
1117 pub fn create_err<'a>(
1119 err: impl IntoDiagnostic<'a>,
1120 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
1121 err.into_diagnostic(self)
1124 pub fn create_warning<'a>(
1126 warning: impl IntoDiagnostic<'a, ()>,
1127 ) -> DiagnosticBuilder<'a, ()> {
1128 warning.into_diagnostic(self)
1131 pub fn emit_warning<'a>(&'a self, warning: impl IntoDiagnostic<'a, ()>) {
1132 self.create_warning(warning).emit()
1135 pub fn create_fatal<'a>(
1137 fatal: impl IntoDiagnostic<'a, !>,
1138 ) -> DiagnosticBuilder<'a, !> {
1139 fatal.into_diagnostic(self)
1142 pub fn emit_fatal<'a>(&'a self, fatal: impl IntoDiagnostic<'a, !>) -> ! {
1143 self.create_fatal(fatal).emit()
1146 pub fn create_bug<'a>(
1148 bug: impl IntoDiagnostic<'a, diagnostic_builder::Bug>,
1149 ) -> DiagnosticBuilder<'a, diagnostic_builder::Bug> {
1150 bug.into_diagnostic(self)
1153 pub fn emit_bug<'a>(
1155 bug: impl IntoDiagnostic<'a, diagnostic_builder::Bug>,
1156 ) -> diagnostic_builder::Bug {
1157 self.create_bug(bug).emit()
1160 fn emit_diag_at_span(
1162 mut diag: Diagnostic,
1163 sp: impl Into<MultiSpan>,
1164 ) -> Option<ErrorGuaranteed> {
1165 let mut inner = self.inner.borrow_mut();
1166 inner.emit_diagnostic(diag.set_span(sp))
1169 pub fn emit_artifact_notification(&self, path: &Path, artifact_type: &str) {
1170 self.inner.borrow_mut().emit_artifact_notification(path, artifact_type)
1173 pub fn emit_future_breakage_report(&self, diags: Vec<Diagnostic>) {
1174 self.inner.borrow_mut().emitter.emit_future_breakage_report(diags)
1177 pub fn emit_unused_externs(
1179 lint_level: rustc_lint_defs::Level,
1181 unused_externs: &[&str],
1183 let mut inner = self.inner.borrow_mut();
1185 if loud && lint_level.is_error() {
1186 inner.bump_err_count();
1189 inner.emit_unused_externs(lint_level, unused_externs)
1192 pub fn update_unstable_expectation_id(
1194 unstable_to_stable: &FxHashMap<LintExpectationId, LintExpectationId>,
1196 let mut inner = self.inner.borrow_mut();
1197 let diags = std::mem::take(&mut inner.unstable_expect_diagnostics);
1198 inner.check_unstable_expect_diagnostics = true;
1200 if !diags.is_empty() {
1201 inner.suppressed_expected_diag = true;
1202 for mut diag in diags.into_iter() {
1203 diag.update_unstable_expectation_id(unstable_to_stable);
1205 // Here the diagnostic is given back to `emit_diagnostic` where it was first
1206 // intercepted. Now it should be processed as usual, since the unstable expectation
1207 // id is now stable.
1208 inner.emit_diagnostic(&mut diag);
1213 .stashed_diagnostics
1215 .for_each(|diag| diag.update_unstable_expectation_id(unstable_to_stable));
1217 .future_breakage_diagnostics
1219 .for_each(|diag| diag.update_unstable_expectation_id(unstable_to_stable));
1222 /// This methods steals all [`LintExpectationId`]s that are stored inside
1223 /// [`HandlerInner`] and indicate that the linked expectation has been fulfilled.
1225 pub fn steal_fulfilled_expectation_ids(&self) -> FxHashSet<LintExpectationId> {
1227 self.inner.borrow().unstable_expect_diagnostics.is_empty(),
1228 "`HandlerInner::unstable_expect_diagnostics` should be empty at this point",
1230 std::mem::take(&mut self.inner.borrow_mut().fulfilled_expectations)
1233 pub fn flush_delayed(&self) {
1234 let mut inner = self.inner.lock();
1235 let bugs = std::mem::replace(&mut inner.delayed_span_bugs, Vec::new());
1236 inner.flush_delayed(bugs, "no errors encountered even though `delay_span_bug` issued");
1241 fn must_teach(&mut self, code: &DiagnosticId) -> bool {
1242 self.taught_diagnostics.insert(code.clone())
1245 fn force_print_diagnostic(&mut self, db: Diagnostic) {
1246 self.emitter.emit_diagnostic(&db);
1249 /// Emit all stashed diagnostics.
1250 fn emit_stashed_diagnostics(&mut self) -> Option<ErrorGuaranteed> {
1251 let has_errors = self.has_errors();
1252 let diags = self.stashed_diagnostics.drain(..).map(|x| x.1).collect::<Vec<_>>();
1253 let mut reported = None;
1254 for mut diag in diags {
1255 // Decrement the count tracking the stash; emitting will increment it.
1256 if diag.is_error() {
1257 if matches!(diag.level, Level::Error { lint: true }) {
1258 self.lint_err_count -= 1;
1260 self.err_count -= 1;
1263 if diag.is_force_warn() {
1264 self.warn_count -= 1;
1266 // Unless they're forced, don't flush stashed warnings when
1267 // there are errors, to avoid causing warning overload. The
1268 // stash would've been stolen already if it were important.
1274 let reported_this = self.emit_diagnostic(&mut diag);
1275 reported = reported.or(reported_this);
1280 // FIXME(eddyb) this should ideally take `diagnostic` by value.
1281 fn emit_diagnostic(&mut self, diagnostic: &mut Diagnostic) -> Option<ErrorGuaranteed> {
1282 // The `LintExpectationId` can be stable or unstable depending on when it was created.
1283 // Diagnostics created before the definition of `HirId`s are unstable and can not yet
1284 // be stored. Instead, they are buffered until the `LintExpectationId` is replaced by
1285 // a stable one by the `LintLevelsBuilder`.
1286 if let Some(LintExpectationId::Unstable { .. }) = diagnostic.level.get_expectation_id() {
1287 self.unstable_expect_diagnostics.push(diagnostic.clone());
1291 if diagnostic.level == Level::DelayedBug {
1292 // FIXME(eddyb) this should check for `has_errors` and stop pushing
1293 // once *any* errors were emitted (and truncate `delayed_span_bugs`
1294 // when an error is first emitted, also), but maybe there's a case
1295 // in which that's not sound? otherwise this is really inefficient.
1296 let backtrace = std::backtrace::Backtrace::force_capture();
1297 self.delayed_span_bugs
1298 .push(DelayedDiagnostic::with_backtrace(diagnostic.clone(), backtrace));
1300 if !self.flags.report_delayed_bugs {
1301 return Some(ErrorGuaranteed::unchecked_claim_error_was_emitted());
1305 if diagnostic.has_future_breakage() {
1306 // Future breakages aren't emitted if they're Level::Allowed,
1307 // but they still need to be constructed and stashed below,
1308 // so they'll trigger the good-path bug check.
1309 self.suppressed_expected_diag = true;
1310 self.future_breakage_diagnostics.push(diagnostic.clone());
1313 if let Some(expectation_id) = diagnostic.level.get_expectation_id() {
1314 self.suppressed_expected_diag = true;
1315 self.fulfilled_expectations.insert(expectation_id.normalize());
1318 if matches!(diagnostic.level, Warning(_))
1319 && !self.flags.can_emit_warnings
1320 && !diagnostic.is_force_warn()
1322 if diagnostic.has_future_breakage() {
1323 (*TRACK_DIAGNOSTICS)(diagnostic, &mut |_| {});
1328 if matches!(diagnostic.level, Level::Expect(_) | Level::Allow) {
1329 (*TRACK_DIAGNOSTICS)(diagnostic, &mut |_| {});
1333 let mut guaranteed = None;
1334 (*TRACK_DIAGNOSTICS)(diagnostic, &mut |diagnostic| {
1335 if let Some(ref code) = diagnostic.code {
1336 self.emitted_diagnostic_codes.insert(code.clone());
1339 let already_emitted = |this: &mut Self| {
1340 let mut hasher = StableHasher::new();
1341 diagnostic.hash(&mut hasher);
1342 let diagnostic_hash = hasher.finish();
1343 !this.emitted_diagnostics.insert(diagnostic_hash)
1346 // Only emit the diagnostic if we've been asked to deduplicate or
1347 // haven't already emitted an equivalent diagnostic.
1348 if !(self.flags.deduplicate_diagnostics && already_emitted(self)) {
1349 debug!(?diagnostic);
1350 debug!(?self.emitted_diagnostics);
1351 let already_emitted_sub = |sub: &mut SubDiagnostic| {
1353 if sub.level != Level::OnceNote {
1356 let mut hasher = StableHasher::new();
1357 sub.hash(&mut hasher);
1358 let diagnostic_hash = hasher.finish();
1359 debug!(?diagnostic_hash);
1360 !self.emitted_diagnostics.insert(diagnostic_hash)
1363 diagnostic.children.drain_filter(already_emitted_sub).for_each(|_| {});
1365 self.emitter.emit_diagnostic(diagnostic);
1366 if diagnostic.is_error() {
1367 self.deduplicated_err_count += 1;
1368 } else if let Warning(_) = diagnostic.level {
1369 self.deduplicated_warn_count += 1;
1372 if diagnostic.is_error() {
1373 if matches!(diagnostic.level, Level::Error { lint: true }) {
1374 self.bump_lint_err_count();
1376 self.bump_err_count();
1379 guaranteed = Some(ErrorGuaranteed::unchecked_claim_error_was_emitted());
1381 self.bump_warn_count();
1388 fn emit_artifact_notification(&mut self, path: &Path, artifact_type: &str) {
1389 self.emitter.emit_artifact_notification(path, artifact_type);
1392 fn emit_unused_externs(&mut self, lint_level: rustc_lint_defs::Level, unused_externs: &[&str]) {
1393 self.emitter.emit_unused_externs(lint_level, unused_externs);
1396 fn treat_err_as_bug(&self) -> bool {
1397 self.flags.treat_err_as_bug.map_or(false, |c| {
1398 self.err_count() + self.lint_err_count + self.delayed_bug_count() >= c.get()
1402 fn delayed_bug_count(&self) -> usize {
1403 self.delayed_span_bugs.len() + self.delayed_good_path_bugs.len()
1406 fn print_error_count(&mut self, registry: &Registry) {
1407 self.emit_stashed_diagnostics();
1409 let warnings = match self.deduplicated_warn_count {
1411 1 => "1 warning emitted".to_string(),
1412 count => format!("{count} warnings emitted"),
1414 let errors = match self.deduplicated_err_count {
1416 1 => "aborting due to previous error".to_string(),
1417 count => format!("aborting due to {count} previous errors"),
1419 if self.treat_err_as_bug() {
1423 match (errors.len(), warnings.len()) {
1425 (0, _) => self.emitter.emit_diagnostic(&Diagnostic::new(
1426 Level::Warning(None),
1427 DiagnosticMessage::Str(warnings),
1430 let _ = self.fatal(&errors);
1433 let _ = self.fatal(&format!("{}; {}", &errors, &warnings));
1437 let can_show_explain = self.emitter.should_show_explain();
1438 let are_there_diagnostics = !self.emitted_diagnostic_codes.is_empty();
1439 if can_show_explain && are_there_diagnostics {
1440 let mut error_codes = self
1441 .emitted_diagnostic_codes
1443 .filter_map(|x| match &x {
1444 DiagnosticId::Error(s)
1445 if registry.try_find_description(s).map_or(false, |o| o.is_some()) =>
1451 .collect::<Vec<_>>();
1452 if !error_codes.is_empty() {
1454 if error_codes.len() > 1 {
1455 let limit = if error_codes.len() > 9 { 9 } else { error_codes.len() };
1456 self.failure(&format!(
1457 "Some errors have detailed explanations: {}{}",
1458 error_codes[..limit].join(", "),
1459 if error_codes.len() > 9 { "..." } else { "." }
1461 self.failure(&format!(
1462 "For more information about an error, try \
1463 `rustc --explain {}`.",
1467 self.failure(&format!(
1468 "For more information about this error, try \
1469 `rustc --explain {}`.",
1477 fn stash(&mut self, key: (Span, StashKey), diagnostic: Diagnostic) {
1478 // Track the diagnostic for counts, but don't panic-if-treat-err-as-bug
1479 // yet; that happens when we actually emit the diagnostic.
1480 if diagnostic.is_error() {
1481 if matches!(diagnostic.level, Level::Error { lint: true }) {
1482 self.lint_err_count += 1;
1484 self.err_count += 1;
1487 // Warnings are only automatically flushed if they're forced.
1488 if diagnostic.is_force_warn() {
1489 self.warn_count += 1;
1493 // FIXME(Centril, #69537): Consider reintroducing panic on overwriting a stashed diagnostic
1494 // if/when we have a more robust macro-friendly replacement for `(span, key)` as a key.
1495 // See the PR for a discussion.
1496 self.stashed_diagnostics.insert(key, diagnostic);
1499 fn steal(&mut self, key: (Span, StashKey)) -> Option<Diagnostic> {
1500 let diagnostic = self.stashed_diagnostics.remove(&key)?;
1501 if diagnostic.is_error() {
1502 if matches!(diagnostic.level, Level::Error { lint: true }) {
1503 self.lint_err_count -= 1;
1505 self.err_count -= 1;
1508 if diagnostic.is_force_warn() {
1509 self.warn_count -= 1;
1516 fn err_count(&self) -> usize {
1520 fn has_errors(&self) -> bool {
1521 self.err_count() > 0
1523 fn has_errors_or_lint_errors(&self) -> bool {
1524 self.has_errors() || self.lint_err_count > 0
1526 fn has_errors_or_delayed_span_bugs(&self) -> bool {
1527 self.has_errors() || !self.delayed_span_bugs.is_empty()
1529 fn has_any_message(&self) -> bool {
1530 self.err_count() > 0 || self.lint_err_count > 0 || self.warn_count > 0
1533 fn is_compilation_going_to_fail(&self) -> bool {
1534 self.has_errors() || self.lint_err_count > 0 || !self.delayed_span_bugs.is_empty()
1537 fn abort_if_errors(&mut self) {
1538 self.emit_stashed_diagnostics();
1540 if self.has_errors() {
1546 fn span_bug(&mut self, sp: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>) -> ! {
1547 self.emit_diag_at_span(Diagnostic::new(Bug, msg), sp);
1548 panic::panic_any(ExplicitBug);
1551 fn emit_diag_at_span(&mut self, mut diag: Diagnostic, sp: impl Into<MultiSpan>) {
1552 self.emit_diagnostic(diag.set_span(sp));
1555 /// For documentation on this, see `Session::delay_span_bug`.
1559 sp: impl Into<MultiSpan>,
1560 msg: impl Into<DiagnosticMessage>,
1561 ) -> ErrorGuaranteed {
1562 // This is technically `self.treat_err_as_bug()` but `delay_span_bug` is called before
1563 // incrementing `err_count` by one, so we need to +1 the comparing.
1564 // FIXME: Would be nice to increment err_count in a more coherent way.
1565 if self.flags.treat_err_as_bug.map_or(false, |c| {
1566 self.err_count() + self.lint_err_count + self.delayed_bug_count() + 1 >= c.get()
1568 // FIXME: don't abort here if report_delayed_bugs is off
1569 self.span_bug(sp, msg);
1571 let mut diagnostic = Diagnostic::new(Level::DelayedBug, msg);
1572 diagnostic.set_span(sp.into());
1573 self.emit_diagnostic(&mut diagnostic).unwrap()
1576 // FIXME(eddyb) note the comment inside `impl Drop for HandlerInner`, that's
1577 // where the explanation of what "good path" is (also, it should be renamed).
1578 fn delay_good_path_bug(&mut self, msg: impl Into<DiagnosticMessage>) {
1579 let mut diagnostic = Diagnostic::new(Level::DelayedBug, msg);
1580 if self.flags.report_delayed_bugs {
1581 self.emit_diagnostic(&mut diagnostic);
1583 let backtrace = std::backtrace::Backtrace::force_capture();
1584 self.delayed_good_path_bugs.push(DelayedDiagnostic::with_backtrace(diagnostic, backtrace));
1587 fn failure(&mut self, msg: impl Into<DiagnosticMessage>) {
1588 self.emit_diagnostic(&mut Diagnostic::new(FailureNote, msg));
1591 fn fatal(&mut self, msg: impl Into<DiagnosticMessage>) -> FatalError {
1592 self.emit(Fatal, msg);
1596 fn err(&mut self, msg: impl Into<DiagnosticMessage>) -> ErrorGuaranteed {
1597 self.emit(Error { lint: false }, msg)
1600 /// Emit an error; level should be `Error` or `Fatal`.
1601 fn emit(&mut self, level: Level, msg: impl Into<DiagnosticMessage>) -> ErrorGuaranteed {
1602 if self.treat_err_as_bug() {
1605 self.emit_diagnostic(&mut Diagnostic::new(level, msg)).unwrap()
1608 fn bug(&mut self, msg: impl Into<DiagnosticMessage>) -> ! {
1609 self.emit_diagnostic(&mut Diagnostic::new(Bug, msg));
1610 panic::panic_any(ExplicitBug);
1615 bugs: impl IntoIterator<Item = DelayedDiagnostic>,
1616 explanation: impl Into<DiagnosticMessage> + Copy,
1618 let mut no_bugs = true;
1620 let mut bug = bug.decorate();
1623 // Put the overall explanation before the `DelayedBug`s, to
1624 // frame them better (e.g. separate warnings from them).
1625 self.emit_diagnostic(&mut Diagnostic::new(Bug, explanation));
1629 // "Undelay" the `DelayedBug`s (into plain `Bug`s).
1630 if bug.level != Level::DelayedBug {
1631 // NOTE(eddyb) not panicking here because we're already producing
1632 // an ICE, and the more information the merrier.
1634 "`flushed_delayed` got diagnostic with level {:?}, \
1635 instead of the expected `DelayedBug`",
1639 bug.level = Level::Bug;
1641 self.emit_diagnostic(&mut bug);
1644 // Panic with `DelayedBugPanic` to avoid "unexpected panic" messages.
1646 panic::panic_any(DelayedBugPanic);
1650 fn bump_lint_err_count(&mut self) {
1651 self.lint_err_count += 1;
1652 self.panic_if_treat_err_as_bug();
1655 fn bump_err_count(&mut self) {
1656 self.err_count += 1;
1657 self.panic_if_treat_err_as_bug();
1660 fn bump_warn_count(&mut self) {
1661 self.warn_count += 1;
1664 fn panic_if_treat_err_as_bug(&self) {
1665 if self.treat_err_as_bug() {
1667 self.err_count() + self.lint_err_count,
1668 self.delayed_bug_count(),
1669 self.flags.treat_err_as_bug.map(|c| c.get()).unwrap_or(0),
1671 (1, 0, 1) => panic!("aborting due to `-Z treat-err-as-bug=1`"),
1672 (0, 1, 1) => panic!("aborting due delayed bug with `-Z treat-err-as-bug=1`"),
1673 (count, delayed_count, as_bug) => {
1674 if delayed_count > 0 {
1676 "aborting after {} errors and {} delayed bugs due to `-Z treat-err-as-bug={}`",
1677 count, delayed_count, as_bug,
1681 "aborting after {} errors due to `-Z treat-err-as-bug={}`",
1691 struct DelayedDiagnostic {
1696 impl DelayedDiagnostic {
1697 fn with_backtrace(diagnostic: Diagnostic, backtrace: Backtrace) -> Self {
1698 DelayedDiagnostic { inner: diagnostic, note: backtrace }
1701 fn decorate(mut self) -> Diagnostic {
1702 self.inner.note(&format!("delayed at {}", self.note));
1707 #[derive(Copy, PartialEq, Eq, Clone, Hash, Debug, Encodable, Decodable)]
1713 /// If this error comes from a lint, don't abort compilation even when abort_if_errors() is called.
1716 /// This [`LintExpectationId`] is used for expected lint diagnostics, which should
1717 /// also emit a warning due to the `force-warn` flag. In all other cases this should
1719 Warning(Option<LintExpectationId>),
1721 /// A note that is only emitted once.
1726 Expect(LintExpectationId),
1729 impl fmt::Display for Level {
1730 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1731 self.to_str().fmt(f)
1736 fn color(self) -> ColorSpec {
1737 let mut spec = ColorSpec::new();
1739 Bug | DelayedBug | Fatal | Error { .. } => {
1740 spec.set_fg(Some(Color::Red)).set_intense(true);
1743 spec.set_fg(Some(Color::Yellow)).set_intense(cfg!(windows));
1745 Note | OnceNote => {
1746 spec.set_fg(Some(Color::Green)).set_intense(true);
1749 spec.set_fg(Some(Color::Cyan)).set_intense(true);
1752 Allow | Expect(_) => unreachable!(),
1757 pub fn to_str(self) -> &'static str {
1759 Bug | DelayedBug => "error: internal compiler error",
1760 Fatal | Error { .. } => "error",
1761 Warning(_) => "warning",
1762 Note | OnceNote => "note",
1764 FailureNote => "failure-note",
1765 Allow => panic!("Shouldn't call on allowed error"),
1766 Expect(_) => panic!("Shouldn't call on expected error"),
1770 pub fn is_failure_note(&self) -> bool {
1771 matches!(*self, FailureNote)
1774 pub fn get_expectation_id(&self) -> Option<LintExpectationId> {
1776 Level::Expect(id) | Level::Warning(Some(id)) => Some(*id),
1782 // FIXME(eddyb) this doesn't belong here AFAICT, should be moved to callsite.
1783 pub fn add_elided_lifetime_in_path_suggestion(
1784 source_map: &SourceMap,
1785 diag: &mut Diagnostic,
1788 incl_angl_brckt: bool,
1789 insertion_span: Span,
1791 diag.span_label(path_span, format!("expected lifetime parameter{}", pluralize!(n)));
1792 if !source_map.is_span_accessible(insertion_span) {
1793 // Do not try to suggest anything if generated by a proc-macro.
1796 let anon_lts = vec!["'_"; n].join(", ");
1798 if incl_angl_brckt { format!("<{}>", anon_lts) } else { format!("{}, ", anon_lts) };
1799 diag.span_suggestion_verbose(
1800 insertion_span.shrink_to_hi(),
1801 &format!("indicate the anonymous lifetime{}", pluralize!(n)),
1803 Applicability::MachineApplicable,
1807 /// Useful type to use with `Result<>` indicate that an error has already
1808 /// been reported to the user, so no need to continue checking.
1809 #[derive(Clone, Copy, Debug, Encodable, Decodable, Hash, PartialEq, Eq, PartialOrd, Ord)]
1810 #[derive(HashStable_Generic)]
1811 pub struct ErrorGuaranteed(());
1813 impl ErrorGuaranteed {
1814 /// To be used only if you really know what you are doing... ideally, we would find a way to
1815 /// eliminate all calls to this method.
1816 pub fn unchecked_claim_error_was_emitted() -> Self {