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