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/nightly-rustc/")]
6 #![feature(crate_visibility_modifier)]
8 #![feature(format_args_capture)]
13 extern crate rustc_macros;
15 pub use emitter::ColorConfig;
20 use emitter::{is_case_difference, Emitter, EmitterWriter};
21 use registry::Registry;
22 use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
23 use rustc_data_structures::stable_hasher::StableHasher;
24 use rustc_data_structures::sync::{self, Lock, Lrc};
25 use rustc_data_structures::AtomicRef;
26 pub use rustc_lint_defs::{pluralize, Applicability};
27 use rustc_serialize::json::Json;
28 use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
29 use rustc_span::source_map::SourceMap;
30 use rustc_span::{Loc, MultiSpan, Span};
33 use std::hash::{Hash, Hasher};
34 use std::num::NonZeroUsize;
37 use std::{error, fmt};
39 use termcolor::{Color, ColorSpec};
41 pub mod annotate_snippet_emitter_writer;
43 mod diagnostic_builder;
50 pub use snippet::Style;
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(all(target_arch = "x86_64", target_pointer_width = "64"))]
57 rustc_data_structures::static_assert_size!(PResult<'_, bool>, 16);
59 #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, Encodable, Decodable)]
60 pub enum SuggestionStyle {
61 /// Hide the suggested code when displaying this suggestion inline.
63 /// Always hide the suggested code but display the message.
65 /// Do not display this suggestion in the cli output, it is only meant for tools.
67 /// Always show the suggested code.
68 /// This will *not* show the code if the suggestion is inline *and* the suggested code is
71 /// Always show the suggested code independently.
75 impl SuggestionStyle {
76 fn hide_inline(&self) -> bool {
77 !matches!(*self, SuggestionStyle::ShowCode)
81 #[derive(Clone, Debug, PartialEq, Default)]
82 pub struct ToolMetadata(pub Option<Json>);
85 fn new(json: Json) -> Self {
86 ToolMetadata(Some(json))
89 fn is_set(&self) -> bool {
94 impl Hash for ToolMetadata {
95 fn hash<H: Hasher>(&self, _state: &mut H) {}
98 // Doesn't really need to round-trip
99 impl<D: Decoder> Decodable<D> for ToolMetadata {
100 fn decode(_d: &mut D) -> Result<Self, D::Error> {
101 Ok(ToolMetadata(None))
105 impl<S: Encoder> Encodable<S> for ToolMetadata {
106 fn encode(&self, e: &mut S) -> Result<(), S::Error> {
108 None => e.emit_unit(),
109 Some(json) => json.encode(e),
114 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
115 pub struct CodeSuggestion {
116 /// Each substitute can have multiple variants due to multiple
117 /// applicable suggestions
119 /// `foo.bar` might be replaced with `a.b` or `x.y` by replacing
120 /// `foo` and `bar` on their own:
124 /// Substitution { parts: vec![(0..3, "a"), (4..7, "b")] },
125 /// Substitution { parts: vec![(0..3, "x"), (4..7, "y")] },
129 /// or by replacing the entire span:
133 /// Substitution { parts: vec![(0..7, "a.b")] },
134 /// Substitution { parts: vec![(0..7, "x.y")] },
137 pub substitutions: Vec<Substitution>,
139 /// Visual representation of this suggestion.
140 pub style: SuggestionStyle,
141 /// Whether or not the suggestion is approximate
143 /// Sometimes we may show suggestions with placeholders,
144 /// which are useful for users but not useful for
145 /// tools like rustfix
146 pub applicability: Applicability,
147 /// Tool-specific metadata
148 pub tool_metadata: ToolMetadata,
151 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
152 /// See the docs on `CodeSuggestion::substitutions`
153 pub struct Substitution {
154 pub parts: Vec<SubstitutionPart>,
157 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
158 pub struct SubstitutionPart {
163 impl CodeSuggestion {
164 /// Returns the assembled code suggestions, whether they should be shown with an underline
165 /// and whether the substitution only differs in capitalization.
166 pub fn splice_lines(&self, sm: &SourceMap) -> Vec<(String, Vec<SubstitutionPart>, bool)> {
167 use rustc_span::{CharPos, Pos};
171 line_opt: Option<&Cow<'_, str>>,
173 hi_opt: Option<&Loc>,
175 let (lo, hi_opt) = (lo.col.to_usize(), hi_opt.map(|hi| hi.col.to_usize()));
176 if let Some(line) = line_opt {
177 if let Some(lo) = line.char_indices().map(|(i, _)| i).nth(lo) {
178 let hi_opt = hi_opt.and_then(|hi| line.char_indices().map(|(i, _)| i).nth(hi));
180 Some(hi) if hi > lo => buf.push_str(&line[lo..hi]),
182 None => buf.push_str(&line[lo..]),
185 if hi_opt.is_none() {
191 assert!(!self.substitutions.is_empty());
196 // Suggestions coming from macros can have malformed spans. This is a heavy
197 // handed approach to avoid ICEs by ignoring the suggestion outright.
198 let invalid = subst.parts.iter().any(|item| sm.is_valid_span(item.span).is_err());
200 debug!("splice_lines: suggestion contains an invalid span: {:?}", subst);
205 .filter_map(|mut substitution| {
206 // Assumption: all spans are in the same file, and all spans
207 // are disjoint. Sort in ascending order.
208 substitution.parts.sort_by_key(|part| part.span.lo());
210 // Find the bounding span.
211 let lo = substitution.parts.iter().map(|part| part.span.lo()).min()?;
212 let hi = substitution.parts.iter().map(|part| part.span.hi()).max()?;
213 let bounding_span = Span::with_root_ctxt(lo, hi);
214 // The different spans might belong to different contexts, if so ignore suggestion.
215 let lines = sm.span_to_lines(bounding_span).ok()?;
216 assert!(!lines.lines.is_empty() || bounding_span.is_dummy());
218 // We can't splice anything if the source is unavailable.
219 if !sm.ensure_source_file_source_present(lines.file.clone()) {
223 // To build up the result, we do this for each span:
224 // - push the line segment trailing the previous span
225 // (at the beginning a "phantom" span pointing at the start of the line)
226 // - push lines between the previous and current span (if any)
227 // - if the previous and current span are not on the same line
228 // push the line segment leading up to the current span
229 // - splice in the span substitution
231 // Finally push the trailing line segment of the last span
232 let sf = &lines.file;
233 let mut prev_hi = sm.lookup_char_pos(bounding_span.lo());
234 prev_hi.col = CharPos::from_usize(0);
236 lines.lines.get(0).and_then(|line0| sf.get_line(line0.line_index));
237 let mut buf = String::new();
239 for part in &substitution.parts {
240 let cur_lo = sm.lookup_char_pos(part.span.lo());
241 if prev_hi.line == cur_lo.line {
242 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, Some(&cur_lo));
244 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
245 // push lines between the previous and current span (if any)
246 for idx in prev_hi.line..(cur_lo.line - 1) {
247 if let Some(line) = sf.get_line(idx) {
248 buf.push_str(line.as_ref());
252 if let Some(cur_line) = sf.get_line(cur_lo.line - 1) {
253 let end = match cur_line.char_indices().nth(cur_lo.col.to_usize()) {
255 None => cur_line.len(),
257 buf.push_str(&cur_line[..end]);
260 buf.push_str(&part.snippet);
261 prev_hi = sm.lookup_char_pos(part.span.hi());
262 prev_line = sf.get_line(prev_hi.line - 1);
264 let only_capitalization = is_case_difference(sm, &buf, bounding_span);
265 // if the replacement already ends with a newline, don't print the next line
266 if !buf.ends_with('\n') {
267 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
269 // remove trailing newlines
270 while buf.ends_with('\n') {
273 Some((buf, substitution.parts, only_capitalization))
279 pub use rustc_span::fatal_error::{FatalError, FatalErrorMarker};
281 /// Signifies that the compiler died with an explicit call to `.bug`
282 /// or `.span_bug` rather than a failed assertion, etc.
283 #[derive(Copy, Clone, Debug)]
284 pub struct ExplicitBug;
286 impl fmt::Display for ExplicitBug {
287 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
288 write!(f, "parser internal bug")
292 impl error::Error for ExplicitBug {}
294 pub use diagnostic::{Diagnostic, DiagnosticId, DiagnosticStyledString, SubDiagnostic};
295 pub use diagnostic_builder::DiagnosticBuilder;
296 use std::backtrace::Backtrace;
298 /// A handler deals with errors and other compiler output.
299 /// Certain errors (fatal, bug, unimpl) may cause immediate exit,
300 /// others log errors for later reporting.
303 inner: Lock<HandlerInner>,
306 /// This inner struct exists to keep it all behind a single lock;
307 /// this is done to prevent possible deadlocks in a multi-threaded compiler,
308 /// as well as inconsistent state observation.
309 struct HandlerInner {
311 /// The number of errors that have been emitted, including duplicates.
313 /// This is not necessarily the count that's reported to the user once
314 /// compilation ends.
317 deduplicated_err_count: usize,
318 emitter: Box<dyn Emitter + sync::Send>,
319 delayed_span_bugs: Vec<Diagnostic>,
320 delayed_good_path_bugs: Vec<DelayedDiagnostic>,
322 /// This set contains the `DiagnosticId` of all emitted diagnostics to avoid
323 /// emitting the same diagnostic with extended help (`--teach`) twice, which
324 /// would be unnecessary repetition.
325 taught_diagnostics: FxHashSet<DiagnosticId>,
327 /// Used to suggest rustc --explain <error code>
328 emitted_diagnostic_codes: FxHashSet<DiagnosticId>,
330 /// This set contains a hash of every diagnostic that has been emitted by
331 /// this handler. These hashes is used to avoid emitting the same error
333 emitted_diagnostics: FxHashSet<u128>,
335 /// Stashed diagnostics emitted in one stage of the compiler that may be
336 /// stolen by other stages (e.g. to improve them and add more information).
337 /// The stashed diagnostics count towards the total error count.
338 /// When `.abort_if_errors()` is called, these are also emitted.
339 stashed_diagnostics: FxIndexMap<(Span, StashKey), Diagnostic>,
341 /// The warning count, used for a recap upon finishing
342 deduplicated_warn_count: usize,
344 future_breakage_diagnostics: Vec<Diagnostic>,
347 /// A key denoting where from a diagnostic was stashed.
348 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
353 fn default_track_diagnostic(_: &Diagnostic) {}
355 pub static TRACK_DIAGNOSTICS: AtomicRef<fn(&Diagnostic)> =
356 AtomicRef::new(&(default_track_diagnostic as fn(&_)));
358 #[derive(Copy, Clone, Default)]
359 pub struct HandlerFlags {
360 /// If false, warning-level lints are suppressed.
361 /// (rustc: see `--allow warnings` and `--cap-lints`)
362 pub can_emit_warnings: bool,
363 /// If true, error-level diagnostics are upgraded to bug-level.
364 /// (rustc: see `-Z treat-err-as-bug`)
365 pub treat_err_as_bug: Option<NonZeroUsize>,
366 /// If true, immediately emit diagnostics that would otherwise be buffered.
367 /// (rustc: see `-Z dont-buffer-diagnostics` and `-Z treat-err-as-bug`)
368 pub dont_buffer_diagnostics: bool,
369 /// If true, immediately print bugs registered with `delay_span_bug`.
370 /// (rustc: see `-Z report-delayed-bugs`)
371 pub report_delayed_bugs: bool,
372 /// Show macro backtraces.
373 /// (rustc: see `-Z macro-backtrace`)
374 pub macro_backtrace: bool,
375 /// If true, identical diagnostics are reported only once.
376 pub deduplicate_diagnostics: bool,
379 impl Drop for HandlerInner {
381 self.emit_stashed_diagnostics();
383 if !self.has_errors() {
384 let bugs = std::mem::replace(&mut self.delayed_span_bugs, Vec::new());
385 self.flush_delayed(bugs, "no errors encountered even though `delay_span_bug` issued");
388 if !self.has_any_message() {
389 let bugs = std::mem::replace(&mut self.delayed_good_path_bugs, Vec::new());
391 bugs.into_iter().map(DelayedDiagnostic::decorate).collect(),
392 "no warnings or errors encountered even though `delayed_good_path_bugs` issued",
399 pub fn with_tty_emitter(
400 color_config: ColorConfig,
401 can_emit_warnings: bool,
402 treat_err_as_bug: Option<NonZeroUsize>,
403 sm: Option<Lrc<SourceMap>>,
405 Self::with_tty_emitter_and_flags(
408 HandlerFlags { can_emit_warnings, treat_err_as_bug, ..Default::default() },
412 pub fn with_tty_emitter_and_flags(
413 color_config: ColorConfig,
414 sm: Option<Lrc<SourceMap>>,
417 let emitter = Box::new(EmitterWriter::stderr(
423 flags.macro_backtrace,
425 Self::with_emitter_and_flags(emitter, flags)
429 can_emit_warnings: bool,
430 treat_err_as_bug: Option<NonZeroUsize>,
431 emitter: Box<dyn Emitter + sync::Send>,
433 Handler::with_emitter_and_flags(
435 HandlerFlags { can_emit_warnings, treat_err_as_bug, ..Default::default() },
439 pub fn with_emitter_and_flags(
440 emitter: Box<dyn Emitter + sync::Send>,
445 inner: Lock::new(HandlerInner {
449 deduplicated_err_count: 0,
450 deduplicated_warn_count: 0,
452 delayed_span_bugs: Vec::new(),
453 delayed_good_path_bugs: Vec::new(),
454 taught_diagnostics: Default::default(),
455 emitted_diagnostic_codes: Default::default(),
456 emitted_diagnostics: Default::default(),
457 stashed_diagnostics: Default::default(),
458 future_breakage_diagnostics: Vec::new(),
463 // This is here to not allow mutation of flags;
464 // as of this writing it's only used in tests in librustc_middle.
465 pub fn can_emit_warnings(&self) -> bool {
466 self.flags.can_emit_warnings
469 /// Resets the diagnostic error count as well as the cached emitted diagnostics.
471 /// NOTE: *do not* call this function from rustc. It is only meant to be called from external
472 /// tools that want to reuse a `Parser` cleaning the previously emitted diagnostics as well as
473 /// the overall count of emitted error diagnostics.
474 pub fn reset_err_count(&self) {
475 let mut inner = self.inner.borrow_mut();
477 inner.warn_count = 0;
478 inner.deduplicated_err_count = 0;
479 inner.deduplicated_warn_count = 0;
481 // actually free the underlying memory (which `clear` would not do)
482 inner.delayed_span_bugs = Default::default();
483 inner.delayed_good_path_bugs = Default::default();
484 inner.taught_diagnostics = Default::default();
485 inner.emitted_diagnostic_codes = Default::default();
486 inner.emitted_diagnostics = Default::default();
487 inner.stashed_diagnostics = Default::default();
490 /// Stash a given diagnostic with the given `Span` and `StashKey` as the key for later stealing.
491 pub fn stash_diagnostic(&self, span: Span, key: StashKey, diag: Diagnostic) {
492 let mut inner = self.inner.borrow_mut();
493 // FIXME(Centril, #69537): Consider reintroducing panic on overwriting a stashed diagnostic
494 // if/when we have a more robust macro-friendly replacement for `(span, key)` as a key.
495 // See the PR for a discussion.
496 inner.stashed_diagnostics.insert((span, key), diag);
499 /// Steal a previously stashed diagnostic with the given `Span` and `StashKey` as the key.
500 pub fn steal_diagnostic(&self, span: Span, key: StashKey) -> Option<DiagnosticBuilder<'_>> {
504 .remove(&(span, key))
505 .map(|diag| DiagnosticBuilder::new_diagnostic(self, diag))
508 /// Emit all stashed diagnostics.
509 pub fn emit_stashed_diagnostics(&self) {
510 self.inner.borrow_mut().emit_stashed_diagnostics();
513 /// Construct a dummy builder with `Level::Cancelled`.
515 /// Using this will neither report anything to the user (e.g. a warning),
516 /// nor will compilation cancel as a result.
517 pub fn struct_dummy(&self) -> DiagnosticBuilder<'_> {
518 DiagnosticBuilder::new(self, Level::Cancelled, "")
521 /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
523 /// The builder will be canceled if warnings cannot be emitted.
524 pub fn struct_span_warn(&self, span: impl Into<MultiSpan>, msg: &str) -> DiagnosticBuilder<'_> {
525 let mut result = self.struct_warn(msg);
526 result.set_span(span);
530 /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
532 /// This will "force" the warning meaning it will not be canceled even
533 /// if warnings cannot be emitted.
534 pub fn struct_span_force_warn(
536 span: impl Into<MultiSpan>,
538 ) -> DiagnosticBuilder<'_> {
539 let mut result = self.struct_force_warn(msg);
540 result.set_span(span);
544 /// Construct a builder at the `Allow` level at the given `span` and with the `msg`.
545 pub fn struct_span_allow(
547 span: impl Into<MultiSpan>,
549 ) -> DiagnosticBuilder<'_> {
550 let mut result = self.struct_allow(msg);
551 result.set_span(span);
555 /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
556 /// Also include a code.
557 pub fn struct_span_warn_with_code(
559 span: impl Into<MultiSpan>,
562 ) -> DiagnosticBuilder<'_> {
563 let mut result = self.struct_span_warn(span, msg);
568 /// Construct a builder at the `Warning` level with the `msg`.
570 /// The builder will be canceled if warnings cannot be emitted.
571 pub fn struct_warn(&self, msg: &str) -> DiagnosticBuilder<'_> {
572 let mut result = DiagnosticBuilder::new(self, Level::Warning, msg);
573 if !self.flags.can_emit_warnings {
579 /// Construct a builder at the `Warning` level with the `msg`.
581 /// This will "force" a warning meaning it will not be canceled even
582 /// if warnings cannot be emitted.
583 pub fn struct_force_warn(&self, msg: &str) -> DiagnosticBuilder<'_> {
584 DiagnosticBuilder::new(self, Level::Warning, msg)
587 /// Construct a builder at the `Allow` level with the `msg`.
588 pub fn struct_allow(&self, msg: &str) -> DiagnosticBuilder<'_> {
589 DiagnosticBuilder::new(self, Level::Allow, msg)
592 /// Construct a builder at the `Error` level at the given `span` and with the `msg`.
593 pub fn struct_span_err(&self, span: impl Into<MultiSpan>, msg: &str) -> DiagnosticBuilder<'_> {
594 let mut result = self.struct_err(msg);
595 result.set_span(span);
599 /// Construct a builder at the `Error` level at the given `span`, with the `msg`, and `code`.
600 pub fn struct_span_err_with_code(
602 span: impl Into<MultiSpan>,
605 ) -> DiagnosticBuilder<'_> {
606 let mut result = self.struct_span_err(span, msg);
611 /// Construct a builder at the `Error` level with the `msg`.
612 // FIXME: This method should be removed (every error should have an associated error code).
613 pub fn struct_err(&self, msg: &str) -> DiagnosticBuilder<'_> {
614 DiagnosticBuilder::new(self, Level::Error, msg)
617 /// Construct a builder at the `Error` level with the `msg` and the `code`.
618 pub fn struct_err_with_code(&self, msg: &str, code: DiagnosticId) -> DiagnosticBuilder<'_> {
619 let mut result = self.struct_err(msg);
624 /// Construct a builder at the `Fatal` level at the given `span` and with the `msg`.
625 pub fn struct_span_fatal(
627 span: impl Into<MultiSpan>,
629 ) -> DiagnosticBuilder<'_> {
630 let mut result = self.struct_fatal(msg);
631 result.set_span(span);
635 /// Construct a builder at the `Fatal` level at the given `span`, with the `msg`, and `code`.
636 pub fn struct_span_fatal_with_code(
638 span: impl Into<MultiSpan>,
641 ) -> DiagnosticBuilder<'_> {
642 let mut result = self.struct_span_fatal(span, msg);
647 /// Construct a builder at the `Error` level with the `msg`.
648 pub fn struct_fatal(&self, msg: &str) -> DiagnosticBuilder<'_> {
649 DiagnosticBuilder::new(self, Level::Fatal, msg)
652 /// Construct a builder at the `Help` level with the `msg`.
653 pub fn struct_help(&self, msg: &str) -> DiagnosticBuilder<'_> {
654 DiagnosticBuilder::new(self, Level::Help, msg)
657 /// Construct a builder at the `Note` level with the `msg`.
658 pub fn struct_note_without_error(&self, msg: &str) -> DiagnosticBuilder<'_> {
659 DiagnosticBuilder::new(self, Level::Note, msg)
662 pub fn span_fatal(&self, span: impl Into<MultiSpan>, msg: &str) -> ! {
663 self.emit_diag_at_span(Diagnostic::new(Fatal, msg), span);
667 pub fn span_fatal_with_code(
669 span: impl Into<MultiSpan>,
673 self.emit_diag_at_span(Diagnostic::new_with_code(Fatal, Some(code), msg), span);
677 pub fn span_err(&self, span: impl Into<MultiSpan>, msg: &str) {
678 self.emit_diag_at_span(Diagnostic::new(Error, msg), span);
681 pub fn span_err_with_code(&self, span: impl Into<MultiSpan>, msg: &str, code: DiagnosticId) {
682 self.emit_diag_at_span(Diagnostic::new_with_code(Error, Some(code), msg), span);
685 pub fn span_warn(&self, span: impl Into<MultiSpan>, msg: &str) {
686 self.emit_diag_at_span(Diagnostic::new(Warning, msg), span);
689 pub fn span_warn_with_code(&self, span: impl Into<MultiSpan>, msg: &str, code: DiagnosticId) {
690 self.emit_diag_at_span(Diagnostic::new_with_code(Warning, Some(code), msg), span);
693 pub fn span_bug(&self, span: impl Into<MultiSpan>, msg: &str) -> ! {
694 self.inner.borrow_mut().span_bug(span, msg)
698 pub fn delay_span_bug(&self, span: impl Into<MultiSpan>, msg: &str) {
699 self.inner.borrow_mut().delay_span_bug(span, msg)
702 pub fn delay_good_path_bug(&self, msg: &str) {
703 self.inner.borrow_mut().delay_good_path_bug(msg)
706 pub fn span_bug_no_panic(&self, span: impl Into<MultiSpan>, msg: &str) {
707 self.emit_diag_at_span(Diagnostic::new(Bug, msg), span);
710 pub fn span_note_without_error(&self, span: impl Into<MultiSpan>, msg: &str) {
711 self.emit_diag_at_span(Diagnostic::new(Note, msg), span);
714 pub fn span_note_diag(&self, span: Span, msg: &str) -> DiagnosticBuilder<'_> {
715 let mut db = DiagnosticBuilder::new(self, Note, msg);
720 // NOTE: intentionally doesn't raise an error so rustc_codegen_ssa only reports fatal errors in the main thread
721 pub fn fatal(&self, msg: &str) -> FatalError {
722 self.inner.borrow_mut().fatal(msg)
725 pub fn err(&self, msg: &str) {
726 self.inner.borrow_mut().err(msg);
729 pub fn warn(&self, msg: &str) {
730 let mut db = DiagnosticBuilder::new(self, Warning, msg);
734 pub fn note_without_error(&self, msg: &str) {
735 DiagnosticBuilder::new(self, Note, msg).emit();
738 pub fn bug(&self, msg: &str) -> ! {
739 self.inner.borrow_mut().bug(msg)
743 pub fn err_count(&self) -> usize {
744 self.inner.borrow().err_count()
747 pub fn has_errors(&self) -> bool {
748 self.inner.borrow().has_errors()
750 pub fn has_errors_or_delayed_span_bugs(&self) -> bool {
751 self.inner.borrow().has_errors_or_delayed_span_bugs()
754 pub fn print_error_count(&self, registry: &Registry) {
755 self.inner.borrow_mut().print_error_count(registry)
758 pub fn take_future_breakage_diagnostics(&self) -> Vec<Diagnostic> {
759 std::mem::take(&mut self.inner.borrow_mut().future_breakage_diagnostics)
762 pub fn abort_if_errors(&self) {
763 self.inner.borrow_mut().abort_if_errors()
766 /// `true` if we haven't taught a diagnostic with this code already.
767 /// The caller must then teach the user about such a diagnostic.
769 /// Used to suppress emitting the same error multiple times with extended explanation when
770 /// calling `-Zteach`.
771 pub fn must_teach(&self, code: &DiagnosticId) -> bool {
772 self.inner.borrow_mut().must_teach(code)
775 pub fn force_print_diagnostic(&self, db: Diagnostic) {
776 self.inner.borrow_mut().force_print_diagnostic(db)
779 pub fn emit_diagnostic(&self, diagnostic: &Diagnostic) {
780 self.inner.borrow_mut().emit_diagnostic(diagnostic)
783 fn emit_diag_at_span(&self, mut diag: Diagnostic, sp: impl Into<MultiSpan>) {
784 let mut inner = self.inner.borrow_mut();
785 inner.emit_diagnostic(diag.set_span(sp));
788 pub fn emit_artifact_notification(&self, path: &Path, artifact_type: &str) {
789 self.inner.borrow_mut().emit_artifact_notification(path, artifact_type)
792 pub fn emit_future_breakage_report(&self, diags: Vec<Diagnostic>) {
793 self.inner.borrow_mut().emitter.emit_future_breakage_report(diags)
796 pub fn emit_unused_externs(&self, lint_level: &str, unused_externs: &[&str]) {
797 self.inner.borrow_mut().emit_unused_externs(lint_level, unused_externs)
800 pub fn delay_as_bug(&self, diagnostic: Diagnostic) {
801 self.inner.borrow_mut().delay_as_bug(diagnostic)
806 fn must_teach(&mut self, code: &DiagnosticId) -> bool {
807 self.taught_diagnostics.insert(code.clone())
810 fn force_print_diagnostic(&mut self, db: Diagnostic) {
811 self.emitter.emit_diagnostic(&db);
814 /// Emit all stashed diagnostics.
815 fn emit_stashed_diagnostics(&mut self) {
816 let diags = self.stashed_diagnostics.drain(..).map(|x| x.1).collect::<Vec<_>>();
817 diags.iter().for_each(|diag| self.emit_diagnostic(diag));
820 fn emit_diagnostic(&mut self, diagnostic: &Diagnostic) {
821 if diagnostic.cancelled() {
825 if diagnostic.has_future_breakage() {
826 self.future_breakage_diagnostics.push(diagnostic.clone());
829 if diagnostic.level == Warning
830 && !self.flags.can_emit_warnings
831 && !diagnostic.is_force_warn()
833 if diagnostic.has_future_breakage() {
834 (*TRACK_DIAGNOSTICS)(diagnostic);
839 (*TRACK_DIAGNOSTICS)(diagnostic);
841 if diagnostic.level == Allow {
845 if let Some(ref code) = diagnostic.code {
846 self.emitted_diagnostic_codes.insert(code.clone());
849 let already_emitted = |this: &mut Self| {
850 let mut hasher = StableHasher::new();
851 diagnostic.hash(&mut hasher);
852 let diagnostic_hash = hasher.finish();
853 !this.emitted_diagnostics.insert(diagnostic_hash)
856 // Only emit the diagnostic if we've been asked to deduplicate and
857 // haven't already emitted an equivalent diagnostic.
858 if !(self.flags.deduplicate_diagnostics && already_emitted(self)) {
859 self.emitter.emit_diagnostic(diagnostic);
860 if diagnostic.is_error() {
861 self.deduplicated_err_count += 1;
862 } else if diagnostic.level == Warning {
863 self.deduplicated_warn_count += 1;
866 if diagnostic.is_error() {
867 self.bump_err_count();
869 self.bump_warn_count();
873 fn emit_artifact_notification(&mut self, path: &Path, artifact_type: &str) {
874 self.emitter.emit_artifact_notification(path, artifact_type);
877 fn emit_unused_externs(&mut self, lint_level: &str, unused_externs: &[&str]) {
878 self.emitter.emit_unused_externs(lint_level, unused_externs);
881 fn treat_err_as_bug(&self) -> bool {
882 self.flags.treat_err_as_bug.map_or(false, |c| self.err_count() >= c.get())
885 fn print_error_count(&mut self, registry: &Registry) {
886 self.emit_stashed_diagnostics();
888 let warnings = match self.deduplicated_warn_count {
890 1 => "1 warning emitted".to_string(),
891 count => format!("{} warnings emitted", count),
893 let errors = match self.deduplicated_err_count {
895 1 => "aborting due to previous error".to_string(),
896 count => format!("aborting due to {} previous errors", count),
898 if self.treat_err_as_bug() {
902 match (errors.len(), warnings.len()) {
904 (0, _) => self.emitter.emit_diagnostic(&Diagnostic::new(Level::Warning, &warnings)),
906 let _ = self.fatal(&errors);
909 let _ = self.fatal(&format!("{}; {}", &errors, &warnings));
913 let can_show_explain = self.emitter.should_show_explain();
914 let are_there_diagnostics = !self.emitted_diagnostic_codes.is_empty();
915 if can_show_explain && are_there_diagnostics {
916 let mut error_codes = self
917 .emitted_diagnostic_codes
919 .filter_map(|x| match &x {
920 DiagnosticId::Error(s) => {
921 if let Ok(Some(_explanation)) = registry.try_find_description(s) {
929 .collect::<Vec<_>>();
930 if !error_codes.is_empty() {
932 if error_codes.len() > 1 {
933 let limit = if error_codes.len() > 9 { 9 } else { error_codes.len() };
934 self.failure(&format!(
935 "Some errors have detailed explanations: {}{}",
936 error_codes[..limit].join(", "),
937 if error_codes.len() > 9 { "..." } else { "." }
939 self.failure(&format!(
940 "For more information about an error, try \
941 `rustc --explain {}`.",
945 self.failure(&format!(
946 "For more information about this error, try \
947 `rustc --explain {}`.",
956 fn err_count(&self) -> usize {
957 self.err_count + self.stashed_diagnostics.len()
960 fn has_errors(&self) -> bool {
963 fn has_errors_or_delayed_span_bugs(&self) -> bool {
964 self.has_errors() || !self.delayed_span_bugs.is_empty()
966 fn has_any_message(&self) -> bool {
967 self.err_count() > 0 || self.warn_count > 0
970 fn abort_if_errors(&mut self) {
971 self.emit_stashed_diagnostics();
973 if self.has_errors() {
978 fn span_bug(&mut self, sp: impl Into<MultiSpan>, msg: &str) -> ! {
979 self.emit_diag_at_span(Diagnostic::new(Bug, msg), sp);
980 panic::panic_any(ExplicitBug);
983 fn emit_diag_at_span(&mut self, mut diag: Diagnostic, sp: impl Into<MultiSpan>) {
984 self.emit_diagnostic(diag.set_span(sp));
988 fn delay_span_bug(&mut self, sp: impl Into<MultiSpan>, msg: &str) {
989 // This is technically `self.treat_err_as_bug()` but `delay_span_bug` is called before
990 // incrementing `err_count` by one, so we need to +1 the comparing.
991 // FIXME: Would be nice to increment err_count in a more coherent way.
992 if self.flags.treat_err_as_bug.map_or(false, |c| self.err_count() + 1 >= c.get()) {
993 // FIXME: don't abort here if report_delayed_bugs is off
994 self.span_bug(sp, msg);
996 let mut diagnostic = Diagnostic::new(Level::Bug, msg);
997 diagnostic.set_span(sp.into());
998 diagnostic.note(&format!("delayed at {}", std::panic::Location::caller()));
999 self.delay_as_bug(diagnostic)
1002 fn delay_good_path_bug(&mut self, msg: &str) {
1003 let diagnostic = Diagnostic::new(Level::Bug, msg);
1004 if self.flags.report_delayed_bugs {
1005 self.emit_diagnostic(&diagnostic);
1007 let backtrace = std::backtrace::Backtrace::force_capture();
1008 self.delayed_good_path_bugs.push(DelayedDiagnostic::with_backtrace(diagnostic, backtrace));
1011 fn failure(&mut self, msg: &str) {
1012 self.emit_diagnostic(&Diagnostic::new(FailureNote, msg));
1015 fn fatal(&mut self, msg: &str) -> FatalError {
1016 self.emit_error(Fatal, msg);
1020 fn err(&mut self, msg: &str) {
1021 self.emit_error(Error, msg);
1024 /// Emit an error; level should be `Error` or `Fatal`.
1025 fn emit_error(&mut self, level: Level, msg: &str) {
1026 if self.treat_err_as_bug() {
1029 self.emit_diagnostic(&Diagnostic::new(level, msg));
1032 fn bug(&mut self, msg: &str) -> ! {
1033 self.emit_diagnostic(&Diagnostic::new(Bug, msg));
1034 panic::panic_any(ExplicitBug);
1037 fn delay_as_bug(&mut self, diagnostic: Diagnostic) {
1038 if self.flags.report_delayed_bugs {
1039 self.emit_diagnostic(&diagnostic);
1041 self.delayed_span_bugs.push(diagnostic);
1044 fn flush_delayed(&mut self, bugs: Vec<Diagnostic>, explanation: &str) {
1045 let has_bugs = !bugs.is_empty();
1047 self.emit_diagnostic(&bug);
1050 panic!("{}", explanation);
1054 fn bump_err_count(&mut self) {
1055 self.err_count += 1;
1056 self.panic_if_treat_err_as_bug();
1059 fn bump_warn_count(&mut self) {
1060 self.warn_count += 1;
1063 fn panic_if_treat_err_as_bug(&self) {
1064 if self.treat_err_as_bug() {
1065 match (self.err_count(), self.flags.treat_err_as_bug.map(|c| c.get()).unwrap_or(0)) {
1066 (1, 1) => panic!("aborting due to `-Z treat-err-as-bug=1`"),
1067 (0, _) | (1, _) => {}
1068 (count, as_bug) => panic!(
1069 "aborting after {} errors due to `-Z treat-err-as-bug={}`",
1077 struct DelayedDiagnostic {
1082 impl DelayedDiagnostic {
1083 fn with_backtrace(diagnostic: Diagnostic, backtrace: Backtrace) -> Self {
1084 DelayedDiagnostic { inner: diagnostic, note: backtrace }
1087 fn decorate(mut self) -> Diagnostic {
1088 self.inner.note(&format!("delayed at {}", self.note));
1093 #[derive(Copy, PartialEq, Clone, Hash, Debug, Encodable, Decodable)]
1106 impl fmt::Display for Level {
1107 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1108 self.to_str().fmt(f)
1113 fn color(self) -> ColorSpec {
1114 let mut spec = ColorSpec::new();
1116 Bug | Fatal | Error => {
1117 spec.set_fg(Some(Color::Red)).set_intense(true);
1120 spec.set_fg(Some(Color::Yellow)).set_intense(cfg!(windows));
1123 spec.set_fg(Some(Color::Green)).set_intense(true);
1126 spec.set_fg(Some(Color::Cyan)).set_intense(true);
1129 Allow | Cancelled => unreachable!(),
1134 pub fn to_str(self) -> &'static str {
1136 Bug => "error: internal compiler error",
1137 Fatal | Error => "error",
1138 Warning => "warning",
1141 FailureNote => "failure-note",
1142 Cancelled => panic!("Shouldn't call on cancelled error"),
1143 Allow => panic!("Shouldn't call on allowed error"),
1147 pub fn is_failure_note(&self) -> bool {
1148 matches!(*self, FailureNote)
1152 pub fn add_elided_lifetime_in_path_suggestion(
1153 source_map: &SourceMap,
1154 db: &mut DiagnosticBuilder<'_>,
1157 incl_angl_brckt: bool,
1158 insertion_span: Span,
1161 let (replace_span, suggestion) = if incl_angl_brckt {
1162 (insertion_span, anon_lts)
1164 // When possible, prefer a suggestion that replaces the whole
1165 // `Path<T>` expression with `Path<'_, T>`, rather than inserting `'_, `
1166 // at a point (which makes for an ugly/confusing label)
1167 if let Ok(snippet) = source_map.span_to_snippet(path_span) {
1168 // But our spans can get out of whack due to macros; if the place we think
1169 // we want to insert `'_` isn't even within the path expression's span, we
1170 // should bail out of making any suggestion rather than panicking on a
1171 // subtract-with-overflow or string-slice-out-out-bounds (!)
1172 // FIXME: can we do better?
1173 if insertion_span.lo().0 < path_span.lo().0 {
1176 let insertion_index = (insertion_span.lo().0 - path_span.lo().0) as usize;
1177 if insertion_index > snippet.len() {
1180 let (before, after) = snippet.split_at(insertion_index);
1181 (path_span, format!("{}{}{}", before, anon_lts, after))
1183 (insertion_span, anon_lts)
1188 &format!("indicate the anonymous lifetime{}", pluralize!(n)),
1190 Applicability::MachineApplicable,
1194 // Useful type to use with `Result<>` indicate that an error has already
1195 // been reported to the user, so no need to continue checking.
1196 #[derive(Clone, Copy, Debug, Encodable, Decodable, Hash, PartialEq, Eq)]
1197 pub struct ErrorReported;
1199 rustc_data_structures::impl_stable_hash_via_hash!(ErrorReported);