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