1 //! Diagnostics creation and emission for `rustc`.
3 //! This module contains the code for creating and emitting diagnostics.
5 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
6 #![feature(drain_filter)]
7 #![feature(if_let_guard)]
8 #![feature(adt_const_params)]
9 #![feature(let_chains)]
10 #![cfg_attr(bootstrap, feature(let_else))]
11 #![feature(never_type)]
12 #![feature(result_option_inspect)]
13 #![feature(rustc_attrs)]
14 #![allow(incomplete_features)]
17 extern crate rustc_macros;
22 pub use emitter::ColorConfig;
24 use rustc_lint_defs::LintExpectationId;
27 use emitter::{is_case_difference, Emitter, EmitterWriter};
28 use registry::Registry;
29 use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet};
30 use rustc_data_structures::stable_hasher::StableHasher;
31 use rustc_data_structures::sync::{self, Lock, Lrc};
32 use rustc_data_structures::AtomicRef;
33 pub use rustc_error_messages::{
34 fallback_fluent_bundle, fluent, fluent_bundle, DiagnosticMessage, FluentBundle,
35 LanguageIdentifier, LazyFallbackBundle, MultiSpan, SpanLabel, SubdiagnosticMessage,
36 DEFAULT_LOCALE_RESOURCES,
38 pub use rustc_lint_defs::{pluralize, Applicability};
39 use rustc_span::source_map::SourceMap;
40 use rustc_span::HashStableContext;
41 use rustc_span::{Loc, Span};
45 use std::num::NonZeroUsize;
48 use std::{error, fmt};
50 use termcolor::{Color, ColorSpec};
52 pub mod annotate_snippet_emitter_writer;
54 mod diagnostic_builder;
63 pub use diagnostic_builder::IntoDiagnostic;
64 pub use snippet::Style;
66 pub type PResult<'a, T> = Result<T, DiagnosticBuilder<'a, ErrorGuaranteed>>;
68 // `PResult` is used a lot. Make sure it doesn't unintentionally get bigger.
69 // (See also the comment on `DiagnosticBuilder`'s `diagnostic` field.)
70 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
71 rustc_data_structures::static_assert_size!(PResult<'_, ()>, 16);
72 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64", not(bootstrap)))]
73 rustc_data_structures::static_assert_size!(PResult<'_, bool>, 16);
75 #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, Encodable, Decodable)]
76 pub enum SuggestionStyle {
77 /// Hide the suggested code when displaying this suggestion inline.
79 /// Always hide the suggested code but display the message.
81 /// Do not display this suggestion in the cli output, it is only meant for tools.
83 /// Always show the suggested code.
84 /// This will *not* show the code if the suggestion is inline *and* the suggested code is
87 /// Always show the suggested code independently.
91 impl SuggestionStyle {
92 fn hide_inline(&self) -> bool {
93 !matches!(*self, SuggestionStyle::ShowCode)
97 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
98 pub struct CodeSuggestion {
99 /// Each substitute can have multiple variants due to multiple
100 /// applicable suggestions
102 /// `foo.bar` might be replaced with `a.b` or `x.y` by replacing
103 /// `foo` and `bar` on their own:
105 /// ```ignore (illustrative)
107 /// Substitution { parts: vec![(0..3, "a"), (4..7, "b")] },
108 /// Substitution { parts: vec![(0..3, "x"), (4..7, "y")] },
112 /// or by replacing the entire span:
114 /// ```ignore (illustrative)
116 /// Substitution { parts: vec![(0..7, "a.b")] },
117 /// Substitution { parts: vec![(0..7, "x.y")] },
120 pub substitutions: Vec<Substitution>,
121 pub msg: DiagnosticMessage,
122 /// Visual representation of this suggestion.
123 pub style: SuggestionStyle,
124 /// Whether or not the suggestion is approximate
126 /// Sometimes we may show suggestions with placeholders,
127 /// which are useful for users but not useful for
128 /// tools like rustfix
129 pub applicability: Applicability,
132 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
133 /// See the docs on `CodeSuggestion::substitutions`
134 pub struct Substitution {
135 pub parts: Vec<SubstitutionPart>,
138 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
139 pub struct SubstitutionPart {
144 /// Used to translate between `Span`s and byte positions within a single output line in highlighted
145 /// code of structured suggestions.
146 #[derive(Debug, Clone, Copy)]
147 pub struct SubstitutionHighlight {
152 impl SubstitutionPart {
153 pub fn is_addition(&self, sm: &SourceMap) -> bool {
154 !self.snippet.is_empty() && !self.replaces_meaningful_content(sm)
157 pub fn is_deletion(&self, sm: &SourceMap) -> bool {
158 self.snippet.trim().is_empty() && self.replaces_meaningful_content(sm)
161 pub fn is_replacement(&self, sm: &SourceMap) -> bool {
162 !self.snippet.is_empty() && self.replaces_meaningful_content(sm)
165 fn replaces_meaningful_content(&self, sm: &SourceMap) -> bool {
166 sm.span_to_snippet(self.span)
167 .map_or(!self.span.is_empty(), |snippet| !snippet.trim().is_empty())
171 impl CodeSuggestion {
172 /// Returns the assembled code suggestions, whether they should be shown with an underline
173 /// and whether the substitution only differs in capitalization.
177 ) -> Vec<(String, Vec<SubstitutionPart>, Vec<Vec<SubstitutionHighlight>>, bool)> {
178 // For the `Vec<Vec<SubstitutionHighlight>>` value, the first level of the vector
179 // corresponds to the output snippet's lines, while the second level corresponds to the
180 // substrings within that line that should be highlighted.
182 use rustc_span::{CharPos, Pos};
184 /// Append to a buffer the remainder of the line of existing source code, and return the
185 /// count of lines that have been added for accurate highlighting.
188 line_opt: Option<&Cow<'_, str>>,
190 hi_opt: Option<&Loc>,
192 let mut line_count = 0;
193 let (lo, hi_opt) = (lo.col.to_usize(), hi_opt.map(|hi| hi.col.to_usize()));
194 if let Some(line) = line_opt {
195 if let Some(lo) = line.char_indices().map(|(i, _)| i).nth(lo) {
196 let hi_opt = hi_opt.and_then(|hi| line.char_indices().map(|(i, _)| i).nth(hi));
198 Some(hi) if hi > lo => {
199 line_count = line[lo..hi].matches('\n').count();
200 buf.push_str(&line[lo..hi])
204 line_count = line[lo..].matches('\n').count();
205 buf.push_str(&line[lo..])
209 if hi_opt.is_none() {
216 assert!(!self.substitutions.is_empty());
221 // Suggestions coming from macros can have malformed spans. This is a heavy
222 // handed approach to avoid ICEs by ignoring the suggestion outright.
223 let invalid = subst.parts.iter().any(|item| sm.is_valid_span(item.span).is_err());
225 debug!("splice_lines: suggestion contains an invalid span: {:?}", subst);
230 .filter_map(|mut substitution| {
231 // Assumption: all spans are in the same file, and all spans
232 // are disjoint. Sort in ascending order.
233 substitution.parts.sort_by_key(|part| part.span.lo());
235 // Find the bounding span.
236 let lo = substitution.parts.iter().map(|part| part.span.lo()).min()?;
237 let hi = substitution.parts.iter().map(|part| part.span.hi()).max()?;
238 let bounding_span = Span::with_root_ctxt(lo, hi);
239 // The different spans might belong to different contexts, if so ignore suggestion.
240 let lines = sm.span_to_lines(bounding_span).ok()?;
241 assert!(!lines.lines.is_empty() || bounding_span.is_dummy());
243 // We can't splice anything if the source is unavailable.
244 if !sm.ensure_source_file_source_present(lines.file.clone()) {
248 let mut highlights = vec![];
249 // To build up the result, we do this for each span:
250 // - push the line segment trailing the previous span
251 // (at the beginning a "phantom" span pointing at the start of the line)
252 // - push lines between the previous and current span (if any)
253 // - if the previous and current span are not on the same line
254 // push the line segment leading up to the current span
255 // - splice in the span substitution
257 // Finally push the trailing line segment of the last span
258 let sf = &lines.file;
259 let mut prev_hi = sm.lookup_char_pos(bounding_span.lo());
260 prev_hi.col = CharPos::from_usize(0);
262 lines.lines.get(0).and_then(|line0| sf.get_line(line0.line_index));
263 let mut buf = String::new();
265 let mut line_highlight = vec![];
266 // We need to keep track of the difference between the existing code and the added
267 // or deleted code in order to point at the correct column *after* substitution.
269 for part in &substitution.parts {
270 let cur_lo = sm.lookup_char_pos(part.span.lo());
271 if prev_hi.line == cur_lo.line {
273 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, Some(&cur_lo));
275 highlights.push(std::mem::take(&mut line_highlight));
281 highlights.push(std::mem::take(&mut line_highlight));
282 let mut count = push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
284 highlights.push(std::mem::take(&mut line_highlight));
287 // push lines between the previous and current span (if any)
288 for idx in prev_hi.line..(cur_lo.line - 1) {
289 if let Some(line) = sf.get_line(idx) {
290 buf.push_str(line.as_ref());
292 highlights.push(std::mem::take(&mut line_highlight));
295 if let Some(cur_line) = sf.get_line(cur_lo.line - 1) {
296 let end = match cur_line.char_indices().nth(cur_lo.col.to_usize()) {
298 None => cur_line.len(),
300 buf.push_str(&cur_line[..end]);
303 // Add a whole line highlight per line in the snippet.
304 let len: isize = part
308 .unwrap_or(&part.snippet)
315 line_highlight.push(SubstitutionHighlight {
316 start: (cur_lo.col.0 as isize + acc) as usize,
317 end: (cur_lo.col.0 as isize + acc + len) as usize,
319 buf.push_str(&part.snippet);
320 let cur_hi = sm.lookup_char_pos(part.span.hi());
321 if prev_hi.line == cur_lo.line && cur_hi.line == cur_lo.line {
322 // Account for the difference between the width of the current code and the
323 // snippet being suggested, so that the *later* suggestions are correctly
324 // aligned on the screen.
325 acc += len as isize - (cur_hi.col.0 - cur_lo.col.0) as isize;
328 prev_line = sf.get_line(prev_hi.line - 1);
329 for line in part.snippet.split('\n').skip(1) {
331 highlights.push(std::mem::take(&mut line_highlight));
332 let end: usize = line
339 line_highlight.push(SubstitutionHighlight { start: 0, end });
342 highlights.push(std::mem::take(&mut line_highlight));
343 let only_capitalization = is_case_difference(sm, &buf, bounding_span);
344 // if the replacement already ends with a newline, don't print the next line
345 if !buf.ends_with('\n') {
346 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
348 // remove trailing newlines
349 while buf.ends_with('\n') {
352 Some((buf, substitution.parts, highlights, only_capitalization))
358 pub use rustc_span::fatal_error::{FatalError, FatalErrorMarker};
360 /// Signifies that the compiler died with an explicit call to `.bug`
361 /// or `.span_bug` rather than a failed assertion, etc.
362 #[derive(Copy, Clone, Debug)]
363 pub struct ExplicitBug;
365 impl fmt::Display for ExplicitBug {
366 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
367 write!(f, "parser internal bug")
371 impl error::Error for ExplicitBug {}
373 pub use diagnostic::{
374 AddToDiagnostic, DecorateLint, Diagnostic, DiagnosticArg, DiagnosticArgFromDisplay,
375 DiagnosticArgValue, DiagnosticId, DiagnosticStyledString, IntoDiagnosticArg, SubDiagnostic,
377 pub use diagnostic_builder::{DiagnosticBuilder, EmissionGuarantee, LintDiagnosticBuilder};
378 use std::backtrace::Backtrace;
380 /// A handler deals with errors and other compiler output.
381 /// Certain errors (fatal, bug, unimpl) may cause immediate exit,
382 /// others log errors for later reporting.
385 inner: Lock<HandlerInner>,
388 /// This inner struct exists to keep it all behind a single lock;
389 /// this is done to prevent possible deadlocks in a multi-threaded compiler,
390 /// as well as inconsistent state observation.
391 struct HandlerInner {
393 /// The number of lint errors that have been emitted.
394 lint_err_count: usize,
395 /// The number of errors that have been emitted, including duplicates.
397 /// This is not necessarily the count that's reported to the user once
398 /// compilation ends.
401 deduplicated_err_count: usize,
402 emitter: Box<dyn Emitter + sync::Send>,
403 delayed_span_bugs: Vec<Diagnostic>,
404 delayed_good_path_bugs: Vec<DelayedDiagnostic>,
405 /// This flag indicates that an expected diagnostic was emitted and suppressed.
406 /// This is used for the `delayed_good_path_bugs` check.
407 suppressed_expected_diag: bool,
409 /// This set contains the `DiagnosticId` of all emitted diagnostics to avoid
410 /// emitting the same diagnostic with extended help (`--teach`) twice, which
411 /// would be unnecessary repetition.
412 taught_diagnostics: FxHashSet<DiagnosticId>,
414 /// Used to suggest rustc --explain <error code>
415 emitted_diagnostic_codes: FxIndexSet<DiagnosticId>,
417 /// This set contains a hash of every diagnostic that has been emitted by
418 /// this handler. These hashes is used to avoid emitting the same error
420 emitted_diagnostics: FxHashSet<u128>,
422 /// Stashed diagnostics emitted in one stage of the compiler that may be
423 /// stolen by other stages (e.g. to improve them and add more information).
424 /// The stashed diagnostics count towards the total error count.
425 /// When `.abort_if_errors()` is called, these are also emitted.
426 stashed_diagnostics: FxIndexMap<(Span, StashKey), Diagnostic>,
428 /// The warning count, used for a recap upon finishing
429 deduplicated_warn_count: usize,
431 future_breakage_diagnostics: Vec<Diagnostic>,
433 /// The [`Self::unstable_expect_diagnostics`] should be empty when this struct is
434 /// dropped. However, it can have values if the compilation is stopped early
435 /// or is only partially executed. To avoid ICEs, like in rust#94953 we only
436 /// check if [`Self::unstable_expect_diagnostics`] is empty, if the expectation ids
437 /// have been converted.
438 check_unstable_expect_diagnostics: bool,
440 /// Expected [`Diagnostic`][diagnostic::Diagnostic]s store a [`LintExpectationId`] as part of
441 /// the lint level. [`LintExpectationId`]s created early during the compilation
442 /// (before `HirId`s have been defined) are not stable and can therefore not be
443 /// stored on disk. This buffer stores these diagnostics until the ID has been
444 /// replaced by a stable [`LintExpectationId`]. The [`Diagnostic`][diagnostic::Diagnostic]s are the
445 /// submitted for storage and added to the list of fulfilled expectations.
446 unstable_expect_diagnostics: Vec<Diagnostic>,
448 /// expected diagnostic will have the level `Expect` which additionally
449 /// carries the [`LintExpectationId`] of the expectation that can be
450 /// marked as fulfilled. This is a collection of all [`LintExpectationId`]s
451 /// that have been marked as fulfilled this way.
453 /// [RFC-2383]: https://rust-lang.github.io/rfcs/2383-lint-reasons.html
454 fulfilled_expectations: FxHashSet<LintExpectationId>,
457 /// A key denoting where from a diagnostic was stashed.
458 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
461 UnderscoreForArrayLengths,
465 fn default_track_diagnostic(_: &Diagnostic) {}
467 pub static TRACK_DIAGNOSTICS: AtomicRef<fn(&Diagnostic)> =
468 AtomicRef::new(&(default_track_diagnostic as fn(&_)));
470 #[derive(Copy, Clone, Default)]
471 pub struct HandlerFlags {
472 /// If false, warning-level lints are suppressed.
473 /// (rustc: see `--allow warnings` and `--cap-lints`)
474 pub can_emit_warnings: bool,
475 /// If true, error-level diagnostics are upgraded to bug-level.
476 /// (rustc: see `-Z treat-err-as-bug`)
477 pub treat_err_as_bug: Option<NonZeroUsize>,
478 /// If true, immediately emit diagnostics that would otherwise be buffered.
479 /// (rustc: see `-Z dont-buffer-diagnostics` and `-Z treat-err-as-bug`)
480 pub dont_buffer_diagnostics: bool,
481 /// If true, immediately print bugs registered with `delay_span_bug`.
482 /// (rustc: see `-Z report-delayed-bugs`)
483 pub report_delayed_bugs: bool,
484 /// Show macro backtraces.
485 /// (rustc: see `-Z macro-backtrace`)
486 pub macro_backtrace: bool,
487 /// If true, identical diagnostics are reported only once.
488 pub deduplicate_diagnostics: bool,
491 impl Drop for HandlerInner {
493 self.emit_stashed_diagnostics();
495 if !self.has_errors() {
496 let bugs = std::mem::replace(&mut self.delayed_span_bugs, Vec::new());
497 self.flush_delayed(bugs, "no errors encountered even though `delay_span_bug` issued");
500 // FIXME(eddyb) this explains what `delayed_good_path_bugs` are!
501 // They're `delayed_span_bugs` but for "require some diagnostic happened"
502 // instead of "require some error happened". Sadly that isn't ideal, as
503 // lints can be `#[allow]`'d, potentially leading to this triggering.
504 // Also, "good path" should be replaced with a better naming.
505 if !self.has_any_message() && !self.suppressed_expected_diag {
506 let bugs = std::mem::replace(&mut self.delayed_good_path_bugs, Vec::new());
508 bugs.into_iter().map(DelayedDiagnostic::decorate),
509 "no warnings or errors encountered even though `delayed_good_path_bugs` issued",
513 if self.check_unstable_expect_diagnostics {
515 self.unstable_expect_diagnostics.is_empty(),
516 "all diagnostics with unstable expectations should have been converted",
523 pub fn with_tty_emitter(
524 color_config: ColorConfig,
525 can_emit_warnings: bool,
526 treat_err_as_bug: Option<NonZeroUsize>,
527 sm: Option<Lrc<SourceMap>>,
528 fluent_bundle: Option<Lrc<FluentBundle>>,
529 fallback_bundle: LazyFallbackBundle,
531 Self::with_tty_emitter_and_flags(
536 HandlerFlags { can_emit_warnings, treat_err_as_bug, ..Default::default() },
540 pub fn with_tty_emitter_and_flags(
541 color_config: ColorConfig,
542 sm: Option<Lrc<SourceMap>>,
543 fluent_bundle: Option<Lrc<FluentBundle>>,
544 fallback_bundle: LazyFallbackBundle,
547 let emitter = Box::new(EmitterWriter::stderr(
555 flags.macro_backtrace,
557 Self::with_emitter_and_flags(emitter, flags)
561 can_emit_warnings: bool,
562 treat_err_as_bug: Option<NonZeroUsize>,
563 emitter: Box<dyn Emitter + sync::Send>,
565 Handler::with_emitter_and_flags(
567 HandlerFlags { can_emit_warnings, treat_err_as_bug, ..Default::default() },
571 pub fn with_emitter_and_flags(
572 emitter: Box<dyn Emitter + sync::Send>,
577 inner: Lock::new(HandlerInner {
582 deduplicated_err_count: 0,
583 deduplicated_warn_count: 0,
585 delayed_span_bugs: Vec::new(),
586 delayed_good_path_bugs: Vec::new(),
587 suppressed_expected_diag: false,
588 taught_diagnostics: Default::default(),
589 emitted_diagnostic_codes: Default::default(),
590 emitted_diagnostics: Default::default(),
591 stashed_diagnostics: Default::default(),
592 future_breakage_diagnostics: Vec::new(),
593 check_unstable_expect_diagnostics: false,
594 unstable_expect_diagnostics: Vec::new(),
595 fulfilled_expectations: Default::default(),
600 // This is here to not allow mutation of flags;
601 // as of this writing it's only used in tests in librustc_middle.
602 pub fn can_emit_warnings(&self) -> bool {
603 self.flags.can_emit_warnings
606 /// Resets the diagnostic error count as well as the cached emitted diagnostics.
608 /// NOTE: *do not* call this function from rustc. It is only meant to be called from external
609 /// tools that want to reuse a `Parser` cleaning the previously emitted diagnostics as well as
610 /// the overall count of emitted error diagnostics.
611 pub fn reset_err_count(&self) {
612 let mut inner = self.inner.borrow_mut();
614 inner.warn_count = 0;
615 inner.deduplicated_err_count = 0;
616 inner.deduplicated_warn_count = 0;
618 // actually free the underlying memory (which `clear` would not do)
619 inner.delayed_span_bugs = Default::default();
620 inner.delayed_good_path_bugs = Default::default();
621 inner.taught_diagnostics = Default::default();
622 inner.emitted_diagnostic_codes = Default::default();
623 inner.emitted_diagnostics = Default::default();
624 inner.stashed_diagnostics = Default::default();
627 /// Stash a given diagnostic with the given `Span` and `StashKey` as the key for later stealing.
628 pub fn stash_diagnostic(&self, span: Span, key: StashKey, diag: Diagnostic) {
629 let mut inner = self.inner.borrow_mut();
630 inner.stash((span, key), diag);
633 /// Steal a previously stashed diagnostic with the given `Span` and `StashKey` as the key.
634 pub fn steal_diagnostic(&self, span: Span, key: StashKey) -> Option<DiagnosticBuilder<'_, ()>> {
635 let mut inner = self.inner.borrow_mut();
636 inner.steal((span, key)).map(|diag| DiagnosticBuilder::new_diagnostic(self, diag))
639 pub fn has_stashed_diagnostic(&self, span: Span, key: StashKey) -> bool {
640 self.inner.borrow().stashed_diagnostics.get(&(span, key)).is_some()
643 /// Emit all stashed diagnostics.
644 pub fn emit_stashed_diagnostics(&self) -> Option<ErrorGuaranteed> {
645 self.inner.borrow_mut().emit_stashed_diagnostics()
648 /// Construct a builder with the `msg` at the level appropriate for the specific `EmissionGuarantee`.
649 #[rustc_lint_diagnostics]
650 pub fn struct_diagnostic<G: EmissionGuarantee>(
652 msg: impl Into<DiagnosticMessage>,
653 ) -> DiagnosticBuilder<'_, G> {
654 G::make_diagnostic_builder(self, msg)
657 /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
659 /// Attempting to `.emit()` the builder will only emit if either:
660 /// * `can_emit_warnings` is `true`
661 /// * `is_force_warn` was set in `DiagnosticId::Lint`
662 #[rustc_lint_diagnostics]
663 pub fn struct_span_warn(
665 span: impl Into<MultiSpan>,
666 msg: impl Into<DiagnosticMessage>,
667 ) -> DiagnosticBuilder<'_, ()> {
668 let mut result = self.struct_warn(msg);
669 result.set_span(span);
673 /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
674 /// The `id` is used for lint emissions which should also fulfill a lint expectation.
676 /// Attempting to `.emit()` the builder will only emit if either:
677 /// * `can_emit_warnings` is `true`
678 /// * `is_force_warn` was set in `DiagnosticId::Lint`
679 pub fn struct_span_warn_with_expectation(
681 span: impl Into<MultiSpan>,
682 msg: impl Into<DiagnosticMessage>,
683 id: LintExpectationId,
684 ) -> DiagnosticBuilder<'_, ()> {
685 let mut result = self.struct_warn_with_expectation(msg, id);
686 result.set_span(span);
690 /// Construct a builder at the `Allow` level at the given `span` and with the `msg`.
691 #[rustc_lint_diagnostics]
692 pub fn struct_span_allow(
694 span: impl Into<MultiSpan>,
695 msg: impl Into<DiagnosticMessage>,
696 ) -> DiagnosticBuilder<'_, ()> {
697 let mut result = self.struct_allow(msg);
698 result.set_span(span);
702 /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
703 /// Also include a code.
704 #[rustc_lint_diagnostics]
705 pub fn struct_span_warn_with_code(
707 span: impl Into<MultiSpan>,
708 msg: impl Into<DiagnosticMessage>,
710 ) -> DiagnosticBuilder<'_, ()> {
711 let mut result = self.struct_span_warn(span, msg);
716 /// Construct a builder at the `Warning` level with the `msg`.
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`
721 #[rustc_lint_diagnostics]
722 pub fn struct_warn(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> {
723 DiagnosticBuilder::new(self, Level::Warning(None), msg)
726 /// Construct a builder at the `Warning` level with the `msg`. The `id` is used for
727 /// lint emissions which should also fulfill a lint expectation.
729 /// Attempting to `.emit()` the builder will only emit if either:
730 /// * `can_emit_warnings` is `true`
731 /// * `is_force_warn` was set in `DiagnosticId::Lint`
732 pub fn struct_warn_with_expectation(
734 msg: impl Into<DiagnosticMessage>,
735 id: LintExpectationId,
736 ) -> DiagnosticBuilder<'_, ()> {
737 DiagnosticBuilder::new(self, Level::Warning(Some(id)), msg)
740 /// Construct a builder at the `Allow` level with the `msg`.
741 #[rustc_lint_diagnostics]
742 pub fn struct_allow(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> {
743 DiagnosticBuilder::new(self, Level::Allow, msg)
746 /// Construct a builder at the `Expect` level with the `msg`.
747 #[rustc_lint_diagnostics]
748 pub fn struct_expect(
750 msg: impl Into<DiagnosticMessage>,
751 id: LintExpectationId,
752 ) -> DiagnosticBuilder<'_, ()> {
753 DiagnosticBuilder::new(self, Level::Expect(id), msg)
756 /// Construct a builder at the `Error` level at the given `span` and with the `msg`.
757 #[rustc_lint_diagnostics]
758 pub fn struct_span_err(
760 span: impl Into<MultiSpan>,
761 msg: impl Into<DiagnosticMessage>,
762 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
763 let mut result = self.struct_err(msg);
764 result.set_span(span);
768 /// Construct a builder at the `Error` level at the given `span`, with the `msg`, and `code`.
769 #[rustc_lint_diagnostics]
770 pub fn struct_span_err_with_code(
772 span: impl Into<MultiSpan>,
773 msg: impl Into<DiagnosticMessage>,
775 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
776 let mut result = self.struct_span_err(span, msg);
781 /// Construct a builder at the `Error` level with the `msg`.
782 // FIXME: This method should be removed (every error should have an associated error code).
783 #[rustc_lint_diagnostics]
786 msg: impl Into<DiagnosticMessage>,
787 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
788 DiagnosticBuilder::new_guaranteeing_error::<_, { Level::Error { lint: false } }>(self, msg)
791 /// This should only be used by `rustc_middle::lint::struct_lint_level`. Do not use it for hard errors.
793 pub fn struct_err_lint(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> {
794 DiagnosticBuilder::new(self, Level::Error { lint: true }, msg)
797 /// Construct a builder at the `Error` level with the `msg` and the `code`.
798 #[rustc_lint_diagnostics]
799 pub fn struct_err_with_code(
801 msg: impl Into<DiagnosticMessage>,
803 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
804 let mut result = self.struct_err(msg);
809 /// Construct a builder at the `Warn` level with the `msg` and the `code`.
810 #[rustc_lint_diagnostics]
811 pub fn struct_warn_with_code(
813 msg: impl Into<DiagnosticMessage>,
815 ) -> DiagnosticBuilder<'_, ()> {
816 let mut result = self.struct_warn(msg);
821 /// Construct a builder at the `Fatal` level at the given `span` and with the `msg`.
822 #[rustc_lint_diagnostics]
823 pub fn struct_span_fatal(
825 span: impl Into<MultiSpan>,
826 msg: impl Into<DiagnosticMessage>,
827 ) -> DiagnosticBuilder<'_, !> {
828 let mut result = self.struct_fatal(msg);
829 result.set_span(span);
833 /// Construct a builder at the `Fatal` level at the given `span`, with the `msg`, and `code`.
834 #[rustc_lint_diagnostics]
835 pub fn struct_span_fatal_with_code(
837 span: impl Into<MultiSpan>,
838 msg: impl Into<DiagnosticMessage>,
840 ) -> DiagnosticBuilder<'_, !> {
841 let mut result = self.struct_span_fatal(span, msg);
846 /// Construct a builder at the `Error` level with the `msg`.
847 #[rustc_lint_diagnostics]
848 pub fn struct_fatal(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, !> {
849 DiagnosticBuilder::new_fatal(self, msg)
852 /// Construct a builder at the `Help` level with the `msg`.
853 #[rustc_lint_diagnostics]
854 pub fn struct_help(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> {
855 DiagnosticBuilder::new(self, Level::Help, msg)
858 /// Construct a builder at the `Note` level with the `msg`.
859 #[rustc_lint_diagnostics]
860 pub fn struct_note_without_error(
862 msg: impl Into<DiagnosticMessage>,
863 ) -> DiagnosticBuilder<'_, ()> {
864 DiagnosticBuilder::new(self, Level::Note, msg)
867 #[rustc_lint_diagnostics]
868 pub fn span_fatal(&self, span: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>) -> ! {
869 self.emit_diag_at_span(Diagnostic::new(Fatal, msg), span);
873 #[rustc_lint_diagnostics]
874 pub fn span_fatal_with_code(
876 span: impl Into<MultiSpan>,
877 msg: impl Into<DiagnosticMessage>,
880 self.emit_diag_at_span(Diagnostic::new_with_code(Fatal, Some(code), msg), span);
884 #[rustc_lint_diagnostics]
887 span: impl Into<MultiSpan>,
888 msg: impl Into<DiagnosticMessage>,
889 ) -> ErrorGuaranteed {
890 self.emit_diag_at_span(Diagnostic::new(Error { lint: false }, msg), span).unwrap()
893 #[rustc_lint_diagnostics]
894 pub fn span_err_with_code(
896 span: impl Into<MultiSpan>,
897 msg: impl Into<DiagnosticMessage>,
900 self.emit_diag_at_span(
901 Diagnostic::new_with_code(Error { lint: false }, Some(code), msg),
906 #[rustc_lint_diagnostics]
907 pub fn span_warn(&self, span: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>) {
908 self.emit_diag_at_span(Diagnostic::new(Warning(None), msg), span);
911 #[rustc_lint_diagnostics]
912 pub fn span_warn_with_code(
914 span: impl Into<MultiSpan>,
915 msg: impl Into<DiagnosticMessage>,
918 self.emit_diag_at_span(Diagnostic::new_with_code(Warning(None), Some(code), msg), span);
921 pub fn span_bug(&self, span: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>) -> ! {
922 self.inner.borrow_mut().span_bug(span, msg)
926 pub fn delay_span_bug(
928 span: impl Into<MultiSpan>,
929 msg: impl Into<DiagnosticMessage>,
930 ) -> ErrorGuaranteed {
931 self.inner.borrow_mut().delay_span_bug(span, msg)
934 // FIXME(eddyb) note the comment inside `impl Drop for HandlerInner`, that's
935 // where the explanation of what "good path" is (also, it should be renamed).
936 pub fn delay_good_path_bug(&self, msg: impl Into<DiagnosticMessage>) {
937 self.inner.borrow_mut().delay_good_path_bug(msg)
940 pub fn span_bug_no_panic(&self, span: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>) {
941 self.emit_diag_at_span(Diagnostic::new(Bug, msg), span);
944 pub fn span_note_without_error(
946 span: impl Into<MultiSpan>,
947 msg: impl Into<DiagnosticMessage>,
949 self.emit_diag_at_span(Diagnostic::new(Note, msg), span);
952 pub fn span_note_diag(
955 msg: impl Into<DiagnosticMessage>,
956 ) -> DiagnosticBuilder<'_, ()> {
957 let mut db = DiagnosticBuilder::new(self, Note, msg);
962 // NOTE: intentionally doesn't raise an error so rustc_codegen_ssa only reports fatal errors in the main thread
963 pub fn fatal(&self, msg: impl Into<DiagnosticMessage>) -> FatalError {
964 self.inner.borrow_mut().fatal(msg)
967 pub fn err(&self, msg: impl Into<DiagnosticMessage>) -> ErrorGuaranteed {
968 self.inner.borrow_mut().err(msg)
971 pub fn warn(&self, msg: impl Into<DiagnosticMessage>) {
972 let mut db = DiagnosticBuilder::new(self, Warning(None), msg);
976 pub fn note_without_error(&self, msg: impl Into<DiagnosticMessage>) {
977 DiagnosticBuilder::new(self, Note, msg).emit();
980 pub fn bug(&self, msg: impl Into<DiagnosticMessage>) -> ! {
981 self.inner.borrow_mut().bug(msg)
985 pub fn err_count(&self) -> usize {
986 self.inner.borrow().err_count()
989 pub fn has_errors(&self) -> Option<ErrorGuaranteed> {
990 if self.inner.borrow().has_errors() { Some(ErrorGuaranteed(())) } else { None }
992 pub fn has_errors_or_lint_errors(&self) -> Option<ErrorGuaranteed> {
993 if self.inner.borrow().has_errors_or_lint_errors() {
994 Some(ErrorGuaranteed(()))
999 pub fn has_errors_or_delayed_span_bugs(&self) -> bool {
1000 self.inner.borrow().has_errors_or_delayed_span_bugs()
1003 pub fn print_error_count(&self, registry: &Registry) {
1004 self.inner.borrow_mut().print_error_count(registry)
1007 pub fn take_future_breakage_diagnostics(&self) -> Vec<Diagnostic> {
1008 std::mem::take(&mut self.inner.borrow_mut().future_breakage_diagnostics)
1011 pub fn abort_if_errors(&self) {
1012 self.inner.borrow_mut().abort_if_errors()
1015 /// `true` if we haven't taught a diagnostic with this code already.
1016 /// The caller must then teach the user about such a diagnostic.
1018 /// Used to suppress emitting the same error multiple times with extended explanation when
1019 /// calling `-Zteach`.
1020 pub fn must_teach(&self, code: &DiagnosticId) -> bool {
1021 self.inner.borrow_mut().must_teach(code)
1024 pub fn force_print_diagnostic(&self, db: Diagnostic) {
1025 self.inner.borrow_mut().force_print_diagnostic(db)
1028 pub fn emit_diagnostic(&self, diagnostic: &mut Diagnostic) -> Option<ErrorGuaranteed> {
1029 self.inner.borrow_mut().emit_diagnostic(diagnostic)
1032 pub fn emit_err<'a>(&'a self, err: impl IntoDiagnostic<'a>) -> ErrorGuaranteed {
1033 self.create_err(err).emit()
1036 pub fn create_err<'a>(
1038 err: impl IntoDiagnostic<'a>,
1039 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
1040 err.into_diagnostic(self)
1043 pub fn create_warning<'a>(
1045 warning: impl IntoDiagnostic<'a, ()>,
1046 ) -> DiagnosticBuilder<'a, ()> {
1047 warning.into_diagnostic(self)
1050 pub fn emit_warning<'a>(&'a self, warning: impl IntoDiagnostic<'a, ()>) {
1051 self.create_warning(warning).emit()
1054 pub fn create_fatal<'a>(
1056 fatal: impl IntoDiagnostic<'a, !>,
1057 ) -> DiagnosticBuilder<'a, !> {
1058 fatal.into_diagnostic(self)
1061 pub fn emit_fatal<'a>(&'a self, fatal: impl IntoDiagnostic<'a, !>) -> ! {
1062 self.create_fatal(fatal).emit()
1065 fn emit_diag_at_span(
1067 mut diag: Diagnostic,
1068 sp: impl Into<MultiSpan>,
1069 ) -> Option<ErrorGuaranteed> {
1070 let mut inner = self.inner.borrow_mut();
1071 inner.emit_diagnostic(diag.set_span(sp))
1074 pub fn emit_artifact_notification(&self, path: &Path, artifact_type: &str) {
1075 self.inner.borrow_mut().emit_artifact_notification(path, artifact_type)
1078 pub fn emit_future_breakage_report(&self, diags: Vec<Diagnostic>) {
1079 self.inner.borrow_mut().emitter.emit_future_breakage_report(diags)
1082 pub fn emit_unused_externs(
1084 lint_level: rustc_lint_defs::Level,
1086 unused_externs: &[&str],
1088 let mut inner = self.inner.borrow_mut();
1090 if loud && lint_level.is_error() {
1091 inner.bump_err_count();
1094 inner.emit_unused_externs(lint_level, unused_externs)
1097 pub fn update_unstable_expectation_id(
1099 unstable_to_stable: &FxHashMap<LintExpectationId, LintExpectationId>,
1101 let mut inner = self.inner.borrow_mut();
1102 let diags = std::mem::take(&mut inner.unstable_expect_diagnostics);
1103 inner.check_unstable_expect_diagnostics = true;
1105 if !diags.is_empty() {
1106 inner.suppressed_expected_diag = true;
1107 for mut diag in diags.into_iter() {
1108 diag.update_unstable_expectation_id(unstable_to_stable);
1110 // Here the diagnostic is given back to `emit_diagnostic` where it was first
1111 // intercepted. Now it should be processed as usual, since the unstable expectation
1112 // id is now stable.
1113 inner.emit_diagnostic(&mut diag);
1118 .stashed_diagnostics
1120 .for_each(|diag| diag.update_unstable_expectation_id(unstable_to_stable));
1122 .future_breakage_diagnostics
1124 .for_each(|diag| diag.update_unstable_expectation_id(unstable_to_stable));
1127 /// This methods steals all [`LintExpectationId`]s that are stored inside
1128 /// [`HandlerInner`] and indicate that the linked expectation has been fulfilled.
1130 pub fn steal_fulfilled_expectation_ids(&self) -> FxHashSet<LintExpectationId> {
1132 self.inner.borrow().unstable_expect_diagnostics.is_empty(),
1133 "`HandlerInner::unstable_expect_diagnostics` should be empty at this point",
1135 std::mem::take(&mut self.inner.borrow_mut().fulfilled_expectations)
1140 fn must_teach(&mut self, code: &DiagnosticId) -> bool {
1141 self.taught_diagnostics.insert(code.clone())
1144 fn force_print_diagnostic(&mut self, mut db: Diagnostic) {
1145 self.emitter.emit_diagnostic(&mut db);
1148 /// Emit all stashed diagnostics.
1149 fn emit_stashed_diagnostics(&mut self) -> Option<ErrorGuaranteed> {
1150 let has_errors = self.has_errors();
1151 let diags = self.stashed_diagnostics.drain(..).map(|x| x.1).collect::<Vec<_>>();
1152 let mut reported = None;
1153 for mut diag in diags {
1154 // Decrement the count tracking the stash; emitting will increment it.
1155 if diag.is_error() {
1156 if matches!(diag.level, Level::Error { lint: true }) {
1157 self.lint_err_count -= 1;
1159 self.err_count -= 1;
1162 if diag.is_force_warn() {
1163 self.warn_count -= 1;
1165 // Unless they're forced, don't flush stashed warnings when
1166 // there are errors, to avoid causing warning overload. The
1167 // stash would've been stolen already if it were important.
1173 let reported_this = self.emit_diagnostic(&mut diag);
1174 reported = reported.or(reported_this);
1179 // FIXME(eddyb) this should ideally take `diagnostic` by value.
1180 fn emit_diagnostic(&mut self, diagnostic: &mut Diagnostic) -> Option<ErrorGuaranteed> {
1181 // The `LintExpectationId` can be stable or unstable depending on when it was created.
1182 // Diagnostics created before the definition of `HirId`s are unstable and can not yet
1183 // be stored. Instead, they are buffered until the `LintExpectationId` is replaced by
1184 // a stable one by the `LintLevelsBuilder`.
1185 if let Some(LintExpectationId::Unstable { .. }) = diagnostic.level.get_expectation_id() {
1186 self.unstable_expect_diagnostics.push(diagnostic.clone());
1190 if diagnostic.level == Level::DelayedBug {
1191 // FIXME(eddyb) this should check for `has_errors` and stop pushing
1192 // once *any* errors were emitted (and truncate `delayed_span_bugs`
1193 // when an error is first emitted, also), but maybe there's a case
1194 // in which that's not sound? otherwise this is really inefficient.
1195 self.delayed_span_bugs.push(diagnostic.clone());
1197 if !self.flags.report_delayed_bugs {
1198 return Some(ErrorGuaranteed::unchecked_claim_error_was_emitted());
1202 if diagnostic.has_future_breakage() {
1203 self.future_breakage_diagnostics.push(diagnostic.clone());
1206 if let Some(expectation_id) = diagnostic.level.get_expectation_id() {
1207 self.suppressed_expected_diag = true;
1208 self.fulfilled_expectations.insert(expectation_id.normalize());
1211 if matches!(diagnostic.level, Warning(_))
1212 && !self.flags.can_emit_warnings
1213 && !diagnostic.is_force_warn()
1215 if diagnostic.has_future_breakage() {
1216 (*TRACK_DIAGNOSTICS)(diagnostic);
1221 (*TRACK_DIAGNOSTICS)(diagnostic);
1223 if matches!(diagnostic.level, Level::Expect(_) | Level::Allow) {
1227 if let Some(ref code) = diagnostic.code {
1228 self.emitted_diagnostic_codes.insert(code.clone());
1231 let already_emitted = |this: &mut Self| {
1232 let mut hasher = StableHasher::new();
1233 diagnostic.hash(&mut hasher);
1234 let diagnostic_hash = hasher.finish();
1235 !this.emitted_diagnostics.insert(diagnostic_hash)
1238 // Only emit the diagnostic if we've been asked to deduplicate or
1239 // haven't already emitted an equivalent diagnostic.
1240 if !(self.flags.deduplicate_diagnostics && already_emitted(self)) {
1241 debug!(?diagnostic);
1242 debug!(?self.emitted_diagnostics);
1243 let already_emitted_sub = |sub: &mut SubDiagnostic| {
1245 if sub.level != Level::OnceNote {
1248 let mut hasher = StableHasher::new();
1249 sub.hash(&mut hasher);
1250 let diagnostic_hash = hasher.finish();
1251 debug!(?diagnostic_hash);
1252 !self.emitted_diagnostics.insert(diagnostic_hash)
1255 diagnostic.children.drain_filter(already_emitted_sub).for_each(|_| {});
1257 self.emitter.emit_diagnostic(&diagnostic);
1258 if diagnostic.is_error() {
1259 self.deduplicated_err_count += 1;
1260 } else if let Warning(_) = diagnostic.level {
1261 self.deduplicated_warn_count += 1;
1264 if diagnostic.is_error() {
1265 if matches!(diagnostic.level, Level::Error { lint: true }) {
1266 self.bump_lint_err_count();
1268 self.bump_err_count();
1271 Some(ErrorGuaranteed::unchecked_claim_error_was_emitted())
1273 self.bump_warn_count();
1279 fn emit_artifact_notification(&mut self, path: &Path, artifact_type: &str) {
1280 self.emitter.emit_artifact_notification(path, artifact_type);
1283 fn emit_unused_externs(&mut self, lint_level: rustc_lint_defs::Level, unused_externs: &[&str]) {
1284 self.emitter.emit_unused_externs(lint_level, unused_externs);
1287 fn treat_err_as_bug(&self) -> bool {
1288 self.flags.treat_err_as_bug.map_or(false, |c| {
1289 self.err_count() + self.lint_err_count + self.delayed_bug_count() >= c.get()
1293 fn delayed_bug_count(&self) -> usize {
1294 self.delayed_span_bugs.len() + self.delayed_good_path_bugs.len()
1297 fn print_error_count(&mut self, registry: &Registry) {
1298 self.emit_stashed_diagnostics();
1300 let warnings = match self.deduplicated_warn_count {
1302 1 => "1 warning emitted".to_string(),
1303 count => format!("{count} warnings emitted"),
1305 let errors = match self.deduplicated_err_count {
1307 1 => "aborting due to previous error".to_string(),
1308 count => format!("aborting due to {count} previous errors"),
1310 if self.treat_err_as_bug() {
1314 match (errors.len(), warnings.len()) {
1316 (0, _) => self.emitter.emit_diagnostic(&Diagnostic::new(
1317 Level::Warning(None),
1318 DiagnosticMessage::Str(warnings),
1321 let _ = self.fatal(&errors);
1324 let _ = self.fatal(&format!("{}; {}", &errors, &warnings));
1328 let can_show_explain = self.emitter.should_show_explain();
1329 let are_there_diagnostics = !self.emitted_diagnostic_codes.is_empty();
1330 if can_show_explain && are_there_diagnostics {
1331 let mut error_codes = self
1332 .emitted_diagnostic_codes
1334 .filter_map(|x| match &x {
1335 DiagnosticId::Error(s)
1336 if registry.try_find_description(s).map_or(false, |o| o.is_some()) =>
1342 .collect::<Vec<_>>();
1343 if !error_codes.is_empty() {
1345 if error_codes.len() > 1 {
1346 let limit = if error_codes.len() > 9 { 9 } else { error_codes.len() };
1347 self.failure(&format!(
1348 "Some errors have detailed explanations: {}{}",
1349 error_codes[..limit].join(", "),
1350 if error_codes.len() > 9 { "..." } else { "." }
1352 self.failure(&format!(
1353 "For more information about an error, try \
1354 `rustc --explain {}`.",
1358 self.failure(&format!(
1359 "For more information about this error, try \
1360 `rustc --explain {}`.",
1368 fn stash(&mut self, key: (Span, StashKey), diagnostic: Diagnostic) {
1369 // Track the diagnostic for counts, but don't panic-if-treat-err-as-bug
1370 // yet; that happens when we actually emit the diagnostic.
1371 if diagnostic.is_error() {
1372 if matches!(diagnostic.level, Level::Error { lint: true }) {
1373 self.lint_err_count += 1;
1375 self.err_count += 1;
1378 // Warnings are only automatically flushed if they're forced.
1379 if diagnostic.is_force_warn() {
1380 self.warn_count += 1;
1384 // FIXME(Centril, #69537): Consider reintroducing panic on overwriting a stashed diagnostic
1385 // if/when we have a more robust macro-friendly replacement for `(span, key)` as a key.
1386 // See the PR for a discussion.
1387 self.stashed_diagnostics.insert(key, diagnostic);
1390 fn steal(&mut self, key: (Span, StashKey)) -> Option<Diagnostic> {
1391 let diagnostic = self.stashed_diagnostics.remove(&key)?;
1392 if diagnostic.is_error() {
1393 if matches!(diagnostic.level, Level::Error { lint: true }) {
1394 self.lint_err_count -= 1;
1396 self.err_count -= 1;
1399 if diagnostic.is_force_warn() {
1400 self.warn_count -= 1;
1407 fn err_count(&self) -> usize {
1411 fn has_errors(&self) -> bool {
1412 self.err_count() > 0
1414 fn has_errors_or_lint_errors(&self) -> bool {
1415 self.has_errors() || self.lint_err_count > 0
1417 fn has_errors_or_delayed_span_bugs(&self) -> bool {
1418 self.has_errors() || !self.delayed_span_bugs.is_empty()
1420 fn has_any_message(&self) -> bool {
1421 self.err_count() > 0 || self.lint_err_count > 0 || self.warn_count > 0
1424 fn abort_if_errors(&mut self) {
1425 self.emit_stashed_diagnostics();
1427 if self.has_errors() {
1432 fn span_bug(&mut self, sp: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>) -> ! {
1433 self.emit_diag_at_span(Diagnostic::new(Bug, msg), sp);
1434 panic::panic_any(ExplicitBug);
1437 fn emit_diag_at_span(&mut self, mut diag: Diagnostic, sp: impl Into<MultiSpan>) {
1438 self.emit_diagnostic(diag.set_span(sp));
1444 sp: impl Into<MultiSpan>,
1445 msg: impl Into<DiagnosticMessage>,
1446 ) -> ErrorGuaranteed {
1447 // This is technically `self.treat_err_as_bug()` but `delay_span_bug` is called before
1448 // incrementing `err_count` by one, so we need to +1 the comparing.
1449 // FIXME: Would be nice to increment err_count in a more coherent way.
1450 if self.flags.treat_err_as_bug.map_or(false, |c| {
1451 self.err_count() + self.lint_err_count + self.delayed_bug_count() + 1 >= c.get()
1453 // FIXME: don't abort here if report_delayed_bugs is off
1454 self.span_bug(sp, msg);
1456 let mut diagnostic = Diagnostic::new(Level::DelayedBug, msg);
1457 diagnostic.set_span(sp.into());
1458 diagnostic.note(&format!("delayed at {}", std::panic::Location::caller()));
1459 self.emit_diagnostic(&mut diagnostic).unwrap()
1462 // FIXME(eddyb) note the comment inside `impl Drop for HandlerInner`, that's
1463 // where the explanation of what "good path" is (also, it should be renamed).
1464 fn delay_good_path_bug(&mut self, msg: impl Into<DiagnosticMessage>) {
1465 let mut diagnostic = Diagnostic::new(Level::DelayedBug, msg);
1466 if self.flags.report_delayed_bugs {
1467 self.emit_diagnostic(&mut diagnostic);
1469 let backtrace = std::backtrace::Backtrace::force_capture();
1470 self.delayed_good_path_bugs.push(DelayedDiagnostic::with_backtrace(diagnostic, backtrace));
1473 fn failure(&mut self, msg: impl Into<DiagnosticMessage>) {
1474 self.emit_diagnostic(&mut Diagnostic::new(FailureNote, msg));
1477 fn fatal(&mut self, msg: impl Into<DiagnosticMessage>) -> FatalError {
1478 self.emit(Fatal, msg);
1482 fn err(&mut self, msg: impl Into<DiagnosticMessage>) -> ErrorGuaranteed {
1483 self.emit(Error { lint: false }, msg)
1486 /// Emit an error; level should be `Error` or `Fatal`.
1487 fn emit(&mut self, level: Level, msg: impl Into<DiagnosticMessage>) -> ErrorGuaranteed {
1488 if self.treat_err_as_bug() {
1491 self.emit_diagnostic(&mut Diagnostic::new(level, msg)).unwrap()
1494 fn bug(&mut self, msg: impl Into<DiagnosticMessage>) -> ! {
1495 self.emit_diagnostic(&mut Diagnostic::new(Bug, msg));
1496 panic::panic_any(ExplicitBug);
1501 bugs: impl IntoIterator<Item = Diagnostic>,
1502 explanation: impl Into<DiagnosticMessage> + Copy,
1504 let mut no_bugs = true;
1505 for mut bug in bugs {
1507 // Put the overall explanation before the `DelayedBug`s, to
1508 // frame them better (e.g. separate warnings from them).
1509 self.emit_diagnostic(&mut Diagnostic::new(Bug, explanation));
1513 // "Undelay" the `DelayedBug`s (into plain `Bug`s).
1514 if bug.level != Level::DelayedBug {
1515 // NOTE(eddyb) not panicking here because we're already producing
1516 // an ICE, and the more information the merrier.
1518 "`flushed_delayed` got diagnostic with level {:?}, \
1519 instead of the expected `DelayedBug`",
1523 bug.level = Level::Bug;
1525 self.emit_diagnostic(&mut bug);
1528 // Panic with `ExplicitBug` to avoid "unexpected panic" messages.
1530 panic::panic_any(ExplicitBug);
1534 fn bump_lint_err_count(&mut self) {
1535 self.lint_err_count += 1;
1536 self.panic_if_treat_err_as_bug();
1539 fn bump_err_count(&mut self) {
1540 self.err_count += 1;
1541 self.panic_if_treat_err_as_bug();
1544 fn bump_warn_count(&mut self) {
1545 self.warn_count += 1;
1548 fn panic_if_treat_err_as_bug(&self) {
1549 if self.treat_err_as_bug() {
1551 self.err_count() + self.lint_err_count,
1552 self.delayed_bug_count(),
1553 self.flags.treat_err_as_bug.map(|c| c.get()).unwrap_or(0),
1555 (1, 0, 1) => panic!("aborting due to `-Z treat-err-as-bug=1`"),
1556 (0, 1, 1) => panic!("aborting due delayed bug with `-Z treat-err-as-bug=1`"),
1557 (count, delayed_count, as_bug) => {
1558 if delayed_count > 0 {
1560 "aborting after {} errors and {} delayed bugs due to `-Z treat-err-as-bug={}`",
1561 count, delayed_count, as_bug,
1565 "aborting after {} errors due to `-Z treat-err-as-bug={}`",
1575 struct DelayedDiagnostic {
1580 impl DelayedDiagnostic {
1581 fn with_backtrace(diagnostic: Diagnostic, backtrace: Backtrace) -> Self {
1582 DelayedDiagnostic { inner: diagnostic, note: backtrace }
1585 fn decorate(mut self) -> Diagnostic {
1586 self.inner.note(&format!("delayed at {}", self.note));
1591 #[derive(Copy, PartialEq, Eq, Clone, Hash, Debug, Encodable, Decodable)]
1597 /// If this error comes from a lint, don't abort compilation even when abort_if_errors() is called.
1600 /// This [`LintExpectationId`] is used for expected lint diagnostics, which should
1601 /// also emit a warning due to the `force-warn` flag. In all other cases this should
1603 Warning(Option<LintExpectationId>),
1605 /// A note that is only emitted once.
1610 Expect(LintExpectationId),
1613 impl fmt::Display for Level {
1614 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1615 self.to_str().fmt(f)
1620 fn color(self) -> ColorSpec {
1621 let mut spec = ColorSpec::new();
1623 Bug | DelayedBug | Fatal | Error { .. } => {
1624 spec.set_fg(Some(Color::Red)).set_intense(true);
1627 spec.set_fg(Some(Color::Yellow)).set_intense(cfg!(windows));
1629 Note | OnceNote => {
1630 spec.set_fg(Some(Color::Green)).set_intense(true);
1633 spec.set_fg(Some(Color::Cyan)).set_intense(true);
1636 Allow | Expect(_) => unreachable!(),
1641 pub fn to_str(self) -> &'static str {
1643 Bug | DelayedBug => "error: internal compiler error",
1644 Fatal | Error { .. } => "error",
1645 Warning(_) => "warning",
1646 Note | OnceNote => "note",
1648 FailureNote => "failure-note",
1649 Allow => panic!("Shouldn't call on allowed error"),
1650 Expect(_) => panic!("Shouldn't call on expected error"),
1654 pub fn is_failure_note(&self) -> bool {
1655 matches!(*self, FailureNote)
1658 pub fn get_expectation_id(&self) -> Option<LintExpectationId> {
1660 Level::Expect(id) | Level::Warning(Some(id)) => Some(*id),
1666 // FIXME(eddyb) this doesn't belong here AFAICT, should be moved to callsite.
1667 pub fn add_elided_lifetime_in_path_suggestion(
1668 source_map: &SourceMap,
1669 diag: &mut Diagnostic,
1672 incl_angl_brckt: bool,
1673 insertion_span: Span,
1675 diag.span_label(path_span, format!("expected lifetime parameter{}", pluralize!(n)));
1676 if !source_map.is_span_accessible(insertion_span) {
1677 // Do not try to suggest anything if generated by a proc-macro.
1680 let anon_lts = vec!["'_"; n].join(", ");
1682 if incl_angl_brckt { format!("<{}>", anon_lts) } else { format!("{}, ", anon_lts) };
1683 diag.span_suggestion_verbose(
1684 insertion_span.shrink_to_hi(),
1685 &format!("indicate the anonymous lifetime{}", pluralize!(n)),
1687 Applicability::MachineApplicable,
1691 /// Useful type to use with `Result<>` indicate that an error has already
1692 /// been reported to the user, so no need to continue checking.
1693 #[derive(Clone, Copy, Debug, Encodable, Decodable, Hash, PartialEq, Eq, PartialOrd, Ord)]
1694 #[derive(HashStable_Generic)]
1695 pub struct ErrorGuaranteed(());
1697 impl ErrorGuaranteed {
1698 /// To be used only if you really know what you are doing... ideally, we would find a way to
1699 /// eliminate all calls to this method.
1700 pub fn unchecked_claim_error_was_emitted() -> Self {