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 #[cfg(target_arch = "x86_64")]
19 use rustc_data_structures::static_assert_size;
20 use rustc_data_structures::sync::{self, Lrc, Lock};
21 use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
22 use rustc_data_structures::stable_hasher::StableHasher;
26 use std::{error, fmt};
30 use termcolor::{ColorSpec, Color};
33 mod diagnostic_builder;
35 pub mod annotate_snippet_emitter_writer;
52 pub type PResult<'a, T> = Result<T, DiagnosticBuilder<'a>>;
54 // `PResult` is used a lot. Make sure it doesn't unintentionally get bigger.
55 // (See also the comment on `DiagnosticBuilderInner`.)
56 #[cfg(target_arch = "x86_64")]
57 static_assert_size!(PResult<'_, bool>, 16);
59 /// Indicates the confidence in the correctness of a suggestion.
61 /// All suggestions are marked with an `Applicability`. Tools use the applicability of a suggestion
62 /// to determine whether it should be automatically applied or if the user should be consulted
63 /// before applying the suggestion.
64 #[derive(Copy, Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
65 pub enum Applicability {
66 /// The suggestion is definitely what the user intended. This suggestion should be
67 /// automatically applied.
70 /// The suggestion may be what the user intended, but it is uncertain. The suggestion should
71 /// result in valid Rust code if it is applied.
74 /// The suggestion contains placeholders like `(...)` or `{ /* fields */ }`. The suggestion
75 /// cannot be applied automatically because it will not result in valid Rust code. The user
76 /// will need to fill in the placeholders.
79 /// The applicability of the suggestion is unknown.
83 #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, RustcEncodable, RustcDecodable)]
84 pub enum SuggestionStyle {
85 /// Hide the suggested code when displaying this suggestion inline.
87 /// Always hide the suggested code but display the message.
89 /// Do not display this suggestion in the cli output, it is only meant for tools.
91 /// Always show the suggested code.
92 /// This will *not* show the code if the suggestion is inline *and* the suggested code is
95 /// Always show the suggested code independently.
99 impl SuggestionStyle {
100 fn hide_inline(&self) -> bool {
102 SuggestionStyle::ShowCode => false,
108 #[derive(Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
109 pub struct CodeSuggestion {
110 /// Each substitute can have multiple variants due to multiple
111 /// applicable suggestions
113 /// `foo.bar` might be replaced with `a.b` or `x.y` by replacing
114 /// `foo` and `bar` on their own:
118 /// Substitution { parts: vec![(0..3, "a"), (4..7, "b")] },
119 /// Substitution { parts: vec![(0..3, "x"), (4..7, "y")] },
123 /// or by replacing the entire span:
127 /// Substitution { parts: vec![(0..7, "a.b")] },
128 /// Substitution { parts: vec![(0..7, "x.y")] },
131 pub substitutions: Vec<Substitution>,
133 /// Visual representation of this suggestion.
134 pub style: SuggestionStyle,
135 /// Whether or not the suggestion is approximate
137 /// Sometimes we may show suggestions with placeholders,
138 /// which are useful for users but not useful for
139 /// tools like rustfix
140 pub applicability: Applicability,
143 #[derive(Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
144 /// See the docs on `CodeSuggestion::substitutions`
145 pub struct Substitution {
146 pub parts: Vec<SubstitutionPart>,
149 #[derive(Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
150 pub struct SubstitutionPart {
155 pub type SourceMapperDyn = dyn SourceMapper + sync::Send + sync::Sync;
157 pub trait SourceMapper {
158 fn lookup_char_pos(&self, pos: BytePos) -> Loc;
159 fn span_to_lines(&self, sp: Span) -> FileLinesResult;
160 fn span_to_string(&self, sp: Span) -> String;
161 fn span_to_snippet(&self, sp: Span) -> Result<String, SpanSnippetError>;
162 fn span_to_filename(&self, sp: Span) -> FileName;
163 fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option<Span>;
164 fn call_span_if_macro(&self, sp: Span) -> Span;
165 fn ensure_source_file_source_present(&self, source_file: Lrc<SourceFile>) -> bool;
166 fn doctest_offset_line(&self, file: &FileName, line: usize) -> usize;
169 impl CodeSuggestion {
170 /// Returns the assembled code suggestions, whether they should be shown with an underline
171 /// and whether the substitution only differs in capitalization.
174 cm: &SourceMapperDyn,
175 ) -> Vec<(String, Vec<SubstitutionPart>, bool)> {
176 use syntax_pos::{CharPos, Pos};
178 fn push_trailing(buf: &mut String,
179 line_opt: Option<&Cow<'_, str>>,
181 hi_opt: Option<&Loc>) {
182 let (lo, hi_opt) = (lo.col.to_usize(), hi_opt.map(|hi| hi.col.to_usize()));
183 if let Some(line) = line_opt {
184 if let Some(lo) = line.char_indices().map(|(i, _)| i).nth(lo) {
185 let hi_opt = hi_opt.and_then(|hi| line.char_indices().map(|(i, _)| i).nth(hi));
187 Some(hi) if hi > lo => buf.push_str(&line[lo..hi]),
189 None => buf.push_str(&line[lo..]),
192 if let None = hi_opt {
198 assert!(!self.substitutions.is_empty());
200 self.substitutions.iter().cloned().map(|mut substitution| {
201 // Assumption: all spans are in the same file, and all spans
202 // are disjoint. Sort in ascending order.
203 substitution.parts.sort_by_key(|part| part.span.lo());
205 // Find the bounding span.
206 let lo = substitution.parts.iter().map(|part| part.span.lo()).min().unwrap();
207 let hi = substitution.parts.iter().map(|part| part.span.hi()).min().unwrap();
208 let bounding_span = Span::with_root_ctxt(lo, hi);
209 let lines = cm.span_to_lines(bounding_span).unwrap();
210 assert!(!lines.lines.is_empty());
212 // To build up the result, we do this for each span:
213 // - push the line segment trailing the previous span
214 // (at the beginning a "phantom" span pointing at the start of the line)
215 // - push lines between the previous and current span (if any)
216 // - if the previous and current span are not on the same line
217 // push the line segment leading up to the current span
218 // - splice in the span substitution
220 // Finally push the trailing line segment of the last span
221 let fm = &lines.file;
222 let mut prev_hi = cm.lookup_char_pos(bounding_span.lo());
223 prev_hi.col = CharPos::from_usize(0);
225 let mut prev_line = fm.get_line(lines.lines[0].line_index);
226 let mut buf = String::new();
228 for part in &substitution.parts {
229 let cur_lo = cm.lookup_char_pos(part.span.lo());
230 if prev_hi.line == cur_lo.line {
231 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, Some(&cur_lo));
233 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
234 // push lines between the previous and current span (if any)
235 for idx in prev_hi.line..(cur_lo.line - 1) {
236 if let Some(line) = fm.get_line(idx) {
237 buf.push_str(line.as_ref());
241 if let Some(cur_line) = fm.get_line(cur_lo.line - 1) {
242 let end = std::cmp::min(cur_line.len(), cur_lo.col.to_usize());
243 buf.push_str(&cur_line[..end]);
246 buf.push_str(&part.snippet);
247 prev_hi = cm.lookup_char_pos(part.span.hi());
248 prev_line = fm.get_line(prev_hi.line - 1);
250 let only_capitalization = is_case_difference(cm, &buf, bounding_span);
251 // if the replacement already ends with a newline, don't print the next line
252 if !buf.ends_with('\n') {
253 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
255 // remove trailing newlines
256 while buf.ends_with('\n') {
259 (buf, substitution.parts, only_capitalization)
264 /// Used as a return value to signify a fatal error occurred. (It is also
265 /// used as the argument to panic at the moment, but that will eventually
267 #[derive(Copy, Clone, Debug)]
269 pub struct FatalError;
271 pub struct FatalErrorMarker;
273 // Don't implement Send on FatalError. This makes it impossible to panic!(FatalError).
274 // We don't want to invoke the panic handler and print a backtrace for fatal errors.
275 impl !Send for FatalError {}
278 pub fn raise(self) -> ! {
279 panic::resume_unwind(Box::new(FatalErrorMarker))
283 impl fmt::Display for FatalError {
284 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
285 write!(f, "parser fatal error")
289 impl error::Error for FatalError {
290 fn description(&self) -> &str {
291 "The parser has encountered a fatal error"
295 /// Signifies that the compiler died with an explicit call to `.bug`
296 /// or `.span_bug` rather than a failed assertion, etc.
297 #[derive(Copy, Clone, Debug)]
298 pub struct ExplicitBug;
300 impl fmt::Display for ExplicitBug {
301 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
302 write!(f, "parser internal bug")
306 impl error::Error for ExplicitBug {
307 fn description(&self) -> &str {
308 "The parser has encountered an internal bug"
312 pub use diagnostic::{Diagnostic, SubDiagnostic, DiagnosticStyledString, DiagnosticId};
313 pub use diagnostic_builder::DiagnosticBuilder;
315 /// A handler deals with errors and other compiler output.
316 /// Certain errors (fatal, bug, unimpl) may cause immediate exit,
317 /// others log errors for later reporting.
320 inner: Lock<HandlerInner>,
323 /// This inner struct exists to keep it all behind a single lock;
324 /// this is done to prevent possible deadlocks in a multi-threaded compiler,
325 /// as well as inconsistent state observation.
326 struct HandlerInner {
328 /// The number of errors that have been emitted, including duplicates.
330 /// This is not necessarily the count that's reported to the user once
331 /// compilation ends.
333 deduplicated_err_count: usize,
334 emitter: Box<dyn Emitter + sync::Send>,
335 continue_after_error: bool,
336 delayed_span_bugs: Vec<Diagnostic>,
338 /// This set contains the `DiagnosticId` of all emitted diagnostics to avoid
339 /// emitting the same diagnostic with extended help (`--teach`) twice, which
340 /// would be uneccessary repetition.
341 taught_diagnostics: FxHashSet<DiagnosticId>,
343 /// Used to suggest rustc --explain <error code>
344 emitted_diagnostic_codes: FxHashSet<DiagnosticId>,
346 /// This set contains a hash of every diagnostic that has been emitted by
347 /// this handler. These hashes is used to avoid emitting the same error
349 emitted_diagnostics: FxHashSet<u128>,
351 /// Stashed diagnostics emitted in one stage of the compiler that may be
352 /// stolen by other stages (e.g. to improve them and add more information).
353 /// The stashed diagnostics count towards the total error count.
354 /// When `.abort_if_errors()` is called, these are also emitted.
355 stashed_diagnostics: FxIndexMap<(Span, StashKey), Diagnostic>,
358 /// A key denoting where from a diagnostic was stashed.
359 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
364 fn default_track_diagnostic(_: &Diagnostic) {}
366 thread_local!(pub static TRACK_DIAGNOSTICS: Cell<fn(&Diagnostic)> =
367 Cell::new(default_track_diagnostic));
369 #[derive(Copy, Clone, Default)]
370 pub struct HandlerFlags {
371 /// If false, warning-level lints are suppressed.
372 /// (rustc: see `--allow warnings` and `--cap-lints`)
373 pub can_emit_warnings: bool,
374 /// If true, error-level diagnostics are upgraded to bug-level.
375 /// (rustc: see `-Z treat-err-as-bug`)
376 pub treat_err_as_bug: Option<usize>,
377 /// If true, immediately emit diagnostics that would otherwise be buffered.
378 /// (rustc: see `-Z dont-buffer-diagnostics` and `-Z treat-err-as-bug`)
379 pub dont_buffer_diagnostics: bool,
380 /// If true, immediately print bugs registered with `delay_span_bug`.
381 /// (rustc: see `-Z report-delayed-bugs`)
382 pub report_delayed_bugs: bool,
383 /// show macro backtraces even for non-local macros.
384 /// (rustc: see `-Z external-macro-backtrace`)
385 pub external_macro_backtrace: bool,
388 impl Drop for HandlerInner {
390 self.emit_stashed_diagnostics();
392 if !self.has_errors() {
393 let bugs = std::mem::replace(&mut self.delayed_span_bugs, Vec::new());
394 let has_bugs = !bugs.is_empty();
396 self.emit_diagnostic(&bug);
399 panic!("no errors encountered even though `delay_span_bug` issued");
406 pub fn with_tty_emitter(
407 color_config: ColorConfig,
408 can_emit_warnings: bool,
409 treat_err_as_bug: Option<usize>,
410 cm: Option<Lrc<SourceMapperDyn>>,
412 Self::with_tty_emitter_and_flags(
418 .. Default::default()
423 pub fn with_tty_emitter_and_flags(
424 color_config: ColorConfig,
425 cm: Option<Lrc<SourceMapperDyn>>,
428 let emitter = Box::new(EmitterWriter::stderr(
434 flags.external_macro_backtrace,
436 Self::with_emitter_and_flags(emitter, flags)
440 can_emit_warnings: bool,
441 treat_err_as_bug: Option<usize>,
442 emitter: Box<dyn Emitter + sync::Send>,
444 Handler::with_emitter_and_flags(
449 .. Default::default()
454 pub fn with_emitter_and_flags(
455 emitter: Box<dyn Emitter + sync::Send>,
460 inner: Lock::new(HandlerInner {
463 deduplicated_err_count: 0,
465 continue_after_error: true,
466 delayed_span_bugs: Vec::new(),
467 taught_diagnostics: Default::default(),
468 emitted_diagnostic_codes: Default::default(),
469 emitted_diagnostics: Default::default(),
470 stashed_diagnostics: Default::default(),
475 pub fn set_continue_after_error(&self, continue_after_error: bool) {
476 self.inner.borrow_mut().continue_after_error = continue_after_error;
479 // This is here to not allow mutation of flags;
480 // as of this writing it's only used in tests in librustc.
481 pub fn can_emit_warnings(&self) -> bool {
482 self.flags.can_emit_warnings
485 /// Resets the diagnostic error count as well as the cached emitted diagnostics.
487 /// NOTE: *do not* call this function from rustc. It is only meant to be called from external
488 /// tools that want to reuse a `Parser` cleaning the previously emitted diagnostics as well as
489 /// the overall count of emitted error diagnostics.
490 pub fn reset_err_count(&self) {
491 let mut inner = self.inner.borrow_mut();
493 inner.deduplicated_err_count = 0;
495 // actually free the underlying memory (which `clear` would not do)
496 inner.delayed_span_bugs = Default::default();
497 inner.taught_diagnostics = Default::default();
498 inner.emitted_diagnostic_codes = Default::default();
499 inner.emitted_diagnostics = Default::default();
500 inner.stashed_diagnostics = Default::default();
503 /// Stash a given diagnostic with the given `Span` and `StashKey` as the key for later stealing.
504 /// If the diagnostic with this `(span, key)` already exists, this will result in an ICE.
505 pub fn stash_diagnostic(&self, span: Span, key: StashKey, diag: Diagnostic) {
506 let mut inner = self.inner.borrow_mut();
507 if let Some(mut old_diag) = inner.stashed_diagnostics.insert((span, key), diag) {
508 // We are removing a previously stashed diagnostic which should not happen.
509 old_diag.level = Bug;
510 old_diag.note(&format!(
511 "{}:{}: already existing stashed diagnostic with (span = {:?}, key = {:?})",
512 file!(), line!(), span, key
514 inner.emit_diag_at_span(old_diag, span);
519 /// Steal a previously stashed diagnostic with the given `Span` and `StashKey` as the key.
520 pub fn steal_diagnostic(&self, span: Span, key: StashKey) -> Option<DiagnosticBuilder<'_>> {
524 .remove(&(span, key))
525 .map(|diag| DiagnosticBuilder::new_diagnostic(self, diag))
528 /// Emit all stashed diagnostics.
529 pub fn emit_stashed_diagnostics(&self) {
530 self.inner.borrow_mut().emit_stashed_diagnostics();
533 /// Construct a dummy builder with `Level::Cancelled`.
535 /// Using this will neither report anything to the user (e.g. a warning),
536 /// nor will compilation cancel as a result.
537 pub fn struct_dummy(&self) -> DiagnosticBuilder<'_> {
538 DiagnosticBuilder::new(self, Level::Cancelled, "")
541 /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
542 pub fn struct_span_warn(&self, span: impl Into<MultiSpan>, msg: &str) -> DiagnosticBuilder<'_> {
543 let mut result = self.struct_warn(msg);
544 result.set_span(span);
548 /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
549 /// Also include a code.
550 pub fn struct_span_warn_with_code(
552 span: impl Into<MultiSpan>,
555 ) -> DiagnosticBuilder<'_> {
556 let mut result = self.struct_span_warn(span, msg);
561 /// Construct a builder at the `Warning` level with the `msg`.
562 pub fn struct_warn(&self, msg: &str) -> DiagnosticBuilder<'_> {
563 let mut result = DiagnosticBuilder::new(self, Level::Warning, msg);
564 if !self.flags.can_emit_warnings {
570 /// Construct a builder at the `Error` level at the given `span` and with the `msg`.
571 pub fn struct_span_err(&self, span: impl Into<MultiSpan>, msg: &str) -> DiagnosticBuilder<'_> {
572 let mut result = self.struct_err(msg);
573 result.set_span(span);
577 /// Construct a builder at the `Error` level at the given `span`, with the `msg`, and `code`.
578 pub fn struct_span_err_with_code(
580 span: impl Into<MultiSpan>,
583 ) -> DiagnosticBuilder<'_> {
584 let mut result = self.struct_span_err(span, msg);
589 /// Construct a builder at the `Error` level with the `msg`.
590 // FIXME: This method should be removed (every error should have an associated error code).
591 pub fn struct_err(&self, msg: &str) -> DiagnosticBuilder<'_> {
592 DiagnosticBuilder::new(self, Level::Error, msg)
595 /// Construct a builder at the `Error` level with the `msg` and the `code`.
596 pub fn struct_err_with_code(&self, msg: &str, code: DiagnosticId) -> DiagnosticBuilder<'_> {
597 let mut result = self.struct_err(msg);
602 /// Construct a builder at the `Fatal` level at the given `span` and with the `msg`.
603 pub fn struct_span_fatal(
605 span: impl Into<MultiSpan>,
607 ) -> DiagnosticBuilder<'_> {
608 let mut result = self.struct_fatal(msg);
609 result.set_span(span);
613 /// Construct a builder at the `Fatal` level at the given `span`, with the `msg`, and `code`.
614 pub fn struct_span_fatal_with_code(
616 span: impl Into<MultiSpan>,
619 ) -> DiagnosticBuilder<'_> {
620 let mut result = self.struct_span_fatal(span, msg);
625 /// Construct a builder at the `Error` level with the `msg`.
626 pub fn struct_fatal(&self, msg: &str) -> DiagnosticBuilder<'_> {
627 DiagnosticBuilder::new(self, Level::Fatal, msg)
630 pub fn span_fatal(&self, span: impl Into<MultiSpan>, msg: &str) -> FatalError {
631 self.emit_diag_at_span(Diagnostic::new(Fatal, msg), span);
635 pub fn span_fatal_with_code(
637 span: impl Into<MultiSpan>,
641 self.emit_diag_at_span(Diagnostic::new_with_code(Fatal, Some(code), msg), span);
645 pub fn span_err(&self, span: impl Into<MultiSpan>, msg: &str) {
646 self.emit_diag_at_span(Diagnostic::new(Error, msg), span);
649 pub fn span_err_with_code(&self, span: impl Into<MultiSpan>, msg: &str, code: DiagnosticId) {
650 self.emit_diag_at_span(Diagnostic::new_with_code(Error, Some(code), msg), span);
653 pub fn span_warn(&self, span: impl Into<MultiSpan>, msg: &str) {
654 self.emit_diag_at_span(Diagnostic::new(Warning, msg), span);
657 pub fn span_warn_with_code(&self, span: impl Into<MultiSpan>, msg: &str, code: DiagnosticId) {
658 self.emit_diag_at_span(Diagnostic::new_with_code(Warning, Some(code), msg), span);
661 pub fn span_bug(&self, span: impl Into<MultiSpan>, msg: &str) -> ! {
662 self.inner.borrow_mut().span_bug(span, msg)
665 pub fn delay_span_bug(&self, span: impl Into<MultiSpan>, msg: &str) {
666 self.inner.borrow_mut().delay_span_bug(span, msg)
669 pub fn span_bug_no_panic(&self, span: impl Into<MultiSpan>, msg: &str) {
670 self.emit_diag_at_span(Diagnostic::new(Bug, msg), span);
673 pub fn span_note_without_error(&self, span: impl Into<MultiSpan>, msg: &str) {
674 self.emit_diag_at_span(Diagnostic::new(Note, msg), span);
677 pub fn span_note_diag(&self, span: Span, msg: &str) -> DiagnosticBuilder<'_> {
678 let mut db = DiagnosticBuilder::new(self, Note, msg);
683 pub fn failure(&self, msg: &str) {
684 self.inner.borrow_mut().failure(msg);
687 pub fn fatal(&self, msg: &str) -> FatalError {
688 self.inner.borrow_mut().fatal(msg)
691 pub fn err(&self, msg: &str) {
692 self.inner.borrow_mut().err(msg);
695 pub fn warn(&self, msg: &str) {
696 let mut db = DiagnosticBuilder::new(self, Warning, msg);
700 pub fn note_without_error(&self, msg: &str) {
701 DiagnosticBuilder::new(self, Note, msg).emit();
704 pub fn bug(&self, msg: &str) -> ! {
705 self.inner.borrow_mut().bug(msg)
708 pub fn err_count(&self) -> usize {
709 self.inner.borrow().err_count()
712 pub fn has_errors(&self) -> bool {
713 self.inner.borrow().has_errors()
715 pub fn has_errors_or_delayed_span_bugs(&self) -> bool {
716 self.inner.borrow().has_errors_or_delayed_span_bugs()
719 pub fn print_error_count(&self, registry: &Registry) {
720 self.inner.borrow_mut().print_error_count(registry)
723 pub fn abort_if_errors(&self) {
724 self.inner.borrow_mut().abort_if_errors()
727 pub fn abort_if_errors_and_should_abort(&self) {
728 self.inner.borrow_mut().abort_if_errors_and_should_abort()
731 /// `true` if we haven't taught a diagnostic with this code already.
732 /// The caller must then teach the user about such a diagnostic.
734 /// Used to suppress emitting the same error multiple times with extended explanation when
735 /// calling `-Zteach`.
736 pub fn must_teach(&self, code: &DiagnosticId) -> bool {
737 self.inner.borrow_mut().must_teach(code)
740 pub fn force_print_diagnostic(&self, db: Diagnostic) {
741 self.inner.borrow_mut().force_print_diagnostic(db)
744 pub fn emit_diagnostic(&self, diagnostic: &Diagnostic) {
745 self.inner.borrow_mut().emit_diagnostic(diagnostic)
748 fn emit_diag_at_span(&self, mut diag: Diagnostic, sp: impl Into<MultiSpan>) {
749 let mut inner = self.inner.borrow_mut();
750 inner.emit_diagnostic(diag.set_span(sp));
751 inner.abort_if_errors_and_should_abort();
754 pub fn emit_artifact_notification(&self, path: &Path, artifact_type: &str) {
755 self.inner.borrow_mut().emit_artifact_notification(path, artifact_type)
758 pub fn delay_as_bug(&self, diagnostic: Diagnostic) {
759 self.inner.borrow_mut().delay_as_bug(diagnostic)
764 fn must_teach(&mut self, code: &DiagnosticId) -> bool {
765 self.taught_diagnostics.insert(code.clone())
768 fn force_print_diagnostic(&mut self, db: Diagnostic) {
769 self.emitter.emit_diagnostic(&db);
772 /// Emit all stashed diagnostics.
773 fn emit_stashed_diagnostics(&mut self) {
774 let diags = self.stashed_diagnostics.drain(..).map(|x| x.1).collect::<Vec<_>>();
775 diags.iter().for_each(|diag| self.emit_diagnostic(diag));
778 fn emit_diagnostic(&mut self, diagnostic: &Diagnostic) {
779 if diagnostic.cancelled() {
783 if diagnostic.level == Warning && !self.flags.can_emit_warnings {
787 TRACK_DIAGNOSTICS.with(|track_diagnostics| {
788 track_diagnostics.get()(diagnostic);
791 if let Some(ref code) = diagnostic.code {
792 self.emitted_diagnostic_codes.insert(code.clone());
795 let diagnostic_hash = {
797 let mut hasher = StableHasher::new();
798 diagnostic.hash(&mut hasher);
802 // Only emit the diagnostic if we haven't already emitted an equivalent
804 if self.emitted_diagnostics.insert(diagnostic_hash) {
805 self.emitter.emit_diagnostic(diagnostic);
806 if diagnostic.is_error() {
807 self.deduplicated_err_count += 1;
810 if diagnostic.is_error() {
811 self.bump_err_count();
815 fn emit_artifact_notification(&mut self, path: &Path, artifact_type: &str) {
816 self.emitter.emit_artifact_notification(path, artifact_type);
819 fn treat_err_as_bug(&self) -> bool {
820 self.flags.treat_err_as_bug.map(|c| self.err_count() >= c).unwrap_or(false)
823 fn print_error_count(&mut self, registry: &Registry) {
824 self.emit_stashed_diagnostics();
826 let s = match self.deduplicated_err_count {
828 1 => "aborting due to previous error".to_string(),
829 count => format!("aborting due to {} previous errors", count)
831 if self.treat_err_as_bug() {
835 let _ = self.fatal(&s);
837 let can_show_explain = self.emitter.should_show_explain();
838 let are_there_diagnostics = !self.emitted_diagnostic_codes.is_empty();
839 if can_show_explain && are_there_diagnostics {
840 let mut error_codes = self
841 .emitted_diagnostic_codes
843 .filter_map(|x| match &x {
844 DiagnosticId::Error(s) if registry.find_description(s).is_some() => {
849 .collect::<Vec<_>>();
850 if !error_codes.is_empty() {
852 if error_codes.len() > 1 {
853 let limit = if error_codes.len() > 9 { 9 } else { error_codes.len() };
854 self.failure(&format!("Some errors have detailed explanations: {}{}",
855 error_codes[..limit].join(", "),
856 if error_codes.len() > 9 { "..." } else { "." }));
857 self.failure(&format!("For more information about an error, try \
858 `rustc --explain {}`.",
861 self.failure(&format!("For more information about this error, try \
862 `rustc --explain {}`.",
869 fn err_count(&self) -> usize {
870 self.err_count + self.stashed_diagnostics.len()
873 fn has_errors(&self) -> bool {
876 fn has_errors_or_delayed_span_bugs(&self) -> bool {
877 self.has_errors() || !self.delayed_span_bugs.is_empty()
880 fn abort_if_errors_and_should_abort(&mut self) {
881 self.emit_stashed_diagnostics();
883 if self.has_errors() && !self.continue_after_error {
888 fn abort_if_errors(&mut self) {
889 self.emit_stashed_diagnostics();
891 if self.has_errors() {
896 fn span_bug(&mut self, sp: impl Into<MultiSpan>, msg: &str) -> ! {
897 self.emit_diag_at_span(Diagnostic::new(Bug, msg), sp);
901 fn emit_diag_at_span(&mut self, mut diag: Diagnostic, sp: impl Into<MultiSpan>) {
902 self.emit_diagnostic(diag.set_span(sp));
903 self.abort_if_errors_and_should_abort();
906 fn delay_span_bug(&mut self, sp: impl Into<MultiSpan>, msg: &str) {
907 if self.treat_err_as_bug() {
908 // FIXME: don't abort here if report_delayed_bugs is off
909 self.span_bug(sp, msg);
911 let mut diagnostic = Diagnostic::new(Level::Bug, msg);
912 diagnostic.set_span(sp.into());
913 self.delay_as_bug(diagnostic)
916 fn failure(&mut self, msg: &str) {
917 self.emit_diagnostic(&Diagnostic::new(FailureNote, msg));
920 fn fatal(&mut self, msg: &str) -> FatalError {
921 self.emit_error(Fatal, msg);
925 fn err(&mut self, msg: &str) {
926 self.emit_error(Error, msg);
929 /// Emit an error; level should be `Error` or `Fatal`.
930 fn emit_error(&mut self, level: Level, msg: &str,) {
931 if self.treat_err_as_bug() {
934 self.emit_diagnostic(&Diagnostic::new(level, msg));
937 fn bug(&mut self, msg: &str) -> ! {
938 self.emit_diagnostic(&Diagnostic::new(Bug, msg));
942 fn delay_as_bug(&mut self, diagnostic: Diagnostic) {
943 if self.flags.report_delayed_bugs {
944 self.emit_diagnostic(&diagnostic);
946 self.delayed_span_bugs.push(diagnostic);
949 fn bump_err_count(&mut self) {
951 self.panic_if_treat_err_as_bug();
954 fn panic_if_treat_err_as_bug(&self) {
955 if self.treat_err_as_bug() {
956 let s = match (self.err_count(), self.flags.treat_err_as_bug.unwrap_or(0)) {
958 (1, 1) => "aborting due to `-Z treat-err-as-bug=1`".to_string(),
962 "aborting after {} errors due to `-Z treat-err-as-bug={}`",
973 #[derive(Copy, PartialEq, Clone, Hash, Debug, RustcEncodable, RustcDecodable)]
985 impl fmt::Display for Level {
986 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
992 fn color(self) -> ColorSpec {
993 let mut spec = ColorSpec::new();
995 Bug | Fatal | Error => {
996 spec.set_fg(Some(Color::Red))
1000 spec.set_fg(Some(Color::Yellow))
1001 .set_intense(cfg!(windows));
1004 spec.set_fg(Some(Color::Green))
1008 spec.set_fg(Some(Color::Cyan))
1012 Cancelled => unreachable!(),
1017 pub fn to_str(self) -> &'static str {
1019 Bug => "error: internal compiler error",
1020 Fatal | Error => "error",
1021 Warning => "warning",
1024 FailureNote => "failure-note",
1025 Cancelled => panic!("Shouldn't call on cancelled error"),
1029 pub fn is_failure_note(&self) -> bool {
1031 FailureNote => true,
1038 macro_rules! pluralize {
1040 if $x != 1 { "s" } else { "" }