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 /// Returns the assembled code suggestions, whether they should be shown with an underline
148 /// and whether the substitution only differs in capitalization.
149 pub fn splice_lines(&self, cm: &SourceMap) -> Vec<(String, Vec<SubstitutionPart>, bool)> {
150 use rustc_span::{CharPos, Pos};
154 line_opt: Option<&Cow<'_, str>>,
156 hi_opt: Option<&Loc>,
158 let (lo, hi_opt) = (lo.col.to_usize(), hi_opt.map(|hi| hi.col.to_usize()));
159 if let Some(line) = line_opt {
160 if let Some(lo) = line.char_indices().map(|(i, _)| i).nth(lo) {
161 let hi_opt = hi_opt.and_then(|hi| line.char_indices().map(|(i, _)| i).nth(hi));
163 Some(hi) if hi > lo => buf.push_str(&line[lo..hi]),
165 None => buf.push_str(&line[lo..]),
168 if let None = hi_opt {
174 assert!(!self.substitutions.is_empty());
179 // Suggestions coming from macros can have malformed spans. This is a heavy
180 // handed approach to avoid ICEs by ignoring the suggestion outright.
181 let invalid = subst.parts.iter().any(|item| cm.is_valid_span(item.span).is_err());
183 debug!("splice_lines: suggestion contains an invalid span: {:?}", subst);
188 .map(|mut substitution| {
189 // Assumption: all spans are in the same file, and all spans
190 // are disjoint. Sort in ascending order.
191 substitution.parts.sort_by_key(|part| part.span.lo());
193 // Find the bounding span.
194 let lo = substitution.parts.iter().map(|part| part.span.lo()).min().unwrap();
195 let hi = substitution.parts.iter().map(|part| part.span.hi()).max().unwrap();
196 let bounding_span = Span::with_root_ctxt(lo, hi);
197 let lines = cm.span_to_lines(bounding_span).unwrap();
198 assert!(!lines.lines.is_empty());
200 // To build up the result, we do this for each span:
201 // - push the line segment trailing the previous span
202 // (at the beginning a "phantom" span pointing at the start of the line)
203 // - push lines between the previous and current span (if any)
204 // - if the previous and current span are not on the same line
205 // push the line segment leading up to the current span
206 // - splice in the span substitution
208 // Finally push the trailing line segment of the last span
209 let fm = &lines.file;
210 let mut prev_hi = cm.lookup_char_pos(bounding_span.lo());
211 prev_hi.col = CharPos::from_usize(0);
213 let mut prev_line = fm.get_line(lines.lines[0].line_index);
214 let mut buf = String::new();
216 for part in &substitution.parts {
217 let cur_lo = cm.lookup_char_pos(part.span.lo());
218 if prev_hi.line == cur_lo.line {
219 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, Some(&cur_lo));
221 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
222 // push lines between the previous and current span (if any)
223 for idx in prev_hi.line..(cur_lo.line - 1) {
224 if let Some(line) = fm.get_line(idx) {
225 buf.push_str(line.as_ref());
229 if let Some(cur_line) = fm.get_line(cur_lo.line - 1) {
230 let end = std::cmp::min(cur_line.len(), cur_lo.col.to_usize());
231 buf.push_str(&cur_line[..end]);
234 buf.push_str(&part.snippet);
235 prev_hi = cm.lookup_char_pos(part.span.hi());
236 prev_line = fm.get_line(prev_hi.line - 1);
238 let only_capitalization = is_case_difference(cm, &buf, bounding_span);
239 // if the replacement already ends with a newline, don't print the next line
240 if !buf.ends_with('\n') {
241 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
243 // remove trailing newlines
244 while buf.ends_with('\n') {
247 (buf, substitution.parts, only_capitalization)
253 pub use rustc_span::fatal_error::{FatalError, FatalErrorMarker};
255 /// Signifies that the compiler died with an explicit call to `.bug`
256 /// or `.span_bug` rather than a failed assertion, etc.
257 #[derive(Copy, Clone, Debug)]
258 pub struct ExplicitBug;
260 impl fmt::Display for ExplicitBug {
261 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
262 write!(f, "parser internal bug")
266 impl error::Error for ExplicitBug {}
268 pub use diagnostic::{Diagnostic, DiagnosticId, DiagnosticStyledString, SubDiagnostic};
269 pub use diagnostic_builder::DiagnosticBuilder;
271 /// A handler deals with errors and other compiler output.
272 /// Certain errors (fatal, bug, unimpl) may cause immediate exit,
273 /// others log errors for later reporting.
276 inner: Lock<HandlerInner>,
279 /// This inner struct exists to keep it all behind a single lock;
280 /// this is done to prevent possible deadlocks in a multi-threaded compiler,
281 /// as well as inconsistent state observation.
282 struct HandlerInner {
284 /// The number of errors that have been emitted, including duplicates.
286 /// This is not necessarily the count that's reported to the user once
287 /// compilation ends.
289 deduplicated_err_count: usize,
290 emitter: Box<dyn Emitter + sync::Send>,
291 delayed_span_bugs: Vec<Diagnostic>,
293 /// This set contains the `DiagnosticId` of all emitted diagnostics to avoid
294 /// emitting the same diagnostic with extended help (`--teach`) twice, which
295 /// would be uneccessary repetition.
296 taught_diagnostics: FxHashSet<DiagnosticId>,
298 /// Used to suggest rustc --explain <error code>
299 emitted_diagnostic_codes: FxHashSet<DiagnosticId>,
301 /// This set contains a hash of every diagnostic that has been emitted by
302 /// this handler. These hashes is used to avoid emitting the same error
304 emitted_diagnostics: FxHashSet<u128>,
306 /// Stashed diagnostics emitted in one stage of the compiler that may be
307 /// stolen by other stages (e.g. to improve them and add more information).
308 /// The stashed diagnostics count towards the total error count.
309 /// When `.abort_if_errors()` is called, these are also emitted.
310 stashed_diagnostics: FxIndexMap<(Span, StashKey), Diagnostic>,
313 /// A key denoting where from a diagnostic was stashed.
314 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
319 fn default_track_diagnostic(_: &Diagnostic) {}
321 pub static TRACK_DIAGNOSTICS: AtomicRef<fn(&Diagnostic)> =
322 AtomicRef::new(&(default_track_diagnostic as fn(&_)));
324 #[derive(Copy, Clone, Default)]
325 pub struct HandlerFlags {
326 /// If false, warning-level lints are suppressed.
327 /// (rustc: see `--allow warnings` and `--cap-lints`)
328 pub can_emit_warnings: bool,
329 /// If true, error-level diagnostics are upgraded to bug-level.
330 /// (rustc: see `-Z treat-err-as-bug`)
331 pub treat_err_as_bug: Option<usize>,
332 /// If true, immediately emit diagnostics that would otherwise be buffered.
333 /// (rustc: see `-Z dont-buffer-diagnostics` and `-Z treat-err-as-bug`)
334 pub dont_buffer_diagnostics: bool,
335 /// If true, immediately print bugs registered with `delay_span_bug`.
336 /// (rustc: see `-Z report-delayed-bugs`)
337 pub report_delayed_bugs: bool,
338 /// show macro backtraces even for non-local macros.
339 /// (rustc: see `-Z external-macro-backtrace`)
340 pub external_macro_backtrace: bool,
341 /// If true, identical diagnostics are reported only once.
342 pub deduplicate_diagnostics: bool,
345 impl Drop for HandlerInner {
347 self.emit_stashed_diagnostics();
349 if !self.has_errors() {
350 let bugs = std::mem::replace(&mut self.delayed_span_bugs, Vec::new());
351 let has_bugs = !bugs.is_empty();
353 self.emit_diagnostic(&bug);
356 panic!("no errors encountered even though `delay_span_bug` issued");
363 pub fn with_tty_emitter(
364 color_config: ColorConfig,
365 can_emit_warnings: bool,
366 treat_err_as_bug: Option<usize>,
367 cm: Option<Lrc<SourceMap>>,
369 Self::with_tty_emitter_and_flags(
372 HandlerFlags { can_emit_warnings, treat_err_as_bug, ..Default::default() },
376 pub fn with_tty_emitter_and_flags(
377 color_config: ColorConfig,
378 cm: Option<Lrc<SourceMap>>,
381 let emitter = Box::new(EmitterWriter::stderr(
387 flags.external_macro_backtrace,
389 Self::with_emitter_and_flags(emitter, flags)
393 can_emit_warnings: bool,
394 treat_err_as_bug: Option<usize>,
395 emitter: Box<dyn Emitter + sync::Send>,
397 Handler::with_emitter_and_flags(
399 HandlerFlags { can_emit_warnings, treat_err_as_bug, ..Default::default() },
403 pub fn with_emitter_and_flags(
404 emitter: Box<dyn Emitter + sync::Send>,
409 inner: Lock::new(HandlerInner {
412 deduplicated_err_count: 0,
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 // This is here to not allow mutation of flags;
424 // as of this writing it's only used in tests in librustc.
425 pub fn can_emit_warnings(&self) -> bool {
426 self.flags.can_emit_warnings
429 /// Resets the diagnostic error count as well as the cached emitted diagnostics.
431 /// NOTE: *do not* call this function from rustc. It is only meant to be called from external
432 /// tools that want to reuse a `Parser` cleaning the previously emitted diagnostics as well as
433 /// the overall count of emitted error diagnostics.
434 pub fn reset_err_count(&self) {
435 let mut inner = self.inner.borrow_mut();
437 inner.deduplicated_err_count = 0;
439 // actually free the underlying memory (which `clear` would not do)
440 inner.delayed_span_bugs = Default::default();
441 inner.taught_diagnostics = Default::default();
442 inner.emitted_diagnostic_codes = Default::default();
443 inner.emitted_diagnostics = Default::default();
444 inner.stashed_diagnostics = Default::default();
447 /// Stash a given diagnostic with the given `Span` and `StashKey` as the key for later stealing.
448 /// If the diagnostic with this `(span, key)` already exists, this will result in an ICE.
449 pub fn stash_diagnostic(&self, span: Span, key: StashKey, diag: Diagnostic) {
450 let mut inner = self.inner.borrow_mut();
451 if let Some(mut old_diag) = inner.stashed_diagnostics.insert((span, key), diag) {
452 // We are removing a previously stashed diagnostic which should not happen.
453 old_diag.level = Bug;
454 old_diag.note(&format!(
455 "{}:{}: already existing stashed diagnostic with (span = {:?}, key = {:?})",
461 inner.emit_diag_at_span(old_diag, span);
466 /// Steal a previously stashed diagnostic with the given `Span` and `StashKey` as the key.
467 pub fn steal_diagnostic(&self, span: Span, key: StashKey) -> Option<DiagnosticBuilder<'_>> {
471 .remove(&(span, key))
472 .map(|diag| DiagnosticBuilder::new_diagnostic(self, diag))
475 /// Emit all stashed diagnostics.
476 pub fn emit_stashed_diagnostics(&self) {
477 self.inner.borrow_mut().emit_stashed_diagnostics();
480 /// Construct a dummy builder with `Level::Cancelled`.
482 /// Using this will neither report anything to the user (e.g. a warning),
483 /// nor will compilation cancel as a result.
484 pub fn struct_dummy(&self) -> DiagnosticBuilder<'_> {
485 DiagnosticBuilder::new(self, Level::Cancelled, "")
488 /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
489 pub fn struct_span_warn(&self, span: impl Into<MultiSpan>, msg: &str) -> DiagnosticBuilder<'_> {
490 let mut result = self.struct_warn(msg);
491 result.set_span(span);
495 /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
496 /// Also include a code.
497 pub fn struct_span_warn_with_code(
499 span: impl Into<MultiSpan>,
502 ) -> DiagnosticBuilder<'_> {
503 let mut result = self.struct_span_warn(span, msg);
508 /// Construct a builder at the `Warning` level with the `msg`.
509 pub fn struct_warn(&self, msg: &str) -> DiagnosticBuilder<'_> {
510 let mut result = DiagnosticBuilder::new(self, Level::Warning, msg);
511 if !self.flags.can_emit_warnings {
517 /// Construct a builder at the `Error` level at the given `span` and with the `msg`.
518 pub fn struct_span_err(&self, span: impl Into<MultiSpan>, msg: &str) -> DiagnosticBuilder<'_> {
519 let mut result = self.struct_err(msg);
520 result.set_span(span);
524 /// Construct a builder at the `Error` level at the given `span`, with the `msg`, and `code`.
525 pub fn struct_span_err_with_code(
527 span: impl Into<MultiSpan>,
530 ) -> DiagnosticBuilder<'_> {
531 let mut result = self.struct_span_err(span, msg);
536 /// Construct a builder at the `Error` level with the `msg`.
537 // FIXME: This method should be removed (every error should have an associated error code).
538 pub fn struct_err(&self, msg: &str) -> DiagnosticBuilder<'_> {
539 DiagnosticBuilder::new(self, Level::Error, msg)
542 /// Construct a builder at the `Error` level with the `msg` and the `code`.
543 pub fn struct_err_with_code(&self, msg: &str, code: DiagnosticId) -> DiagnosticBuilder<'_> {
544 let mut result = self.struct_err(msg);
549 /// Construct a builder at the `Fatal` level at the given `span` and with the `msg`.
550 pub fn struct_span_fatal(
552 span: impl Into<MultiSpan>,
554 ) -> DiagnosticBuilder<'_> {
555 let mut result = self.struct_fatal(msg);
556 result.set_span(span);
560 /// Construct a builder at the `Fatal` level at the given `span`, with the `msg`, and `code`.
561 pub fn struct_span_fatal_with_code(
563 span: impl Into<MultiSpan>,
566 ) -> DiagnosticBuilder<'_> {
567 let mut result = self.struct_span_fatal(span, msg);
572 /// Construct a builder at the `Error` level with the `msg`.
573 pub fn struct_fatal(&self, msg: &str) -> DiagnosticBuilder<'_> {
574 DiagnosticBuilder::new(self, Level::Fatal, msg)
577 /// Construct a builder at the `Help` level with the `msg`.
578 pub fn struct_help(&self, msg: &str) -> DiagnosticBuilder<'_> {
579 DiagnosticBuilder::new(self, Level::Help, msg)
582 pub fn span_fatal(&self, span: impl Into<MultiSpan>, msg: &str) -> FatalError {
583 self.emit_diag_at_span(Diagnostic::new(Fatal, msg), span);
587 pub fn span_fatal_with_code(
589 span: impl Into<MultiSpan>,
593 self.emit_diag_at_span(Diagnostic::new_with_code(Fatal, Some(code), msg), span);
597 pub fn span_err(&self, span: impl Into<MultiSpan>, msg: &str) {
598 self.emit_diag_at_span(Diagnostic::new(Error, msg), span);
601 pub fn span_err_with_code(&self, span: impl Into<MultiSpan>, msg: &str, code: DiagnosticId) {
602 self.emit_diag_at_span(Diagnostic::new_with_code(Error, Some(code), msg), span);
605 pub fn span_warn(&self, span: impl Into<MultiSpan>, msg: &str) {
606 self.emit_diag_at_span(Diagnostic::new(Warning, msg), span);
609 pub fn span_warn_with_code(&self, span: impl Into<MultiSpan>, msg: &str, code: DiagnosticId) {
610 self.emit_diag_at_span(Diagnostic::new_with_code(Warning, Some(code), msg), span);
613 pub fn span_bug(&self, span: impl Into<MultiSpan>, msg: &str) -> ! {
614 self.inner.borrow_mut().span_bug(span, msg)
617 pub fn delay_span_bug(&self, span: impl Into<MultiSpan>, msg: &str) {
618 self.inner.borrow_mut().delay_span_bug(span, msg)
621 pub fn span_bug_no_panic(&self, span: impl Into<MultiSpan>, msg: &str) {
622 self.emit_diag_at_span(Diagnostic::new(Bug, msg), span);
625 pub fn span_note_without_error(&self, span: impl Into<MultiSpan>, msg: &str) {
626 self.emit_diag_at_span(Diagnostic::new(Note, msg), span);
629 pub fn span_note_diag(&self, span: Span, msg: &str) -> DiagnosticBuilder<'_> {
630 let mut db = DiagnosticBuilder::new(self, Note, msg);
635 pub fn failure(&self, msg: &str) {
636 self.inner.borrow_mut().failure(msg);
639 pub fn fatal(&self, msg: &str) -> FatalError {
640 self.inner.borrow_mut().fatal(msg)
643 pub fn err(&self, msg: &str) {
644 self.inner.borrow_mut().err(msg);
647 pub fn warn(&self, msg: &str) {
648 let mut db = DiagnosticBuilder::new(self, Warning, msg);
652 pub fn note_without_error(&self, msg: &str) {
653 DiagnosticBuilder::new(self, Note, msg).emit();
656 pub fn bug(&self, msg: &str) -> ! {
657 self.inner.borrow_mut().bug(msg)
660 pub fn err_count(&self) -> usize {
661 self.inner.borrow().err_count()
664 pub fn has_errors(&self) -> bool {
665 self.inner.borrow().has_errors()
667 pub fn has_errors_or_delayed_span_bugs(&self) -> bool {
668 self.inner.borrow().has_errors_or_delayed_span_bugs()
671 pub fn print_error_count(&self, registry: &Registry) {
672 self.inner.borrow_mut().print_error_count(registry)
675 pub fn abort_if_errors(&self) {
676 self.inner.borrow_mut().abort_if_errors()
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));
701 pub fn emit_artifact_notification(&self, path: &Path, artifact_type: &str) {
702 self.inner.borrow_mut().emit_artifact_notification(path, artifact_type)
705 pub fn delay_as_bug(&self, diagnostic: Diagnostic) {
706 self.inner.borrow_mut().delay_as_bug(diagnostic)
711 fn must_teach(&mut self, code: &DiagnosticId) -> bool {
712 self.taught_diagnostics.insert(code.clone())
715 fn force_print_diagnostic(&mut self, db: Diagnostic) {
716 self.emitter.emit_diagnostic(&db);
719 /// Emit all stashed diagnostics.
720 fn emit_stashed_diagnostics(&mut self) {
721 let diags = self.stashed_diagnostics.drain(..).map(|x| x.1).collect::<Vec<_>>();
722 diags.iter().for_each(|diag| self.emit_diagnostic(diag));
725 fn emit_diagnostic(&mut self, diagnostic: &Diagnostic) {
726 if diagnostic.cancelled() {
730 if diagnostic.level == Warning && !self.flags.can_emit_warnings {
734 (*TRACK_DIAGNOSTICS)(diagnostic);
736 if let Some(ref code) = diagnostic.code {
737 self.emitted_diagnostic_codes.insert(code.clone());
740 let already_emitted = |this: &mut Self| {
742 let mut hasher = StableHasher::new();
743 diagnostic.hash(&mut hasher);
744 let diagnostic_hash = hasher.finish();
745 !this.emitted_diagnostics.insert(diagnostic_hash)
748 // Only emit the diagnostic if we've been asked to deduplicate and
749 // haven't already emitted an equivalent diagnostic.
750 if !(self.flags.deduplicate_diagnostics && already_emitted(self)) {
751 self.emitter.emit_diagnostic(diagnostic);
752 if diagnostic.is_error() {
753 self.deduplicated_err_count += 1;
756 if diagnostic.is_error() {
757 self.bump_err_count();
761 fn emit_artifact_notification(&mut self, path: &Path, artifact_type: &str) {
762 self.emitter.emit_artifact_notification(path, artifact_type);
765 fn treat_err_as_bug(&self) -> bool {
766 self.flags.treat_err_as_bug.map(|c| self.err_count() >= c).unwrap_or(false)
769 fn print_error_count(&mut self, registry: &Registry) {
770 self.emit_stashed_diagnostics();
772 let s = match self.deduplicated_err_count {
774 1 => "aborting due to previous error".to_string(),
775 count => format!("aborting due to {} previous errors", count),
777 if self.treat_err_as_bug() {
781 let _ = self.fatal(&s);
783 let can_show_explain = self.emitter.should_show_explain();
784 let are_there_diagnostics = !self.emitted_diagnostic_codes.is_empty();
785 if can_show_explain && are_there_diagnostics {
786 let mut error_codes = self
787 .emitted_diagnostic_codes
789 .filter_map(|x| match &x {
790 DiagnosticId::Error(s) if registry.find_description(s).is_some() => {
795 .collect::<Vec<_>>();
796 if !error_codes.is_empty() {
798 if error_codes.len() > 1 {
799 let limit = if error_codes.len() > 9 { 9 } else { error_codes.len() };
800 self.failure(&format!(
801 "Some errors have detailed explanations: {}{}",
802 error_codes[..limit].join(", "),
803 if error_codes.len() > 9 { "..." } else { "." }
805 self.failure(&format!(
806 "For more information about an error, try \
807 `rustc --explain {}`.",
811 self.failure(&format!(
812 "For more information about this error, try \
813 `rustc --explain {}`.",
821 fn err_count(&self) -> usize {
822 self.err_count + self.stashed_diagnostics.len()
825 fn has_errors(&self) -> bool {
828 fn has_errors_or_delayed_span_bugs(&self) -> bool {
829 self.has_errors() || !self.delayed_span_bugs.is_empty()
832 fn abort_if_errors(&mut self) {
833 self.emit_stashed_diagnostics();
835 if self.has_errors() {
840 fn span_bug(&mut self, sp: impl Into<MultiSpan>, msg: &str) -> ! {
841 self.emit_diag_at_span(Diagnostic::new(Bug, msg), sp);
845 fn emit_diag_at_span(&mut self, mut diag: Diagnostic, sp: impl Into<MultiSpan>) {
846 self.emit_diagnostic(diag.set_span(sp));
849 fn delay_span_bug(&mut self, sp: impl Into<MultiSpan>, msg: &str) {
850 if self.treat_err_as_bug() {
851 // FIXME: don't abort here if report_delayed_bugs is off
852 self.span_bug(sp, msg);
854 let mut diagnostic = Diagnostic::new(Level::Bug, msg);
855 diagnostic.set_span(sp.into());
856 self.delay_as_bug(diagnostic)
859 fn failure(&mut self, msg: &str) {
860 self.emit_diagnostic(&Diagnostic::new(FailureNote, msg));
863 fn fatal(&mut self, msg: &str) -> FatalError {
864 self.emit_error(Fatal, msg);
868 fn err(&mut self, msg: &str) {
869 self.emit_error(Error, msg);
872 /// Emit an error; level should be `Error` or `Fatal`.
873 fn emit_error(&mut self, level: Level, msg: &str) {
874 if self.treat_err_as_bug() {
877 self.emit_diagnostic(&Diagnostic::new(level, msg));
880 fn bug(&mut self, msg: &str) -> ! {
881 self.emit_diagnostic(&Diagnostic::new(Bug, msg));
885 fn delay_as_bug(&mut self, diagnostic: Diagnostic) {
886 if self.flags.report_delayed_bugs {
887 self.emit_diagnostic(&diagnostic);
889 self.delayed_span_bugs.push(diagnostic);
892 fn bump_err_count(&mut self) {
894 self.panic_if_treat_err_as_bug();
897 fn panic_if_treat_err_as_bug(&self) {
898 if self.treat_err_as_bug() {
899 let s = match (self.err_count(), self.flags.treat_err_as_bug.unwrap_or(0)) {
901 (1, 1) => "aborting due to `-Z treat-err-as-bug=1`".to_string(),
903 (count, as_bug) => format!(
904 "aborting after {} errors due to `-Z treat-err-as-bug={}`",
913 #[derive(Copy, PartialEq, Clone, Hash, Debug, RustcEncodable, RustcDecodable)]
925 impl fmt::Display for Level {
926 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
932 fn color(self) -> ColorSpec {
933 let mut spec = ColorSpec::new();
935 Bug | Fatal | Error => {
936 spec.set_fg(Some(Color::Red)).set_intense(true);
939 spec.set_fg(Some(Color::Yellow)).set_intense(cfg!(windows));
942 spec.set_fg(Some(Color::Green)).set_intense(true);
945 spec.set_fg(Some(Color::Cyan)).set_intense(true);
948 Cancelled => unreachable!(),
953 pub fn to_str(self) -> &'static str {
955 Bug => "error: internal compiler error",
956 Fatal | Error => "error",
957 Warning => "warning",
960 FailureNote => "failure-note",
961 Cancelled => panic!("Shouldn't call on cancelled error"),
965 pub fn is_failure_note(&self) -> bool {
974 macro_rules! pluralize {
976 if $x != 1 { "s" } else { "" }
980 // Useful type to use with `Result<>` indicate that an error has already
981 // been reported to the user, so no need to continue checking.
982 #[derive(Clone, Copy, Debug, RustcEncodable, RustcDecodable, Hash, PartialEq, Eq)]
983 pub struct ErrorReported;
985 rustc_data_structures::impl_stable_hash_via_hash!(ErrorReported);