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