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;
42 pub type PResult<'a, T> = Result<T, DiagnosticBuilder<'a>>;
44 // `PResult` is used a lot. Make sure it doesn't unintentionally get bigger.
45 // (See also the comment on `DiagnosticBuilderInner`.)
46 #[cfg(target_arch = "x86_64")]
47 rustc_data_structures::static_assert_size!(PResult<'_, bool>, 16);
49 /// Indicates the confidence in the correctness of a suggestion.
51 /// All suggestions are marked with an `Applicability`. Tools use the applicability of a suggestion
52 /// to determine whether it should be automatically applied or if the user should be consulted
53 /// before applying the suggestion.
54 #[derive(Copy, Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
55 pub enum Applicability {
56 /// The suggestion is definitely what the user intended. This suggestion should be
57 /// automatically applied.
60 /// The suggestion may be what the user intended, but it is uncertain. The suggestion should
61 /// result in valid Rust code if it is applied.
64 /// The suggestion contains placeholders like `(...)` or `{ /* fields */ }`. The suggestion
65 /// cannot be applied automatically because it will not result in valid Rust code. The user
66 /// will need to fill in the placeholders.
69 /// The applicability of the suggestion is unknown.
73 #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, RustcEncodable, RustcDecodable)]
74 pub enum SuggestionStyle {
75 /// Hide the suggested code when displaying this suggestion inline.
77 /// Always hide the suggested code but display the message.
79 /// Do not display this suggestion in the cli output, it is only meant for tools.
81 /// Always show the suggested code.
82 /// This will *not* show the code if the suggestion is inline *and* the suggested code is
85 /// Always show the suggested code independently.
89 impl SuggestionStyle {
90 fn hide_inline(&self) -> bool {
92 SuggestionStyle::ShowCode => false,
98 #[derive(Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
99 pub struct CodeSuggestion {
100 /// Each substitute can have multiple variants due to multiple
101 /// applicable suggestions
103 /// `foo.bar` might be replaced with `a.b` or `x.y` by replacing
104 /// `foo` and `bar` on their own:
108 /// Substitution { parts: vec![(0..3, "a"), (4..7, "b")] },
109 /// Substitution { parts: vec![(0..3, "x"), (4..7, "y")] },
113 /// or by replacing the entire span:
117 /// Substitution { parts: vec![(0..7, "a.b")] },
118 /// Substitution { parts: vec![(0..7, "x.y")] },
121 pub substitutions: Vec<Substitution>,
123 /// Visual representation of this suggestion.
124 pub style: SuggestionStyle,
125 /// Whether or not the suggestion is approximate
127 /// Sometimes we may show suggestions with placeholders,
128 /// which are useful for users but not useful for
129 /// tools like rustfix
130 pub applicability: Applicability,
133 #[derive(Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
134 /// See the docs on `CodeSuggestion::substitutions`
135 pub struct Substitution {
136 pub parts: Vec<SubstitutionPart>,
139 #[derive(Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
140 pub struct SubstitutionPart {
145 impl CodeSuggestion {
146 /// Returns the assembled code suggestions, whether they should be shown with an underline
147 /// and whether the substitution only differs in capitalization.
151 ) -> Vec<(String, Vec<SubstitutionPart>, bool)> {
152 use syntax_pos::{CharPos, Pos};
154 fn push_trailing(buf: &mut String,
155 line_opt: Option<&Cow<'_, str>>,
157 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());
176 self.substitutions.iter().cloned().map(|mut substitution| {
177 // Assumption: all spans are in the same file, and all spans
178 // are disjoint. Sort in ascending order.
179 substitution.parts.sort_by_key(|part| part.span.lo());
181 // Find the bounding span.
182 let lo = substitution.parts.iter().map(|part| part.span.lo()).min().unwrap();
183 let hi = substitution.parts.iter().map(|part| part.span.hi()).min().unwrap();
184 let bounding_span = Span::with_root_ctxt(lo, hi);
185 let lines = cm.span_to_lines(bounding_span).unwrap();
186 assert!(!lines.lines.is_empty());
188 // To build up the result, we do this for each span:
189 // - push the line segment trailing the previous span
190 // (at the beginning a "phantom" span pointing at the start of the line)
191 // - push lines between the previous and current span (if any)
192 // - if the previous and current span are not on the same line
193 // push the line segment leading up to the current span
194 // - splice in the span substitution
196 // Finally push the trailing line segment of the last span
197 let fm = &lines.file;
198 let mut prev_hi = cm.lookup_char_pos(bounding_span.lo());
199 prev_hi.col = CharPos::from_usize(0);
201 let mut prev_line = fm.get_line(lines.lines[0].line_index);
202 let mut buf = String::new();
204 for part in &substitution.parts {
205 let cur_lo = cm.lookup_char_pos(part.span.lo());
206 if prev_hi.line == cur_lo.line {
207 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, Some(&cur_lo));
209 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
210 // push lines between the previous and current span (if any)
211 for idx in prev_hi.line..(cur_lo.line - 1) {
212 if let Some(line) = fm.get_line(idx) {
213 buf.push_str(line.as_ref());
217 if let Some(cur_line) = fm.get_line(cur_lo.line - 1) {
218 let end = std::cmp::min(cur_line.len(), cur_lo.col.to_usize());
219 buf.push_str(&cur_line[..end]);
222 buf.push_str(&part.snippet);
223 prev_hi = cm.lookup_char_pos(part.span.hi());
224 prev_line = fm.get_line(prev_hi.line - 1);
226 let only_capitalization = is_case_difference(cm, &buf, bounding_span);
227 // if the replacement already ends with a newline, don't print the next line
228 if !buf.ends_with('\n') {
229 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
231 // remove trailing newlines
232 while buf.ends_with('\n') {
235 (buf, substitution.parts, only_capitalization)
240 pub use syntax_pos::fatal_error::{FatalError, FatalErrorMarker};
242 /// Signifies that the compiler died with an explicit call to `.bug`
243 /// or `.span_bug` rather than a failed assertion, etc.
244 #[derive(Copy, Clone, Debug)]
245 pub struct ExplicitBug;
247 impl fmt::Display for ExplicitBug {
248 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
249 write!(f, "parser internal bug")
253 impl error::Error for ExplicitBug {
254 fn description(&self) -> &str {
255 "The parser has encountered an internal bug"
259 pub use diagnostic::{Diagnostic, SubDiagnostic, DiagnosticStyledString, DiagnosticId};
260 pub use diagnostic_builder::DiagnosticBuilder;
262 /// A handler deals with errors and other compiler output.
263 /// Certain errors (fatal, bug, unimpl) may cause immediate exit,
264 /// others log errors for later reporting.
267 inner: Lock<HandlerInner>,
270 /// This inner struct exists to keep it all behind a single lock;
271 /// this is done to prevent possible deadlocks in a multi-threaded compiler,
272 /// as well as inconsistent state observation.
273 struct HandlerInner {
275 /// The number of errors that have been emitted, including duplicates.
277 /// This is not necessarily the count that's reported to the user once
278 /// compilation ends.
280 deduplicated_err_count: usize,
281 emitter: Box<dyn Emitter + sync::Send>,
282 continue_after_error: bool,
283 delayed_span_bugs: Vec<Diagnostic>,
285 /// This set contains the `DiagnosticId` of all emitted diagnostics to avoid
286 /// emitting the same diagnostic with extended help (`--teach`) twice, which
287 /// would be uneccessary repetition.
288 taught_diagnostics: FxHashSet<DiagnosticId>,
290 /// Used to suggest rustc --explain <error code>
291 emitted_diagnostic_codes: FxHashSet<DiagnosticId>,
293 /// This set contains a hash of every diagnostic that has been emitted by
294 /// this handler. These hashes is used to avoid emitting the same error
296 emitted_diagnostics: FxHashSet<u128>,
298 /// Stashed diagnostics emitted in one stage of the compiler that may be
299 /// stolen by other stages (e.g. to improve them and add more information).
300 /// The stashed diagnostics count towards the total error count.
301 /// When `.abort_if_errors()` is called, these are also emitted.
302 stashed_diagnostics: FxIndexMap<(Span, StashKey), Diagnostic>,
305 /// A key denoting where from a diagnostic was stashed.
306 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
311 fn default_track_diagnostic(_: &Diagnostic) {}
313 thread_local!(pub static TRACK_DIAGNOSTICS: Cell<fn(&Diagnostic)> =
314 Cell::new(default_track_diagnostic));
316 #[derive(Copy, Clone, Default)]
317 pub struct HandlerFlags {
318 /// If false, warning-level lints are suppressed.
319 /// (rustc: see `--allow warnings` and `--cap-lints`)
320 pub can_emit_warnings: bool,
321 /// If true, error-level diagnostics are upgraded to bug-level.
322 /// (rustc: see `-Z treat-err-as-bug`)
323 pub treat_err_as_bug: Option<usize>,
324 /// If true, immediately emit diagnostics that would otherwise be buffered.
325 /// (rustc: see `-Z dont-buffer-diagnostics` and `-Z treat-err-as-bug`)
326 pub dont_buffer_diagnostics: bool,
327 /// If true, immediately print bugs registered with `delay_span_bug`.
328 /// (rustc: see `-Z report-delayed-bugs`)
329 pub report_delayed_bugs: bool,
330 /// show macro backtraces even for non-local macros.
331 /// (rustc: see `-Z external-macro-backtrace`)
332 pub external_macro_backtrace: bool,
335 impl Drop for HandlerInner {
337 self.emit_stashed_diagnostics();
339 if !self.has_errors() {
340 let bugs = std::mem::replace(&mut self.delayed_span_bugs, Vec::new());
341 let has_bugs = !bugs.is_empty();
343 self.emit_diagnostic(&bug);
346 panic!("no errors encountered even though `delay_span_bug` issued");
353 pub fn with_tty_emitter(
354 color_config: ColorConfig,
355 can_emit_warnings: bool,
356 treat_err_as_bug: Option<usize>,
357 cm: Option<Lrc<SourceMap>>,
359 Self::with_tty_emitter_and_flags(
365 .. Default::default()
370 pub fn with_tty_emitter_and_flags(
371 color_config: ColorConfig,
372 cm: Option<Lrc<SourceMap>>,
375 let emitter = Box::new(EmitterWriter::stderr(
381 flags.external_macro_backtrace,
383 Self::with_emitter_and_flags(emitter, flags)
387 can_emit_warnings: bool,
388 treat_err_as_bug: Option<usize>,
389 emitter: Box<dyn Emitter + sync::Send>,
391 Handler::with_emitter_and_flags(
396 .. Default::default()
401 pub fn with_emitter_and_flags(
402 emitter: Box<dyn Emitter + sync::Send>,
407 inner: Lock::new(HandlerInner {
410 deduplicated_err_count: 0,
412 continue_after_error: true,
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 pub fn set_continue_after_error(&self, continue_after_error: bool) {
423 self.inner.borrow_mut().continue_after_error = continue_after_error;
426 // This is here to not allow mutation of flags;
427 // as of this writing it's only used in tests in librustc.
428 pub fn can_emit_warnings(&self) -> bool {
429 self.flags.can_emit_warnings
432 /// Resets the diagnostic error count as well as the cached emitted diagnostics.
434 /// NOTE: *do not* call this function from rustc. It is only meant to be called from external
435 /// tools that want to reuse a `Parser` cleaning the previously emitted diagnostics as well as
436 /// the overall count of emitted error diagnostics.
437 pub fn reset_err_count(&self) {
438 let mut inner = self.inner.borrow_mut();
440 inner.deduplicated_err_count = 0;
442 // actually free the underlying memory (which `clear` would not do)
443 inner.delayed_span_bugs = Default::default();
444 inner.taught_diagnostics = Default::default();
445 inner.emitted_diagnostic_codes = Default::default();
446 inner.emitted_diagnostics = Default::default();
447 inner.stashed_diagnostics = Default::default();
450 /// Stash a given diagnostic with the given `Span` and `StashKey` as the key for later stealing.
451 /// If the diagnostic with this `(span, key)` already exists, this will result in an ICE.
452 pub fn stash_diagnostic(&self, span: Span, key: StashKey, diag: Diagnostic) {
453 let mut inner = self.inner.borrow_mut();
454 if let Some(mut old_diag) = inner.stashed_diagnostics.insert((span, key), diag) {
455 // We are removing a previously stashed diagnostic which should not happen.
456 old_diag.level = Bug;
457 old_diag.note(&format!(
458 "{}:{}: already existing stashed diagnostic with (span = {:?}, key = {:?})",
459 file!(), line!(), 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 pub fn span_fatal(&self, span: impl Into<MultiSpan>, msg: &str) -> FatalError {
578 self.emit_diag_at_span(Diagnostic::new(Fatal, msg), span);
582 pub fn span_fatal_with_code(
584 span: impl Into<MultiSpan>,
588 self.emit_diag_at_span(Diagnostic::new_with_code(Fatal, Some(code), msg), span);
592 pub fn span_err(&self, span: impl Into<MultiSpan>, msg: &str) {
593 self.emit_diag_at_span(Diagnostic::new(Error, msg), span);
596 pub fn span_err_with_code(&self, span: impl Into<MultiSpan>, msg: &str, code: DiagnosticId) {
597 self.emit_diag_at_span(Diagnostic::new_with_code(Error, Some(code), msg), span);
600 pub fn span_warn(&self, span: impl Into<MultiSpan>, msg: &str) {
601 self.emit_diag_at_span(Diagnostic::new(Warning, msg), span);
604 pub fn span_warn_with_code(&self, span: impl Into<MultiSpan>, msg: &str, code: DiagnosticId) {
605 self.emit_diag_at_span(Diagnostic::new_with_code(Warning, Some(code), msg), span);
608 pub fn span_bug(&self, span: impl Into<MultiSpan>, msg: &str) -> ! {
609 self.inner.borrow_mut().span_bug(span, msg)
612 pub fn delay_span_bug(&self, span: impl Into<MultiSpan>, msg: &str) {
613 self.inner.borrow_mut().delay_span_bug(span, msg)
616 pub fn span_bug_no_panic(&self, span: impl Into<MultiSpan>, msg: &str) {
617 self.emit_diag_at_span(Diagnostic::new(Bug, msg), span);
620 pub fn span_note_without_error(&self, span: impl Into<MultiSpan>, msg: &str) {
621 self.emit_diag_at_span(Diagnostic::new(Note, msg), span);
624 pub fn span_note_diag(&self, span: Span, msg: &str) -> DiagnosticBuilder<'_> {
625 let mut db = DiagnosticBuilder::new(self, Note, msg);
630 pub fn failure(&self, msg: &str) {
631 self.inner.borrow_mut().failure(msg);
634 pub fn fatal(&self, msg: &str) -> FatalError {
635 self.inner.borrow_mut().fatal(msg)
638 pub fn err(&self, msg: &str) {
639 self.inner.borrow_mut().err(msg);
642 pub fn warn(&self, msg: &str) {
643 let mut db = DiagnosticBuilder::new(self, Warning, msg);
647 pub fn note_without_error(&self, msg: &str) {
648 DiagnosticBuilder::new(self, Note, msg).emit();
651 pub fn bug(&self, msg: &str) -> ! {
652 self.inner.borrow_mut().bug(msg)
655 pub fn err_count(&self) -> usize {
656 self.inner.borrow().err_count()
659 pub fn has_errors(&self) -> bool {
660 self.inner.borrow().has_errors()
662 pub fn has_errors_or_delayed_span_bugs(&self) -> bool {
663 self.inner.borrow().has_errors_or_delayed_span_bugs()
666 pub fn print_error_count(&self, registry: &Registry) {
667 self.inner.borrow_mut().print_error_count(registry)
670 pub fn abort_if_errors(&self) {
671 self.inner.borrow_mut().abort_if_errors()
674 pub fn abort_if_errors_and_should_abort(&self) {
675 self.inner.borrow_mut().abort_if_errors_and_should_abort()
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));
698 inner.abort_if_errors_and_should_abort();
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.with(|track_diagnostics| {
735 track_diagnostics.get()(diagnostic);
738 if let Some(ref code) = diagnostic.code {
739 self.emitted_diagnostic_codes.insert(code.clone());
742 let diagnostic_hash = {
744 let mut hasher = StableHasher::new();
745 diagnostic.hash(&mut hasher);
749 // Only emit the diagnostic if we haven't already emitted an equivalent
751 if self.emitted_diagnostics.insert(diagnostic_hash) {
752 self.emitter.emit_diagnostic(diagnostic);
753 if diagnostic.is_error() {
754 self.deduplicated_err_count += 1;
757 if diagnostic.is_error() {
758 self.bump_err_count();
762 fn emit_artifact_notification(&mut self, path: &Path, artifact_type: &str) {
763 self.emitter.emit_artifact_notification(path, artifact_type);
766 fn treat_err_as_bug(&self) -> bool {
767 self.flags.treat_err_as_bug.map(|c| self.err_count() >= c).unwrap_or(false)
770 fn print_error_count(&mut self, registry: &Registry) {
771 self.emit_stashed_diagnostics();
773 let s = match self.deduplicated_err_count {
775 1 => "aborting due to previous error".to_string(),
776 count => format!("aborting due to {} previous errors", count)
778 if self.treat_err_as_bug() {
782 let _ = self.fatal(&s);
784 let can_show_explain = self.emitter.should_show_explain();
785 let are_there_diagnostics = !self.emitted_diagnostic_codes.is_empty();
786 if can_show_explain && are_there_diagnostics {
787 let mut error_codes = self
788 .emitted_diagnostic_codes
790 .filter_map(|x| match &x {
791 DiagnosticId::Error(s) if registry.find_description(s).is_some() => {
796 .collect::<Vec<_>>();
797 if !error_codes.is_empty() {
799 if error_codes.len() > 1 {
800 let limit = if error_codes.len() > 9 { 9 } else { error_codes.len() };
801 self.failure(&format!("Some errors have detailed explanations: {}{}",
802 error_codes[..limit].join(", "),
803 if error_codes.len() > 9 { "..." } else { "." }));
804 self.failure(&format!("For more information about an error, try \
805 `rustc --explain {}`.",
808 self.failure(&format!("For more information about this error, try \
809 `rustc --explain {}`.",
816 fn err_count(&self) -> usize {
817 self.err_count + self.stashed_diagnostics.len()
820 fn has_errors(&self) -> bool {
823 fn has_errors_or_delayed_span_bugs(&self) -> bool {
824 self.has_errors() || !self.delayed_span_bugs.is_empty()
827 fn abort_if_errors_and_should_abort(&mut self) {
828 self.emit_stashed_diagnostics();
830 if self.has_errors() && !self.continue_after_error {
835 fn abort_if_errors(&mut self) {
836 self.emit_stashed_diagnostics();
838 if self.has_errors() {
843 fn span_bug(&mut self, sp: impl Into<MultiSpan>, msg: &str) -> ! {
844 self.emit_diag_at_span(Diagnostic::new(Bug, msg), sp);
848 fn emit_diag_at_span(&mut self, mut diag: Diagnostic, sp: impl Into<MultiSpan>) {
849 self.emit_diagnostic(diag.set_span(sp));
850 self.abort_if_errors_and_should_abort();
853 fn delay_span_bug(&mut self, sp: impl Into<MultiSpan>, msg: &str) {
854 if self.treat_err_as_bug() {
855 // FIXME: don't abort here if report_delayed_bugs is off
856 self.span_bug(sp, msg);
858 let mut diagnostic = Diagnostic::new(Level::Bug, msg);
859 diagnostic.set_span(sp.into());
860 self.delay_as_bug(diagnostic)
863 fn failure(&mut self, msg: &str) {
864 self.emit_diagnostic(&Diagnostic::new(FailureNote, msg));
867 fn fatal(&mut self, msg: &str) -> FatalError {
868 self.emit_error(Fatal, msg);
872 fn err(&mut self, msg: &str) {
873 self.emit_error(Error, msg);
876 /// Emit an error; level should be `Error` or `Fatal`.
877 fn emit_error(&mut self, level: Level, msg: &str,) {
878 if self.treat_err_as_bug() {
881 self.emit_diagnostic(&Diagnostic::new(level, msg));
884 fn bug(&mut self, msg: &str) -> ! {
885 self.emit_diagnostic(&Diagnostic::new(Bug, msg));
889 fn delay_as_bug(&mut self, diagnostic: Diagnostic) {
890 if self.flags.report_delayed_bugs {
891 self.emit_diagnostic(&diagnostic);
893 self.delayed_span_bugs.push(diagnostic);
896 fn bump_err_count(&mut self) {
898 self.panic_if_treat_err_as_bug();
901 fn panic_if_treat_err_as_bug(&self) {
902 if self.treat_err_as_bug() {
903 let s = match (self.err_count(), self.flags.treat_err_as_bug.unwrap_or(0)) {
905 (1, 1) => "aborting due to `-Z treat-err-as-bug=1`".to_string(),
909 "aborting after {} errors due to `-Z treat-err-as-bug={}`",
920 #[derive(Copy, PartialEq, Clone, Hash, Debug, RustcEncodable, RustcDecodable)]
932 impl fmt::Display for Level {
933 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
939 fn color(self) -> ColorSpec {
940 let mut spec = ColorSpec::new();
942 Bug | Fatal | Error => {
943 spec.set_fg(Some(Color::Red))
947 spec.set_fg(Some(Color::Yellow))
948 .set_intense(cfg!(windows));
951 spec.set_fg(Some(Color::Green))
955 spec.set_fg(Some(Color::Cyan))
959 Cancelled => unreachable!(),
964 pub fn to_str(self) -> &'static str {
966 Bug => "error: internal compiler error",
967 Fatal | Error => "error",
968 Warning => "warning",
971 FailureNote => "failure-note",
972 Cancelled => panic!("Shouldn't call on cancelled error"),
976 pub fn is_failure_note(&self) -> bool {
985 macro_rules! pluralize {
987 if $x != 1 { "s" } else { "" }