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