1 //! Diagnostics creation and emission for `rustc`.
3 //! This module contains the code for creating and emitting diagnostics.
5 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
7 #![feature(crate_visibility_modifier)]
8 #![allow(unused_attributes)]
9 #![cfg_attr(unix, feature(libc))]
11 #![feature(optin_builtin_traits)]
12 #![deny(rust_2018_idioms)]
14 #![deny(unused_lifetimes)]
16 #[allow(unused_extern_crates)]
17 extern crate serialize as rustc_serialize; // used by deriving
19 pub use emitter::ColorConfig;
23 use emitter::{Emitter, EmitterWriter};
24 use registry::Registry;
26 use rustc_data_structures::sync::{self, Lrc, Lock, AtomicUsize, AtomicBool, SeqCst};
27 use rustc_data_structures::fx::FxHashSet;
28 use rustc_data_structures::stable_hasher::StableHasher;
32 use std::{error, fmt};
36 use termcolor::{ColorSpec, Color};
39 mod diagnostic_builder;
41 pub mod annotate_snippet_emitter_writer;
47 use syntax_pos::{BytePos,
56 /// Indicates the confidence in the correctness of a suggestion.
58 /// All suggestions are marked with an `Applicability`. Tools use the applicability of a suggestion
59 /// to determine whether it should be automatically applied or if the user should be consulted
60 /// before applying the suggestion.
61 #[derive(Copy, Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
62 pub enum Applicability {
63 /// The suggestion is definitely what the user intended. This suggestion should be
64 /// automatically applied.
67 /// The suggestion may be what the user intended, but it is uncertain. The suggestion should
68 /// result in valid Rust code if it is applied.
71 /// The suggestion contains placeholders like `(...)` or `{ /* fields */ }`. The suggestion
72 /// cannot be applied automatically because it will not result in valid Rust code. The user
73 /// will need to fill in the placeholders.
76 /// The applicability of the suggestion is unknown.
80 #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, RustcEncodable, RustcDecodable)]
81 pub enum SuggestionStyle {
82 /// Hide the suggested code when displaying this suggestion inline.
84 /// Always hide the suggested code but display the message.
86 /// Do not display this suggestion in the cli output, it is only meant for tools.
88 /// Always show the suggested code.
89 /// This will *not* show the code if the suggestion is inline *and* the suggested code is
94 impl SuggestionStyle {
95 fn hide_inline(&self) -> bool {
97 SuggestionStyle::ShowCode => false,
103 #[derive(Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
104 pub struct CodeSuggestion {
105 /// Each substitute can have multiple variants due to multiple
106 /// applicable suggestions
108 /// `foo.bar` might be replaced with `a.b` or `x.y` by replacing
109 /// `foo` and `bar` on their own:
113 /// Substitution { parts: vec![(0..3, "a"), (4..7, "b")] },
114 /// Substitution { parts: vec![(0..3, "x"), (4..7, "y")] },
118 /// or by replacing the entire span:
122 /// Substitution { parts: vec![(0..7, "a.b")] },
123 /// Substitution { parts: vec![(0..7, "x.y")] },
126 pub substitutions: Vec<Substitution>,
128 /// Visual representation of this suggestion.
129 pub style: SuggestionStyle,
130 /// Whether or not the suggestion is approximate
132 /// Sometimes we may show suggestions with placeholders,
133 /// which are useful for users but not useful for
134 /// tools like rustfix
135 pub applicability: Applicability,
138 #[derive(Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
139 /// See the docs on `CodeSuggestion::substitutions`
140 pub struct Substitution {
141 pub parts: Vec<SubstitutionPart>,
144 #[derive(Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
145 pub struct SubstitutionPart {
150 pub type SourceMapperDyn = dyn SourceMapper + sync::Send + sync::Sync;
152 pub trait SourceMapper {
153 fn lookup_char_pos(&self, pos: BytePos) -> Loc;
154 fn span_to_lines(&self, sp: Span) -> FileLinesResult;
155 fn span_to_string(&self, sp: Span) -> String;
156 fn span_to_filename(&self, sp: Span) -> FileName;
157 fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option<Span>;
158 fn call_span_if_macro(&self, sp: Span) -> Span;
159 fn ensure_source_file_source_present(&self, source_file: Lrc<SourceFile>) -> bool;
160 fn doctest_offset_line(&self, file: &FileName, line: usize) -> usize;
163 impl CodeSuggestion {
164 /// Returns the assembled code suggestions and whether they should be shown with an underline.
165 pub fn splice_lines(&self, cm: &SourceMapperDyn)
166 -> Vec<(String, Vec<SubstitutionPart>)> {
167 use syntax_pos::{CharPos, Pos};
169 fn push_trailing(buf: &mut String,
170 line_opt: Option<&Cow<'_, str>>,
172 hi_opt: Option<&Loc>) {
173 let (lo, hi_opt) = (lo.col.to_usize(), hi_opt.map(|hi| hi.col.to_usize()));
174 if let Some(line) = line_opt {
175 if let Some(lo) = line.char_indices().map(|(i, _)| i).nth(lo) {
176 let hi_opt = hi_opt.and_then(|hi| line.char_indices().map(|(i, _)| i).nth(hi));
178 Some(hi) if hi > lo => buf.push_str(&line[lo..hi]),
180 None => buf.push_str(&line[lo..]),
183 if let None = hi_opt {
189 assert!(!self.substitutions.is_empty());
191 self.substitutions.iter().cloned().map(|mut substitution| {
192 // Assumption: all spans are in the same file, and all spans
193 // are disjoint. Sort in ascending order.
194 substitution.parts.sort_by_key(|part| part.span.lo());
196 // Find the bounding span.
197 let lo = substitution.parts.iter().map(|part| part.span.lo()).min().unwrap();
198 let hi = substitution.parts.iter().map(|part| part.span.hi()).min().unwrap();
199 let bounding_span = Span::new(lo, hi, NO_EXPANSION);
200 let lines = cm.span_to_lines(bounding_span).unwrap();
201 assert!(!lines.lines.is_empty());
203 // To build up the result, we do this for each span:
204 // - push the line segment trailing the previous span
205 // (at the beginning a "phantom" span pointing at the start of the line)
206 // - push lines between the previous and current span (if any)
207 // - if the previous and current span are not on the same line
208 // push the line segment leading up to the current span
209 // - splice in the span substitution
211 // Finally push the trailing line segment of the last span
212 let fm = &lines.file;
213 let mut prev_hi = cm.lookup_char_pos(bounding_span.lo());
214 prev_hi.col = CharPos::from_usize(0);
216 let mut prev_line = fm.get_line(lines.lines[0].line_index);
217 let mut buf = String::new();
219 for part in &substitution.parts {
220 let cur_lo = cm.lookup_char_pos(part.span.lo());
221 if prev_hi.line == cur_lo.line {
222 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, Some(&cur_lo));
224 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
225 // push lines between the previous and current span (if any)
226 for idx in prev_hi.line..(cur_lo.line - 1) {
227 if let Some(line) = fm.get_line(idx) {
228 buf.push_str(line.as_ref());
232 if let Some(cur_line) = fm.get_line(cur_lo.line - 1) {
233 buf.push_str(&cur_line[..cur_lo.col.to_usize()]);
236 buf.push_str(&part.snippet);
237 prev_hi = cm.lookup_char_pos(part.span.hi());
238 prev_line = fm.get_line(prev_hi.line - 1);
240 // if the replacement already ends with a newline, don't print the next line
241 if !buf.ends_with('\n') {
242 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
244 // remove trailing newlines
245 while buf.ends_with('\n') {
248 (buf, substitution.parts)
253 /// Used as a return value to signify a fatal error occurred. (It is also
254 /// used as the argument to panic at the moment, but that will eventually
256 #[derive(Copy, Clone, Debug)]
258 pub struct FatalError;
260 pub struct FatalErrorMarker;
262 // Don't implement Send on FatalError. This makes it impossible to panic!(FatalError).
263 // We don't want to invoke the panic handler and print a backtrace for fatal errors.
264 impl !Send for FatalError {}
267 pub fn raise(self) -> ! {
268 panic::resume_unwind(Box::new(FatalErrorMarker))
272 impl fmt::Display for FatalError {
273 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
274 write!(f, "parser fatal error")
278 impl error::Error for FatalError {
279 fn description(&self) -> &str {
280 "The parser has encountered a fatal error"
284 /// Signifies that the compiler died with an explicit call to `.bug`
285 /// or `.span_bug` rather than a failed assertion, etc.
286 #[derive(Copy, Clone, Debug)]
287 pub struct ExplicitBug;
289 impl fmt::Display for ExplicitBug {
290 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
291 write!(f, "parser internal bug")
295 impl error::Error for ExplicitBug {
296 fn description(&self) -> &str {
297 "The parser has encountered an internal bug"
301 pub use diagnostic::{Diagnostic, SubDiagnostic, DiagnosticStyledString, DiagnosticId};
302 pub use diagnostic_builder::DiagnosticBuilder;
304 /// A handler deals with errors and other compiler output.
305 /// Certain errors (fatal, bug, unimpl) may cause immediate exit,
306 /// others log errors for later reporting.
308 pub flags: HandlerFlags,
310 err_count: AtomicUsize,
311 emitter: Lock<Box<dyn Emitter + sync::Send>>,
312 continue_after_error: AtomicBool,
313 delayed_span_bugs: Lock<Vec<Diagnostic>>,
315 /// This set contains the `DiagnosticId` of all emitted diagnostics to avoid
316 /// emitting the same diagnostic with extended help (`--teach`) twice, which
317 /// would be uneccessary repetition.
318 taught_diagnostics: Lock<FxHashSet<DiagnosticId>>,
320 /// Used to suggest rustc --explain <error code>
321 emitted_diagnostic_codes: Lock<FxHashSet<DiagnosticId>>,
323 /// This set contains a hash of every diagnostic that has been emitted by
324 /// this handler. These hashes is used to avoid emitting the same error
326 emitted_diagnostics: Lock<FxHashSet<u128>>,
329 fn default_track_diagnostic(_: &Diagnostic) {}
331 thread_local!(pub static TRACK_DIAGNOSTICS: Cell<fn(&Diagnostic)> =
332 Cell::new(default_track_diagnostic));
335 pub struct HandlerFlags {
336 /// If false, warning-level lints are suppressed.
337 /// (rustc: see `--allow warnings` and `--cap-lints`)
338 pub can_emit_warnings: bool,
339 /// If true, error-level diagnostics are upgraded to bug-level.
340 /// (rustc: see `-Z treat-err-as-bug`)
341 pub treat_err_as_bug: Option<usize>,
342 /// If true, immediately emit diagnostics that would otherwise be buffered.
343 /// (rustc: see `-Z dont-buffer-diagnostics` and `-Z treat-err-as-bug`)
344 pub dont_buffer_diagnostics: bool,
345 /// If true, immediately print bugs registered with `delay_span_bug`.
346 /// (rustc: see `-Z report-delayed-bugs`)
347 pub report_delayed_bugs: bool,
348 /// show macro backtraces even for non-local macros.
349 /// (rustc: see `-Z external-macro-backtrace`)
350 pub external_macro_backtrace: bool,
353 impl Drop for Handler {
355 if self.err_count() == 0 {
356 let mut bugs = self.delayed_span_bugs.borrow_mut();
357 let has_bugs = !bugs.is_empty();
358 for bug in bugs.drain(..) {
359 DiagnosticBuilder::new_diagnostic(self, bug).emit();
362 panic!("no errors encountered even though `delay_span_bug` issued");
369 pub fn with_tty_emitter(color_config: ColorConfig,
370 can_emit_warnings: bool,
371 treat_err_as_bug: Option<usize>,
372 cm: Option<Lrc<SourceMapperDyn>>)
374 Handler::with_tty_emitter_and_flags(
380 .. Default::default()
384 pub fn with_tty_emitter_and_flags(color_config: ColorConfig,
385 cm: Option<Lrc<SourceMapperDyn>>,
388 let emitter = Box::new(EmitterWriter::stderr(color_config, cm, false, false));
389 Handler::with_emitter_and_flags(emitter, flags)
392 pub fn with_emitter(can_emit_warnings: bool,
393 treat_err_as_bug: Option<usize>,
394 e: Box<dyn Emitter + sync::Send>)
396 Handler::with_emitter_and_flags(
401 .. Default::default()
405 pub fn with_emitter_and_flags(e: Box<dyn Emitter + sync::Send>, flags: HandlerFlags) -> Handler
409 err_count: AtomicUsize::new(0),
410 emitter: Lock::new(e),
411 continue_after_error: AtomicBool::new(true),
412 delayed_span_bugs: Lock::new(Vec::new()),
413 taught_diagnostics: Default::default(),
414 emitted_diagnostic_codes: Default::default(),
415 emitted_diagnostics: Default::default(),
419 pub fn set_continue_after_error(&self, continue_after_error: bool) {
420 self.continue_after_error.store(continue_after_error, SeqCst);
423 /// Resets the diagnostic error count as well as the cached emitted diagnostics.
425 /// NOTE: *do not* call this function from rustc. It is only meant to be called from external
426 /// tools that want to reuse a `Parser` cleaning the previously emitted diagnostics as well as
427 /// the overall count of emitted error diagnostics.
428 pub fn reset_err_count(&self) {
429 // actually frees the underlying memory (which `clear` would not do)
430 *self.emitted_diagnostics.borrow_mut() = Default::default();
431 self.err_count.store(0, SeqCst);
434 pub fn struct_dummy<'a>(&'a self) -> DiagnosticBuilder<'a> {
435 DiagnosticBuilder::new(self, Level::Cancelled, "")
438 pub fn struct_span_warn<'a, S: Into<MultiSpan>>(&'a self,
441 -> DiagnosticBuilder<'a> {
442 let mut result = DiagnosticBuilder::new(self, Level::Warning, msg);
444 if !self.flags.can_emit_warnings {
449 pub fn struct_span_warn_with_code<'a, S: Into<MultiSpan>>(&'a self,
453 -> DiagnosticBuilder<'a> {
454 let mut result = DiagnosticBuilder::new(self, Level::Warning, msg);
457 if !self.flags.can_emit_warnings {
462 pub fn struct_warn<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
463 let mut result = DiagnosticBuilder::new(self, Level::Warning, msg);
464 if !self.flags.can_emit_warnings {
469 pub fn struct_span_err<'a, S: Into<MultiSpan>>(&'a self,
472 -> DiagnosticBuilder<'a> {
473 let mut result = DiagnosticBuilder::new(self, Level::Error, msg);
477 pub fn struct_span_err_with_code<'a, S: Into<MultiSpan>>(&'a self,
481 -> DiagnosticBuilder<'a> {
482 let mut result = DiagnosticBuilder::new(self, Level::Error, msg);
487 // FIXME: This method should be removed (every error should have an associated error code).
488 pub fn struct_err<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
489 DiagnosticBuilder::new(self, Level::Error, msg)
491 pub fn struct_err_with_code<'a>(
495 ) -> DiagnosticBuilder<'a> {
496 let mut result = DiagnosticBuilder::new(self, Level::Error, msg);
500 pub fn struct_span_fatal<'a, S: Into<MultiSpan>>(&'a self,
503 -> DiagnosticBuilder<'a> {
504 let mut result = DiagnosticBuilder::new(self, Level::Fatal, msg);
508 pub fn struct_span_fatal_with_code<'a, S: Into<MultiSpan>>(&'a self,
512 -> DiagnosticBuilder<'a> {
513 let mut result = DiagnosticBuilder::new(self, Level::Fatal, msg);
518 pub fn struct_fatal<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
519 DiagnosticBuilder::new(self, Level::Fatal, msg)
522 pub fn cancel(&self, err: &mut DiagnosticBuilder<'_>) {
526 fn panic_if_treat_err_as_bug(&self) {
527 if self.treat_err_as_bug() {
528 let s = match (self.err_count(), self.flags.treat_err_as_bug.unwrap_or(0)) {
530 (1, 1) => "aborting due to `-Z treat-err-as-bug=1`".to_string(),
534 "aborting after {} errors due to `-Z treat-err-as-bug={}`",
544 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> FatalError {
545 self.emit(&sp.into(), msg, Fatal);
548 pub fn span_fatal_with_code<S: Into<MultiSpan>>(&self,
553 self.emit_with_code(&sp.into(), msg, code, Fatal);
556 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
557 self.emit(&sp.into(), msg, Error);
559 pub fn mut_span_err<'a, S: Into<MultiSpan>>(&'a self,
562 -> DiagnosticBuilder<'a> {
563 let mut result = DiagnosticBuilder::new(self, Level::Error, msg);
567 pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
568 self.emit_with_code(&sp.into(), msg, code, Error);
570 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
571 self.emit(&sp.into(), msg, Warning);
573 pub fn span_warn_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
574 self.emit_with_code(&sp.into(), msg, code, Warning);
576 pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
577 self.emit(&sp.into(), msg, Bug);
580 pub fn delay_span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
581 if self.treat_err_as_bug() {
582 // FIXME: don't abort here if report_delayed_bugs is off
583 self.span_bug(sp, msg);
585 let mut diagnostic = Diagnostic::new(Level::Bug, msg);
586 diagnostic.set_span(sp.into());
587 self.delay_as_bug(diagnostic);
589 fn delay_as_bug(&self, diagnostic: Diagnostic) {
590 if self.flags.report_delayed_bugs {
591 DiagnosticBuilder::new_diagnostic(self, diagnostic.clone()).emit();
593 self.delayed_span_bugs.borrow_mut().push(diagnostic);
595 pub fn span_bug_no_panic<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
596 self.emit(&sp.into(), msg, Bug);
598 pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
599 self.emit(&sp.into(), msg, Note);
601 pub fn span_note_diag<'a>(&'a self,
604 -> DiagnosticBuilder<'a> {
605 let mut db = DiagnosticBuilder::new(self, Note, msg);
609 pub fn span_unimpl<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
610 self.span_bug(sp, &format!("unimplemented {}", msg));
612 pub fn failure(&self, msg: &str) {
613 DiagnosticBuilder::new(self, FailureNote, msg).emit()
615 pub fn fatal(&self, msg: &str) -> FatalError {
616 if self.treat_err_as_bug() {
619 DiagnosticBuilder::new(self, Fatal, msg).emit();
622 pub fn err(&self, msg: &str) {
623 if self.treat_err_as_bug() {
626 let mut db = DiagnosticBuilder::new(self, Error, msg);
629 pub fn warn(&self, msg: &str) {
630 let mut db = DiagnosticBuilder::new(self, Warning, msg);
633 fn treat_err_as_bug(&self) -> bool {
634 self.flags.treat_err_as_bug.map(|c| self.err_count() >= c).unwrap_or(false)
636 pub fn note_without_error(&self, msg: &str) {
637 let mut db = DiagnosticBuilder::new(self, Note, msg);
640 pub fn bug(&self, msg: &str) -> ! {
641 let mut db = DiagnosticBuilder::new(self, Bug, msg);
645 pub fn unimpl(&self, msg: &str) -> ! {
646 self.bug(&format!("unimplemented {}", msg));
649 fn bump_err_count(&self) {
650 self.err_count.fetch_add(1, SeqCst);
651 self.panic_if_treat_err_as_bug();
654 pub fn err_count(&self) -> usize {
655 self.err_count.load(SeqCst)
658 pub fn has_errors(&self) -> bool {
662 pub fn print_error_count(&self, registry: &Registry) {
663 let s = match self.err_count() {
665 1 => "aborting due to previous error".to_string(),
666 _ => format!("aborting due to {} previous errors", self.err_count())
668 if self.treat_err_as_bug() {
672 let _ = self.fatal(&s);
674 let can_show_explain = self.emitter.borrow().should_show_explain();
675 let are_there_diagnostics = !self.emitted_diagnostic_codes.borrow().is_empty();
676 if can_show_explain && are_there_diagnostics {
677 let mut error_codes = self
678 .emitted_diagnostic_codes
681 .filter_map(|x| match &x {
682 DiagnosticId::Error(s) if registry.find_description(s).is_some() => {
687 .collect::<Vec<_>>();
688 if !error_codes.is_empty() {
690 if error_codes.len() > 1 {
691 let limit = if error_codes.len() > 9 { 9 } else { error_codes.len() };
692 self.failure(&format!("Some errors have detailed explanations: {}{}",
693 error_codes[..limit].join(", "),
694 if error_codes.len() > 9 { "..." } else { "." }));
695 self.failure(&format!("For more information about an error, try \
696 `rustc --explain {}`.",
699 self.failure(&format!("For more information about this error, try \
700 `rustc --explain {}`.",
707 pub fn abort_if_errors(&self) {
708 if self.err_count() == 0 {
713 pub fn emit(&self, msp: &MultiSpan, msg: &str, lvl: Level) {
714 if lvl == Warning && !self.flags.can_emit_warnings {
717 let mut db = DiagnosticBuilder::new(self, lvl, msg);
718 db.set_span(msp.clone());
720 if !self.continue_after_error.load(SeqCst) {
721 self.abort_if_errors();
724 pub fn emit_with_code(&self, msp: &MultiSpan, msg: &str, code: DiagnosticId, lvl: Level) {
725 if lvl == Warning && !self.flags.can_emit_warnings {
728 let mut db = DiagnosticBuilder::new_with_code(self, lvl, Some(code), msg);
729 db.set_span(msp.clone());
731 if !self.continue_after_error.load(SeqCst) {
732 self.abort_if_errors();
736 /// `true` if we haven't taught a diagnostic with this code already.
737 /// The caller must then teach the user about such a diagnostic.
739 /// Used to suppress emitting the same error multiple times with extended explanation when
740 /// calling `-Zteach`.
741 pub fn must_teach(&self, code: &DiagnosticId) -> bool {
742 self.taught_diagnostics.borrow_mut().insert(code.clone())
745 pub fn force_print_db(&self, mut db: DiagnosticBuilder<'_>) {
746 self.emitter.borrow_mut().emit_diagnostic(&db);
750 fn emit_db(&self, db: &DiagnosticBuilder<'_>) {
751 let diagnostic = &**db;
753 TRACK_DIAGNOSTICS.with(|track_diagnostics| {
754 track_diagnostics.get()(diagnostic);
757 if let Some(ref code) = diagnostic.code {
758 self.emitted_diagnostic_codes.borrow_mut().insert(code.clone());
761 let diagnostic_hash = {
763 let mut hasher = StableHasher::new();
764 diagnostic.hash(&mut hasher);
768 // Only emit the diagnostic if we haven't already emitted an equivalent
770 if self.emitted_diagnostics.borrow_mut().insert(diagnostic_hash) {
771 self.emitter.borrow_mut().emit_diagnostic(db);
773 self.bump_err_count();
778 pub fn emit_artifact_notification(&self, path: &Path, artifact_type: &str) {
779 self.emitter.borrow_mut().emit_artifact_notification(path, artifact_type);
783 #[derive(Copy, PartialEq, Clone, Hash, Debug, RustcEncodable, RustcDecodable)]
787 // An error which while not immediately fatal, should stop the compiler
788 // progressing beyond the current phase.
798 impl fmt::Display for Level {
799 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
805 fn color(self) -> ColorSpec {
806 let mut spec = ColorSpec::new();
808 Bug | Fatal | PhaseFatal | Error => {
809 spec.set_fg(Some(Color::Red))
813 spec.set_fg(Some(Color::Yellow))
814 .set_intense(cfg!(windows));
817 spec.set_fg(Some(Color::Green))
821 spec.set_fg(Some(Color::Cyan))
825 Cancelled => unreachable!(),
830 pub fn to_str(self) -> &'static str {
832 Bug => "error: internal compiler error",
833 Fatal | PhaseFatal | Error => "error",
834 Warning => "warning",
838 Cancelled => panic!("Shouldn't call on cancelled error"),
842 pub fn is_failure_note(&self) -> bool {