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