]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_errors/src/lib.rs
Rollup merge of #92021 - woodenarrow:br_single_fp_element, 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(let_else)]
10 #![feature(nll)]
11
12 #[macro_use]
13 extern crate rustc_macros;
14
15 #[macro_use]
16 extern crate tracing;
17
18 pub use emitter::ColorConfig;
19
20 use Level::*;
21
22 use emitter::{is_case_difference, Emitter, EmitterWriter};
23 use registry::Registry;
24 use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
25 use rustc_data_structures::stable_hasher::StableHasher;
26 use rustc_data_structures::sync::{self, Lock, Lrc};
27 use rustc_data_structures::AtomicRef;
28 pub use rustc_lint_defs::{pluralize, Applicability};
29 use rustc_serialize::json::Json;
30 use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
31 use rustc_span::source_map::SourceMap;
32 use rustc_span::{Loc, MultiSpan, Span};
33
34 use std::borrow::Cow;
35 use std::hash::{Hash, Hasher};
36 use std::num::NonZeroUsize;
37 use std::panic;
38 use std::path::Path;
39 use std::{error, fmt};
40
41 use termcolor::{Color, ColorSpec};
42
43 pub mod annotate_snippet_emitter_writer;
44 mod diagnostic;
45 mod diagnostic_builder;
46 pub mod emitter;
47 pub mod json;
48 mod lock;
49 pub mod registry;
50 mod snippet;
51 mod styled_buffer;
52 pub use snippet::Style;
53
54 pub type PResult<'a, T> = Result<T, DiagnosticBuilder<'a>>;
55
56 // `PResult` is used a lot. Make sure it doesn't unintentionally get bigger.
57 // (See also the comment on `DiagnosticBuilder`'s `diagnostic` field.)
58 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
59 rustc_data_structures::static_assert_size!(PResult<'_, ()>, 16);
60 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
61 rustc_data_structures::static_assert_size!(PResult<'_, bool>, 24);
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) -> Self {
105         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 lint errors that have been emitted.
415     lint_err_count: usize,
416     /// The number of errors that have been emitted, including duplicates.
417     ///
418     /// This is not necessarily the count that's reported to the user once
419     /// compilation ends.
420     err_count: usize,
421     warn_count: usize,
422     deduplicated_err_count: usize,
423     emitter: Box<dyn Emitter + sync::Send>,
424     delayed_span_bugs: Vec<Diagnostic>,
425     delayed_good_path_bugs: Vec<DelayedDiagnostic>,
426
427     /// This set contains the `DiagnosticId` of all emitted diagnostics to avoid
428     /// emitting the same diagnostic with extended help (`--teach`) twice, which
429     /// would be unnecessary repetition.
430     taught_diagnostics: FxHashSet<DiagnosticId>,
431
432     /// Used to suggest rustc --explain <error code>
433     emitted_diagnostic_codes: FxHashSet<DiagnosticId>,
434
435     /// This set contains a hash of every diagnostic that has been emitted by
436     /// this handler. These hashes is used to avoid emitting the same error
437     /// twice.
438     emitted_diagnostics: FxHashSet<u128>,
439
440     /// Stashed diagnostics emitted in one stage of the compiler that may be
441     /// stolen by other stages (e.g. to improve them and add more information).
442     /// The stashed diagnostics count towards the total error count.
443     /// When `.abort_if_errors()` is called, these are also emitted.
444     stashed_diagnostics: FxIndexMap<(Span, StashKey), Diagnostic>,
445
446     /// The warning count, used for a recap upon finishing
447     deduplicated_warn_count: usize,
448
449     future_breakage_diagnostics: Vec<Diagnostic>,
450 }
451
452 /// A key denoting where from a diagnostic was stashed.
453 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
454 pub enum StashKey {
455     ItemNoType,
456 }
457
458 fn default_track_diagnostic(_: &Diagnostic) {}
459
460 pub static TRACK_DIAGNOSTICS: AtomicRef<fn(&Diagnostic)> =
461     AtomicRef::new(&(default_track_diagnostic as fn(&_)));
462
463 #[derive(Copy, Clone, Default)]
464 pub struct HandlerFlags {
465     /// If false, warning-level lints are suppressed.
466     /// (rustc: see `--allow warnings` and `--cap-lints`)
467     pub can_emit_warnings: bool,
468     /// If true, error-level diagnostics are upgraded to bug-level.
469     /// (rustc: see `-Z treat-err-as-bug`)
470     pub treat_err_as_bug: Option<NonZeroUsize>,
471     /// If true, immediately emit diagnostics that would otherwise be buffered.
472     /// (rustc: see `-Z dont-buffer-diagnostics` and `-Z treat-err-as-bug`)
473     pub dont_buffer_diagnostics: bool,
474     /// If true, immediately print bugs registered with `delay_span_bug`.
475     /// (rustc: see `-Z report-delayed-bugs`)
476     pub report_delayed_bugs: bool,
477     /// Show macro backtraces.
478     /// (rustc: see `-Z macro-backtrace`)
479     pub macro_backtrace: bool,
480     /// If true, identical diagnostics are reported only once.
481     pub deduplicate_diagnostics: bool,
482 }
483
484 impl Drop for HandlerInner {
485     fn drop(&mut self) {
486         self.emit_stashed_diagnostics();
487
488         if !self.has_errors() {
489             let bugs = std::mem::replace(&mut self.delayed_span_bugs, Vec::new());
490             self.flush_delayed(bugs, "no errors encountered even though `delay_span_bug` issued");
491         }
492
493         if !self.has_any_message() {
494             let bugs = std::mem::replace(&mut self.delayed_good_path_bugs, Vec::new());
495             self.flush_delayed(
496                 bugs.into_iter().map(DelayedDiagnostic::decorate).collect(),
497                 "no warnings or errors encountered even though `delayed_good_path_bugs` issued",
498             );
499         }
500     }
501 }
502
503 impl Handler {
504     pub fn with_tty_emitter(
505         color_config: ColorConfig,
506         can_emit_warnings: bool,
507         treat_err_as_bug: Option<NonZeroUsize>,
508         sm: Option<Lrc<SourceMap>>,
509     ) -> Self {
510         Self::with_tty_emitter_and_flags(
511             color_config,
512             sm,
513             HandlerFlags { can_emit_warnings, treat_err_as_bug, ..Default::default() },
514         )
515     }
516
517     pub fn with_tty_emitter_and_flags(
518         color_config: ColorConfig,
519         sm: Option<Lrc<SourceMap>>,
520         flags: HandlerFlags,
521     ) -> Self {
522         let emitter = Box::new(EmitterWriter::stderr(
523             color_config,
524             sm,
525             false,
526             false,
527             None,
528             flags.macro_backtrace,
529         ));
530         Self::with_emitter_and_flags(emitter, flags)
531     }
532
533     pub fn with_emitter(
534         can_emit_warnings: bool,
535         treat_err_as_bug: Option<NonZeroUsize>,
536         emitter: Box<dyn Emitter + sync::Send>,
537     ) -> Self {
538         Handler::with_emitter_and_flags(
539             emitter,
540             HandlerFlags { can_emit_warnings, treat_err_as_bug, ..Default::default() },
541         )
542     }
543
544     pub fn with_emitter_and_flags(
545         emitter: Box<dyn Emitter + sync::Send>,
546         flags: HandlerFlags,
547     ) -> Self {
548         Self {
549             flags,
550             inner: Lock::new(HandlerInner {
551                 flags,
552                 lint_err_count: 0,
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             }),
566         }
567     }
568
569     // This is here to not allow mutation of flags;
570     // as of this writing it's only used in tests in librustc_middle.
571     pub fn can_emit_warnings(&self) -> bool {
572         self.flags.can_emit_warnings
573     }
574
575     /// Resets the diagnostic error count as well as the cached emitted diagnostics.
576     ///
577     /// NOTE: *do not* call this function from rustc. It is only meant to be called from external
578     /// tools that want to reuse a `Parser` cleaning the previously emitted diagnostics as well as
579     /// the overall count of emitted error diagnostics.
580     pub fn reset_err_count(&self) {
581         let mut inner = self.inner.borrow_mut();
582         inner.err_count = 0;
583         inner.warn_count = 0;
584         inner.deduplicated_err_count = 0;
585         inner.deduplicated_warn_count = 0;
586
587         // actually free the underlying memory (which `clear` would not do)
588         inner.delayed_span_bugs = Default::default();
589         inner.delayed_good_path_bugs = Default::default();
590         inner.taught_diagnostics = Default::default();
591         inner.emitted_diagnostic_codes = Default::default();
592         inner.emitted_diagnostics = Default::default();
593         inner.stashed_diagnostics = Default::default();
594     }
595
596     /// Stash a given diagnostic with the given `Span` and `StashKey` as the key for later stealing.
597     pub fn stash_diagnostic(&self, span: Span, key: StashKey, diag: Diagnostic) {
598         let mut inner = self.inner.borrow_mut();
599         // FIXME(Centril, #69537): Consider reintroducing panic on overwriting a stashed diagnostic
600         // if/when we have a more robust macro-friendly replacement for `(span, key)` as a key.
601         // See the PR for a discussion.
602         inner.stashed_diagnostics.insert((span, key), diag);
603     }
604
605     /// Steal a previously stashed diagnostic with the given `Span` and `StashKey` as the key.
606     pub fn steal_diagnostic(&self, span: Span, key: StashKey) -> Option<DiagnosticBuilder<'_>> {
607         self.inner
608             .borrow_mut()
609             .stashed_diagnostics
610             .remove(&(span, key))
611             .map(|diag| DiagnosticBuilder::new_diagnostic(self, diag))
612     }
613
614     /// Emit all stashed diagnostics.
615     pub fn emit_stashed_diagnostics(&self) {
616         self.inner.borrow_mut().emit_stashed_diagnostics();
617     }
618
619     /// Construct a dummy builder with `Level::Cancelled`.
620     ///
621     /// Using this will neither report anything to the user (e.g. a warning),
622     /// nor will compilation cancel as a result.
623     pub fn struct_dummy(&self) -> DiagnosticBuilder<'_> {
624         DiagnosticBuilder::new(self, Level::Cancelled, "")
625     }
626
627     /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
628     ///
629     /// The builder will be canceled if warnings cannot be emitted.
630     pub fn struct_span_warn(&self, span: impl Into<MultiSpan>, msg: &str) -> DiagnosticBuilder<'_> {
631         let mut result = self.struct_warn(msg);
632         result.set_span(span);
633         result
634     }
635
636     /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
637     ///
638     /// This will "force" the warning meaning it will not be canceled even
639     /// if warnings cannot be emitted.
640     pub fn struct_span_force_warn(
641         &self,
642         span: impl Into<MultiSpan>,
643         msg: &str,
644     ) -> DiagnosticBuilder<'_> {
645         let mut result = self.struct_force_warn(msg);
646         result.set_span(span);
647         result
648     }
649
650     /// Construct a builder at the `Allow` level at the given `span` and with the `msg`.
651     pub fn struct_span_allow(
652         &self,
653         span: impl Into<MultiSpan>,
654         msg: &str,
655     ) -> DiagnosticBuilder<'_> {
656         let mut result = self.struct_allow(msg);
657         result.set_span(span);
658         result
659     }
660
661     /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
662     /// Also include a code.
663     pub fn struct_span_warn_with_code(
664         &self,
665         span: impl Into<MultiSpan>,
666         msg: &str,
667         code: DiagnosticId,
668     ) -> DiagnosticBuilder<'_> {
669         let mut result = self.struct_span_warn(span, msg);
670         result.code(code);
671         result
672     }
673
674     /// Construct a builder at the `Warning` level with the `msg`.
675     ///
676     /// The builder will be canceled if warnings cannot be emitted.
677     pub fn struct_warn(&self, msg: &str) -> DiagnosticBuilder<'_> {
678         let mut result = DiagnosticBuilder::new(self, Level::Warning, msg);
679         if !self.flags.can_emit_warnings {
680             result.cancel();
681         }
682         result
683     }
684
685     /// Construct a builder at the `Warning` level with the `msg`.
686     ///
687     /// This will "force" a warning meaning it will not be canceled even
688     /// if warnings cannot be emitted.
689     pub fn struct_force_warn(&self, msg: &str) -> DiagnosticBuilder<'_> {
690         DiagnosticBuilder::new(self, Level::Warning, msg)
691     }
692
693     /// Construct a builder at the `Allow` level with the `msg`.
694     pub fn struct_allow(&self, msg: &str) -> DiagnosticBuilder<'_> {
695         DiagnosticBuilder::new(self, Level::Allow, msg)
696     }
697
698     /// Construct a builder at the `Error` level at the given `span` and with the `msg`.
699     pub fn struct_span_err(&self, span: impl Into<MultiSpan>, msg: &str) -> DiagnosticBuilder<'_> {
700         let mut result = self.struct_err(msg);
701         result.set_span(span);
702         result
703     }
704
705     /// Construct a builder at the `Error` level at the given `span`, with the `msg`, and `code`.
706     pub fn struct_span_err_with_code(
707         &self,
708         span: impl Into<MultiSpan>,
709         msg: &str,
710         code: DiagnosticId,
711     ) -> DiagnosticBuilder<'_> {
712         let mut result = self.struct_span_err(span, msg);
713         result.code(code);
714         result
715     }
716
717     /// Construct a builder at the `Error` level with the `msg`.
718     // FIXME: This method should be removed (every error should have an associated error code).
719     pub fn struct_err(&self, msg: &str) -> DiagnosticBuilder<'_> {
720         DiagnosticBuilder::new(self, Level::Error { lint: false }, msg)
721     }
722
723     /// This should only be used by `rustc_middle::lint::struct_lint_level`. Do not use it for hard errors.
724     #[doc(hidden)]
725     pub fn struct_err_lint(&self, msg: &str) -> DiagnosticBuilder<'_> {
726         DiagnosticBuilder::new(self, Level::Error { lint: true }, msg)
727     }
728
729     /// Construct a builder at the `Error` level with the `msg` and the `code`.
730     pub fn struct_err_with_code(&self, msg: &str, code: DiagnosticId) -> DiagnosticBuilder<'_> {
731         let mut result = self.struct_err(msg);
732         result.code(code);
733         result
734     }
735
736     /// Construct a builder at the `Fatal` level at the given `span` and with the `msg`.
737     pub fn struct_span_fatal(
738         &self,
739         span: impl Into<MultiSpan>,
740         msg: &str,
741     ) -> DiagnosticBuilder<'_> {
742         let mut result = self.struct_fatal(msg);
743         result.set_span(span);
744         result
745     }
746
747     /// Construct a builder at the `Fatal` level at the given `span`, with the `msg`, and `code`.
748     pub fn struct_span_fatal_with_code(
749         &self,
750         span: impl Into<MultiSpan>,
751         msg: &str,
752         code: DiagnosticId,
753     ) -> DiagnosticBuilder<'_> {
754         let mut result = self.struct_span_fatal(span, msg);
755         result.code(code);
756         result
757     }
758
759     /// Construct a builder at the `Error` level with the `msg`.
760     pub fn struct_fatal(&self, msg: &str) -> DiagnosticBuilder<'_> {
761         DiagnosticBuilder::new(self, Level::Fatal, msg)
762     }
763
764     /// Construct a builder at the `Help` level with the `msg`.
765     pub fn struct_help(&self, msg: &str) -> DiagnosticBuilder<'_> {
766         DiagnosticBuilder::new(self, Level::Help, msg)
767     }
768
769     /// Construct a builder at the `Note` level with the `msg`.
770     pub fn struct_note_without_error(&self, msg: &str) -> DiagnosticBuilder<'_> {
771         DiagnosticBuilder::new(self, Level::Note, msg)
772     }
773
774     pub fn span_fatal(&self, span: impl Into<MultiSpan>, msg: &str) -> ! {
775         self.emit_diag_at_span(Diagnostic::new(Fatal, msg), span);
776         FatalError.raise()
777     }
778
779     pub fn span_fatal_with_code(
780         &self,
781         span: impl Into<MultiSpan>,
782         msg: &str,
783         code: DiagnosticId,
784     ) -> ! {
785         self.emit_diag_at_span(Diagnostic::new_with_code(Fatal, Some(code), msg), span);
786         FatalError.raise()
787     }
788
789     pub fn span_err(&self, span: impl Into<MultiSpan>, msg: &str) {
790         self.emit_diag_at_span(Diagnostic::new(Error { lint: false }, msg), span);
791     }
792
793     pub fn span_err_with_code(&self, span: impl Into<MultiSpan>, msg: &str, code: DiagnosticId) {
794         self.emit_diag_at_span(
795             Diagnostic::new_with_code(Error { lint: false }, Some(code), msg),
796             span,
797         );
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_lint_errors(&self) -> bool {
866         self.inner.borrow().has_errors_or_lint_errors()
867     }
868     pub fn has_errors_or_delayed_span_bugs(&self) -> bool {
869         self.inner.borrow().has_errors_or_delayed_span_bugs()
870     }
871
872     pub fn print_error_count(&self, registry: &Registry) {
873         self.inner.borrow_mut().print_error_count(registry)
874     }
875
876     pub fn take_future_breakage_diagnostics(&self) -> Vec<Diagnostic> {
877         std::mem::take(&mut self.inner.borrow_mut().future_breakage_diagnostics)
878     }
879
880     pub fn abort_if_errors(&self) {
881         self.inner.borrow_mut().abort_if_errors()
882     }
883
884     /// `true` if we haven't taught a diagnostic with this code already.
885     /// The caller must then teach the user about such a diagnostic.
886     ///
887     /// Used to suppress emitting the same error multiple times with extended explanation when
888     /// calling `-Zteach`.
889     pub fn must_teach(&self, code: &DiagnosticId) -> bool {
890         self.inner.borrow_mut().must_teach(code)
891     }
892
893     pub fn force_print_diagnostic(&self, db: Diagnostic) {
894         self.inner.borrow_mut().force_print_diagnostic(db)
895     }
896
897     pub fn emit_diagnostic(&self, diagnostic: &Diagnostic) {
898         self.inner.borrow_mut().emit_diagnostic(diagnostic)
899     }
900
901     fn emit_diag_at_span(&self, mut diag: Diagnostic, sp: impl Into<MultiSpan>) {
902         let mut inner = self.inner.borrow_mut();
903         inner.emit_diagnostic(diag.set_span(sp));
904     }
905
906     pub fn emit_artifact_notification(&self, path: &Path, artifact_type: &str) {
907         self.inner.borrow_mut().emit_artifact_notification(path, artifact_type)
908     }
909
910     pub fn emit_future_breakage_report(&self, diags: Vec<Diagnostic>) {
911         self.inner.borrow_mut().emitter.emit_future_breakage_report(diags)
912     }
913
914     pub fn emit_unused_externs(&self, lint_level: &str, unused_externs: &[&str]) {
915         self.inner.borrow_mut().emit_unused_externs(lint_level, unused_externs)
916     }
917
918     pub fn delay_as_bug(&self, diagnostic: Diagnostic) {
919         self.inner.borrow_mut().delay_as_bug(diagnostic)
920     }
921 }
922
923 impl HandlerInner {
924     fn must_teach(&mut self, code: &DiagnosticId) -> bool {
925         self.taught_diagnostics.insert(code.clone())
926     }
927
928     fn force_print_diagnostic(&mut self, db: Diagnostic) {
929         self.emitter.emit_diagnostic(&db);
930     }
931
932     /// Emit all stashed diagnostics.
933     fn emit_stashed_diagnostics(&mut self) {
934         let diags = self.stashed_diagnostics.drain(..).map(|x| x.1).collect::<Vec<_>>();
935         diags.iter().for_each(|diag| self.emit_diagnostic(diag));
936     }
937
938     fn emit_diagnostic(&mut self, diagnostic: &Diagnostic) {
939         if diagnostic.cancelled() {
940             return;
941         }
942
943         if diagnostic.has_future_breakage() {
944             self.future_breakage_diagnostics.push(diagnostic.clone());
945         }
946
947         if diagnostic.level == Warning
948             && !self.flags.can_emit_warnings
949             && !diagnostic.is_force_warn()
950         {
951             if diagnostic.has_future_breakage() {
952                 (*TRACK_DIAGNOSTICS)(diagnostic);
953             }
954             return;
955         }
956
957         (*TRACK_DIAGNOSTICS)(diagnostic);
958
959         if diagnostic.level == Allow {
960             return;
961         }
962
963         if let Some(ref code) = diagnostic.code {
964             self.emitted_diagnostic_codes.insert(code.clone());
965         }
966
967         let already_emitted = |this: &mut Self| {
968             let mut hasher = StableHasher::new();
969             diagnostic.hash(&mut hasher);
970             let diagnostic_hash = hasher.finish();
971             !this.emitted_diagnostics.insert(diagnostic_hash)
972         };
973
974         // Only emit the diagnostic if we've been asked to deduplicate and
975         // haven't already emitted an equivalent diagnostic.
976         if !(self.flags.deduplicate_diagnostics && already_emitted(self)) {
977             self.emitter.emit_diagnostic(diagnostic);
978             if diagnostic.is_error() {
979                 self.deduplicated_err_count += 1;
980             } else if diagnostic.level == Warning {
981                 self.deduplicated_warn_count += 1;
982             }
983         }
984         if diagnostic.is_error() {
985             if matches!(diagnostic.level, Level::Error { lint: true }) {
986                 self.bump_lint_err_count();
987             } else {
988                 self.bump_err_count();
989             }
990         } else {
991             self.bump_warn_count();
992         }
993     }
994
995     fn emit_artifact_notification(&mut self, path: &Path, artifact_type: &str) {
996         self.emitter.emit_artifact_notification(path, artifact_type);
997     }
998
999     fn emit_unused_externs(&mut self, lint_level: &str, unused_externs: &[&str]) {
1000         self.emitter.emit_unused_externs(lint_level, unused_externs);
1001     }
1002
1003     fn treat_err_as_bug(&self) -> bool {
1004         self.flags
1005             .treat_err_as_bug
1006             .map_or(false, |c| self.err_count() + self.lint_err_count >= c.get())
1007     }
1008
1009     fn print_error_count(&mut self, registry: &Registry) {
1010         self.emit_stashed_diagnostics();
1011
1012         let warnings = match self.deduplicated_warn_count {
1013             0 => String::new(),
1014             1 => "1 warning emitted".to_string(),
1015             count => format!("{} warnings emitted", count),
1016         };
1017         let errors = match self.deduplicated_err_count {
1018             0 => String::new(),
1019             1 => "aborting due to previous error".to_string(),
1020             count => format!("aborting due to {} previous errors", count),
1021         };
1022         if self.treat_err_as_bug() {
1023             return;
1024         }
1025
1026         match (errors.len(), warnings.len()) {
1027             (0, 0) => return,
1028             (0, _) => self.emitter.emit_diagnostic(&Diagnostic::new(Level::Warning, &warnings)),
1029             (_, 0) => {
1030                 let _ = self.fatal(&errors);
1031             }
1032             (_, _) => {
1033                 let _ = self.fatal(&format!("{}; {}", &errors, &warnings));
1034             }
1035         }
1036
1037         let can_show_explain = self.emitter.should_show_explain();
1038         let are_there_diagnostics = !self.emitted_diagnostic_codes.is_empty();
1039         if can_show_explain && are_there_diagnostics {
1040             let mut error_codes = self
1041                 .emitted_diagnostic_codes
1042                 .iter()
1043                 .filter_map(|x| match &x {
1044                     DiagnosticId::Error(s)
1045                         if registry.try_find_description(s).map_or(false, |o| o.is_some()) =>
1046                     {
1047                         Some(s.clone())
1048                     }
1049                     _ => None,
1050                 })
1051                 .collect::<Vec<_>>();
1052             if !error_codes.is_empty() {
1053                 error_codes.sort();
1054                 if error_codes.len() > 1 {
1055                     let limit = if error_codes.len() > 9 { 9 } else { error_codes.len() };
1056                     self.failure(&format!(
1057                         "Some errors have detailed explanations: {}{}",
1058                         error_codes[..limit].join(", "),
1059                         if error_codes.len() > 9 { "..." } else { "." }
1060                     ));
1061                     self.failure(&format!(
1062                         "For more information about an error, try \
1063                          `rustc --explain {}`.",
1064                         &error_codes[0]
1065                     ));
1066                 } else {
1067                     self.failure(&format!(
1068                         "For more information about this error, try \
1069                          `rustc --explain {}`.",
1070                         &error_codes[0]
1071                     ));
1072                 }
1073             }
1074         }
1075     }
1076
1077     #[inline]
1078     fn err_count(&self) -> usize {
1079         self.err_count + self.stashed_diagnostics.len()
1080     }
1081
1082     fn has_errors(&self) -> bool {
1083         self.err_count() > 0
1084     }
1085     fn has_errors_or_lint_errors(&self) -> bool {
1086         self.has_errors() || self.lint_err_count > 0
1087     }
1088     fn has_errors_or_delayed_span_bugs(&self) -> bool {
1089         self.has_errors() || !self.delayed_span_bugs.is_empty()
1090     }
1091     fn has_any_message(&self) -> bool {
1092         self.err_count() > 0 || self.lint_err_count > 0 || self.warn_count > 0
1093     }
1094
1095     fn abort_if_errors(&mut self) {
1096         self.emit_stashed_diagnostics();
1097
1098         if self.has_errors() {
1099             FatalError.raise();
1100         }
1101     }
1102
1103     fn span_bug(&mut self, sp: impl Into<MultiSpan>, msg: &str) -> ! {
1104         self.emit_diag_at_span(Diagnostic::new(Bug, msg), sp);
1105         panic::panic_any(ExplicitBug);
1106     }
1107
1108     fn emit_diag_at_span(&mut self, mut diag: Diagnostic, sp: impl Into<MultiSpan>) {
1109         self.emit_diagnostic(diag.set_span(sp));
1110     }
1111
1112     #[track_caller]
1113     fn delay_span_bug(&mut self, sp: impl Into<MultiSpan>, msg: &str) {
1114         // This is technically `self.treat_err_as_bug()` but `delay_span_bug` is called before
1115         // incrementing `err_count` by one, so we need to +1 the comparing.
1116         // FIXME: Would be nice to increment err_count in a more coherent way.
1117         if self.flags.treat_err_as_bug.map_or(false, |c| self.err_count() + 1 >= c.get()) {
1118             // FIXME: don't abort here if report_delayed_bugs is off
1119             self.span_bug(sp, msg);
1120         }
1121         let mut diagnostic = Diagnostic::new(Level::Bug, msg);
1122         diagnostic.set_span(sp.into());
1123         diagnostic.note(&format!("delayed at {}", std::panic::Location::caller()));
1124         self.delay_as_bug(diagnostic)
1125     }
1126
1127     fn delay_good_path_bug(&mut self, msg: &str) {
1128         let diagnostic = Diagnostic::new(Level::Bug, msg);
1129         if self.flags.report_delayed_bugs {
1130             self.emit_diagnostic(&diagnostic);
1131         }
1132         let backtrace = std::backtrace::Backtrace::force_capture();
1133         self.delayed_good_path_bugs.push(DelayedDiagnostic::with_backtrace(diagnostic, backtrace));
1134     }
1135
1136     fn failure(&mut self, msg: &str) {
1137         self.emit_diagnostic(&Diagnostic::new(FailureNote, msg));
1138     }
1139
1140     fn fatal(&mut self, msg: &str) -> FatalError {
1141         self.emit_error(Fatal, msg);
1142         FatalError
1143     }
1144
1145     fn err(&mut self, msg: &str) {
1146         self.emit_error(Error { lint: false }, msg);
1147     }
1148
1149     /// Emit an error; level should be `Error` or `Fatal`.
1150     fn emit_error(&mut self, level: Level, msg: &str) {
1151         if self.treat_err_as_bug() {
1152             self.bug(msg);
1153         }
1154         self.emit_diagnostic(&Diagnostic::new(level, msg));
1155     }
1156
1157     fn bug(&mut self, msg: &str) -> ! {
1158         self.emit_diagnostic(&Diagnostic::new(Bug, msg));
1159         panic::panic_any(ExplicitBug);
1160     }
1161
1162     fn delay_as_bug(&mut self, diagnostic: Diagnostic) {
1163         if self.flags.report_delayed_bugs {
1164             self.emit_diagnostic(&diagnostic);
1165         }
1166         self.delayed_span_bugs.push(diagnostic);
1167     }
1168
1169     fn flush_delayed(&mut self, bugs: Vec<Diagnostic>, explanation: &str) {
1170         let has_bugs = !bugs.is_empty();
1171         for bug in bugs {
1172             self.emit_diagnostic(&bug);
1173         }
1174         if has_bugs {
1175             panic!("{}", explanation);
1176         }
1177     }
1178
1179     fn bump_lint_err_count(&mut self) {
1180         self.lint_err_count += 1;
1181         self.panic_if_treat_err_as_bug();
1182     }
1183
1184     fn bump_err_count(&mut self) {
1185         self.err_count += 1;
1186         self.panic_if_treat_err_as_bug();
1187     }
1188
1189     fn bump_warn_count(&mut self) {
1190         self.warn_count += 1;
1191     }
1192
1193     fn panic_if_treat_err_as_bug(&self) {
1194         if self.treat_err_as_bug() {
1195             match (
1196                 self.err_count() + self.lint_err_count,
1197                 self.flags.treat_err_as_bug.map(|c| c.get()).unwrap_or(0),
1198             ) {
1199                 (1, 1) => panic!("aborting due to `-Z treat-err-as-bug=1`"),
1200                 (0, _) | (1, _) => {}
1201                 (count, as_bug) => panic!(
1202                     "aborting after {} errors due to `-Z treat-err-as-bug={}`",
1203                     count, as_bug,
1204                 ),
1205             }
1206         }
1207     }
1208 }
1209
1210 struct DelayedDiagnostic {
1211     inner: Diagnostic,
1212     note: Backtrace,
1213 }
1214
1215 impl DelayedDiagnostic {
1216     fn with_backtrace(diagnostic: Diagnostic, backtrace: Backtrace) -> Self {
1217         DelayedDiagnostic { inner: diagnostic, note: backtrace }
1218     }
1219
1220     fn decorate(mut self) -> Diagnostic {
1221         self.inner.note(&format!("delayed at {}", self.note));
1222         self.inner
1223     }
1224 }
1225
1226 #[derive(Copy, PartialEq, Clone, Hash, Debug, Encodable, Decodable)]
1227 pub enum Level {
1228     Bug,
1229     Fatal,
1230     Error {
1231         /// If this error comes from a lint, don't abort compilation even when abort_if_errors() is called.
1232         lint: bool,
1233     },
1234     Warning,
1235     Note,
1236     Help,
1237     Cancelled,
1238     FailureNote,
1239     Allow,
1240 }
1241
1242 impl fmt::Display for Level {
1243     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1244         self.to_str().fmt(f)
1245     }
1246 }
1247
1248 impl Level {
1249     fn color(self) -> ColorSpec {
1250         let mut spec = ColorSpec::new();
1251         match self {
1252             Bug | Fatal | Error { .. } => {
1253                 spec.set_fg(Some(Color::Red)).set_intense(true);
1254             }
1255             Warning => {
1256                 spec.set_fg(Some(Color::Yellow)).set_intense(cfg!(windows));
1257             }
1258             Note => {
1259                 spec.set_fg(Some(Color::Green)).set_intense(true);
1260             }
1261             Help => {
1262                 spec.set_fg(Some(Color::Cyan)).set_intense(true);
1263             }
1264             FailureNote => {}
1265             Allow | Cancelled => unreachable!(),
1266         }
1267         spec
1268     }
1269
1270     pub fn to_str(self) -> &'static str {
1271         match self {
1272             Bug => "error: internal compiler error",
1273             Fatal | Error { .. } => "error",
1274             Warning => "warning",
1275             Note => "note",
1276             Help => "help",
1277             FailureNote => "failure-note",
1278             Cancelled => panic!("Shouldn't call on cancelled error"),
1279             Allow => panic!("Shouldn't call on allowed error"),
1280         }
1281     }
1282
1283     pub fn is_failure_note(&self) -> bool {
1284         matches!(*self, FailureNote)
1285     }
1286 }
1287
1288 pub fn add_elided_lifetime_in_path_suggestion(
1289     source_map: &SourceMap,
1290     db: &mut DiagnosticBuilder<'_>,
1291     n: usize,
1292     path_span: Span,
1293     incl_angl_brckt: bool,
1294     insertion_span: Span,
1295     anon_lts: String,
1296 ) {
1297     let (replace_span, suggestion) = if incl_angl_brckt {
1298         (insertion_span, anon_lts)
1299     } else {
1300         // When possible, prefer a suggestion that replaces the whole
1301         // `Path<T>` expression with `Path<'_, T>`, rather than inserting `'_, `
1302         // at a point (which makes for an ugly/confusing label)
1303         if let Ok(snippet) = source_map.span_to_snippet(path_span) {
1304             // But our spans can get out of whack due to macros; if the place we think
1305             // we want to insert `'_` isn't even within the path expression's span, we
1306             // should bail out of making any suggestion rather than panicking on a
1307             // subtract-with-overflow or string-slice-out-out-bounds (!)
1308             // FIXME: can we do better?
1309             if insertion_span.lo().0 < path_span.lo().0 {
1310                 return;
1311             }
1312             let insertion_index = (insertion_span.lo().0 - path_span.lo().0) as usize;
1313             if insertion_index > snippet.len() {
1314                 return;
1315             }
1316             let (before, after) = snippet.split_at(insertion_index);
1317             (path_span, format!("{}{}{}", before, anon_lts, after))
1318         } else {
1319             (insertion_span, anon_lts)
1320         }
1321     };
1322     db.span_suggestion(
1323         replace_span,
1324         &format!("indicate the anonymous lifetime{}", pluralize!(n)),
1325         suggestion,
1326         Applicability::MachineApplicable,
1327     );
1328 }
1329
1330 // Useful type to use with `Result<>` indicate that an error has already
1331 // been reported to the user, so no need to continue checking.
1332 #[derive(Clone, Copy, Debug, Encodable, Decodable, Hash, PartialEq, Eq)]
1333 pub struct ErrorReported;
1334
1335 rustc_data_structures::impl_stable_hash_via_hash!(ErrorReported);