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, is_case_difference};
17 use registry::Registry;
18 use rustc_data_structures::sync::{self, Lrc, Lock};
19 use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
20 use rustc_data_structures::stable_hasher::StableHasher;
21 use syntax_pos::source_map::SourceMap;
22 use syntax_pos::{Loc, Span, MultiSpan};
26 use std::{error, fmt};
30 use termcolor::{ColorSpec, Color};
33 mod diagnostic_builder;
35 pub mod annotate_snippet_emitter_writer;
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 /// Returns the assembled code suggestions, whether they should be shown with an underline
148 /// and whether the substitution only differs in capitalization.
152 ) -> Vec<(String, Vec<SubstitutionPart>, bool)> {
153 use syntax_pos::{CharPos, Pos};
155 fn push_trailing(buf: &mut String,
156 line_opt: Option<&Cow<'_, str>>,
158 hi_opt: Option<&Loc>) {
159 let (lo, hi_opt) = (lo.col.to_usize(), hi_opt.map(|hi| hi.col.to_usize()));
160 if let Some(line) = line_opt {
161 if let Some(lo) = line.char_indices().map(|(i, _)| i).nth(lo) {
162 let hi_opt = hi_opt.and_then(|hi| line.char_indices().map(|(i, _)| i).nth(hi));
164 Some(hi) if hi > lo => buf.push_str(&line[lo..hi]),
166 None => buf.push_str(&line[lo..]),
169 if let None = hi_opt {
175 assert!(!self.substitutions.is_empty());
177 self.substitutions.iter().cloned().map(|mut substitution| {
178 // Assumption: all spans are in the same file, and all spans
179 // are disjoint. Sort in ascending order.
180 substitution.parts.sort_by_key(|part| part.span.lo());
182 // Find the bounding span.
183 let lo = substitution.parts.iter().map(|part| part.span.lo()).min().unwrap();
184 let hi = substitution.parts.iter().map(|part| part.span.hi()).min().unwrap();
185 let bounding_span = Span::with_root_ctxt(lo, hi);
186 let lines = cm.span_to_lines(bounding_span).unwrap();
187 assert!(!lines.lines.is_empty());
189 // To build up the result, we do this for each span:
190 // - push the line segment trailing the previous span
191 // (at the beginning a "phantom" span pointing at the start of the line)
192 // - push lines between the previous and current span (if any)
193 // - if the previous and current span are not on the same line
194 // push the line segment leading up to the current span
195 // - splice in the span substitution
197 // Finally push the trailing line segment of the last span
198 let fm = &lines.file;
199 let mut prev_hi = cm.lookup_char_pos(bounding_span.lo());
200 prev_hi.col = CharPos::from_usize(0);
202 let mut prev_line = fm.get_line(lines.lines[0].line_index);
203 let mut buf = String::new();
205 for part in &substitution.parts {
206 let cur_lo = cm.lookup_char_pos(part.span.lo());
207 if prev_hi.line == cur_lo.line {
208 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, Some(&cur_lo));
210 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
211 // push lines between the previous and current span (if any)
212 for idx in prev_hi.line..(cur_lo.line - 1) {
213 if let Some(line) = fm.get_line(idx) {
214 buf.push_str(line.as_ref());
218 if let Some(cur_line) = fm.get_line(cur_lo.line - 1) {
219 let end = std::cmp::min(cur_line.len(), cur_lo.col.to_usize());
220 buf.push_str(&cur_line[..end]);
223 buf.push_str(&part.snippet);
224 prev_hi = cm.lookup_char_pos(part.span.hi());
225 prev_line = fm.get_line(prev_hi.line - 1);
227 let only_capitalization = is_case_difference(cm, &buf, bounding_span);
228 // if the replacement already ends with a newline, don't print the next line
229 if !buf.ends_with('\n') {
230 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
232 // remove trailing newlines
233 while buf.ends_with('\n') {
236 (buf, substitution.parts, only_capitalization)
241 pub use syntax_pos::fatal_error::{FatalError, FatalErrorMarker};
243 /// Signifies that the compiler died with an explicit call to `.bug`
244 /// or `.span_bug` rather than a failed assertion, etc.
245 #[derive(Copy, Clone, Debug)]
246 pub struct ExplicitBug;
248 impl fmt::Display for ExplicitBug {
249 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
250 write!(f, "parser internal bug")
254 impl error::Error for ExplicitBug {
255 fn description(&self) -> &str {
256 "The parser has encountered an internal bug"
260 pub use diagnostic::{Diagnostic, SubDiagnostic, DiagnosticStyledString, DiagnosticId};
261 pub use diagnostic_builder::DiagnosticBuilder;
263 /// A handler deals with errors and other compiler output.
264 /// Certain errors (fatal, bug, unimpl) may cause immediate exit,
265 /// others log errors for later reporting.
268 inner: Lock<HandlerInner>,
271 /// This inner struct exists to keep it all behind a single lock;
272 /// this is done to prevent possible deadlocks in a multi-threaded compiler,
273 /// as well as inconsistent state observation.
274 struct HandlerInner {
276 /// The number of errors that have been emitted, including duplicates.
278 /// This is not necessarily the count that's reported to the user once
279 /// compilation ends.
281 deduplicated_err_count: usize,
282 emitter: Box<dyn Emitter + sync::Send>,
283 continue_after_error: bool,
284 delayed_span_bugs: Vec<Diagnostic>,
286 /// This set contains the `DiagnosticId` of all emitted diagnostics to avoid
287 /// emitting the same diagnostic with extended help (`--teach`) twice, which
288 /// would be uneccessary repetition.
289 taught_diagnostics: FxHashSet<DiagnosticId>,
291 /// Used to suggest rustc --explain <error code>
292 emitted_diagnostic_codes: FxHashSet<DiagnosticId>,
294 /// This set contains a hash of every diagnostic that has been emitted by
295 /// this handler. These hashes is used to avoid emitting the same error
297 emitted_diagnostics: FxHashSet<u128>,
299 /// Stashed diagnostics emitted in one stage of the compiler that may be
300 /// stolen by other stages (e.g. to improve them and add more information).
301 /// The stashed diagnostics count towards the total error count.
302 /// When `.abort_if_errors()` is called, these are also emitted.
303 stashed_diagnostics: FxIndexMap<(Span, StashKey), Diagnostic>,
306 /// A key denoting where from a diagnostic was stashed.
307 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
312 fn default_track_diagnostic(_: &Diagnostic) {}
314 thread_local!(pub static TRACK_DIAGNOSTICS: Cell<fn(&Diagnostic)> =
315 Cell::new(default_track_diagnostic));
317 #[derive(Copy, Clone, Default)]
318 pub struct HandlerFlags {
319 /// If false, warning-level lints are suppressed.
320 /// (rustc: see `--allow warnings` and `--cap-lints`)
321 pub can_emit_warnings: bool,
322 /// If true, error-level diagnostics are upgraded to bug-level.
323 /// (rustc: see `-Z treat-err-as-bug`)
324 pub treat_err_as_bug: Option<usize>,
325 /// If true, immediately emit diagnostics that would otherwise be buffered.
326 /// (rustc: see `-Z dont-buffer-diagnostics` and `-Z treat-err-as-bug`)
327 pub dont_buffer_diagnostics: bool,
328 /// If true, immediately print bugs registered with `delay_span_bug`.
329 /// (rustc: see `-Z report-delayed-bugs`)
330 pub report_delayed_bugs: bool,
331 /// show macro backtraces even for non-local macros.
332 /// (rustc: see `-Z external-macro-backtrace`)
333 pub external_macro_backtrace: bool,
336 impl Drop for HandlerInner {
338 self.emit_stashed_diagnostics();
340 if !self.has_errors() {
341 let bugs = std::mem::replace(&mut self.delayed_span_bugs, Vec::new());
342 let has_bugs = !bugs.is_empty();
344 self.emit_diagnostic(&bug);
347 panic!("no errors encountered even though `delay_span_bug` issued");
354 pub fn with_tty_emitter(
355 color_config: ColorConfig,
356 can_emit_warnings: bool,
357 treat_err_as_bug: Option<usize>,
358 cm: Option<Lrc<SourceMap>>,
360 Self::with_tty_emitter_and_flags(
366 .. Default::default()
371 pub fn with_tty_emitter_and_flags(
372 color_config: ColorConfig,
373 cm: Option<Lrc<SourceMap>>,
376 let emitter = Box::new(EmitterWriter::stderr(
382 flags.external_macro_backtrace,
384 Self::with_emitter_and_flags(emitter, flags)
388 can_emit_warnings: bool,
389 treat_err_as_bug: Option<usize>,
390 emitter: Box<dyn Emitter + sync::Send>,
392 Handler::with_emitter_and_flags(
397 .. Default::default()
402 pub fn with_emitter_and_flags(
403 emitter: Box<dyn Emitter + sync::Send>,
408 inner: Lock::new(HandlerInner {
411 deduplicated_err_count: 0,
413 continue_after_error: true,
414 delayed_span_bugs: Vec::new(),
415 taught_diagnostics: Default::default(),
416 emitted_diagnostic_codes: Default::default(),
417 emitted_diagnostics: Default::default(),
418 stashed_diagnostics: Default::default(),
423 pub fn set_continue_after_error(&self, continue_after_error: bool) {
424 self.inner.borrow_mut().continue_after_error = continue_after_error;
427 // This is here to not allow mutation of flags;
428 // as of this writing it's only used in tests in librustc.
429 pub fn can_emit_warnings(&self) -> bool {
430 self.flags.can_emit_warnings
433 /// Resets the diagnostic error count as well as the cached emitted diagnostics.
435 /// NOTE: *do not* call this function from rustc. It is only meant to be called from external
436 /// tools that want to reuse a `Parser` cleaning the previously emitted diagnostics as well as
437 /// the overall count of emitted error diagnostics.
438 pub fn reset_err_count(&self) {
439 let mut inner = self.inner.borrow_mut();
441 inner.deduplicated_err_count = 0;
443 // actually free the underlying memory (which `clear` would not do)
444 inner.delayed_span_bugs = Default::default();
445 inner.taught_diagnostics = Default::default();
446 inner.emitted_diagnostic_codes = Default::default();
447 inner.emitted_diagnostics = Default::default();
448 inner.stashed_diagnostics = Default::default();
451 /// Stash a given diagnostic with the given `Span` and `StashKey` as the key for later stealing.
452 /// If the diagnostic with this `(span, key)` already exists, this will result in an ICE.
453 pub fn stash_diagnostic(&self, span: Span, key: StashKey, diag: Diagnostic) {
454 let mut inner = self.inner.borrow_mut();
455 if let Some(mut old_diag) = inner.stashed_diagnostics.insert((span, key), diag) {
456 // We are removing a previously stashed diagnostic which should not happen.
457 old_diag.level = Bug;
458 old_diag.note(&format!(
459 "{}:{}: already existing stashed diagnostic with (span = {:?}, key = {:?})",
460 file!(), line!(), span, key
462 inner.emit_diag_at_span(old_diag, span);
467 /// Steal a previously stashed diagnostic with the given `Span` and `StashKey` as the key.
468 pub fn steal_diagnostic(&self, span: Span, key: StashKey) -> Option<DiagnosticBuilder<'_>> {
472 .remove(&(span, key))
473 .map(|diag| DiagnosticBuilder::new_diagnostic(self, diag))
476 /// Emit all stashed diagnostics.
477 pub fn emit_stashed_diagnostics(&self) {
478 self.inner.borrow_mut().emit_stashed_diagnostics();
481 /// Construct a dummy builder with `Level::Cancelled`.
483 /// Using this will neither report anything to the user (e.g. a warning),
484 /// nor will compilation cancel as a result.
485 pub fn struct_dummy(&self) -> DiagnosticBuilder<'_> {
486 DiagnosticBuilder::new(self, Level::Cancelled, "")
489 /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
490 pub fn struct_span_warn(&self, span: impl Into<MultiSpan>, msg: &str) -> DiagnosticBuilder<'_> {
491 let mut result = self.struct_warn(msg);
492 result.set_span(span);
496 /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
497 /// Also include a code.
498 pub fn struct_span_warn_with_code(
500 span: impl Into<MultiSpan>,
503 ) -> DiagnosticBuilder<'_> {
504 let mut result = self.struct_span_warn(span, msg);
509 /// Construct a builder at the `Warning` level with the `msg`.
510 pub fn struct_warn(&self, msg: &str) -> DiagnosticBuilder<'_> {
511 let mut result = DiagnosticBuilder::new(self, Level::Warning, msg);
512 if !self.flags.can_emit_warnings {
518 /// Construct a builder at the `Error` level at the given `span` and with the `msg`.
519 pub fn struct_span_err(&self, span: impl Into<MultiSpan>, msg: &str) -> DiagnosticBuilder<'_> {
520 let mut result = self.struct_err(msg);
521 result.set_span(span);
525 /// Construct a builder at the `Error` level at the given `span`, with the `msg`, and `code`.
526 pub fn struct_span_err_with_code(
528 span: impl Into<MultiSpan>,
531 ) -> DiagnosticBuilder<'_> {
532 let mut result = self.struct_span_err(span, msg);
537 /// Construct a builder at the `Error` level with the `msg`.
538 // FIXME: This method should be removed (every error should have an associated error code).
539 pub fn struct_err(&self, msg: &str) -> DiagnosticBuilder<'_> {
540 DiagnosticBuilder::new(self, Level::Error, msg)
543 /// Construct a builder at the `Error` level with the `msg` and the `code`.
544 pub fn struct_err_with_code(&self, msg: &str, code: DiagnosticId) -> DiagnosticBuilder<'_> {
545 let mut result = self.struct_err(msg);
550 /// Construct a builder at the `Fatal` level at the given `span` and with the `msg`.
551 pub fn struct_span_fatal(
553 span: impl Into<MultiSpan>,
555 ) -> DiagnosticBuilder<'_> {
556 let mut result = self.struct_fatal(msg);
557 result.set_span(span);
561 /// Construct a builder at the `Fatal` level at the given `span`, with the `msg`, and `code`.
562 pub fn struct_span_fatal_with_code(
564 span: impl Into<MultiSpan>,
567 ) -> DiagnosticBuilder<'_> {
568 let mut result = self.struct_span_fatal(span, msg);
573 /// Construct a builder at the `Error` level with the `msg`.
574 pub fn struct_fatal(&self, msg: &str) -> DiagnosticBuilder<'_> {
575 DiagnosticBuilder::new(self, Level::Fatal, msg)
578 /// Construct a builder at the `Help` level with the `msg`.
579 pub fn struct_help(&self, msg: &str) -> DiagnosticBuilder<'_> {
580 DiagnosticBuilder::new(self, Level::Help, msg)
583 pub fn span_fatal(&self, span: impl Into<MultiSpan>, msg: &str) -> FatalError {
584 self.emit_diag_at_span(Diagnostic::new(Fatal, msg), span);
588 pub fn span_fatal_with_code(
590 span: impl Into<MultiSpan>,
594 self.emit_diag_at_span(Diagnostic::new_with_code(Fatal, Some(code), msg), span);
598 pub fn span_err(&self, span: impl Into<MultiSpan>, msg: &str) {
599 self.emit_diag_at_span(Diagnostic::new(Error, msg), span);
602 pub fn span_err_with_code(&self, span: impl Into<MultiSpan>, msg: &str, code: DiagnosticId) {
603 self.emit_diag_at_span(Diagnostic::new_with_code(Error, Some(code), msg), span);
606 pub fn span_warn(&self, span: impl Into<MultiSpan>, msg: &str) {
607 self.emit_diag_at_span(Diagnostic::new(Warning, msg), span);
610 pub fn span_warn_with_code(&self, span: impl Into<MultiSpan>, msg: &str, code: DiagnosticId) {
611 self.emit_diag_at_span(Diagnostic::new_with_code(Warning, Some(code), msg), span);
614 pub fn span_bug(&self, span: impl Into<MultiSpan>, msg: &str) -> ! {
615 self.inner.borrow_mut().span_bug(span, msg)
618 pub fn delay_span_bug(&self, span: impl Into<MultiSpan>, msg: &str) {
619 self.inner.borrow_mut().delay_span_bug(span, msg)
622 pub fn span_bug_no_panic(&self, span: impl Into<MultiSpan>, msg: &str) {
623 self.emit_diag_at_span(Diagnostic::new(Bug, msg), span);
626 pub fn span_note_without_error(&self, span: impl Into<MultiSpan>, msg: &str) {
627 self.emit_diag_at_span(Diagnostic::new(Note, msg), span);
630 pub fn span_note_diag(&self, span: Span, msg: &str) -> DiagnosticBuilder<'_> {
631 let mut db = DiagnosticBuilder::new(self, Note, msg);
636 pub fn failure(&self, msg: &str) {
637 self.inner.borrow_mut().failure(msg);
640 pub fn fatal(&self, msg: &str) -> FatalError {
641 self.inner.borrow_mut().fatal(msg)
644 pub fn err(&self, msg: &str) {
645 self.inner.borrow_mut().err(msg);
648 pub fn warn(&self, msg: &str) {
649 let mut db = DiagnosticBuilder::new(self, Warning, msg);
653 pub fn note_without_error(&self, msg: &str) {
654 DiagnosticBuilder::new(self, Note, msg).emit();
657 pub fn bug(&self, msg: &str) -> ! {
658 self.inner.borrow_mut().bug(msg)
661 pub fn err_count(&self) -> usize {
662 self.inner.borrow().err_count()
665 pub fn has_errors(&self) -> bool {
666 self.inner.borrow().has_errors()
668 pub fn has_errors_or_delayed_span_bugs(&self) -> bool {
669 self.inner.borrow().has_errors_or_delayed_span_bugs()
672 pub fn print_error_count(&self, registry: &Registry) {
673 self.inner.borrow_mut().print_error_count(registry)
676 pub fn abort_if_errors(&self) {
677 self.inner.borrow_mut().abort_if_errors()
680 pub fn abort_if_errors_and_should_abort(&self) {
681 self.inner.borrow_mut().abort_if_errors_and_should_abort()
684 /// `true` if we haven't taught a diagnostic with this code already.
685 /// The caller must then teach the user about such a diagnostic.
687 /// Used to suppress emitting the same error multiple times with extended explanation when
688 /// calling `-Zteach`.
689 pub fn must_teach(&self, code: &DiagnosticId) -> bool {
690 self.inner.borrow_mut().must_teach(code)
693 pub fn force_print_diagnostic(&self, db: Diagnostic) {
694 self.inner.borrow_mut().force_print_diagnostic(db)
697 pub fn emit_diagnostic(&self, diagnostic: &Diagnostic) {
698 self.inner.borrow_mut().emit_diagnostic(diagnostic)
701 fn emit_diag_at_span(&self, mut diag: Diagnostic, sp: impl Into<MultiSpan>) {
702 let mut inner = self.inner.borrow_mut();
703 inner.emit_diagnostic(diag.set_span(sp));
704 inner.abort_if_errors_and_should_abort();
707 pub fn emit_artifact_notification(&self, path: &Path, artifact_type: &str) {
708 self.inner.borrow_mut().emit_artifact_notification(path, artifact_type)
711 pub fn delay_as_bug(&self, diagnostic: Diagnostic) {
712 self.inner.borrow_mut().delay_as_bug(diagnostic)
717 fn must_teach(&mut self, code: &DiagnosticId) -> bool {
718 self.taught_diagnostics.insert(code.clone())
721 fn force_print_diagnostic(&mut self, db: Diagnostic) {
722 self.emitter.emit_diagnostic(&db);
725 /// Emit all stashed diagnostics.
726 fn emit_stashed_diagnostics(&mut self) {
727 let diags = self.stashed_diagnostics.drain(..).map(|x| x.1).collect::<Vec<_>>();
728 diags.iter().for_each(|diag| self.emit_diagnostic(diag));
731 fn emit_diagnostic(&mut self, diagnostic: &Diagnostic) {
732 if diagnostic.cancelled() {
736 if diagnostic.level == Warning && !self.flags.can_emit_warnings {
740 TRACK_DIAGNOSTICS.with(|track_diagnostics| {
741 track_diagnostics.get()(diagnostic);
744 if let Some(ref code) = diagnostic.code {
745 self.emitted_diagnostic_codes.insert(code.clone());
748 let diagnostic_hash = {
750 let mut hasher = StableHasher::new();
751 diagnostic.hash(&mut hasher);
755 // Only emit the diagnostic if we haven't already emitted an equivalent
757 if self.emitted_diagnostics.insert(diagnostic_hash) {
758 self.emitter.emit_diagnostic(diagnostic);
759 if diagnostic.is_error() {
760 self.deduplicated_err_count += 1;
763 if diagnostic.is_error() {
764 self.bump_err_count();
768 fn emit_artifact_notification(&mut self, path: &Path, artifact_type: &str) {
769 self.emitter.emit_artifact_notification(path, artifact_type);
772 fn treat_err_as_bug(&self) -> bool {
773 self.flags.treat_err_as_bug.map(|c| self.err_count() >= c).unwrap_or(false)
776 fn print_error_count(&mut self, registry: &Registry) {
777 self.emit_stashed_diagnostics();
779 let s = match self.deduplicated_err_count {
781 1 => "aborting due to previous error".to_string(),
782 count => format!("aborting due to {} previous errors", count)
784 if self.treat_err_as_bug() {
788 let _ = self.fatal(&s);
790 let can_show_explain = self.emitter.should_show_explain();
791 let are_there_diagnostics = !self.emitted_diagnostic_codes.is_empty();
792 if can_show_explain && are_there_diagnostics {
793 let mut error_codes = self
794 .emitted_diagnostic_codes
796 .filter_map(|x| match &x {
797 DiagnosticId::Error(s) if registry.find_description(s).is_some() => {
802 .collect::<Vec<_>>();
803 if !error_codes.is_empty() {
805 if error_codes.len() > 1 {
806 let limit = if error_codes.len() > 9 { 9 } else { error_codes.len() };
807 self.failure(&format!("Some errors have detailed explanations: {}{}",
808 error_codes[..limit].join(", "),
809 if error_codes.len() > 9 { "..." } else { "." }));
810 self.failure(&format!("For more information about an error, try \
811 `rustc --explain {}`.",
814 self.failure(&format!("For more information about this error, try \
815 `rustc --explain {}`.",
822 fn err_count(&self) -> usize {
823 self.err_count + self.stashed_diagnostics.len()
826 fn has_errors(&self) -> bool {
829 fn has_errors_or_delayed_span_bugs(&self) -> bool {
830 self.has_errors() || !self.delayed_span_bugs.is_empty()
833 fn abort_if_errors_and_should_abort(&mut self) {
834 self.emit_stashed_diagnostics();
836 if self.has_errors() && !self.continue_after_error {
841 fn abort_if_errors(&mut self) {
842 self.emit_stashed_diagnostics();
844 if self.has_errors() {
849 fn span_bug(&mut self, sp: impl Into<MultiSpan>, msg: &str) -> ! {
850 self.emit_diag_at_span(Diagnostic::new(Bug, msg), sp);
854 fn emit_diag_at_span(&mut self, mut diag: Diagnostic, sp: impl Into<MultiSpan>) {
855 self.emit_diagnostic(diag.set_span(sp));
856 self.abort_if_errors_and_should_abort();
859 fn delay_span_bug(&mut self, sp: impl Into<MultiSpan>, msg: &str) {
860 if self.treat_err_as_bug() {
861 // FIXME: don't abort here if report_delayed_bugs is off
862 self.span_bug(sp, msg);
864 let mut diagnostic = Diagnostic::new(Level::Bug, msg);
865 diagnostic.set_span(sp.into());
866 self.delay_as_bug(diagnostic)
869 fn failure(&mut self, msg: &str) {
870 self.emit_diagnostic(&Diagnostic::new(FailureNote, msg));
873 fn fatal(&mut self, msg: &str) -> FatalError {
874 self.emit_error(Fatal, msg);
878 fn err(&mut self, msg: &str) {
879 self.emit_error(Error, msg);
882 /// Emit an error; level should be `Error` or `Fatal`.
883 fn emit_error(&mut self, level: Level, msg: &str,) {
884 if self.treat_err_as_bug() {
887 self.emit_diagnostic(&Diagnostic::new(level, msg));
890 fn bug(&mut self, msg: &str) -> ! {
891 self.emit_diagnostic(&Diagnostic::new(Bug, msg));
895 fn delay_as_bug(&mut self, diagnostic: Diagnostic) {
896 if self.flags.report_delayed_bugs {
897 self.emit_diagnostic(&diagnostic);
899 self.delayed_span_bugs.push(diagnostic);
902 fn bump_err_count(&mut self) {
904 self.panic_if_treat_err_as_bug();
907 fn panic_if_treat_err_as_bug(&self) {
908 if self.treat_err_as_bug() {
909 let s = match (self.err_count(), self.flags.treat_err_as_bug.unwrap_or(0)) {
911 (1, 1) => "aborting due to `-Z treat-err-as-bug=1`".to_string(),
915 "aborting after {} errors due to `-Z treat-err-as-bug={}`",
926 #[derive(Copy, PartialEq, Clone, Hash, Debug, RustcEncodable, RustcDecodable)]
938 impl fmt::Display for Level {
939 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
945 fn color(self) -> ColorSpec {
946 let mut spec = ColorSpec::new();
948 Bug | Fatal | Error => {
949 spec.set_fg(Some(Color::Red))
953 spec.set_fg(Some(Color::Yellow))
954 .set_intense(cfg!(windows));
957 spec.set_fg(Some(Color::Green))
961 spec.set_fg(Some(Color::Cyan))
965 Cancelled => unreachable!(),
970 pub fn to_str(self) -> &'static str {
972 Bug => "error: internal compiler error",
973 Fatal | Error => "error",
974 Warning => "warning",
977 FailureNote => "failure-note",
978 Cancelled => panic!("Shouldn't call on cancelled error"),
982 pub fn is_failure_note(&self) -> bool {
991 macro_rules! pluralize {
993 if $x != 1 { "s" } else { "" }