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