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