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 #![cfg_attr(unix, feature(libc))]
10 #![feature(optin_builtin_traits)]
12 pub use emitter::ColorConfig;
16 use emitter::{Emitter, EmitterWriter};
17 use registry::Registry;
19 use rustc_data_structures::sync::{self, Lrc, Lock, AtomicUsize, AtomicBool, SeqCst};
20 use rustc_data_structures::fx::FxHashSet;
21 use rustc_data_structures::stable_hasher::StableHasher;
25 use std::{error, fmt};
29 use termcolor::{ColorSpec, Color};
32 mod diagnostic_builder;
34 pub mod annotate_snippet_emitter_writer;
40 use syntax_pos::{BytePos,
48 /// Indicates the confidence in the correctness of a suggestion.
50 /// All suggestions are marked with an `Applicability`. Tools use the applicability of a suggestion
51 /// to determine whether it should be automatically applied or if the user should be consulted
52 /// before applying the suggestion.
53 #[derive(Copy, Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
54 pub enum Applicability {
55 /// The suggestion is definitely what the user intended. This suggestion should be
56 /// automatically applied.
59 /// The suggestion may be what the user intended, but it is uncertain. The suggestion should
60 /// result in valid Rust code if it is applied.
63 /// The suggestion contains placeholders like `(...)` or `{ /* fields */ }`. The suggestion
64 /// cannot be applied automatically because it will not result in valid Rust code. The user
65 /// will need to fill in the placeholders.
68 /// The applicability of the suggestion is unknown.
72 #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, RustcEncodable, RustcDecodable)]
73 pub enum SuggestionStyle {
74 /// Hide the suggested code when displaying this suggestion inline.
76 /// Always hide the suggested code but display the message.
78 /// Do not display this suggestion in the cli output, it is only meant for tools.
80 /// Always show the suggested code.
81 /// This will *not* show the code if the suggestion is inline *and* the suggested code is
86 impl SuggestionStyle {
87 fn hide_inline(&self) -> bool {
89 SuggestionStyle::ShowCode => false,
95 #[derive(Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
96 pub struct CodeSuggestion {
97 /// Each substitute can have multiple variants due to multiple
98 /// applicable suggestions
100 /// `foo.bar` might be replaced with `a.b` or `x.y` by replacing
101 /// `foo` and `bar` on their own:
105 /// Substitution { parts: vec![(0..3, "a"), (4..7, "b")] },
106 /// Substitution { parts: vec![(0..3, "x"), (4..7, "y")] },
110 /// or by replacing the entire span:
114 /// Substitution { parts: vec![(0..7, "a.b")] },
115 /// Substitution { parts: vec![(0..7, "x.y")] },
118 pub substitutions: Vec<Substitution>,
120 /// Visual representation of this suggestion.
121 pub style: SuggestionStyle,
122 /// Whether or not the suggestion is approximate
124 /// Sometimes we may show suggestions with placeholders,
125 /// which are useful for users but not useful for
126 /// tools like rustfix
127 pub applicability: Applicability,
130 #[derive(Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
131 /// See the docs on `CodeSuggestion::substitutions`
132 pub struct Substitution {
133 pub parts: Vec<SubstitutionPart>,
136 #[derive(Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
137 pub struct SubstitutionPart {
142 pub type SourceMapperDyn = dyn SourceMapper + sync::Send + sync::Sync;
144 pub trait SourceMapper {
145 fn lookup_char_pos(&self, pos: BytePos) -> Loc;
146 fn span_to_lines(&self, sp: Span) -> FileLinesResult;
147 fn span_to_string(&self, sp: Span) -> String;
148 fn span_to_filename(&self, sp: Span) -> FileName;
149 fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option<Span>;
150 fn call_span_if_macro(&self, sp: Span) -> Span;
151 fn ensure_source_file_source_present(&self, source_file: Lrc<SourceFile>) -> bool;
152 fn doctest_offset_line(&self, file: &FileName, line: usize) -> usize;
155 impl CodeSuggestion {
156 /// Returns the assembled code suggestions and whether they should be shown with an underline.
157 pub fn splice_lines(&self, cm: &SourceMapperDyn)
158 -> Vec<(String, Vec<SubstitutionPart>)> {
159 use syntax_pos::{CharPos, Pos};
161 fn push_trailing(buf: &mut String,
162 line_opt: Option<&Cow<'_, str>>,
164 hi_opt: Option<&Loc>) {
165 let (lo, hi_opt) = (lo.col.to_usize(), hi_opt.map(|hi| hi.col.to_usize()));
166 if let Some(line) = line_opt {
167 if let Some(lo) = line.char_indices().map(|(i, _)| i).nth(lo) {
168 let hi_opt = hi_opt.and_then(|hi| line.char_indices().map(|(i, _)| i).nth(hi));
170 Some(hi) if hi > lo => buf.push_str(&line[lo..hi]),
172 None => buf.push_str(&line[lo..]),
175 if let None = hi_opt {
181 assert!(!self.substitutions.is_empty());
183 self.substitutions.iter().cloned().map(|mut substitution| {
184 // Assumption: all spans are in the same file, and all spans
185 // are disjoint. Sort in ascending order.
186 substitution.parts.sort_by_key(|part| part.span.lo());
188 // Find the bounding span.
189 let lo = substitution.parts.iter().map(|part| part.span.lo()).min().unwrap();
190 let hi = substitution.parts.iter().map(|part| part.span.hi()).min().unwrap();
191 let bounding_span = Span::with_root_ctxt(lo, hi);
192 let lines = cm.span_to_lines(bounding_span).unwrap();
193 assert!(!lines.lines.is_empty());
195 // To build up the result, we do this for each span:
196 // - push the line segment trailing the previous span
197 // (at the beginning a "phantom" span pointing at the start of the line)
198 // - push lines between the previous and current span (if any)
199 // - if the previous and current span are not on the same line
200 // push the line segment leading up to the current span
201 // - splice in the span substitution
203 // Finally push the trailing line segment of the last span
204 let fm = &lines.file;
205 let mut prev_hi = cm.lookup_char_pos(bounding_span.lo());
206 prev_hi.col = CharPos::from_usize(0);
208 let mut prev_line = fm.get_line(lines.lines[0].line_index);
209 let mut buf = String::new();
211 for part in &substitution.parts {
212 let cur_lo = cm.lookup_char_pos(part.span.lo());
213 if prev_hi.line == cur_lo.line {
214 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, Some(&cur_lo));
216 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
217 // push lines between the previous and current span (if any)
218 for idx in prev_hi.line..(cur_lo.line - 1) {
219 if let Some(line) = fm.get_line(idx) {
220 buf.push_str(line.as_ref());
224 if let Some(cur_line) = fm.get_line(cur_lo.line - 1) {
225 let end = std::cmp::min(cur_line.len(), cur_lo.col.to_usize());
226 buf.push_str(&cur_line[..end]);
229 buf.push_str(&part.snippet);
230 prev_hi = cm.lookup_char_pos(part.span.hi());
231 prev_line = fm.get_line(prev_hi.line - 1);
233 // if the replacement already ends with a newline, don't print the next line
234 if !buf.ends_with('\n') {
235 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
237 // remove trailing newlines
238 while buf.ends_with('\n') {
241 (buf, substitution.parts)
246 /// Used as a return value to signify a fatal error occurred. (It is also
247 /// used as the argument to panic at the moment, but that will eventually
249 #[derive(Copy, Clone, Debug)]
251 pub struct FatalError;
253 pub struct FatalErrorMarker;
255 // Don't implement Send on FatalError. This makes it impossible to panic!(FatalError).
256 // We don't want to invoke the panic handler and print a backtrace for fatal errors.
257 impl !Send for FatalError {}
260 pub fn raise(self) -> ! {
261 panic::resume_unwind(Box::new(FatalErrorMarker))
265 impl fmt::Display for FatalError {
266 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
267 write!(f, "parser fatal error")
271 impl error::Error for FatalError {
272 fn description(&self) -> &str {
273 "The parser has encountered a fatal error"
277 /// Signifies that the compiler died with an explicit call to `.bug`
278 /// or `.span_bug` rather than a failed assertion, etc.
279 #[derive(Copy, Clone, Debug)]
280 pub struct ExplicitBug;
282 impl fmt::Display for ExplicitBug {
283 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
284 write!(f, "parser internal bug")
288 impl error::Error for ExplicitBug {
289 fn description(&self) -> &str {
290 "The parser has encountered an internal bug"
294 pub use diagnostic::{Diagnostic, SubDiagnostic, DiagnosticStyledString, DiagnosticId};
295 pub use diagnostic_builder::DiagnosticBuilder;
297 /// A handler deals with errors and other compiler output.
298 /// Certain errors (fatal, bug, unimpl) may cause immediate exit,
299 /// others log errors for later reporting.
301 pub flags: HandlerFlags,
303 /// The number of errors that have been emitted, including duplicates.
305 /// This is not necessarily the count that's reported to the user once
306 /// compilation ends.
307 err_count: AtomicUsize,
308 deduplicated_err_count: AtomicUsize,
309 emitter: Lock<Box<dyn Emitter + sync::Send>>,
310 continue_after_error: AtomicBool,
311 delayed_span_bugs: Lock<Vec<Diagnostic>>,
313 /// This set contains the `DiagnosticId` of all emitted diagnostics to avoid
314 /// emitting the same diagnostic with extended help (`--teach`) twice, which
315 /// would be uneccessary repetition.
316 taught_diagnostics: Lock<FxHashSet<DiagnosticId>>,
318 /// Used to suggest rustc --explain <error code>
319 emitted_diagnostic_codes: Lock<FxHashSet<DiagnosticId>>,
321 /// This set contains a hash of every diagnostic that has been emitted by
322 /// this handler. These hashes is used to avoid emitting the same error
324 emitted_diagnostics: Lock<FxHashSet<u128>>,
327 fn default_track_diagnostic(_: &Diagnostic) {}
329 thread_local!(pub static TRACK_DIAGNOSTICS: Cell<fn(&Diagnostic)> =
330 Cell::new(default_track_diagnostic));
333 pub struct HandlerFlags {
334 /// If false, warning-level lints are suppressed.
335 /// (rustc: see `--allow warnings` and `--cap-lints`)
336 pub can_emit_warnings: bool,
337 /// If true, error-level diagnostics are upgraded to bug-level.
338 /// (rustc: see `-Z treat-err-as-bug`)
339 pub treat_err_as_bug: Option<usize>,
340 /// If true, immediately emit diagnostics that would otherwise be buffered.
341 /// (rustc: see `-Z dont-buffer-diagnostics` and `-Z treat-err-as-bug`)
342 pub dont_buffer_diagnostics: bool,
343 /// If true, immediately print bugs registered with `delay_span_bug`.
344 /// (rustc: see `-Z report-delayed-bugs`)
345 pub report_delayed_bugs: bool,
346 /// show macro backtraces even for non-local macros.
347 /// (rustc: see `-Z external-macro-backtrace`)
348 pub external_macro_backtrace: bool,
351 impl Drop for Handler {
353 if !self.has_errors() {
354 let mut bugs = self.delayed_span_bugs.borrow_mut();
355 let has_bugs = !bugs.is_empty();
356 for bug in bugs.drain(..) {
357 DiagnosticBuilder::new_diagnostic(self, bug).emit();
360 panic!("no errors encountered even though `delay_span_bug` issued");
367 pub fn with_tty_emitter(color_config: ColorConfig,
368 can_emit_warnings: bool,
369 treat_err_as_bug: Option<usize>,
370 cm: Option<Lrc<SourceMapperDyn>>)
372 Handler::with_tty_emitter_and_flags(
378 .. Default::default()
382 pub fn with_tty_emitter_and_flags(color_config: ColorConfig,
383 cm: Option<Lrc<SourceMapperDyn>>,
386 let emitter = Box::new(EmitterWriter::stderr(
387 color_config, cm, false, false, None, flags.external_macro_backtrace));
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 deduplicated_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.deduplicated_err_count.store(0, SeqCst);
432 self.err_count.store(0, SeqCst);
435 pub fn struct_dummy(&self) -> DiagnosticBuilder<'_> {
436 DiagnosticBuilder::new(self, Level::Cancelled, "")
439 pub fn struct_span_warn<S: Into<MultiSpan>>(&self,
442 -> DiagnosticBuilder<'_> {
443 let mut result = DiagnosticBuilder::new(self, Level::Warning, msg);
445 if !self.flags.can_emit_warnings {
450 pub fn struct_span_warn_with_code<S: Into<MultiSpan>>(&self,
454 -> DiagnosticBuilder<'_> {
455 let mut result = DiagnosticBuilder::new(self, Level::Warning, msg);
458 if !self.flags.can_emit_warnings {
463 pub fn struct_warn(&self, msg: &str) -> DiagnosticBuilder<'_> {
464 let mut result = DiagnosticBuilder::new(self, Level::Warning, msg);
465 if !self.flags.can_emit_warnings {
470 pub fn struct_span_err<S: Into<MultiSpan>>(&self,
473 -> DiagnosticBuilder<'_> {
474 let mut result = DiagnosticBuilder::new(self, Level::Error, msg);
478 pub fn struct_span_err_with_code<S: Into<MultiSpan>>(&self,
482 -> DiagnosticBuilder<'_> {
483 let mut result = DiagnosticBuilder::new(self, Level::Error, msg);
488 // FIXME: This method should be removed (every error should have an associated error code).
489 pub fn struct_err(&self, msg: &str) -> DiagnosticBuilder<'_> {
490 DiagnosticBuilder::new(self, Level::Error, msg)
492 pub fn struct_err_with_code(
496 ) -> DiagnosticBuilder<'_> {
497 let mut result = DiagnosticBuilder::new(self, Level::Error, msg);
501 pub fn struct_span_fatal<S: Into<MultiSpan>>(&self,
504 -> DiagnosticBuilder<'_> {
505 let mut result = DiagnosticBuilder::new(self, Level::Fatal, msg);
509 pub fn struct_span_fatal_with_code<S: Into<MultiSpan>>(&self,
513 -> DiagnosticBuilder<'_> {
514 let mut result = DiagnosticBuilder::new(self, Level::Fatal, msg);
519 pub fn struct_fatal(&self, msg: &str) -> DiagnosticBuilder<'_> {
520 DiagnosticBuilder::new(self, Level::Fatal, msg)
523 fn panic_if_treat_err_as_bug(&self) {
524 if self.treat_err_as_bug() {
525 let s = match (self.err_count(), self.flags.treat_err_as_bug.unwrap_or(0)) {
527 (1, 1) => "aborting due to `-Z treat-err-as-bug=1`".to_string(),
531 "aborting after {} errors due to `-Z treat-err-as-bug={}`",
541 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> FatalError {
542 self.emit(&sp.into(), msg, Fatal);
545 pub fn span_fatal_with_code<S: Into<MultiSpan>>(&self,
550 self.emit_with_code(&sp.into(), msg, code, Fatal);
553 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
554 self.emit(&sp.into(), msg, Error);
556 pub fn mut_span_err<S: Into<MultiSpan>>(&self,
559 -> DiagnosticBuilder<'_> {
560 let mut result = DiagnosticBuilder::new(self, Level::Error, msg);
564 pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
565 self.emit_with_code(&sp.into(), msg, code, Error);
567 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
568 self.emit(&sp.into(), msg, Warning);
570 pub fn span_warn_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
571 self.emit_with_code(&sp.into(), msg, code, Warning);
573 pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
574 self.emit(&sp.into(), msg, Bug);
577 pub fn delay_span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
578 if self.treat_err_as_bug() {
579 // FIXME: don't abort here if report_delayed_bugs is off
580 self.span_bug(sp, msg);
582 let mut diagnostic = Diagnostic::new(Level::Bug, msg);
583 diagnostic.set_span(sp.into());
584 self.delay_as_bug(diagnostic);
586 fn delay_as_bug(&self, diagnostic: Diagnostic) {
587 if self.flags.report_delayed_bugs {
588 self.emit_diagnostic(&diagnostic);
590 self.delayed_span_bugs.borrow_mut().push(diagnostic);
592 pub fn span_bug_no_panic<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
593 self.emit(&sp.into(), msg, Bug);
595 pub fn span_note_without_error<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
596 self.emit(&sp.into(), msg, Note);
598 pub fn span_note_diag(&self,
601 -> DiagnosticBuilder<'_> {
602 let mut db = DiagnosticBuilder::new(self, Note, msg);
606 pub fn span_unimpl<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
607 self.span_bug(sp, &format!("unimplemented {}", msg));
609 pub fn failure(&self, msg: &str) {
610 DiagnosticBuilder::new(self, FailureNote, msg).emit()
612 pub fn fatal(&self, msg: &str) -> FatalError {
613 if self.treat_err_as_bug() {
616 DiagnosticBuilder::new(self, Fatal, msg).emit();
619 pub fn err(&self, msg: &str) {
620 if self.treat_err_as_bug() {
623 let mut db = DiagnosticBuilder::new(self, Error, msg);
626 pub fn warn(&self, msg: &str) {
627 let mut db = DiagnosticBuilder::new(self, Warning, msg);
630 fn treat_err_as_bug(&self) -> bool {
631 self.flags.treat_err_as_bug.map(|c| self.err_count() >= c).unwrap_or(false)
633 pub fn note_without_error(&self, msg: &str) {
634 let mut db = DiagnosticBuilder::new(self, Note, msg);
637 pub fn bug(&self, msg: &str) -> ! {
638 let mut db = DiagnosticBuilder::new(self, Bug, msg);
642 pub fn unimpl(&self, msg: &str) -> ! {
643 self.bug(&format!("unimplemented {}", msg));
646 fn bump_err_count(&self) {
647 self.err_count.fetch_add(1, SeqCst);
648 self.panic_if_treat_err_as_bug();
651 pub fn err_count(&self) -> usize {
652 self.err_count.load(SeqCst)
655 pub fn has_errors(&self) -> bool {
659 pub fn print_error_count(&self, registry: &Registry) {
660 let s = match self.deduplicated_err_count.load(SeqCst) {
662 1 => "aborting due to previous error".to_string(),
663 count => format!("aborting due to {} previous errors", count)
665 if self.treat_err_as_bug() {
669 let _ = self.fatal(&s);
671 let can_show_explain = self.emitter.borrow().should_show_explain();
672 let are_there_diagnostics = !self.emitted_diagnostic_codes.borrow().is_empty();
673 if can_show_explain && are_there_diagnostics {
674 let mut error_codes = self
675 .emitted_diagnostic_codes
678 .filter_map(|x| match &x {
679 DiagnosticId::Error(s) if registry.find_description(s).is_some() => {
684 .collect::<Vec<_>>();
685 if !error_codes.is_empty() {
687 if error_codes.len() > 1 {
688 let limit = if error_codes.len() > 9 { 9 } else { error_codes.len() };
689 self.failure(&format!("Some errors have detailed explanations: {}{}",
690 error_codes[..limit].join(", "),
691 if error_codes.len() > 9 { "..." } else { "." }));
692 self.failure(&format!("For more information about an error, try \
693 `rustc --explain {}`.",
696 self.failure(&format!("For more information about this error, try \
697 `rustc --explain {}`.",
704 pub fn abort_if_errors(&self) {
705 if self.has_errors() {
709 pub fn emit(&self, msp: &MultiSpan, msg: &str, lvl: Level) {
710 if lvl == Warning && !self.flags.can_emit_warnings {
713 let mut db = DiagnosticBuilder::new(self, lvl, msg);
714 db.set_span(msp.clone());
716 if !self.continue_after_error.load(SeqCst) {
717 self.abort_if_errors();
720 pub fn emit_with_code(&self, msp: &MultiSpan, msg: &str, code: DiagnosticId, lvl: Level) {
721 if lvl == Warning && !self.flags.can_emit_warnings {
724 let mut db = DiagnosticBuilder::new_with_code(self, lvl, Some(code), msg);
725 db.set_span(msp.clone());
727 if !self.continue_after_error.load(SeqCst) {
728 self.abort_if_errors();
732 /// `true` if we haven't taught a diagnostic with this code already.
733 /// The caller must then teach the user about such a diagnostic.
735 /// Used to suppress emitting the same error multiple times with extended explanation when
736 /// calling `-Zteach`.
737 pub fn must_teach(&self, code: &DiagnosticId) -> bool {
738 self.taught_diagnostics.borrow_mut().insert(code.clone())
741 pub fn force_print_diagnostic(&self, db: Diagnostic) {
742 self.emitter.borrow_mut().emit_diagnostic(&db);
745 pub fn emit_diagnostic(&self, diagnostic: &Diagnostic) {
746 if diagnostic.cancelled() {
750 TRACK_DIAGNOSTICS.with(|track_diagnostics| {
751 track_diagnostics.get()(diagnostic);
754 if let Some(ref code) = diagnostic.code {
755 self.emitted_diagnostic_codes.borrow_mut().insert(code.clone());
758 let diagnostic_hash = {
760 let mut hasher = StableHasher::new();
761 diagnostic.hash(&mut hasher);
765 // Only emit the diagnostic if we haven't already emitted an equivalent
767 if self.emitted_diagnostics.borrow_mut().insert(diagnostic_hash) {
768 self.emitter.borrow_mut().emit_diagnostic(diagnostic);
769 if diagnostic.is_error() {
770 self.deduplicated_err_count.fetch_add(1, SeqCst);
773 if diagnostic.is_error() {
774 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)]
795 impl fmt::Display for Level {
796 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
802 fn color(self) -> ColorSpec {
803 let mut spec = ColorSpec::new();
805 Bug | Fatal | Error => {
806 spec.set_fg(Some(Color::Red))
810 spec.set_fg(Some(Color::Yellow))
811 .set_intense(cfg!(windows));
814 spec.set_fg(Some(Color::Green))
818 spec.set_fg(Some(Color::Cyan))
822 Cancelled => unreachable!(),
827 pub fn to_str(self) -> &'static str {
829 Bug => "error: internal compiler error",
830 Fatal | Error => "error",
831 Warning => "warning",
835 Cancelled => panic!("Shouldn't call on cancelled error"),
839 pub fn is_failure_note(&self) -> bool {
848 macro_rules! pluralise {
850 if $x != 1 { "s" } else { "" }