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(if_let_guard)]
11 #![cfg_attr(not(bootstrap), allow(rustc::potential_query_instability))]
12 #![feature(adt_const_params)]
13 #![allow(incomplete_features)]
16 extern crate rustc_macros;
21 pub use emitter::ColorConfig;
25 use emitter::{is_case_difference, Emitter, EmitterWriter};
26 use registry::Registry;
27 use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
28 use rustc_data_structures::stable_hasher::StableHasher;
29 use rustc_data_structures::sync::{self, Lock, Lrc};
30 use rustc_data_structures::AtomicRef;
31 pub use rustc_lint_defs::{pluralize, Applicability};
32 use rustc_serialize::json::Json;
33 use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
34 use rustc_span::source_map::SourceMap;
35 use rustc_span::{Loc, MultiSpan, Span};
38 use std::hash::{Hash, Hasher};
39 use std::num::NonZeroUsize;
42 use std::{error, fmt};
44 use termcolor::{Color, ColorSpec};
46 pub mod annotate_snippet_emitter_writer;
48 mod diagnostic_builder;
55 pub use snippet::Style;
57 pub type PResult<'a, T> = Result<T, DiagnosticBuilder<'a, ErrorReported>>;
59 // `PResult` is used a lot. Make sure it doesn't unintentionally get bigger.
60 // (See also the comment on `DiagnosticBuilder`'s `diagnostic` field.)
61 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
62 rustc_data_structures::static_assert_size!(PResult<'_, ()>, 16);
63 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
64 rustc_data_structures::static_assert_size!(PResult<'_, bool>, 24);
66 #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, Encodable, Decodable)]
67 pub enum SuggestionStyle {
68 /// Hide the suggested code when displaying this suggestion inline.
70 /// Always hide the suggested code but display the message.
72 /// Do not display this suggestion in the cli output, it is only meant for tools.
74 /// Always show the suggested code.
75 /// This will *not* show the code if the suggestion is inline *and* the suggested code is
78 /// Always show the suggested code independently.
82 impl SuggestionStyle {
83 fn hide_inline(&self) -> bool {
84 !matches!(*self, SuggestionStyle::ShowCode)
88 #[derive(Clone, Debug, PartialEq, Default)]
89 pub struct ToolMetadata(pub Option<Json>);
92 fn new(json: Json) -> Self {
93 ToolMetadata(Some(json))
96 fn is_set(&self) -> bool {
101 impl Hash for ToolMetadata {
102 fn hash<H: Hasher>(&self, _state: &mut H) {}
105 // Doesn't really need to round-trip
106 impl<D: Decoder> Decodable<D> for ToolMetadata {
107 fn decode(_d: &mut D) -> Self {
112 impl<S: Encoder> Encodable<S> for ToolMetadata {
113 fn encode(&self, e: &mut S) -> Result<(), S::Error> {
115 None => e.emit_unit(),
116 Some(json) => json.encode(e),
121 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
122 pub struct CodeSuggestion {
123 /// Each substitute can have multiple variants due to multiple
124 /// applicable suggestions
126 /// `foo.bar` might be replaced with `a.b` or `x.y` by replacing
127 /// `foo` and `bar` on their own:
131 /// Substitution { parts: vec![(0..3, "a"), (4..7, "b")] },
132 /// Substitution { parts: vec![(0..3, "x"), (4..7, "y")] },
136 /// or by replacing the entire span:
140 /// Substitution { parts: vec![(0..7, "a.b")] },
141 /// Substitution { parts: vec![(0..7, "x.y")] },
144 pub substitutions: Vec<Substitution>,
146 /// Visual representation of this suggestion.
147 pub style: SuggestionStyle,
148 /// Whether or not the suggestion is approximate
150 /// Sometimes we may show suggestions with placeholders,
151 /// which are useful for users but not useful for
152 /// tools like rustfix
153 pub applicability: Applicability,
154 /// Tool-specific metadata
155 pub tool_metadata: ToolMetadata,
158 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
159 /// See the docs on `CodeSuggestion::substitutions`
160 pub struct Substitution {
161 pub parts: Vec<SubstitutionPart>,
164 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
165 pub struct SubstitutionPart {
170 /// Used to translate between `Span`s and byte positions within a single output line in highlighted
171 /// code of structured suggestions.
172 #[derive(Debug, Clone, Copy)]
173 pub struct SubstitutionHighlight {
178 impl SubstitutionPart {
179 pub fn is_addition(&self, sm: &SourceMap) -> bool {
180 !self.snippet.is_empty()
182 .span_to_snippet(self.span)
183 .map_or(self.span.is_empty(), |snippet| snippet.trim().is_empty())
186 pub fn is_deletion(&self) -> bool {
187 self.snippet.trim().is_empty()
190 pub fn is_replacement(&self, sm: &SourceMap) -> bool {
191 !self.snippet.is_empty()
193 .span_to_snippet(self.span)
194 .map_or(!self.span.is_empty(), |snippet| !snippet.trim().is_empty())
198 impl CodeSuggestion {
199 /// Returns the assembled code suggestions, whether they should be shown with an underline
200 /// and whether the substitution only differs in capitalization.
204 ) -> Vec<(String, Vec<SubstitutionPart>, Vec<Vec<SubstitutionHighlight>>, bool)> {
205 // For the `Vec<Vec<SubstitutionHighlight>>` value, the first level of the vector
206 // corresponds to the output snippet's lines, while the second level corresponds to the
207 // substrings within that line that should be highlighted.
209 use rustc_span::{CharPos, Pos};
211 /// Append to a buffer the remainder of the line of existing source code, and return the
212 /// count of lines that have been added for accurate highlighting.
215 line_opt: Option<&Cow<'_, str>>,
217 hi_opt: Option<&Loc>,
219 let mut line_count = 0;
220 let (lo, hi_opt) = (lo.col.to_usize(), hi_opt.map(|hi| hi.col.to_usize()));
221 if let Some(line) = line_opt {
222 if let Some(lo) = line.char_indices().map(|(i, _)| i).nth(lo) {
223 let hi_opt = hi_opt.and_then(|hi| line.char_indices().map(|(i, _)| i).nth(hi));
225 Some(hi) if hi > lo => {
226 line_count = line[lo..hi].matches('\n').count();
227 buf.push_str(&line[lo..hi])
231 line_count = line[lo..].matches('\n').count();
232 buf.push_str(&line[lo..])
236 if hi_opt.is_none() {
243 assert!(!self.substitutions.is_empty());
248 // Suggestions coming from macros can have malformed spans. This is a heavy
249 // handed approach to avoid ICEs by ignoring the suggestion outright.
250 let invalid = subst.parts.iter().any(|item| sm.is_valid_span(item.span).is_err());
252 debug!("splice_lines: suggestion contains an invalid span: {:?}", subst);
257 .filter_map(|mut substitution| {
258 // Assumption: all spans are in the same file, and all spans
259 // are disjoint. Sort in ascending order.
260 substitution.parts.sort_by_key(|part| part.span.lo());
262 // Find the bounding span.
263 let lo = substitution.parts.iter().map(|part| part.span.lo()).min()?;
264 let hi = substitution.parts.iter().map(|part| part.span.hi()).max()?;
265 let bounding_span = Span::with_root_ctxt(lo, hi);
266 // The different spans might belong to different contexts, if so ignore suggestion.
267 let lines = sm.span_to_lines(bounding_span).ok()?;
268 assert!(!lines.lines.is_empty() || bounding_span.is_dummy());
270 // We can't splice anything if the source is unavailable.
271 if !sm.ensure_source_file_source_present(lines.file.clone()) {
275 let mut highlights = vec![];
276 // To build up the result, we do this for each span:
277 // - push the line segment trailing the previous span
278 // (at the beginning a "phantom" span pointing at the start of the line)
279 // - push lines between the previous and current span (if any)
280 // - if the previous and current span are not on the same line
281 // push the line segment leading up to the current span
282 // - splice in the span substitution
284 // Finally push the trailing line segment of the last span
285 let sf = &lines.file;
286 let mut prev_hi = sm.lookup_char_pos(bounding_span.lo());
287 prev_hi.col = CharPos::from_usize(0);
289 lines.lines.get(0).and_then(|line0| sf.get_line(line0.line_index));
290 let mut buf = String::new();
292 let mut line_highlight = vec![];
293 // We need to keep track of the difference between the existing code and the added
294 // or deleted code in order to point at the correct column *after* substitution.
296 for part in &substitution.parts {
297 let cur_lo = sm.lookup_char_pos(part.span.lo());
298 if prev_hi.line == cur_lo.line {
300 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, Some(&cur_lo));
302 highlights.push(std::mem::take(&mut line_highlight));
308 highlights.push(std::mem::take(&mut line_highlight));
309 let mut count = push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
311 highlights.push(std::mem::take(&mut line_highlight));
314 // push lines between the previous and current span (if any)
315 for idx in prev_hi.line..(cur_lo.line - 1) {
316 if let Some(line) = sf.get_line(idx) {
317 buf.push_str(line.as_ref());
319 highlights.push(std::mem::take(&mut line_highlight));
322 if let Some(cur_line) = sf.get_line(cur_lo.line - 1) {
323 let end = match cur_line.char_indices().nth(cur_lo.col.to_usize()) {
325 None => cur_line.len(),
327 buf.push_str(&cur_line[..end]);
330 // Add a whole line highlight per line in the snippet.
331 let len: isize = part
335 .unwrap_or(&part.snippet)
342 line_highlight.push(SubstitutionHighlight {
343 start: (cur_lo.col.0 as isize + acc) as usize,
344 end: (cur_lo.col.0 as isize + acc + len) as usize,
346 buf.push_str(&part.snippet);
347 let cur_hi = sm.lookup_char_pos(part.span.hi());
348 if prev_hi.line == cur_lo.line && cur_hi.line == cur_lo.line {
349 // Account for the difference between the width of the current code and the
350 // snippet being suggested, so that the *later* suggestions are correctly
351 // aligned on the screen.
352 acc += len as isize - (cur_hi.col.0 - cur_lo.col.0) as isize;
355 prev_line = sf.get_line(prev_hi.line - 1);
356 for line in part.snippet.split('\n').skip(1) {
358 highlights.push(std::mem::take(&mut line_highlight));
359 let end: usize = line
366 line_highlight.push(SubstitutionHighlight { start: 0, end });
369 highlights.push(std::mem::take(&mut line_highlight));
370 let only_capitalization = is_case_difference(sm, &buf, bounding_span);
371 // if the replacement already ends with a newline, don't print the next line
372 if !buf.ends_with('\n') {
373 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
375 // remove trailing newlines
376 while buf.ends_with('\n') {
379 Some((buf, substitution.parts, highlights, only_capitalization))
385 pub use rustc_span::fatal_error::{FatalError, FatalErrorMarker};
387 /// Signifies that the compiler died with an explicit call to `.bug`
388 /// or `.span_bug` rather than a failed assertion, etc.
389 #[derive(Copy, Clone, Debug)]
390 pub struct ExplicitBug;
392 impl fmt::Display for ExplicitBug {
393 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
394 write!(f, "parser internal bug")
398 impl error::Error for ExplicitBug {}
400 pub use diagnostic::{Diagnostic, DiagnosticId, DiagnosticStyledString, SubDiagnostic};
401 pub use diagnostic_builder::DiagnosticBuilder;
402 use std::backtrace::Backtrace;
404 /// A handler deals with errors and other compiler output.
405 /// Certain errors (fatal, bug, unimpl) may cause immediate exit,
406 /// others log errors for later reporting.
409 inner: Lock<HandlerInner>,
412 /// This inner struct exists to keep it all behind a single lock;
413 /// this is done to prevent possible deadlocks in a multi-threaded compiler,
414 /// as well as inconsistent state observation.
415 struct HandlerInner {
417 /// The number of lint errors that have been emitted.
418 lint_err_count: usize,
419 /// The number of errors that have been emitted, including duplicates.
421 /// This is not necessarily the count that's reported to the user once
422 /// compilation ends.
425 deduplicated_err_count: usize,
426 emitter: Box<dyn Emitter + sync::Send>,
427 delayed_span_bugs: Vec<Diagnostic>,
428 delayed_good_path_bugs: Vec<DelayedDiagnostic>,
430 /// This set contains the `DiagnosticId` of all emitted diagnostics to avoid
431 /// emitting the same diagnostic with extended help (`--teach`) twice, which
432 /// would be unnecessary repetition.
433 taught_diagnostics: FxHashSet<DiagnosticId>,
435 /// Used to suggest rustc --explain <error code>
436 emitted_diagnostic_codes: FxHashSet<DiagnosticId>,
438 /// This set contains a hash of every diagnostic that has been emitted by
439 /// this handler. These hashes is used to avoid emitting the same error
441 emitted_diagnostics: FxHashSet<u128>,
443 /// Stashed diagnostics emitted in one stage of the compiler that may be
444 /// stolen by other stages (e.g. to improve them and add more information).
445 /// The stashed diagnostics count towards the total error count.
446 /// When `.abort_if_errors()` is called, these are also emitted.
447 stashed_diagnostics: FxIndexMap<(Span, StashKey), Diagnostic>,
449 /// The warning count, used for a recap upon finishing
450 deduplicated_warn_count: usize,
452 future_breakage_diagnostics: Vec<Diagnostic>,
455 /// A key denoting where from a diagnostic was stashed.
456 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
461 fn default_track_diagnostic(_: &Diagnostic) {}
463 pub static TRACK_DIAGNOSTICS: AtomicRef<fn(&Diagnostic)> =
464 AtomicRef::new(&(default_track_diagnostic as fn(&_)));
466 #[derive(Copy, Clone, Default)]
467 pub struct HandlerFlags {
468 /// If false, warning-level lints are suppressed.
469 /// (rustc: see `--allow warnings` and `--cap-lints`)
470 pub can_emit_warnings: bool,
471 /// If true, error-level diagnostics are upgraded to bug-level.
472 /// (rustc: see `-Z treat-err-as-bug`)
473 pub treat_err_as_bug: Option<NonZeroUsize>,
474 /// If true, immediately emit diagnostics that would otherwise be buffered.
475 /// (rustc: see `-Z dont-buffer-diagnostics` and `-Z treat-err-as-bug`)
476 pub dont_buffer_diagnostics: bool,
477 /// If true, immediately print bugs registered with `delay_span_bug`.
478 /// (rustc: see `-Z report-delayed-bugs`)
479 pub report_delayed_bugs: bool,
480 /// Show macro backtraces.
481 /// (rustc: see `-Z macro-backtrace`)
482 pub macro_backtrace: bool,
483 /// If true, identical diagnostics are reported only once.
484 pub deduplicate_diagnostics: bool,
487 impl Drop for HandlerInner {
489 self.emit_stashed_diagnostics();
491 if !self.has_errors() {
492 let bugs = std::mem::replace(&mut self.delayed_span_bugs, Vec::new());
493 self.flush_delayed(bugs, "no errors encountered even though `delay_span_bug` issued");
496 // FIXME(eddyb) this explains what `delayed_good_path_bugs` are!
497 // They're `delayed_span_bugs` but for "require some diagnostic happened"
498 // instead of "require some error happened". Sadly that isn't ideal, as
499 // lints can be `#[allow]`'d, potentially leading to this triggering.
500 // Also, "good path" should be replaced with a better naming.
501 if !self.has_any_message() {
502 let bugs = std::mem::replace(&mut self.delayed_good_path_bugs, Vec::new());
504 bugs.into_iter().map(DelayedDiagnostic::decorate),
505 "no warnings or errors encountered even though `delayed_good_path_bugs` issued",
512 pub fn with_tty_emitter(
513 color_config: ColorConfig,
514 can_emit_warnings: bool,
515 treat_err_as_bug: Option<NonZeroUsize>,
516 sm: Option<Lrc<SourceMap>>,
518 Self::with_tty_emitter_and_flags(
521 HandlerFlags { can_emit_warnings, treat_err_as_bug, ..Default::default() },
525 pub fn with_tty_emitter_and_flags(
526 color_config: ColorConfig,
527 sm: Option<Lrc<SourceMap>>,
530 let emitter = Box::new(EmitterWriter::stderr(
536 flags.macro_backtrace,
538 Self::with_emitter_and_flags(emitter, flags)
542 can_emit_warnings: bool,
543 treat_err_as_bug: Option<NonZeroUsize>,
544 emitter: Box<dyn Emitter + sync::Send>,
546 Handler::with_emitter_and_flags(
548 HandlerFlags { can_emit_warnings, treat_err_as_bug, ..Default::default() },
552 pub fn with_emitter_and_flags(
553 emitter: Box<dyn Emitter + sync::Send>,
558 inner: Lock::new(HandlerInner {
563 deduplicated_err_count: 0,
564 deduplicated_warn_count: 0,
566 delayed_span_bugs: Vec::new(),
567 delayed_good_path_bugs: Vec::new(),
568 taught_diagnostics: Default::default(),
569 emitted_diagnostic_codes: Default::default(),
570 emitted_diagnostics: Default::default(),
571 stashed_diagnostics: Default::default(),
572 future_breakage_diagnostics: Vec::new(),
577 // This is here to not allow mutation of flags;
578 // as of this writing it's only used in tests in librustc_middle.
579 pub fn can_emit_warnings(&self) -> bool {
580 self.flags.can_emit_warnings
583 /// Resets the diagnostic error count as well as the cached emitted diagnostics.
585 /// NOTE: *do not* call this function from rustc. It is only meant to be called from external
586 /// tools that want to reuse a `Parser` cleaning the previously emitted diagnostics as well as
587 /// the overall count of emitted error diagnostics.
588 pub fn reset_err_count(&self) {
589 let mut inner = self.inner.borrow_mut();
591 inner.warn_count = 0;
592 inner.deduplicated_err_count = 0;
593 inner.deduplicated_warn_count = 0;
595 // actually free the underlying memory (which `clear` would not do)
596 inner.delayed_span_bugs = Default::default();
597 inner.delayed_good_path_bugs = Default::default();
598 inner.taught_diagnostics = Default::default();
599 inner.emitted_diagnostic_codes = Default::default();
600 inner.emitted_diagnostics = Default::default();
601 inner.stashed_diagnostics = Default::default();
604 /// Stash a given diagnostic with the given `Span` and `StashKey` as the key for later stealing.
605 pub fn stash_diagnostic(&self, span: Span, key: StashKey, diag: Diagnostic) {
606 let mut inner = self.inner.borrow_mut();
607 // FIXME(Centril, #69537): Consider reintroducing panic on overwriting a stashed diagnostic
608 // if/when we have a more robust macro-friendly replacement for `(span, key)` as a key.
609 // See the PR for a discussion.
610 inner.stashed_diagnostics.insert((span, key), diag);
613 /// Steal a previously stashed diagnostic with the given `Span` and `StashKey` as the key.
614 pub fn steal_diagnostic(&self, span: Span, key: StashKey) -> Option<DiagnosticBuilder<'_, ()>> {
618 .remove(&(span, key))
619 .map(|diag| DiagnosticBuilder::new_diagnostic(self, diag))
622 /// Emit all stashed diagnostics.
623 pub fn emit_stashed_diagnostics(&self) {
624 self.inner.borrow_mut().emit_stashed_diagnostics();
627 /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
629 /// Attempting to `.emit()` the builder will only emit if either:
630 /// * `can_emit_warnings` is `true`
631 /// * `is_force_warn` was set in `DiagnosticId::Lint`
632 pub fn struct_span_warn(
634 span: impl Into<MultiSpan>,
636 ) -> DiagnosticBuilder<'_, ()> {
637 let mut result = self.struct_warn(msg);
638 result.set_span(span);
642 /// Construct a builder at the `Allow` level at the given `span` and with the `msg`.
643 pub fn struct_span_allow(
645 span: impl Into<MultiSpan>,
647 ) -> DiagnosticBuilder<'_, ()> {
648 let mut result = self.struct_allow(msg);
649 result.set_span(span);
653 /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
654 /// Also include a code.
655 pub fn struct_span_warn_with_code(
657 span: impl Into<MultiSpan>,
660 ) -> DiagnosticBuilder<'_, ()> {
661 let mut result = self.struct_span_warn(span, msg);
666 /// Construct a builder at the `Warning` level with the `msg`.
668 /// Attempting to `.emit()` the builder will only emit if either:
669 /// * `can_emit_warnings` is `true`
670 /// * `is_force_warn` was set in `DiagnosticId::Lint`
671 pub fn struct_warn(&self, msg: &str) -> DiagnosticBuilder<'_, ()> {
672 DiagnosticBuilder::new(self, Level::Warning, msg)
675 /// Construct a builder at the `Allow` level with the `msg`.
676 pub fn struct_allow(&self, msg: &str) -> DiagnosticBuilder<'_, ()> {
677 DiagnosticBuilder::new(self, Level::Allow, msg)
680 /// Construct a builder at the `Error` level at the given `span` and with the `msg`.
681 pub fn struct_span_err(
683 span: impl Into<MultiSpan>,
685 ) -> DiagnosticBuilder<'_, ErrorReported> {
686 let mut result = self.struct_err(msg);
687 result.set_span(span);
691 /// Construct a builder at the `Error` level at the given `span`, with the `msg`, and `code`.
692 pub fn struct_span_err_with_code(
694 span: impl Into<MultiSpan>,
697 ) -> DiagnosticBuilder<'_, ErrorReported> {
698 let mut result = self.struct_span_err(span, msg);
703 /// Construct a builder at the `Error` level with the `msg`.
704 // FIXME: This method should be removed (every error should have an associated error code).
705 pub fn struct_err(&self, msg: &str) -> DiagnosticBuilder<'_, ErrorReported> {
706 DiagnosticBuilder::new_guaranteeing_error::<{ Level::Error { lint: false } }>(self, msg)
709 /// This should only be used by `rustc_middle::lint::struct_lint_level`. Do not use it for hard errors.
711 pub fn struct_err_lint(&self, msg: &str) -> DiagnosticBuilder<'_, ()> {
712 DiagnosticBuilder::new(self, Level::Error { lint: true }, msg)
715 /// Construct a builder at the `Error` level with the `msg` and the `code`.
716 pub fn struct_err_with_code(
720 ) -> DiagnosticBuilder<'_, ErrorReported> {
721 let mut result = self.struct_err(msg);
726 /// Construct a builder at the `Fatal` level at the given `span` and with the `msg`.
727 pub fn struct_span_fatal(
729 span: impl Into<MultiSpan>,
731 ) -> DiagnosticBuilder<'_, ErrorReported> {
732 let mut result = self.struct_fatal(msg);
733 result.set_span(span);
737 /// Construct a builder at the `Fatal` level at the given `span`, with the `msg`, and `code`.
738 pub fn struct_span_fatal_with_code(
740 span: impl Into<MultiSpan>,
743 ) -> DiagnosticBuilder<'_, ErrorReported> {
744 let mut result = self.struct_span_fatal(span, msg);
749 /// Construct a builder at the `Error` level with the `msg`.
750 pub fn struct_fatal(&self, msg: &str) -> DiagnosticBuilder<'_, ErrorReported> {
751 DiagnosticBuilder::new_guaranteeing_error::<{ Level::Fatal }>(self, msg)
754 /// Construct a builder at the `Help` level with the `msg`.
755 pub fn struct_help(&self, msg: &str) -> DiagnosticBuilder<'_, ()> {
756 DiagnosticBuilder::new(self, Level::Help, msg)
759 /// Construct a builder at the `Note` level with the `msg`.
760 pub fn struct_note_without_error(&self, msg: &str) -> DiagnosticBuilder<'_, ()> {
761 DiagnosticBuilder::new(self, Level::Note, msg)
764 pub fn span_fatal(&self, span: impl Into<MultiSpan>, msg: &str) -> ! {
765 self.emit_diag_at_span(Diagnostic::new(Fatal, msg), span);
769 pub fn span_fatal_with_code(
771 span: impl Into<MultiSpan>,
775 self.emit_diag_at_span(Diagnostic::new_with_code(Fatal, Some(code), msg), span);
779 pub fn span_err(&self, span: impl Into<MultiSpan>, msg: &str) {
780 self.emit_diag_at_span(Diagnostic::new(Error { lint: false }, msg), span);
783 pub fn span_err_with_code(&self, span: impl Into<MultiSpan>, msg: &str, code: DiagnosticId) {
784 self.emit_diag_at_span(
785 Diagnostic::new_with_code(Error { lint: false }, Some(code), msg),
790 pub fn span_warn(&self, span: impl Into<MultiSpan>, msg: &str) {
791 self.emit_diag_at_span(Diagnostic::new(Warning, msg), span);
794 pub fn span_warn_with_code(&self, span: impl Into<MultiSpan>, msg: &str, code: DiagnosticId) {
795 self.emit_diag_at_span(Diagnostic::new_with_code(Warning, Some(code), msg), span);
798 pub fn span_bug(&self, span: impl Into<MultiSpan>, msg: &str) -> ! {
799 self.inner.borrow_mut().span_bug(span, msg)
803 pub fn delay_span_bug(&self, span: impl Into<MultiSpan>, msg: &str) {
804 self.inner.borrow_mut().delay_span_bug(span, msg)
807 // FIXME(eddyb) note the comment inside `impl Drop for HandlerInner`, that's
808 // where the explanation of what "good path" is (also, it should be renamed).
809 pub fn delay_good_path_bug(&self, msg: &str) {
810 self.inner.borrow_mut().delay_good_path_bug(msg)
813 pub fn span_bug_no_panic(&self, span: impl Into<MultiSpan>, msg: &str) {
814 self.emit_diag_at_span(Diagnostic::new(Bug, msg), span);
817 pub fn span_note_without_error(&self, span: impl Into<MultiSpan>, msg: &str) {
818 self.emit_diag_at_span(Diagnostic::new(Note, msg), span);
821 pub fn span_note_diag(&self, span: Span, msg: &str) -> DiagnosticBuilder<'_, ()> {
822 let mut db = DiagnosticBuilder::new(self, Note, msg);
827 // NOTE: intentionally doesn't raise an error so rustc_codegen_ssa only reports fatal errors in the main thread
828 pub fn fatal(&self, msg: &str) -> FatalError {
829 self.inner.borrow_mut().fatal(msg)
832 pub fn err(&self, msg: &str) {
833 self.inner.borrow_mut().err(msg);
836 pub fn warn(&self, msg: &str) {
837 let mut db = DiagnosticBuilder::new(self, Warning, msg);
841 pub fn note_without_error(&self, msg: &str) {
842 DiagnosticBuilder::new(self, Note, msg).emit();
845 pub fn bug(&self, msg: &str) -> ! {
846 self.inner.borrow_mut().bug(msg)
850 pub fn err_count(&self) -> usize {
851 self.inner.borrow().err_count()
854 pub fn has_errors(&self) -> bool {
855 self.inner.borrow().has_errors()
857 pub fn has_errors_or_lint_errors(&self) -> bool {
858 self.inner.borrow().has_errors_or_lint_errors()
860 pub fn has_errors_or_delayed_span_bugs(&self) -> bool {
861 self.inner.borrow().has_errors_or_delayed_span_bugs()
864 pub fn print_error_count(&self, registry: &Registry) {
865 self.inner.borrow_mut().print_error_count(registry)
868 pub fn take_future_breakage_diagnostics(&self) -> Vec<Diagnostic> {
869 std::mem::take(&mut self.inner.borrow_mut().future_breakage_diagnostics)
872 pub fn abort_if_errors(&self) {
873 self.inner.borrow_mut().abort_if_errors()
876 /// `true` if we haven't taught a diagnostic with this code already.
877 /// The caller must then teach the user about such a diagnostic.
879 /// Used to suppress emitting the same error multiple times with extended explanation when
880 /// calling `-Zteach`.
881 pub fn must_teach(&self, code: &DiagnosticId) -> bool {
882 self.inner.borrow_mut().must_teach(code)
885 pub fn force_print_diagnostic(&self, db: Diagnostic) {
886 self.inner.borrow_mut().force_print_diagnostic(db)
889 pub fn emit_diagnostic(&self, diagnostic: &Diagnostic) {
890 self.inner.borrow_mut().emit_diagnostic(diagnostic)
893 fn emit_diag_at_span(&self, mut diag: Diagnostic, sp: impl Into<MultiSpan>) {
894 let mut inner = self.inner.borrow_mut();
895 inner.emit_diagnostic(diag.set_span(sp));
898 pub fn emit_artifact_notification(&self, path: &Path, artifact_type: &str) {
899 self.inner.borrow_mut().emit_artifact_notification(path, artifact_type)
902 pub fn emit_future_breakage_report(&self, diags: Vec<Diagnostic>) {
903 self.inner.borrow_mut().emitter.emit_future_breakage_report(diags)
906 pub fn emit_unused_externs(&self, lint_level: &str, unused_externs: &[&str]) {
907 self.inner.borrow_mut().emit_unused_externs(lint_level, unused_externs)
912 fn must_teach(&mut self, code: &DiagnosticId) -> bool {
913 self.taught_diagnostics.insert(code.clone())
916 fn force_print_diagnostic(&mut self, db: Diagnostic) {
917 self.emitter.emit_diagnostic(&db);
920 /// Emit all stashed diagnostics.
921 fn emit_stashed_diagnostics(&mut self) {
922 let diags = self.stashed_diagnostics.drain(..).map(|x| x.1).collect::<Vec<_>>();
923 diags.iter().for_each(|diag| self.emit_diagnostic(diag));
926 // FIXME(eddyb) this should ideally take `diagnostic` by value.
927 fn emit_diagnostic(&mut self, diagnostic: &Diagnostic) {
928 if diagnostic.level == Level::DelayedBug {
929 // FIXME(eddyb) this should check for `has_errors` and stop pushing
930 // once *any* errors were emitted (and truncate `delayed_span_bugs`
931 // when an error is first emitted, also), but maybe there's a case
932 // in which that's not sound? otherwise this is really inefficient.
933 self.delayed_span_bugs.push(diagnostic.clone());
935 if !self.flags.report_delayed_bugs {
940 if diagnostic.has_future_breakage() {
941 self.future_breakage_diagnostics.push(diagnostic.clone());
944 if diagnostic.level == Warning
945 && !self.flags.can_emit_warnings
946 && !diagnostic.is_force_warn()
948 if diagnostic.has_future_breakage() {
949 (*TRACK_DIAGNOSTICS)(diagnostic);
954 (*TRACK_DIAGNOSTICS)(diagnostic);
956 if diagnostic.level == Allow {
960 if let Some(ref code) = diagnostic.code {
961 self.emitted_diagnostic_codes.insert(code.clone());
964 let already_emitted = |this: &mut Self| {
965 let mut hasher = StableHasher::new();
966 diagnostic.hash(&mut hasher);
967 let diagnostic_hash = hasher.finish();
968 !this.emitted_diagnostics.insert(diagnostic_hash)
971 // Only emit the diagnostic if we've been asked to deduplicate and
972 // haven't already emitted an equivalent diagnostic.
973 if !(self.flags.deduplicate_diagnostics && already_emitted(self)) {
974 self.emitter.emit_diagnostic(diagnostic);
975 if diagnostic.is_error() {
976 self.deduplicated_err_count += 1;
977 } else if diagnostic.level == Warning {
978 self.deduplicated_warn_count += 1;
981 if diagnostic.is_error() {
982 if matches!(diagnostic.level, Level::Error { lint: true }) {
983 self.bump_lint_err_count();
985 self.bump_err_count();
988 self.bump_warn_count();
992 fn emit_artifact_notification(&mut self, path: &Path, artifact_type: &str) {
993 self.emitter.emit_artifact_notification(path, artifact_type);
996 fn emit_unused_externs(&mut self, lint_level: &str, unused_externs: &[&str]) {
997 self.emitter.emit_unused_externs(lint_level, unused_externs);
1000 fn treat_err_as_bug(&self) -> bool {
1003 .map_or(false, |c| self.err_count() + self.lint_err_count >= c.get())
1006 fn print_error_count(&mut self, registry: &Registry) {
1007 self.emit_stashed_diagnostics();
1009 let warnings = match self.deduplicated_warn_count {
1011 1 => "1 warning emitted".to_string(),
1012 count => format!("{} warnings emitted", count),
1014 let errors = match self.deduplicated_err_count {
1016 1 => "aborting due to previous error".to_string(),
1017 count => format!("aborting due to {} previous errors", count),
1019 if self.treat_err_as_bug() {
1023 match (errors.len(), warnings.len()) {
1025 (0, _) => self.emitter.emit_diagnostic(&Diagnostic::new(Level::Warning, &warnings)),
1027 let _ = self.fatal(&errors);
1030 let _ = self.fatal(&format!("{}; {}", &errors, &warnings));
1034 let can_show_explain = self.emitter.should_show_explain();
1035 let are_there_diagnostics = !self.emitted_diagnostic_codes.is_empty();
1036 if can_show_explain && are_there_diagnostics {
1037 let mut error_codes = self
1038 .emitted_diagnostic_codes
1040 .filter_map(|x| match &x {
1041 DiagnosticId::Error(s)
1042 if registry.try_find_description(s).map_or(false, |o| o.is_some()) =>
1048 .collect::<Vec<_>>();
1049 if !error_codes.is_empty() {
1051 if error_codes.len() > 1 {
1052 let limit = if error_codes.len() > 9 { 9 } else { error_codes.len() };
1053 self.failure(&format!(
1054 "Some errors have detailed explanations: {}{}",
1055 error_codes[..limit].join(", "),
1056 if error_codes.len() > 9 { "..." } else { "." }
1058 self.failure(&format!(
1059 "For more information about an error, try \
1060 `rustc --explain {}`.",
1064 self.failure(&format!(
1065 "For more information about this error, try \
1066 `rustc --explain {}`.",
1075 fn err_count(&self) -> usize {
1076 self.err_count + self.stashed_diagnostics.len()
1079 fn has_errors(&self) -> bool {
1080 self.err_count() > 0
1082 fn has_errors_or_lint_errors(&self) -> bool {
1083 self.has_errors() || self.lint_err_count > 0
1085 fn has_errors_or_delayed_span_bugs(&self) -> bool {
1086 self.has_errors() || !self.delayed_span_bugs.is_empty()
1088 fn has_any_message(&self) -> bool {
1089 self.err_count() > 0 || self.lint_err_count > 0 || self.warn_count > 0
1092 fn abort_if_errors(&mut self) {
1093 self.emit_stashed_diagnostics();
1095 if self.has_errors() {
1100 fn span_bug(&mut self, sp: impl Into<MultiSpan>, msg: &str) -> ! {
1101 self.emit_diag_at_span(Diagnostic::new(Bug, msg), sp);
1102 panic::panic_any(ExplicitBug);
1105 fn emit_diag_at_span(&mut self, mut diag: Diagnostic, sp: impl Into<MultiSpan>) {
1106 self.emit_diagnostic(diag.set_span(sp));
1110 fn delay_span_bug(&mut self, sp: impl Into<MultiSpan>, msg: &str) {
1111 // This is technically `self.treat_err_as_bug()` but `delay_span_bug` is called before
1112 // incrementing `err_count` by one, so we need to +1 the comparing.
1113 // FIXME: Would be nice to increment err_count in a more coherent way.
1114 if self.flags.treat_err_as_bug.map_or(false, |c| self.err_count() + 1 >= c.get()) {
1115 // FIXME: don't abort here if report_delayed_bugs is off
1116 self.span_bug(sp, msg);
1118 let mut diagnostic = Diagnostic::new(Level::DelayedBug, msg);
1119 diagnostic.set_span(sp.into());
1120 diagnostic.note(&format!("delayed at {}", std::panic::Location::caller()));
1121 self.emit_diagnostic(&diagnostic)
1124 // FIXME(eddyb) note the comment inside `impl Drop for HandlerInner`, that's
1125 // where the explanation of what "good path" is (also, it should be renamed).
1126 fn delay_good_path_bug(&mut self, msg: &str) {
1127 let diagnostic = Diagnostic::new(Level::DelayedBug, msg);
1128 if self.flags.report_delayed_bugs {
1129 self.emit_diagnostic(&diagnostic);
1131 let backtrace = std::backtrace::Backtrace::force_capture();
1132 self.delayed_good_path_bugs.push(DelayedDiagnostic::with_backtrace(diagnostic, backtrace));
1135 fn failure(&mut self, msg: &str) {
1136 self.emit_diagnostic(&Diagnostic::new(FailureNote, msg));
1139 fn fatal(&mut self, msg: &str) -> FatalError {
1140 self.emit_error(Fatal, msg);
1144 fn err(&mut self, msg: &str) {
1145 self.emit_error(Error { lint: false }, msg);
1148 /// Emit an error; level should be `Error` or `Fatal`.
1149 fn emit_error(&mut self, level: Level, msg: &str) {
1150 if self.treat_err_as_bug() {
1153 self.emit_diagnostic(&Diagnostic::new(level, msg));
1156 fn bug(&mut self, msg: &str) -> ! {
1157 self.emit_diagnostic(&Diagnostic::new(Bug, msg));
1158 panic::panic_any(ExplicitBug);
1161 fn flush_delayed(&mut self, bugs: impl IntoIterator<Item = Diagnostic>, explanation: &str) {
1162 let mut no_bugs = true;
1163 for mut bug in bugs {
1165 // Put the overall explanation before the `DelayedBug`s, to
1166 // frame them better (e.g. separate warnings from them).
1167 self.emit_diagnostic(&Diagnostic::new(Bug, explanation));
1171 // "Undelay" the `DelayedBug`s (into plain `Bug`s).
1172 if bug.level != Level::DelayedBug {
1173 // NOTE(eddyb) not panicking here because we're already producing
1174 // an ICE, and the more information the merrier.
1176 "`flushed_delayed` got diagnostic with level {:?}, \
1177 instead of the expected `DelayedBug`",
1181 bug.level = Level::Bug;
1183 self.emit_diagnostic(&bug);
1186 // Panic with `ExplicitBug` to avoid "unexpected panic" messages.
1188 panic::panic_any(ExplicitBug);
1192 fn bump_lint_err_count(&mut self) {
1193 self.lint_err_count += 1;
1194 self.panic_if_treat_err_as_bug();
1197 fn bump_err_count(&mut self) {
1198 self.err_count += 1;
1199 self.panic_if_treat_err_as_bug();
1202 fn bump_warn_count(&mut self) {
1203 self.warn_count += 1;
1206 fn panic_if_treat_err_as_bug(&self) {
1207 if self.treat_err_as_bug() {
1209 self.err_count() + self.lint_err_count,
1210 self.flags.treat_err_as_bug.map(|c| c.get()).unwrap_or(0),
1212 (1, 1) => panic!("aborting due to `-Z treat-err-as-bug=1`"),
1213 (0, _) | (1, _) => {}
1214 (count, as_bug) => panic!(
1215 "aborting after {} errors due to `-Z treat-err-as-bug={}`",
1223 struct DelayedDiagnostic {
1228 impl DelayedDiagnostic {
1229 fn with_backtrace(diagnostic: Diagnostic, backtrace: Backtrace) -> Self {
1230 DelayedDiagnostic { inner: diagnostic, note: backtrace }
1233 fn decorate(mut self) -> Diagnostic {
1234 self.inner.note(&format!("delayed at {}", self.note));
1239 #[derive(Copy, PartialEq, Eq, Clone, Hash, Debug, Encodable, Decodable)]
1245 /// If this error comes from a lint, don't abort compilation even when abort_if_errors() is called.
1255 impl fmt::Display for Level {
1256 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1257 self.to_str().fmt(f)
1262 fn color(self) -> ColorSpec {
1263 let mut spec = ColorSpec::new();
1265 Bug | DelayedBug | Fatal | Error { .. } => {
1266 spec.set_fg(Some(Color::Red)).set_intense(true);
1269 spec.set_fg(Some(Color::Yellow)).set_intense(cfg!(windows));
1272 spec.set_fg(Some(Color::Green)).set_intense(true);
1275 spec.set_fg(Some(Color::Cyan)).set_intense(true);
1278 Allow => unreachable!(),
1283 pub fn to_str(self) -> &'static str {
1285 Bug | DelayedBug => "error: internal compiler error",
1286 Fatal | Error { .. } => "error",
1287 Warning => "warning",
1290 FailureNote => "failure-note",
1291 Allow => panic!("Shouldn't call on allowed error"),
1295 pub fn is_failure_note(&self) -> bool {
1296 matches!(*self, FailureNote)
1300 // FIXME(eddyb) this doesn't belong here AFAICT, should be moved to callsite.
1301 pub fn add_elided_lifetime_in_path_suggestion(
1302 source_map: &SourceMap,
1303 diag: &mut Diagnostic,
1306 incl_angl_brckt: bool,
1307 insertion_span: Span,
1310 let (replace_span, suggestion) = if incl_angl_brckt {
1311 (insertion_span, anon_lts)
1313 // When possible, prefer a suggestion that replaces the whole
1314 // `Path<T>` expression with `Path<'_, T>`, rather than inserting `'_, `
1315 // at a point (which makes for an ugly/confusing label)
1316 if let Ok(snippet) = source_map.span_to_snippet(path_span) {
1317 // But our spans can get out of whack due to macros; if the place we think
1318 // we want to insert `'_` isn't even within the path expression's span, we
1319 // should bail out of making any suggestion rather than panicking on a
1320 // subtract-with-overflow or string-slice-out-out-bounds (!)
1321 // FIXME: can we do better?
1322 if insertion_span.lo().0 < path_span.lo().0 {
1325 let insertion_index = (insertion_span.lo().0 - path_span.lo().0) as usize;
1326 if insertion_index > snippet.len() {
1329 let (before, after) = snippet.split_at(insertion_index);
1330 (path_span, format!("{}{}{}", before, anon_lts, after))
1332 (insertion_span, anon_lts)
1335 diag.span_suggestion(
1337 &format!("indicate the anonymous lifetime{}", pluralize!(n)),
1339 Applicability::MachineApplicable,
1343 // Useful type to use with `Result<>` indicate that an error has already
1344 // been reported to the user, so no need to continue checking.
1345 #[derive(Clone, Copy, Debug, Encodable, Decodable, Hash, PartialEq, Eq)]
1346 pub struct ErrorReported;
1348 rustc_data_structures::impl_stable_hash_via_hash!(ErrorReported);