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(crate_visibility_modifier)]
7 #![feature(drain_filter)]
9 #![feature(if_let_guard)]
11 #![feature(never_type)]
13 #![feature(adt_const_params)]
14 #![allow(incomplete_features)]
15 #![allow(rustc::potential_query_instability)]
18 extern crate rustc_macros;
23 pub use emitter::ColorConfig;
25 use rustc_lint_defs::LintExpectationId;
28 use emitter::{is_case_difference, Emitter, EmitterWriter};
29 use registry::Registry;
30 use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap};
31 use rustc_data_structures::stable_hasher::StableHasher;
32 use rustc_data_structures::sync::{self, Lock, Lrc};
33 use rustc_data_structures::AtomicRef;
34 pub use rustc_error_messages::{
35 fallback_fluent_bundle, fluent_bundle, DiagnosticMessage, FluentBundle, LanguageIdentifier,
36 LazyFallbackBundle, MultiSpan, SpanLabel, 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;
62 pub use snippet::Style;
64 pub type PResult<'a, T> = Result<T, DiagnosticBuilder<'a, ErrorGuaranteed>>;
66 // `PResult` is used a lot. Make sure it doesn't unintentionally get bigger.
67 // (See also the comment on `DiagnosticBuilder`'s `diagnostic` field.)
68 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
69 rustc_data_structures::static_assert_size!(PResult<'_, ()>, 16);
70 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
71 rustc_data_structures::static_assert_size!(PResult<'_, bool>, 24);
73 #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, Encodable, Decodable)]
74 pub enum SuggestionStyle {
75 /// Hide the suggested code when displaying this suggestion inline.
77 /// Always hide the suggested code but display the message.
79 /// Do not display this suggestion in the cli output, it is only meant for tools.
81 /// Always show the suggested code.
82 /// This will *not* show the code if the suggestion is inline *and* the suggested code is
85 /// Always show the suggested code independently.
89 impl SuggestionStyle {
90 fn hide_inline(&self) -> bool {
91 !matches!(*self, SuggestionStyle::ShowCode)
95 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
96 pub struct CodeSuggestion {
97 /// Each substitute can have multiple variants due to multiple
98 /// applicable suggestions
100 /// `foo.bar` might be replaced with `a.b` or `x.y` by replacing
101 /// `foo` and `bar` on their own:
103 /// ```ignore (illustrative)
105 /// Substitution { parts: vec![(0..3, "a"), (4..7, "b")] },
106 /// Substitution { parts: vec![(0..3, "x"), (4..7, "y")] },
110 /// or by replacing the entire span:
112 /// ```ignore (illustrative)
114 /// Substitution { parts: vec![(0..7, "a.b")] },
115 /// Substitution { parts: vec![(0..7, "x.y")] },
118 pub substitutions: Vec<Substitution>,
119 pub msg: DiagnosticMessage,
120 /// Visual representation of this suggestion.
121 pub style: SuggestionStyle,
122 /// Whether or not the suggestion is approximate
124 /// Sometimes we may show suggestions with placeholders,
125 /// which are useful for users but not useful for
126 /// tools like rustfix
127 pub applicability: Applicability,
130 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
131 /// See the docs on `CodeSuggestion::substitutions`
132 pub struct Substitution {
133 pub parts: Vec<SubstitutionPart>,
136 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
137 pub struct SubstitutionPart {
142 /// Used to translate between `Span`s and byte positions within a single output line in highlighted
143 /// code of structured suggestions.
144 #[derive(Debug, Clone, Copy)]
145 pub struct SubstitutionHighlight {
150 impl SubstitutionPart {
151 pub fn is_addition(&self, sm: &SourceMap) -> bool {
152 !self.snippet.is_empty()
154 .span_to_snippet(self.span)
155 .map_or(self.span.is_empty(), |snippet| snippet.trim().is_empty())
158 pub fn is_deletion(&self) -> bool {
159 self.snippet.trim().is_empty()
162 pub fn is_replacement(&self, sm: &SourceMap) -> bool {
163 !self.snippet.is_empty()
165 .span_to_snippet(self.span)
166 .map_or(!self.span.is_empty(), |snippet| !snippet.trim().is_empty())
170 impl CodeSuggestion {
171 /// Returns the assembled code suggestions, whether they should be shown with an underline
172 /// and whether the substitution only differs in capitalization.
176 ) -> Vec<(String, Vec<SubstitutionPart>, Vec<Vec<SubstitutionHighlight>>, bool)> {
177 // For the `Vec<Vec<SubstitutionHighlight>>` value, the first level of the vector
178 // corresponds to the output snippet's lines, while the second level corresponds to the
179 // substrings within that line that should be highlighted.
181 use rustc_span::{CharPos, Pos};
183 /// Append to a buffer the remainder of the line of existing source code, and return the
184 /// count of lines that have been added for accurate highlighting.
187 line_opt: Option<&Cow<'_, str>>,
189 hi_opt: Option<&Loc>,
191 let mut line_count = 0;
192 let (lo, hi_opt) = (lo.col.to_usize(), hi_opt.map(|hi| hi.col.to_usize()));
193 if let Some(line) = line_opt {
194 if let Some(lo) = line.char_indices().map(|(i, _)| i).nth(lo) {
195 let hi_opt = hi_opt.and_then(|hi| line.char_indices().map(|(i, _)| i).nth(hi));
197 Some(hi) if hi > lo => {
198 line_count = line[lo..hi].matches('\n').count();
199 buf.push_str(&line[lo..hi])
203 line_count = line[lo..].matches('\n').count();
204 buf.push_str(&line[lo..])
208 if hi_opt.is_none() {
215 assert!(!self.substitutions.is_empty());
220 // Suggestions coming from macros can have malformed spans. This is a heavy
221 // handed approach to avoid ICEs by ignoring the suggestion outright.
222 let invalid = subst.parts.iter().any(|item| sm.is_valid_span(item.span).is_err());
224 debug!("splice_lines: suggestion contains an invalid span: {:?}", subst);
229 .filter_map(|mut substitution| {
230 // Assumption: all spans are in the same file, and all spans
231 // are disjoint. Sort in ascending order.
232 substitution.parts.sort_by_key(|part| part.span.lo());
234 // Find the bounding span.
235 let lo = substitution.parts.iter().map(|part| part.span.lo()).min()?;
236 let hi = substitution.parts.iter().map(|part| part.span.hi()).max()?;
237 let bounding_span = Span::with_root_ctxt(lo, hi);
238 // The different spans might belong to different contexts, if so ignore suggestion.
239 let lines = sm.span_to_lines(bounding_span).ok()?;
240 assert!(!lines.lines.is_empty() || bounding_span.is_dummy());
242 // We can't splice anything if the source is unavailable.
243 if !sm.ensure_source_file_source_present(lines.file.clone()) {
247 let mut highlights = vec![];
248 // To build up the result, we do this for each span:
249 // - push the line segment trailing the previous span
250 // (at the beginning a "phantom" span pointing at the start of the line)
251 // - push lines between the previous and current span (if any)
252 // - if the previous and current span are not on the same line
253 // push the line segment leading up to the current span
254 // - splice in the span substitution
256 // Finally push the trailing line segment of the last span
257 let sf = &lines.file;
258 let mut prev_hi = sm.lookup_char_pos(bounding_span.lo());
259 prev_hi.col = CharPos::from_usize(0);
261 lines.lines.get(0).and_then(|line0| sf.get_line(line0.line_index));
262 let mut buf = String::new();
264 let mut line_highlight = vec![];
265 // We need to keep track of the difference between the existing code and the added
266 // or deleted code in order to point at the correct column *after* substitution.
268 for part in &substitution.parts {
269 let cur_lo = sm.lookup_char_pos(part.span.lo());
270 if prev_hi.line == cur_lo.line {
272 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, Some(&cur_lo));
274 highlights.push(std::mem::take(&mut line_highlight));
280 highlights.push(std::mem::take(&mut line_highlight));
281 let mut count = push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
283 highlights.push(std::mem::take(&mut line_highlight));
286 // push lines between the previous and current span (if any)
287 for idx in prev_hi.line..(cur_lo.line - 1) {
288 if let Some(line) = sf.get_line(idx) {
289 buf.push_str(line.as_ref());
291 highlights.push(std::mem::take(&mut line_highlight));
294 if let Some(cur_line) = sf.get_line(cur_lo.line - 1) {
295 let end = match cur_line.char_indices().nth(cur_lo.col.to_usize()) {
297 None => cur_line.len(),
299 buf.push_str(&cur_line[..end]);
302 // Add a whole line highlight per line in the snippet.
303 let len: isize = part
307 .unwrap_or(&part.snippet)
314 line_highlight.push(SubstitutionHighlight {
315 start: (cur_lo.col.0 as isize + acc) as usize,
316 end: (cur_lo.col.0 as isize + acc + len) as usize,
318 buf.push_str(&part.snippet);
319 let cur_hi = sm.lookup_char_pos(part.span.hi());
320 if prev_hi.line == cur_lo.line && cur_hi.line == cur_lo.line {
321 // Account for the difference between the width of the current code and the
322 // snippet being suggested, so that the *later* suggestions are correctly
323 // aligned on the screen.
324 acc += len as isize - (cur_hi.col.0 - cur_lo.col.0) as isize;
327 prev_line = sf.get_line(prev_hi.line - 1);
328 for line in part.snippet.split('\n').skip(1) {
330 highlights.push(std::mem::take(&mut line_highlight));
331 let end: usize = line
338 line_highlight.push(SubstitutionHighlight { start: 0, end });
341 highlights.push(std::mem::take(&mut line_highlight));
342 let only_capitalization = is_case_difference(sm, &buf, bounding_span);
343 // if the replacement already ends with a newline, don't print the next line
344 if !buf.ends_with('\n') {
345 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
347 // remove trailing newlines
348 while buf.ends_with('\n') {
351 Some((buf, substitution.parts, highlights, only_capitalization))
357 pub use rustc_span::fatal_error::{FatalError, FatalErrorMarker};
359 /// Signifies that the compiler died with an explicit call to `.bug`
360 /// or `.span_bug` rather than a failed assertion, etc.
361 #[derive(Copy, Clone, Debug)]
362 pub struct ExplicitBug;
364 impl fmt::Display for ExplicitBug {
365 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
366 write!(f, "parser internal bug")
370 impl error::Error for ExplicitBug {}
372 pub use diagnostic::{
373 AddSubdiagnostic, Diagnostic, DiagnosticArg, DiagnosticArgValue, DiagnosticId,
374 DiagnosticStyledString, IntoDiagnosticArg, SubDiagnostic,
376 pub use diagnostic_builder::{DiagnosticBuilder, EmissionGuarantee};
377 use std::backtrace::Backtrace;
379 /// A handler deals with errors and other compiler output.
380 /// Certain errors (fatal, bug, unimpl) may cause immediate exit,
381 /// others log errors for later reporting.
384 inner: Lock<HandlerInner>,
387 /// This inner struct exists to keep it all behind a single lock;
388 /// this is done to prevent possible deadlocks in a multi-threaded compiler,
389 /// as well as inconsistent state observation.
390 struct HandlerInner {
392 /// The number of lint errors that have been emitted.
393 lint_err_count: usize,
394 /// The number of errors that have been emitted, including duplicates.
396 /// This is not necessarily the count that's reported to the user once
397 /// compilation ends.
400 deduplicated_err_count: usize,
401 emitter: Box<dyn Emitter + sync::Send>,
402 delayed_span_bugs: Vec<Diagnostic>,
403 delayed_good_path_bugs: Vec<DelayedDiagnostic>,
405 /// This set contains the `DiagnosticId` of all emitted diagnostics to avoid
406 /// emitting the same diagnostic with extended help (`--teach`) twice, which
407 /// would be unnecessary repetition.
408 taught_diagnostics: FxHashSet<DiagnosticId>,
410 /// Used to suggest rustc --explain <error code>
411 emitted_diagnostic_codes: FxHashSet<DiagnosticId>,
413 /// This set contains a hash of every diagnostic that has been emitted by
414 /// this handler. These hashes is used to avoid emitting the same error
416 emitted_diagnostics: FxHashSet<u128>,
418 /// Stashed diagnostics emitted in one stage of the compiler that may be
419 /// stolen by other stages (e.g. to improve them and add more information).
420 /// The stashed diagnostics count towards the total error count.
421 /// When `.abort_if_errors()` is called, these are also emitted.
422 stashed_diagnostics: FxIndexMap<(Span, StashKey), Diagnostic>,
424 /// The warning count, used for a recap upon finishing
425 deduplicated_warn_count: usize,
427 future_breakage_diagnostics: Vec<Diagnostic>,
429 /// Expected [`Diagnostic`]s store a [`LintExpectationId`] as part of
430 /// the lint level. [`LintExpectationId`]s created early during the compilation
431 /// (before `HirId`s have been defined) are not stable and can therefore not be
432 /// stored on disk. This buffer stores these diagnostics until the ID has been
433 /// replaced by a stable [`LintExpectationId`]. The [`Diagnostic`]s are the
434 /// submitted for storage and added to the list of fulfilled expectations.
435 unstable_expect_diagnostics: Vec<Diagnostic>,
437 /// expected diagnostic will have the level `Expect` which additionally
438 /// carries the [`LintExpectationId`] of the expectation that can be
439 /// marked as fulfilled. This is a collection of all [`LintExpectationId`]s
440 /// that have been marked as fulfilled this way.
442 /// [RFC-2383]: https://rust-lang.github.io/rfcs/2383-lint-reasons.html
443 fulfilled_expectations: FxHashSet<LintExpectationId>,
446 /// A key denoting where from a diagnostic was stashed.
447 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
452 fn default_track_diagnostic(_: &Diagnostic) {}
454 pub static TRACK_DIAGNOSTICS: AtomicRef<fn(&Diagnostic)> =
455 AtomicRef::new(&(default_track_diagnostic as fn(&_)));
457 #[derive(Copy, Clone, Default)]
458 pub struct HandlerFlags {
459 /// If false, warning-level lints are suppressed.
460 /// (rustc: see `--allow warnings` and `--cap-lints`)
461 pub can_emit_warnings: bool,
462 /// If true, error-level diagnostics are upgraded to bug-level.
463 /// (rustc: see `-Z treat-err-as-bug`)
464 pub treat_err_as_bug: Option<NonZeroUsize>,
465 /// If true, immediately emit diagnostics that would otherwise be buffered.
466 /// (rustc: see `-Z dont-buffer-diagnostics` and `-Z treat-err-as-bug`)
467 pub dont_buffer_diagnostics: bool,
468 /// If true, immediately print bugs registered with `delay_span_bug`.
469 /// (rustc: see `-Z report-delayed-bugs`)
470 pub report_delayed_bugs: bool,
471 /// Show macro backtraces.
472 /// (rustc: see `-Z macro-backtrace`)
473 pub macro_backtrace: bool,
474 /// If true, identical diagnostics are reported only once.
475 pub deduplicate_diagnostics: bool,
478 impl Drop for HandlerInner {
480 self.emit_stashed_diagnostics();
482 if !self.has_errors() {
483 let bugs = std::mem::replace(&mut self.delayed_span_bugs, Vec::new());
484 self.flush_delayed(bugs, "no errors encountered even though `delay_span_bug` issued");
487 // FIXME(eddyb) this explains what `delayed_good_path_bugs` are!
488 // They're `delayed_span_bugs` but for "require some diagnostic happened"
489 // instead of "require some error happened". Sadly that isn't ideal, as
490 // lints can be `#[allow]`'d, potentially leading to this triggering.
491 // Also, "good path" should be replaced with a better naming.
492 if !self.has_any_message() {
493 let bugs = std::mem::replace(&mut self.delayed_good_path_bugs, Vec::new());
495 bugs.into_iter().map(DelayedDiagnostic::decorate),
496 "no warnings or errors encountered even though `delayed_good_path_bugs` issued",
501 self.unstable_expect_diagnostics.is_empty(),
502 "all diagnostics with unstable expectations should have been converted",
508 pub fn with_tty_emitter(
509 color_config: ColorConfig,
510 can_emit_warnings: bool,
511 treat_err_as_bug: Option<NonZeroUsize>,
512 sm: Option<Lrc<SourceMap>>,
513 fluent_bundle: Option<Lrc<FluentBundle>>,
514 fallback_bundle: LazyFallbackBundle,
516 Self::with_tty_emitter_and_flags(
521 HandlerFlags { can_emit_warnings, treat_err_as_bug, ..Default::default() },
525 pub fn with_tty_emitter_and_flags(
526 color_config: ColorConfig,
527 sm: Option<Lrc<SourceMap>>,
528 fluent_bundle: Option<Lrc<FluentBundle>>,
529 fallback_bundle: LazyFallbackBundle,
532 let emitter = Box::new(EmitterWriter::stderr(
540 flags.macro_backtrace,
542 Self::with_emitter_and_flags(emitter, flags)
546 can_emit_warnings: bool,
547 treat_err_as_bug: Option<NonZeroUsize>,
548 emitter: Box<dyn Emitter + sync::Send>,
550 Handler::with_emitter_and_flags(
552 HandlerFlags { can_emit_warnings, treat_err_as_bug, ..Default::default() },
556 pub fn with_emitter_and_flags(
557 emitter: Box<dyn Emitter + sync::Send>,
562 inner: Lock::new(HandlerInner {
567 deduplicated_err_count: 0,
568 deduplicated_warn_count: 0,
570 delayed_span_bugs: Vec::new(),
571 delayed_good_path_bugs: Vec::new(),
572 taught_diagnostics: Default::default(),
573 emitted_diagnostic_codes: Default::default(),
574 emitted_diagnostics: Default::default(),
575 stashed_diagnostics: Default::default(),
576 future_breakage_diagnostics: Vec::new(),
577 unstable_expect_diagnostics: Vec::new(),
578 fulfilled_expectations: Default::default(),
583 // This is here to not allow mutation of flags;
584 // as of this writing it's only used in tests in librustc_middle.
585 pub fn can_emit_warnings(&self) -> bool {
586 self.flags.can_emit_warnings
589 /// Resets the diagnostic error count as well as the cached emitted diagnostics.
591 /// NOTE: *do not* call this function from rustc. It is only meant to be called from external
592 /// tools that want to reuse a `Parser` cleaning the previously emitted diagnostics as well as
593 /// the overall count of emitted error diagnostics.
594 pub fn reset_err_count(&self) {
595 let mut inner = self.inner.borrow_mut();
597 inner.warn_count = 0;
598 inner.deduplicated_err_count = 0;
599 inner.deduplicated_warn_count = 0;
601 // actually free the underlying memory (which `clear` would not do)
602 inner.delayed_span_bugs = Default::default();
603 inner.delayed_good_path_bugs = Default::default();
604 inner.taught_diagnostics = Default::default();
605 inner.emitted_diagnostic_codes = Default::default();
606 inner.emitted_diagnostics = Default::default();
607 inner.stashed_diagnostics = Default::default();
610 /// Stash a given diagnostic with the given `Span` and `StashKey` as the key for later stealing.
611 pub fn stash_diagnostic(&self, span: Span, key: StashKey, diag: Diagnostic) {
612 let mut inner = self.inner.borrow_mut();
613 // FIXME(Centril, #69537): Consider reintroducing panic on overwriting a stashed diagnostic
614 // if/when we have a more robust macro-friendly replacement for `(span, key)` as a key.
615 // See the PR for a discussion.
616 inner.stashed_diagnostics.insert((span, key), diag);
619 /// Steal a previously stashed diagnostic with the given `Span` and `StashKey` as the key.
620 pub fn steal_diagnostic(&self, span: Span, key: StashKey) -> Option<DiagnosticBuilder<'_, ()>> {
624 .remove(&(span, key))
625 .map(|diag| DiagnosticBuilder::new_diagnostic(self, diag))
628 /// Emit all stashed diagnostics.
629 pub fn emit_stashed_diagnostics(&self) -> Option<ErrorGuaranteed> {
630 self.inner.borrow_mut().emit_stashed_diagnostics()
633 /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
635 /// Attempting to `.emit()` the builder will only emit if either:
636 /// * `can_emit_warnings` is `true`
637 /// * `is_force_warn` was set in `DiagnosticId::Lint`
638 pub fn struct_span_warn(
640 span: impl Into<MultiSpan>,
641 msg: impl Into<DiagnosticMessage>,
642 ) -> DiagnosticBuilder<'_, ()> {
643 let mut result = self.struct_warn(msg);
644 result.set_span(span);
648 /// Construct a builder at the `Allow` level at the given `span` and with the `msg`.
649 pub fn struct_span_allow(
651 span: impl Into<MultiSpan>,
652 msg: impl Into<DiagnosticMessage>,
653 ) -> DiagnosticBuilder<'_, ()> {
654 let mut result = self.struct_allow(msg);
655 result.set_span(span);
659 /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
660 /// Also include a code.
661 pub fn struct_span_warn_with_code(
663 span: impl Into<MultiSpan>,
664 msg: impl Into<DiagnosticMessage>,
666 ) -> DiagnosticBuilder<'_, ()> {
667 let mut result = self.struct_span_warn(span, msg);
672 /// Construct a builder at the `Warning` level with the `msg`.
674 /// Attempting to `.emit()` the builder will only emit if either:
675 /// * `can_emit_warnings` is `true`
676 /// * `is_force_warn` was set in `DiagnosticId::Lint`
677 pub fn struct_warn(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> {
678 DiagnosticBuilder::new(self, Level::Warning, msg)
681 /// Construct a builder at the `Allow` level with the `msg`.
682 pub fn struct_allow(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> {
683 DiagnosticBuilder::new(self, Level::Allow, msg)
686 /// Construct a builder at the `Expect` level with the `msg`.
687 pub fn struct_expect(
689 msg: impl Into<DiagnosticMessage>,
690 id: LintExpectationId,
691 ) -> DiagnosticBuilder<'_, ()> {
692 DiagnosticBuilder::new(self, Level::Expect(id), msg)
695 /// Construct a builder at the `Error` level at the given `span` and with the `msg`.
696 pub fn struct_span_err(
698 span: impl Into<MultiSpan>,
699 msg: impl Into<DiagnosticMessage>,
700 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
701 let mut result = self.struct_err(msg);
702 result.set_span(span);
706 /// Construct a builder at the `Error` level at the given `span`, with the `msg`, and `code`.
707 pub fn struct_span_err_with_code(
709 span: impl Into<MultiSpan>,
710 msg: impl Into<DiagnosticMessage>,
712 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
713 let mut result = self.struct_span_err(span, msg);
718 /// Construct a builder at the `Error` level with the `msg`.
719 // FIXME: This method should be removed (every error should have an associated error code).
722 msg: impl Into<DiagnosticMessage>,
723 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
724 DiagnosticBuilder::new_guaranteeing_error::<_, { Level::Error { lint: false } }>(self, msg)
727 /// This should only be used by `rustc_middle::lint::struct_lint_level`. Do not use it for hard errors.
729 pub fn struct_err_lint(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> {
730 DiagnosticBuilder::new(self, Level::Error { lint: true }, msg)
733 /// Construct a builder at the `Error` level with the `msg` and the `code`.
734 pub fn struct_err_with_code(
736 msg: impl Into<DiagnosticMessage>,
738 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
739 let mut result = self.struct_err(msg);
744 /// Construct a builder at the `Warn` level with the `msg` and the `code`.
745 pub fn struct_warn_with_code(
747 msg: impl Into<DiagnosticMessage>,
749 ) -> DiagnosticBuilder<'_, ()> {
750 let mut result = self.struct_warn(msg);
755 /// Construct a builder at the `Fatal` level at the given `span` and with the `msg`.
756 pub fn struct_span_fatal(
758 span: impl Into<MultiSpan>,
759 msg: impl Into<DiagnosticMessage>,
760 ) -> DiagnosticBuilder<'_, !> {
761 let mut result = self.struct_fatal(msg);
762 result.set_span(span);
766 /// Construct a builder at the `Fatal` level at the given `span`, with the `msg`, and `code`.
767 pub fn struct_span_fatal_with_code(
769 span: impl Into<MultiSpan>,
770 msg: impl Into<DiagnosticMessage>,
772 ) -> DiagnosticBuilder<'_, !> {
773 let mut result = self.struct_span_fatal(span, msg);
778 /// Construct a builder at the `Error` level with the `msg`.
779 pub fn struct_fatal(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, !> {
780 DiagnosticBuilder::new_fatal(self, msg)
783 /// Construct a builder at the `Help` level with the `msg`.
784 pub fn struct_help(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> {
785 DiagnosticBuilder::new(self, Level::Help, msg)
788 /// Construct a builder at the `Note` level with the `msg`.
789 pub fn struct_note_without_error(
791 msg: impl Into<DiagnosticMessage>,
792 ) -> DiagnosticBuilder<'_, ()> {
793 DiagnosticBuilder::new(self, Level::Note, msg)
796 pub fn span_fatal(&self, span: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>) -> ! {
797 self.emit_diag_at_span(Diagnostic::new(Fatal, msg), span);
801 pub fn span_fatal_with_code(
803 span: impl Into<MultiSpan>,
804 msg: impl Into<DiagnosticMessage>,
807 self.emit_diag_at_span(Diagnostic::new_with_code(Fatal, Some(code), msg), span);
813 span: impl Into<MultiSpan>,
814 msg: impl Into<DiagnosticMessage>,
815 ) -> ErrorGuaranteed {
816 self.emit_diag_at_span(Diagnostic::new(Error { lint: false }, msg), span).unwrap()
819 pub fn span_err_with_code(
821 span: impl Into<MultiSpan>,
822 msg: impl Into<DiagnosticMessage>,
825 self.emit_diag_at_span(
826 Diagnostic::new_with_code(Error { lint: false }, Some(code), msg),
831 pub fn span_warn(&self, span: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>) {
832 self.emit_diag_at_span(Diagnostic::new(Warning, msg), span);
835 pub fn span_warn_with_code(
837 span: impl Into<MultiSpan>,
838 msg: impl Into<DiagnosticMessage>,
841 self.emit_diag_at_span(Diagnostic::new_with_code(Warning, Some(code), msg), span);
844 pub fn span_bug(&self, span: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>) -> ! {
845 self.inner.borrow_mut().span_bug(span, msg)
849 pub fn delay_span_bug(
851 span: impl Into<MultiSpan>,
852 msg: impl Into<DiagnosticMessage>,
853 ) -> ErrorGuaranteed {
854 self.inner.borrow_mut().delay_span_bug(span, msg)
857 // FIXME(eddyb) note the comment inside `impl Drop for HandlerInner`, that's
858 // where the explanation of what "good path" is (also, it should be renamed).
859 pub fn delay_good_path_bug(&self, msg: impl Into<DiagnosticMessage>) {
860 self.inner.borrow_mut().delay_good_path_bug(msg)
863 pub fn span_bug_no_panic(&self, span: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>) {
864 self.emit_diag_at_span(Diagnostic::new(Bug, msg), span);
867 pub fn span_note_without_error(
869 span: impl Into<MultiSpan>,
870 msg: impl Into<DiagnosticMessage>,
872 self.emit_diag_at_span(Diagnostic::new(Note, msg), span);
875 pub fn span_note_diag(
878 msg: impl Into<DiagnosticMessage>,
879 ) -> DiagnosticBuilder<'_, ()> {
880 let mut db = DiagnosticBuilder::new(self, Note, msg);
885 // NOTE: intentionally doesn't raise an error so rustc_codegen_ssa only reports fatal errors in the main thread
886 pub fn fatal(&self, msg: impl Into<DiagnosticMessage>) -> FatalError {
887 self.inner.borrow_mut().fatal(msg)
890 pub fn err(&self, msg: impl Into<DiagnosticMessage>) -> ErrorGuaranteed {
891 self.inner.borrow_mut().err(msg)
894 pub fn warn(&self, msg: impl Into<DiagnosticMessage>) {
895 let mut db = DiagnosticBuilder::new(self, Warning, msg);
899 pub fn note_without_error(&self, msg: impl Into<DiagnosticMessage>) {
900 DiagnosticBuilder::new(self, Note, msg).emit();
903 pub fn bug(&self, msg: impl Into<DiagnosticMessage>) -> ! {
904 self.inner.borrow_mut().bug(msg)
908 pub fn err_count(&self) -> usize {
909 self.inner.borrow().err_count()
912 pub fn has_errors(&self) -> Option<ErrorGuaranteed> {
913 if self.inner.borrow().has_errors() { Some(ErrorGuaranteed(())) } else { None }
915 pub fn has_errors_or_lint_errors(&self) -> Option<ErrorGuaranteed> {
916 if self.inner.borrow().has_errors_or_lint_errors() {
917 Some(ErrorGuaranteed(()))
922 pub fn has_errors_or_delayed_span_bugs(&self) -> bool {
923 self.inner.borrow().has_errors_or_delayed_span_bugs()
926 pub fn print_error_count(&self, registry: &Registry) {
927 self.inner.borrow_mut().print_error_count(registry)
930 pub fn take_future_breakage_diagnostics(&self) -> Vec<Diagnostic> {
931 std::mem::take(&mut self.inner.borrow_mut().future_breakage_diagnostics)
934 pub fn abort_if_errors(&self) {
935 self.inner.borrow_mut().abort_if_errors()
938 /// `true` if we haven't taught a diagnostic with this code already.
939 /// The caller must then teach the user about such a diagnostic.
941 /// Used to suppress emitting the same error multiple times with extended explanation when
942 /// calling `-Zteach`.
943 pub fn must_teach(&self, code: &DiagnosticId) -> bool {
944 self.inner.borrow_mut().must_teach(code)
947 pub fn force_print_diagnostic(&self, db: Diagnostic) {
948 self.inner.borrow_mut().force_print_diagnostic(db)
951 pub fn emit_diagnostic(&self, diagnostic: &mut Diagnostic) -> Option<ErrorGuaranteed> {
952 self.inner.borrow_mut().emit_diagnostic(diagnostic)
955 fn emit_diag_at_span(
957 mut diag: Diagnostic,
958 sp: impl Into<MultiSpan>,
959 ) -> Option<ErrorGuaranteed> {
960 let mut inner = self.inner.borrow_mut();
961 inner.emit_diagnostic(diag.set_span(sp))
964 pub fn emit_artifact_notification(&self, path: &Path, artifact_type: &str) {
965 self.inner.borrow_mut().emit_artifact_notification(path, artifact_type)
968 pub fn emit_future_breakage_report(&self, diags: Vec<Diagnostic>) {
969 self.inner.borrow_mut().emitter.emit_future_breakage_report(diags)
972 pub fn emit_unused_externs(
974 lint_level: rustc_lint_defs::Level,
976 unused_externs: &[&str],
978 let mut inner = self.inner.borrow_mut();
980 if loud && lint_level.is_error() {
981 inner.bump_err_count();
984 inner.emit_unused_externs(lint_level, unused_externs)
987 pub fn update_unstable_expectation_id(
989 unstable_to_stable: &FxHashMap<LintExpectationId, LintExpectationId>,
991 let diags = std::mem::take(&mut self.inner.borrow_mut().unstable_expect_diagnostics);
992 if diags.is_empty() {
996 let mut inner = self.inner.borrow_mut();
997 for mut diag in diags.into_iter() {
998 diag.update_unstable_expectation_id(unstable_to_stable);
1000 let stable_id = diag
1002 .get_expectation_id()
1003 .expect("all diagnostics inside `unstable_expect_diagnostics` must have a `LintExpectationId`");
1004 inner.fulfilled_expectations.insert(stable_id);
1006 (*TRACK_DIAGNOSTICS)(&diag);
1010 .stashed_diagnostics
1012 .for_each(|diag| diag.update_unstable_expectation_id(unstable_to_stable));
1014 .future_breakage_diagnostics
1016 .for_each(|diag| diag.update_unstable_expectation_id(unstable_to_stable));
1019 /// This methods steals all [`LintExpectationId`]s that are stored inside
1020 /// [`HandlerInner`] and indicate that the linked expectation has been fulfilled.
1022 pub fn steal_fulfilled_expectation_ids(&self) -> FxHashSet<LintExpectationId> {
1024 self.inner.borrow().unstable_expect_diagnostics.is_empty(),
1025 "`HandlerInner::unstable_expect_diagnostics` should be empty at this point",
1027 std::mem::take(&mut self.inner.borrow_mut().fulfilled_expectations)
1032 fn must_teach(&mut self, code: &DiagnosticId) -> bool {
1033 self.taught_diagnostics.insert(code.clone())
1036 fn force_print_diagnostic(&mut self, mut db: Diagnostic) {
1037 self.emitter.emit_diagnostic(&mut db);
1040 /// Emit all stashed diagnostics.
1041 fn emit_stashed_diagnostics(&mut self) -> Option<ErrorGuaranteed> {
1042 let diags = self.stashed_diagnostics.drain(..).map(|x| x.1).collect::<Vec<_>>();
1043 let mut reported = None;
1044 for mut diag in diags {
1045 if diag.is_error() {
1046 reported = Some(ErrorGuaranteed(()));
1048 self.emit_diagnostic(&mut diag);
1053 // FIXME(eddyb) this should ideally take `diagnostic` by value.
1054 fn emit_diagnostic(&mut self, diagnostic: &mut Diagnostic) -> Option<ErrorGuaranteed> {
1055 if diagnostic.level == Level::DelayedBug {
1056 // FIXME(eddyb) this should check for `has_errors` and stop pushing
1057 // once *any* errors were emitted (and truncate `delayed_span_bugs`
1058 // when an error is first emitted, also), but maybe there's a case
1059 // in which that's not sound? otherwise this is really inefficient.
1060 self.delayed_span_bugs.push(diagnostic.clone());
1062 if !self.flags.report_delayed_bugs {
1063 return Some(ErrorGuaranteed::unchecked_claim_error_was_emitted());
1067 if diagnostic.has_future_breakage() {
1068 self.future_breakage_diagnostics.push(diagnostic.clone());
1071 if diagnostic.level == Warning
1072 && !self.flags.can_emit_warnings
1073 && !diagnostic.is_force_warn()
1075 if diagnostic.has_future_breakage() {
1076 (*TRACK_DIAGNOSTICS)(diagnostic);
1081 // The `LintExpectationId` can be stable or unstable depending on when it was created.
1082 // Diagnostics created before the definition of `HirId`s are unstable and can not yet
1083 // be stored. Instead, they are buffered until the `LintExpectationId` is replaced by
1084 // a stable one by the `LintLevelsBuilder`.
1085 if let Level::Expect(LintExpectationId::Unstable { .. }) = diagnostic.level {
1086 self.unstable_expect_diagnostics.push(diagnostic.clone());
1090 (*TRACK_DIAGNOSTICS)(diagnostic);
1092 if let Level::Expect(expectation_id) = diagnostic.level {
1093 self.fulfilled_expectations.insert(expectation_id);
1095 } else if diagnostic.level == Allow {
1099 if let Some(ref code) = diagnostic.code {
1100 self.emitted_diagnostic_codes.insert(code.clone());
1103 let already_emitted = |this: &mut Self| {
1104 let mut hasher = StableHasher::new();
1105 diagnostic.hash(&mut hasher);
1106 let diagnostic_hash = hasher.finish();
1107 !this.emitted_diagnostics.insert(diagnostic_hash)
1110 // Only emit the diagnostic if we've been asked to deduplicate and
1111 // haven't already emitted an equivalent diagnostic.
1112 if !(self.flags.deduplicate_diagnostics && already_emitted(self)) {
1113 debug!(?diagnostic);
1114 debug!(?self.emitted_diagnostics);
1115 let already_emitted_sub = |sub: &mut SubDiagnostic| {
1117 if sub.level != Level::OnceNote {
1120 let mut hasher = StableHasher::new();
1121 sub.hash(&mut hasher);
1122 let diagnostic_hash = hasher.finish();
1123 debug!(?diagnostic_hash);
1124 !self.emitted_diagnostics.insert(diagnostic_hash)
1127 diagnostic.children.drain_filter(already_emitted_sub).for_each(|_| {});
1129 self.emitter.emit_diagnostic(&diagnostic);
1130 if diagnostic.is_error() {
1131 self.deduplicated_err_count += 1;
1132 } else if diagnostic.level == Warning {
1133 self.deduplicated_warn_count += 1;
1136 if diagnostic.is_error() {
1137 if matches!(diagnostic.level, Level::Error { lint: true }) {
1138 self.bump_lint_err_count();
1140 self.bump_err_count();
1143 Some(ErrorGuaranteed::unchecked_claim_error_was_emitted())
1145 self.bump_warn_count();
1151 fn emit_artifact_notification(&mut self, path: &Path, artifact_type: &str) {
1152 self.emitter.emit_artifact_notification(path, artifact_type);
1155 fn emit_unused_externs(&mut self, lint_level: rustc_lint_defs::Level, unused_externs: &[&str]) {
1156 self.emitter.emit_unused_externs(lint_level, unused_externs);
1159 fn treat_err_as_bug(&self) -> bool {
1162 .map_or(false, |c| self.err_count() + self.lint_err_count >= c.get())
1165 fn print_error_count(&mut self, registry: &Registry) {
1166 self.emit_stashed_diagnostics();
1168 let warnings = match self.deduplicated_warn_count {
1170 1 => "1 warning emitted".to_string(),
1171 count => format!("{count} warnings emitted"),
1173 let errors = match self.deduplicated_err_count {
1175 1 => "aborting due to previous error".to_string(),
1176 count => format!("aborting due to {count} previous errors"),
1178 if self.treat_err_as_bug() {
1182 match (errors.len(), warnings.len()) {
1184 (0, _) => self.emitter.emit_diagnostic(&Diagnostic::new(
1186 DiagnosticMessage::Str(warnings),
1189 let _ = self.fatal(&errors);
1192 let _ = self.fatal(&format!("{}; {}", &errors, &warnings));
1196 let can_show_explain = self.emitter.should_show_explain();
1197 let are_there_diagnostics = !self.emitted_diagnostic_codes.is_empty();
1198 if can_show_explain && are_there_diagnostics {
1199 let mut error_codes = self
1200 .emitted_diagnostic_codes
1202 .filter_map(|x| match &x {
1203 DiagnosticId::Error(s)
1204 if registry.try_find_description(s).map_or(false, |o| o.is_some()) =>
1210 .collect::<Vec<_>>();
1211 if !error_codes.is_empty() {
1213 if error_codes.len() > 1 {
1214 let limit = if error_codes.len() > 9 { 9 } else { error_codes.len() };
1215 self.failure(&format!(
1216 "Some errors have detailed explanations: {}{}",
1217 error_codes[..limit].join(", "),
1218 if error_codes.len() > 9 { "..." } else { "." }
1220 self.failure(&format!(
1221 "For more information about an error, try \
1222 `rustc --explain {}`.",
1226 self.failure(&format!(
1227 "For more information about this error, try \
1228 `rustc --explain {}`.",
1237 fn err_count(&self) -> usize {
1238 self.err_count + self.stashed_diagnostics.len()
1241 fn has_errors(&self) -> bool {
1242 self.err_count() > 0
1244 fn has_errors_or_lint_errors(&self) -> bool {
1245 self.has_errors() || self.lint_err_count > 0
1247 fn has_errors_or_delayed_span_bugs(&self) -> bool {
1248 self.has_errors() || !self.delayed_span_bugs.is_empty()
1250 fn has_any_message(&self) -> bool {
1251 self.err_count() > 0 || self.lint_err_count > 0 || self.warn_count > 0
1254 fn abort_if_errors(&mut self) {
1255 self.emit_stashed_diagnostics();
1257 if self.has_errors() {
1262 fn span_bug(&mut self, sp: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>) -> ! {
1263 self.emit_diag_at_span(Diagnostic::new(Bug, msg), sp);
1264 panic::panic_any(ExplicitBug);
1267 fn emit_diag_at_span(&mut self, mut diag: Diagnostic, sp: impl Into<MultiSpan>) {
1268 self.emit_diagnostic(diag.set_span(sp));
1274 sp: impl Into<MultiSpan>,
1275 msg: impl Into<DiagnosticMessage>,
1276 ) -> ErrorGuaranteed {
1277 // This is technically `self.treat_err_as_bug()` but `delay_span_bug` is called before
1278 // incrementing `err_count` by one, so we need to +1 the comparing.
1279 // FIXME: Would be nice to increment err_count in a more coherent way.
1280 if self.flags.treat_err_as_bug.map_or(false, |c| self.err_count() + 1 >= c.get()) {
1281 // FIXME: don't abort here if report_delayed_bugs is off
1282 self.span_bug(sp, msg);
1284 let mut diagnostic = Diagnostic::new(Level::DelayedBug, msg);
1285 diagnostic.set_span(sp.into());
1286 diagnostic.note(&format!("delayed at {}", std::panic::Location::caller()));
1287 self.emit_diagnostic(&mut diagnostic).unwrap()
1290 // FIXME(eddyb) note the comment inside `impl Drop for HandlerInner`, that's
1291 // where the explanation of what "good path" is (also, it should be renamed).
1292 fn delay_good_path_bug(&mut self, msg: impl Into<DiagnosticMessage>) {
1293 let mut diagnostic = Diagnostic::new(Level::DelayedBug, msg);
1294 if self.flags.report_delayed_bugs {
1295 self.emit_diagnostic(&mut diagnostic);
1297 let backtrace = std::backtrace::Backtrace::force_capture();
1298 self.delayed_good_path_bugs.push(DelayedDiagnostic::with_backtrace(diagnostic, backtrace));
1301 fn failure(&mut self, msg: impl Into<DiagnosticMessage>) {
1302 self.emit_diagnostic(&mut Diagnostic::new(FailureNote, msg));
1305 fn fatal(&mut self, msg: impl Into<DiagnosticMessage>) -> FatalError {
1306 self.emit(Fatal, msg);
1310 fn err(&mut self, msg: impl Into<DiagnosticMessage>) -> ErrorGuaranteed {
1311 self.emit(Error { lint: false }, msg)
1314 /// Emit an error; level should be `Error` or `Fatal`.
1315 fn emit(&mut self, level: Level, msg: impl Into<DiagnosticMessage>) -> ErrorGuaranteed {
1316 if self.treat_err_as_bug() {
1319 self.emit_diagnostic(&mut Diagnostic::new(level, msg)).unwrap()
1322 fn bug(&mut self, msg: impl Into<DiagnosticMessage>) -> ! {
1323 self.emit_diagnostic(&mut Diagnostic::new(Bug, msg));
1324 panic::panic_any(ExplicitBug);
1329 bugs: impl IntoIterator<Item = Diagnostic>,
1330 explanation: impl Into<DiagnosticMessage> + Copy,
1332 let mut no_bugs = true;
1333 for mut bug in bugs {
1335 // Put the overall explanation before the `DelayedBug`s, to
1336 // frame them better (e.g. separate warnings from them).
1337 self.emit_diagnostic(&mut Diagnostic::new(Bug, explanation));
1341 // "Undelay" the `DelayedBug`s (into plain `Bug`s).
1342 if bug.level != Level::DelayedBug {
1343 // NOTE(eddyb) not panicking here because we're already producing
1344 // an ICE, and the more information the merrier.
1346 "`flushed_delayed` got diagnostic with level {:?}, \
1347 instead of the expected `DelayedBug`",
1351 bug.level = Level::Bug;
1353 self.emit_diagnostic(&mut bug);
1356 // Panic with `ExplicitBug` to avoid "unexpected panic" messages.
1358 panic::panic_any(ExplicitBug);
1362 fn bump_lint_err_count(&mut self) {
1363 self.lint_err_count += 1;
1364 self.panic_if_treat_err_as_bug();
1367 fn bump_err_count(&mut self) {
1368 self.err_count += 1;
1369 self.panic_if_treat_err_as_bug();
1372 fn bump_warn_count(&mut self) {
1373 self.warn_count += 1;
1376 fn panic_if_treat_err_as_bug(&self) {
1377 if self.treat_err_as_bug() {
1379 self.err_count() + self.lint_err_count,
1380 self.flags.treat_err_as_bug.map(|c| c.get()).unwrap_or(0),
1382 (1, 1) => panic!("aborting due to `-Z treat-err-as-bug=1`"),
1383 (0, _) | (1, _) => {}
1384 (count, as_bug) => panic!(
1385 "aborting after {} errors due to `-Z treat-err-as-bug={}`",
1393 struct DelayedDiagnostic {
1398 impl DelayedDiagnostic {
1399 fn with_backtrace(diagnostic: Diagnostic, backtrace: Backtrace) -> Self {
1400 DelayedDiagnostic { inner: diagnostic, note: backtrace }
1403 fn decorate(mut self) -> Diagnostic {
1404 self.inner.note(&format!("delayed at {}", self.note));
1409 #[derive(Copy, PartialEq, Eq, Clone, Hash, Debug, Encodable, Decodable)]
1415 /// If this error comes from a lint, don't abort compilation even when abort_if_errors() is called.
1420 /// A note that is only emitted once.
1425 Expect(LintExpectationId),
1428 impl fmt::Display for Level {
1429 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1430 self.to_str().fmt(f)
1435 fn color(self) -> ColorSpec {
1436 let mut spec = ColorSpec::new();
1438 Bug | DelayedBug | Fatal | Error { .. } => {
1439 spec.set_fg(Some(Color::Red)).set_intense(true);
1442 spec.set_fg(Some(Color::Yellow)).set_intense(cfg!(windows));
1444 Note | OnceNote => {
1445 spec.set_fg(Some(Color::Green)).set_intense(true);
1448 spec.set_fg(Some(Color::Cyan)).set_intense(true);
1451 Allow | Expect(_) => unreachable!(),
1456 pub fn to_str(self) -> &'static str {
1458 Bug | DelayedBug => "error: internal compiler error",
1459 Fatal | Error { .. } => "error",
1460 Warning => "warning",
1461 Note | OnceNote => "note",
1463 FailureNote => "failure-note",
1464 Allow => panic!("Shouldn't call on allowed error"),
1465 Expect(_) => panic!("Shouldn't call on expected error"),
1469 pub fn is_failure_note(&self) -> bool {
1470 matches!(*self, FailureNote)
1473 pub fn get_expectation_id(&self) -> Option<LintExpectationId> {
1475 Level::Expect(id) => Some(*id),
1481 // FIXME(eddyb) this doesn't belong here AFAICT, should be moved to callsite.
1482 pub fn add_elided_lifetime_in_path_suggestion(
1483 source_map: &SourceMap,
1484 diag: &mut Diagnostic,
1487 incl_angl_brckt: bool,
1488 insertion_span: Span,
1490 diag.span_label(path_span, format!("expected lifetime parameter{}", pluralize!(n)));
1491 if source_map.span_to_snippet(insertion_span).is_err() {
1492 // Do not try to suggest anything if generated by a proc-macro.
1495 let anon_lts = vec!["'_"; n].join(", ");
1497 if incl_angl_brckt { format!("<{}>", anon_lts) } else { format!("{}, ", anon_lts) };
1498 diag.span_suggestion_verbose(
1499 insertion_span.shrink_to_hi(),
1500 &format!("indicate the anonymous lifetime{}", pluralize!(n)),
1502 Applicability::MachineApplicable,
1506 /// Useful type to use with `Result<>` indicate that an error has already
1507 /// been reported to the user, so no need to continue checking.
1508 #[derive(Clone, Copy, Debug, Encodable, Decodable, Hash, PartialEq, Eq, PartialOrd, Ord)]
1509 #[derive(HashStable_Generic)]
1510 pub struct ErrorGuaranteed(());
1512 impl ErrorGuaranteed {
1513 /// To be used only if you really know what you are doing... ideally, we would find a way to
1514 /// eliminate all calls to this method.
1515 pub fn unchecked_claim_error_was_emitted() -> Self {