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