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