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)]
15 #[allow(unused_extern_crates)]
16 extern crate serialize as rustc_serialize; // used by deriving
18 pub use emitter::ColorConfig;
22 use emitter::{Emitter, EmitterWriter};
23 use registry::Registry;
25 use rustc_data_structures::sync::{self, Lrc, Lock, AtomicUsize, AtomicBool, SeqCst};
26 use rustc_data_structures::fx::FxHashSet;
27 use rustc_data_structures::stable_hasher::StableHasher;
31 use std::{error, fmt};
35 use termcolor::{ColorSpec, Color};
38 mod diagnostic_builder;
40 pub mod annotate_snippet_emitter_writer;
46 use syntax_pos::{BytePos,
55 /// Indicates the confidence in the correctness of a suggestion.
57 /// All suggestions are marked with an `Applicability`. Tools use the applicability of a suggestion
58 /// to determine whether it should be automatically applied or if the user should be consulted
59 /// before applying the suggestion.
60 #[derive(Copy, Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
61 pub enum Applicability {
62 /// The suggestion is definitely what the user intended. This suggestion should be
63 /// automatically applied.
66 /// The suggestion may be what the user intended, but it is uncertain. The suggestion should
67 /// result in valid Rust code if it is applied.
70 /// The suggestion contains placeholders like `(...)` or `{ /* fields */ }`. The suggestion
71 /// cannot be applied automatically because it will not result in valid Rust code. The user
72 /// will need to fill in the placeholders.
75 /// The applicability of the suggestion is unknown.
79 #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, RustcEncodable, RustcDecodable)]
80 pub enum SuggestionStyle {
81 /// Hide the suggested code when displaying this suggestion inline.
83 /// Always hide the suggested code but display the message.
85 /// Do not display this suggestion in the cli output, it is only meant for tools.
87 /// Always show the suggested code.
88 /// This will *not* show the code if the suggestion is inline *and* the suggested code is
93 impl SuggestionStyle {
94 fn hide_inline(&self) -> bool {
96 SuggestionStyle::ShowCode => false,
102 #[derive(Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
103 pub struct CodeSuggestion {
104 /// Each substitute can have multiple variants due to multiple
105 /// applicable suggestions
107 /// `foo.bar` might be replaced with `a.b` or `x.y` by replacing
108 /// `foo` and `bar` on their own:
112 /// Substitution { parts: vec![(0..3, "a"), (4..7, "b")] },
113 /// Substitution { parts: vec![(0..3, "x"), (4..7, "y")] },
117 /// or by replacing the entire span:
121 /// Substitution { parts: vec![(0..7, "a.b")] },
122 /// Substitution { parts: vec![(0..7, "x.y")] },
125 pub substitutions: Vec<Substitution>,
127 /// Visual representation of this suggestion.
128 pub style: SuggestionStyle,
129 /// Whether or not the suggestion is approximate
131 /// Sometimes we may show suggestions with placeholders,
132 /// which are useful for users but not useful for
133 /// tools like rustfix
134 pub applicability: Applicability,
137 #[derive(Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
138 /// See the docs on `CodeSuggestion::substitutions`
139 pub struct Substitution {
140 pub parts: Vec<SubstitutionPart>,
143 #[derive(Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
144 pub struct SubstitutionPart {
149 pub type SourceMapperDyn = dyn SourceMapper + sync::Send + sync::Sync;
151 pub trait SourceMapper {
152 fn lookup_char_pos(&self, pos: BytePos) -> Loc;
153 fn span_to_lines(&self, sp: Span) -> FileLinesResult;
154 fn span_to_string(&self, sp: Span) -> String;
155 fn span_to_filename(&self, sp: Span) -> FileName;
156 fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option<Span>;
157 fn call_span_if_macro(&self, sp: Span) -> Span;
158 fn ensure_source_file_source_present(&self, source_file: Lrc<SourceFile>) -> bool;
159 fn doctest_offset_line(&self, file: &FileName, line: usize) -> usize;
162 impl CodeSuggestion {
163 /// Returns the assembled code suggestions and whether they should be shown with an underline.
164 pub fn splice_lines(&self, cm: &SourceMapperDyn)
165 -> Vec<(String, Vec<SubstitutionPart>)> {
166 use syntax_pos::{CharPos, Pos};
168 fn push_trailing(buf: &mut String,
169 line_opt: Option<&Cow<'_, str>>,
171 hi_opt: Option<&Loc>) {
172 let (lo, hi_opt) = (lo.col.to_usize(), hi_opt.map(|hi| hi.col.to_usize()));
173 if let Some(line) = line_opt {
174 if let Some(lo) = line.char_indices().map(|(i, _)| i).nth(lo) {
175 let hi_opt = hi_opt.and_then(|hi| line.char_indices().map(|(i, _)| i).nth(hi));
177 Some(hi) if hi > lo => buf.push_str(&line[lo..hi]),
179 None => buf.push_str(&line[lo..]),
182 if let None = hi_opt {
188 assert!(!self.substitutions.is_empty());
190 self.substitutions.iter().cloned().map(|mut substitution| {
191 // Assumption: all spans are in the same file, and all spans
192 // are disjoint. Sort in ascending order.
193 substitution.parts.sort_by_key(|part| part.span.lo());
195 // Find the bounding span.
196 let lo = substitution.parts.iter().map(|part| part.span.lo()).min().unwrap();
197 let hi = substitution.parts.iter().map(|part| part.span.hi()).min().unwrap();
198 let bounding_span = Span::new(lo, hi, NO_EXPANSION);
199 let lines = cm.span_to_lines(bounding_span).unwrap();
200 assert!(!lines.lines.is_empty());
202 // To build up the result, we do this for each span:
203 // - push the line segment trailing the previous span
204 // (at the beginning a "phantom" span pointing at the start of the line)
205 // - push lines between the previous and current span (if any)
206 // - if the previous and current span are not on the same line
207 // push the line segment leading up to the current span
208 // - splice in the span substitution
210 // Finally push the trailing line segment of the last span
211 let fm = &lines.file;
212 let mut prev_hi = cm.lookup_char_pos(bounding_span.lo());
213 prev_hi.col = CharPos::from_usize(0);
215 let mut prev_line = fm.get_line(lines.lines[0].line_index);
216 let mut buf = String::new();
218 for part in &substitution.parts {
219 let cur_lo = cm.lookup_char_pos(part.span.lo());
220 if prev_hi.line == cur_lo.line {
221 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, Some(&cur_lo));
223 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
224 // push lines between the previous and current span (if any)
225 for idx in prev_hi.line..(cur_lo.line - 1) {
226 if let Some(line) = fm.get_line(idx) {
227 buf.push_str(line.as_ref());
231 if let Some(cur_line) = fm.get_line(cur_lo.line - 1) {
232 buf.push_str(&cur_line[..cur_lo.col.to_usize()]);
235 buf.push_str(&part.snippet);
236 prev_hi = cm.lookup_char_pos(part.span.hi());
237 prev_line = fm.get_line(prev_hi.line - 1);
239 // if the replacement already ends with a newline, don't print the next line
240 if !buf.ends_with('\n') {
241 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
243 // remove trailing newlines
244 while buf.ends_with('\n') {
247 (buf, substitution.parts)
252 /// Used as a return value to signify a fatal error occurred. (It is also
253 /// used as the argument to panic at the moment, but that will eventually
255 #[derive(Copy, Clone, Debug)]
257 pub struct FatalError;
259 pub struct FatalErrorMarker;
261 // Don't implement Send on FatalError. This makes it impossible to panic!(FatalError).
262 // We don't want to invoke the panic handler and print a backtrace for fatal errors.
263 impl !Send for FatalError {}
266 pub fn raise(self) -> ! {
267 panic::resume_unwind(Box::new(FatalErrorMarker))
271 impl fmt::Display for FatalError {
272 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
273 write!(f, "parser fatal error")
277 impl error::Error for FatalError {
278 fn description(&self) -> &str {
279 "The parser has encountered a fatal error"
283 /// Signifies that the compiler died with an explicit call to `.bug`
284 /// or `.span_bug` rather than a failed assertion, etc.
285 #[derive(Copy, Clone, Debug)]
286 pub struct ExplicitBug;
288 impl fmt::Display for ExplicitBug {
289 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
290 write!(f, "parser internal bug")
294 impl error::Error for ExplicitBug {
295 fn description(&self) -> &str {
296 "The parser has encountered an internal bug"
300 pub use diagnostic::{Diagnostic, SubDiagnostic, DiagnosticStyledString, DiagnosticId};
301 pub use diagnostic_builder::DiagnosticBuilder;
303 /// A handler deals with errors and other compiler output.
304 /// Certain errors (fatal, bug, unimpl) may cause immediate exit,
305 /// others log errors for later reporting.
307 pub flags: HandlerFlags,
309 err_count: AtomicUsize,
310 emitter: Lock<Box<dyn Emitter + sync::Send>>,
311 continue_after_error: AtomicBool,
312 delayed_span_bugs: Lock<Vec<Diagnostic>>,
314 /// This set contains the `DiagnosticId` of all emitted diagnostics to avoid
315 /// emitting the same diagnostic with extended help (`--teach`) twice, which
316 /// would be uneccessary repetition.
317 taught_diagnostics: Lock<FxHashSet<DiagnosticId>>,
319 /// Used to suggest rustc --explain <error code>
320 emitted_diagnostic_codes: Lock<FxHashSet<DiagnosticId>>,
322 /// This set contains a hash of every diagnostic that has been emitted by
323 /// this handler. These hashes is used to avoid emitting the same error
325 emitted_diagnostics: Lock<FxHashSet<u128>>,
328 fn default_track_diagnostic(_: &Diagnostic) {}
330 thread_local!(pub static TRACK_DIAGNOSTICS: Cell<fn(&Diagnostic)> =
331 Cell::new(default_track_diagnostic));
334 pub struct HandlerFlags {
335 /// If false, warning-level lints are suppressed.
336 /// (rustc: see `--allow warnings` and `--cap-lints`)
337 pub can_emit_warnings: bool,
338 /// If true, error-level diagnostics are upgraded to bug-level.
339 /// (rustc: see `-Z treat-err-as-bug`)
340 pub treat_err_as_bug: Option<usize>,
341 /// If true, immediately emit diagnostics that would otherwise be buffered.
342 /// (rustc: see `-Z dont-buffer-diagnostics` and `-Z treat-err-as-bug`)
343 pub dont_buffer_diagnostics: bool,
344 /// If true, immediately print bugs registered with `delay_span_bug`.
345 /// (rustc: see `-Z report-delayed-bugs`)
346 pub report_delayed_bugs: bool,
347 /// show macro backtraces even for non-local macros.
348 /// (rustc: see `-Z external-macro-backtrace`)
349 pub external_macro_backtrace: bool,
352 impl Drop for Handler {
354 if self.err_count() == 0 {
355 let mut bugs = self.delayed_span_bugs.borrow_mut();
356 let has_bugs = !bugs.is_empty();
357 for bug in bugs.drain(..) {
358 DiagnosticBuilder::new_diagnostic(self, bug).emit();
361 panic!("no errors encountered even though `delay_span_bug` issued");
368 pub fn with_tty_emitter(color_config: ColorConfig,
369 can_emit_warnings: bool,
370 treat_err_as_bug: Option<usize>,
371 cm: Option<Lrc<SourceMapperDyn>>)
373 Handler::with_tty_emitter_and_flags(
379 .. Default::default()
383 pub fn with_tty_emitter_and_flags(color_config: ColorConfig,
384 cm: Option<Lrc<SourceMapperDyn>>,
387 let emitter = Box::new(EmitterWriter::stderr(color_config, cm, false, false));
388 Handler::with_emitter_and_flags(emitter, flags)
391 pub fn with_emitter(can_emit_warnings: bool,
392 treat_err_as_bug: Option<usize>,
393 e: Box<dyn Emitter + sync::Send>)
395 Handler::with_emitter_and_flags(
400 .. Default::default()
404 pub fn with_emitter_and_flags(e: Box<dyn Emitter + sync::Send>, flags: HandlerFlags) -> Handler
408 err_count: AtomicUsize::new(0),
409 emitter: Lock::new(e),
410 continue_after_error: AtomicBool::new(true),
411 delayed_span_bugs: Lock::new(Vec::new()),
412 taught_diagnostics: Default::default(),
413 emitted_diagnostic_codes: Default::default(),
414 emitted_diagnostics: Default::default(),
418 pub fn set_continue_after_error(&self, continue_after_error: bool) {
419 self.continue_after_error.store(continue_after_error, SeqCst);
422 /// Resets the diagnostic error count as well as the cached emitted diagnostics.
424 /// NOTE: *do not* call this function from rustc. It is only meant to be called from external
425 /// tools that want to reuse a `Parser` cleaning the previously emitted diagnostics as well as
426 /// the overall count of emitted error diagnostics.
427 pub fn reset_err_count(&self) {
428 // actually frees the underlying memory (which `clear` would not do)
429 *self.emitted_diagnostics.borrow_mut() = Default::default();
430 self.err_count.store(0, SeqCst);
433 pub fn struct_dummy<'a>(&'a self) -> DiagnosticBuilder<'a> {
434 DiagnosticBuilder::new(self, Level::Cancelled, "")
437 pub fn struct_span_warn<'a, S: Into<MultiSpan>>(&'a self,
440 -> DiagnosticBuilder<'a> {
441 let mut result = DiagnosticBuilder::new(self, Level::Warning, msg);
443 if !self.flags.can_emit_warnings {
448 pub fn struct_span_warn_with_code<'a, S: Into<MultiSpan>>(&'a self,
452 -> DiagnosticBuilder<'a> {
453 let mut result = DiagnosticBuilder::new(self, Level::Warning, msg);
456 if !self.flags.can_emit_warnings {
461 pub fn struct_warn<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
462 let mut result = DiagnosticBuilder::new(self, Level::Warning, msg);
463 if !self.flags.can_emit_warnings {
468 pub fn struct_span_err<'a, S: Into<MultiSpan>>(&'a self,
471 -> DiagnosticBuilder<'a> {
472 let mut result = DiagnosticBuilder::new(self, Level::Error, msg);
476 pub fn struct_span_err_with_code<'a, S: Into<MultiSpan>>(&'a self,
480 -> DiagnosticBuilder<'a> {
481 let mut result = DiagnosticBuilder::new(self, Level::Error, msg);
486 // FIXME: This method should be removed (every error should have an associated error code).
487 pub fn struct_err<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
488 DiagnosticBuilder::new(self, Level::Error, msg)
490 pub fn struct_err_with_code<'a>(
494 ) -> DiagnosticBuilder<'a> {
495 let mut result = DiagnosticBuilder::new(self, Level::Error, msg);
499 pub fn struct_span_fatal<'a, S: Into<MultiSpan>>(&'a self,
502 -> DiagnosticBuilder<'a> {
503 let mut result = DiagnosticBuilder::new(self, Level::Fatal, msg);
507 pub fn struct_span_fatal_with_code<'a, S: Into<MultiSpan>>(&'a self,
511 -> DiagnosticBuilder<'a> {
512 let mut result = DiagnosticBuilder::new(self, Level::Fatal, msg);
517 pub fn struct_fatal<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
518 DiagnosticBuilder::new(self, Level::Fatal, msg)
521 pub fn cancel(&self, err: &mut DiagnosticBuilder<'_>) {
525 fn panic_if_treat_err_as_bug(&self) {
526 if self.treat_err_as_bug() {
527 let s = match (self.err_count(), self.flags.treat_err_as_bug.unwrap_or(0)) {
529 (1, 1) => "aborting due to `-Z treat-err-as-bug=1`".to_string(),
533 "aborting after {} errors due to `-Z treat-err-as-bug={}`",
543 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> FatalError {
544 self.emit(&sp.into(), msg, Fatal);
547 pub fn span_fatal_with_code<S: Into<MultiSpan>>(&self,
552 self.emit_with_code(&sp.into(), msg, code, Fatal);
555 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
556 self.emit(&sp.into(), msg, Error);
558 pub fn mut_span_err<'a, S: Into<MultiSpan>>(&'a self,
561 -> DiagnosticBuilder<'a> {
562 let mut result = DiagnosticBuilder::new(self, Level::Error, msg);
566 pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
567 self.emit_with_code(&sp.into(), msg, code, Error);
569 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
570 self.emit(&sp.into(), msg, Warning);
572 pub fn span_warn_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
573 self.emit_with_code(&sp.into(), msg, code, Warning);
575 pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
576 self.emit(&sp.into(), msg, Bug);
579 pub fn delay_span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
580 if self.treat_err_as_bug() {
581 // FIXME: don't abort here if report_delayed_bugs is off
582 self.span_bug(sp, msg);
584 let mut diagnostic = Diagnostic::new(Level::Bug, msg);
585 diagnostic.set_span(sp.into());
586 self.delay_as_bug(diagnostic);
588 fn delay_as_bug(&self, diagnostic: Diagnostic) {
589 if self.flags.report_delayed_bugs {
590 DiagnosticBuilder::new_diagnostic(self, diagnostic.clone()).emit();
592 self.delayed_span_bugs.borrow_mut().push(diagnostic);
594 pub fn span_bug_no_panic<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
595 self.emit(&sp.into(), msg, Bug);
597 pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
598 self.emit(&sp.into(), msg, Note);
600 pub fn span_note_diag<'a>(&'a self,
603 -> DiagnosticBuilder<'a> {
604 let mut db = DiagnosticBuilder::new(self, Note, msg);
608 pub fn span_unimpl<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
609 self.span_bug(sp, &format!("unimplemented {}", msg));
611 pub fn failure(&self, msg: &str) {
612 DiagnosticBuilder::new(self, FailureNote, msg).emit()
614 pub fn fatal(&self, msg: &str) -> FatalError {
615 if self.treat_err_as_bug() {
618 DiagnosticBuilder::new(self, Fatal, msg).emit();
621 pub fn err(&self, msg: &str) {
622 if self.treat_err_as_bug() {
625 let mut db = DiagnosticBuilder::new(self, Error, msg);
628 pub fn warn(&self, msg: &str) {
629 let mut db = DiagnosticBuilder::new(self, Warning, msg);
632 fn treat_err_as_bug(&self) -> bool {
633 self.flags.treat_err_as_bug.map(|c| self.err_count() >= c).unwrap_or(false)
635 pub fn note_without_error(&self, msg: &str) {
636 let mut db = DiagnosticBuilder::new(self, Note, msg);
639 pub fn bug(&self, msg: &str) -> ! {
640 let mut db = DiagnosticBuilder::new(self, Bug, msg);
644 pub fn unimpl(&self, msg: &str) -> ! {
645 self.bug(&format!("unimplemented {}", msg));
648 fn bump_err_count(&self) {
649 self.err_count.fetch_add(1, SeqCst);
650 self.panic_if_treat_err_as_bug();
653 pub fn err_count(&self) -> usize {
654 self.err_count.load(SeqCst)
657 pub fn has_errors(&self) -> bool {
661 pub fn print_error_count(&self, registry: &Registry) {
662 let s = match self.err_count() {
664 1 => "aborting due to previous error".to_string(),
665 _ => format!("aborting due to {} previous errors", self.err_count())
667 if self.treat_err_as_bug() {
671 let _ = self.fatal(&s);
673 let can_show_explain = self.emitter.borrow().should_show_explain();
674 let are_there_diagnostics = !self.emitted_diagnostic_codes.borrow().is_empty();
675 if can_show_explain && are_there_diagnostics {
676 let mut error_codes = self
677 .emitted_diagnostic_codes
680 .filter_map(|x| match &x {
681 DiagnosticId::Error(s) if registry.find_description(s).is_some() => {
686 .collect::<Vec<_>>();
687 if !error_codes.is_empty() {
689 if error_codes.len() > 1 {
690 let limit = if error_codes.len() > 9 { 9 } else { error_codes.len() };
691 self.failure(&format!("Some errors have detailed explanations: {}{}",
692 error_codes[..limit].join(", "),
693 if error_codes.len() > 9 { "..." } else { "." }));
694 self.failure(&format!("For more information about an error, try \
695 `rustc --explain {}`.",
698 self.failure(&format!("For more information about this error, try \
699 `rustc --explain {}`.",
706 pub fn abort_if_errors(&self) {
707 if self.err_count() == 0 {
712 pub fn emit(&self, msp: &MultiSpan, msg: &str, lvl: Level) {
713 if lvl == Warning && !self.flags.can_emit_warnings {
716 let mut db = DiagnosticBuilder::new(self, lvl, msg);
717 db.set_span(msp.clone());
719 if !self.continue_after_error.load(SeqCst) {
720 self.abort_if_errors();
723 pub fn emit_with_code(&self, msp: &MultiSpan, msg: &str, code: DiagnosticId, lvl: Level) {
724 if lvl == Warning && !self.flags.can_emit_warnings {
727 let mut db = DiagnosticBuilder::new_with_code(self, lvl, Some(code), msg);
728 db.set_span(msp.clone());
730 if !self.continue_after_error.load(SeqCst) {
731 self.abort_if_errors();
735 /// `true` if we haven't taught a diagnostic with this code already.
736 /// The caller must then teach the user about such a diagnostic.
738 /// Used to suppress emitting the same error multiple times with extended explanation when
739 /// calling `-Zteach`.
740 pub fn must_teach(&self, code: &DiagnosticId) -> bool {
741 self.taught_diagnostics.borrow_mut().insert(code.clone())
744 pub fn force_print_db(&self, mut db: DiagnosticBuilder<'_>) {
745 self.emitter.borrow_mut().emit_diagnostic(&db);
749 fn emit_db(&self, db: &DiagnosticBuilder<'_>) {
750 let diagnostic = &**db;
752 TRACK_DIAGNOSTICS.with(|track_diagnostics| {
753 track_diagnostics.get()(diagnostic);
756 if let Some(ref code) = diagnostic.code {
757 self.emitted_diagnostic_codes.borrow_mut().insert(code.clone());
760 let diagnostic_hash = {
762 let mut hasher = StableHasher::new();
763 diagnostic.hash(&mut hasher);
767 // Only emit the diagnostic if we haven't already emitted an equivalent
769 if self.emitted_diagnostics.borrow_mut().insert(diagnostic_hash) {
770 self.emitter.borrow_mut().emit_diagnostic(db);
772 self.bump_err_count();
777 pub fn emit_artifact_notification(&self, path: &Path, artifact_type: &str) {
778 self.emitter.borrow_mut().emit_artifact_notification(path, artifact_type);
782 #[derive(Copy, PartialEq, Clone, Hash, Debug, RustcEncodable, RustcDecodable)]
786 // An error which while not immediately fatal, should stop the compiler
787 // progressing beyond the current phase.
797 impl fmt::Display for Level {
798 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
804 fn color(self) -> ColorSpec {
805 let mut spec = ColorSpec::new();
807 Bug | Fatal | PhaseFatal | Error => {
808 spec.set_fg(Some(Color::Red))
812 spec.set_fg(Some(Color::Yellow))
813 .set_intense(cfg!(windows));
816 spec.set_fg(Some(Color::Green))
820 spec.set_fg(Some(Color::Cyan))
824 Cancelled => unreachable!(),
829 pub fn to_str(self) -> &'static str {
831 Bug => "error: internal compiler error",
832 Fatal | PhaseFatal | Error => "error",
833 Warning => "warning",
837 Cancelled => panic!("Shouldn't call on cancelled error"),
841 pub fn is_failure_note(&self) -> bool {