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 #![feature(adt_const_params)]
12 #![allow(incomplete_features)]
13 #![allow(rustc::potential_query_instability)]
16 extern crate rustc_macros;
21 pub use emitter::ColorConfig;
23 use rustc_lint_defs::LintExpectationId;
26 use emitter::{is_case_difference, Emitter, EmitterWriter};
27 use registry::Registry;
28 use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap};
29 use rustc_data_structures::stable_hasher::StableHasher;
30 use rustc_data_structures::sync::{self, Lock, Lrc};
31 use rustc_data_structures::AtomicRef;
32 pub use rustc_lint_defs::{pluralize, Applicability};
33 use rustc_serialize::json::Json;
34 use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
35 use rustc_span::source_map::SourceMap;
36 use rustc_span::{Loc, MultiSpan, Span};
39 use std::hash::{Hash, Hasher};
40 use std::num::NonZeroUsize;
43 use std::{error, fmt};
45 use termcolor::{Color, ColorSpec};
47 pub mod annotate_snippet_emitter_writer;
49 mod diagnostic_builder;
56 pub use snippet::Style;
58 pub type PResult<'a, T> = Result<T, DiagnosticBuilder<'a, ErrorGuaranteed>>;
60 // `PResult` is used a lot. Make sure it doesn't unintentionally get bigger.
61 // (See also the comment on `DiagnosticBuilder`'s `diagnostic` field.)
62 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
63 rustc_data_structures::static_assert_size!(PResult<'_, ()>, 16);
64 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
65 rustc_data_structures::static_assert_size!(PResult<'_, bool>, 24);
67 #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, Encodable, Decodable)]
68 pub enum SuggestionStyle {
69 /// Hide the suggested code when displaying this suggestion inline.
71 /// Always hide the suggested code but display the message.
73 /// Do not display this suggestion in the cli output, it is only meant for tools.
75 /// Always show the suggested code.
76 /// This will *not* show the code if the suggestion is inline *and* the suggested code is
79 /// Always show the suggested code independently.
83 impl SuggestionStyle {
84 fn hide_inline(&self) -> bool {
85 !matches!(*self, SuggestionStyle::ShowCode)
89 #[derive(Clone, Debug, PartialEq, Default)]
90 pub struct ToolMetadata(pub Option<Json>);
93 fn new(json: Json) -> Self {
94 ToolMetadata(Some(json))
97 fn is_set(&self) -> bool {
102 impl Hash for ToolMetadata {
103 fn hash<H: Hasher>(&self, _state: &mut H) {}
106 // Doesn't really need to round-trip
107 impl<D: Decoder> Decodable<D> for ToolMetadata {
108 fn decode(_d: &mut D) -> Self {
113 impl<S: Encoder> Encodable<S> for ToolMetadata {
114 fn encode(&self, e: &mut S) -> Result<(), S::Error> {
116 None => e.emit_unit(),
117 Some(json) => json.encode(e),
122 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
123 pub struct CodeSuggestion {
124 /// Each substitute can have multiple variants due to multiple
125 /// applicable suggestions
127 /// `foo.bar` might be replaced with `a.b` or `x.y` by replacing
128 /// `foo` and `bar` on their own:
132 /// Substitution { parts: vec![(0..3, "a"), (4..7, "b")] },
133 /// Substitution { parts: vec![(0..3, "x"), (4..7, "y")] },
137 /// or by replacing the entire span:
141 /// Substitution { parts: vec![(0..7, "a.b")] },
142 /// Substitution { parts: vec![(0..7, "x.y")] },
145 pub substitutions: Vec<Substitution>,
147 /// Visual representation of this suggestion.
148 pub style: SuggestionStyle,
149 /// Whether or not the suggestion is approximate
151 /// Sometimes we may show suggestions with placeholders,
152 /// which are useful for users but not useful for
153 /// tools like rustfix
154 pub applicability: Applicability,
155 /// Tool-specific metadata
156 pub tool_metadata: ToolMetadata,
159 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
160 /// See the docs on `CodeSuggestion::substitutions`
161 pub struct Substitution {
162 pub parts: Vec<SubstitutionPart>,
165 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
166 pub struct SubstitutionPart {
171 /// Used to translate between `Span`s and byte positions within a single output line in highlighted
172 /// code of structured suggestions.
173 #[derive(Debug, Clone, Copy)]
174 pub struct SubstitutionHighlight {
179 impl SubstitutionPart {
180 pub fn is_addition(&self, sm: &SourceMap) -> bool {
181 !self.snippet.is_empty()
183 .span_to_snippet(self.span)
184 .map_or(self.span.is_empty(), |snippet| snippet.trim().is_empty())
187 pub fn is_deletion(&self) -> bool {
188 self.snippet.trim().is_empty()
191 pub fn is_replacement(&self, sm: &SourceMap) -> bool {
192 !self.snippet.is_empty()
194 .span_to_snippet(self.span)
195 .map_or(!self.span.is_empty(), |snippet| !snippet.trim().is_empty())
199 impl CodeSuggestion {
200 /// Returns the assembled code suggestions, whether they should be shown with an underline
201 /// and whether the substitution only differs in capitalization.
205 ) -> Vec<(String, Vec<SubstitutionPart>, Vec<Vec<SubstitutionHighlight>>, bool)> {
206 // For the `Vec<Vec<SubstitutionHighlight>>` value, the first level of the vector
207 // corresponds to the output snippet's lines, while the second level corresponds to the
208 // substrings within that line that should be highlighted.
210 use rustc_span::{CharPos, Pos};
212 /// Append to a buffer the remainder of the line of existing source code, and return the
213 /// count of lines that have been added for accurate highlighting.
216 line_opt: Option<&Cow<'_, str>>,
218 hi_opt: Option<&Loc>,
220 let mut line_count = 0;
221 let (lo, hi_opt) = (lo.col.to_usize(), hi_opt.map(|hi| hi.col.to_usize()));
222 if let Some(line) = line_opt {
223 if let Some(lo) = line.char_indices().map(|(i, _)| i).nth(lo) {
224 let hi_opt = hi_opt.and_then(|hi| line.char_indices().map(|(i, _)| i).nth(hi));
226 Some(hi) if hi > lo => {
227 line_count = line[lo..hi].matches('\n').count();
228 buf.push_str(&line[lo..hi])
232 line_count = line[lo..].matches('\n').count();
233 buf.push_str(&line[lo..])
237 if hi_opt.is_none() {
244 assert!(!self.substitutions.is_empty());
249 // Suggestions coming from macros can have malformed spans. This is a heavy
250 // handed approach to avoid ICEs by ignoring the suggestion outright.
251 let invalid = subst.parts.iter().any(|item| sm.is_valid_span(item.span).is_err());
253 debug!("splice_lines: suggestion contains an invalid span: {:?}", subst);
258 .filter_map(|mut substitution| {
259 // Assumption: all spans are in the same file, and all spans
260 // are disjoint. Sort in ascending order.
261 substitution.parts.sort_by_key(|part| part.span.lo());
263 // Find the bounding span.
264 let lo = substitution.parts.iter().map(|part| part.span.lo()).min()?;
265 let hi = substitution.parts.iter().map(|part| part.span.hi()).max()?;
266 let bounding_span = Span::with_root_ctxt(lo, hi);
267 // The different spans might belong to different contexts, if so ignore suggestion.
268 let lines = sm.span_to_lines(bounding_span).ok()?;
269 assert!(!lines.lines.is_empty() || bounding_span.is_dummy());
271 // We can't splice anything if the source is unavailable.
272 if !sm.ensure_source_file_source_present(lines.file.clone()) {
276 let mut highlights = vec![];
277 // To build up the result, we do this for each span:
278 // - push the line segment trailing the previous span
279 // (at the beginning a "phantom" span pointing at the start of the line)
280 // - push lines between the previous and current span (if any)
281 // - if the previous and current span are not on the same line
282 // push the line segment leading up to the current span
283 // - splice in the span substitution
285 // Finally push the trailing line segment of the last span
286 let sf = &lines.file;
287 let mut prev_hi = sm.lookup_char_pos(bounding_span.lo());
288 prev_hi.col = CharPos::from_usize(0);
290 lines.lines.get(0).and_then(|line0| sf.get_line(line0.line_index));
291 let mut buf = String::new();
293 let mut line_highlight = vec![];
294 // We need to keep track of the difference between the existing code and the added
295 // or deleted code in order to point at the correct column *after* substitution.
297 for part in &substitution.parts {
298 let cur_lo = sm.lookup_char_pos(part.span.lo());
299 if prev_hi.line == cur_lo.line {
301 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, Some(&cur_lo));
303 highlights.push(std::mem::take(&mut line_highlight));
309 highlights.push(std::mem::take(&mut line_highlight));
310 let mut count = push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
312 highlights.push(std::mem::take(&mut line_highlight));
315 // push lines between the previous and current span (if any)
316 for idx in prev_hi.line..(cur_lo.line - 1) {
317 if let Some(line) = sf.get_line(idx) {
318 buf.push_str(line.as_ref());
320 highlights.push(std::mem::take(&mut line_highlight));
323 if let Some(cur_line) = sf.get_line(cur_lo.line - 1) {
324 let end = match cur_line.char_indices().nth(cur_lo.col.to_usize()) {
326 None => cur_line.len(),
328 buf.push_str(&cur_line[..end]);
331 // Add a whole line highlight per line in the snippet.
332 let len: isize = part
336 .unwrap_or(&part.snippet)
343 line_highlight.push(SubstitutionHighlight {
344 start: (cur_lo.col.0 as isize + acc) as usize,
345 end: (cur_lo.col.0 as isize + acc + len) as usize,
347 buf.push_str(&part.snippet);
348 let cur_hi = sm.lookup_char_pos(part.span.hi());
349 if prev_hi.line == cur_lo.line && cur_hi.line == cur_lo.line {
350 // Account for the difference between the width of the current code and the
351 // snippet being suggested, so that the *later* suggestions are correctly
352 // aligned on the screen.
353 acc += len as isize - (cur_hi.col.0 - cur_lo.col.0) as isize;
356 prev_line = sf.get_line(prev_hi.line - 1);
357 for line in part.snippet.split('\n').skip(1) {
359 highlights.push(std::mem::take(&mut line_highlight));
360 let end: usize = line
367 line_highlight.push(SubstitutionHighlight { start: 0, end });
370 highlights.push(std::mem::take(&mut line_highlight));
371 let only_capitalization = is_case_difference(sm, &buf, bounding_span);
372 // if the replacement already ends with a newline, don't print the next line
373 if !buf.ends_with('\n') {
374 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
376 // remove trailing newlines
377 while buf.ends_with('\n') {
380 Some((buf, substitution.parts, highlights, only_capitalization))
386 pub use rustc_span::fatal_error::{FatalError, FatalErrorMarker};
388 /// Signifies that the compiler died with an explicit call to `.bug`
389 /// or `.span_bug` rather than a failed assertion, etc.
390 #[derive(Copy, Clone, Debug)]
391 pub struct ExplicitBug;
393 impl fmt::Display for ExplicitBug {
394 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
395 write!(f, "parser internal bug")
399 impl error::Error for ExplicitBug {}
401 pub use diagnostic::{Diagnostic, DiagnosticId, DiagnosticStyledString, SubDiagnostic};
402 pub use diagnostic_builder::DiagnosticBuilder;
403 use std::backtrace::Backtrace;
405 /// A handler deals with errors and other compiler output.
406 /// Certain errors (fatal, bug, unimpl) may cause immediate exit,
407 /// others log errors for later reporting.
410 inner: Lock<HandlerInner>,
413 /// This inner struct exists to keep it all behind a single lock;
414 /// this is done to prevent possible deadlocks in a multi-threaded compiler,
415 /// as well as inconsistent state observation.
416 struct HandlerInner {
418 /// The number of lint errors that have been emitted.
419 lint_err_count: usize,
420 /// The number of errors that have been emitted, including duplicates.
422 /// This is not necessarily the count that's reported to the user once
423 /// compilation ends.
426 deduplicated_err_count: usize,
427 emitter: Box<dyn Emitter + sync::Send>,
428 delayed_span_bugs: Vec<Diagnostic>,
429 delayed_good_path_bugs: Vec<DelayedDiagnostic>,
431 /// This set contains the `DiagnosticId` of all emitted diagnostics to avoid
432 /// emitting the same diagnostic with extended help (`--teach`) twice, which
433 /// would be unnecessary repetition.
434 taught_diagnostics: FxHashSet<DiagnosticId>,
436 /// Used to suggest rustc --explain <error code>
437 emitted_diagnostic_codes: FxHashSet<DiagnosticId>,
439 /// This set contains a hash of every diagnostic that has been emitted by
440 /// this handler. These hashes is used to avoid emitting the same error
442 emitted_diagnostics: FxHashSet<u128>,
444 /// Stashed diagnostics emitted in one stage of the compiler that may be
445 /// stolen by other stages (e.g. to improve them and add more information).
446 /// The stashed diagnostics count towards the total error count.
447 /// When `.abort_if_errors()` is called, these are also emitted.
448 stashed_diagnostics: FxIndexMap<(Span, StashKey), Diagnostic>,
450 /// The warning count, used for a recap upon finishing
451 deduplicated_warn_count: usize,
453 future_breakage_diagnostics: Vec<Diagnostic>,
455 /// Expected [`Diagnostic`]s store a [`LintExpectationId`] as part of
456 /// the lint level. [`LintExpectationId`]s created early during the compilation
457 /// (before `HirId`s have been defined) are not stable and can therefore not be
458 /// stored on disk. This buffer stores these diagnostics until the ID has been
459 /// replaced by a stable [`LintExpectationId`]. The [`Diagnostic`]s are the
460 /// submitted for storage and added to the list of fulfilled expectations.
461 unstable_expect_diagnostics: Vec<Diagnostic>,
463 /// expected diagnostic will have the level `Expect` which additionally
464 /// carries the [`LintExpectationId`] of the expectation that can be
465 /// marked as fulfilled. This is a collection of all [`LintExpectationId`]s
466 /// that have been marked as fulfilled this way.
468 /// [RFC-2383]: https://rust-lang.github.io/rfcs/2383-lint-reasons.html
469 fulfilled_expectations: FxHashSet<LintExpectationId>,
472 /// A key denoting where from a diagnostic was stashed.
473 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
478 fn default_track_diagnostic(_: &Diagnostic) {}
480 pub static TRACK_DIAGNOSTICS: AtomicRef<fn(&Diagnostic)> =
481 AtomicRef::new(&(default_track_diagnostic as fn(&_)));
483 #[derive(Copy, Clone, Default)]
484 pub struct HandlerFlags {
485 /// If false, warning-level lints are suppressed.
486 /// (rustc: see `--allow warnings` and `--cap-lints`)
487 pub can_emit_warnings: bool,
488 /// If true, error-level diagnostics are upgraded to bug-level.
489 /// (rustc: see `-Z treat-err-as-bug`)
490 pub treat_err_as_bug: Option<NonZeroUsize>,
491 /// If true, immediately emit diagnostics that would otherwise be buffered.
492 /// (rustc: see `-Z dont-buffer-diagnostics` and `-Z treat-err-as-bug`)
493 pub dont_buffer_diagnostics: bool,
494 /// If true, immediately print bugs registered with `delay_span_bug`.
495 /// (rustc: see `-Z report-delayed-bugs`)
496 pub report_delayed_bugs: bool,
497 /// Show macro backtraces.
498 /// (rustc: see `-Z macro-backtrace`)
499 pub macro_backtrace: bool,
500 /// If true, identical diagnostics are reported only once.
501 pub deduplicate_diagnostics: bool,
504 impl Drop for HandlerInner {
506 self.emit_stashed_diagnostics();
508 if !self.has_errors() {
509 let bugs = std::mem::replace(&mut self.delayed_span_bugs, Vec::new());
510 self.flush_delayed(bugs, "no errors encountered even though `delay_span_bug` issued");
513 // FIXME(eddyb) this explains what `delayed_good_path_bugs` are!
514 // They're `delayed_span_bugs` but for "require some diagnostic happened"
515 // instead of "require some error happened". Sadly that isn't ideal, as
516 // lints can be `#[allow]`'d, potentially leading to this triggering.
517 // Also, "good path" should be replaced with a better naming.
518 if !self.has_any_message() {
519 let bugs = std::mem::replace(&mut self.delayed_good_path_bugs, Vec::new());
521 bugs.into_iter().map(DelayedDiagnostic::decorate),
522 "no warnings or errors encountered even though `delayed_good_path_bugs` issued",
527 self.unstable_expect_diagnostics.is_empty(),
528 "all diagnostics with unstable expectations should have been converted",
534 pub fn with_tty_emitter(
535 color_config: ColorConfig,
536 can_emit_warnings: bool,
537 treat_err_as_bug: Option<NonZeroUsize>,
538 sm: Option<Lrc<SourceMap>>,
540 Self::with_tty_emitter_and_flags(
543 HandlerFlags { can_emit_warnings, treat_err_as_bug, ..Default::default() },
547 pub fn with_tty_emitter_and_flags(
548 color_config: ColorConfig,
549 sm: Option<Lrc<SourceMap>>,
552 let emitter = Box::new(EmitterWriter::stderr(
558 flags.macro_backtrace,
560 Self::with_emitter_and_flags(emitter, flags)
564 can_emit_warnings: bool,
565 treat_err_as_bug: Option<NonZeroUsize>,
566 emitter: Box<dyn Emitter + sync::Send>,
568 Handler::with_emitter_and_flags(
570 HandlerFlags { can_emit_warnings, treat_err_as_bug, ..Default::default() },
574 pub fn with_emitter_and_flags(
575 emitter: Box<dyn Emitter + sync::Send>,
580 inner: Lock::new(HandlerInner {
585 deduplicated_err_count: 0,
586 deduplicated_warn_count: 0,
588 delayed_span_bugs: Vec::new(),
589 delayed_good_path_bugs: Vec::new(),
590 taught_diagnostics: Default::default(),
591 emitted_diagnostic_codes: Default::default(),
592 emitted_diagnostics: Default::default(),
593 stashed_diagnostics: Default::default(),
594 future_breakage_diagnostics: Vec::new(),
595 unstable_expect_diagnostics: Vec::new(),
596 fulfilled_expectations: Default::default(),
601 // This is here to not allow mutation of flags;
602 // as of this writing it's only used in tests in librustc_middle.
603 pub fn can_emit_warnings(&self) -> bool {
604 self.flags.can_emit_warnings
607 /// Resets the diagnostic error count as well as the cached emitted diagnostics.
609 /// NOTE: *do not* call this function from rustc. It is only meant to be called from external
610 /// tools that want to reuse a `Parser` cleaning the previously emitted diagnostics as well as
611 /// the overall count of emitted error diagnostics.
612 pub fn reset_err_count(&self) {
613 let mut inner = self.inner.borrow_mut();
615 inner.warn_count = 0;
616 inner.deduplicated_err_count = 0;
617 inner.deduplicated_warn_count = 0;
619 // actually free the underlying memory (which `clear` would not do)
620 inner.delayed_span_bugs = Default::default();
621 inner.delayed_good_path_bugs = Default::default();
622 inner.taught_diagnostics = Default::default();
623 inner.emitted_diagnostic_codes = Default::default();
624 inner.emitted_diagnostics = Default::default();
625 inner.stashed_diagnostics = Default::default();
628 /// Stash a given diagnostic with the given `Span` and `StashKey` as the key for later stealing.
629 pub fn stash_diagnostic(&self, span: Span, key: StashKey, diag: Diagnostic) {
630 let mut inner = self.inner.borrow_mut();
631 // FIXME(Centril, #69537): Consider reintroducing panic on overwriting a stashed diagnostic
632 // if/when we have a more robust macro-friendly replacement for `(span, key)` as a key.
633 // See the PR for a discussion.
634 inner.stashed_diagnostics.insert((span, key), diag);
637 /// Steal a previously stashed diagnostic with the given `Span` and `StashKey` as the key.
638 pub fn steal_diagnostic(&self, span: Span, key: StashKey) -> Option<DiagnosticBuilder<'_, ()>> {
642 .remove(&(span, key))
643 .map(|diag| DiagnosticBuilder::new_diagnostic(self, diag))
646 /// Emit all stashed diagnostics.
647 pub fn emit_stashed_diagnostics(&self) {
648 self.inner.borrow_mut().emit_stashed_diagnostics();
651 /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
653 /// Attempting to `.emit()` the builder will only emit if either:
654 /// * `can_emit_warnings` is `true`
655 /// * `is_force_warn` was set in `DiagnosticId::Lint`
656 pub fn struct_span_warn(
658 span: impl Into<MultiSpan>,
660 ) -> DiagnosticBuilder<'_, ()> {
661 let mut result = self.struct_warn(msg);
662 result.set_span(span);
666 /// Construct a builder at the `Allow` level at the given `span` and with the `msg`.
667 pub fn struct_span_allow(
669 span: impl Into<MultiSpan>,
671 ) -> DiagnosticBuilder<'_, ()> {
672 let mut result = self.struct_allow(msg);
673 result.set_span(span);
677 /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
678 /// Also include a code.
679 pub fn struct_span_warn_with_code(
681 span: impl Into<MultiSpan>,
684 ) -> DiagnosticBuilder<'_, ()> {
685 let mut result = self.struct_span_warn(span, msg);
690 /// Construct a builder at the `Warning` level with the `msg`.
692 /// Attempting to `.emit()` the builder will only emit if either:
693 /// * `can_emit_warnings` is `true`
694 /// * `is_force_warn` was set in `DiagnosticId::Lint`
695 pub fn struct_warn(&self, msg: &str) -> DiagnosticBuilder<'_, ()> {
696 DiagnosticBuilder::new(self, Level::Warning, msg)
699 /// Construct a builder at the `Allow` level with the `msg`.
700 pub fn struct_allow(&self, msg: &str) -> DiagnosticBuilder<'_, ()> {
701 DiagnosticBuilder::new(self, Level::Allow, msg)
704 /// Construct a builder at the `Expect` level with the `msg`.
705 pub fn struct_expect(&self, msg: &str, id: LintExpectationId) -> DiagnosticBuilder<'_, ()> {
706 DiagnosticBuilder::new(self, Level::Expect(id), msg)
709 /// Construct a builder at the `Error` level at the given `span` and with the `msg`.
710 pub fn struct_span_err(
712 span: impl Into<MultiSpan>,
714 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
715 let mut result = self.struct_err(msg);
716 result.set_span(span);
720 /// Construct a builder at the `Error` level at the given `span`, with the `msg`, and `code`.
721 pub fn struct_span_err_with_code(
723 span: impl Into<MultiSpan>,
726 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
727 let mut result = self.struct_span_err(span, msg);
732 /// Construct a builder at the `Error` level with the `msg`.
733 // FIXME: This method should be removed (every error should have an associated error code).
734 pub fn struct_err(&self, msg: &str) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
735 DiagnosticBuilder::new_guaranteeing_error::<{ Level::Error { lint: false } }>(self, msg)
738 /// This should only be used by `rustc_middle::lint::struct_lint_level`. Do not use it for hard errors.
740 pub fn struct_err_lint(&self, msg: &str) -> DiagnosticBuilder<'_, ()> {
741 DiagnosticBuilder::new(self, Level::Error { lint: true }, msg)
744 /// Construct a builder at the `Error` level with the `msg` and the `code`.
745 pub fn struct_err_with_code(
749 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
750 let mut result = self.struct_err(msg);
755 /// Construct a builder at the `Fatal` level at the given `span` and with the `msg`.
756 pub fn struct_span_fatal(
758 span: impl Into<MultiSpan>,
760 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
761 let mut result = self.struct_fatal(msg);
762 result.set_span(span);
766 /// Construct a builder at the `Fatal` level at the given `span`, with the `msg`, and `code`.
767 pub fn struct_span_fatal_with_code(
769 span: impl Into<MultiSpan>,
772 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
773 let mut result = self.struct_span_fatal(span, msg);
778 /// Construct a builder at the `Error` level with the `msg`.
779 pub fn struct_fatal(&self, msg: &str) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
780 DiagnosticBuilder::new_guaranteeing_error::<{ Level::Fatal }>(self, msg)
783 /// Construct a builder at the `Help` level with the `msg`.
784 pub fn struct_help(&self, msg: &str) -> DiagnosticBuilder<'_, ()> {
785 DiagnosticBuilder::new(self, Level::Help, msg)
788 /// Construct a builder at the `Note` level with the `msg`.
789 pub fn struct_note_without_error(&self, msg: &str) -> DiagnosticBuilder<'_, ()> {
790 DiagnosticBuilder::new(self, Level::Note, msg)
793 pub fn span_fatal(&self, span: impl Into<MultiSpan>, msg: &str) -> ! {
794 self.emit_diag_at_span(Diagnostic::new(Fatal, msg), span);
798 pub fn span_fatal_with_code(
800 span: impl Into<MultiSpan>,
804 self.emit_diag_at_span(Diagnostic::new_with_code(Fatal, Some(code), msg), span);
808 pub fn span_err(&self, span: impl Into<MultiSpan>, msg: &str) {
809 self.emit_diag_at_span(Diagnostic::new(Error { lint: false }, msg), span);
812 pub fn span_err_with_code(&self, span: impl Into<MultiSpan>, msg: &str, code: DiagnosticId) {
813 self.emit_diag_at_span(
814 Diagnostic::new_with_code(Error { lint: false }, Some(code), msg),
819 pub fn span_warn(&self, span: impl Into<MultiSpan>, msg: &str) {
820 self.emit_diag_at_span(Diagnostic::new(Warning, msg), span);
823 pub fn span_warn_with_code(&self, span: impl Into<MultiSpan>, msg: &str, code: DiagnosticId) {
824 self.emit_diag_at_span(Diagnostic::new_with_code(Warning, Some(code), msg), span);
827 pub fn span_bug(&self, span: impl Into<MultiSpan>, msg: &str) -> ! {
828 self.inner.borrow_mut().span_bug(span, msg)
832 pub fn delay_span_bug(&self, span: impl Into<MultiSpan>, msg: &str) {
833 self.inner.borrow_mut().delay_span_bug(span, msg)
836 // FIXME(eddyb) note the comment inside `impl Drop for HandlerInner`, that's
837 // where the explanation of what "good path" is (also, it should be renamed).
838 pub fn delay_good_path_bug(&self, msg: &str) {
839 self.inner.borrow_mut().delay_good_path_bug(msg)
842 pub fn span_bug_no_panic(&self, span: impl Into<MultiSpan>, msg: &str) {
843 self.emit_diag_at_span(Diagnostic::new(Bug, msg), span);
846 pub fn span_note_without_error(&self, span: impl Into<MultiSpan>, msg: &str) {
847 self.emit_diag_at_span(Diagnostic::new(Note, msg), span);
850 pub fn span_note_diag(&self, span: Span, msg: &str) -> DiagnosticBuilder<'_, ()> {
851 let mut db = DiagnosticBuilder::new(self, Note, msg);
856 // NOTE: intentionally doesn't raise an error so rustc_codegen_ssa only reports fatal errors in the main thread
857 pub fn fatal(&self, msg: &str) -> FatalError {
858 self.inner.borrow_mut().fatal(msg)
861 pub fn err(&self, msg: &str) {
862 self.inner.borrow_mut().err(msg);
865 pub fn warn(&self, msg: &str) {
866 let mut db = DiagnosticBuilder::new(self, Warning, msg);
870 pub fn note_without_error(&self, msg: &str) {
871 DiagnosticBuilder::new(self, Note, msg).emit();
874 pub fn bug(&self, msg: &str) -> ! {
875 self.inner.borrow_mut().bug(msg)
879 pub fn err_count(&self) -> usize {
880 self.inner.borrow().err_count()
883 pub fn has_errors(&self) -> bool {
884 self.inner.borrow().has_errors()
886 pub fn has_errors_or_lint_errors(&self) -> bool {
887 self.inner.borrow().has_errors_or_lint_errors()
889 pub fn has_errors_or_delayed_span_bugs(&self) -> bool {
890 self.inner.borrow().has_errors_or_delayed_span_bugs()
893 pub fn print_error_count(&self, registry: &Registry) {
894 self.inner.borrow_mut().print_error_count(registry)
897 pub fn take_future_breakage_diagnostics(&self) -> Vec<Diagnostic> {
898 std::mem::take(&mut self.inner.borrow_mut().future_breakage_diagnostics)
901 pub fn abort_if_errors(&self) {
902 self.inner.borrow_mut().abort_if_errors()
905 /// `true` if we haven't taught a diagnostic with this code already.
906 /// The caller must then teach the user about such a diagnostic.
908 /// Used to suppress emitting the same error multiple times with extended explanation when
909 /// calling `-Zteach`.
910 pub fn must_teach(&self, code: &DiagnosticId) -> bool {
911 self.inner.borrow_mut().must_teach(code)
914 pub fn force_print_diagnostic(&self, db: Diagnostic) {
915 self.inner.borrow_mut().force_print_diagnostic(db)
918 pub fn emit_diagnostic(&self, diagnostic: &Diagnostic) {
919 self.inner.borrow_mut().emit_diagnostic(diagnostic)
922 fn emit_diag_at_span(&self, mut diag: Diagnostic, sp: impl Into<MultiSpan>) {
923 let mut inner = self.inner.borrow_mut();
924 inner.emit_diagnostic(diag.set_span(sp));
927 pub fn emit_artifact_notification(&self, path: &Path, artifact_type: &str) {
928 self.inner.borrow_mut().emit_artifact_notification(path, artifact_type)
931 pub fn emit_future_breakage_report(&self, diags: Vec<Diagnostic>) {
932 self.inner.borrow_mut().emitter.emit_future_breakage_report(diags)
935 pub fn emit_unused_externs(&self, lint_level: &str, unused_externs: &[&str]) {
936 self.inner.borrow_mut().emit_unused_externs(lint_level, unused_externs)
939 pub fn update_unstable_expectation_id(
941 unstable_to_stable: &FxHashMap<LintExpectationId, LintExpectationId>,
943 let diags = std::mem::take(&mut self.inner.borrow_mut().unstable_expect_diagnostics);
944 if diags.is_empty() {
948 let mut inner = self.inner.borrow_mut();
949 for mut diag in diags.into_iter() {
950 diag.update_unstable_expectation_id(unstable_to_stable);
954 .get_expectation_id()
955 .expect("all diagnostics inside `unstable_expect_diagnostics` must have a `LintExpectationId`");
956 inner.fulfilled_expectations.insert(stable_id);
958 (*TRACK_DIAGNOSTICS)(&diag);
964 .for_each(|diag| diag.update_unstable_expectation_id(unstable_to_stable));
966 .future_breakage_diagnostics
968 .for_each(|diag| diag.update_unstable_expectation_id(unstable_to_stable));
971 /// This methods steals all [`LintExpectationId`]s that are stored inside
972 /// [`HandlerInner`] and indicate that the linked expectation has been fulfilled.
974 pub fn steal_fulfilled_expectation_ids(&self) -> FxHashSet<LintExpectationId> {
976 self.inner.borrow().unstable_expect_diagnostics.is_empty(),
977 "`HandlerInner::unstable_expect_diagnostics` should be empty at this point",
979 std::mem::take(&mut self.inner.borrow_mut().fulfilled_expectations)
984 fn must_teach(&mut self, code: &DiagnosticId) -> bool {
985 self.taught_diagnostics.insert(code.clone())
988 fn force_print_diagnostic(&mut self, db: Diagnostic) {
989 self.emitter.emit_diagnostic(&db);
992 /// Emit all stashed diagnostics.
993 fn emit_stashed_diagnostics(&mut self) {
994 let diags = self.stashed_diagnostics.drain(..).map(|x| x.1).collect::<Vec<_>>();
995 diags.iter().for_each(|diag| self.emit_diagnostic(diag));
998 // FIXME(eddyb) this should ideally take `diagnostic` by value.
999 fn emit_diagnostic(&mut self, diagnostic: &Diagnostic) {
1000 if diagnostic.level == Level::DelayedBug {
1001 // FIXME(eddyb) this should check for `has_errors` and stop pushing
1002 // once *any* errors were emitted (and truncate `delayed_span_bugs`
1003 // when an error is first emitted, also), but maybe there's a case
1004 // in which that's not sound? otherwise this is really inefficient.
1005 self.delayed_span_bugs.push(diagnostic.clone());
1007 if !self.flags.report_delayed_bugs {
1012 if diagnostic.has_future_breakage() {
1013 self.future_breakage_diagnostics.push(diagnostic.clone());
1016 if diagnostic.level == Warning
1017 && !self.flags.can_emit_warnings
1018 && !diagnostic.is_force_warn()
1020 if diagnostic.has_future_breakage() {
1021 (*TRACK_DIAGNOSTICS)(diagnostic);
1026 // The `LintExpectationId` can be stable or unstable depending on when it was created.
1027 // Diagnostics created before the definition of `HirId`s are unstable and can not yet
1028 // be stored. Instead, they are buffered until the `LintExpectationId` is replaced by
1029 // a stable one by the `LintLevelsBuilder`.
1030 if let Level::Expect(LintExpectationId::Unstable { .. }) = diagnostic.level {
1031 self.unstable_expect_diagnostics.push(diagnostic.clone());
1035 (*TRACK_DIAGNOSTICS)(diagnostic);
1037 if let Level::Expect(expectation_id) = diagnostic.level {
1038 self.fulfilled_expectations.insert(expectation_id);
1040 } else if diagnostic.level == Allow {
1044 if let Some(ref code) = diagnostic.code {
1045 self.emitted_diagnostic_codes.insert(code.clone());
1048 let already_emitted = |this: &mut Self| {
1049 let mut hasher = StableHasher::new();
1050 diagnostic.hash(&mut hasher);
1051 let diagnostic_hash = hasher.finish();
1052 !this.emitted_diagnostics.insert(diagnostic_hash)
1055 // Only emit the diagnostic if we've been asked to deduplicate and
1056 // haven't already emitted an equivalent diagnostic.
1057 if !(self.flags.deduplicate_diagnostics && already_emitted(self)) {
1058 self.emitter.emit_diagnostic(diagnostic);
1059 if diagnostic.is_error() {
1060 self.deduplicated_err_count += 1;
1061 } else if diagnostic.level == Warning {
1062 self.deduplicated_warn_count += 1;
1065 if diagnostic.is_error() {
1066 if matches!(diagnostic.level, Level::Error { lint: true }) {
1067 self.bump_lint_err_count();
1069 self.bump_err_count();
1072 self.bump_warn_count();
1076 fn emit_artifact_notification(&mut self, path: &Path, artifact_type: &str) {
1077 self.emitter.emit_artifact_notification(path, artifact_type);
1080 fn emit_unused_externs(&mut self, lint_level: &str, unused_externs: &[&str]) {
1081 self.emitter.emit_unused_externs(lint_level, unused_externs);
1084 fn treat_err_as_bug(&self) -> bool {
1087 .map_or(false, |c| self.err_count() + self.lint_err_count >= c.get())
1090 fn print_error_count(&mut self, registry: &Registry) {
1091 self.emit_stashed_diagnostics();
1093 let warnings = match self.deduplicated_warn_count {
1095 1 => "1 warning emitted".to_string(),
1096 count => format!("{} warnings emitted", count),
1098 let errors = match self.deduplicated_err_count {
1100 1 => "aborting due to previous error".to_string(),
1101 count => format!("aborting due to {} previous errors", count),
1103 if self.treat_err_as_bug() {
1107 match (errors.len(), warnings.len()) {
1109 (0, _) => self.emitter.emit_diagnostic(&Diagnostic::new(Level::Warning, &warnings)),
1111 let _ = self.fatal(&errors);
1114 let _ = self.fatal(&format!("{}; {}", &errors, &warnings));
1118 let can_show_explain = self.emitter.should_show_explain();
1119 let are_there_diagnostics = !self.emitted_diagnostic_codes.is_empty();
1120 if can_show_explain && are_there_diagnostics {
1121 let mut error_codes = self
1122 .emitted_diagnostic_codes
1124 .filter_map(|x| match &x {
1125 DiagnosticId::Error(s)
1126 if registry.try_find_description(s).map_or(false, |o| o.is_some()) =>
1132 .collect::<Vec<_>>();
1133 if !error_codes.is_empty() {
1135 if error_codes.len() > 1 {
1136 let limit = if error_codes.len() > 9 { 9 } else { error_codes.len() };
1137 self.failure(&format!(
1138 "Some errors have detailed explanations: {}{}",
1139 error_codes[..limit].join(", "),
1140 if error_codes.len() > 9 { "..." } else { "." }
1142 self.failure(&format!(
1143 "For more information about an error, try \
1144 `rustc --explain {}`.",
1148 self.failure(&format!(
1149 "For more information about this error, try \
1150 `rustc --explain {}`.",
1159 fn err_count(&self) -> usize {
1160 self.err_count + self.stashed_diagnostics.len()
1163 fn has_errors(&self) -> bool {
1164 self.err_count() > 0
1166 fn has_errors_or_lint_errors(&self) -> bool {
1167 self.has_errors() || self.lint_err_count > 0
1169 fn has_errors_or_delayed_span_bugs(&self) -> bool {
1170 self.has_errors() || !self.delayed_span_bugs.is_empty()
1172 fn has_any_message(&self) -> bool {
1173 self.err_count() > 0 || self.lint_err_count > 0 || self.warn_count > 0
1176 fn abort_if_errors(&mut self) {
1177 self.emit_stashed_diagnostics();
1179 if self.has_errors() {
1184 fn span_bug(&mut self, sp: impl Into<MultiSpan>, msg: &str) -> ! {
1185 self.emit_diag_at_span(Diagnostic::new(Bug, msg), sp);
1186 panic::panic_any(ExplicitBug);
1189 fn emit_diag_at_span(&mut self, mut diag: Diagnostic, sp: impl Into<MultiSpan>) {
1190 self.emit_diagnostic(diag.set_span(sp));
1194 fn delay_span_bug(&mut self, sp: impl Into<MultiSpan>, msg: &str) {
1195 // This is technically `self.treat_err_as_bug()` but `delay_span_bug` is called before
1196 // incrementing `err_count` by one, so we need to +1 the comparing.
1197 // FIXME: Would be nice to increment err_count in a more coherent way.
1198 if self.flags.treat_err_as_bug.map_or(false, |c| self.err_count() + 1 >= c.get()) {
1199 // FIXME: don't abort here if report_delayed_bugs is off
1200 self.span_bug(sp, msg);
1202 let mut diagnostic = Diagnostic::new(Level::DelayedBug, msg);
1203 diagnostic.set_span(sp.into());
1204 diagnostic.note(&format!("delayed at {}", std::panic::Location::caller()));
1205 self.emit_diagnostic(&diagnostic)
1208 // FIXME(eddyb) note the comment inside `impl Drop for HandlerInner`, that's
1209 // where the explanation of what "good path" is (also, it should be renamed).
1210 fn delay_good_path_bug(&mut self, msg: &str) {
1211 let diagnostic = Diagnostic::new(Level::DelayedBug, msg);
1212 if self.flags.report_delayed_bugs {
1213 self.emit_diagnostic(&diagnostic);
1215 let backtrace = std::backtrace::Backtrace::force_capture();
1216 self.delayed_good_path_bugs.push(DelayedDiagnostic::with_backtrace(diagnostic, backtrace));
1219 fn failure(&mut self, msg: &str) {
1220 self.emit_diagnostic(&Diagnostic::new(FailureNote, msg));
1223 fn fatal(&mut self, msg: &str) -> FatalError {
1224 self.emit_error(Fatal, msg);
1228 fn err(&mut self, msg: &str) {
1229 self.emit_error(Error { lint: false }, msg);
1232 /// Emit an error; level should be `Error` or `Fatal`.
1233 fn emit_error(&mut self, level: Level, msg: &str) {
1234 if self.treat_err_as_bug() {
1237 self.emit_diagnostic(&Diagnostic::new(level, msg));
1240 fn bug(&mut self, msg: &str) -> ! {
1241 self.emit_diagnostic(&Diagnostic::new(Bug, msg));
1242 panic::panic_any(ExplicitBug);
1245 fn flush_delayed(&mut self, bugs: impl IntoIterator<Item = Diagnostic>, explanation: &str) {
1246 let mut no_bugs = true;
1247 for mut bug in bugs {
1249 // Put the overall explanation before the `DelayedBug`s, to
1250 // frame them better (e.g. separate warnings from them).
1251 self.emit_diagnostic(&Diagnostic::new(Bug, explanation));
1255 // "Undelay" the `DelayedBug`s (into plain `Bug`s).
1256 if bug.level != Level::DelayedBug {
1257 // NOTE(eddyb) not panicking here because we're already producing
1258 // an ICE, and the more information the merrier.
1260 "`flushed_delayed` got diagnostic with level {:?}, \
1261 instead of the expected `DelayedBug`",
1265 bug.level = Level::Bug;
1267 self.emit_diagnostic(&bug);
1270 // Panic with `ExplicitBug` to avoid "unexpected panic" messages.
1272 panic::panic_any(ExplicitBug);
1276 fn bump_lint_err_count(&mut self) {
1277 self.lint_err_count += 1;
1278 self.panic_if_treat_err_as_bug();
1281 fn bump_err_count(&mut self) {
1282 self.err_count += 1;
1283 self.panic_if_treat_err_as_bug();
1286 fn bump_warn_count(&mut self) {
1287 self.warn_count += 1;
1290 fn panic_if_treat_err_as_bug(&self) {
1291 if self.treat_err_as_bug() {
1293 self.err_count() + self.lint_err_count,
1294 self.flags.treat_err_as_bug.map(|c| c.get()).unwrap_or(0),
1296 (1, 1) => panic!("aborting due to `-Z treat-err-as-bug=1`"),
1297 (0, _) | (1, _) => {}
1298 (count, as_bug) => panic!(
1299 "aborting after {} errors due to `-Z treat-err-as-bug={}`",
1307 struct DelayedDiagnostic {
1312 impl DelayedDiagnostic {
1313 fn with_backtrace(diagnostic: Diagnostic, backtrace: Backtrace) -> Self {
1314 DelayedDiagnostic { inner: diagnostic, note: backtrace }
1317 fn decorate(mut self) -> Diagnostic {
1318 self.inner.note(&format!("delayed at {}", self.note));
1323 #[derive(Copy, PartialEq, Eq, Clone, Hash, Debug, Encodable, Decodable)]
1329 /// If this error comes from a lint, don't abort compilation even when abort_if_errors() is called.
1337 Expect(LintExpectationId),
1340 impl fmt::Display for Level {
1341 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1342 self.to_str().fmt(f)
1347 fn color(self) -> ColorSpec {
1348 let mut spec = ColorSpec::new();
1350 Bug | DelayedBug | Fatal | Error { .. } => {
1351 spec.set_fg(Some(Color::Red)).set_intense(true);
1354 spec.set_fg(Some(Color::Yellow)).set_intense(cfg!(windows));
1357 spec.set_fg(Some(Color::Green)).set_intense(true);
1360 spec.set_fg(Some(Color::Cyan)).set_intense(true);
1363 Allow | Expect(_) => unreachable!(),
1368 pub fn to_str(self) -> &'static str {
1370 Bug | DelayedBug => "error: internal compiler error",
1371 Fatal | Error { .. } => "error",
1372 Warning => "warning",
1375 FailureNote => "failure-note",
1376 Allow => panic!("Shouldn't call on allowed error"),
1377 Expect(_) => panic!("Shouldn't call on expected error"),
1381 pub fn is_failure_note(&self) -> bool {
1382 matches!(*self, FailureNote)
1385 pub fn get_expectation_id(&self) -> Option<LintExpectationId> {
1387 Level::Expect(id) => Some(*id),
1393 // FIXME(eddyb) this doesn't belong here AFAICT, should be moved to callsite.
1394 pub fn add_elided_lifetime_in_path_suggestion(
1395 source_map: &SourceMap,
1396 diag: &mut Diagnostic,
1399 incl_angl_brckt: bool,
1400 insertion_span: Span,
1403 let (replace_span, suggestion) = if incl_angl_brckt {
1404 (insertion_span, anon_lts)
1406 // When possible, prefer a suggestion that replaces the whole
1407 // `Path<T>` expression with `Path<'_, T>`, rather than inserting `'_, `
1408 // at a point (which makes for an ugly/confusing label)
1409 if let Ok(snippet) = source_map.span_to_snippet(path_span) {
1410 // But our spans can get out of whack due to macros; if the place we think
1411 // we want to insert `'_` isn't even within the path expression's span, we
1412 // should bail out of making any suggestion rather than panicking on a
1413 // subtract-with-overflow or string-slice-out-out-bounds (!)
1414 // FIXME: can we do better?
1415 if insertion_span.lo().0 < path_span.lo().0 {
1418 let insertion_index = (insertion_span.lo().0 - path_span.lo().0) as usize;
1419 if insertion_index > snippet.len() {
1422 let (before, after) = snippet.split_at(insertion_index);
1423 (path_span, format!("{}{}{}", before, anon_lts, after))
1425 (insertion_span, anon_lts)
1428 diag.span_suggestion(
1430 &format!("indicate the anonymous lifetime{}", pluralize!(n)),
1432 Applicability::MachineApplicable,
1436 // Useful type to use with `Result<>` indicate that an error has already
1437 // been reported to the user, so no need to continue checking.
1438 #[derive(Clone, Copy, Debug, Encodable, Decodable, Hash, PartialEq, Eq)]
1439 pub struct ErrorGuaranteed;
1441 rustc_data_structures::impl_stable_hash_via_hash!(ErrorGuaranteed);