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