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;
19 use rustc_data_structures::sync::{self, Lrc, Lock};
20 use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
21 use rustc_data_structures::stable_hasher::StableHasher;
25 use std::{error, fmt};
29 use termcolor::{ColorSpec, Color};
32 mod diagnostic_builder;
34 pub mod annotate_snippet_emitter_writer;
51 /// Indicates the confidence in the correctness of a suggestion.
53 /// All suggestions are marked with an `Applicability`. Tools use the applicability of a suggestion
54 /// to determine whether it should be automatically applied or if the user should be consulted
55 /// before applying the suggestion.
56 #[derive(Copy, Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
57 pub enum Applicability {
58 /// The suggestion is definitely what the user intended. This suggestion should be
59 /// automatically applied.
62 /// The suggestion may be what the user intended, but it is uncertain. The suggestion should
63 /// result in valid Rust code if it is applied.
66 /// The suggestion contains placeholders like `(...)` or `{ /* fields */ }`. The suggestion
67 /// cannot be applied automatically because it will not result in valid Rust code. The user
68 /// will need to fill in the placeholders.
71 /// The applicability of the suggestion is unknown.
75 #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, RustcEncodable, RustcDecodable)]
76 pub enum SuggestionStyle {
77 /// Hide the suggested code when displaying this suggestion inline.
79 /// Always hide the suggested code but display the message.
81 /// Do not display this suggestion in the cli output, it is only meant for tools.
83 /// Always show the suggested code.
84 /// This will *not* show the code if the suggestion is inline *and* the suggested code is
87 /// Always show the suggested code independently.
91 impl SuggestionStyle {
92 fn hide_inline(&self) -> bool {
94 SuggestionStyle::ShowCode => false,
100 #[derive(Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
101 pub struct CodeSuggestion {
102 /// Each substitute can have multiple variants due to multiple
103 /// applicable suggestions
105 /// `foo.bar` might be replaced with `a.b` or `x.y` by replacing
106 /// `foo` and `bar` on their own:
110 /// Substitution { parts: vec![(0..3, "a"), (4..7, "b")] },
111 /// Substitution { parts: vec![(0..3, "x"), (4..7, "y")] },
115 /// or by replacing the entire span:
119 /// Substitution { parts: vec![(0..7, "a.b")] },
120 /// Substitution { parts: vec![(0..7, "x.y")] },
123 pub substitutions: Vec<Substitution>,
125 /// Visual representation of this suggestion.
126 pub style: SuggestionStyle,
127 /// Whether or not the suggestion is approximate
129 /// Sometimes we may show suggestions with placeholders,
130 /// which are useful for users but not useful for
131 /// tools like rustfix
132 pub applicability: Applicability,
135 #[derive(Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
136 /// See the docs on `CodeSuggestion::substitutions`
137 pub struct Substitution {
138 pub parts: Vec<SubstitutionPart>,
141 #[derive(Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
142 pub struct SubstitutionPart {
147 pub type SourceMapperDyn = dyn SourceMapper + sync::Send + sync::Sync;
149 pub trait SourceMapper {
150 fn lookup_char_pos(&self, pos: BytePos) -> Loc;
151 fn span_to_lines(&self, sp: Span) -> FileLinesResult;
152 fn span_to_string(&self, sp: Span) -> String;
153 fn span_to_snippet(&self, sp: Span) -> Result<String, SpanSnippetError>;
154 fn span_to_filename(&self, sp: Span) -> FileName;
155 fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option<Span>;
156 fn call_span_if_macro(&self, sp: Span) -> Span;
157 fn ensure_source_file_source_present(&self, source_file: Lrc<SourceFile>) -> bool;
158 fn doctest_offset_line(&self, file: &FileName, line: usize) -> usize;
161 impl CodeSuggestion {
162 /// Returns the assembled code suggestions, whether they should be shown with an underline
163 /// and whether the substitution only differs in capitalization.
166 cm: &SourceMapperDyn,
167 ) -> Vec<(String, Vec<SubstitutionPart>, bool)> {
168 use syntax_pos::{CharPos, Pos};
170 fn push_trailing(buf: &mut String,
171 line_opt: Option<&Cow<'_, str>>,
173 hi_opt: Option<&Loc>) {
174 let (lo, hi_opt) = (lo.col.to_usize(), hi_opt.map(|hi| hi.col.to_usize()));
175 if let Some(line) = line_opt {
176 if let Some(lo) = line.char_indices().map(|(i, _)| i).nth(lo) {
177 let hi_opt = hi_opt.and_then(|hi| line.char_indices().map(|(i, _)| i).nth(hi));
179 Some(hi) if hi > lo => buf.push_str(&line[lo..hi]),
181 None => buf.push_str(&line[lo..]),
184 if let None = hi_opt {
190 assert!(!self.substitutions.is_empty());
192 self.substitutions.iter().cloned().map(|mut substitution| {
193 // Assumption: all spans are in the same file, and all spans
194 // are disjoint. Sort in ascending order.
195 substitution.parts.sort_by_key(|part| part.span.lo());
197 // Find the bounding span.
198 let lo = substitution.parts.iter().map(|part| part.span.lo()).min().unwrap();
199 let hi = substitution.parts.iter().map(|part| part.span.hi()).min().unwrap();
200 let bounding_span = Span::with_root_ctxt(lo, hi);
201 let lines = cm.span_to_lines(bounding_span).unwrap();
202 assert!(!lines.lines.is_empty());
204 // To build up the result, we do this for each span:
205 // - push the line segment trailing the previous span
206 // (at the beginning a "phantom" span pointing at the start of the line)
207 // - push lines between the previous and current span (if any)
208 // - if the previous and current span are not on the same line
209 // push the line segment leading up to the current span
210 // - splice in the span substitution
212 // Finally push the trailing line segment of the last span
213 let fm = &lines.file;
214 let mut prev_hi = cm.lookup_char_pos(bounding_span.lo());
215 prev_hi.col = CharPos::from_usize(0);
217 let mut prev_line = fm.get_line(lines.lines[0].line_index);
218 let mut buf = String::new();
220 for part in &substitution.parts {
221 let cur_lo = cm.lookup_char_pos(part.span.lo());
222 if prev_hi.line == cur_lo.line {
223 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, Some(&cur_lo));
225 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
226 // push lines between the previous and current span (if any)
227 for idx in prev_hi.line..(cur_lo.line - 1) {
228 if let Some(line) = fm.get_line(idx) {
229 buf.push_str(line.as_ref());
233 if let Some(cur_line) = fm.get_line(cur_lo.line - 1) {
234 let end = std::cmp::min(cur_line.len(), cur_lo.col.to_usize());
235 buf.push_str(&cur_line[..end]);
238 buf.push_str(&part.snippet);
239 prev_hi = cm.lookup_char_pos(part.span.hi());
240 prev_line = fm.get_line(prev_hi.line - 1);
242 let only_capitalization = is_case_difference(cm, &buf, bounding_span);
243 // if the replacement already ends with a newline, don't print the next line
244 if !buf.ends_with('\n') {
245 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
247 // remove trailing newlines
248 while buf.ends_with('\n') {
251 (buf, substitution.parts, only_capitalization)
256 /// Used as a return value to signify a fatal error occurred. (It is also
257 /// used as the argument to panic at the moment, but that will eventually
259 #[derive(Copy, Clone, Debug)]
261 pub struct FatalError;
263 pub struct FatalErrorMarker;
265 // Don't implement Send on FatalError. This makes it impossible to panic!(FatalError).
266 // We don't want to invoke the panic handler and print a backtrace for fatal errors.
267 impl !Send for FatalError {}
270 pub fn raise(self) -> ! {
271 panic::resume_unwind(Box::new(FatalErrorMarker))
275 impl fmt::Display for FatalError {
276 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
277 write!(f, "parser fatal error")
281 impl error::Error for FatalError {
282 fn description(&self) -> &str {
283 "The parser has encountered a fatal error"
287 /// Signifies that the compiler died with an explicit call to `.bug`
288 /// or `.span_bug` rather than a failed assertion, etc.
289 #[derive(Copy, Clone, Debug)]
290 pub struct ExplicitBug;
292 impl fmt::Display for ExplicitBug {
293 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
294 write!(f, "parser internal bug")
298 impl error::Error for ExplicitBug {
299 fn description(&self) -> &str {
300 "The parser has encountered an internal bug"
304 pub use diagnostic::{Diagnostic, SubDiagnostic, DiagnosticStyledString, DiagnosticId};
305 pub use diagnostic_builder::DiagnosticBuilder;
307 /// A handler deals with errors and other compiler output.
308 /// Certain errors (fatal, bug, unimpl) may cause immediate exit,
309 /// others log errors for later reporting.
312 inner: Lock<HandlerInner>,
315 /// This inner struct exists to keep it all behind a single lock;
316 /// this is done to prevent possible deadlocks in a multi-threaded compiler,
317 /// as well as inconsistent state observation.
318 struct HandlerInner {
320 /// The number of errors that have been emitted, including duplicates.
322 /// This is not necessarily the count that's reported to the user once
323 /// compilation ends.
325 deduplicated_err_count: usize,
326 emitter: Box<dyn Emitter + sync::Send>,
327 continue_after_error: bool,
328 delayed_span_bugs: Vec<Diagnostic>,
330 /// This set contains the `DiagnosticId` of all emitted diagnostics to avoid
331 /// emitting the same diagnostic with extended help (`--teach`) twice, which
332 /// would be uneccessary repetition.
333 taught_diagnostics: FxHashSet<DiagnosticId>,
335 /// Used to suggest rustc --explain <error code>
336 emitted_diagnostic_codes: FxHashSet<DiagnosticId>,
338 /// This set contains a hash of every diagnostic that has been emitted by
339 /// this handler. These hashes is used to avoid emitting the same error
341 emitted_diagnostics: FxHashSet<u128>,
343 /// Stashed diagnostics emitted in one stage of the compiler that may be
344 /// stolen by other stages (e.g. to improve them and add more information).
345 /// The stashed diagnostics count towards the total error count.
346 /// When `.abort_if_errors()` is called, these are also emitted.
347 stashed_diagnostics: FxIndexMap<(Span, StashKey), Diagnostic>,
350 /// A key denoting where from a diagnostic was stashed.
351 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
356 fn default_track_diagnostic(_: &Diagnostic) {}
358 thread_local!(pub static TRACK_DIAGNOSTICS: Cell<fn(&Diagnostic)> =
359 Cell::new(default_track_diagnostic));
361 #[derive(Copy, Clone, Default)]
362 pub struct HandlerFlags {
363 /// If false, warning-level lints are suppressed.
364 /// (rustc: see `--allow warnings` and `--cap-lints`)
365 pub can_emit_warnings: bool,
366 /// If true, error-level diagnostics are upgraded to bug-level.
367 /// (rustc: see `-Z treat-err-as-bug`)
368 pub treat_err_as_bug: Option<usize>,
369 /// If true, immediately emit diagnostics that would otherwise be buffered.
370 /// (rustc: see `-Z dont-buffer-diagnostics` and `-Z treat-err-as-bug`)
371 pub dont_buffer_diagnostics: bool,
372 /// If true, immediately print bugs registered with `delay_span_bug`.
373 /// (rustc: see `-Z report-delayed-bugs`)
374 pub report_delayed_bugs: bool,
375 /// show macro backtraces even for non-local macros.
376 /// (rustc: see `-Z external-macro-backtrace`)
377 pub external_macro_backtrace: bool,
380 impl Drop for HandlerInner {
382 self.emit_stashed_diagnostics();
384 if !self.has_errors() {
385 let bugs = std::mem::replace(&mut self.delayed_span_bugs, Vec::new());
386 let has_bugs = !bugs.is_empty();
388 self.emit_diagnostic(&bug);
391 panic!("no errors encountered even though `delay_span_bug` issued");
398 pub fn with_tty_emitter(
399 color_config: ColorConfig,
400 can_emit_warnings: bool,
401 treat_err_as_bug: Option<usize>,
402 cm: Option<Lrc<SourceMapperDyn>>,
404 Self::with_tty_emitter_and_flags(
410 .. Default::default()
415 pub fn with_tty_emitter_and_flags(
416 color_config: ColorConfig,
417 cm: Option<Lrc<SourceMapperDyn>>,
420 let emitter = Box::new(EmitterWriter::stderr(
426 flags.external_macro_backtrace,
428 Self::with_emitter_and_flags(emitter, flags)
432 can_emit_warnings: bool,
433 treat_err_as_bug: Option<usize>,
434 emitter: Box<dyn Emitter + sync::Send>,
436 Handler::with_emitter_and_flags(
441 .. Default::default()
446 pub fn with_emitter_and_flags(
447 emitter: Box<dyn Emitter + sync::Send>,
452 inner: Lock::new(HandlerInner {
455 deduplicated_err_count: 0,
457 continue_after_error: true,
458 delayed_span_bugs: Vec::new(),
459 taught_diagnostics: Default::default(),
460 emitted_diagnostic_codes: Default::default(),
461 emitted_diagnostics: Default::default(),
462 stashed_diagnostics: Default::default(),
467 pub fn set_continue_after_error(&self, continue_after_error: bool) {
468 self.inner.borrow_mut().continue_after_error = continue_after_error;
471 // This is here to not allow mutation of flags;
472 // as of this writing it's only used in tests in librustc.
473 pub fn can_emit_warnings(&self) -> bool {
474 self.flags.can_emit_warnings
477 /// Resets the diagnostic error count as well as the cached emitted diagnostics.
479 /// NOTE: *do not* call this function from rustc. It is only meant to be called from external
480 /// tools that want to reuse a `Parser` cleaning the previously emitted diagnostics as well as
481 /// the overall count of emitted error diagnostics.
482 pub fn reset_err_count(&self) {
483 let mut inner = self.inner.borrow_mut();
485 inner.deduplicated_err_count = 0;
487 // actually free the underlying memory (which `clear` would not do)
488 inner.delayed_span_bugs = Default::default();
489 inner.taught_diagnostics = Default::default();
490 inner.emitted_diagnostic_codes = Default::default();
491 inner.emitted_diagnostics = Default::default();
492 inner.stashed_diagnostics = Default::default();
495 /// Stash a given diagnostic with the given `Span` and `StashKey` as the key for later stealing.
496 /// If the diagnostic with this `(span, key)` already exists, this will result in an ICE.
497 pub fn stash_diagnostic(&self, span: Span, key: StashKey, diag: Diagnostic) {
498 let mut inner = self.inner.borrow_mut();
499 if let Some(mut old_diag) = inner.stashed_diagnostics.insert((span, key), diag) {
500 // We are removing a previously stashed diagnostic which should not happen.
501 old_diag.level = Bug;
502 old_diag.note(&format!(
503 "{}:{}: already existing stashed diagnostic with (span = {:?}, key = {:?})",
504 file!(), line!(), span, key
506 inner.emit_diag_at_span(old_diag, span);
511 /// Steal a previously stashed diagnostic with the given `Span` and `StashKey` as the key.
512 pub fn steal_diagnostic(&self, span: Span, key: StashKey) -> Option<DiagnosticBuilder<'_>> {
516 .remove(&(span, key))
517 .map(|diag| DiagnosticBuilder::new_diagnostic(self, diag))
520 /// Emit all stashed diagnostics.
521 pub fn emit_stashed_diagnostics(&self) {
522 self.inner.borrow_mut().emit_stashed_diagnostics();
525 /// Construct a dummy builder with `Level::Cancelled`.
527 /// Using this will neither report anything to the user (e.g. a warning),
528 /// nor will compilation cancel as a result.
529 pub fn struct_dummy(&self) -> DiagnosticBuilder<'_> {
530 DiagnosticBuilder::new(self, Level::Cancelled, "")
533 /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
534 pub fn struct_span_warn(&self, span: impl Into<MultiSpan>, msg: &str) -> DiagnosticBuilder<'_> {
535 let mut result = self.struct_warn(msg);
536 result.set_span(span);
540 /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
541 /// Also include a code.
542 pub fn struct_span_warn_with_code(
544 span: impl Into<MultiSpan>,
547 ) -> DiagnosticBuilder<'_> {
548 let mut result = self.struct_span_warn(span, msg);
553 /// Construct a builder at the `Warning` level with the `msg`.
554 pub fn struct_warn(&self, msg: &str) -> DiagnosticBuilder<'_> {
555 let mut result = DiagnosticBuilder::new(self, Level::Warning, msg);
556 if !self.flags.can_emit_warnings {
562 /// Construct a builder at the `Error` level at the given `span` and with the `msg`.
563 pub fn struct_span_err(&self, span: impl Into<MultiSpan>, msg: &str) -> DiagnosticBuilder<'_> {
564 let mut result = self.struct_err(msg);
565 result.set_span(span);
569 /// Construct a builder at the `Error` level at the given `span`, with the `msg`, and `code`.
570 pub fn struct_span_err_with_code(
572 span: impl Into<MultiSpan>,
575 ) -> DiagnosticBuilder<'_> {
576 let mut result = self.struct_span_err(span, msg);
581 /// Construct a builder at the `Error` level with the `msg`.
582 // FIXME: This method should be removed (every error should have an associated error code).
583 pub fn struct_err(&self, msg: &str) -> DiagnosticBuilder<'_> {
584 DiagnosticBuilder::new(self, Level::Error, msg)
587 /// Construct a builder at the `Error` level with the `msg` and the `code`.
588 pub fn struct_err_with_code(&self, msg: &str, code: DiagnosticId) -> DiagnosticBuilder<'_> {
589 let mut result = self.struct_err(msg);
594 /// Construct a builder at the `Fatal` level at the given `span` and with the `msg`.
595 pub fn struct_span_fatal(
597 span: impl Into<MultiSpan>,
599 ) -> DiagnosticBuilder<'_> {
600 let mut result = self.struct_fatal(msg);
601 result.set_span(span);
605 /// Construct a builder at the `Fatal` level at the given `span`, with the `msg`, and `code`.
606 pub fn struct_span_fatal_with_code(
608 span: impl Into<MultiSpan>,
611 ) -> DiagnosticBuilder<'_> {
612 let mut result = self.struct_span_fatal(span, msg);
617 /// Construct a builder at the `Error` level with the `msg`.
618 pub fn struct_fatal(&self, msg: &str) -> DiagnosticBuilder<'_> {
619 DiagnosticBuilder::new(self, Level::Fatal, msg)
622 pub fn span_fatal(&self, span: impl Into<MultiSpan>, msg: &str) -> FatalError {
623 self.emit_diag_at_span(Diagnostic::new(Fatal, msg), span);
627 pub fn span_fatal_with_code(
629 span: impl Into<MultiSpan>,
633 self.emit_diag_at_span(Diagnostic::new_with_code(Fatal, Some(code), msg), span);
637 pub fn span_err(&self, span: impl Into<MultiSpan>, msg: &str) {
638 self.emit_diag_at_span(Diagnostic::new(Error, msg), span);
641 pub fn span_err_with_code(&self, span: impl Into<MultiSpan>, msg: &str, code: DiagnosticId) {
642 self.emit_diag_at_span(Diagnostic::new_with_code(Error, Some(code), msg), span);
645 pub fn span_warn(&self, span: impl Into<MultiSpan>, msg: &str) {
646 self.emit_diag_at_span(Diagnostic::new(Warning, msg), span);
649 pub fn span_warn_with_code(&self, span: impl Into<MultiSpan>, msg: &str, code: DiagnosticId) {
650 self.emit_diag_at_span(Diagnostic::new_with_code(Warning, Some(code), msg), span);
653 pub fn span_bug(&self, span: impl Into<MultiSpan>, msg: &str) -> ! {
654 self.inner.borrow_mut().span_bug(span, msg)
657 pub fn delay_span_bug(&self, span: impl Into<MultiSpan>, msg: &str) {
658 self.inner.borrow_mut().delay_span_bug(span, msg)
661 pub fn span_bug_no_panic(&self, span: impl Into<MultiSpan>, msg: &str) {
662 self.emit_diag_at_span(Diagnostic::new(Bug, msg), span);
665 pub fn span_note_without_error(&self, span: impl Into<MultiSpan>, msg: &str) {
666 self.emit_diag_at_span(Diagnostic::new(Note, msg), span);
669 pub fn span_note_diag(&self, span: Span, msg: &str) -> DiagnosticBuilder<'_> {
670 let mut db = DiagnosticBuilder::new(self, Note, msg);
675 pub fn failure(&self, msg: &str) {
676 self.inner.borrow_mut().failure(msg);
679 pub fn fatal(&self, msg: &str) -> FatalError {
680 self.inner.borrow_mut().fatal(msg)
683 pub fn err(&self, msg: &str) {
684 self.inner.borrow_mut().err(msg);
687 pub fn warn(&self, msg: &str) {
688 let mut db = DiagnosticBuilder::new(self, Warning, msg);
692 pub fn note_without_error(&self, msg: &str) {
693 DiagnosticBuilder::new(self, Note, msg).emit();
696 pub fn bug(&self, msg: &str) -> ! {
697 self.inner.borrow_mut().bug(msg)
700 pub fn err_count(&self) -> usize {
701 self.inner.borrow().err_count()
704 pub fn has_errors(&self) -> bool {
705 self.inner.borrow().has_errors()
707 pub fn has_errors_or_delayed_span_bugs(&self) -> bool {
708 self.inner.borrow().has_errors_or_delayed_span_bugs()
711 pub fn print_error_count(&self, registry: &Registry) {
712 self.inner.borrow_mut().print_error_count(registry)
715 pub fn abort_if_errors(&self) {
716 self.inner.borrow_mut().abort_if_errors()
719 pub fn abort_if_errors_and_should_abort(&self) {
720 self.inner.borrow_mut().abort_if_errors_and_should_abort()
723 /// `true` if we haven't taught a diagnostic with this code already.
724 /// The caller must then teach the user about such a diagnostic.
726 /// Used to suppress emitting the same error multiple times with extended explanation when
727 /// calling `-Zteach`.
728 pub fn must_teach(&self, code: &DiagnosticId) -> bool {
729 self.inner.borrow_mut().must_teach(code)
732 pub fn force_print_diagnostic(&self, db: Diagnostic) {
733 self.inner.borrow_mut().force_print_diagnostic(db)
736 pub fn emit_diagnostic(&self, diagnostic: &Diagnostic) {
737 self.inner.borrow_mut().emit_diagnostic(diagnostic)
740 fn emit_diag_at_span(&self, mut diag: Diagnostic, sp: impl Into<MultiSpan>) {
741 let mut inner = self.inner.borrow_mut();
742 inner.emit_diagnostic(diag.set_span(sp));
743 inner.abort_if_errors_and_should_abort();
746 pub fn emit_artifact_notification(&self, path: &Path, artifact_type: &str) {
747 self.inner.borrow_mut().emit_artifact_notification(path, artifact_type)
750 pub fn delay_as_bug(&self, diagnostic: Diagnostic) {
751 self.inner.borrow_mut().delay_as_bug(diagnostic)
756 fn must_teach(&mut self, code: &DiagnosticId) -> bool {
757 self.taught_diagnostics.insert(code.clone())
760 fn force_print_diagnostic(&mut self, db: Diagnostic) {
761 self.emitter.emit_diagnostic(&db);
764 /// Emit all stashed diagnostics.
765 fn emit_stashed_diagnostics(&mut self) {
766 let diags = self.stashed_diagnostics.drain(..).map(|x| x.1).collect::<Vec<_>>();
767 diags.iter().for_each(|diag| self.emit_diagnostic(diag));
770 fn emit_diagnostic(&mut self, diagnostic: &Diagnostic) {
771 if diagnostic.cancelled() {
775 if diagnostic.level == Warning && !self.flags.can_emit_warnings {
779 TRACK_DIAGNOSTICS.with(|track_diagnostics| {
780 track_diagnostics.get()(diagnostic);
783 if let Some(ref code) = diagnostic.code {
784 self.emitted_diagnostic_codes.insert(code.clone());
787 let diagnostic_hash = {
789 let mut hasher = StableHasher::new();
790 diagnostic.hash(&mut hasher);
794 // Only emit the diagnostic if we haven't already emitted an equivalent
796 if self.emitted_diagnostics.insert(diagnostic_hash) {
797 self.emitter.emit_diagnostic(diagnostic);
798 if diagnostic.is_error() {
799 self.deduplicated_err_count += 1;
802 if diagnostic.is_error() {
803 self.bump_err_count();
807 fn emit_artifact_notification(&mut self, path: &Path, artifact_type: &str) {
808 self.emitter.emit_artifact_notification(path, artifact_type);
811 fn treat_err_as_bug(&self) -> bool {
812 self.flags.treat_err_as_bug.map(|c| self.err_count() >= c).unwrap_or(false)
815 fn print_error_count(&mut self, registry: &Registry) {
816 self.emit_stashed_diagnostics();
818 let s = match self.deduplicated_err_count {
820 1 => "aborting due to previous error".to_string(),
821 count => format!("aborting due to {} previous errors", count)
823 if self.treat_err_as_bug() {
827 let _ = self.fatal(&s);
829 let can_show_explain = self.emitter.should_show_explain();
830 let are_there_diagnostics = !self.emitted_diagnostic_codes.is_empty();
831 if can_show_explain && are_there_diagnostics {
832 let mut error_codes = self
833 .emitted_diagnostic_codes
835 .filter_map(|x| match &x {
836 DiagnosticId::Error(s) if registry.find_description(s).is_some() => {
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!("Some errors have detailed explanations: {}{}",
847 error_codes[..limit].join(", "),
848 if error_codes.len() > 9 { "..." } else { "." }));
849 self.failure(&format!("For more information about an error, try \
850 `rustc --explain {}`.",
853 self.failure(&format!("For more information about this error, try \
854 `rustc --explain {}`.",
861 fn err_count(&self) -> usize {
862 self.err_count + self.stashed_diagnostics.len()
865 fn has_errors(&self) -> bool {
868 fn has_errors_or_delayed_span_bugs(&self) -> bool {
869 self.has_errors() || !self.delayed_span_bugs.is_empty()
872 fn abort_if_errors_and_should_abort(&mut self) {
873 self.emit_stashed_diagnostics();
875 if self.has_errors() && !self.continue_after_error {
880 fn abort_if_errors(&mut self) {
881 self.emit_stashed_diagnostics();
883 if self.has_errors() {
888 fn span_bug(&mut self, sp: impl Into<MultiSpan>, msg: &str) -> ! {
889 self.emit_diag_at_span(Diagnostic::new(Bug, msg), sp);
893 fn emit_diag_at_span(&mut self, mut diag: Diagnostic, sp: impl Into<MultiSpan>) {
894 self.emit_diagnostic(diag.set_span(sp));
895 self.abort_if_errors_and_should_abort();
898 fn delay_span_bug(&mut self, sp: impl Into<MultiSpan>, msg: &str) {
899 if self.treat_err_as_bug() {
900 // FIXME: don't abort here if report_delayed_bugs is off
901 self.span_bug(sp, msg);
903 let mut diagnostic = Diagnostic::new(Level::Bug, msg);
904 diagnostic.set_span(sp.into());
905 self.delay_as_bug(diagnostic)
908 fn failure(&mut self, msg: &str) {
909 self.emit_diagnostic(&Diagnostic::new(FailureNote, msg));
912 fn fatal(&mut self, msg: &str) -> FatalError {
913 self.emit_error(Fatal, msg);
917 fn err(&mut self, msg: &str) {
918 self.emit_error(Error, msg);
921 /// Emit an error; level should be `Error` or `Fatal`.
922 fn emit_error(&mut self, level: Level, msg: &str,) {
923 if self.treat_err_as_bug() {
926 self.emit_diagnostic(&Diagnostic::new(level, msg));
929 fn bug(&mut self, msg: &str) -> ! {
930 self.emit_diagnostic(&Diagnostic::new(Bug, msg));
934 fn delay_as_bug(&mut self, diagnostic: Diagnostic) {
935 if self.flags.report_delayed_bugs {
936 self.emit_diagnostic(&diagnostic);
938 self.delayed_span_bugs.push(diagnostic);
941 fn bump_err_count(&mut self) {
943 self.panic_if_treat_err_as_bug();
946 fn panic_if_treat_err_as_bug(&self) {
947 if self.treat_err_as_bug() {
948 let s = match (self.err_count(), self.flags.treat_err_as_bug.unwrap_or(0)) {
950 (1, 1) => "aborting due to `-Z treat-err-as-bug=1`".to_string(),
954 "aborting after {} errors due to `-Z treat-err-as-bug={}`",
965 #[derive(Copy, PartialEq, Clone, Hash, Debug, RustcEncodable, RustcDecodable)]
977 impl fmt::Display for Level {
978 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
984 fn color(self) -> ColorSpec {
985 let mut spec = ColorSpec::new();
987 Bug | Fatal | Error => {
988 spec.set_fg(Some(Color::Red))
992 spec.set_fg(Some(Color::Yellow))
993 .set_intense(cfg!(windows));
996 spec.set_fg(Some(Color::Green))
1000 spec.set_fg(Some(Color::Cyan))
1004 Cancelled => unreachable!(),
1009 pub fn to_str(self) -> &'static str {
1011 Bug => "error: internal compiler error",
1012 Fatal | Error => "error",
1013 Warning => "warning",
1016 FailureNote => "failure-note",
1017 Cancelled => panic!("Shouldn't call on cancelled error"),
1021 pub fn is_failure_note(&self) -> bool {
1023 FailureNote => true,
1030 macro_rules! pluralise {
1032 if $x != 1 { "s" } else { "" }