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