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)]
11 extern crate rustc_macros;
13 pub use emitter::ColorConfig;
18 use emitter::{is_case_difference, Emitter, EmitterWriter};
19 use registry::Registry;
20 use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
21 use rustc_data_structures::stable_hasher::StableHasher;
22 use rustc_data_structures::sync::{self, Lock, Lrc};
23 use rustc_data_structures::AtomicRef;
24 use rustc_span::source_map::SourceMap;
25 use rustc_span::{Loc, MultiSpan, Span};
30 use std::{error, fmt};
32 use termcolor::{Color, ColorSpec};
34 pub mod annotate_snippet_emitter_writer;
36 mod diagnostic_builder;
43 pub use snippet::Style;
45 pub type PResult<'a, T> = Result<T, DiagnosticBuilder<'a>>;
47 // `PResult` is used a lot. Make sure it doesn't unintentionally get bigger.
48 // (See also the comment on `DiagnosticBuilderInner`.)
49 #[cfg(target_arch = "x86_64")]
50 rustc_data_structures::static_assert_size!(PResult<'_, bool>, 16);
52 /// Indicates the confidence in the correctness of a suggestion.
54 /// All suggestions are marked with an `Applicability`. Tools use the applicability of a suggestion
55 /// to determine whether it should be automatically applied or if the user should be consulted
56 /// before applying the suggestion.
57 #[derive(Copy, Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
58 pub enum Applicability {
59 /// The suggestion is definitely what the user intended. This suggestion should be
60 /// automatically applied.
63 /// The suggestion may be what the user intended, but it is uncertain. The suggestion should
64 /// result in valid Rust code if it is applied.
67 /// The suggestion contains placeholders like `(...)` or `{ /* fields */ }`. The suggestion
68 /// cannot be applied automatically because it will not result in valid Rust code. The user
69 /// will need to fill in the placeholders.
72 /// The applicability of the suggestion is unknown.
76 #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, Encodable, Decodable)]
77 pub enum SuggestionStyle {
78 /// Hide the suggested code when displaying this suggestion inline.
80 /// Always hide the suggested code but display the message.
82 /// Do not display this suggestion in the cli output, it is only meant for tools.
84 /// Always show the suggested code.
85 /// This will *not* show the code if the suggestion is inline *and* the suggested code is
88 /// Always show the suggested code independently.
92 impl SuggestionStyle {
93 fn hide_inline(&self) -> bool {
95 SuggestionStyle::ShowCode => false,
101 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
102 pub struct CodeSuggestion {
103 /// Each substitute can have multiple variants due to multiple
104 /// applicable suggestions
106 /// `foo.bar` might be replaced with `a.b` or `x.y` by replacing
107 /// `foo` and `bar` on their own:
111 /// Substitution { parts: vec![(0..3, "a"), (4..7, "b")] },
112 /// Substitution { parts: vec![(0..3, "x"), (4..7, "y")] },
116 /// or by replacing the entire span:
120 /// Substitution { parts: vec![(0..7, "a.b")] },
121 /// Substitution { parts: vec![(0..7, "x.y")] },
124 pub substitutions: Vec<Substitution>,
126 /// Visual representation of this suggestion.
127 pub style: SuggestionStyle,
128 /// Whether or not the suggestion is approximate
130 /// Sometimes we may show suggestions with placeholders,
131 /// which are useful for users but not useful for
132 /// tools like rustfix
133 pub applicability: Applicability,
136 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
137 /// See the docs on `CodeSuggestion::substitutions`
138 pub struct Substitution {
139 pub parts: Vec<SubstitutionPart>,
142 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
143 pub struct SubstitutionPart {
148 impl CodeSuggestion {
149 /// Returns the assembled code suggestions, whether they should be shown with an underline
150 /// and whether the substitution only differs in capitalization.
151 pub fn splice_lines(&self, sm: &SourceMap) -> Vec<(String, Vec<SubstitutionPart>, bool)> {
152 use rustc_span::{CharPos, Pos};
156 line_opt: Option<&Cow<'_, str>>,
158 hi_opt: Option<&Loc>,
160 let (lo, hi_opt) = (lo.col.to_usize(), hi_opt.map(|hi| hi.col.to_usize()));
161 if let Some(line) = line_opt {
162 if let Some(lo) = line.char_indices().map(|(i, _)| i).nth(lo) {
163 let hi_opt = hi_opt.and_then(|hi| line.char_indices().map(|(i, _)| i).nth(hi));
165 Some(hi) if hi > lo => buf.push_str(&line[lo..hi]),
167 None => buf.push_str(&line[lo..]),
170 if hi_opt.is_none() {
176 assert!(!self.substitutions.is_empty());
181 // Suggestions coming from macros can have malformed spans. This is a heavy
182 // handed approach to avoid ICEs by ignoring the suggestion outright.
183 let invalid = subst.parts.iter().any(|item| sm.is_valid_span(item.span).is_err());
185 debug!("splice_lines: suggestion contains an invalid span: {:?}", subst);
190 .filter_map(|mut substitution| {
191 // Assumption: all spans are in the same file, and all spans
192 // are disjoint. Sort in ascending order.
193 substitution.parts.sort_by_key(|part| part.span.lo());
195 // Find the bounding span.
196 let lo = substitution.parts.iter().map(|part| part.span.lo()).min()?;
197 let hi = substitution.parts.iter().map(|part| part.span.hi()).max()?;
198 let bounding_span = Span::with_root_ctxt(lo, hi);
199 // The different spans might belong to different contexts, if so ignore suggestion.
200 let lines = sm.span_to_lines(bounding_span).ok()?;
201 assert!(!lines.lines.is_empty() || bounding_span.is_dummy());
203 // We can't splice anything if the source is unavailable.
204 if !sm.ensure_source_file_source_present(lines.file.clone()) {
208 // To build up the result, we do this for each span:
209 // - push the line segment trailing the previous span
210 // (at the beginning a "phantom" span pointing at the start of the line)
211 // - push lines between the previous and current span (if any)
212 // - if the previous and current span are not on the same line
213 // push the line segment leading up to the current span
214 // - splice in the span substitution
216 // Finally push the trailing line segment of the last span
217 let sf = &lines.file;
218 let mut prev_hi = sm.lookup_char_pos(bounding_span.lo());
219 prev_hi.col = CharPos::from_usize(0);
221 lines.lines.get(0).and_then(|line0| sf.get_line(line0.line_index));
222 let mut buf = String::new();
224 for part in &substitution.parts {
225 let cur_lo = sm.lookup_char_pos(part.span.lo());
226 if prev_hi.line == cur_lo.line {
227 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, Some(&cur_lo));
229 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
230 // push lines between the previous and current span (if any)
231 for idx in prev_hi.line..(cur_lo.line - 1) {
232 if let Some(line) = sf.get_line(idx) {
233 buf.push_str(line.as_ref());
237 if let Some(cur_line) = sf.get_line(cur_lo.line - 1) {
238 let end = match cur_line.char_indices().nth(cur_lo.col.to_usize()) {
240 None => cur_line.len(),
242 buf.push_str(&cur_line[..end]);
245 buf.push_str(&part.snippet);
246 prev_hi = sm.lookup_char_pos(part.span.hi());
247 prev_line = sf.get_line(prev_hi.line - 1);
249 let only_capitalization = is_case_difference(sm, &buf, bounding_span);
250 // if the replacement already ends with a newline, don't print the next line
251 if !buf.ends_with('\n') {
252 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
254 // remove trailing newlines
255 while buf.ends_with('\n') {
258 Some((buf, substitution.parts, only_capitalization))
264 pub use rustc_span::fatal_error::{FatalError, FatalErrorMarker};
266 /// Signifies that the compiler died with an explicit call to `.bug`
267 /// or `.span_bug` rather than a failed assertion, etc.
268 #[derive(Copy, Clone, Debug)]
269 pub struct ExplicitBug;
271 impl fmt::Display for ExplicitBug {
272 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
273 write!(f, "parser internal bug")
277 impl error::Error for ExplicitBug {}
279 pub use diagnostic::{Diagnostic, DiagnosticId, DiagnosticStyledString, SubDiagnostic};
280 pub use diagnostic_builder::DiagnosticBuilder;
282 /// A handler deals with errors and other compiler output.
283 /// Certain errors (fatal, bug, unimpl) may cause immediate exit,
284 /// others log errors for later reporting.
287 inner: Lock<HandlerInner>,
290 /// This inner struct exists to keep it all behind a single lock;
291 /// this is done to prevent possible deadlocks in a multi-threaded compiler,
292 /// as well as inconsistent state observation.
293 struct HandlerInner {
295 /// The number of errors that have been emitted, including duplicates.
297 /// This is not necessarily the count that's reported to the user once
298 /// compilation ends.
301 deduplicated_err_count: usize,
302 emitter: Box<dyn Emitter + sync::Send>,
303 delayed_span_bugs: Vec<Diagnostic>,
304 delayed_good_path_bugs: Vec<Diagnostic>,
306 /// This set contains the `DiagnosticId` of all emitted diagnostics to avoid
307 /// emitting the same diagnostic with extended help (`--teach`) twice, which
308 /// would be uneccessary repetition.
309 taught_diagnostics: FxHashSet<DiagnosticId>,
311 /// Used to suggest rustc --explain <error code>
312 emitted_diagnostic_codes: FxHashSet<DiagnosticId>,
314 /// This set contains a hash of every diagnostic that has been emitted by
315 /// this handler. These hashes is used to avoid emitting the same error
317 emitted_diagnostics: FxHashSet<u128>,
319 /// Stashed diagnostics emitted in one stage of the compiler that may be
320 /// stolen by other stages (e.g. to improve them and add more information).
321 /// The stashed diagnostics count towards the total error count.
322 /// When `.abort_if_errors()` is called, these are also emitted.
323 stashed_diagnostics: FxIndexMap<(Span, StashKey), Diagnostic>,
325 /// The warning count, used for a recap upon finishing
326 deduplicated_warn_count: usize,
329 /// A key denoting where from a diagnostic was stashed.
330 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
335 fn default_track_diagnostic(_: &Diagnostic) {}
337 pub static TRACK_DIAGNOSTICS: AtomicRef<fn(&Diagnostic)> =
338 AtomicRef::new(&(default_track_diagnostic as fn(&_)));
340 #[derive(Copy, Clone, Default)]
341 pub struct HandlerFlags {
342 /// If false, warning-level lints are suppressed.
343 /// (rustc: see `--allow warnings` and `--cap-lints`)
344 pub can_emit_warnings: bool,
345 /// If true, error-level diagnostics are upgraded to bug-level.
346 /// (rustc: see `-Z treat-err-as-bug`)
347 pub treat_err_as_bug: Option<usize>,
348 /// If true, immediately emit diagnostics that would otherwise be buffered.
349 /// (rustc: see `-Z dont-buffer-diagnostics` and `-Z treat-err-as-bug`)
350 pub dont_buffer_diagnostics: bool,
351 /// If true, immediately print bugs registered with `delay_span_bug`.
352 /// (rustc: see `-Z report-delayed-bugs`)
353 pub report_delayed_bugs: bool,
354 /// Show macro backtraces.
355 /// (rustc: see `-Z macro-backtrace`)
356 pub macro_backtrace: bool,
357 /// If true, identical diagnostics are reported only once.
358 pub deduplicate_diagnostics: bool,
361 impl Drop for HandlerInner {
363 self.emit_stashed_diagnostics();
365 if !self.has_errors() {
366 let bugs = std::mem::replace(&mut self.delayed_span_bugs, Vec::new());
367 self.flush_delayed(bugs, "no errors encountered even though `delay_span_bug` issued");
370 if !self.has_any_message() {
371 let bugs = std::mem::replace(&mut self.delayed_good_path_bugs, Vec::new());
374 "no warnings or errors encountered even though `delayed_good_path_bugs` issued",
381 pub fn with_tty_emitter(
382 color_config: ColorConfig,
383 can_emit_warnings: bool,
384 treat_err_as_bug: Option<usize>,
385 sm: Option<Lrc<SourceMap>>,
387 Self::with_tty_emitter_and_flags(
390 HandlerFlags { can_emit_warnings, treat_err_as_bug, ..Default::default() },
394 pub fn with_tty_emitter_and_flags(
395 color_config: ColorConfig,
396 sm: Option<Lrc<SourceMap>>,
399 let emitter = Box::new(EmitterWriter::stderr(
405 flags.macro_backtrace,
407 Self::with_emitter_and_flags(emitter, flags)
411 can_emit_warnings: bool,
412 treat_err_as_bug: Option<usize>,
413 emitter: Box<dyn Emitter + sync::Send>,
415 Handler::with_emitter_and_flags(
417 HandlerFlags { can_emit_warnings, treat_err_as_bug, ..Default::default() },
421 pub fn with_emitter_and_flags(
422 emitter: Box<dyn Emitter + sync::Send>,
427 inner: Lock::new(HandlerInner {
431 deduplicated_err_count: 0,
432 deduplicated_warn_count: 0,
434 delayed_span_bugs: Vec::new(),
435 delayed_good_path_bugs: Vec::new(),
436 taught_diagnostics: Default::default(),
437 emitted_diagnostic_codes: Default::default(),
438 emitted_diagnostics: Default::default(),
439 stashed_diagnostics: Default::default(),
444 // This is here to not allow mutation of flags;
445 // as of this writing it's only used in tests in librustc_middle.
446 pub fn can_emit_warnings(&self) -> bool {
447 self.flags.can_emit_warnings
450 /// Resets the diagnostic error count as well as the cached emitted diagnostics.
452 /// NOTE: *do not* call this function from rustc. It is only meant to be called from external
453 /// tools that want to reuse a `Parser` cleaning the previously emitted diagnostics as well as
454 /// the overall count of emitted error diagnostics.
455 pub fn reset_err_count(&self) {
456 let mut inner = self.inner.borrow_mut();
458 inner.warn_count = 0;
459 inner.deduplicated_err_count = 0;
460 inner.deduplicated_warn_count = 0;
462 // actually free the underlying memory (which `clear` would not do)
463 inner.delayed_span_bugs = Default::default();
464 inner.delayed_good_path_bugs = Default::default();
465 inner.taught_diagnostics = Default::default();
466 inner.emitted_diagnostic_codes = Default::default();
467 inner.emitted_diagnostics = Default::default();
468 inner.stashed_diagnostics = Default::default();
471 /// Stash a given diagnostic with the given `Span` and `StashKey` as the key for later stealing.
472 pub fn stash_diagnostic(&self, span: Span, key: StashKey, diag: Diagnostic) {
473 let mut inner = self.inner.borrow_mut();
474 // FIXME(Centril, #69537): Consider reintroducing panic on overwriting a stashed diagnostic
475 // if/when we have a more robust macro-friendly replacement for `(span, key)` as a key.
476 // See the PR for a discussion.
477 inner.stashed_diagnostics.insert((span, key), diag);
480 /// Steal a previously stashed diagnostic with the given `Span` and `StashKey` as the key.
481 pub fn steal_diagnostic(&self, span: Span, key: StashKey) -> Option<DiagnosticBuilder<'_>> {
485 .remove(&(span, key))
486 .map(|diag| DiagnosticBuilder::new_diagnostic(self, diag))
489 /// Emit all stashed diagnostics.
490 pub fn emit_stashed_diagnostics(&self) {
491 self.inner.borrow_mut().emit_stashed_diagnostics();
494 /// Construct a dummy builder with `Level::Cancelled`.
496 /// Using this will neither report anything to the user (e.g. a warning),
497 /// nor will compilation cancel as a result.
498 pub fn struct_dummy(&self) -> DiagnosticBuilder<'_> {
499 DiagnosticBuilder::new(self, Level::Cancelled, "")
502 /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
503 pub fn struct_span_warn(&self, span: impl Into<MultiSpan>, msg: &str) -> DiagnosticBuilder<'_> {
504 let mut result = self.struct_warn(msg);
505 result.set_span(span);
509 /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
510 /// Also include a code.
511 pub fn struct_span_warn_with_code(
513 span: impl Into<MultiSpan>,
516 ) -> DiagnosticBuilder<'_> {
517 let mut result = self.struct_span_warn(span, msg);
522 /// Construct a builder at the `Warning` level with the `msg`.
523 pub fn struct_warn(&self, msg: &str) -> DiagnosticBuilder<'_> {
524 let mut result = DiagnosticBuilder::new(self, Level::Warning, msg);
525 if !self.flags.can_emit_warnings {
531 /// Construct a builder at the `Error` level at the given `span` and with the `msg`.
532 pub fn struct_span_err(&self, span: impl Into<MultiSpan>, msg: &str) -> DiagnosticBuilder<'_> {
533 let mut result = self.struct_err(msg);
534 result.set_span(span);
538 /// Construct a builder at the `Error` level at the given `span`, with the `msg`, and `code`.
539 pub fn struct_span_err_with_code(
541 span: impl Into<MultiSpan>,
544 ) -> DiagnosticBuilder<'_> {
545 let mut result = self.struct_span_err(span, msg);
550 /// Construct a builder at the `Error` level with the `msg`.
551 // FIXME: This method should be removed (every error should have an associated error code).
552 pub fn struct_err(&self, msg: &str) -> DiagnosticBuilder<'_> {
553 DiagnosticBuilder::new(self, Level::Error, msg)
556 /// Construct a builder at the `Error` level with the `msg` and the `code`.
557 pub fn struct_err_with_code(&self, msg: &str, code: DiagnosticId) -> DiagnosticBuilder<'_> {
558 let mut result = self.struct_err(msg);
563 /// Construct a builder at the `Fatal` level at the given `span` and with the `msg`.
564 pub fn struct_span_fatal(
566 span: impl Into<MultiSpan>,
568 ) -> DiagnosticBuilder<'_> {
569 let mut result = self.struct_fatal(msg);
570 result.set_span(span);
574 /// Construct a builder at the `Fatal` level at the given `span`, with the `msg`, and `code`.
575 pub fn struct_span_fatal_with_code(
577 span: impl Into<MultiSpan>,
580 ) -> DiagnosticBuilder<'_> {
581 let mut result = self.struct_span_fatal(span, msg);
586 /// Construct a builder at the `Error` level with the `msg`.
587 pub fn struct_fatal(&self, msg: &str) -> DiagnosticBuilder<'_> {
588 DiagnosticBuilder::new(self, Level::Fatal, msg)
591 /// Construct a builder at the `Help` level with the `msg`.
592 pub fn struct_help(&self, msg: &str) -> DiagnosticBuilder<'_> {
593 DiagnosticBuilder::new(self, Level::Help, msg)
596 /// Construct a builder at the `Note` level with the `msg`.
597 pub fn struct_note_without_error(&self, msg: &str) -> DiagnosticBuilder<'_> {
598 DiagnosticBuilder::new(self, Level::Note, msg)
601 pub fn span_fatal(&self, span: impl Into<MultiSpan>, msg: &str) -> FatalError {
602 self.emit_diag_at_span(Diagnostic::new(Fatal, msg), span);
606 pub fn span_fatal_with_code(
608 span: impl Into<MultiSpan>,
612 self.emit_diag_at_span(Diagnostic::new_with_code(Fatal, Some(code), msg), span);
616 pub fn span_err(&self, span: impl Into<MultiSpan>, msg: &str) {
617 self.emit_diag_at_span(Diagnostic::new(Error, msg), span);
620 pub fn span_err_with_code(&self, span: impl Into<MultiSpan>, msg: &str, code: DiagnosticId) {
621 self.emit_diag_at_span(Diagnostic::new_with_code(Error, Some(code), msg), span);
624 pub fn span_warn(&self, span: impl Into<MultiSpan>, msg: &str) {
625 self.emit_diag_at_span(Diagnostic::new(Warning, msg), span);
628 pub fn span_warn_with_code(&self, span: impl Into<MultiSpan>, msg: &str, code: DiagnosticId) {
629 self.emit_diag_at_span(Diagnostic::new_with_code(Warning, Some(code), msg), span);
632 pub fn span_bug(&self, span: impl Into<MultiSpan>, msg: &str) -> ! {
633 self.inner.borrow_mut().span_bug(span, msg)
637 pub fn delay_span_bug(&self, span: impl Into<MultiSpan>, msg: &str) {
638 self.inner.borrow_mut().delay_span_bug(span, msg)
641 pub fn delay_good_path_bug(&self, msg: &str) {
642 self.inner.borrow_mut().delay_good_path_bug(msg)
645 pub fn span_bug_no_panic(&self, span: impl Into<MultiSpan>, msg: &str) {
646 self.emit_diag_at_span(Diagnostic::new(Bug, msg), span);
649 pub fn span_note_without_error(&self, span: impl Into<MultiSpan>, msg: &str) {
650 self.emit_diag_at_span(Diagnostic::new(Note, msg), span);
653 pub fn span_note_diag(&self, span: Span, msg: &str) -> DiagnosticBuilder<'_> {
654 let mut db = DiagnosticBuilder::new(self, Note, msg);
659 pub fn failure(&self, msg: &str) {
660 self.inner.borrow_mut().failure(msg);
663 pub fn fatal(&self, msg: &str) -> FatalError {
664 self.inner.borrow_mut().fatal(msg)
667 pub fn err(&self, msg: &str) {
668 self.inner.borrow_mut().err(msg);
671 pub fn warn(&self, msg: &str) {
672 let mut db = DiagnosticBuilder::new(self, Warning, msg);
676 pub fn note_without_error(&self, msg: &str) {
677 DiagnosticBuilder::new(self, Note, msg).emit();
680 pub fn bug(&self, msg: &str) -> ! {
681 self.inner.borrow_mut().bug(msg)
684 pub fn err_count(&self) -> usize {
685 self.inner.borrow().err_count()
688 pub fn has_errors(&self) -> bool {
689 self.inner.borrow().has_errors()
691 pub fn has_errors_or_delayed_span_bugs(&self) -> bool {
692 self.inner.borrow().has_errors_or_delayed_span_bugs()
695 pub fn print_error_count(&self, registry: &Registry) {
696 self.inner.borrow_mut().print_error_count(registry)
699 pub fn abort_if_errors(&self) {
700 self.inner.borrow_mut().abort_if_errors()
703 /// `true` if we haven't taught a diagnostic with this code already.
704 /// The caller must then teach the user about such a diagnostic.
706 /// Used to suppress emitting the same error multiple times with extended explanation when
707 /// calling `-Zteach`.
708 pub fn must_teach(&self, code: &DiagnosticId) -> bool {
709 self.inner.borrow_mut().must_teach(code)
712 pub fn force_print_diagnostic(&self, db: Diagnostic) {
713 self.inner.borrow_mut().force_print_diagnostic(db)
716 pub fn emit_diagnostic(&self, diagnostic: &Diagnostic) {
717 self.inner.borrow_mut().emit_diagnostic(diagnostic)
720 fn emit_diag_at_span(&self, mut diag: Diagnostic, sp: impl Into<MultiSpan>) {
721 let mut inner = self.inner.borrow_mut();
722 inner.emit_diagnostic(diag.set_span(sp));
725 pub fn emit_artifact_notification(&self, path: &Path, artifact_type: &str) {
726 self.inner.borrow_mut().emit_artifact_notification(path, artifact_type)
729 pub fn delay_as_bug(&self, diagnostic: Diagnostic) {
730 self.inner.borrow_mut().delay_as_bug(diagnostic)
735 fn must_teach(&mut self, code: &DiagnosticId) -> bool {
736 self.taught_diagnostics.insert(code.clone())
739 fn force_print_diagnostic(&mut self, db: Diagnostic) {
740 self.emitter.emit_diagnostic(&db);
743 /// Emit all stashed diagnostics.
744 fn emit_stashed_diagnostics(&mut self) {
745 let diags = self.stashed_diagnostics.drain(..).map(|x| x.1).collect::<Vec<_>>();
746 diags.iter().for_each(|diag| self.emit_diagnostic(diag));
749 fn emit_diagnostic(&mut self, diagnostic: &Diagnostic) {
750 if diagnostic.cancelled() {
754 if diagnostic.level == Warning && !self.flags.can_emit_warnings {
758 (*TRACK_DIAGNOSTICS)(diagnostic);
760 if let Some(ref code) = diagnostic.code {
761 self.emitted_diagnostic_codes.insert(code.clone());
764 let already_emitted = |this: &mut Self| {
766 let mut hasher = StableHasher::new();
767 diagnostic.hash(&mut hasher);
768 let diagnostic_hash = hasher.finish();
769 !this.emitted_diagnostics.insert(diagnostic_hash)
772 // Only emit the diagnostic if we've been asked to deduplicate and
773 // haven't already emitted an equivalent diagnostic.
774 if !(self.flags.deduplicate_diagnostics && already_emitted(self)) {
775 self.emitter.emit_diagnostic(diagnostic);
776 if diagnostic.is_error() {
777 self.deduplicated_err_count += 1;
778 } else if diagnostic.level == Warning {
779 self.deduplicated_warn_count += 1;
782 if diagnostic.is_error() {
783 self.bump_err_count();
785 self.bump_warn_count();
789 fn emit_artifact_notification(&mut self, path: &Path, artifact_type: &str) {
790 self.emitter.emit_artifact_notification(path, artifact_type);
793 fn treat_err_as_bug(&self) -> bool {
794 self.flags.treat_err_as_bug.map(|c| self.err_count() >= c).unwrap_or(false)
797 fn print_error_count(&mut self, registry: &Registry) {
798 self.emit_stashed_diagnostics();
800 let warnings = match self.deduplicated_warn_count {
802 1 => "1 warning emitted".to_string(),
803 count => format!("{} warnings emitted", count),
805 let errors = match self.deduplicated_err_count {
807 1 => "aborting due to previous error".to_string(),
808 count => format!("aborting due to {} previous errors", count),
810 if self.treat_err_as_bug() {
814 match (errors.len(), warnings.len()) {
816 (0, _) => self.emit_diagnostic(&Diagnostic::new(Level::Warning, &warnings)),
818 let _ = self.fatal(&errors);
821 let _ = self.fatal(&format!("{}; {}", &errors, &warnings));
825 let can_show_explain = self.emitter.should_show_explain();
826 let are_there_diagnostics = !self.emitted_diagnostic_codes.is_empty();
827 if can_show_explain && are_there_diagnostics {
828 let mut error_codes = self
829 .emitted_diagnostic_codes
831 .filter_map(|x| match &x {
832 DiagnosticId::Error(s) => {
833 if let Ok(Some(_explanation)) = registry.try_find_description(s) {
841 .collect::<Vec<_>>();
842 if !error_codes.is_empty() {
844 if error_codes.len() > 1 {
845 let limit = if error_codes.len() > 9 { 9 } else { error_codes.len() };
846 self.failure(&format!(
847 "Some errors have detailed explanations: {}{}",
848 error_codes[..limit].join(", "),
849 if error_codes.len() > 9 { "..." } else { "." }
851 self.failure(&format!(
852 "For more information about an error, try \
853 `rustc --explain {}`.",
857 self.failure(&format!(
858 "For more information about this error, try \
859 `rustc --explain {}`.",
867 fn err_count(&self) -> usize {
868 self.err_count + self.stashed_diagnostics.len()
871 fn has_errors(&self) -> bool {
874 fn has_errors_or_delayed_span_bugs(&self) -> bool {
875 self.has_errors() || !self.delayed_span_bugs.is_empty()
877 fn has_any_message(&self) -> bool {
878 self.err_count() > 0 || self.warn_count > 0
881 fn abort_if_errors(&mut self) {
882 self.emit_stashed_diagnostics();
884 if self.has_errors() {
889 fn span_bug(&mut self, sp: impl Into<MultiSpan>, msg: &str) -> ! {
890 self.emit_diag_at_span(Diagnostic::new(Bug, msg), sp);
894 fn emit_diag_at_span(&mut self, mut diag: Diagnostic, sp: impl Into<MultiSpan>) {
895 self.emit_diagnostic(diag.set_span(sp));
899 fn delay_span_bug(&mut self, sp: impl Into<MultiSpan>, msg: &str) {
900 // This is technically `self.treat_err_as_bug()` but `delay_span_bug` is called before
901 // incrementing `err_count` by one, so we need to +1 the comparing.
902 // FIXME: Would be nice to increment err_count in a more coherent way.
903 if self.flags.treat_err_as_bug.map(|c| self.err_count() + 1 >= c).unwrap_or(false) {
904 // FIXME: don't abort here if report_delayed_bugs is off
905 self.span_bug(sp, msg);
907 let mut diagnostic = Diagnostic::new(Level::Bug, msg);
908 diagnostic.set_span(sp.into());
909 diagnostic.note(&format!("delayed at {}", std::panic::Location::caller()));
910 self.delay_as_bug(diagnostic)
913 fn delay_good_path_bug(&mut self, msg: &str) {
914 let mut diagnostic = Diagnostic::new(Level::Bug, msg);
915 if self.flags.report_delayed_bugs {
916 self.emit_diagnostic(&diagnostic);
918 diagnostic.note(&format!("delayed at {}", std::backtrace::Backtrace::force_capture()));
919 self.delayed_good_path_bugs.push(diagnostic);
922 fn failure(&mut self, msg: &str) {
923 self.emit_diagnostic(&Diagnostic::new(FailureNote, msg));
926 fn fatal(&mut self, msg: &str) -> FatalError {
927 self.emit_error(Fatal, msg);
931 fn err(&mut self, msg: &str) {
932 self.emit_error(Error, msg);
935 /// Emit an error; level should be `Error` or `Fatal`.
936 fn emit_error(&mut self, level: Level, msg: &str) {
937 if self.treat_err_as_bug() {
940 self.emit_diagnostic(&Diagnostic::new(level, msg));
943 fn bug(&mut self, msg: &str) -> ! {
944 self.emit_diagnostic(&Diagnostic::new(Bug, msg));
948 fn delay_as_bug(&mut self, diagnostic: Diagnostic) {
949 if self.flags.report_delayed_bugs {
950 self.emit_diagnostic(&diagnostic);
952 self.delayed_span_bugs.push(diagnostic);
955 fn flush_delayed(&mut self, bugs: Vec<Diagnostic>, explanation: &str) {
956 let has_bugs = !bugs.is_empty();
958 self.emit_diagnostic(&bug);
961 panic!("{}", explanation);
965 fn bump_err_count(&mut self) {
967 self.panic_if_treat_err_as_bug();
970 fn bump_warn_count(&mut self) {
971 self.warn_count += 1;
974 fn panic_if_treat_err_as_bug(&self) {
975 if self.treat_err_as_bug() {
976 match (self.err_count(), self.flags.treat_err_as_bug.unwrap_or(0)) {
977 (1, 1) => panic!("aborting due to `-Z treat-err-as-bug=1`"),
978 (0, _) | (1, _) => {}
979 (count, as_bug) => panic!(
980 "aborting after {} errors due to `-Z treat-err-as-bug={}`",
988 #[derive(Copy, PartialEq, Clone, Hash, Debug, Encodable, Decodable)]
1000 impl fmt::Display for Level {
1001 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1002 self.to_str().fmt(f)
1007 fn color(self) -> ColorSpec {
1008 let mut spec = ColorSpec::new();
1010 Bug | Fatal | Error => {
1011 spec.set_fg(Some(Color::Red)).set_intense(true);
1014 spec.set_fg(Some(Color::Yellow)).set_intense(cfg!(windows));
1017 spec.set_fg(Some(Color::Green)).set_intense(true);
1020 spec.set_fg(Some(Color::Cyan)).set_intense(true);
1023 Cancelled => unreachable!(),
1028 pub fn to_str(self) -> &'static str {
1030 Bug => "error: internal compiler error",
1031 Fatal | Error => "error",
1032 Warning => "warning",
1035 FailureNote => "failure-note",
1036 Cancelled => panic!("Shouldn't call on cancelled error"),
1040 pub fn is_failure_note(&self) -> bool {
1042 FailureNote => true,
1049 macro_rules! pluralize {
1051 if $x != 1 { "s" } else { "" }
1055 // Useful type to use with `Result<>` indicate that an error has already
1056 // been reported to the user, so no need to continue checking.
1057 #[derive(Clone, Copy, Debug, Encodable, Decodable, Hash, PartialEq, Eq)]
1058 pub struct ErrorReported;
1060 rustc_data_structures::impl_stable_hash_via_hash!(ErrorReported);