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/")]
6 #![feature(crate_visibility_modifier)]
7 #![cfg_attr(unix, feature(libc))]
9 #![feature(optin_builtin_traits)]
11 pub use emitter::ColorConfig;
16 use emitter::{is_case_difference, Emitter, EmitterWriter};
17 use registry::Registry;
18 use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
19 use rustc_data_structures::stable_hasher::StableHasher;
20 use rustc_data_structures::sync::{self, Lock, Lrc};
21 use rustc_data_structures::AtomicRef;
22 use rustc_span::source_map::SourceMap;
23 use rustc_span::{Loc, MultiSpan, Span};
28 use std::{error, fmt};
30 use termcolor::{Color, ColorSpec};
32 pub mod annotate_snippet_emitter_writer;
34 mod diagnostic_builder;
41 pub use snippet::Style;
43 pub type PResult<'a, T> = Result<T, DiagnosticBuilder<'a>>;
45 // `PResult` is used a lot. Make sure it doesn't unintentionally get bigger.
46 // (See also the comment on `DiagnosticBuilderInner`.)
47 #[cfg(target_arch = "x86_64")]
48 rustc_data_structures::static_assert_size!(PResult<'_, bool>, 16);
50 /// Indicates the confidence in the correctness of a suggestion.
52 /// All suggestions are marked with an `Applicability`. Tools use the applicability of a suggestion
53 /// to determine whether it should be automatically applied or if the user should be consulted
54 /// before applying the suggestion.
55 #[derive(Copy, Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
56 pub enum Applicability {
57 /// The suggestion is definitely what the user intended. This suggestion should be
58 /// automatically applied.
61 /// The suggestion may be what the user intended, but it is uncertain. The suggestion should
62 /// result in valid Rust code if it is applied.
65 /// The suggestion contains placeholders like `(...)` or `{ /* fields */ }`. The suggestion
66 /// cannot be applied automatically because it will not result in valid Rust code. The user
67 /// will need to fill in the placeholders.
70 /// The applicability of the suggestion is unknown.
74 #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, RustcEncodable, RustcDecodable)]
75 pub enum SuggestionStyle {
76 /// Hide the suggested code when displaying this suggestion inline.
78 /// Always hide the suggested code but display the message.
80 /// Do not display this suggestion in the cli output, it is only meant for tools.
82 /// Always show the suggested code.
83 /// This will *not* show the code if the suggestion is inline *and* the suggested code is
86 /// Always show the suggested code independently.
90 impl SuggestionStyle {
91 fn hide_inline(&self) -> bool {
93 SuggestionStyle::ShowCode => false,
99 #[derive(Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
100 pub struct CodeSuggestion {
101 /// Each substitute can have multiple variants due to multiple
102 /// applicable suggestions
104 /// `foo.bar` might be replaced with `a.b` or `x.y` by replacing
105 /// `foo` and `bar` on their own:
109 /// Substitution { parts: vec![(0..3, "a"), (4..7, "b")] },
110 /// Substitution { parts: vec![(0..3, "x"), (4..7, "y")] },
114 /// or by replacing the entire span:
118 /// Substitution { parts: vec![(0..7, "a.b")] },
119 /// Substitution { parts: vec![(0..7, "x.y")] },
122 pub substitutions: Vec<Substitution>,
124 /// Visual representation of this suggestion.
125 pub style: SuggestionStyle,
126 /// Whether or not the suggestion is approximate
128 /// Sometimes we may show suggestions with placeholders,
129 /// which are useful for users but not useful for
130 /// tools like rustfix
131 pub applicability: Applicability,
134 #[derive(Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
135 /// See the docs on `CodeSuggestion::substitutions`
136 pub struct Substitution {
137 pub parts: Vec<SubstitutionPart>,
140 #[derive(Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
141 pub struct SubstitutionPart {
146 impl CodeSuggestion {
147 /// Suggestions coming from macros can have malformed spans. This is a heavy handed approach
148 /// to avoid ICEs by ignoring the suggestion outright.
149 pub fn has_valid_spans(&self, cm: &SourceMap) -> bool {
150 !self.substitutions.iter().any(|subst| {
151 let invalid = subst.parts.iter().any(|item| cm.is_valid_span(item.span).is_err());
153 debug!("malformed span in suggestion: {:?}", subst);
159 /// Returns the assembled code suggestions, whether they should be shown with an underline
160 /// and whether the substitution only differs in capitalization.
161 pub fn splice_lines(&self, cm: &SourceMap) -> Vec<(String, Vec<SubstitutionPart>, bool)> {
162 use rustc_span::{CharPos, Pos};
166 line_opt: Option<&Cow<'_, str>>,
168 hi_opt: Option<&Loc>,
170 let (lo, hi_opt) = (lo.col.to_usize(), hi_opt.map(|hi| hi.col.to_usize()));
171 if let Some(line) = line_opt {
172 if let Some(lo) = line.char_indices().map(|(i, _)| i).nth(lo) {
173 let hi_opt = hi_opt.and_then(|hi| line.char_indices().map(|(i, _)| i).nth(hi));
175 Some(hi) if hi > lo => buf.push_str(&line[lo..hi]),
177 None => buf.push_str(&line[lo..]),
180 if let None = hi_opt {
186 assert!(!self.substitutions.is_empty());
191 .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()).max().unwrap();
199 let bounding_span = Span::with_root_ctxt(lo, hi);
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 let end = std::cmp::min(cur_line.len(), cur_lo.col.to_usize());
234 buf.push_str(&cur_line[..end]);
237 buf.push_str(&part.snippet);
238 prev_hi = cm.lookup_char_pos(part.span.hi());
239 prev_line = fm.get_line(prev_hi.line - 1);
241 let only_capitalization = is_case_difference(cm, &buf, bounding_span);
242 // if the replacement already ends with a newline, don't print the next line
243 if !buf.ends_with('\n') {
244 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
246 // remove trailing newlines
247 while buf.ends_with('\n') {
250 (buf, substitution.parts, only_capitalization)
256 pub use rustc_span::fatal_error::{FatalError, FatalErrorMarker};
258 /// Signifies that the compiler died with an explicit call to `.bug`
259 /// or `.span_bug` rather than a failed assertion, etc.
260 #[derive(Copy, Clone, Debug)]
261 pub struct ExplicitBug;
263 impl fmt::Display for ExplicitBug {
264 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
265 write!(f, "parser internal bug")
269 impl error::Error for ExplicitBug {}
271 pub use diagnostic::{Diagnostic, DiagnosticId, DiagnosticStyledString, SubDiagnostic};
272 pub use diagnostic_builder::DiagnosticBuilder;
274 /// A handler deals with errors and other compiler output.
275 /// Certain errors (fatal, bug, unimpl) may cause immediate exit,
276 /// others log errors for later reporting.
279 inner: Lock<HandlerInner>,
282 /// This inner struct exists to keep it all behind a single lock;
283 /// this is done to prevent possible deadlocks in a multi-threaded compiler,
284 /// as well as inconsistent state observation.
285 struct HandlerInner {
287 /// The number of errors that have been emitted, including duplicates.
289 /// This is not necessarily the count that's reported to the user once
290 /// compilation ends.
292 deduplicated_err_count: usize,
293 emitter: Box<dyn Emitter + sync::Send>,
294 delayed_span_bugs: Vec<Diagnostic>,
296 /// This set contains the `DiagnosticId` of all emitted diagnostics to avoid
297 /// emitting the same diagnostic with extended help (`--teach`) twice, which
298 /// would be uneccessary repetition.
299 taught_diagnostics: FxHashSet<DiagnosticId>,
301 /// Used to suggest rustc --explain <error code>
302 emitted_diagnostic_codes: FxHashSet<DiagnosticId>,
304 /// This set contains a hash of every diagnostic that has been emitted by
305 /// this handler. These hashes is used to avoid emitting the same error
307 emitted_diagnostics: FxHashSet<u128>,
309 /// Stashed diagnostics emitted in one stage of the compiler that may be
310 /// stolen by other stages (e.g. to improve them and add more information).
311 /// The stashed diagnostics count towards the total error count.
312 /// When `.abort_if_errors()` is called, these are also emitted.
313 stashed_diagnostics: FxIndexMap<(Span, StashKey), Diagnostic>,
316 /// A key denoting where from a diagnostic was stashed.
317 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
322 fn default_track_diagnostic(_: &Diagnostic) {}
324 pub static TRACK_DIAGNOSTICS: AtomicRef<fn(&Diagnostic)> =
325 AtomicRef::new(&(default_track_diagnostic as fn(&_)));
327 #[derive(Copy, Clone, Default)]
328 pub struct HandlerFlags {
329 /// If false, warning-level lints are suppressed.
330 /// (rustc: see `--allow warnings` and `--cap-lints`)
331 pub can_emit_warnings: bool,
332 /// If true, error-level diagnostics are upgraded to bug-level.
333 /// (rustc: see `-Z treat-err-as-bug`)
334 pub treat_err_as_bug: Option<usize>,
335 /// If true, immediately emit diagnostics that would otherwise be buffered.
336 /// (rustc: see `-Z dont-buffer-diagnostics` and `-Z treat-err-as-bug`)
337 pub dont_buffer_diagnostics: bool,
338 /// If true, immediately print bugs registered with `delay_span_bug`.
339 /// (rustc: see `-Z report-delayed-bugs`)
340 pub report_delayed_bugs: bool,
341 /// show macro backtraces even for non-local macros.
342 /// (rustc: see `-Z external-macro-backtrace`)
343 pub external_macro_backtrace: bool,
344 /// If true, identical diagnostics are reported only once.
345 pub deduplicate_diagnostics: bool,
348 impl Drop for HandlerInner {
350 self.emit_stashed_diagnostics();
352 if !self.has_errors() {
353 let bugs = std::mem::replace(&mut self.delayed_span_bugs, Vec::new());
354 let has_bugs = !bugs.is_empty();
356 self.emit_diagnostic(&bug);
359 panic!("no errors encountered even though `delay_span_bug` issued");
366 pub fn with_tty_emitter(
367 color_config: ColorConfig,
368 can_emit_warnings: bool,
369 treat_err_as_bug: Option<usize>,
370 cm: Option<Lrc<SourceMap>>,
372 Self::with_tty_emitter_and_flags(
375 HandlerFlags { can_emit_warnings, treat_err_as_bug, ..Default::default() },
379 pub fn with_tty_emitter_and_flags(
380 color_config: ColorConfig,
381 cm: Option<Lrc<SourceMap>>,
384 let emitter = Box::new(EmitterWriter::stderr(
390 flags.external_macro_backtrace,
392 Self::with_emitter_and_flags(emitter, flags)
396 can_emit_warnings: bool,
397 treat_err_as_bug: Option<usize>,
398 emitter: Box<dyn Emitter + sync::Send>,
400 Handler::with_emitter_and_flags(
402 HandlerFlags { can_emit_warnings, treat_err_as_bug, ..Default::default() },
406 pub fn with_emitter_and_flags(
407 emitter: Box<dyn Emitter + sync::Send>,
412 inner: Lock::new(HandlerInner {
415 deduplicated_err_count: 0,
417 delayed_span_bugs: Vec::new(),
418 taught_diagnostics: Default::default(),
419 emitted_diagnostic_codes: Default::default(),
420 emitted_diagnostics: Default::default(),
421 stashed_diagnostics: Default::default(),
426 // This is here to not allow mutation of flags;
427 // as of this writing it's only used in tests in librustc.
428 pub fn can_emit_warnings(&self) -> bool {
429 self.flags.can_emit_warnings
432 /// Resets the diagnostic error count as well as the cached emitted diagnostics.
434 /// NOTE: *do not* call this function from rustc. It is only meant to be called from external
435 /// tools that want to reuse a `Parser` cleaning the previously emitted diagnostics as well as
436 /// the overall count of emitted error diagnostics.
437 pub fn reset_err_count(&self) {
438 let mut inner = self.inner.borrow_mut();
440 inner.deduplicated_err_count = 0;
442 // actually free the underlying memory (which `clear` would not do)
443 inner.delayed_span_bugs = Default::default();
444 inner.taught_diagnostics = Default::default();
445 inner.emitted_diagnostic_codes = Default::default();
446 inner.emitted_diagnostics = Default::default();
447 inner.stashed_diagnostics = Default::default();
450 /// Stash a given diagnostic with the given `Span` and `StashKey` as the key for later stealing.
451 /// If the diagnostic with this `(span, key)` already exists, this will result in an ICE.
452 pub fn stash_diagnostic(&self, span: Span, key: StashKey, diag: Diagnostic) {
453 let mut inner = self.inner.borrow_mut();
454 if let Some(mut old_diag) = inner.stashed_diagnostics.insert((span, key), diag) {
455 // We are removing a previously stashed diagnostic which should not happen.
456 old_diag.level = Bug;
457 old_diag.note(&format!(
458 "{}:{}: already existing stashed diagnostic with (span = {:?}, key = {:?})",
464 inner.emit_diag_at_span(old_diag, span);
469 /// Steal a previously stashed diagnostic with the given `Span` and `StashKey` as the key.
470 pub fn steal_diagnostic(&self, span: Span, key: StashKey) -> Option<DiagnosticBuilder<'_>> {
474 .remove(&(span, key))
475 .map(|diag| DiagnosticBuilder::new_diagnostic(self, diag))
478 /// Emit all stashed diagnostics.
479 pub fn emit_stashed_diagnostics(&self) {
480 self.inner.borrow_mut().emit_stashed_diagnostics();
483 /// Construct a dummy builder with `Level::Cancelled`.
485 /// Using this will neither report anything to the user (e.g. a warning),
486 /// nor will compilation cancel as a result.
487 pub fn struct_dummy(&self) -> DiagnosticBuilder<'_> {
488 DiagnosticBuilder::new(self, Level::Cancelled, "")
491 /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
492 pub fn struct_span_warn(&self, span: impl Into<MultiSpan>, msg: &str) -> DiagnosticBuilder<'_> {
493 let mut result = self.struct_warn(msg);
494 result.set_span(span);
498 /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
499 /// Also include a code.
500 pub fn struct_span_warn_with_code(
502 span: impl Into<MultiSpan>,
505 ) -> DiagnosticBuilder<'_> {
506 let mut result = self.struct_span_warn(span, msg);
511 /// Construct a builder at the `Warning` level with the `msg`.
512 pub fn struct_warn(&self, msg: &str) -> DiagnosticBuilder<'_> {
513 let mut result = DiagnosticBuilder::new(self, Level::Warning, msg);
514 if !self.flags.can_emit_warnings {
520 /// Construct a builder at the `Error` level at the given `span` and with the `msg`.
521 pub fn struct_span_err(&self, span: impl Into<MultiSpan>, msg: &str) -> DiagnosticBuilder<'_> {
522 let mut result = self.struct_err(msg);
523 result.set_span(span);
527 /// Construct a builder at the `Error` level at the given `span`, with the `msg`, and `code`.
528 pub fn struct_span_err_with_code(
530 span: impl Into<MultiSpan>,
533 ) -> DiagnosticBuilder<'_> {
534 let mut result = self.struct_span_err(span, msg);
539 /// Construct a builder at the `Error` level with the `msg`.
540 // FIXME: This method should be removed (every error should have an associated error code).
541 pub fn struct_err(&self, msg: &str) -> DiagnosticBuilder<'_> {
542 DiagnosticBuilder::new(self, Level::Error, msg)
545 /// Construct a builder at the `Error` level with the `msg` and the `code`.
546 pub fn struct_err_with_code(&self, msg: &str, code: DiagnosticId) -> DiagnosticBuilder<'_> {
547 let mut result = self.struct_err(msg);
552 /// Construct a builder at the `Fatal` level at the given `span` and with the `msg`.
553 pub fn struct_span_fatal(
555 span: impl Into<MultiSpan>,
557 ) -> DiagnosticBuilder<'_> {
558 let mut result = self.struct_fatal(msg);
559 result.set_span(span);
563 /// Construct a builder at the `Fatal` level at the given `span`, with the `msg`, and `code`.
564 pub fn struct_span_fatal_with_code(
566 span: impl Into<MultiSpan>,
569 ) -> DiagnosticBuilder<'_> {
570 let mut result = self.struct_span_fatal(span, msg);
575 /// Construct a builder at the `Error` level with the `msg`.
576 pub fn struct_fatal(&self, msg: &str) -> DiagnosticBuilder<'_> {
577 DiagnosticBuilder::new(self, Level::Fatal, msg)
580 /// Construct a builder at the `Help` level with the `msg`.
581 pub fn struct_help(&self, msg: &str) -> DiagnosticBuilder<'_> {
582 DiagnosticBuilder::new(self, Level::Help, msg)
585 pub fn span_fatal(&self, span: impl Into<MultiSpan>, msg: &str) -> FatalError {
586 self.emit_diag_at_span(Diagnostic::new(Fatal, msg), span);
590 pub fn span_fatal_with_code(
592 span: impl Into<MultiSpan>,
596 self.emit_diag_at_span(Diagnostic::new_with_code(Fatal, Some(code), msg), span);
600 pub fn span_err(&self, span: impl Into<MultiSpan>, msg: &str) {
601 self.emit_diag_at_span(Diagnostic::new(Error, msg), span);
604 pub fn span_err_with_code(&self, span: impl Into<MultiSpan>, msg: &str, code: DiagnosticId) {
605 self.emit_diag_at_span(Diagnostic::new_with_code(Error, Some(code), msg), span);
608 pub fn span_warn(&self, span: impl Into<MultiSpan>, msg: &str) {
609 self.emit_diag_at_span(Diagnostic::new(Warning, msg), span);
612 pub fn span_warn_with_code(&self, span: impl Into<MultiSpan>, msg: &str, code: DiagnosticId) {
613 self.emit_diag_at_span(Diagnostic::new_with_code(Warning, Some(code), msg), span);
616 pub fn span_bug(&self, span: impl Into<MultiSpan>, msg: &str) -> ! {
617 self.inner.borrow_mut().span_bug(span, msg)
620 pub fn delay_span_bug(&self, span: impl Into<MultiSpan>, msg: &str) {
621 self.inner.borrow_mut().delay_span_bug(span, msg)
624 pub fn span_bug_no_panic(&self, span: impl Into<MultiSpan>, msg: &str) {
625 self.emit_diag_at_span(Diagnostic::new(Bug, msg), span);
628 pub fn span_note_without_error(&self, span: impl Into<MultiSpan>, msg: &str) {
629 self.emit_diag_at_span(Diagnostic::new(Note, msg), span);
632 pub fn span_note_diag(&self, span: Span, msg: &str) -> DiagnosticBuilder<'_> {
633 let mut db = DiagnosticBuilder::new(self, Note, msg);
638 pub fn failure(&self, msg: &str) {
639 self.inner.borrow_mut().failure(msg);
642 pub fn fatal(&self, msg: &str) -> FatalError {
643 self.inner.borrow_mut().fatal(msg)
646 pub fn err(&self, msg: &str) {
647 self.inner.borrow_mut().err(msg);
650 pub fn warn(&self, msg: &str) {
651 let mut db = DiagnosticBuilder::new(self, Warning, msg);
655 pub fn note_without_error(&self, msg: &str) {
656 DiagnosticBuilder::new(self, Note, msg).emit();
659 pub fn bug(&self, msg: &str) -> ! {
660 self.inner.borrow_mut().bug(msg)
663 pub fn err_count(&self) -> usize {
664 self.inner.borrow().err_count()
667 pub fn has_errors(&self) -> bool {
668 self.inner.borrow().has_errors()
670 pub fn has_errors_or_delayed_span_bugs(&self) -> bool {
671 self.inner.borrow().has_errors_or_delayed_span_bugs()
674 pub fn print_error_count(&self, registry: &Registry) {
675 self.inner.borrow_mut().print_error_count(registry)
678 pub fn abort_if_errors(&self) {
679 self.inner.borrow_mut().abort_if_errors()
682 /// `true` if we haven't taught a diagnostic with this code already.
683 /// The caller must then teach the user about such a diagnostic.
685 /// Used to suppress emitting the same error multiple times with extended explanation when
686 /// calling `-Zteach`.
687 pub fn must_teach(&self, code: &DiagnosticId) -> bool {
688 self.inner.borrow_mut().must_teach(code)
691 pub fn force_print_diagnostic(&self, db: Diagnostic) {
692 self.inner.borrow_mut().force_print_diagnostic(db)
695 pub fn emit_diagnostic(&self, diagnostic: &Diagnostic) {
696 self.inner.borrow_mut().emit_diagnostic(diagnostic)
699 fn emit_diag_at_span(&self, mut diag: Diagnostic, sp: impl Into<MultiSpan>) {
700 let mut inner = self.inner.borrow_mut();
701 inner.emit_diagnostic(diag.set_span(sp));
704 pub fn emit_artifact_notification(&self, path: &Path, artifact_type: &str) {
705 self.inner.borrow_mut().emit_artifact_notification(path, artifact_type)
708 pub fn delay_as_bug(&self, diagnostic: Diagnostic) {
709 self.inner.borrow_mut().delay_as_bug(diagnostic)
714 fn must_teach(&mut self, code: &DiagnosticId) -> bool {
715 self.taught_diagnostics.insert(code.clone())
718 fn force_print_diagnostic(&mut self, db: Diagnostic) {
719 self.emitter.emit_diagnostic(&db);
722 /// Emit all stashed diagnostics.
723 fn emit_stashed_diagnostics(&mut self) {
724 let diags = self.stashed_diagnostics.drain(..).map(|x| x.1).collect::<Vec<_>>();
725 diags.iter().for_each(|diag| self.emit_diagnostic(diag));
728 fn emit_diagnostic(&mut self, diagnostic: &Diagnostic) {
729 if diagnostic.cancelled() {
733 if diagnostic.level == Warning && !self.flags.can_emit_warnings {
737 (*TRACK_DIAGNOSTICS)(diagnostic);
739 if let Some(ref code) = diagnostic.code {
740 self.emitted_diagnostic_codes.insert(code.clone());
743 let already_emitted = |this: &mut Self| {
745 let mut hasher = StableHasher::new();
746 diagnostic.hash(&mut hasher);
747 let diagnostic_hash = hasher.finish();
748 !this.emitted_diagnostics.insert(diagnostic_hash)
751 // Only emit the diagnostic if we've been asked to deduplicate and
752 // haven't already emitted an equivalent diagnostic.
753 if !(self.flags.deduplicate_diagnostics && already_emitted(self)) {
754 self.emitter.emit_diagnostic(diagnostic);
755 if diagnostic.is_error() {
756 self.deduplicated_err_count += 1;
759 if diagnostic.is_error() {
760 self.bump_err_count();
764 fn emit_artifact_notification(&mut self, path: &Path, artifact_type: &str) {
765 self.emitter.emit_artifact_notification(path, artifact_type);
768 fn treat_err_as_bug(&self) -> bool {
769 self.flags.treat_err_as_bug.map(|c| self.err_count() >= c).unwrap_or(false)
772 fn print_error_count(&mut self, registry: &Registry) {
773 self.emit_stashed_diagnostics();
775 let s = match self.deduplicated_err_count {
777 1 => "aborting due to previous error".to_string(),
778 count => format!("aborting due to {} previous errors", count),
780 if self.treat_err_as_bug() {
784 let _ = self.fatal(&s);
786 let can_show_explain = self.emitter.should_show_explain();
787 let are_there_diagnostics = !self.emitted_diagnostic_codes.is_empty();
788 if can_show_explain && are_there_diagnostics {
789 let mut error_codes = self
790 .emitted_diagnostic_codes
792 .filter_map(|x| match &x {
793 DiagnosticId::Error(s) if registry.find_description(s).is_some() => {
798 .collect::<Vec<_>>();
799 if !error_codes.is_empty() {
801 if error_codes.len() > 1 {
802 let limit = if error_codes.len() > 9 { 9 } else { error_codes.len() };
803 self.failure(&format!(
804 "Some errors have detailed explanations: {}{}",
805 error_codes[..limit].join(", "),
806 if error_codes.len() > 9 { "..." } else { "." }
808 self.failure(&format!(
809 "For more information about an error, try \
810 `rustc --explain {}`.",
814 self.failure(&format!(
815 "For more information about this error, try \
816 `rustc --explain {}`.",
824 fn err_count(&self) -> usize {
825 self.err_count + self.stashed_diagnostics.len()
828 fn has_errors(&self) -> bool {
831 fn has_errors_or_delayed_span_bugs(&self) -> bool {
832 self.has_errors() || !self.delayed_span_bugs.is_empty()
835 fn abort_if_errors(&mut self) {
836 self.emit_stashed_diagnostics();
838 if self.has_errors() {
843 fn span_bug(&mut self, sp: impl Into<MultiSpan>, msg: &str) -> ! {
844 self.emit_diag_at_span(Diagnostic::new(Bug, msg), sp);
848 fn emit_diag_at_span(&mut self, mut diag: Diagnostic, sp: impl Into<MultiSpan>) {
849 self.emit_diagnostic(diag.set_span(sp));
852 fn delay_span_bug(&mut self, sp: impl Into<MultiSpan>, msg: &str) {
853 if self.treat_err_as_bug() {
854 // FIXME: don't abort here if report_delayed_bugs is off
855 self.span_bug(sp, msg);
857 let mut diagnostic = Diagnostic::new(Level::Bug, msg);
858 diagnostic.set_span(sp.into());
859 self.delay_as_bug(diagnostic)
862 fn failure(&mut self, msg: &str) {
863 self.emit_diagnostic(&Diagnostic::new(FailureNote, msg));
866 fn fatal(&mut self, msg: &str) -> FatalError {
867 self.emit_error(Fatal, msg);
871 fn err(&mut self, msg: &str) {
872 self.emit_error(Error, msg);
875 /// Emit an error; level should be `Error` or `Fatal`.
876 fn emit_error(&mut self, level: Level, msg: &str) {
877 if self.treat_err_as_bug() {
880 self.emit_diagnostic(&Diagnostic::new(level, msg));
883 fn bug(&mut self, msg: &str) -> ! {
884 self.emit_diagnostic(&Diagnostic::new(Bug, msg));
888 fn delay_as_bug(&mut self, diagnostic: Diagnostic) {
889 if self.flags.report_delayed_bugs {
890 self.emit_diagnostic(&diagnostic);
892 self.delayed_span_bugs.push(diagnostic);
895 fn bump_err_count(&mut self) {
897 self.panic_if_treat_err_as_bug();
900 fn panic_if_treat_err_as_bug(&self) {
901 if self.treat_err_as_bug() {
902 let s = match (self.err_count(), self.flags.treat_err_as_bug.unwrap_or(0)) {
904 (1, 1) => "aborting due to `-Z treat-err-as-bug=1`".to_string(),
906 (count, as_bug) => format!(
907 "aborting after {} errors due to `-Z treat-err-as-bug={}`",
916 #[derive(Copy, PartialEq, Clone, Hash, Debug, RustcEncodable, RustcDecodable)]
928 impl fmt::Display for Level {
929 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
935 fn color(self) -> ColorSpec {
936 let mut spec = ColorSpec::new();
938 Bug | Fatal | Error => {
939 spec.set_fg(Some(Color::Red)).set_intense(true);
942 spec.set_fg(Some(Color::Yellow)).set_intense(cfg!(windows));
945 spec.set_fg(Some(Color::Green)).set_intense(true);
948 spec.set_fg(Some(Color::Cyan)).set_intense(true);
951 Cancelled => unreachable!(),
956 pub fn to_str(self) -> &'static str {
958 Bug => "error: internal compiler error",
959 Fatal | Error => "error",
960 Warning => "warning",
963 FailureNote => "failure-note",
964 Cancelled => panic!("Shouldn't call on cancelled error"),
968 pub fn is_failure_note(&self) -> bool {
977 macro_rules! pluralize {
979 if $x != 1 { "s" } else { "" }
983 // Useful type to use with `Result<>` indicate that an error has already
984 // been reported to the user, so no need to continue checking.
985 #[derive(Clone, Copy, Debug, RustcEncodable, RustcDecodable, Hash, PartialEq, Eq)]
986 pub struct ErrorReported;
988 rustc_data_structures::impl_stable_hash_via_hash!(ErrorReported);