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