]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_errors/src/lib.rs
Rollup merge of #107491 - notriddle:notriddle/setting-check, r=GuillaumeGomez
[rust.git] / compiler / rustc_errors / src / lib.rs
1 //! Diagnostics creation and emission for `rustc`.
2 //!
3 //! This module contains the code for creating and emitting diagnostics.
4
5 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
6 #![feature(array_windows)]
7 #![feature(drain_filter)]
8 #![feature(if_let_guard)]
9 #![feature(is_terminal)]
10 #![feature(adt_const_params)]
11 #![feature(let_chains)]
12 #![feature(never_type)]
13 #![feature(result_option_inspect)]
14 #![feature(rustc_attrs)]
15 #![feature(yeet_expr)]
16 #![feature(try_blocks)]
17 #![feature(box_patterns)]
18 #![feature(error_reporter)]
19 #![allow(incomplete_features)]
20
21 #[macro_use]
22 extern crate rustc_macros;
23
24 #[macro_use]
25 extern crate tracing;
26
27 pub use emitter::ColorConfig;
28
29 use rustc_lint_defs::LintExpectationId;
30 use Level::*;
31
32 use emitter::{is_case_difference, Emitter, EmitterWriter};
33 use registry::Registry;
34 use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet};
35 use rustc_data_structures::stable_hasher::StableHasher;
36 use rustc_data_structures::sync::{self, Lock, Lrc};
37 use rustc_data_structures::AtomicRef;
38 pub use rustc_error_messages::{
39     fallback_fluent_bundle, fluent, fluent_bundle, DelayDm, DiagnosticMessage, FluentBundle,
40     LanguageIdentifier, LazyFallbackBundle, MultiSpan, SpanLabel, SubdiagnosticMessage,
41     DEFAULT_LOCALE_RESOURCES,
42 };
43 pub use rustc_lint_defs::{pluralize, Applicability};
44 use rustc_span::source_map::SourceMap;
45 use rustc_span::HashStableContext;
46 use rustc_span::{Loc, Span};
47
48 use std::borrow::Cow;
49 use std::error::Report;
50 use std::fmt;
51 use std::hash::Hash;
52 use std::num::NonZeroUsize;
53 use std::panic;
54 use std::path::Path;
55
56 use termcolor::{Color, ColorSpec};
57
58 pub mod annotate_snippet_emitter_writer;
59 mod diagnostic;
60 mod diagnostic_builder;
61 mod diagnostic_impls;
62 pub mod emitter;
63 pub mod error;
64 pub mod json;
65 mod lock;
66 pub mod registry;
67 mod snippet;
68 mod styled_buffer;
69 #[cfg(test)]
70 mod tests;
71 pub mod translation;
72
73 pub use diagnostic_builder::IntoDiagnostic;
74 pub use snippet::Style;
75
76 pub type PErr<'a> = DiagnosticBuilder<'a, ErrorGuaranteed>;
77 pub type PResult<'a, T> = Result<T, PErr<'a>>;
78
79 // `PResult` is used a lot. Make sure it doesn't unintentionally get bigger.
80 // (See also the comment on `DiagnosticBuilderInner`'s `diagnostic` field.)
81 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
82 rustc_data_structures::static_assert_size!(PResult<'_, ()>, 16);
83 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
84 rustc_data_structures::static_assert_size!(PResult<'_, bool>, 16);
85
86 #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, Encodable, Decodable)]
87 pub enum SuggestionStyle {
88     /// Hide the suggested code when displaying this suggestion inline.
89     HideCodeInline,
90     /// Always hide the suggested code but display the message.
91     HideCodeAlways,
92     /// Do not display this suggestion in the cli output, it is only meant for tools.
93     CompletelyHidden,
94     /// Always show the suggested code.
95     /// This will *not* show the code if the suggestion is inline *and* the suggested code is
96     /// empty.
97     ShowCode,
98     /// Always show the suggested code independently.
99     ShowAlways,
100 }
101
102 impl SuggestionStyle {
103     fn hide_inline(&self) -> bool {
104         !matches!(*self, SuggestionStyle::ShowCode)
105     }
106 }
107
108 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
109 pub struct CodeSuggestion {
110     /// Each substitute can have multiple variants due to multiple
111     /// applicable suggestions
112     ///
113     /// `foo.bar` might be replaced with `a.b` or `x.y` by replacing
114     /// `foo` and `bar` on their own:
115     ///
116     /// ```ignore (illustrative)
117     /// vec![
118     ///     Substitution { parts: vec![(0..3, "a"), (4..7, "b")] },
119     ///     Substitution { parts: vec![(0..3, "x"), (4..7, "y")] },
120     /// ]
121     /// ```
122     ///
123     /// or by replacing the entire span:
124     ///
125     /// ```ignore (illustrative)
126     /// vec![
127     ///     Substitution { parts: vec![(0..7, "a.b")] },
128     ///     Substitution { parts: vec![(0..7, "x.y")] },
129     /// ]
130     /// ```
131     pub substitutions: Vec<Substitution>,
132     pub msg: DiagnosticMessage,
133     /// Visual representation of this suggestion.
134     pub style: SuggestionStyle,
135     /// Whether or not the suggestion is approximate
136     ///
137     /// Sometimes we may show suggestions with placeholders,
138     /// which are useful for users but not useful for
139     /// tools like rustfix
140     pub applicability: Applicability,
141 }
142
143 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
144 /// See the docs on `CodeSuggestion::substitutions`
145 pub struct Substitution {
146     pub parts: Vec<SubstitutionPart>,
147 }
148
149 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
150 pub struct SubstitutionPart {
151     pub span: Span,
152     pub snippet: String,
153 }
154
155 /// Used to translate between `Span`s and byte positions within a single output line in highlighted
156 /// code of structured suggestions.
157 #[derive(Debug, Clone, Copy)]
158 pub struct SubstitutionHighlight {
159     start: usize,
160     end: usize,
161 }
162
163 impl SubstitutionPart {
164     pub fn is_addition(&self, sm: &SourceMap) -> bool {
165         !self.snippet.is_empty() && !self.replaces_meaningful_content(sm)
166     }
167
168     pub fn is_deletion(&self, sm: &SourceMap) -> bool {
169         self.snippet.trim().is_empty() && self.replaces_meaningful_content(sm)
170     }
171
172     pub fn is_replacement(&self, sm: &SourceMap) -> bool {
173         !self.snippet.is_empty() && self.replaces_meaningful_content(sm)
174     }
175
176     fn replaces_meaningful_content(&self, sm: &SourceMap) -> bool {
177         sm.span_to_snippet(self.span)
178             .map_or(!self.span.is_empty(), |snippet| !snippet.trim().is_empty())
179     }
180 }
181
182 impl CodeSuggestion {
183     /// Returns the assembled code suggestions, whether they should be shown with an underline
184     /// and whether the substitution only differs in capitalization.
185     pub fn splice_lines(
186         &self,
187         sm: &SourceMap,
188     ) -> Vec<(String, Vec<SubstitutionPart>, Vec<Vec<SubstitutionHighlight>>, bool)> {
189         // For the `Vec<Vec<SubstitutionHighlight>>` value, the first level of the vector
190         // corresponds to the output snippet's lines, while the second level corresponds to the
191         // substrings within that line that should be highlighted.
192
193         use rustc_span::{CharPos, Pos};
194
195         /// Append to a buffer the remainder of the line of existing source code, and return the
196         /// count of lines that have been added for accurate highlighting.
197         fn push_trailing(
198             buf: &mut String,
199             line_opt: Option<&Cow<'_, str>>,
200             lo: &Loc,
201             hi_opt: Option<&Loc>,
202         ) -> usize {
203             let mut line_count = 0;
204             let (lo, hi_opt) = (lo.col.to_usize(), hi_opt.map(|hi| hi.col.to_usize()));
205             if let Some(line) = line_opt {
206                 if let Some(lo) = line.char_indices().map(|(i, _)| i).nth(lo) {
207                     let hi_opt = hi_opt.and_then(|hi| line.char_indices().map(|(i, _)| i).nth(hi));
208                     match hi_opt {
209                         Some(hi) if hi > lo => {
210                             line_count = line[lo..hi].matches('\n').count();
211                             buf.push_str(&line[lo..hi])
212                         }
213                         Some(_) => (),
214                         None => {
215                             line_count = line[lo..].matches('\n').count();
216                             buf.push_str(&line[lo..])
217                         }
218                     }
219                 }
220                 if hi_opt.is_none() {
221                     buf.push('\n');
222                 }
223             }
224             line_count
225         }
226
227         assert!(!self.substitutions.is_empty());
228
229         self.substitutions
230             .iter()
231             .filter(|subst| {
232                 // Suggestions coming from macros can have malformed spans. This is a heavy
233                 // handed approach to avoid ICEs by ignoring the suggestion outright.
234                 let invalid = subst.parts.iter().any(|item| sm.is_valid_span(item.span).is_err());
235                 if invalid {
236                     debug!("splice_lines: suggestion contains an invalid span: {:?}", subst);
237                 }
238                 !invalid
239             })
240             .cloned()
241             .filter_map(|mut substitution| {
242                 // Assumption: all spans are in the same file, and all spans
243                 // are disjoint. Sort in ascending order.
244                 substitution.parts.sort_by_key(|part| part.span.lo());
245
246                 // Find the bounding span.
247                 let lo = substitution.parts.iter().map(|part| part.span.lo()).min()?;
248                 let hi = substitution.parts.iter().map(|part| part.span.hi()).max()?;
249                 let bounding_span = Span::with_root_ctxt(lo, hi);
250                 // The different spans might belong to different contexts, if so ignore suggestion.
251                 let lines = sm.span_to_lines(bounding_span).ok()?;
252                 assert!(!lines.lines.is_empty() || bounding_span.is_dummy());
253
254                 // We can't splice anything if the source is unavailable.
255                 if !sm.ensure_source_file_source_present(lines.file.clone()) {
256                     return None;
257                 }
258
259                 let mut highlights = vec![];
260                 // To build up the result, we do this for each span:
261                 // - push the line segment trailing the previous span
262                 //   (at the beginning a "phantom" span pointing at the start of the line)
263                 // - push lines between the previous and current span (if any)
264                 // - if the previous and current span are not on the same line
265                 //   push the line segment leading up to the current span
266                 // - splice in the span substitution
267                 //
268                 // Finally push the trailing line segment of the last span
269                 let sf = &lines.file;
270                 let mut prev_hi = sm.lookup_char_pos(bounding_span.lo());
271                 prev_hi.col = CharPos::from_usize(0);
272                 let mut prev_line =
273                     lines.lines.get(0).and_then(|line0| sf.get_line(line0.line_index));
274                 let mut buf = String::new();
275
276                 let mut line_highlight = vec![];
277                 // We need to keep track of the difference between the existing code and the added
278                 // or deleted code in order to point at the correct column *after* substitution.
279                 let mut acc = 0;
280                 for part in &substitution.parts {
281                     let cur_lo = sm.lookup_char_pos(part.span.lo());
282                     if prev_hi.line == cur_lo.line {
283                         let mut count =
284                             push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, Some(&cur_lo));
285                         while count > 0 {
286                             highlights.push(std::mem::take(&mut line_highlight));
287                             acc = 0;
288                             count -= 1;
289                         }
290                     } else {
291                         acc = 0;
292                         highlights.push(std::mem::take(&mut line_highlight));
293                         let mut count = push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
294                         while count > 0 {
295                             highlights.push(std::mem::take(&mut line_highlight));
296                             count -= 1;
297                         }
298                         // push lines between the previous and current span (if any)
299                         for idx in prev_hi.line..(cur_lo.line - 1) {
300                             if let Some(line) = sf.get_line(idx) {
301                                 buf.push_str(line.as_ref());
302                                 buf.push('\n');
303                                 highlights.push(std::mem::take(&mut line_highlight));
304                             }
305                         }
306                         if let Some(cur_line) = sf.get_line(cur_lo.line - 1) {
307                             let end = match cur_line.char_indices().nth(cur_lo.col.to_usize()) {
308                                 Some((i, _)) => i,
309                                 None => cur_line.len(),
310                             };
311                             buf.push_str(&cur_line[..end]);
312                         }
313                     }
314                     // Add a whole line highlight per line in the snippet.
315                     let len: isize = part
316                         .snippet
317                         .split('\n')
318                         .next()
319                         .unwrap_or(&part.snippet)
320                         .chars()
321                         .map(|c| match c {
322                             '\t' => 4,
323                             _ => 1,
324                         })
325                         .sum();
326                     line_highlight.push(SubstitutionHighlight {
327                         start: (cur_lo.col.0 as isize + acc) as usize,
328                         end: (cur_lo.col.0 as isize + acc + len) as usize,
329                     });
330                     buf.push_str(&part.snippet);
331                     let cur_hi = sm.lookup_char_pos(part.span.hi());
332                     if prev_hi.line == cur_lo.line && cur_hi.line == cur_lo.line {
333                         // Account for the difference between the width of the current code and the
334                         // snippet being suggested, so that the *later* suggestions are correctly
335                         // aligned on the screen.
336                         acc += len - (cur_hi.col.0 - cur_lo.col.0) as isize;
337                     }
338                     prev_hi = cur_hi;
339                     prev_line = sf.get_line(prev_hi.line - 1);
340                     for line in part.snippet.split('\n').skip(1) {
341                         acc = 0;
342                         highlights.push(std::mem::take(&mut line_highlight));
343                         let end: usize = line
344                             .chars()
345                             .map(|c| match c {
346                                 '\t' => 4,
347                                 _ => 1,
348                             })
349                             .sum();
350                         line_highlight.push(SubstitutionHighlight { start: 0, end });
351                     }
352                 }
353                 highlights.push(std::mem::take(&mut line_highlight));
354                 let only_capitalization = is_case_difference(sm, &buf, bounding_span);
355                 // if the replacement already ends with a newline, don't print the next line
356                 if !buf.ends_with('\n') {
357                     push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
358                 }
359                 // remove trailing newlines
360                 while buf.ends_with('\n') {
361                     buf.pop();
362                 }
363                 Some((buf, substitution.parts, highlights, only_capitalization))
364             })
365             .collect()
366     }
367 }
368
369 pub use rustc_span::fatal_error::{FatalError, FatalErrorMarker};
370
371 /// Signifies that the compiler died with an explicit call to `.bug`
372 /// or `.span_bug` rather than a failed assertion, etc.
373 pub struct ExplicitBug;
374
375 /// Signifies that the compiler died with an explicit call to `.delay_*_bug`
376 /// rather than a failed assertion, etc.
377 pub struct DelayedBugPanic;
378
379 pub use diagnostic::{
380     AddToDiagnostic, DecorateLint, Diagnostic, DiagnosticArg, DiagnosticArgValue, DiagnosticId,
381     DiagnosticStyledString, IntoDiagnosticArg, SubDiagnostic,
382 };
383 pub use diagnostic_builder::{DiagnosticBuilder, EmissionGuarantee, Noted};
384 pub use diagnostic_impls::{DiagnosticArgFromDisplay, DiagnosticSymbolList};
385 use std::backtrace::Backtrace;
386
387 /// A handler deals with errors and other compiler output.
388 /// Certain errors (fatal, bug, unimpl) may cause immediate exit,
389 /// others log errors for later reporting.
390 pub struct Handler {
391     flags: HandlerFlags,
392     inner: Lock<HandlerInner>,
393 }
394
395 /// This inner struct exists to keep it all behind a single lock;
396 /// this is done to prevent possible deadlocks in a multi-threaded compiler,
397 /// as well as inconsistent state observation.
398 struct HandlerInner {
399     flags: HandlerFlags,
400     /// The number of lint errors that have been emitted.
401     lint_err_count: usize,
402     /// The number of errors that have been emitted, including duplicates.
403     ///
404     /// This is not necessarily the count that's reported to the user once
405     /// compilation ends.
406     err_count: usize,
407     warn_count: usize,
408     deduplicated_err_count: usize,
409     emitter: Box<dyn Emitter + sync::Send>,
410     delayed_span_bugs: Vec<DelayedDiagnostic>,
411     delayed_good_path_bugs: Vec<DelayedDiagnostic>,
412     /// This flag indicates that an expected diagnostic was emitted and suppressed.
413     /// This is used for the `delayed_good_path_bugs` check.
414     suppressed_expected_diag: bool,
415
416     /// This set contains the `DiagnosticId` of all emitted diagnostics to avoid
417     /// emitting the same diagnostic with extended help (`--teach`) twice, which
418     /// would be unnecessary repetition.
419     taught_diagnostics: FxHashSet<DiagnosticId>,
420
421     /// Used to suggest rustc --explain `<error code>`
422     emitted_diagnostic_codes: FxIndexSet<DiagnosticId>,
423
424     /// This set contains a hash of every diagnostic that has been emitted by
425     /// this handler. These hashes is used to avoid emitting the same error
426     /// twice.
427     emitted_diagnostics: FxHashSet<u128>,
428
429     /// Stashed diagnostics emitted in one stage of the compiler that may be
430     /// stolen by other stages (e.g. to improve them and add more information).
431     /// The stashed diagnostics count towards the total error count.
432     /// When `.abort_if_errors()` is called, these are also emitted.
433     stashed_diagnostics: FxIndexMap<(Span, StashKey), Diagnostic>,
434
435     /// The warning count, used for a recap upon finishing
436     deduplicated_warn_count: usize,
437
438     future_breakage_diagnostics: Vec<Diagnostic>,
439
440     /// The [`Self::unstable_expect_diagnostics`] should be empty when this struct is
441     /// dropped. However, it can have values if the compilation is stopped early
442     /// or is only partially executed. To avoid ICEs, like in rust#94953 we only
443     /// check if [`Self::unstable_expect_diagnostics`] is empty, if the expectation ids
444     /// have been converted.
445     check_unstable_expect_diagnostics: bool,
446
447     /// Expected [`Diagnostic`][diagnostic::Diagnostic]s store a [`LintExpectationId`] as part of
448     /// the lint level. [`LintExpectationId`]s created early during the compilation
449     /// (before `HirId`s have been defined) are not stable and can therefore not be
450     /// stored on disk. This buffer stores these diagnostics until the ID has been
451     /// replaced by a stable [`LintExpectationId`]. The [`Diagnostic`][diagnostic::Diagnostic]s are the
452     /// submitted for storage and added to the list of fulfilled expectations.
453     unstable_expect_diagnostics: Vec<Diagnostic>,
454
455     /// expected diagnostic will have the level `Expect` which additionally
456     /// carries the [`LintExpectationId`] of the expectation that can be
457     /// marked as fulfilled. This is a collection of all [`LintExpectationId`]s
458     /// that have been marked as fulfilled this way.
459     ///
460     /// [RFC-2383]: https://rust-lang.github.io/rfcs/2383-lint-reasons.html
461     fulfilled_expectations: FxHashSet<LintExpectationId>,
462 }
463
464 /// A key denoting where from a diagnostic was stashed.
465 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
466 pub enum StashKey {
467     ItemNoType,
468     UnderscoreForArrayLengths,
469     EarlySyntaxWarning,
470     CallIntoMethod,
471     /// When an invalid lifetime e.g. `'2` should be reinterpreted
472     /// as a char literal in the parser
473     LifetimeIsChar,
474     /// Maybe there was a typo where a comma was forgotten before
475     /// FRU syntax
476     MaybeFruTypo,
477     CallAssocMethod,
478 }
479
480 fn default_track_diagnostic(d: &mut Diagnostic, f: &mut dyn FnMut(&mut Diagnostic)) {
481     (*f)(d)
482 }
483
484 pub static TRACK_DIAGNOSTICS: AtomicRef<fn(&mut Diagnostic, &mut dyn FnMut(&mut Diagnostic))> =
485     AtomicRef::new(&(default_track_diagnostic as _));
486
487 #[derive(Copy, Clone, Default)]
488 pub struct HandlerFlags {
489     /// If false, warning-level lints are suppressed.
490     /// (rustc: see `--allow warnings` and `--cap-lints`)
491     pub can_emit_warnings: bool,
492     /// If true, error-level diagnostics are upgraded to bug-level.
493     /// (rustc: see `-Z treat-err-as-bug`)
494     pub treat_err_as_bug: Option<NonZeroUsize>,
495     /// If true, immediately emit diagnostics that would otherwise be buffered.
496     /// (rustc: see `-Z dont-buffer-diagnostics` and `-Z treat-err-as-bug`)
497     pub dont_buffer_diagnostics: bool,
498     /// If true, immediately print bugs registered with `delay_span_bug`.
499     /// (rustc: see `-Z report-delayed-bugs`)
500     pub report_delayed_bugs: bool,
501     /// Show macro backtraces.
502     /// (rustc: see `-Z macro-backtrace`)
503     pub macro_backtrace: bool,
504     /// If true, identical diagnostics are reported only once.
505     pub deduplicate_diagnostics: bool,
506     /// Track where errors are created. Enabled with `-Ztrack-diagnostics`.
507     pub track_diagnostics: bool,
508 }
509
510 impl Drop for HandlerInner {
511     fn drop(&mut self) {
512         self.emit_stashed_diagnostics();
513
514         if !self.has_errors() {
515             let bugs = std::mem::replace(&mut self.delayed_span_bugs, Vec::new());
516             self.flush_delayed(bugs, "no errors encountered even though `delay_span_bug` issued");
517         }
518
519         // FIXME(eddyb) this explains what `delayed_good_path_bugs` are!
520         // They're `delayed_span_bugs` but for "require some diagnostic happened"
521         // instead of "require some error happened". Sadly that isn't ideal, as
522         // lints can be `#[allow]`'d, potentially leading to this triggering.
523         // Also, "good path" should be replaced with a better naming.
524         if !self.has_any_message() && !self.suppressed_expected_diag {
525             let bugs = std::mem::replace(&mut self.delayed_good_path_bugs, Vec::new());
526             self.flush_delayed(
527                 bugs,
528                 "no warnings or errors encountered even though `delayed_good_path_bugs` issued",
529             );
530         }
531
532         if self.check_unstable_expect_diagnostics {
533             assert!(
534                 self.unstable_expect_diagnostics.is_empty(),
535                 "all diagnostics with unstable expectations should have been converted",
536             );
537         }
538     }
539 }
540
541 impl Handler {
542     pub fn with_tty_emitter(
543         color_config: ColorConfig,
544         can_emit_warnings: bool,
545         treat_err_as_bug: Option<NonZeroUsize>,
546         sm: Option<Lrc<SourceMap>>,
547         fluent_bundle: Option<Lrc<FluentBundle>>,
548         fallback_bundle: LazyFallbackBundle,
549     ) -> Self {
550         Self::with_tty_emitter_and_flags(
551             color_config,
552             sm,
553             fluent_bundle,
554             fallback_bundle,
555             HandlerFlags { can_emit_warnings, treat_err_as_bug, ..Default::default() },
556         )
557     }
558
559     pub fn with_tty_emitter_and_flags(
560         color_config: ColorConfig,
561         sm: Option<Lrc<SourceMap>>,
562         fluent_bundle: Option<Lrc<FluentBundle>>,
563         fallback_bundle: LazyFallbackBundle,
564         flags: HandlerFlags,
565     ) -> Self {
566         let emitter = Box::new(EmitterWriter::stderr(
567             color_config,
568             sm,
569             fluent_bundle,
570             fallback_bundle,
571             false,
572             false,
573             None,
574             flags.macro_backtrace,
575             flags.track_diagnostics,
576         ));
577         Self::with_emitter_and_flags(emitter, flags)
578     }
579
580     pub fn with_emitter(
581         can_emit_warnings: bool,
582         treat_err_as_bug: Option<NonZeroUsize>,
583         emitter: Box<dyn Emitter + sync::Send>,
584     ) -> Self {
585         Handler::with_emitter_and_flags(
586             emitter,
587             HandlerFlags { can_emit_warnings, treat_err_as_bug, ..Default::default() },
588         )
589     }
590
591     pub fn with_emitter_and_flags(
592         emitter: Box<dyn Emitter + sync::Send>,
593         flags: HandlerFlags,
594     ) -> Self {
595         Self {
596             flags,
597             inner: Lock::new(HandlerInner {
598                 flags,
599                 lint_err_count: 0,
600                 err_count: 0,
601                 warn_count: 0,
602                 deduplicated_err_count: 0,
603                 deduplicated_warn_count: 0,
604                 emitter,
605                 delayed_span_bugs: Vec::new(),
606                 delayed_good_path_bugs: Vec::new(),
607                 suppressed_expected_diag: false,
608                 taught_diagnostics: Default::default(),
609                 emitted_diagnostic_codes: Default::default(),
610                 emitted_diagnostics: Default::default(),
611                 stashed_diagnostics: Default::default(),
612                 future_breakage_diagnostics: Vec::new(),
613                 check_unstable_expect_diagnostics: false,
614                 unstable_expect_diagnostics: Vec::new(),
615                 fulfilled_expectations: Default::default(),
616             }),
617         }
618     }
619
620     /// Translate `message` eagerly with `args` to `SubdiagnosticMessage::Eager`.
621     pub fn eagerly_translate<'a>(
622         &self,
623         message: DiagnosticMessage,
624         args: impl Iterator<Item = DiagnosticArg<'a, 'static>>,
625     ) -> SubdiagnosticMessage {
626         SubdiagnosticMessage::Eager(self.eagerly_translate_to_string(message, args))
627     }
628
629     /// Translate `message` eagerly with `args` to `String`.
630     pub fn eagerly_translate_to_string<'a>(
631         &self,
632         message: DiagnosticMessage,
633         args: impl Iterator<Item = DiagnosticArg<'a, 'static>>,
634     ) -> String {
635         let inner = self.inner.borrow();
636         let args = crate::translation::to_fluent_args(args);
637         inner.emitter.translate_message(&message, &args).map_err(Report::new).unwrap().to_string()
638     }
639
640     // This is here to not allow mutation of flags;
641     // as of this writing it's only used in tests in librustc_middle.
642     pub fn can_emit_warnings(&self) -> bool {
643         self.flags.can_emit_warnings
644     }
645
646     /// Resets the diagnostic error count as well as the cached emitted diagnostics.
647     ///
648     /// NOTE: *do not* call this function from rustc. It is only meant to be called from external
649     /// tools that want to reuse a `Parser` cleaning the previously emitted diagnostics as well as
650     /// the overall count of emitted error diagnostics.
651     pub fn reset_err_count(&self) {
652         let mut inner = self.inner.borrow_mut();
653         inner.err_count = 0;
654         inner.warn_count = 0;
655         inner.deduplicated_err_count = 0;
656         inner.deduplicated_warn_count = 0;
657
658         // actually free the underlying memory (which `clear` would not do)
659         inner.delayed_span_bugs = Default::default();
660         inner.delayed_good_path_bugs = Default::default();
661         inner.taught_diagnostics = Default::default();
662         inner.emitted_diagnostic_codes = Default::default();
663         inner.emitted_diagnostics = Default::default();
664         inner.stashed_diagnostics = Default::default();
665     }
666
667     /// Stash a given diagnostic with the given `Span` and [`StashKey`] as the key.
668     /// Retrieve a stashed diagnostic with `steal_diagnostic`.
669     pub fn stash_diagnostic(&self, span: Span, key: StashKey, diag: Diagnostic) {
670         let mut inner = self.inner.borrow_mut();
671         inner.stash((span.with_parent(None), key), diag);
672     }
673
674     /// Steal a previously stashed diagnostic with the given `Span` and [`StashKey`] as the key.
675     pub fn steal_diagnostic(&self, span: Span, key: StashKey) -> Option<DiagnosticBuilder<'_, ()>> {
676         let mut inner = self.inner.borrow_mut();
677         inner
678             .steal((span.with_parent(None), key))
679             .map(|diag| DiagnosticBuilder::new_diagnostic(self, diag))
680     }
681
682     pub fn has_stashed_diagnostic(&self, span: Span, key: StashKey) -> bool {
683         self.inner.borrow().stashed_diagnostics.get(&(span.with_parent(None), key)).is_some()
684     }
685
686     /// Emit all stashed diagnostics.
687     pub fn emit_stashed_diagnostics(&self) -> Option<ErrorGuaranteed> {
688         self.inner.borrow_mut().emit_stashed_diagnostics()
689     }
690
691     /// Construct a builder with the `msg` at the level appropriate for the specific `EmissionGuarantee`.
692     #[rustc_lint_diagnostics]
693     #[track_caller]
694     pub fn struct_diagnostic<G: EmissionGuarantee>(
695         &self,
696         msg: impl Into<DiagnosticMessage>,
697     ) -> DiagnosticBuilder<'_, G> {
698         G::make_diagnostic_builder(self, msg)
699     }
700
701     /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
702     ///
703     /// Attempting to `.emit()` the builder will only emit if either:
704     /// * `can_emit_warnings` is `true`
705     /// * `is_force_warn` was set in `DiagnosticId::Lint`
706     #[rustc_lint_diagnostics]
707     #[track_caller]
708     pub fn struct_span_warn(
709         &self,
710         span: impl Into<MultiSpan>,
711         msg: impl Into<DiagnosticMessage>,
712     ) -> DiagnosticBuilder<'_, ()> {
713         let mut result = self.struct_warn(msg);
714         result.set_span(span);
715         result
716     }
717
718     /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
719     /// The `id` is used for lint emissions which should also fulfill a lint expectation.
720     ///
721     /// Attempting to `.emit()` the builder will only emit if either:
722     /// * `can_emit_warnings` is `true`
723     /// * `is_force_warn` was set in `DiagnosticId::Lint`
724     #[track_caller]
725     pub fn struct_span_warn_with_expectation(
726         &self,
727         span: impl Into<MultiSpan>,
728         msg: impl Into<DiagnosticMessage>,
729         id: LintExpectationId,
730     ) -> DiagnosticBuilder<'_, ()> {
731         let mut result = self.struct_warn_with_expectation(msg, id);
732         result.set_span(span);
733         result
734     }
735
736     /// Construct a builder at the `Allow` level at the given `span` and with the `msg`.
737     #[rustc_lint_diagnostics]
738     #[track_caller]
739     pub fn struct_span_allow(
740         &self,
741         span: impl Into<MultiSpan>,
742         msg: impl Into<DiagnosticMessage>,
743     ) -> DiagnosticBuilder<'_, ()> {
744         let mut result = self.struct_allow(msg);
745         result.set_span(span);
746         result
747     }
748
749     /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
750     /// Also include a code.
751     #[rustc_lint_diagnostics]
752     #[track_caller]
753     pub fn struct_span_warn_with_code(
754         &self,
755         span: impl Into<MultiSpan>,
756         msg: impl Into<DiagnosticMessage>,
757         code: DiagnosticId,
758     ) -> DiagnosticBuilder<'_, ()> {
759         let mut result = self.struct_span_warn(span, msg);
760         result.code(code);
761         result
762     }
763
764     /// Construct a builder at the `Warning` level with the `msg`.
765     ///
766     /// Attempting to `.emit()` the builder will only emit if either:
767     /// * `can_emit_warnings` is `true`
768     /// * `is_force_warn` was set in `DiagnosticId::Lint`
769     #[rustc_lint_diagnostics]
770     #[track_caller]
771     pub fn struct_warn(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> {
772         DiagnosticBuilder::new(self, Level::Warning(None), msg)
773     }
774
775     /// Construct a builder at the `Warning` level with the `msg`. The `id` is used for
776     /// lint emissions which should also fulfill a lint expectation.
777     ///
778     /// Attempting to `.emit()` the builder will only emit if either:
779     /// * `can_emit_warnings` is `true`
780     /// * `is_force_warn` was set in `DiagnosticId::Lint`
781     #[track_caller]
782     pub fn struct_warn_with_expectation(
783         &self,
784         msg: impl Into<DiagnosticMessage>,
785         id: LintExpectationId,
786     ) -> DiagnosticBuilder<'_, ()> {
787         DiagnosticBuilder::new(self, Level::Warning(Some(id)), msg)
788     }
789
790     /// Construct a builder at the `Allow` level with the `msg`.
791     #[rustc_lint_diagnostics]
792     #[track_caller]
793     pub fn struct_allow(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> {
794         DiagnosticBuilder::new(self, Level::Allow, msg)
795     }
796
797     /// Construct a builder at the `Expect` level with the `msg`.
798     #[rustc_lint_diagnostics]
799     #[track_caller]
800     pub fn struct_expect(
801         &self,
802         msg: impl Into<DiagnosticMessage>,
803         id: LintExpectationId,
804     ) -> DiagnosticBuilder<'_, ()> {
805         DiagnosticBuilder::new(self, Level::Expect(id), msg)
806     }
807
808     /// Construct a builder at the `Error` level at the given `span` and with the `msg`.
809     #[rustc_lint_diagnostics]
810     #[track_caller]
811     pub fn struct_span_err(
812         &self,
813         span: impl Into<MultiSpan>,
814         msg: impl Into<DiagnosticMessage>,
815     ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
816         let mut result = self.struct_err(msg);
817         result.set_span(span);
818         result
819     }
820
821     /// Construct a builder at the `Error` level at the given `span`, with the `msg`, and `code`.
822     #[rustc_lint_diagnostics]
823     #[track_caller]
824     pub fn struct_span_err_with_code(
825         &self,
826         span: impl Into<MultiSpan>,
827         msg: impl Into<DiagnosticMessage>,
828         code: DiagnosticId,
829     ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
830         let mut result = self.struct_span_err(span, msg);
831         result.code(code);
832         result
833     }
834
835     /// Construct a builder at the `Error` level with the `msg`.
836     // FIXME: This method should be removed (every error should have an associated error code).
837     #[rustc_lint_diagnostics]
838     #[track_caller]
839     pub fn struct_err(
840         &self,
841         msg: impl Into<DiagnosticMessage>,
842     ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
843         DiagnosticBuilder::new_guaranteeing_error::<_, { Level::Error { lint: false } }>(self, msg)
844     }
845
846     /// This should only be used by `rustc_middle::lint::struct_lint_level`. Do not use it for hard errors.
847     #[doc(hidden)]
848     #[track_caller]
849     pub fn struct_err_lint(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> {
850         DiagnosticBuilder::new(self, Level::Error { lint: true }, msg)
851     }
852
853     /// Construct a builder at the `Error` level with the `msg` and the `code`.
854     #[rustc_lint_diagnostics]
855     #[track_caller]
856     pub fn struct_err_with_code(
857         &self,
858         msg: impl Into<DiagnosticMessage>,
859         code: DiagnosticId,
860     ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
861         let mut result = self.struct_err(msg);
862         result.code(code);
863         result
864     }
865
866     /// Construct a builder at the `Warn` level with the `msg` and the `code`.
867     #[rustc_lint_diagnostics]
868     #[track_caller]
869     pub fn struct_warn_with_code(
870         &self,
871         msg: impl Into<DiagnosticMessage>,
872         code: DiagnosticId,
873     ) -> DiagnosticBuilder<'_, ()> {
874         let mut result = self.struct_warn(msg);
875         result.code(code);
876         result
877     }
878
879     /// Construct a builder at the `Fatal` level at the given `span` and with the `msg`.
880     #[rustc_lint_diagnostics]
881     #[track_caller]
882     pub fn struct_span_fatal(
883         &self,
884         span: impl Into<MultiSpan>,
885         msg: impl Into<DiagnosticMessage>,
886     ) -> DiagnosticBuilder<'_, !> {
887         let mut result = self.struct_fatal(msg);
888         result.set_span(span);
889         result
890     }
891
892     /// Construct a builder at the `Fatal` level at the given `span`, with the `msg`, and `code`.
893     #[rustc_lint_diagnostics]
894     #[track_caller]
895     pub fn struct_span_fatal_with_code(
896         &self,
897         span: impl Into<MultiSpan>,
898         msg: impl Into<DiagnosticMessage>,
899         code: DiagnosticId,
900     ) -> DiagnosticBuilder<'_, !> {
901         let mut result = self.struct_span_fatal(span, msg);
902         result.code(code);
903         result
904     }
905
906     /// Construct a builder at the `Error` level with the `msg`.
907     #[rustc_lint_diagnostics]
908     #[track_caller]
909     pub fn struct_fatal(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, !> {
910         DiagnosticBuilder::new_fatal(self, msg)
911     }
912
913     /// Construct a builder at the `Help` level with the `msg`.
914     #[rustc_lint_diagnostics]
915     pub fn struct_help(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> {
916         DiagnosticBuilder::new(self, Level::Help, msg)
917     }
918
919     /// Construct a builder at the `Note` level with the `msg`.
920     #[rustc_lint_diagnostics]
921     #[track_caller]
922     pub fn struct_note_without_error(
923         &self,
924         msg: impl Into<DiagnosticMessage>,
925     ) -> DiagnosticBuilder<'_, ()> {
926         DiagnosticBuilder::new(self, Level::Note, msg)
927     }
928
929     #[rustc_lint_diagnostics]
930     #[track_caller]
931     pub fn span_fatal(&self, span: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>) -> ! {
932         self.emit_diag_at_span(Diagnostic::new(Fatal, msg), span);
933         FatalError.raise()
934     }
935
936     #[rustc_lint_diagnostics]
937     #[track_caller]
938     pub fn span_fatal_with_code(
939         &self,
940         span: impl Into<MultiSpan>,
941         msg: impl Into<DiagnosticMessage>,
942         code: DiagnosticId,
943     ) -> ! {
944         self.emit_diag_at_span(Diagnostic::new_with_code(Fatal, Some(code), msg), span);
945         FatalError.raise()
946     }
947
948     #[rustc_lint_diagnostics]
949     #[track_caller]
950     pub fn span_err(
951         &self,
952         span: impl Into<MultiSpan>,
953         msg: impl Into<DiagnosticMessage>,
954     ) -> ErrorGuaranteed {
955         self.emit_diag_at_span(Diagnostic::new(Error { lint: false }, msg), span).unwrap()
956     }
957
958     #[rustc_lint_diagnostics]
959     #[track_caller]
960     pub fn span_err_with_code(
961         &self,
962         span: impl Into<MultiSpan>,
963         msg: impl Into<DiagnosticMessage>,
964         code: DiagnosticId,
965     ) {
966         self.emit_diag_at_span(
967             Diagnostic::new_with_code(Error { lint: false }, Some(code), msg),
968             span,
969         );
970     }
971
972     #[rustc_lint_diagnostics]
973     #[track_caller]
974     pub fn span_warn(&self, span: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>) {
975         self.emit_diag_at_span(Diagnostic::new(Warning(None), msg), span);
976     }
977
978     #[rustc_lint_diagnostics]
979     #[track_caller]
980     pub fn span_warn_with_code(
981         &self,
982         span: impl Into<MultiSpan>,
983         msg: impl Into<DiagnosticMessage>,
984         code: DiagnosticId,
985     ) {
986         self.emit_diag_at_span(Diagnostic::new_with_code(Warning(None), Some(code), msg), span);
987     }
988
989     pub fn span_bug(&self, span: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>) -> ! {
990         self.inner.borrow_mut().span_bug(span, msg)
991     }
992
993     /// For documentation on this, see `Session::delay_span_bug`.
994     #[track_caller]
995     pub fn delay_span_bug(
996         &self,
997         span: impl Into<MultiSpan>,
998         msg: impl Into<DiagnosticMessage>,
999     ) -> ErrorGuaranteed {
1000         self.inner.borrow_mut().delay_span_bug(span, msg)
1001     }
1002
1003     // FIXME(eddyb) note the comment inside `impl Drop for HandlerInner`, that's
1004     // where the explanation of what "good path" is (also, it should be renamed).
1005     pub fn delay_good_path_bug(&self, msg: impl Into<DiagnosticMessage>) {
1006         self.inner.borrow_mut().delay_good_path_bug(msg)
1007     }
1008
1009     #[track_caller]
1010     pub fn span_bug_no_panic(&self, span: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>) {
1011         self.emit_diag_at_span(Diagnostic::new(Bug, msg), span);
1012     }
1013
1014     #[track_caller]
1015     #[rustc_lint_diagnostics]
1016     pub fn span_note_without_error(
1017         &self,
1018         span: impl Into<MultiSpan>,
1019         msg: impl Into<DiagnosticMessage>,
1020     ) {
1021         self.emit_diag_at_span(Diagnostic::new(Note, msg), span);
1022     }
1023
1024     #[track_caller]
1025     #[rustc_lint_diagnostics]
1026     pub fn span_note_diag(
1027         &self,
1028         span: Span,
1029         msg: impl Into<DiagnosticMessage>,
1030     ) -> DiagnosticBuilder<'_, ()> {
1031         let mut db = DiagnosticBuilder::new(self, Note, msg);
1032         db.set_span(span);
1033         db
1034     }
1035
1036     // NOTE: intentionally doesn't raise an error so rustc_codegen_ssa only reports fatal errors in the main thread
1037     #[rustc_lint_diagnostics]
1038     pub fn fatal(&self, msg: impl Into<DiagnosticMessage>) -> FatalError {
1039         self.inner.borrow_mut().fatal(msg)
1040     }
1041
1042     #[rustc_lint_diagnostics]
1043     pub fn err(&self, msg: impl Into<DiagnosticMessage>) -> ErrorGuaranteed {
1044         self.inner.borrow_mut().err(msg)
1045     }
1046
1047     #[rustc_lint_diagnostics]
1048     pub fn warn(&self, msg: impl Into<DiagnosticMessage>) {
1049         let mut db = DiagnosticBuilder::new(self, Warning(None), msg);
1050         db.emit();
1051     }
1052
1053     #[rustc_lint_diagnostics]
1054     pub fn note_without_error(&self, msg: impl Into<DiagnosticMessage>) {
1055         DiagnosticBuilder::new(self, Note, msg).emit();
1056     }
1057
1058     pub fn bug(&self, msg: impl Into<DiagnosticMessage>) -> ! {
1059         self.inner.borrow_mut().bug(msg)
1060     }
1061
1062     #[inline]
1063     pub fn err_count(&self) -> usize {
1064         self.inner.borrow().err_count()
1065     }
1066
1067     pub fn has_errors(&self) -> Option<ErrorGuaranteed> {
1068         if self.inner.borrow().has_errors() { Some(ErrorGuaranteed(())) } else { None }
1069     }
1070
1071     pub fn has_errors_or_lint_errors(&self) -> Option<ErrorGuaranteed> {
1072         if self.inner.borrow().has_errors_or_lint_errors() {
1073             Some(ErrorGuaranteed::unchecked_claim_error_was_emitted())
1074         } else {
1075             None
1076         }
1077     }
1078     pub fn has_errors_or_delayed_span_bugs(&self) -> Option<ErrorGuaranteed> {
1079         if self.inner.borrow().has_errors_or_delayed_span_bugs() {
1080             Some(ErrorGuaranteed::unchecked_claim_error_was_emitted())
1081         } else {
1082             None
1083         }
1084     }
1085     pub fn is_compilation_going_to_fail(&self) -> Option<ErrorGuaranteed> {
1086         if self.inner.borrow().is_compilation_going_to_fail() {
1087             Some(ErrorGuaranteed::unchecked_claim_error_was_emitted())
1088         } else {
1089             None
1090         }
1091     }
1092
1093     pub fn print_error_count(&self, registry: &Registry) {
1094         self.inner.borrow_mut().print_error_count(registry)
1095     }
1096
1097     pub fn take_future_breakage_diagnostics(&self) -> Vec<Diagnostic> {
1098         std::mem::take(&mut self.inner.borrow_mut().future_breakage_diagnostics)
1099     }
1100
1101     pub fn abort_if_errors(&self) {
1102         self.inner.borrow_mut().abort_if_errors()
1103     }
1104
1105     /// `true` if we haven't taught a diagnostic with this code already.
1106     /// The caller must then teach the user about such a diagnostic.
1107     ///
1108     /// Used to suppress emitting the same error multiple times with extended explanation when
1109     /// calling `-Zteach`.
1110     pub fn must_teach(&self, code: &DiagnosticId) -> bool {
1111         self.inner.borrow_mut().must_teach(code)
1112     }
1113
1114     pub fn force_print_diagnostic(&self, db: Diagnostic) {
1115         self.inner.borrow_mut().force_print_diagnostic(db)
1116     }
1117
1118     pub fn emit_diagnostic(&self, diagnostic: &mut Diagnostic) -> Option<ErrorGuaranteed> {
1119         self.inner.borrow_mut().emit_diagnostic(diagnostic)
1120     }
1121
1122     pub fn emit_err<'a>(&'a self, err: impl IntoDiagnostic<'a>) -> ErrorGuaranteed {
1123         self.create_err(err).emit()
1124     }
1125
1126     pub fn create_err<'a>(
1127         &'a self,
1128         err: impl IntoDiagnostic<'a>,
1129     ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
1130         err.into_diagnostic(self)
1131     }
1132
1133     pub fn create_warning<'a>(
1134         &'a self,
1135         warning: impl IntoDiagnostic<'a, ()>,
1136     ) -> DiagnosticBuilder<'a, ()> {
1137         warning.into_diagnostic(self)
1138     }
1139
1140     pub fn emit_warning<'a>(&'a self, warning: impl IntoDiagnostic<'a, ()>) {
1141         self.create_warning(warning).emit()
1142     }
1143
1144     pub fn create_almost_fatal<'a>(
1145         &'a self,
1146         fatal: impl IntoDiagnostic<'a, FatalError>,
1147     ) -> DiagnosticBuilder<'a, FatalError> {
1148         fatal.into_diagnostic(self)
1149     }
1150
1151     pub fn emit_almost_fatal<'a>(
1152         &'a self,
1153         fatal: impl IntoDiagnostic<'a, FatalError>,
1154     ) -> FatalError {
1155         self.create_almost_fatal(fatal).emit()
1156     }
1157
1158     pub fn create_fatal<'a>(
1159         &'a self,
1160         fatal: impl IntoDiagnostic<'a, !>,
1161     ) -> DiagnosticBuilder<'a, !> {
1162         fatal.into_diagnostic(self)
1163     }
1164
1165     pub fn emit_fatal<'a>(&'a self, fatal: impl IntoDiagnostic<'a, !>) -> ! {
1166         self.create_fatal(fatal).emit()
1167     }
1168
1169     pub fn create_bug<'a>(
1170         &'a self,
1171         bug: impl IntoDiagnostic<'a, diagnostic_builder::Bug>,
1172     ) -> DiagnosticBuilder<'a, diagnostic_builder::Bug> {
1173         bug.into_diagnostic(self)
1174     }
1175
1176     pub fn emit_bug<'a>(
1177         &'a self,
1178         bug: impl IntoDiagnostic<'a, diagnostic_builder::Bug>,
1179     ) -> diagnostic_builder::Bug {
1180         self.create_bug(bug).emit()
1181     }
1182
1183     pub fn emit_note<'a>(&'a self, note: impl IntoDiagnostic<'a, Noted>) -> Noted {
1184         self.create_note(note).emit()
1185     }
1186
1187     pub fn create_note<'a>(
1188         &'a self,
1189         note: impl IntoDiagnostic<'a, Noted>,
1190     ) -> DiagnosticBuilder<'a, Noted> {
1191         note.into_diagnostic(self)
1192     }
1193
1194     fn emit_diag_at_span(
1195         &self,
1196         mut diag: Diagnostic,
1197         sp: impl Into<MultiSpan>,
1198     ) -> Option<ErrorGuaranteed> {
1199         let mut inner = self.inner.borrow_mut();
1200         inner.emit_diagnostic(diag.set_span(sp))
1201     }
1202
1203     pub fn emit_artifact_notification(&self, path: &Path, artifact_type: &str) {
1204         self.inner.borrow_mut().emit_artifact_notification(path, artifact_type)
1205     }
1206
1207     pub fn emit_future_breakage_report(&self, diags: Vec<Diagnostic>) {
1208         self.inner.borrow_mut().emitter.emit_future_breakage_report(diags)
1209     }
1210
1211     pub fn emit_unused_externs(
1212         &self,
1213         lint_level: rustc_lint_defs::Level,
1214         loud: bool,
1215         unused_externs: &[&str],
1216     ) {
1217         let mut inner = self.inner.borrow_mut();
1218
1219         if loud && lint_level.is_error() {
1220             inner.bump_err_count();
1221         }
1222
1223         inner.emit_unused_externs(lint_level, unused_externs)
1224     }
1225
1226     pub fn update_unstable_expectation_id(
1227         &self,
1228         unstable_to_stable: &FxHashMap<LintExpectationId, LintExpectationId>,
1229     ) {
1230         let mut inner = self.inner.borrow_mut();
1231         let diags = std::mem::take(&mut inner.unstable_expect_diagnostics);
1232         inner.check_unstable_expect_diagnostics = true;
1233
1234         if !diags.is_empty() {
1235             inner.suppressed_expected_diag = true;
1236             for mut diag in diags.into_iter() {
1237                 diag.update_unstable_expectation_id(unstable_to_stable);
1238
1239                 // Here the diagnostic is given back to `emit_diagnostic` where it was first
1240                 // intercepted. Now it should be processed as usual, since the unstable expectation
1241                 // id is now stable.
1242                 inner.emit_diagnostic(&mut diag);
1243             }
1244         }
1245
1246         inner
1247             .stashed_diagnostics
1248             .values_mut()
1249             .for_each(|diag| diag.update_unstable_expectation_id(unstable_to_stable));
1250         inner
1251             .future_breakage_diagnostics
1252             .iter_mut()
1253             .for_each(|diag| diag.update_unstable_expectation_id(unstable_to_stable));
1254     }
1255
1256     /// This methods steals all [`LintExpectationId`]s that are stored inside
1257     /// [`HandlerInner`] and indicate that the linked expectation has been fulfilled.
1258     #[must_use]
1259     pub fn steal_fulfilled_expectation_ids(&self) -> FxHashSet<LintExpectationId> {
1260         assert!(
1261             self.inner.borrow().unstable_expect_diagnostics.is_empty(),
1262             "`HandlerInner::unstable_expect_diagnostics` should be empty at this point",
1263         );
1264         std::mem::take(&mut self.inner.borrow_mut().fulfilled_expectations)
1265     }
1266
1267     pub fn flush_delayed(&self) {
1268         let mut inner = self.inner.lock();
1269         let bugs = std::mem::replace(&mut inner.delayed_span_bugs, Vec::new());
1270         inner.flush_delayed(bugs, "no errors encountered even though `delay_span_bug` issued");
1271     }
1272 }
1273
1274 impl HandlerInner {
1275     fn must_teach(&mut self, code: &DiagnosticId) -> bool {
1276         self.taught_diagnostics.insert(code.clone())
1277     }
1278
1279     fn force_print_diagnostic(&mut self, db: Diagnostic) {
1280         self.emitter.emit_diagnostic(&db);
1281     }
1282
1283     /// Emit all stashed diagnostics.
1284     fn emit_stashed_diagnostics(&mut self) -> Option<ErrorGuaranteed> {
1285         let has_errors = self.has_errors();
1286         let diags = self.stashed_diagnostics.drain(..).map(|x| x.1).collect::<Vec<_>>();
1287         let mut reported = None;
1288         for mut diag in diags {
1289             // Decrement the count tracking the stash; emitting will increment it.
1290             if diag.is_error() {
1291                 if matches!(diag.level, Level::Error { lint: true }) {
1292                     self.lint_err_count -= 1;
1293                 } else {
1294                     self.err_count -= 1;
1295                 }
1296             } else {
1297                 if diag.is_force_warn() {
1298                     self.warn_count -= 1;
1299                 } else {
1300                     // Unless they're forced, don't flush stashed warnings when
1301                     // there are errors, to avoid causing warning overload. The
1302                     // stash would've been stolen already if it were important.
1303                     if has_errors {
1304                         continue;
1305                     }
1306                 }
1307             }
1308             let reported_this = self.emit_diagnostic(&mut diag);
1309             reported = reported.or(reported_this);
1310         }
1311         reported
1312     }
1313
1314     // FIXME(eddyb) this should ideally take `diagnostic` by value.
1315     fn emit_diagnostic(&mut self, diagnostic: &mut Diagnostic) -> Option<ErrorGuaranteed> {
1316         // The `LintExpectationId` can be stable or unstable depending on when it was created.
1317         // Diagnostics created before the definition of `HirId`s are unstable and can not yet
1318         // be stored. Instead, they are buffered until the `LintExpectationId` is replaced by
1319         // a stable one by the `LintLevelsBuilder`.
1320         if let Some(LintExpectationId::Unstable { .. }) = diagnostic.level.get_expectation_id() {
1321             self.unstable_expect_diagnostics.push(diagnostic.clone());
1322             return None;
1323         }
1324
1325         if diagnostic.level == Level::DelayedBug {
1326             // FIXME(eddyb) this should check for `has_errors` and stop pushing
1327             // once *any* errors were emitted (and truncate `delayed_span_bugs`
1328             // when an error is first emitted, also), but maybe there's a case
1329             // in which that's not sound? otherwise this is really inefficient.
1330             let backtrace = std::backtrace::Backtrace::force_capture();
1331             self.delayed_span_bugs
1332                 .push(DelayedDiagnostic::with_backtrace(diagnostic.clone(), backtrace));
1333
1334             if !self.flags.report_delayed_bugs {
1335                 return Some(ErrorGuaranteed::unchecked_claim_error_was_emitted());
1336             }
1337         }
1338
1339         if diagnostic.has_future_breakage() {
1340             // Future breakages aren't emitted if they're Level::Allowed,
1341             // but they still need to be constructed and stashed below,
1342             // so they'll trigger the good-path bug check.
1343             self.suppressed_expected_diag = true;
1344             self.future_breakage_diagnostics.push(diagnostic.clone());
1345         }
1346
1347         if let Some(expectation_id) = diagnostic.level.get_expectation_id() {
1348             self.suppressed_expected_diag = true;
1349             self.fulfilled_expectations.insert(expectation_id.normalize());
1350         }
1351
1352         if matches!(diagnostic.level, Warning(_))
1353             && !self.flags.can_emit_warnings
1354             && !diagnostic.is_force_warn()
1355         {
1356             if diagnostic.has_future_breakage() {
1357                 (*TRACK_DIAGNOSTICS)(diagnostic, &mut |_| {});
1358             }
1359             return None;
1360         }
1361
1362         if matches!(diagnostic.level, Level::Expect(_) | Level::Allow) {
1363             (*TRACK_DIAGNOSTICS)(diagnostic, &mut |_| {});
1364             return None;
1365         }
1366
1367         let mut guaranteed = None;
1368         (*TRACK_DIAGNOSTICS)(diagnostic, &mut |diagnostic| {
1369             if let Some(ref code) = diagnostic.code {
1370                 self.emitted_diagnostic_codes.insert(code.clone());
1371             }
1372
1373             let already_emitted = |this: &mut Self| {
1374                 let mut hasher = StableHasher::new();
1375                 diagnostic.hash(&mut hasher);
1376                 let diagnostic_hash = hasher.finish();
1377                 !this.emitted_diagnostics.insert(diagnostic_hash)
1378             };
1379
1380             // Only emit the diagnostic if we've been asked to deduplicate or
1381             // haven't already emitted an equivalent diagnostic.
1382             if !(self.flags.deduplicate_diagnostics && already_emitted(self)) {
1383                 debug!(?diagnostic);
1384                 debug!(?self.emitted_diagnostics);
1385                 let already_emitted_sub = |sub: &mut SubDiagnostic| {
1386                     debug!(?sub);
1387                     if sub.level != Level::OnceNote {
1388                         return false;
1389                     }
1390                     let mut hasher = StableHasher::new();
1391                     sub.hash(&mut hasher);
1392                     let diagnostic_hash = hasher.finish();
1393                     debug!(?diagnostic_hash);
1394                     !self.emitted_diagnostics.insert(diagnostic_hash)
1395                 };
1396
1397                 diagnostic.children.drain_filter(already_emitted_sub).for_each(|_| {});
1398
1399                 self.emitter.emit_diagnostic(diagnostic);
1400                 if diagnostic.is_error() {
1401                     self.deduplicated_err_count += 1;
1402                 } else if let Warning(_) = diagnostic.level {
1403                     self.deduplicated_warn_count += 1;
1404                 }
1405             }
1406             if diagnostic.is_error() {
1407                 if matches!(diagnostic.level, Level::Error { lint: true }) {
1408                     self.bump_lint_err_count();
1409                 } else {
1410                     self.bump_err_count();
1411                 }
1412
1413                 guaranteed = Some(ErrorGuaranteed::unchecked_claim_error_was_emitted());
1414             } else {
1415                 self.bump_warn_count();
1416             }
1417         });
1418
1419         guaranteed
1420     }
1421
1422     fn emit_artifact_notification(&mut self, path: &Path, artifact_type: &str) {
1423         self.emitter.emit_artifact_notification(path, artifact_type);
1424     }
1425
1426     fn emit_unused_externs(&mut self, lint_level: rustc_lint_defs::Level, unused_externs: &[&str]) {
1427         self.emitter.emit_unused_externs(lint_level, unused_externs);
1428     }
1429
1430     fn treat_err_as_bug(&self) -> bool {
1431         self.flags.treat_err_as_bug.map_or(false, |c| {
1432             self.err_count() + self.lint_err_count + self.delayed_bug_count() >= c.get()
1433         })
1434     }
1435
1436     fn delayed_bug_count(&self) -> usize {
1437         self.delayed_span_bugs.len() + self.delayed_good_path_bugs.len()
1438     }
1439
1440     fn print_error_count(&mut self, registry: &Registry) {
1441         self.emit_stashed_diagnostics();
1442
1443         let warnings = match self.deduplicated_warn_count {
1444             0 => String::new(),
1445             1 => "1 warning emitted".to_string(),
1446             count => format!("{count} warnings emitted"),
1447         };
1448         let errors = match self.deduplicated_err_count {
1449             0 => String::new(),
1450             1 => "aborting due to previous error".to_string(),
1451             count => format!("aborting due to {count} previous errors"),
1452         };
1453         if self.treat_err_as_bug() {
1454             return;
1455         }
1456
1457         match (errors.len(), warnings.len()) {
1458             (0, 0) => return,
1459             (0, _) => self.emitter.emit_diagnostic(&Diagnostic::new(
1460                 Level::Warning(None),
1461                 DiagnosticMessage::Str(warnings),
1462             )),
1463             (_, 0) => {
1464                 let _ = self.fatal(&errors);
1465             }
1466             (_, _) => {
1467                 let _ = self.fatal(&format!("{}; {}", &errors, &warnings));
1468             }
1469         }
1470
1471         let can_show_explain = self.emitter.should_show_explain();
1472         let are_there_diagnostics = !self.emitted_diagnostic_codes.is_empty();
1473         if can_show_explain && are_there_diagnostics {
1474             let mut error_codes = self
1475                 .emitted_diagnostic_codes
1476                 .iter()
1477                 .filter_map(|x| match &x {
1478                     DiagnosticId::Error(s)
1479                         if registry.try_find_description(s).map_or(false, |o| o.is_some()) =>
1480                     {
1481                         Some(s.clone())
1482                     }
1483                     _ => None,
1484                 })
1485                 .collect::<Vec<_>>();
1486             if !error_codes.is_empty() {
1487                 error_codes.sort();
1488                 if error_codes.len() > 1 {
1489                     let limit = if error_codes.len() > 9 { 9 } else { error_codes.len() };
1490                     self.failure(&format!(
1491                         "Some errors have detailed explanations: {}{}",
1492                         error_codes[..limit].join(", "),
1493                         if error_codes.len() > 9 { "..." } else { "." }
1494                     ));
1495                     self.failure(&format!(
1496                         "For more information about an error, try \
1497                          `rustc --explain {}`.",
1498                         &error_codes[0]
1499                     ));
1500                 } else {
1501                     self.failure(&format!(
1502                         "For more information about this error, try \
1503                          `rustc --explain {}`.",
1504                         &error_codes[0]
1505                     ));
1506                 }
1507             }
1508         }
1509     }
1510
1511     fn stash(&mut self, key: (Span, StashKey), diagnostic: Diagnostic) {
1512         // Track the diagnostic for counts, but don't panic-if-treat-err-as-bug
1513         // yet; that happens when we actually emit the diagnostic.
1514         if diagnostic.is_error() {
1515             if matches!(diagnostic.level, Level::Error { lint: true }) {
1516                 self.lint_err_count += 1;
1517             } else {
1518                 self.err_count += 1;
1519             }
1520         } else {
1521             // Warnings are only automatically flushed if they're forced.
1522             if diagnostic.is_force_warn() {
1523                 self.warn_count += 1;
1524             }
1525         }
1526
1527         // FIXME(Centril, #69537): Consider reintroducing panic on overwriting a stashed diagnostic
1528         // if/when we have a more robust macro-friendly replacement for `(span, key)` as a key.
1529         // See the PR for a discussion.
1530         self.stashed_diagnostics.insert(key, diagnostic);
1531     }
1532
1533     fn steal(&mut self, key: (Span, StashKey)) -> Option<Diagnostic> {
1534         let diagnostic = self.stashed_diagnostics.remove(&key)?;
1535         if diagnostic.is_error() {
1536             if matches!(diagnostic.level, Level::Error { lint: true }) {
1537                 self.lint_err_count -= 1;
1538             } else {
1539                 self.err_count -= 1;
1540             }
1541         } else {
1542             if diagnostic.is_force_warn() {
1543                 self.warn_count -= 1;
1544             }
1545         }
1546         Some(diagnostic)
1547     }
1548
1549     #[inline]
1550     fn err_count(&self) -> usize {
1551         self.err_count
1552     }
1553
1554     fn has_errors(&self) -> bool {
1555         self.err_count() > 0
1556     }
1557     fn has_errors_or_lint_errors(&self) -> bool {
1558         self.has_errors() || self.lint_err_count > 0
1559     }
1560     fn has_errors_or_delayed_span_bugs(&self) -> bool {
1561         self.has_errors() || !self.delayed_span_bugs.is_empty()
1562     }
1563     fn has_any_message(&self) -> bool {
1564         self.err_count() > 0 || self.lint_err_count > 0 || self.warn_count > 0
1565     }
1566
1567     fn is_compilation_going_to_fail(&self) -> bool {
1568         self.has_errors() || self.lint_err_count > 0 || !self.delayed_span_bugs.is_empty()
1569     }
1570
1571     fn abort_if_errors(&mut self) {
1572         self.emit_stashed_diagnostics();
1573
1574         if self.has_errors() {
1575             FatalError.raise();
1576         }
1577     }
1578
1579     #[track_caller]
1580     fn span_bug(&mut self, sp: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>) -> ! {
1581         self.emit_diag_at_span(Diagnostic::new(Bug, msg), sp);
1582         panic::panic_any(ExplicitBug);
1583     }
1584
1585     fn emit_diag_at_span(&mut self, mut diag: Diagnostic, sp: impl Into<MultiSpan>) {
1586         self.emit_diagnostic(diag.set_span(sp));
1587     }
1588
1589     /// For documentation on this, see `Session::delay_span_bug`.
1590     #[track_caller]
1591     fn delay_span_bug(
1592         &mut self,
1593         sp: impl Into<MultiSpan>,
1594         msg: impl Into<DiagnosticMessage>,
1595     ) -> ErrorGuaranteed {
1596         // This is technically `self.treat_err_as_bug()` but `delay_span_bug` is called before
1597         // incrementing `err_count` by one, so we need to +1 the comparing.
1598         // FIXME: Would be nice to increment err_count in a more coherent way.
1599         if self.flags.treat_err_as_bug.map_or(false, |c| {
1600             self.err_count() + self.lint_err_count + self.delayed_bug_count() + 1 >= c.get()
1601         }) {
1602             // FIXME: don't abort here if report_delayed_bugs is off
1603             self.span_bug(sp, msg);
1604         }
1605         let mut diagnostic = Diagnostic::new(Level::DelayedBug, msg);
1606         diagnostic.set_span(sp.into());
1607         self.emit_diagnostic(&mut diagnostic).unwrap()
1608     }
1609
1610     // FIXME(eddyb) note the comment inside `impl Drop for HandlerInner`, that's
1611     // where the explanation of what "good path" is (also, it should be renamed).
1612     fn delay_good_path_bug(&mut self, msg: impl Into<DiagnosticMessage>) {
1613         let mut diagnostic = Diagnostic::new(Level::DelayedBug, msg);
1614         if self.flags.report_delayed_bugs {
1615             self.emit_diagnostic(&mut diagnostic);
1616         }
1617         let backtrace = std::backtrace::Backtrace::force_capture();
1618         self.delayed_good_path_bugs.push(DelayedDiagnostic::with_backtrace(diagnostic, backtrace));
1619     }
1620
1621     fn failure(&mut self, msg: impl Into<DiagnosticMessage>) {
1622         self.emit_diagnostic(&mut Diagnostic::new(FailureNote, msg));
1623     }
1624
1625     fn fatal(&mut self, msg: impl Into<DiagnosticMessage>) -> FatalError {
1626         self.emit(Fatal, msg);
1627         FatalError
1628     }
1629
1630     fn err(&mut self, msg: impl Into<DiagnosticMessage>) -> ErrorGuaranteed {
1631         self.emit(Error { lint: false }, msg)
1632     }
1633
1634     /// Emit an error; level should be `Error` or `Fatal`.
1635     fn emit(&mut self, level: Level, msg: impl Into<DiagnosticMessage>) -> ErrorGuaranteed {
1636         if self.treat_err_as_bug() {
1637             self.bug(msg);
1638         }
1639         self.emit_diagnostic(&mut Diagnostic::new(level, msg)).unwrap()
1640     }
1641
1642     fn bug(&mut self, msg: impl Into<DiagnosticMessage>) -> ! {
1643         self.emit_diagnostic(&mut Diagnostic::new(Bug, msg));
1644         panic::panic_any(ExplicitBug);
1645     }
1646
1647     fn flush_delayed(
1648         &mut self,
1649         bugs: impl IntoIterator<Item = DelayedDiagnostic>,
1650         explanation: impl Into<DiagnosticMessage> + Copy,
1651     ) {
1652         let mut no_bugs = true;
1653         for bug in bugs {
1654             let mut bug = bug.decorate();
1655
1656             if no_bugs {
1657                 // Put the overall explanation before the `DelayedBug`s, to
1658                 // frame them better (e.g. separate warnings from them).
1659                 self.emit_diagnostic(&mut Diagnostic::new(Bug, explanation));
1660                 no_bugs = false;
1661             }
1662
1663             // "Undelay" the `DelayedBug`s (into plain `Bug`s).
1664             if bug.level != Level::DelayedBug {
1665                 // NOTE(eddyb) not panicking here because we're already producing
1666                 // an ICE, and the more information the merrier.
1667                 bug.note(&format!(
1668                     "`flushed_delayed` got diagnostic with level {:?}, \
1669                      instead of the expected `DelayedBug`",
1670                     bug.level,
1671                 ));
1672             }
1673             bug.level = Level::Bug;
1674
1675             self.emit_diagnostic(&mut bug);
1676         }
1677
1678         // Panic with `DelayedBugPanic` to avoid "unexpected panic" messages.
1679         if !no_bugs {
1680             panic::panic_any(DelayedBugPanic);
1681         }
1682     }
1683
1684     fn bump_lint_err_count(&mut self) {
1685         self.lint_err_count += 1;
1686         self.panic_if_treat_err_as_bug();
1687     }
1688
1689     fn bump_err_count(&mut self) {
1690         self.err_count += 1;
1691         self.panic_if_treat_err_as_bug();
1692     }
1693
1694     fn bump_warn_count(&mut self) {
1695         self.warn_count += 1;
1696     }
1697
1698     fn panic_if_treat_err_as_bug(&self) {
1699         if self.treat_err_as_bug() {
1700             match (
1701                 self.err_count() + self.lint_err_count,
1702                 self.delayed_bug_count(),
1703                 self.flags.treat_err_as_bug.map(|c| c.get()).unwrap_or(0),
1704             ) {
1705                 (1, 0, 1) => panic!("aborting due to `-Z treat-err-as-bug=1`"),
1706                 (0, 1, 1) => panic!("aborting due delayed bug with `-Z treat-err-as-bug=1`"),
1707                 (count, delayed_count, as_bug) => {
1708                     if delayed_count > 0 {
1709                         panic!(
1710                             "aborting after {} errors and {} delayed bugs due to `-Z treat-err-as-bug={}`",
1711                             count, delayed_count, as_bug,
1712                         )
1713                     } else {
1714                         panic!(
1715                             "aborting after {} errors due to `-Z treat-err-as-bug={}`",
1716                             count, as_bug,
1717                         )
1718                     }
1719                 }
1720             }
1721         }
1722     }
1723 }
1724
1725 struct DelayedDiagnostic {
1726     inner: Diagnostic,
1727     note: Backtrace,
1728 }
1729
1730 impl DelayedDiagnostic {
1731     fn with_backtrace(diagnostic: Diagnostic, backtrace: Backtrace) -> Self {
1732         DelayedDiagnostic { inner: diagnostic, note: backtrace }
1733     }
1734
1735     fn decorate(mut self) -> Diagnostic {
1736         self.inner.note(&format!("delayed at {}", self.note));
1737         self.inner
1738     }
1739 }
1740
1741 #[derive(Copy, PartialEq, Eq, Clone, Hash, Debug, Encodable, Decodable)]
1742 pub enum Level {
1743     Bug,
1744     DelayedBug,
1745     Fatal,
1746     Error {
1747         /// If this error comes from a lint, don't abort compilation even when abort_if_errors() is called.
1748         lint: bool,
1749     },
1750     /// This [`LintExpectationId`] is used for expected lint diagnostics, which should
1751     /// also emit a warning due to the `force-warn` flag. In all other cases this should
1752     /// be `None`.
1753     Warning(Option<LintExpectationId>),
1754     Note,
1755     /// A note that is only emitted once.
1756     OnceNote,
1757     Help,
1758     FailureNote,
1759     Allow,
1760     Expect(LintExpectationId),
1761 }
1762
1763 impl fmt::Display for Level {
1764     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1765         self.to_str().fmt(f)
1766     }
1767 }
1768
1769 impl Level {
1770     fn color(self) -> ColorSpec {
1771         let mut spec = ColorSpec::new();
1772         match self {
1773             Bug | DelayedBug | Fatal | Error { .. } => {
1774                 spec.set_fg(Some(Color::Red)).set_intense(true);
1775             }
1776             Warning(_) => {
1777                 spec.set_fg(Some(Color::Yellow)).set_intense(cfg!(windows));
1778             }
1779             Note | OnceNote => {
1780                 spec.set_fg(Some(Color::Green)).set_intense(true);
1781             }
1782             Help => {
1783                 spec.set_fg(Some(Color::Cyan)).set_intense(true);
1784             }
1785             FailureNote => {}
1786             Allow | Expect(_) => unreachable!(),
1787         }
1788         spec
1789     }
1790
1791     pub fn to_str(self) -> &'static str {
1792         match self {
1793             Bug | DelayedBug => "error: internal compiler error",
1794             Fatal | Error { .. } => "error",
1795             Warning(_) => "warning",
1796             Note | OnceNote => "note",
1797             Help => "help",
1798             FailureNote => "failure-note",
1799             Allow => panic!("Shouldn't call on allowed error"),
1800             Expect(_) => panic!("Shouldn't call on expected error"),
1801         }
1802     }
1803
1804     pub fn is_failure_note(&self) -> bool {
1805         matches!(*self, FailureNote)
1806     }
1807
1808     pub fn get_expectation_id(&self) -> Option<LintExpectationId> {
1809         match self {
1810             Level::Expect(id) | Level::Warning(Some(id)) => Some(*id),
1811             _ => None,
1812         }
1813     }
1814 }
1815
1816 // FIXME(eddyb) this doesn't belong here AFAICT, should be moved to callsite.
1817 pub fn add_elided_lifetime_in_path_suggestion(
1818     source_map: &SourceMap,
1819     diag: &mut Diagnostic,
1820     n: usize,
1821     path_span: Span,
1822     incl_angl_brckt: bool,
1823     insertion_span: Span,
1824 ) {
1825     diag.span_label(path_span, format!("expected lifetime parameter{}", pluralize!(n)));
1826     if !source_map.is_span_accessible(insertion_span) {
1827         // Do not try to suggest anything if generated by a proc-macro.
1828         return;
1829     }
1830     let anon_lts = vec!["'_"; n].join(", ");
1831     let suggestion =
1832         if incl_angl_brckt { format!("<{}>", anon_lts) } else { format!("{}, ", anon_lts) };
1833     diag.span_suggestion_verbose(
1834         insertion_span.shrink_to_hi(),
1835         &format!("indicate the anonymous lifetime{}", pluralize!(n)),
1836         suggestion,
1837         Applicability::MachineApplicable,
1838     );
1839 }
1840
1841 /// Useful type to use with `Result<>` indicate that an error has already
1842 /// been reported to the user, so no need to continue checking.
1843 #[derive(Clone, Copy, Debug, Encodable, Decodable, Hash, PartialEq, Eq, PartialOrd, Ord)]
1844 #[derive(HashStable_Generic)]
1845 pub struct ErrorGuaranteed(());
1846
1847 impl ErrorGuaranteed {
1848     /// To be used only if you really know what you are doing... ideally, we would find a way to
1849     /// eliminate all calls to this method.
1850     pub fn unchecked_claim_error_was_emitted() -> Self {
1851         ErrorGuaranteed(())
1852     }
1853 }