]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_errors/src/lib.rs
Rollup merge of #102938 - c410-f3r:here-we-go-again, r=petrochenkov
[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 }
467
468 fn default_track_diagnostic(_: &Diagnostic) {}
469
470 pub static TRACK_DIAGNOSTICS: AtomicRef<fn(&Diagnostic)> =
471     AtomicRef::new(&(default_track_diagnostic as fn(&_)));
472
473 #[derive(Copy, Clone, Default)]
474 pub struct HandlerFlags {
475     /// If false, warning-level lints are suppressed.
476     /// (rustc: see `--allow warnings` and `--cap-lints`)
477     pub can_emit_warnings: bool,
478     /// If true, error-level diagnostics are upgraded to bug-level.
479     /// (rustc: see `-Z treat-err-as-bug`)
480     pub treat_err_as_bug: Option<NonZeroUsize>,
481     /// If true, immediately emit diagnostics that would otherwise be buffered.
482     /// (rustc: see `-Z dont-buffer-diagnostics` and `-Z treat-err-as-bug`)
483     pub dont_buffer_diagnostics: bool,
484     /// If true, immediately print bugs registered with `delay_span_bug`.
485     /// (rustc: see `-Z report-delayed-bugs`)
486     pub report_delayed_bugs: bool,
487     /// Show macro backtraces.
488     /// (rustc: see `-Z macro-backtrace`)
489     pub macro_backtrace: bool,
490     /// If true, identical diagnostics are reported only once.
491     pub deduplicate_diagnostics: bool,
492 }
493
494 impl Drop for HandlerInner {
495     fn drop(&mut self) {
496         self.emit_stashed_diagnostics();
497
498         if !self.has_errors() {
499             let bugs = std::mem::replace(&mut self.delayed_span_bugs, Vec::new());
500             self.flush_delayed(bugs, "no errors encountered even though `delay_span_bug` issued");
501         }
502
503         // FIXME(eddyb) this explains what `delayed_good_path_bugs` are!
504         // They're `delayed_span_bugs` but for "require some diagnostic happened"
505         // instead of "require some error happened". Sadly that isn't ideal, as
506         // lints can be `#[allow]`'d, potentially leading to this triggering.
507         // Also, "good path" should be replaced with a better naming.
508         if !self.has_any_message() && !self.suppressed_expected_diag {
509             let bugs = std::mem::replace(&mut self.delayed_good_path_bugs, Vec::new());
510             self.flush_delayed(
511                 bugs.into_iter().map(DelayedDiagnostic::decorate),
512                 "no warnings or errors encountered even though `delayed_good_path_bugs` issued",
513             );
514         }
515
516         if self.check_unstable_expect_diagnostics {
517             assert!(
518                 self.unstable_expect_diagnostics.is_empty(),
519                 "all diagnostics with unstable expectations should have been converted",
520             );
521         }
522     }
523 }
524
525 impl Handler {
526     pub fn with_tty_emitter(
527         color_config: ColorConfig,
528         can_emit_warnings: bool,
529         treat_err_as_bug: Option<NonZeroUsize>,
530         sm: Option<Lrc<SourceMap>>,
531         fluent_bundle: Option<Lrc<FluentBundle>>,
532         fallback_bundle: LazyFallbackBundle,
533     ) -> Self {
534         Self::with_tty_emitter_and_flags(
535             color_config,
536             sm,
537             fluent_bundle,
538             fallback_bundle,
539             HandlerFlags { can_emit_warnings, treat_err_as_bug, ..Default::default() },
540         )
541     }
542
543     pub fn with_tty_emitter_and_flags(
544         color_config: ColorConfig,
545         sm: Option<Lrc<SourceMap>>,
546         fluent_bundle: Option<Lrc<FluentBundle>>,
547         fallback_bundle: LazyFallbackBundle,
548         flags: HandlerFlags,
549     ) -> Self {
550         let emitter = Box::new(EmitterWriter::stderr(
551             color_config,
552             sm,
553             fluent_bundle,
554             fallback_bundle,
555             false,
556             false,
557             None,
558             flags.macro_backtrace,
559         ));
560         Self::with_emitter_and_flags(emitter, flags)
561     }
562
563     pub fn with_emitter(
564         can_emit_warnings: bool,
565         treat_err_as_bug: Option<NonZeroUsize>,
566         emitter: Box<dyn Emitter + sync::Send>,
567     ) -> Self {
568         Handler::with_emitter_and_flags(
569             emitter,
570             HandlerFlags { can_emit_warnings, treat_err_as_bug, ..Default::default() },
571         )
572     }
573
574     pub fn with_emitter_and_flags(
575         emitter: Box<dyn Emitter + sync::Send>,
576         flags: HandlerFlags,
577     ) -> Self {
578         Self {
579             flags,
580             inner: Lock::new(HandlerInner {
581                 flags,
582                 lint_err_count: 0,
583                 err_count: 0,
584                 warn_count: 0,
585                 deduplicated_err_count: 0,
586                 deduplicated_warn_count: 0,
587                 emitter,
588                 delayed_span_bugs: Vec::new(),
589                 delayed_good_path_bugs: Vec::new(),
590                 suppressed_expected_diag: false,
591                 taught_diagnostics: Default::default(),
592                 emitted_diagnostic_codes: Default::default(),
593                 emitted_diagnostics: Default::default(),
594                 stashed_diagnostics: Default::default(),
595                 future_breakage_diagnostics: Vec::new(),
596                 check_unstable_expect_diagnostics: false,
597                 unstable_expect_diagnostics: Vec::new(),
598                 fulfilled_expectations: Default::default(),
599             }),
600         }
601     }
602
603     /// Translate `message` eagerly with `args`.
604     pub fn eagerly_translate<'a>(
605         &self,
606         message: DiagnosticMessage,
607         args: impl Iterator<Item = DiagnosticArg<'a, 'static>>,
608     ) -> SubdiagnosticMessage {
609         let inner = self.inner.borrow();
610         let args = crate::translation::to_fluent_args(args);
611         SubdiagnosticMessage::Eager(inner.emitter.translate_message(&message, &args).to_string())
612     }
613
614     // This is here to not allow mutation of flags;
615     // as of this writing it's only used in tests in librustc_middle.
616     pub fn can_emit_warnings(&self) -> bool {
617         self.flags.can_emit_warnings
618     }
619
620     /// Resets the diagnostic error count as well as the cached emitted diagnostics.
621     ///
622     /// NOTE: *do not* call this function from rustc. It is only meant to be called from external
623     /// tools that want to reuse a `Parser` cleaning the previously emitted diagnostics as well as
624     /// the overall count of emitted error diagnostics.
625     pub fn reset_err_count(&self) {
626         let mut inner = self.inner.borrow_mut();
627         inner.err_count = 0;
628         inner.warn_count = 0;
629         inner.deduplicated_err_count = 0;
630         inner.deduplicated_warn_count = 0;
631
632         // actually free the underlying memory (which `clear` would not do)
633         inner.delayed_span_bugs = Default::default();
634         inner.delayed_good_path_bugs = Default::default();
635         inner.taught_diagnostics = Default::default();
636         inner.emitted_diagnostic_codes = Default::default();
637         inner.emitted_diagnostics = Default::default();
638         inner.stashed_diagnostics = Default::default();
639     }
640
641     /// Stash a given diagnostic with the given `Span` and `StashKey` as the key for later stealing.
642     pub fn stash_diagnostic(&self, span: Span, key: StashKey, diag: Diagnostic) {
643         let mut inner = self.inner.borrow_mut();
644         inner.stash((span, key), diag);
645     }
646
647     /// Steal a previously stashed diagnostic with the given `Span` and `StashKey` as the key.
648     pub fn steal_diagnostic(&self, span: Span, key: StashKey) -> Option<DiagnosticBuilder<'_, ()>> {
649         let mut inner = self.inner.borrow_mut();
650         inner.steal((span, key)).map(|diag| DiagnosticBuilder::new_diagnostic(self, diag))
651     }
652
653     pub fn has_stashed_diagnostic(&self, span: Span, key: StashKey) -> bool {
654         self.inner.borrow().stashed_diagnostics.get(&(span, key)).is_some()
655     }
656
657     /// Emit all stashed diagnostics.
658     pub fn emit_stashed_diagnostics(&self) -> Option<ErrorGuaranteed> {
659         self.inner.borrow_mut().emit_stashed_diagnostics()
660     }
661
662     /// Construct a builder with the `msg` at the level appropriate for the specific `EmissionGuarantee`.
663     #[rustc_lint_diagnostics]
664     pub fn struct_diagnostic<G: EmissionGuarantee>(
665         &self,
666         msg: impl Into<DiagnosticMessage>,
667     ) -> DiagnosticBuilder<'_, G> {
668         G::make_diagnostic_builder(self, msg)
669     }
670
671     /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
672     ///
673     /// Attempting to `.emit()` the builder will only emit if either:
674     /// * `can_emit_warnings` is `true`
675     /// * `is_force_warn` was set in `DiagnosticId::Lint`
676     #[rustc_lint_diagnostics]
677     pub fn struct_span_warn(
678         &self,
679         span: impl Into<MultiSpan>,
680         msg: impl Into<DiagnosticMessage>,
681     ) -> DiagnosticBuilder<'_, ()> {
682         let mut result = self.struct_warn(msg);
683         result.set_span(span);
684         result
685     }
686
687     /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
688     /// The `id` is used for lint emissions which should also fulfill a lint expectation.
689     ///
690     /// Attempting to `.emit()` the builder will only emit if either:
691     /// * `can_emit_warnings` is `true`
692     /// * `is_force_warn` was set in `DiagnosticId::Lint`
693     pub fn struct_span_warn_with_expectation(
694         &self,
695         span: impl Into<MultiSpan>,
696         msg: impl Into<DiagnosticMessage>,
697         id: LintExpectationId,
698     ) -> DiagnosticBuilder<'_, ()> {
699         let mut result = self.struct_warn_with_expectation(msg, id);
700         result.set_span(span);
701         result
702     }
703
704     /// Construct a builder at the `Allow` level at the given `span` and with the `msg`.
705     #[rustc_lint_diagnostics]
706     pub fn struct_span_allow(
707         &self,
708         span: impl Into<MultiSpan>,
709         msg: impl Into<DiagnosticMessage>,
710     ) -> DiagnosticBuilder<'_, ()> {
711         let mut result = self.struct_allow(msg);
712         result.set_span(span);
713         result
714     }
715
716     /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
717     /// Also include a code.
718     #[rustc_lint_diagnostics]
719     pub fn struct_span_warn_with_code(
720         &self,
721         span: impl Into<MultiSpan>,
722         msg: impl Into<DiagnosticMessage>,
723         code: DiagnosticId,
724     ) -> DiagnosticBuilder<'_, ()> {
725         let mut result = self.struct_span_warn(span, msg);
726         result.code(code);
727         result
728     }
729
730     /// Construct a builder at the `Warning` level with the `msg`.
731     ///
732     /// Attempting to `.emit()` the builder will only emit if either:
733     /// * `can_emit_warnings` is `true`
734     /// * `is_force_warn` was set in `DiagnosticId::Lint`
735     #[rustc_lint_diagnostics]
736     pub fn struct_warn(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> {
737         DiagnosticBuilder::new(self, Level::Warning(None), msg)
738     }
739
740     /// Construct a builder at the `Warning` level with the `msg`. The `id` is used for
741     /// lint emissions which should also fulfill a lint expectation.
742     ///
743     /// Attempting to `.emit()` the builder will only emit if either:
744     /// * `can_emit_warnings` is `true`
745     /// * `is_force_warn` was set in `DiagnosticId::Lint`
746     pub fn struct_warn_with_expectation(
747         &self,
748         msg: impl Into<DiagnosticMessage>,
749         id: LintExpectationId,
750     ) -> DiagnosticBuilder<'_, ()> {
751         DiagnosticBuilder::new(self, Level::Warning(Some(id)), msg)
752     }
753
754     /// Construct a builder at the `Allow` level with the `msg`.
755     #[rustc_lint_diagnostics]
756     pub fn struct_allow(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> {
757         DiagnosticBuilder::new(self, Level::Allow, msg)
758     }
759
760     /// Construct a builder at the `Expect` level with the `msg`.
761     #[rustc_lint_diagnostics]
762     pub fn struct_expect(
763         &self,
764         msg: impl Into<DiagnosticMessage>,
765         id: LintExpectationId,
766     ) -> DiagnosticBuilder<'_, ()> {
767         DiagnosticBuilder::new(self, Level::Expect(id), msg)
768     }
769
770     /// Construct a builder at the `Error` level at the given `span` and with the `msg`.
771     #[rustc_lint_diagnostics]
772     pub fn struct_span_err(
773         &self,
774         span: impl Into<MultiSpan>,
775         msg: impl Into<DiagnosticMessage>,
776     ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
777         let mut result = self.struct_err(msg);
778         result.set_span(span);
779         result
780     }
781
782     /// Construct a builder at the `Error` level at the given `span`, with the `msg`, and `code`.
783     #[rustc_lint_diagnostics]
784     pub fn struct_span_err_with_code(
785         &self,
786         span: impl Into<MultiSpan>,
787         msg: impl Into<DiagnosticMessage>,
788         code: DiagnosticId,
789     ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
790         let mut result = self.struct_span_err(span, msg);
791         result.code(code);
792         result
793     }
794
795     /// Construct a builder at the `Error` level with the `msg`.
796     // FIXME: This method should be removed (every error should have an associated error code).
797     #[rustc_lint_diagnostics]
798     pub fn struct_err(
799         &self,
800         msg: impl Into<DiagnosticMessage>,
801     ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
802         DiagnosticBuilder::new_guaranteeing_error::<_, { Level::Error { lint: false } }>(self, msg)
803     }
804
805     /// This should only be used by `rustc_middle::lint::struct_lint_level`. Do not use it for hard errors.
806     #[doc(hidden)]
807     pub fn struct_err_lint(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> {
808         DiagnosticBuilder::new(self, Level::Error { lint: true }, msg)
809     }
810
811     /// Construct a builder at the `Error` level with the `msg` and the `code`.
812     #[rustc_lint_diagnostics]
813     pub fn struct_err_with_code(
814         &self,
815         msg: impl Into<DiagnosticMessage>,
816         code: DiagnosticId,
817     ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
818         let mut result = self.struct_err(msg);
819         result.code(code);
820         result
821     }
822
823     /// Construct a builder at the `Warn` level with the `msg` and the `code`.
824     #[rustc_lint_diagnostics]
825     pub fn struct_warn_with_code(
826         &self,
827         msg: impl Into<DiagnosticMessage>,
828         code: DiagnosticId,
829     ) -> DiagnosticBuilder<'_, ()> {
830         let mut result = self.struct_warn(msg);
831         result.code(code);
832         result
833     }
834
835     /// Construct a builder at the `Fatal` level at the given `span` and with the `msg`.
836     #[rustc_lint_diagnostics]
837     pub fn struct_span_fatal(
838         &self,
839         span: impl Into<MultiSpan>,
840         msg: impl Into<DiagnosticMessage>,
841     ) -> DiagnosticBuilder<'_, !> {
842         let mut result = self.struct_fatal(msg);
843         result.set_span(span);
844         result
845     }
846
847     /// Construct a builder at the `Fatal` level at the given `span`, with the `msg`, and `code`.
848     #[rustc_lint_diagnostics]
849     pub fn struct_span_fatal_with_code(
850         &self,
851         span: impl Into<MultiSpan>,
852         msg: impl Into<DiagnosticMessage>,
853         code: DiagnosticId,
854     ) -> DiagnosticBuilder<'_, !> {
855         let mut result = self.struct_span_fatal(span, msg);
856         result.code(code);
857         result
858     }
859
860     /// Construct a builder at the `Error` level with the `msg`.
861     #[rustc_lint_diagnostics]
862     pub fn struct_fatal(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, !> {
863         DiagnosticBuilder::new_fatal(self, msg)
864     }
865
866     /// Construct a builder at the `Help` level with the `msg`.
867     #[rustc_lint_diagnostics]
868     pub fn struct_help(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> {
869         DiagnosticBuilder::new(self, Level::Help, msg)
870     }
871
872     /// Construct a builder at the `Note` level with the `msg`.
873     #[rustc_lint_diagnostics]
874     pub fn struct_note_without_error(
875         &self,
876         msg: impl Into<DiagnosticMessage>,
877     ) -> DiagnosticBuilder<'_, ()> {
878         DiagnosticBuilder::new(self, Level::Note, msg)
879     }
880
881     #[rustc_lint_diagnostics]
882     pub fn span_fatal(&self, span: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>) -> ! {
883         self.emit_diag_at_span(Diagnostic::new(Fatal, msg), span);
884         FatalError.raise()
885     }
886
887     #[rustc_lint_diagnostics]
888     pub fn span_fatal_with_code(
889         &self,
890         span: impl Into<MultiSpan>,
891         msg: impl Into<DiagnosticMessage>,
892         code: DiagnosticId,
893     ) -> ! {
894         self.emit_diag_at_span(Diagnostic::new_with_code(Fatal, Some(code), msg), span);
895         FatalError.raise()
896     }
897
898     #[rustc_lint_diagnostics]
899     pub fn span_err(
900         &self,
901         span: impl Into<MultiSpan>,
902         msg: impl Into<DiagnosticMessage>,
903     ) -> ErrorGuaranteed {
904         self.emit_diag_at_span(Diagnostic::new(Error { lint: false }, msg), span).unwrap()
905     }
906
907     #[rustc_lint_diagnostics]
908     pub fn span_err_with_code(
909         &self,
910         span: impl Into<MultiSpan>,
911         msg: impl Into<DiagnosticMessage>,
912         code: DiagnosticId,
913     ) {
914         self.emit_diag_at_span(
915             Diagnostic::new_with_code(Error { lint: false }, Some(code), msg),
916             span,
917         );
918     }
919
920     #[rustc_lint_diagnostics]
921     pub fn span_warn(&self, span: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>) {
922         self.emit_diag_at_span(Diagnostic::new(Warning(None), msg), span);
923     }
924
925     #[rustc_lint_diagnostics]
926     pub fn span_warn_with_code(
927         &self,
928         span: impl Into<MultiSpan>,
929         msg: impl Into<DiagnosticMessage>,
930         code: DiagnosticId,
931     ) {
932         self.emit_diag_at_span(Diagnostic::new_with_code(Warning(None), Some(code), msg), span);
933     }
934
935     pub fn span_bug(&self, span: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>) -> ! {
936         self.inner.borrow_mut().span_bug(span, msg)
937     }
938
939     #[track_caller]
940     pub fn delay_span_bug(
941         &self,
942         span: impl Into<MultiSpan>,
943         msg: impl Into<DiagnosticMessage>,
944     ) -> ErrorGuaranteed {
945         self.inner.borrow_mut().delay_span_bug(span, msg)
946     }
947
948     // FIXME(eddyb) note the comment inside `impl Drop for HandlerInner`, that's
949     // where the explanation of what "good path" is (also, it should be renamed).
950     pub fn delay_good_path_bug(&self, msg: impl Into<DiagnosticMessage>) {
951         self.inner.borrow_mut().delay_good_path_bug(msg)
952     }
953
954     pub fn span_bug_no_panic(&self, span: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>) {
955         self.emit_diag_at_span(Diagnostic::new(Bug, msg), span);
956     }
957
958     pub fn span_note_without_error(
959         &self,
960         span: impl Into<MultiSpan>,
961         msg: impl Into<DiagnosticMessage>,
962     ) {
963         self.emit_diag_at_span(Diagnostic::new(Note, msg), span);
964     }
965
966     pub fn span_note_diag(
967         &self,
968         span: Span,
969         msg: impl Into<DiagnosticMessage>,
970     ) -> DiagnosticBuilder<'_, ()> {
971         let mut db = DiagnosticBuilder::new(self, Note, msg);
972         db.set_span(span);
973         db
974     }
975
976     // NOTE: intentionally doesn't raise an error so rustc_codegen_ssa only reports fatal errors in the main thread
977     pub fn fatal(&self, msg: impl Into<DiagnosticMessage>) -> FatalError {
978         self.inner.borrow_mut().fatal(msg)
979     }
980
981     pub fn err(&self, msg: impl Into<DiagnosticMessage>) -> ErrorGuaranteed {
982         self.inner.borrow_mut().err(msg)
983     }
984
985     pub fn warn(&self, msg: impl Into<DiagnosticMessage>) {
986         let mut db = DiagnosticBuilder::new(self, Warning(None), msg);
987         db.emit();
988     }
989
990     pub fn note_without_error(&self, msg: impl Into<DiagnosticMessage>) {
991         DiagnosticBuilder::new(self, Note, msg).emit();
992     }
993
994     pub fn bug(&self, msg: impl Into<DiagnosticMessage>) -> ! {
995         self.inner.borrow_mut().bug(msg)
996     }
997
998     #[inline]
999     pub fn err_count(&self) -> usize {
1000         self.inner.borrow().err_count()
1001     }
1002
1003     pub fn has_errors(&self) -> Option<ErrorGuaranteed> {
1004         if self.inner.borrow().has_errors() { Some(ErrorGuaranteed(())) } else { None }
1005     }
1006     pub fn has_errors_or_lint_errors(&self) -> Option<ErrorGuaranteed> {
1007         if self.inner.borrow().has_errors_or_lint_errors() {
1008             Some(ErrorGuaranteed(()))
1009         } else {
1010             None
1011         }
1012     }
1013     pub fn has_errors_or_delayed_span_bugs(&self) -> bool {
1014         self.inner.borrow().has_errors_or_delayed_span_bugs()
1015     }
1016
1017     pub fn print_error_count(&self, registry: &Registry) {
1018         self.inner.borrow_mut().print_error_count(registry)
1019     }
1020
1021     pub fn take_future_breakage_diagnostics(&self) -> Vec<Diagnostic> {
1022         std::mem::take(&mut self.inner.borrow_mut().future_breakage_diagnostics)
1023     }
1024
1025     pub fn abort_if_errors(&self) {
1026         self.inner.borrow_mut().abort_if_errors()
1027     }
1028
1029     /// `true` if we haven't taught a diagnostic with this code already.
1030     /// The caller must then teach the user about such a diagnostic.
1031     ///
1032     /// Used to suppress emitting the same error multiple times with extended explanation when
1033     /// calling `-Zteach`.
1034     pub fn must_teach(&self, code: &DiagnosticId) -> bool {
1035         self.inner.borrow_mut().must_teach(code)
1036     }
1037
1038     pub fn force_print_diagnostic(&self, db: Diagnostic) {
1039         self.inner.borrow_mut().force_print_diagnostic(db)
1040     }
1041
1042     pub fn emit_diagnostic(&self, diagnostic: &mut Diagnostic) -> Option<ErrorGuaranteed> {
1043         self.inner.borrow_mut().emit_diagnostic(diagnostic)
1044     }
1045
1046     pub fn emit_err<'a>(&'a self, err: impl IntoDiagnostic<'a>) -> ErrorGuaranteed {
1047         self.create_err(err).emit()
1048     }
1049
1050     pub fn create_err<'a>(
1051         &'a self,
1052         err: impl IntoDiagnostic<'a>,
1053     ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
1054         err.into_diagnostic(self)
1055     }
1056
1057     pub fn create_warning<'a>(
1058         &'a self,
1059         warning: impl IntoDiagnostic<'a, ()>,
1060     ) -> DiagnosticBuilder<'a, ()> {
1061         warning.into_diagnostic(self)
1062     }
1063
1064     pub fn emit_warning<'a>(&'a self, warning: impl IntoDiagnostic<'a, ()>) {
1065         self.create_warning(warning).emit()
1066     }
1067
1068     pub fn create_fatal<'a>(
1069         &'a self,
1070         fatal: impl IntoDiagnostic<'a, !>,
1071     ) -> DiagnosticBuilder<'a, !> {
1072         fatal.into_diagnostic(self)
1073     }
1074
1075     pub fn emit_fatal<'a>(&'a self, fatal: impl IntoDiagnostic<'a, !>) -> ! {
1076         self.create_fatal(fatal).emit()
1077     }
1078
1079     fn emit_diag_at_span(
1080         &self,
1081         mut diag: Diagnostic,
1082         sp: impl Into<MultiSpan>,
1083     ) -> Option<ErrorGuaranteed> {
1084         let mut inner = self.inner.borrow_mut();
1085         inner.emit_diagnostic(diag.set_span(sp))
1086     }
1087
1088     pub fn emit_artifact_notification(&self, path: &Path, artifact_type: &str) {
1089         self.inner.borrow_mut().emit_artifact_notification(path, artifact_type)
1090     }
1091
1092     pub fn emit_future_breakage_report(&self, diags: Vec<Diagnostic>) {
1093         self.inner.borrow_mut().emitter.emit_future_breakage_report(diags)
1094     }
1095
1096     pub fn emit_unused_externs(
1097         &self,
1098         lint_level: rustc_lint_defs::Level,
1099         loud: bool,
1100         unused_externs: &[&str],
1101     ) {
1102         let mut inner = self.inner.borrow_mut();
1103
1104         if loud && lint_level.is_error() {
1105             inner.bump_err_count();
1106         }
1107
1108         inner.emit_unused_externs(lint_level, unused_externs)
1109     }
1110
1111     pub fn update_unstable_expectation_id(
1112         &self,
1113         unstable_to_stable: &FxHashMap<LintExpectationId, LintExpectationId>,
1114     ) {
1115         let mut inner = self.inner.borrow_mut();
1116         let diags = std::mem::take(&mut inner.unstable_expect_diagnostics);
1117         inner.check_unstable_expect_diagnostics = true;
1118
1119         if !diags.is_empty() {
1120             inner.suppressed_expected_diag = true;
1121             for mut diag in diags.into_iter() {
1122                 diag.update_unstable_expectation_id(unstable_to_stable);
1123
1124                 // Here the diagnostic is given back to `emit_diagnostic` where it was first
1125                 // intercepted. Now it should be processed as usual, since the unstable expectation
1126                 // id is now stable.
1127                 inner.emit_diagnostic(&mut diag);
1128             }
1129         }
1130
1131         inner
1132             .stashed_diagnostics
1133             .values_mut()
1134             .for_each(|diag| diag.update_unstable_expectation_id(unstable_to_stable));
1135         inner
1136             .future_breakage_diagnostics
1137             .iter_mut()
1138             .for_each(|diag| diag.update_unstable_expectation_id(unstable_to_stable));
1139     }
1140
1141     /// This methods steals all [`LintExpectationId`]s that are stored inside
1142     /// [`HandlerInner`] and indicate that the linked expectation has been fulfilled.
1143     #[must_use]
1144     pub fn steal_fulfilled_expectation_ids(&self) -> FxHashSet<LintExpectationId> {
1145         assert!(
1146             self.inner.borrow().unstable_expect_diagnostics.is_empty(),
1147             "`HandlerInner::unstable_expect_diagnostics` should be empty at this point",
1148         );
1149         std::mem::take(&mut self.inner.borrow_mut().fulfilled_expectations)
1150     }
1151
1152     pub fn flush_delayed(&self) {
1153         let mut inner = self.inner.lock();
1154         let bugs = std::mem::replace(&mut inner.delayed_span_bugs, Vec::new());
1155         inner.flush_delayed(bugs, "no errors encountered even though `delay_span_bug` issued");
1156     }
1157 }
1158
1159 impl HandlerInner {
1160     fn must_teach(&mut self, code: &DiagnosticId) -> bool {
1161         self.taught_diagnostics.insert(code.clone())
1162     }
1163
1164     fn force_print_diagnostic(&mut self, mut db: Diagnostic) {
1165         self.emitter.emit_diagnostic(&mut db);
1166     }
1167
1168     /// Emit all stashed diagnostics.
1169     fn emit_stashed_diagnostics(&mut self) -> Option<ErrorGuaranteed> {
1170         let has_errors = self.has_errors();
1171         let diags = self.stashed_diagnostics.drain(..).map(|x| x.1).collect::<Vec<_>>();
1172         let mut reported = None;
1173         for mut diag in diags {
1174             // Decrement the count tracking the stash; emitting will increment it.
1175             if diag.is_error() {
1176                 if matches!(diag.level, Level::Error { lint: true }) {
1177                     self.lint_err_count -= 1;
1178                 } else {
1179                     self.err_count -= 1;
1180                 }
1181             } else {
1182                 if diag.is_force_warn() {
1183                     self.warn_count -= 1;
1184                 } else {
1185                     // Unless they're forced, don't flush stashed warnings when
1186                     // there are errors, to avoid causing warning overload. The
1187                     // stash would've been stolen already if it were important.
1188                     if has_errors {
1189                         continue;
1190                     }
1191                 }
1192             }
1193             let reported_this = self.emit_diagnostic(&mut diag);
1194             reported = reported.or(reported_this);
1195         }
1196         reported
1197     }
1198
1199     // FIXME(eddyb) this should ideally take `diagnostic` by value.
1200     fn emit_diagnostic(&mut self, diagnostic: &mut Diagnostic) -> Option<ErrorGuaranteed> {
1201         // The `LintExpectationId` can be stable or unstable depending on when it was created.
1202         // Diagnostics created before the definition of `HirId`s are unstable and can not yet
1203         // be stored. Instead, they are buffered until the `LintExpectationId` is replaced by
1204         // a stable one by the `LintLevelsBuilder`.
1205         if let Some(LintExpectationId::Unstable { .. }) = diagnostic.level.get_expectation_id() {
1206             self.unstable_expect_diagnostics.push(diagnostic.clone());
1207             return None;
1208         }
1209
1210         if diagnostic.level == Level::DelayedBug {
1211             // FIXME(eddyb) this should check for `has_errors` and stop pushing
1212             // once *any* errors were emitted (and truncate `delayed_span_bugs`
1213             // when an error is first emitted, also), but maybe there's a case
1214             // in which that's not sound? otherwise this is really inefficient.
1215             self.delayed_span_bugs.push(diagnostic.clone());
1216
1217             if !self.flags.report_delayed_bugs {
1218                 return Some(ErrorGuaranteed::unchecked_claim_error_was_emitted());
1219             }
1220         }
1221
1222         if diagnostic.has_future_breakage() {
1223             self.future_breakage_diagnostics.push(diagnostic.clone());
1224         }
1225
1226         if let Some(expectation_id) = diagnostic.level.get_expectation_id() {
1227             self.suppressed_expected_diag = true;
1228             self.fulfilled_expectations.insert(expectation_id.normalize());
1229         }
1230
1231         if matches!(diagnostic.level, Warning(_))
1232             && !self.flags.can_emit_warnings
1233             && !diagnostic.is_force_warn()
1234         {
1235             if diagnostic.has_future_breakage() {
1236                 (*TRACK_DIAGNOSTICS)(diagnostic);
1237             }
1238             return None;
1239         }
1240
1241         (*TRACK_DIAGNOSTICS)(diagnostic);
1242
1243         if matches!(diagnostic.level, Level::Expect(_) | Level::Allow) {
1244             return None;
1245         }
1246
1247         if let Some(ref code) = diagnostic.code {
1248             self.emitted_diagnostic_codes.insert(code.clone());
1249         }
1250
1251         let already_emitted = |this: &mut Self| {
1252             let mut hasher = StableHasher::new();
1253             diagnostic.hash(&mut hasher);
1254             let diagnostic_hash = hasher.finish();
1255             !this.emitted_diagnostics.insert(diagnostic_hash)
1256         };
1257
1258         // Only emit the diagnostic if we've been asked to deduplicate or
1259         // haven't already emitted an equivalent diagnostic.
1260         if !(self.flags.deduplicate_diagnostics && already_emitted(self)) {
1261             debug!(?diagnostic);
1262             debug!(?self.emitted_diagnostics);
1263             let already_emitted_sub = |sub: &mut SubDiagnostic| {
1264                 debug!(?sub);
1265                 if sub.level != Level::OnceNote {
1266                     return false;
1267                 }
1268                 let mut hasher = StableHasher::new();
1269                 sub.hash(&mut hasher);
1270                 let diagnostic_hash = hasher.finish();
1271                 debug!(?diagnostic_hash);
1272                 !self.emitted_diagnostics.insert(diagnostic_hash)
1273             };
1274
1275             diagnostic.children.drain_filter(already_emitted_sub).for_each(|_| {});
1276
1277             self.emitter.emit_diagnostic(&diagnostic);
1278             if diagnostic.is_error() {
1279                 self.deduplicated_err_count += 1;
1280             } else if let Warning(_) = diagnostic.level {
1281                 self.deduplicated_warn_count += 1;
1282             }
1283         }
1284         if diagnostic.is_error() {
1285             if matches!(diagnostic.level, Level::Error { lint: true }) {
1286                 self.bump_lint_err_count();
1287             } else {
1288                 self.bump_err_count();
1289             }
1290
1291             Some(ErrorGuaranteed::unchecked_claim_error_was_emitted())
1292         } else {
1293             self.bump_warn_count();
1294
1295             None
1296         }
1297     }
1298
1299     fn emit_artifact_notification(&mut self, path: &Path, artifact_type: &str) {
1300         self.emitter.emit_artifact_notification(path, artifact_type);
1301     }
1302
1303     fn emit_unused_externs(&mut self, lint_level: rustc_lint_defs::Level, unused_externs: &[&str]) {
1304         self.emitter.emit_unused_externs(lint_level, unused_externs);
1305     }
1306
1307     fn treat_err_as_bug(&self) -> bool {
1308         self.flags.treat_err_as_bug.map_or(false, |c| {
1309             self.err_count() + self.lint_err_count + self.delayed_bug_count() >= c.get()
1310         })
1311     }
1312
1313     fn delayed_bug_count(&self) -> usize {
1314         self.delayed_span_bugs.len() + self.delayed_good_path_bugs.len()
1315     }
1316
1317     fn print_error_count(&mut self, registry: &Registry) {
1318         self.emit_stashed_diagnostics();
1319
1320         let warnings = match self.deduplicated_warn_count {
1321             0 => String::new(),
1322             1 => "1 warning emitted".to_string(),
1323             count => format!("{count} warnings emitted"),
1324         };
1325         let errors = match self.deduplicated_err_count {
1326             0 => String::new(),
1327             1 => "aborting due to previous error".to_string(),
1328             count => format!("aborting due to {count} previous errors"),
1329         };
1330         if self.treat_err_as_bug() {
1331             return;
1332         }
1333
1334         match (errors.len(), warnings.len()) {
1335             (0, 0) => return,
1336             (0, _) => self.emitter.emit_diagnostic(&Diagnostic::new(
1337                 Level::Warning(None),
1338                 DiagnosticMessage::Str(warnings),
1339             )),
1340             (_, 0) => {
1341                 let _ = self.fatal(&errors);
1342             }
1343             (_, _) => {
1344                 let _ = self.fatal(&format!("{}; {}", &errors, &warnings));
1345             }
1346         }
1347
1348         let can_show_explain = self.emitter.should_show_explain();
1349         let are_there_diagnostics = !self.emitted_diagnostic_codes.is_empty();
1350         if can_show_explain && are_there_diagnostics {
1351             let mut error_codes = self
1352                 .emitted_diagnostic_codes
1353                 .iter()
1354                 .filter_map(|x| match &x {
1355                     DiagnosticId::Error(s)
1356                         if registry.try_find_description(s).map_or(false, |o| o.is_some()) =>
1357                     {
1358                         Some(s.clone())
1359                     }
1360                     _ => None,
1361                 })
1362                 .collect::<Vec<_>>();
1363             if !error_codes.is_empty() {
1364                 error_codes.sort();
1365                 if error_codes.len() > 1 {
1366                     let limit = if error_codes.len() > 9 { 9 } else { error_codes.len() };
1367                     self.failure(&format!(
1368                         "Some errors have detailed explanations: {}{}",
1369                         error_codes[..limit].join(", "),
1370                         if error_codes.len() > 9 { "..." } else { "." }
1371                     ));
1372                     self.failure(&format!(
1373                         "For more information about an error, try \
1374                          `rustc --explain {}`.",
1375                         &error_codes[0]
1376                     ));
1377                 } else {
1378                     self.failure(&format!(
1379                         "For more information about this error, try \
1380                          `rustc --explain {}`.",
1381                         &error_codes[0]
1382                     ));
1383                 }
1384             }
1385         }
1386     }
1387
1388     fn stash(&mut self, key: (Span, StashKey), diagnostic: Diagnostic) {
1389         // Track the diagnostic for counts, but don't panic-if-treat-err-as-bug
1390         // yet; that happens when we actually emit the diagnostic.
1391         if diagnostic.is_error() {
1392             if matches!(diagnostic.level, Level::Error { lint: true }) {
1393                 self.lint_err_count += 1;
1394             } else {
1395                 self.err_count += 1;
1396             }
1397         } else {
1398             // Warnings are only automatically flushed if they're forced.
1399             if diagnostic.is_force_warn() {
1400                 self.warn_count += 1;
1401             }
1402         }
1403
1404         // FIXME(Centril, #69537): Consider reintroducing panic on overwriting a stashed diagnostic
1405         // if/when we have a more robust macro-friendly replacement for `(span, key)` as a key.
1406         // See the PR for a discussion.
1407         self.stashed_diagnostics.insert(key, diagnostic);
1408     }
1409
1410     fn steal(&mut self, key: (Span, StashKey)) -> Option<Diagnostic> {
1411         let diagnostic = self.stashed_diagnostics.remove(&key)?;
1412         if diagnostic.is_error() {
1413             if matches!(diagnostic.level, Level::Error { lint: true }) {
1414                 self.lint_err_count -= 1;
1415             } else {
1416                 self.err_count -= 1;
1417             }
1418         } else {
1419             if diagnostic.is_force_warn() {
1420                 self.warn_count -= 1;
1421             }
1422         }
1423         Some(diagnostic)
1424     }
1425
1426     #[inline]
1427     fn err_count(&self) -> usize {
1428         self.err_count
1429     }
1430
1431     fn has_errors(&self) -> bool {
1432         self.err_count() > 0
1433     }
1434     fn has_errors_or_lint_errors(&self) -> bool {
1435         self.has_errors() || self.lint_err_count > 0
1436     }
1437     fn has_errors_or_delayed_span_bugs(&self) -> bool {
1438         self.has_errors() || !self.delayed_span_bugs.is_empty()
1439     }
1440     fn has_any_message(&self) -> bool {
1441         self.err_count() > 0 || self.lint_err_count > 0 || self.warn_count > 0
1442     }
1443
1444     fn abort_if_errors(&mut self) {
1445         self.emit_stashed_diagnostics();
1446
1447         if self.has_errors() {
1448             FatalError.raise();
1449         }
1450     }
1451
1452     fn span_bug(&mut self, sp: impl Into<MultiSpan>, msg: impl Into<DiagnosticMessage>) -> ! {
1453         self.emit_diag_at_span(Diagnostic::new(Bug, msg), sp);
1454         panic::panic_any(ExplicitBug);
1455     }
1456
1457     fn emit_diag_at_span(&mut self, mut diag: Diagnostic, sp: impl Into<MultiSpan>) {
1458         self.emit_diagnostic(diag.set_span(sp));
1459     }
1460
1461     #[track_caller]
1462     fn delay_span_bug(
1463         &mut self,
1464         sp: impl Into<MultiSpan>,
1465         msg: impl Into<DiagnosticMessage>,
1466     ) -> ErrorGuaranteed {
1467         // This is technically `self.treat_err_as_bug()` but `delay_span_bug` is called before
1468         // incrementing `err_count` by one, so we need to +1 the comparing.
1469         // FIXME: Would be nice to increment err_count in a more coherent way.
1470         if self.flags.treat_err_as_bug.map_or(false, |c| {
1471             self.err_count() + self.lint_err_count + self.delayed_bug_count() + 1 >= c.get()
1472         }) {
1473             // FIXME: don't abort here if report_delayed_bugs is off
1474             self.span_bug(sp, msg);
1475         }
1476         let mut diagnostic = Diagnostic::new(Level::DelayedBug, msg);
1477         diagnostic.set_span(sp.into());
1478         diagnostic.note(&format!("delayed at {}", std::panic::Location::caller()));
1479         self.emit_diagnostic(&mut diagnostic).unwrap()
1480     }
1481
1482     // FIXME(eddyb) note the comment inside `impl Drop for HandlerInner`, that's
1483     // where the explanation of what "good path" is (also, it should be renamed).
1484     fn delay_good_path_bug(&mut self, msg: impl Into<DiagnosticMessage>) {
1485         let mut diagnostic = Diagnostic::new(Level::DelayedBug, msg);
1486         if self.flags.report_delayed_bugs {
1487             self.emit_diagnostic(&mut diagnostic);
1488         }
1489         let backtrace = std::backtrace::Backtrace::force_capture();
1490         self.delayed_good_path_bugs.push(DelayedDiagnostic::with_backtrace(diagnostic, backtrace));
1491     }
1492
1493     fn failure(&mut self, msg: impl Into<DiagnosticMessage>) {
1494         self.emit_diagnostic(&mut Diagnostic::new(FailureNote, msg));
1495     }
1496
1497     fn fatal(&mut self, msg: impl Into<DiagnosticMessage>) -> FatalError {
1498         self.emit(Fatal, msg);
1499         FatalError
1500     }
1501
1502     fn err(&mut self, msg: impl Into<DiagnosticMessage>) -> ErrorGuaranteed {
1503         self.emit(Error { lint: false }, msg)
1504     }
1505
1506     /// Emit an error; level should be `Error` or `Fatal`.
1507     fn emit(&mut self, level: Level, msg: impl Into<DiagnosticMessage>) -> ErrorGuaranteed {
1508         if self.treat_err_as_bug() {
1509             self.bug(msg);
1510         }
1511         self.emit_diagnostic(&mut Diagnostic::new(level, msg)).unwrap()
1512     }
1513
1514     fn bug(&mut self, msg: impl Into<DiagnosticMessage>) -> ! {
1515         self.emit_diagnostic(&mut Diagnostic::new(Bug, msg));
1516         panic::panic_any(ExplicitBug);
1517     }
1518
1519     fn flush_delayed(
1520         &mut self,
1521         bugs: impl IntoIterator<Item = Diagnostic>,
1522         explanation: impl Into<DiagnosticMessage> + Copy,
1523     ) {
1524         let mut no_bugs = true;
1525         for mut bug in bugs {
1526             if no_bugs {
1527                 // Put the overall explanation before the `DelayedBug`s, to
1528                 // frame them better (e.g. separate warnings from them).
1529                 self.emit_diagnostic(&mut Diagnostic::new(Bug, explanation));
1530                 no_bugs = false;
1531             }
1532
1533             // "Undelay" the `DelayedBug`s (into plain `Bug`s).
1534             if bug.level != Level::DelayedBug {
1535                 // NOTE(eddyb) not panicking here because we're already producing
1536                 // an ICE, and the more information the merrier.
1537                 bug.note(&format!(
1538                     "`flushed_delayed` got diagnostic with level {:?}, \
1539                      instead of the expected `DelayedBug`",
1540                     bug.level,
1541                 ));
1542             }
1543             bug.level = Level::Bug;
1544
1545             self.emit_diagnostic(&mut bug);
1546         }
1547
1548         // Panic with `ExplicitBug` to avoid "unexpected panic" messages.
1549         if !no_bugs {
1550             panic::panic_any(ExplicitBug);
1551         }
1552     }
1553
1554     fn bump_lint_err_count(&mut self) {
1555         self.lint_err_count += 1;
1556         self.panic_if_treat_err_as_bug();
1557     }
1558
1559     fn bump_err_count(&mut self) {
1560         self.err_count += 1;
1561         self.panic_if_treat_err_as_bug();
1562     }
1563
1564     fn bump_warn_count(&mut self) {
1565         self.warn_count += 1;
1566     }
1567
1568     fn panic_if_treat_err_as_bug(&self) {
1569         if self.treat_err_as_bug() {
1570             match (
1571                 self.err_count() + self.lint_err_count,
1572                 self.delayed_bug_count(),
1573                 self.flags.treat_err_as_bug.map(|c| c.get()).unwrap_or(0),
1574             ) {
1575                 (1, 0, 1) => panic!("aborting due to `-Z treat-err-as-bug=1`"),
1576                 (0, 1, 1) => panic!("aborting due delayed bug with `-Z treat-err-as-bug=1`"),
1577                 (count, delayed_count, as_bug) => {
1578                     if delayed_count > 0 {
1579                         panic!(
1580                             "aborting after {} errors and {} delayed bugs due to `-Z treat-err-as-bug={}`",
1581                             count, delayed_count, as_bug,
1582                         )
1583                     } else {
1584                         panic!(
1585                             "aborting after {} errors due to `-Z treat-err-as-bug={}`",
1586                             count, as_bug,
1587                         )
1588                     }
1589                 }
1590             }
1591         }
1592     }
1593 }
1594
1595 struct DelayedDiagnostic {
1596     inner: Diagnostic,
1597     note: Backtrace,
1598 }
1599
1600 impl DelayedDiagnostic {
1601     fn with_backtrace(diagnostic: Diagnostic, backtrace: Backtrace) -> Self {
1602         DelayedDiagnostic { inner: diagnostic, note: backtrace }
1603     }
1604
1605     fn decorate(mut self) -> Diagnostic {
1606         self.inner.note(&format!("delayed at {}", self.note));
1607         self.inner
1608     }
1609 }
1610
1611 #[derive(Copy, PartialEq, Eq, Clone, Hash, Debug, Encodable, Decodable)]
1612 pub enum Level {
1613     Bug,
1614     DelayedBug,
1615     Fatal,
1616     Error {
1617         /// If this error comes from a lint, don't abort compilation even when abort_if_errors() is called.
1618         lint: bool,
1619     },
1620     /// This [`LintExpectationId`] is used for expected lint diagnostics, which should
1621     /// also emit a warning due to the `force-warn` flag. In all other cases this should
1622     /// be `None`.
1623     Warning(Option<LintExpectationId>),
1624     Note,
1625     /// A note that is only emitted once.
1626     OnceNote,
1627     Help,
1628     FailureNote,
1629     Allow,
1630     Expect(LintExpectationId),
1631 }
1632
1633 impl fmt::Display for Level {
1634     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1635         self.to_str().fmt(f)
1636     }
1637 }
1638
1639 impl Level {
1640     fn color(self) -> ColorSpec {
1641         let mut spec = ColorSpec::new();
1642         match self {
1643             Bug | DelayedBug | Fatal | Error { .. } => {
1644                 spec.set_fg(Some(Color::Red)).set_intense(true);
1645             }
1646             Warning(_) => {
1647                 spec.set_fg(Some(Color::Yellow)).set_intense(cfg!(windows));
1648             }
1649             Note | OnceNote => {
1650                 spec.set_fg(Some(Color::Green)).set_intense(true);
1651             }
1652             Help => {
1653                 spec.set_fg(Some(Color::Cyan)).set_intense(true);
1654             }
1655             FailureNote => {}
1656             Allow | Expect(_) => unreachable!(),
1657         }
1658         spec
1659     }
1660
1661     pub fn to_str(self) -> &'static str {
1662         match self {
1663             Bug | DelayedBug => "error: internal compiler error",
1664             Fatal | Error { .. } => "error",
1665             Warning(_) => "warning",
1666             Note | OnceNote => "note",
1667             Help => "help",
1668             FailureNote => "failure-note",
1669             Allow => panic!("Shouldn't call on allowed error"),
1670             Expect(_) => panic!("Shouldn't call on expected error"),
1671         }
1672     }
1673
1674     pub fn is_failure_note(&self) -> bool {
1675         matches!(*self, FailureNote)
1676     }
1677
1678     pub fn get_expectation_id(&self) -> Option<LintExpectationId> {
1679         match self {
1680             Level::Expect(id) | Level::Warning(Some(id)) => Some(*id),
1681             _ => None,
1682         }
1683     }
1684 }
1685
1686 // FIXME(eddyb) this doesn't belong here AFAICT, should be moved to callsite.
1687 pub fn add_elided_lifetime_in_path_suggestion(
1688     source_map: &SourceMap,
1689     diag: &mut Diagnostic,
1690     n: usize,
1691     path_span: Span,
1692     incl_angl_brckt: bool,
1693     insertion_span: Span,
1694 ) {
1695     diag.span_label(path_span, format!("expected lifetime parameter{}", pluralize!(n)));
1696     if !source_map.is_span_accessible(insertion_span) {
1697         // Do not try to suggest anything if generated by a proc-macro.
1698         return;
1699     }
1700     let anon_lts = vec!["'_"; n].join(", ");
1701     let suggestion =
1702         if incl_angl_brckt { format!("<{}>", anon_lts) } else { format!("{}, ", anon_lts) };
1703     diag.span_suggestion_verbose(
1704         insertion_span.shrink_to_hi(),
1705         &format!("indicate the anonymous lifetime{}", pluralize!(n)),
1706         suggestion,
1707         Applicability::MachineApplicable,
1708     );
1709 }
1710
1711 /// Useful type to use with `Result<>` indicate that an error has already
1712 /// been reported to the user, so no need to continue checking.
1713 #[derive(Clone, Copy, Debug, Encodable, Decodable, Hash, PartialEq, Eq, PartialOrd, Ord)]
1714 #[derive(HashStable_Generic)]
1715 pub struct ErrorGuaranteed(());
1716
1717 impl ErrorGuaranteed {
1718     /// To be used only if you really know what you are doing... ideally, we would find a way to
1719     /// eliminate all calls to this method.
1720     pub fn unchecked_claim_error_was_emitted() -> Self {
1721         ErrorGuaranteed(())
1722     }
1723 }