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 pub fn span_fatal(&self, span: impl Into<MultiSpan>, msg: &str) -> FatalError {
579 self.emit_diag_at_span(Diagnostic::new(Fatal, msg), span);
583 pub fn span_fatal_with_code(
585 span: impl Into<MultiSpan>,
589 self.emit_diag_at_span(Diagnostic::new_with_code(Fatal, Some(code), msg), span);
593 pub fn span_err(&self, span: impl Into<MultiSpan>, msg: &str) {
594 self.emit_diag_at_span(Diagnostic::new(Error, msg), span);
597 pub fn span_err_with_code(&self, span: impl Into<MultiSpan>, msg: &str, code: DiagnosticId) {
598 self.emit_diag_at_span(Diagnostic::new_with_code(Error, Some(code), msg), span);
601 pub fn span_warn(&self, span: impl Into<MultiSpan>, msg: &str) {
602 self.emit_diag_at_span(Diagnostic::new(Warning, msg), span);
605 pub fn span_warn_with_code(&self, span: impl Into<MultiSpan>, msg: &str, code: DiagnosticId) {
606 self.emit_diag_at_span(Diagnostic::new_with_code(Warning, Some(code), msg), span);
609 pub fn span_bug(&self, span: impl Into<MultiSpan>, msg: &str) -> ! {
610 self.inner.borrow_mut().span_bug(span, msg)
613 pub fn delay_span_bug(&self, span: impl Into<MultiSpan>, msg: &str) {
614 self.inner.borrow_mut().delay_span_bug(span, msg)
617 pub fn span_bug_no_panic(&self, span: impl Into<MultiSpan>, msg: &str) {
618 self.emit_diag_at_span(Diagnostic::new(Bug, msg), span);
621 pub fn span_note_without_error(&self, span: impl Into<MultiSpan>, msg: &str) {
622 self.emit_diag_at_span(Diagnostic::new(Note, msg), span);
625 pub fn span_note_diag(&self, span: Span, msg: &str) -> DiagnosticBuilder<'_> {
626 let mut db = DiagnosticBuilder::new(self, Note, msg);
631 pub fn failure(&self, msg: &str) {
632 self.inner.borrow_mut().failure(msg);
635 pub fn fatal(&self, msg: &str) -> FatalError {
636 self.inner.borrow_mut().fatal(msg)
639 pub fn err(&self, msg: &str) {
640 self.inner.borrow_mut().err(msg);
643 pub fn warn(&self, msg: &str) {
644 let mut db = DiagnosticBuilder::new(self, Warning, msg);
648 pub fn note_without_error(&self, msg: &str) {
649 DiagnosticBuilder::new(self, Note, msg).emit();
652 pub fn bug(&self, msg: &str) -> ! {
653 self.inner.borrow_mut().bug(msg)
656 pub fn err_count(&self) -> usize {
657 self.inner.borrow().err_count()
660 pub fn has_errors(&self) -> bool {
661 self.inner.borrow().has_errors()
663 pub fn has_errors_or_delayed_span_bugs(&self) -> bool {
664 self.inner.borrow().has_errors_or_delayed_span_bugs()
667 pub fn print_error_count(&self, registry: &Registry) {
668 self.inner.borrow_mut().print_error_count(registry)
671 pub fn abort_if_errors(&self) {
672 self.inner.borrow_mut().abort_if_errors()
675 pub fn abort_if_errors_and_should_abort(&self) {
676 self.inner.borrow_mut().abort_if_errors_and_should_abort()
679 /// `true` if we haven't taught a diagnostic with this code already.
680 /// The caller must then teach the user about such a diagnostic.
682 /// Used to suppress emitting the same error multiple times with extended explanation when
683 /// calling `-Zteach`.
684 pub fn must_teach(&self, code: &DiagnosticId) -> bool {
685 self.inner.borrow_mut().must_teach(code)
688 pub fn force_print_diagnostic(&self, db: Diagnostic) {
689 self.inner.borrow_mut().force_print_diagnostic(db)
692 pub fn emit_diagnostic(&self, diagnostic: &Diagnostic) {
693 self.inner.borrow_mut().emit_diagnostic(diagnostic)
696 fn emit_diag_at_span(&self, mut diag: Diagnostic, sp: impl Into<MultiSpan>) {
697 let mut inner = self.inner.borrow_mut();
698 inner.emit_diagnostic(diag.set_span(sp));
699 inner.abort_if_errors_and_should_abort();
702 pub fn emit_artifact_notification(&self, path: &Path, artifact_type: &str) {
703 self.inner.borrow_mut().emit_artifact_notification(path, artifact_type)
706 pub fn delay_as_bug(&self, diagnostic: Diagnostic) {
707 self.inner.borrow_mut().delay_as_bug(diagnostic)
712 fn must_teach(&mut self, code: &DiagnosticId) -> bool {
713 self.taught_diagnostics.insert(code.clone())
716 fn force_print_diagnostic(&mut self, db: Diagnostic) {
717 self.emitter.emit_diagnostic(&db);
720 /// Emit all stashed diagnostics.
721 fn emit_stashed_diagnostics(&mut self) {
722 let diags = self.stashed_diagnostics.drain(..).map(|x| x.1).collect::<Vec<_>>();
723 diags.iter().for_each(|diag| self.emit_diagnostic(diag));
726 fn emit_diagnostic(&mut self, diagnostic: &Diagnostic) {
727 if diagnostic.cancelled() {
731 if diagnostic.level == Warning && !self.flags.can_emit_warnings {
735 TRACK_DIAGNOSTICS.with(|track_diagnostics| {
736 track_diagnostics.get()(diagnostic);
739 if let Some(ref code) = diagnostic.code {
740 self.emitted_diagnostic_codes.insert(code.clone());
743 let diagnostic_hash = {
745 let mut hasher = StableHasher::new();
746 diagnostic.hash(&mut hasher);
750 // Only emit the diagnostic if we haven't already emitted an equivalent
752 if self.emitted_diagnostics.insert(diagnostic_hash) {
753 self.emitter.emit_diagnostic(diagnostic);
754 if diagnostic.is_error() {
755 self.deduplicated_err_count += 1;
758 if diagnostic.is_error() {
759 self.bump_err_count();
763 fn emit_artifact_notification(&mut self, path: &Path, artifact_type: &str) {
764 self.emitter.emit_artifact_notification(path, artifact_type);
767 fn treat_err_as_bug(&self) -> bool {
768 self.flags.treat_err_as_bug.map(|c| self.err_count() >= c).unwrap_or(false)
771 fn print_error_count(&mut self, registry: &Registry) {
772 self.emit_stashed_diagnostics();
774 let s = match self.deduplicated_err_count {
776 1 => "aborting due to previous error".to_string(),
777 count => format!("aborting due to {} previous errors", count)
779 if self.treat_err_as_bug() {
783 let _ = self.fatal(&s);
785 let can_show_explain = self.emitter.should_show_explain();
786 let are_there_diagnostics = !self.emitted_diagnostic_codes.is_empty();
787 if can_show_explain && are_there_diagnostics {
788 let mut error_codes = self
789 .emitted_diagnostic_codes
791 .filter_map(|x| match &x {
792 DiagnosticId::Error(s) if registry.find_description(s).is_some() => {
797 .collect::<Vec<_>>();
798 if !error_codes.is_empty() {
800 if error_codes.len() > 1 {
801 let limit = if error_codes.len() > 9 { 9 } else { error_codes.len() };
802 self.failure(&format!("Some errors have detailed explanations: {}{}",
803 error_codes[..limit].join(", "),
804 if error_codes.len() > 9 { "..." } else { "." }));
805 self.failure(&format!("For more information about an error, try \
806 `rustc --explain {}`.",
809 self.failure(&format!("For more information about this error, try \
810 `rustc --explain {}`.",
817 fn err_count(&self) -> usize {
818 self.err_count + self.stashed_diagnostics.len()
821 fn has_errors(&self) -> bool {
824 fn has_errors_or_delayed_span_bugs(&self) -> bool {
825 self.has_errors() || !self.delayed_span_bugs.is_empty()
828 fn abort_if_errors_and_should_abort(&mut self) {
829 self.emit_stashed_diagnostics();
831 if self.has_errors() && !self.continue_after_error {
836 fn abort_if_errors(&mut self) {
837 self.emit_stashed_diagnostics();
839 if self.has_errors() {
844 fn span_bug(&mut self, sp: impl Into<MultiSpan>, msg: &str) -> ! {
845 self.emit_diag_at_span(Diagnostic::new(Bug, msg), sp);
849 fn emit_diag_at_span(&mut self, mut diag: Diagnostic, sp: impl Into<MultiSpan>) {
850 self.emit_diagnostic(diag.set_span(sp));
851 self.abort_if_errors_and_should_abort();
854 fn delay_span_bug(&mut self, sp: impl Into<MultiSpan>, msg: &str) {
855 if self.treat_err_as_bug() {
856 // FIXME: don't abort here if report_delayed_bugs is off
857 self.span_bug(sp, msg);
859 let mut diagnostic = Diagnostic::new(Level::Bug, msg);
860 diagnostic.set_span(sp.into());
861 self.delay_as_bug(diagnostic)
864 fn failure(&mut self, msg: &str) {
865 self.emit_diagnostic(&Diagnostic::new(FailureNote, msg));
868 fn fatal(&mut self, msg: &str) -> FatalError {
869 self.emit_error(Fatal, msg);
873 fn err(&mut self, msg: &str) {
874 self.emit_error(Error, msg);
877 /// Emit an error; level should be `Error` or `Fatal`.
878 fn emit_error(&mut self, level: Level, msg: &str,) {
879 if self.treat_err_as_bug() {
882 self.emit_diagnostic(&Diagnostic::new(level, msg));
885 fn bug(&mut self, msg: &str) -> ! {
886 self.emit_diagnostic(&Diagnostic::new(Bug, msg));
890 fn delay_as_bug(&mut self, diagnostic: Diagnostic) {
891 if self.flags.report_delayed_bugs {
892 self.emit_diagnostic(&diagnostic);
894 self.delayed_span_bugs.push(diagnostic);
897 fn bump_err_count(&mut self) {
899 self.panic_if_treat_err_as_bug();
902 fn panic_if_treat_err_as_bug(&self) {
903 if self.treat_err_as_bug() {
904 let s = match (self.err_count(), self.flags.treat_err_as_bug.unwrap_or(0)) {
906 (1, 1) => "aborting due to `-Z treat-err-as-bug=1`".to_string(),
910 "aborting after {} errors due to `-Z treat-err-as-bug={}`",
921 #[derive(Copy, PartialEq, Clone, Hash, Debug, RustcEncodable, RustcDecodable)]
933 impl fmt::Display for Level {
934 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
940 fn color(self) -> ColorSpec {
941 let mut spec = ColorSpec::new();
943 Bug | Fatal | Error => {
944 spec.set_fg(Some(Color::Red))
948 spec.set_fg(Some(Color::Yellow))
949 .set_intense(cfg!(windows));
952 spec.set_fg(Some(Color::Green))
956 spec.set_fg(Some(Color::Cyan))
960 Cancelled => unreachable!(),
965 pub fn to_str(self) -> &'static str {
967 Bug => "error: internal compiler error",
968 Fatal | Error => "error",
969 Warning => "warning",
972 FailureNote => "failure-note",
973 Cancelled => panic!("Shouldn't call on cancelled error"),
977 pub fn is_failure_note(&self) -> bool {
986 macro_rules! pluralize {
988 if $x != 1 { "s" } else { "" }