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