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