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)]
9 pub use emitter::ColorConfig;
14 use emitter::{is_case_difference, Emitter, EmitterWriter};
15 use registry::Registry;
16 use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
17 use rustc_data_structures::stable_hasher::StableHasher;
18 use rustc_data_structures::sync::{self, Lock, Lrc};
19 use rustc_data_structures::AtomicRef;
20 use rustc_span::source_map::SourceMap;
21 use rustc_span::{Loc, MultiSpan, Span};
26 use std::{error, fmt};
28 use termcolor::{Color, ColorSpec};
30 pub mod annotate_snippet_emitter_writer;
32 mod diagnostic_builder;
39 pub use snippet::Style;
41 pub type PResult<'a, T> = Result<T, DiagnosticBuilder<'a>>;
43 // `PResult` is used a lot. Make sure it doesn't unintentionally get bigger.
44 // (See also the comment on `DiagnosticBuilderInner`.)
45 #[cfg(target_arch = "x86_64")]
46 rustc_data_structures::static_assert_size!(PResult<'_, bool>, 16);
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
84 /// Always show the suggested code independently.
88 impl SuggestionStyle {
89 fn hide_inline(&self) -> bool {
91 SuggestionStyle::ShowCode => false,
97 #[derive(Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
98 pub struct CodeSuggestion {
99 /// Each substitute can have multiple variants due to multiple
100 /// applicable suggestions
102 /// `foo.bar` might be replaced with `a.b` or `x.y` by replacing
103 /// `foo` and `bar` on their own:
107 /// Substitution { parts: vec![(0..3, "a"), (4..7, "b")] },
108 /// Substitution { parts: vec![(0..3, "x"), (4..7, "y")] },
112 /// or by replacing the entire span:
116 /// Substitution { parts: vec![(0..7, "a.b")] },
117 /// Substitution { parts: vec![(0..7, "x.y")] },
120 pub substitutions: Vec<Substitution>,
122 /// Visual representation of this suggestion.
123 pub style: SuggestionStyle,
124 /// Whether or not the suggestion is approximate
126 /// Sometimes we may show suggestions with placeholders,
127 /// which are useful for users but not useful for
128 /// tools like rustfix
129 pub applicability: Applicability,
132 #[derive(Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
133 /// See the docs on `CodeSuggestion::substitutions`
134 pub struct Substitution {
135 pub parts: Vec<SubstitutionPart>,
138 #[derive(Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
139 pub struct SubstitutionPart {
144 impl CodeSuggestion {
145 /// Returns the assembled code suggestions, whether they should be shown with an underline
146 /// and whether the substitution only differs in capitalization.
147 pub fn splice_lines(&self, sm: &SourceMap) -> Vec<(String, Vec<SubstitutionPart>, bool)> {
148 use rustc_span::{CharPos, Pos};
152 line_opt: Option<&Cow<'_, str>>,
154 hi_opt: Option<&Loc>,
156 let (lo, hi_opt) = (lo.col.to_usize(), hi_opt.map(|hi| hi.col.to_usize()));
157 if let Some(line) = line_opt {
158 if let Some(lo) = line.char_indices().map(|(i, _)| i).nth(lo) {
159 let hi_opt = hi_opt.and_then(|hi| line.char_indices().map(|(i, _)| i).nth(hi));
161 Some(hi) if hi > lo => buf.push_str(&line[lo..hi]),
163 None => buf.push_str(&line[lo..]),
166 if let None = hi_opt {
172 assert!(!self.substitutions.is_empty());
177 // Suggestions coming from macros can have malformed spans. This is a heavy
178 // handed approach to avoid ICEs by ignoring the suggestion outright.
179 let invalid = subst.parts.iter().any(|item| sm.is_valid_span(item.span).is_err());
181 debug!("splice_lines: suggestion contains an invalid span: {:?}", subst);
186 .filter_map(|mut substitution| {
187 // Assumption: all spans are in the same file, and all spans
188 // are disjoint. Sort in ascending order.
189 substitution.parts.sort_by_key(|part| part.span.lo());
191 // Find the bounding span.
192 let lo = substitution.parts.iter().map(|part| part.span.lo()).min()?;
193 let hi = substitution.parts.iter().map(|part| part.span.hi()).max()?;
194 let bounding_span = Span::with_root_ctxt(lo, hi);
195 // The different spans might belong to different contexts, if so ignore suggestion.
196 let lines = sm.span_to_lines(bounding_span).ok()?;
197 assert!(!lines.lines.is_empty());
199 // To build up the result, we do this for each span:
200 // - push the line segment trailing the previous span
201 // (at the beginning a "phantom" span pointing at the start of the line)
202 // - push lines between the previous and current span (if any)
203 // - if the previous and current span are not on the same line
204 // push the line segment leading up to the current span
205 // - splice in the span substitution
207 // Finally push the trailing line segment of the last span
208 let sf = &lines.file;
209 let mut prev_hi = sm.lookup_char_pos(bounding_span.lo());
210 prev_hi.col = CharPos::from_usize(0);
212 let mut prev_line = sf.get_line(lines.lines[0].line_index);
213 let mut buf = String::new();
215 for part in &substitution.parts {
216 let cur_lo = sm.lookup_char_pos(part.span.lo());
217 if prev_hi.line == cur_lo.line {
218 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, Some(&cur_lo));
220 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
221 // push lines between the previous and current span (if any)
222 for idx in prev_hi.line..(cur_lo.line - 1) {
223 if let Some(line) = sf.get_line(idx) {
224 buf.push_str(line.as_ref());
228 if let Some(cur_line) = sf.get_line(cur_lo.line - 1) {
229 let end = std::cmp::min(cur_line.len(), cur_lo.col.to_usize());
230 buf.push_str(&cur_line[..end]);
233 buf.push_str(&part.snippet);
234 prev_hi = sm.lookup_char_pos(part.span.hi());
235 prev_line = sf.get_line(prev_hi.line - 1);
237 let only_capitalization = is_case_difference(sm, &buf, bounding_span);
238 // if the replacement already ends with a newline, don't print the next line
239 if !buf.ends_with('\n') {
240 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
242 // remove trailing newlines
243 while buf.ends_with('\n') {
246 Some((buf, substitution.parts, only_capitalization))
252 pub use rustc_span::fatal_error::{FatalError, FatalErrorMarker};
254 /// Signifies that the compiler died with an explicit call to `.bug`
255 /// or `.span_bug` rather than a failed assertion, etc.
256 #[derive(Copy, Clone, Debug)]
257 pub struct ExplicitBug;
259 impl fmt::Display for ExplicitBug {
260 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
261 write!(f, "parser internal bug")
265 impl error::Error for ExplicitBug {}
267 pub use diagnostic::{Diagnostic, DiagnosticId, DiagnosticStyledString, SubDiagnostic};
268 pub use diagnostic_builder::DiagnosticBuilder;
270 /// A handler deals with errors and other compiler output.
271 /// Certain errors (fatal, bug, unimpl) may cause immediate exit,
272 /// others log errors for later reporting.
275 inner: Lock<HandlerInner>,
278 /// This inner struct exists to keep it all behind a single lock;
279 /// this is done to prevent possible deadlocks in a multi-threaded compiler,
280 /// as well as inconsistent state observation.
281 struct HandlerInner {
283 /// The number of errors that have been emitted, including duplicates.
285 /// This is not necessarily the count that's reported to the user once
286 /// compilation ends.
288 deduplicated_err_count: usize,
289 emitter: Box<dyn Emitter + sync::Send>,
290 delayed_span_bugs: Vec<Diagnostic>,
292 /// This set contains the `DiagnosticId` of all emitted diagnostics to avoid
293 /// emitting the same diagnostic with extended help (`--teach`) twice, which
294 /// would be uneccessary repetition.
295 taught_diagnostics: FxHashSet<DiagnosticId>,
297 /// Used to suggest rustc --explain <error code>
298 emitted_diagnostic_codes: FxHashSet<DiagnosticId>,
300 /// This set contains a hash of every diagnostic that has been emitted by
301 /// this handler. These hashes is used to avoid emitting the same error
303 emitted_diagnostics: FxHashSet<u128>,
305 /// Stashed diagnostics emitted in one stage of the compiler that may be
306 /// stolen by other stages (e.g. to improve them and add more information).
307 /// The stashed diagnostics count towards the total error count.
308 /// When `.abort_if_errors()` is called, these are also emitted.
309 stashed_diagnostics: FxIndexMap<(Span, StashKey), Diagnostic>,
312 /// A key denoting where from a diagnostic was stashed.
313 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
318 fn default_track_diagnostic(_: &Diagnostic) {}
320 pub static TRACK_DIAGNOSTICS: AtomicRef<fn(&Diagnostic)> =
321 AtomicRef::new(&(default_track_diagnostic as fn(&_)));
323 #[derive(Copy, Clone, Default)]
324 pub struct HandlerFlags {
325 /// If false, warning-level lints are suppressed.
326 /// (rustc: see `--allow warnings` and `--cap-lints`)
327 pub can_emit_warnings: bool,
328 /// If true, error-level diagnostics are upgraded to bug-level.
329 /// (rustc: see `-Z treat-err-as-bug`)
330 pub treat_err_as_bug: Option<usize>,
331 /// If true, immediately emit diagnostics that would otherwise be buffered.
332 /// (rustc: see `-Z dont-buffer-diagnostics` and `-Z treat-err-as-bug`)
333 pub dont_buffer_diagnostics: bool,
334 /// If true, immediately print bugs registered with `delay_span_bug`.
335 /// (rustc: see `-Z report-delayed-bugs`)
336 pub report_delayed_bugs: bool,
337 /// Show macro backtraces.
338 /// (rustc: see `-Z macro-backtrace`)
339 pub macro_backtrace: bool,
340 /// If true, identical diagnostics are reported only once.
341 pub deduplicate_diagnostics: bool,
344 impl Drop for HandlerInner {
346 self.emit_stashed_diagnostics();
348 if !self.has_errors() {
349 let bugs = std::mem::replace(&mut self.delayed_span_bugs, Vec::new());
350 let has_bugs = !bugs.is_empty();
352 self.emit_diagnostic(&bug);
355 panic!("no errors encountered even though `delay_span_bug` issued");
362 pub fn with_tty_emitter(
363 color_config: ColorConfig,
364 can_emit_warnings: bool,
365 treat_err_as_bug: Option<usize>,
366 sm: Option<Lrc<SourceMap>>,
368 Self::with_tty_emitter_and_flags(
371 HandlerFlags { can_emit_warnings, treat_err_as_bug, ..Default::default() },
375 pub fn with_tty_emitter_and_flags(
376 color_config: ColorConfig,
377 sm: Option<Lrc<SourceMap>>,
380 let emitter = Box::new(EmitterWriter::stderr(
386 flags.macro_backtrace,
388 Self::with_emitter_and_flags(emitter, flags)
392 can_emit_warnings: bool,
393 treat_err_as_bug: Option<usize>,
394 emitter: Box<dyn Emitter + sync::Send>,
396 Handler::with_emitter_and_flags(
398 HandlerFlags { can_emit_warnings, treat_err_as_bug, ..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 delayed_span_bugs: Vec::new(),
414 taught_diagnostics: Default::default(),
415 emitted_diagnostic_codes: Default::default(),
416 emitted_diagnostics: Default::default(),
417 stashed_diagnostics: Default::default(),
422 // This is here to not allow mutation of flags;
423 // as of this writing it's only used in tests in librustc.
424 pub fn can_emit_warnings(&self) -> bool {
425 self.flags.can_emit_warnings
428 /// Resets the diagnostic error count as well as the cached emitted diagnostics.
430 /// NOTE: *do not* call this function from rustc. It is only meant to be called from external
431 /// tools that want to reuse a `Parser` cleaning the previously emitted diagnostics as well as
432 /// the overall count of emitted error diagnostics.
433 pub fn reset_err_count(&self) {
434 let mut inner = self.inner.borrow_mut();
436 inner.deduplicated_err_count = 0;
438 // actually free the underlying memory (which `clear` would not do)
439 inner.delayed_span_bugs = Default::default();
440 inner.taught_diagnostics = Default::default();
441 inner.emitted_diagnostic_codes = Default::default();
442 inner.emitted_diagnostics = Default::default();
443 inner.stashed_diagnostics = Default::default();
446 /// Stash a given diagnostic with the given `Span` and `StashKey` as the key for later stealing.
447 /// If the diagnostic with this `(span, key)` already exists, this will result in an ICE.
448 pub fn stash_diagnostic(&self, span: Span, key: StashKey, diag: Diagnostic) {
449 let mut inner = self.inner.borrow_mut();
450 if let Some(mut old_diag) = inner.stashed_diagnostics.insert((span, key), diag) {
451 // We are removing a previously stashed diagnostic which should not happen.
452 old_diag.level = Bug;
453 old_diag.note(&format!(
454 "{}:{}: already existing stashed diagnostic with (span = {:?}, key = {:?})",
460 inner.emit_diag_at_span(old_diag, span);
465 /// Steal a previously stashed diagnostic with the given `Span` and `StashKey` as the key.
466 pub fn steal_diagnostic(&self, span: Span, key: StashKey) -> Option<DiagnosticBuilder<'_>> {
470 .remove(&(span, key))
471 .map(|diag| DiagnosticBuilder::new_diagnostic(self, diag))
474 /// Emit all stashed diagnostics.
475 pub fn emit_stashed_diagnostics(&self) {
476 self.inner.borrow_mut().emit_stashed_diagnostics();
479 /// Construct a dummy builder with `Level::Cancelled`.
481 /// Using this will neither report anything to the user (e.g. a warning),
482 /// nor will compilation cancel as a result.
483 pub fn struct_dummy(&self) -> DiagnosticBuilder<'_> {
484 DiagnosticBuilder::new(self, Level::Cancelled, "")
487 /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
488 pub fn struct_span_warn(&self, span: impl Into<MultiSpan>, msg: &str) -> DiagnosticBuilder<'_> {
489 let mut result = self.struct_warn(msg);
490 result.set_span(span);
494 /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
495 /// Also include a code.
496 pub fn struct_span_warn_with_code(
498 span: impl Into<MultiSpan>,
501 ) -> DiagnosticBuilder<'_> {
502 let mut result = self.struct_span_warn(span, msg);
507 /// Construct a builder at the `Warning` level with the `msg`.
508 pub fn struct_warn(&self, msg: &str) -> DiagnosticBuilder<'_> {
509 let mut result = DiagnosticBuilder::new(self, Level::Warning, msg);
510 if !self.flags.can_emit_warnings {
516 /// Construct a builder at the `Error` level at the given `span` and with the `msg`.
517 pub fn struct_span_err(&self, span: impl Into<MultiSpan>, msg: &str) -> DiagnosticBuilder<'_> {
518 let mut result = self.struct_err(msg);
519 result.set_span(span);
523 /// Construct a builder at the `Error` level at the given `span`, with the `msg`, and `code`.
524 pub fn struct_span_err_with_code(
526 span: impl Into<MultiSpan>,
529 ) -> DiagnosticBuilder<'_> {
530 let mut result = self.struct_span_err(span, msg);
535 /// Construct a builder at the `Error` level with the `msg`.
536 // FIXME: This method should be removed (every error should have an associated error code).
537 pub fn struct_err(&self, msg: &str) -> DiagnosticBuilder<'_> {
538 DiagnosticBuilder::new(self, Level::Error, msg)
541 /// Construct a builder at the `Error` level with the `msg` and the `code`.
542 pub fn struct_err_with_code(&self, msg: &str, code: DiagnosticId) -> DiagnosticBuilder<'_> {
543 let mut result = self.struct_err(msg);
548 /// Construct a builder at the `Fatal` level at the given `span` and with the `msg`.
549 pub fn struct_span_fatal(
551 span: impl Into<MultiSpan>,
553 ) -> DiagnosticBuilder<'_> {
554 let mut result = self.struct_fatal(msg);
555 result.set_span(span);
559 /// Construct a builder at the `Fatal` level at the given `span`, with the `msg`, and `code`.
560 pub fn struct_span_fatal_with_code(
562 span: impl Into<MultiSpan>,
565 ) -> DiagnosticBuilder<'_> {
566 let mut result = self.struct_span_fatal(span, msg);
571 /// Construct a builder at the `Error` level with the `msg`.
572 pub fn struct_fatal(&self, msg: &str) -> DiagnosticBuilder<'_> {
573 DiagnosticBuilder::new(self, Level::Fatal, msg)
576 /// Construct a builder at the `Help` level with the `msg`.
577 pub fn struct_help(&self, msg: &str) -> DiagnosticBuilder<'_> {
578 DiagnosticBuilder::new(self, Level::Help, msg)
581 pub fn span_fatal(&self, span: impl Into<MultiSpan>, msg: &str) -> FatalError {
582 self.emit_diag_at_span(Diagnostic::new(Fatal, msg), span);
586 pub fn span_fatal_with_code(
588 span: impl Into<MultiSpan>,
592 self.emit_diag_at_span(Diagnostic::new_with_code(Fatal, Some(code), msg), span);
596 pub fn span_err(&self, span: impl Into<MultiSpan>, msg: &str) {
597 self.emit_diag_at_span(Diagnostic::new(Error, msg), span);
600 pub fn span_err_with_code(&self, span: impl Into<MultiSpan>, msg: &str, code: DiagnosticId) {
601 self.emit_diag_at_span(Diagnostic::new_with_code(Error, Some(code), msg), span);
604 pub fn span_warn(&self, span: impl Into<MultiSpan>, msg: &str) {
605 self.emit_diag_at_span(Diagnostic::new(Warning, msg), span);
608 pub fn span_warn_with_code(&self, span: impl Into<MultiSpan>, msg: &str, code: DiagnosticId) {
609 self.emit_diag_at_span(Diagnostic::new_with_code(Warning, Some(code), msg), span);
612 pub fn span_bug(&self, span: impl Into<MultiSpan>, msg: &str) -> ! {
613 self.inner.borrow_mut().span_bug(span, msg)
616 pub fn delay_span_bug(&self, span: impl Into<MultiSpan>, msg: &str) {
617 self.inner.borrow_mut().delay_span_bug(span, msg)
620 pub fn span_bug_no_panic(&self, span: impl Into<MultiSpan>, msg: &str) {
621 self.emit_diag_at_span(Diagnostic::new(Bug, msg), span);
624 pub fn span_note_without_error(&self, span: impl Into<MultiSpan>, msg: &str) {
625 self.emit_diag_at_span(Diagnostic::new(Note, msg), span);
628 pub fn span_note_diag(&self, span: Span, msg: &str) -> DiagnosticBuilder<'_> {
629 let mut db = DiagnosticBuilder::new(self, Note, msg);
634 pub fn failure(&self, msg: &str) {
635 self.inner.borrow_mut().failure(msg);
638 pub fn fatal(&self, msg: &str) -> FatalError {
639 self.inner.borrow_mut().fatal(msg)
642 pub fn err(&self, msg: &str) {
643 self.inner.borrow_mut().err(msg);
646 pub fn warn(&self, msg: &str) {
647 let mut db = DiagnosticBuilder::new(self, Warning, msg);
651 pub fn note_without_error(&self, msg: &str) {
652 DiagnosticBuilder::new(self, Note, msg).emit();
655 pub fn bug(&self, msg: &str) -> ! {
656 self.inner.borrow_mut().bug(msg)
659 pub fn err_count(&self) -> usize {
660 self.inner.borrow().err_count()
663 pub fn has_errors(&self) -> bool {
664 self.inner.borrow().has_errors()
666 pub fn has_errors_or_delayed_span_bugs(&self) -> bool {
667 self.inner.borrow().has_errors_or_delayed_span_bugs()
670 pub fn print_error_count(&self, registry: &Registry) {
671 self.inner.borrow_mut().print_error_count(registry)
674 pub fn abort_if_errors(&self) {
675 self.inner.borrow_mut().abort_if_errors()
678 /// `true` if we haven't taught a diagnostic with this code already.
679 /// The caller must then teach the user about such a diagnostic.
681 /// Used to suppress emitting the same error multiple times with extended explanation when
682 /// calling `-Zteach`.
683 pub fn must_teach(&self, code: &DiagnosticId) -> bool {
684 self.inner.borrow_mut().must_teach(code)
687 pub fn force_print_diagnostic(&self, db: Diagnostic) {
688 self.inner.borrow_mut().force_print_diagnostic(db)
691 pub fn emit_diagnostic(&self, diagnostic: &Diagnostic) {
692 self.inner.borrow_mut().emit_diagnostic(diagnostic)
695 fn emit_diag_at_span(&self, mut diag: Diagnostic, sp: impl Into<MultiSpan>) {
696 let mut inner = self.inner.borrow_mut();
697 inner.emit_diagnostic(diag.set_span(sp));
700 pub fn emit_artifact_notification(&self, path: &Path, artifact_type: &str) {
701 self.inner.borrow_mut().emit_artifact_notification(path, artifact_type)
704 pub fn delay_as_bug(&self, diagnostic: Diagnostic) {
705 self.inner.borrow_mut().delay_as_bug(diagnostic)
710 fn must_teach(&mut self, code: &DiagnosticId) -> bool {
711 self.taught_diagnostics.insert(code.clone())
714 fn force_print_diagnostic(&mut self, db: Diagnostic) {
715 self.emitter.emit_diagnostic(&db);
718 /// Emit all stashed diagnostics.
719 fn emit_stashed_diagnostics(&mut self) {
720 let diags = self.stashed_diagnostics.drain(..).map(|x| x.1).collect::<Vec<_>>();
721 diags.iter().for_each(|diag| self.emit_diagnostic(diag));
724 fn emit_diagnostic(&mut self, diagnostic: &Diagnostic) {
725 if diagnostic.cancelled() {
729 if diagnostic.level == Warning && !self.flags.can_emit_warnings {
733 (*TRACK_DIAGNOSTICS)(diagnostic);
735 if let Some(ref code) = diagnostic.code {
736 self.emitted_diagnostic_codes.insert(code.clone());
739 let already_emitted = |this: &mut Self| {
741 let mut hasher = StableHasher::new();
742 diagnostic.hash(&mut hasher);
743 let diagnostic_hash = hasher.finish();
744 !this.emitted_diagnostics.insert(diagnostic_hash)
747 // Only emit the diagnostic if we've been asked to deduplicate and
748 // haven't already emitted an equivalent diagnostic.
749 if !(self.flags.deduplicate_diagnostics && already_emitted(self)) {
750 self.emitter.emit_diagnostic(diagnostic);
751 if diagnostic.is_error() {
752 self.deduplicated_err_count += 1;
755 if diagnostic.is_error() {
756 self.bump_err_count();
760 fn emit_artifact_notification(&mut self, path: &Path, artifact_type: &str) {
761 self.emitter.emit_artifact_notification(path, artifact_type);
764 fn treat_err_as_bug(&self) -> bool {
765 self.flags.treat_err_as_bug.map(|c| self.err_count() >= c).unwrap_or(false)
768 fn print_error_count(&mut self, registry: &Registry) {
769 self.emit_stashed_diagnostics();
771 let s = match self.deduplicated_err_count {
773 1 => "aborting due to previous error".to_string(),
774 count => format!("aborting due to {} previous errors", count),
776 if self.treat_err_as_bug() {
780 let _ = self.fatal(&s);
782 let can_show_explain = self.emitter.should_show_explain();
783 let are_there_diagnostics = !self.emitted_diagnostic_codes.is_empty();
784 if can_show_explain && are_there_diagnostics {
785 let mut error_codes = self
786 .emitted_diagnostic_codes
788 .filter_map(|x| match &x {
789 DiagnosticId::Error(s) if registry.find_description(s).is_some() => {
794 .collect::<Vec<_>>();
795 if !error_codes.is_empty() {
797 if error_codes.len() > 1 {
798 let limit = if error_codes.len() > 9 { 9 } else { error_codes.len() };
799 self.failure(&format!(
800 "Some errors have detailed explanations: {}{}",
801 error_codes[..limit].join(", "),
802 if error_codes.len() > 9 { "..." } else { "." }
804 self.failure(&format!(
805 "For more information about an error, try \
806 `rustc --explain {}`.",
810 self.failure(&format!(
811 "For more information about this error, try \
812 `rustc --explain {}`.",
820 fn err_count(&self) -> usize {
821 self.err_count + self.stashed_diagnostics.len()
824 fn has_errors(&self) -> bool {
827 fn has_errors_or_delayed_span_bugs(&self) -> bool {
828 self.has_errors() || !self.delayed_span_bugs.is_empty()
831 fn abort_if_errors(&mut self) {
832 self.emit_stashed_diagnostics();
834 if self.has_errors() {
839 fn span_bug(&mut self, sp: impl Into<MultiSpan>, msg: &str) -> ! {
840 self.emit_diag_at_span(Diagnostic::new(Bug, msg), sp);
844 fn emit_diag_at_span(&mut self, mut diag: Diagnostic, sp: impl Into<MultiSpan>) {
845 self.emit_diagnostic(diag.set_span(sp));
848 fn delay_span_bug(&mut self, sp: impl Into<MultiSpan>, msg: &str) {
849 if self.treat_err_as_bug() {
850 // FIXME: don't abort here if report_delayed_bugs is off
851 self.span_bug(sp, msg);
853 let mut diagnostic = Diagnostic::new(Level::Bug, msg);
854 diagnostic.set_span(sp.into());
855 self.delay_as_bug(diagnostic)
858 fn failure(&mut self, msg: &str) {
859 self.emit_diagnostic(&Diagnostic::new(FailureNote, msg));
862 fn fatal(&mut self, msg: &str) -> FatalError {
863 self.emit_error(Fatal, msg);
867 fn err(&mut self, msg: &str) {
868 self.emit_error(Error, msg);
871 /// Emit an error; level should be `Error` or `Fatal`.
872 fn emit_error(&mut self, level: Level, msg: &str) {
873 if self.treat_err_as_bug() {
876 self.emit_diagnostic(&Diagnostic::new(level, msg));
879 fn bug(&mut self, msg: &str) -> ! {
880 self.emit_diagnostic(&Diagnostic::new(Bug, msg));
884 fn delay_as_bug(&mut self, diagnostic: Diagnostic) {
885 if self.flags.report_delayed_bugs {
886 self.emit_diagnostic(&diagnostic);
888 self.delayed_span_bugs.push(diagnostic);
891 fn bump_err_count(&mut self) {
893 self.panic_if_treat_err_as_bug();
896 fn panic_if_treat_err_as_bug(&self) {
897 if self.treat_err_as_bug() {
898 let s = match (self.err_count(), self.flags.treat_err_as_bug.unwrap_or(0)) {
900 (1, 1) => "aborting due to `-Z treat-err-as-bug=1`".to_string(),
902 (count, as_bug) => format!(
903 "aborting after {} errors due to `-Z treat-err-as-bug={}`",
912 #[derive(Copy, PartialEq, Clone, Hash, Debug, RustcEncodable, RustcDecodable)]
924 impl fmt::Display for Level {
925 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
931 fn color(self) -> ColorSpec {
932 let mut spec = ColorSpec::new();
934 Bug | Fatal | Error => {
935 spec.set_fg(Some(Color::Red)).set_intense(true);
938 spec.set_fg(Some(Color::Yellow)).set_intense(cfg!(windows));
941 spec.set_fg(Some(Color::Green)).set_intense(true);
944 spec.set_fg(Some(Color::Cyan)).set_intense(true);
947 Cancelled => unreachable!(),
952 pub fn to_str(self) -> &'static str {
954 Bug => "error: internal compiler error",
955 Fatal | Error => "error",
956 Warning => "warning",
959 FailureNote => "failure-note",
960 Cancelled => panic!("Shouldn't call on cancelled error"),
964 pub fn is_failure_note(&self) -> bool {
973 macro_rules! pluralize {
975 if $x != 1 { "s" } else { "" }
979 // Useful type to use with `Result<>` indicate that an error has already
980 // been reported to the user, so no need to continue checking.
981 #[derive(Clone, Copy, Debug, RustcEncodable, RustcDecodable, Hash, PartialEq, Eq)]
982 pub struct ErrorReported;
984 rustc_data_structures::impl_stable_hash_via_hash!(ErrorReported);