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