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