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