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