1 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
3 #![feature(custom_attribute)]
4 #![allow(unused_attributes)]
5 #![cfg_attr(unix, feature(libc))]
7 #![feature(optin_builtin_traits)]
8 #![deny(rust_2018_idioms)]
11 #[allow(unused_extern_crates)]
12 extern crate serialize as rustc_serialize; // used by deriving
14 pub use emitter::ColorConfig;
18 use emitter::{Emitter, EmitterWriter};
19 use registry::Registry;
21 use rustc_data_structures::sync::{self, Lrc, Lock, AtomicUsize, AtomicBool, SeqCst};
22 use rustc_data_structures::fx::FxHashSet;
23 use rustc_data_structures::stable_hasher::StableHasher;
27 use std::{error, fmt};
31 use termcolor::{ColorSpec, Color};
34 mod diagnostic_builder;
36 pub mod annotate_snippet_emitter_writer;
42 use syntax_pos::{BytePos,
51 /// Indicates the confidence in the correctness of a suggestion.
53 /// All suggestions are marked with an `Applicability`. Tools use the applicability of a suggestion
54 /// to determine whether it should be automatically applied or if the user should be consulted
55 /// before applying the suggestion.
56 #[derive(Copy, Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
57 pub enum Applicability {
58 /// The suggestion is definitely what the user intended. This suggestion should be
59 /// automatically applied.
62 /// The suggestion may be what the user intended, but it is uncertain. The suggestion should
63 /// result in valid Rust code if it is applied.
66 /// The suggestion contains placeholders like `(...)` or `{ /* fields */ }`. The suggestion
67 /// cannot be applied automatically because it will not result in valid Rust code. The user
68 /// will need to fill in the placeholders.
71 /// The applicability of the suggestion is unknown.
75 #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, RustcEncodable, RustcDecodable)]
76 pub enum SuggestionStyle {
77 /// Hide the suggested code when displaying this suggestion inline.
79 /// Always hide the suggested code but display the message.
81 /// Do not display this suggestion in the cli output, it is only meant for tools.
83 /// Always show the suggested code.
84 /// This will *not* show the code if the suggestion is inline *and* the suggested code is
89 impl SuggestionStyle {
90 fn hide_inline(&self) -> bool {
92 SuggestionStyle::ShowCode => false,
98 #[derive(Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
99 pub struct CodeSuggestion {
100 /// Each substitute can have multiple variants due to multiple
101 /// applicable suggestions
103 /// `foo.bar` might be replaced with `a.b` or `x.y` by replacing
104 /// `foo` and `bar` on their own:
108 /// Substitution { parts: vec![(0..3, "a"), (4..7, "b")] },
109 /// Substitution { parts: vec![(0..3, "x"), (4..7, "y")] },
113 /// or by replacing the entire span:
117 /// Substitution { parts: vec![(0..7, "a.b")] },
118 /// Substitution { parts: vec![(0..7, "x.y")] },
121 pub substitutions: Vec<Substitution>,
123 /// Visual representation of this suggestion.
124 pub style: SuggestionStyle,
125 /// Whether or not the suggestion is approximate
127 /// Sometimes we may show suggestions with placeholders,
128 /// which are useful for users but not useful for
129 /// tools like rustfix
130 pub applicability: Applicability,
133 #[derive(Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
134 /// See the docs on `CodeSuggestion::substitutions`
135 pub struct Substitution {
136 pub parts: Vec<SubstitutionPart>,
139 #[derive(Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
140 pub struct SubstitutionPart {
145 pub type SourceMapperDyn = dyn SourceMapper + sync::Send + sync::Sync;
147 pub trait SourceMapper {
148 fn lookup_char_pos(&self, pos: BytePos) -> Loc;
149 fn span_to_lines(&self, sp: Span) -> FileLinesResult;
150 fn span_to_string(&self, sp: Span) -> String;
151 fn span_to_filename(&self, sp: Span) -> FileName;
152 fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option<Span>;
153 fn call_span_if_macro(&self, sp: Span) -> Span;
154 fn ensure_source_file_source_present(&self, source_file: Lrc<SourceFile>) -> bool;
155 fn doctest_offset_line(&self, file: &FileName, line: usize) -> usize;
158 impl CodeSuggestion {
159 /// Returns the assembled code suggestions and whether they should be shown with an underline.
160 pub fn splice_lines(&self, cm: &SourceMapperDyn)
161 -> Vec<(String, Vec<SubstitutionPart>)> {
162 use syntax_pos::{CharPos, Pos};
164 fn push_trailing(buf: &mut String,
165 line_opt: Option<&Cow<'_, str>>,
167 hi_opt: Option<&Loc>) {
168 let (lo, hi_opt) = (lo.col.to_usize(), hi_opt.map(|hi| hi.col.to_usize()));
169 if let Some(line) = line_opt {
170 if let Some(lo) = line.char_indices().map(|(i, _)| i).nth(lo) {
171 let hi_opt = hi_opt.and_then(|hi| line.char_indices().map(|(i, _)| i).nth(hi));
173 Some(hi) if hi > lo => buf.push_str(&line[lo..hi]),
175 None => buf.push_str(&line[lo..]),
178 if let None = hi_opt {
184 assert!(!self.substitutions.is_empty());
186 self.substitutions.iter().cloned().map(|mut substitution| {
187 // Assumption: all spans are in the same file, and all spans
188 // are disjoint. Sort in ascending order.
189 substitution.parts.sort_by_key(|part| part.span.lo());
191 // Find the bounding span.
192 let lo = substitution.parts.iter().map(|part| part.span.lo()).min().unwrap();
193 let hi = substitution.parts.iter().map(|part| part.span.hi()).min().unwrap();
194 let bounding_span = Span::new(lo, hi, NO_EXPANSION);
195 let lines = cm.span_to_lines(bounding_span).unwrap();
196 assert!(!lines.lines.is_empty());
198 // To build up the result, we do this for each span:
199 // - push the line segment trailing the previous span
200 // (at the beginning a "phantom" span pointing at the start of the line)
201 // - push lines between the previous and current span (if any)
202 // - if the previous and current span are not on the same line
203 // push the line segment leading up to the current span
204 // - splice in the span substitution
206 // Finally push the trailing line segment of the last span
207 let fm = &lines.file;
208 let mut prev_hi = cm.lookup_char_pos(bounding_span.lo());
209 prev_hi.col = CharPos::from_usize(0);
211 let mut prev_line = fm.get_line(lines.lines[0].line_index);
212 let mut buf = String::new();
214 for part in &substitution.parts {
215 let cur_lo = cm.lookup_char_pos(part.span.lo());
216 if prev_hi.line == cur_lo.line {
217 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, Some(&cur_lo));
219 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
220 // push lines between the previous and current span (if any)
221 for idx in prev_hi.line..(cur_lo.line - 1) {
222 if let Some(line) = fm.get_line(idx) {
223 buf.push_str(line.as_ref());
227 if let Some(cur_line) = fm.get_line(cur_lo.line - 1) {
228 buf.push_str(&cur_line[..cur_lo.col.to_usize()]);
231 buf.push_str(&part.snippet);
232 prev_hi = cm.lookup_char_pos(part.span.hi());
233 prev_line = fm.get_line(prev_hi.line - 1);
235 // if the replacement already ends with a newline, don't print the next line
236 if !buf.ends_with('\n') {
237 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
239 // remove trailing newlines
240 while buf.ends_with('\n') {
243 (buf, substitution.parts)
248 /// Used as a return value to signify a fatal error occurred. (It is also
249 /// used as the argument to panic at the moment, but that will eventually
251 #[derive(Copy, Clone, Debug)]
253 pub struct FatalError;
255 pub struct FatalErrorMarker;
257 // Don't implement Send on FatalError. This makes it impossible to panic!(FatalError).
258 // We don't want to invoke the panic handler and print a backtrace for fatal errors.
259 impl !Send for FatalError {}
262 pub fn raise(self) -> ! {
263 panic::resume_unwind(Box::new(FatalErrorMarker))
267 impl fmt::Display for FatalError {
268 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
269 write!(f, "parser fatal error")
273 impl error::Error for FatalError {
274 fn description(&self) -> &str {
275 "The parser has encountered a fatal error"
279 /// Signifies that the compiler died with an explicit call to `.bug`
280 /// or `.span_bug` rather than a failed assertion, etc.
281 #[derive(Copy, Clone, Debug)]
282 pub struct ExplicitBug;
284 impl fmt::Display for ExplicitBug {
285 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
286 write!(f, "parser internal bug")
290 impl error::Error for ExplicitBug {
291 fn description(&self) -> &str {
292 "The parser has encountered an internal bug"
296 pub use diagnostic::{Diagnostic, SubDiagnostic, DiagnosticStyledString, DiagnosticId};
297 pub use diagnostic_builder::DiagnosticBuilder;
299 /// A handler deals with errors and other compiler output.
300 /// Certain errors (fatal, bug, unimpl) may cause immediate exit,
301 /// others log errors for later reporting.
303 pub flags: HandlerFlags,
305 err_count: AtomicUsize,
306 emitter: Lock<Box<dyn Emitter + sync::Send>>,
307 continue_after_error: AtomicBool,
308 delayed_span_bugs: Lock<Vec<Diagnostic>>,
310 /// This set contains the `DiagnosticId` of all emitted diagnostics to avoid
311 /// emitting the same diagnostic with extended help (`--teach`) twice, which
312 /// would be uneccessary repetition.
313 taught_diagnostics: Lock<FxHashSet<DiagnosticId>>,
315 /// Used to suggest rustc --explain <error code>
316 emitted_diagnostic_codes: Lock<FxHashSet<DiagnosticId>>,
318 /// This set contains a hash of every diagnostic that has been emitted by
319 /// this handler. These hashes is used to avoid emitting the same error
321 emitted_diagnostics: Lock<FxHashSet<u128>>,
324 fn default_track_diagnostic(_: &Diagnostic) {}
326 thread_local!(pub static TRACK_DIAGNOSTICS: Cell<fn(&Diagnostic)> =
327 Cell::new(default_track_diagnostic));
330 pub struct HandlerFlags {
331 /// If false, warning-level lints are suppressed.
332 /// (rustc: see `--allow warnings` and `--cap-lints`)
333 pub can_emit_warnings: bool,
334 /// If true, error-level diagnostics are upgraded to bug-level.
335 /// (rustc: see `-Z treat-err-as-bug`)
336 pub treat_err_as_bug: Option<usize>,
337 /// If true, immediately emit diagnostics that would otherwise be buffered.
338 /// (rustc: see `-Z dont-buffer-diagnostics` and `-Z treat-err-as-bug`)
339 pub dont_buffer_diagnostics: bool,
340 /// If true, immediately print bugs registered with `delay_span_bug`.
341 /// (rustc: see `-Z report-delayed-bugs`)
342 pub report_delayed_bugs: bool,
343 /// show macro backtraces even for non-local macros.
344 /// (rustc: see `-Z external-macro-backtrace`)
345 pub external_macro_backtrace: bool,
348 impl Drop for Handler {
350 if self.err_count() == 0 {
351 let mut bugs = self.delayed_span_bugs.borrow_mut();
352 let has_bugs = !bugs.is_empty();
353 for bug in bugs.drain(..) {
354 DiagnosticBuilder::new_diagnostic(self, bug).emit();
357 panic!("no errors encountered even though `delay_span_bug` issued");
364 pub fn with_tty_emitter(color_config: ColorConfig,
365 can_emit_warnings: bool,
366 treat_err_as_bug: Option<usize>,
367 cm: Option<Lrc<SourceMapperDyn>>)
369 Handler::with_tty_emitter_and_flags(
375 .. Default::default()
379 pub fn with_tty_emitter_and_flags(color_config: ColorConfig,
380 cm: Option<Lrc<SourceMapperDyn>>,
383 let emitter = Box::new(EmitterWriter::stderr(color_config, cm, false, false));
384 Handler::with_emitter_and_flags(emitter, flags)
387 pub fn with_emitter(can_emit_warnings: bool,
388 treat_err_as_bug: Option<usize>,
389 e: Box<dyn Emitter + sync::Send>)
391 Handler::with_emitter_and_flags(
396 .. Default::default()
400 pub fn with_emitter_and_flags(e: Box<dyn Emitter + sync::Send>, flags: HandlerFlags) -> Handler
404 err_count: AtomicUsize::new(0),
405 emitter: Lock::new(e),
406 continue_after_error: AtomicBool::new(true),
407 delayed_span_bugs: Lock::new(Vec::new()),
408 taught_diagnostics: Default::default(),
409 emitted_diagnostic_codes: Default::default(),
410 emitted_diagnostics: Default::default(),
414 pub fn set_continue_after_error(&self, continue_after_error: bool) {
415 self.continue_after_error.store(continue_after_error, SeqCst);
418 /// Resets the diagnostic error count as well as the cached emitted diagnostics.
420 /// NOTE: *do not* call this function from rustc. It is only meant to be called from external
421 /// tools that want to reuse a `Parser` cleaning the previously emitted diagnostics as well as
422 /// the overall count of emitted error diagnostics.
423 pub fn reset_err_count(&self) {
424 // actually frees the underlying memory (which `clear` would not do)
425 *self.emitted_diagnostics.borrow_mut() = Default::default();
426 self.err_count.store(0, SeqCst);
429 pub fn struct_dummy<'a>(&'a self) -> DiagnosticBuilder<'a> {
430 DiagnosticBuilder::new(self, Level::Cancelled, "")
433 pub fn struct_span_warn<'a, S: Into<MultiSpan>>(&'a self,
436 -> DiagnosticBuilder<'a> {
437 let mut result = DiagnosticBuilder::new(self, Level::Warning, msg);
439 if !self.flags.can_emit_warnings {
444 pub fn struct_span_warn_with_code<'a, S: Into<MultiSpan>>(&'a self,
448 -> DiagnosticBuilder<'a> {
449 let mut result = DiagnosticBuilder::new(self, Level::Warning, msg);
452 if !self.flags.can_emit_warnings {
457 pub fn struct_warn<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
458 let mut result = DiagnosticBuilder::new(self, Level::Warning, msg);
459 if !self.flags.can_emit_warnings {
464 pub fn struct_span_err<'a, S: Into<MultiSpan>>(&'a self,
467 -> DiagnosticBuilder<'a> {
468 let mut result = DiagnosticBuilder::new(self, Level::Error, msg);
472 pub fn struct_span_err_with_code<'a, S: Into<MultiSpan>>(&'a self,
476 -> DiagnosticBuilder<'a> {
477 let mut result = DiagnosticBuilder::new(self, Level::Error, msg);
482 // FIXME: This method should be removed (every error should have an associated error code).
483 pub fn struct_err<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
484 DiagnosticBuilder::new(self, Level::Error, msg)
486 pub fn struct_err_with_code<'a>(
490 ) -> DiagnosticBuilder<'a> {
491 let mut result = DiagnosticBuilder::new(self, Level::Error, msg);
495 pub fn struct_span_fatal<'a, S: Into<MultiSpan>>(&'a self,
498 -> DiagnosticBuilder<'a> {
499 let mut result = DiagnosticBuilder::new(self, Level::Fatal, msg);
503 pub fn struct_span_fatal_with_code<'a, S: Into<MultiSpan>>(&'a self,
507 -> DiagnosticBuilder<'a> {
508 let mut result = DiagnosticBuilder::new(self, Level::Fatal, msg);
513 pub fn struct_fatal<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
514 DiagnosticBuilder::new(self, Level::Fatal, msg)
517 pub fn cancel(&self, err: &mut DiagnosticBuilder<'_>) {
521 fn panic_if_treat_err_as_bug(&self) {
522 if self.treat_err_as_bug() {
523 let s = match (self.err_count(), self.flags.treat_err_as_bug.unwrap_or(0)) {
525 (1, 1) => "aborting due to `-Z treat-err-as-bug=1`".to_string(),
529 "aborting after {} errors due to `-Z treat-err-as-bug={}`",
539 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> FatalError {
540 self.emit(&sp.into(), msg, Fatal);
543 pub fn span_fatal_with_code<S: Into<MultiSpan>>(&self,
548 self.emit_with_code(&sp.into(), msg, code, Fatal);
551 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
552 self.emit(&sp.into(), msg, Error);
554 pub fn mut_span_err<'a, S: Into<MultiSpan>>(&'a self,
557 -> DiagnosticBuilder<'a> {
558 let mut result = DiagnosticBuilder::new(self, Level::Error, msg);
562 pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
563 self.emit_with_code(&sp.into(), msg, code, Error);
565 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
566 self.emit(&sp.into(), msg, Warning);
568 pub fn span_warn_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
569 self.emit_with_code(&sp.into(), msg, code, Warning);
571 pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
572 self.emit(&sp.into(), msg, Bug);
575 pub fn delay_span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
576 if self.treat_err_as_bug() {
577 // FIXME: don't abort here if report_delayed_bugs is off
578 self.span_bug(sp, msg);
580 let mut diagnostic = Diagnostic::new(Level::Bug, msg);
581 diagnostic.set_span(sp.into());
582 self.delay_as_bug(diagnostic);
584 fn delay_as_bug(&self, diagnostic: Diagnostic) {
585 if self.flags.report_delayed_bugs {
586 DiagnosticBuilder::new_diagnostic(self, diagnostic.clone()).emit();
588 self.delayed_span_bugs.borrow_mut().push(diagnostic);
590 pub fn span_bug_no_panic<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
591 self.emit(&sp.into(), msg, Bug);
593 pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
594 self.emit(&sp.into(), msg, Note);
596 pub fn span_note_diag<'a>(&'a self,
599 -> DiagnosticBuilder<'a> {
600 let mut db = DiagnosticBuilder::new(self, Note, msg);
604 pub fn span_unimpl<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
605 self.span_bug(sp, &format!("unimplemented {}", msg));
607 pub fn failure(&self, msg: &str) {
608 DiagnosticBuilder::new(self, FailureNote, msg).emit()
610 pub fn fatal(&self, msg: &str) -> FatalError {
611 if self.treat_err_as_bug() {
614 DiagnosticBuilder::new(self, Fatal, msg).emit();
617 pub fn err(&self, msg: &str) {
618 if self.treat_err_as_bug() {
621 let mut db = DiagnosticBuilder::new(self, Error, msg);
624 pub fn warn(&self, msg: &str) {
625 let mut db = DiagnosticBuilder::new(self, Warning, msg);
628 fn treat_err_as_bug(&self) -> bool {
629 self.flags.treat_err_as_bug.map(|c| self.err_count() >= c).unwrap_or(false)
631 pub fn note_without_error(&self, msg: &str) {
632 let mut db = DiagnosticBuilder::new(self, Note, msg);
635 pub fn bug(&self, msg: &str) -> ! {
636 let mut db = DiagnosticBuilder::new(self, Bug, msg);
640 pub fn unimpl(&self, msg: &str) -> ! {
641 self.bug(&format!("unimplemented {}", msg));
644 fn bump_err_count(&self) {
645 self.err_count.fetch_add(1, SeqCst);
646 self.panic_if_treat_err_as_bug();
649 pub fn err_count(&self) -> usize {
650 self.err_count.load(SeqCst)
653 pub fn has_errors(&self) -> bool {
657 pub fn print_error_count(&self, registry: &Registry) {
658 let s = match self.err_count() {
660 1 => "aborting due to previous error".to_string(),
661 _ => format!("aborting due to {} previous errors", self.err_count())
663 if self.treat_err_as_bug() {
667 let _ = self.fatal(&s);
669 let can_show_explain = self.emitter.borrow().should_show_explain();
670 let are_there_diagnostics = !self.emitted_diagnostic_codes.borrow().is_empty();
671 if can_show_explain && are_there_diagnostics {
672 let mut error_codes = self
673 .emitted_diagnostic_codes
676 .filter_map(|x| match &x {
677 DiagnosticId::Error(s) if registry.find_description(s).is_some() => {
682 .collect::<Vec<_>>();
683 if !error_codes.is_empty() {
685 if error_codes.len() > 1 {
686 let limit = if error_codes.len() > 9 { 9 } else { error_codes.len() };
687 self.failure(&format!("Some errors have detailed explanations: {}{}",
688 error_codes[..limit].join(", "),
689 if error_codes.len() > 9 { "..." } else { "." }));
690 self.failure(&format!("For more information about an error, try \
691 `rustc --explain {}`.",
694 self.failure(&format!("For more information about this error, try \
695 `rustc --explain {}`.",
702 pub fn abort_if_errors(&self) {
703 if self.err_count() == 0 {
708 pub fn emit(&self, msp: &MultiSpan, msg: &str, lvl: Level) {
709 if lvl == Warning && !self.flags.can_emit_warnings {
712 let mut db = DiagnosticBuilder::new(self, lvl, msg);
713 db.set_span(msp.clone());
715 if !self.continue_after_error.load(SeqCst) {
716 self.abort_if_errors();
719 pub fn emit_with_code(&self, msp: &MultiSpan, msg: &str, code: DiagnosticId, lvl: Level) {
720 if lvl == Warning && !self.flags.can_emit_warnings {
723 let mut db = DiagnosticBuilder::new_with_code(self, lvl, Some(code), msg);
724 db.set_span(msp.clone());
726 if !self.continue_after_error.load(SeqCst) {
727 self.abort_if_errors();
731 /// `true` if we haven't taught a diagnostic with this code already.
732 /// The caller must then teach the user about such a diagnostic.
734 /// Used to suppress emitting the same error multiple times with extended explanation when
735 /// calling `-Zteach`.
736 pub fn must_teach(&self, code: &DiagnosticId) -> bool {
737 self.taught_diagnostics.borrow_mut().insert(code.clone())
740 pub fn force_print_db(&self, mut db: DiagnosticBuilder<'_>) {
741 self.emitter.borrow_mut().emit_diagnostic(&db);
745 fn emit_db(&self, db: &DiagnosticBuilder<'_>) {
746 let diagnostic = &**db;
748 TRACK_DIAGNOSTICS.with(|track_diagnostics| {
749 track_diagnostics.get()(diagnostic);
752 if let Some(ref code) = diagnostic.code {
753 self.emitted_diagnostic_codes.borrow_mut().insert(code.clone());
756 let diagnostic_hash = {
758 let mut hasher = StableHasher::new();
759 diagnostic.hash(&mut hasher);
763 // Only emit the diagnostic if we haven't already emitted an equivalent
765 if self.emitted_diagnostics.borrow_mut().insert(diagnostic_hash) {
766 self.emitter.borrow_mut().emit_diagnostic(db);
768 self.bump_err_count();
773 pub fn emit_artifact_notification(&self, path: &Path, artifact_type: &str) {
774 self.emitter.borrow_mut().emit_artifact_notification(path, artifact_type);
778 #[derive(Copy, PartialEq, Clone, Hash, Debug, RustcEncodable, RustcDecodable)]
782 // An error which while not immediately fatal, should stop the compiler
783 // progressing beyond the current phase.
793 impl fmt::Display for Level {
794 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
800 fn color(self) -> ColorSpec {
801 let mut spec = ColorSpec::new();
803 Bug | Fatal | PhaseFatal | Error => {
804 spec.set_fg(Some(Color::Red))
808 spec.set_fg(Some(Color::Yellow))
809 .set_intense(cfg!(windows));
812 spec.set_fg(Some(Color::Green))
816 spec.set_fg(Some(Color::Cyan))
820 Cancelled => unreachable!(),
825 pub fn to_str(self) -> &'static str {
827 Bug => "error: internal compiler error",
828 Fatal | PhaseFatal | Error => "error",
829 Warning => "warning",
833 Cancelled => panic!("Shouldn't call on cancelled error"),
837 pub fn is_failure_note(&self) -> bool {