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)]
14 extern crate rustc_macros;
19 pub use emitter::ColorConfig;
23 use emitter::{is_case_difference, Emitter, EmitterWriter};
24 use registry::Registry;
25 use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
26 use rustc_data_structures::stable_hasher::StableHasher;
27 use rustc_data_structures::sync::{self, Lock, Lrc};
28 use rustc_data_structures::AtomicRef;
29 pub use rustc_lint_defs::{pluralize, Applicability};
30 use rustc_serialize::json::Json;
31 use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
32 use rustc_span::source_map::SourceMap;
33 use rustc_span::{Loc, MultiSpan, Span};
36 use std::hash::{Hash, Hasher};
37 use std::num::NonZeroUsize;
40 use std::{error, fmt};
42 use termcolor::{Color, ColorSpec};
44 pub mod annotate_snippet_emitter_writer;
46 mod diagnostic_builder;
53 pub use snippet::Style;
55 pub type PResult<'a, T> = Result<T, DiagnosticBuilder<'a>>;
57 // `PResult` is used a lot. Make sure it doesn't unintentionally get bigger.
58 // (See also the comment on `DiagnosticBuilderInner`.)
59 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
60 rustc_data_structures::static_assert_size!(PResult<'_, bool>, 16);
62 #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, Encodable, Decodable)]
63 pub enum SuggestionStyle {
64 /// Hide the suggested code when displaying this suggestion inline.
66 /// Always hide the suggested code but display the message.
68 /// Do not display this suggestion in the cli output, it is only meant for tools.
70 /// Always show the suggested code.
71 /// This will *not* show the code if the suggestion is inline *and* the suggested code is
74 /// Always show the suggested code independently.
78 impl SuggestionStyle {
79 fn hide_inline(&self) -> bool {
80 !matches!(*self, SuggestionStyle::ShowCode)
84 #[derive(Clone, Debug, PartialEq, Default)]
85 pub struct ToolMetadata(pub Option<Json>);
88 fn new(json: Json) -> Self {
89 ToolMetadata(Some(json))
92 fn is_set(&self) -> bool {
97 impl Hash for ToolMetadata {
98 fn hash<H: Hasher>(&self, _state: &mut H) {}
101 // Doesn't really need to round-trip
102 impl<D: Decoder> Decodable<D> for ToolMetadata {
103 fn decode(_d: &mut D) -> Result<Self, D::Error> {
104 Ok(ToolMetadata(None))
108 impl<S: Encoder> Encodable<S> for ToolMetadata {
109 fn encode(&self, e: &mut S) -> Result<(), S::Error> {
111 None => e.emit_unit(),
112 Some(json) => json.encode(e),
117 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
118 pub struct CodeSuggestion {
119 /// Each substitute can have multiple variants due to multiple
120 /// applicable suggestions
122 /// `foo.bar` might be replaced with `a.b` or `x.y` by replacing
123 /// `foo` and `bar` on their own:
127 /// Substitution { parts: vec![(0..3, "a"), (4..7, "b")] },
128 /// Substitution { parts: vec![(0..3, "x"), (4..7, "y")] },
132 /// or by replacing the entire span:
136 /// Substitution { parts: vec![(0..7, "a.b")] },
137 /// Substitution { parts: vec![(0..7, "x.y")] },
140 pub substitutions: Vec<Substitution>,
142 /// Visual representation of this suggestion.
143 pub style: SuggestionStyle,
144 /// Whether or not the suggestion is approximate
146 /// Sometimes we may show suggestions with placeholders,
147 /// which are useful for users but not useful for
148 /// tools like rustfix
149 pub applicability: Applicability,
150 /// Tool-specific metadata
151 pub tool_metadata: ToolMetadata,
154 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
155 /// See the docs on `CodeSuggestion::substitutions`
156 pub struct Substitution {
157 pub parts: Vec<SubstitutionPart>,
160 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
161 pub struct SubstitutionPart {
166 /// Used to translate between `Span`s and byte positions within a single output line in highlighted
167 /// code of structured suggestions.
168 #[derive(Debug, Clone, Copy)]
169 pub struct SubstitutionHighlight {
174 impl SubstitutionPart {
175 pub fn is_addition(&self, sm: &SourceMap) -> bool {
176 !self.snippet.is_empty()
178 .span_to_snippet(self.span)
179 .map_or(self.span.is_empty(), |snippet| snippet.trim().is_empty())
182 pub fn is_deletion(&self) -> bool {
183 self.snippet.trim().is_empty()
186 pub fn is_replacement(&self, sm: &SourceMap) -> bool {
187 !self.snippet.is_empty()
189 .span_to_snippet(self.span)
190 .map_or(!self.span.is_empty(), |snippet| !snippet.trim().is_empty())
194 impl CodeSuggestion {
195 /// Returns the assembled code suggestions, whether they should be shown with an underline
196 /// and whether the substitution only differs in capitalization.
200 ) -> Vec<(String, Vec<SubstitutionPart>, Vec<Vec<SubstitutionHighlight>>, bool)> {
201 // For the `Vec<Vec<SubstitutionHighlight>>` value, the first level of the vector
202 // corresponds to the output snippet's lines, while the second level corresponds to the
203 // substrings within that line that should be highlighted.
205 use rustc_span::{CharPos, Pos};
207 /// Append to a buffer the remainder of the line of existing source code, and return the
208 /// count of lines that have been added for accurate highlighting.
211 line_opt: Option<&Cow<'_, str>>,
213 hi_opt: Option<&Loc>,
215 let mut line_count = 0;
216 let (lo, hi_opt) = (lo.col.to_usize(), hi_opt.map(|hi| hi.col.to_usize()));
217 if let Some(line) = line_opt {
218 if let Some(lo) = line.char_indices().map(|(i, _)| i).nth(lo) {
219 let hi_opt = hi_opt.and_then(|hi| line.char_indices().map(|(i, _)| i).nth(hi));
221 Some(hi) if hi > lo => {
222 line_count = line[lo..hi].matches('\n').count();
223 buf.push_str(&line[lo..hi])
227 line_count = line[lo..].matches('\n').count();
228 buf.push_str(&line[lo..])
232 if hi_opt.is_none() {
239 assert!(!self.substitutions.is_empty());
244 // Suggestions coming from macros can have malformed spans. This is a heavy
245 // handed approach to avoid ICEs by ignoring the suggestion outright.
246 let invalid = subst.parts.iter().any(|item| sm.is_valid_span(item.span).is_err());
248 debug!("splice_lines: suggestion contains an invalid span: {:?}", subst);
253 .filter_map(|mut substitution| {
254 // Assumption: all spans are in the same file, and all spans
255 // are disjoint. Sort in ascending order.
256 substitution.parts.sort_by_key(|part| part.span.lo());
258 // Find the bounding span.
259 let lo = substitution.parts.iter().map(|part| part.span.lo()).min()?;
260 let hi = substitution.parts.iter().map(|part| part.span.hi()).max()?;
261 let bounding_span = Span::with_root_ctxt(lo, hi);
262 // The different spans might belong to different contexts, if so ignore suggestion.
263 let lines = sm.span_to_lines(bounding_span).ok()?;
264 assert!(!lines.lines.is_empty() || bounding_span.is_dummy());
266 // We can't splice anything if the source is unavailable.
267 if !sm.ensure_source_file_source_present(lines.file.clone()) {
271 let mut highlights = vec![];
272 // To build up the result, we do this for each span:
273 // - push the line segment trailing the previous span
274 // (at the beginning a "phantom" span pointing at the start of the line)
275 // - push lines between the previous and current span (if any)
276 // - if the previous and current span are not on the same line
277 // push the line segment leading up to the current span
278 // - splice in the span substitution
280 // Finally push the trailing line segment of the last span
281 let sf = &lines.file;
282 let mut prev_hi = sm.lookup_char_pos(bounding_span.lo());
283 prev_hi.col = CharPos::from_usize(0);
285 lines.lines.get(0).and_then(|line0| sf.get_line(line0.line_index));
286 let mut buf = String::new();
288 let mut line_highlight = vec![];
289 // We need to keep track of the difference between the existing code and the added
290 // or deleted code in order to point at the correct column *after* substitution.
292 for part in &substitution.parts {
293 let cur_lo = sm.lookup_char_pos(part.span.lo());
294 if prev_hi.line == cur_lo.line {
296 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, Some(&cur_lo));
298 highlights.push(std::mem::take(&mut line_highlight));
304 highlights.push(std::mem::take(&mut line_highlight));
305 let mut count = push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
307 highlights.push(std::mem::take(&mut line_highlight));
310 // push lines between the previous and current span (if any)
311 for idx in prev_hi.line..(cur_lo.line - 1) {
312 if let Some(line) = sf.get_line(idx) {
313 buf.push_str(line.as_ref());
315 highlights.push(std::mem::take(&mut line_highlight));
318 if let Some(cur_line) = sf.get_line(cur_lo.line - 1) {
319 let end = match cur_line.char_indices().nth(cur_lo.col.to_usize()) {
321 None => cur_line.len(),
323 buf.push_str(&cur_line[..end]);
326 // Add a whole line highlight per line in the snippet.
327 let len: isize = part
331 .unwrap_or(&part.snippet)
338 line_highlight.push(SubstitutionHighlight {
339 start: (cur_lo.col.0 as isize + acc) as usize,
340 end: (cur_lo.col.0 as isize + acc + len) as usize,
342 buf.push_str(&part.snippet);
343 let cur_hi = sm.lookup_char_pos(part.span.hi());
344 if prev_hi.line == cur_lo.line && cur_hi.line == cur_lo.line {
345 // Account for the difference between the width of the current code and the
346 // snippet being suggested, so that the *later* suggestions are correctly
347 // aligned on the screen.
348 acc += len as isize - (cur_hi.col.0 - cur_lo.col.0) as isize;
351 prev_line = sf.get_line(prev_hi.line - 1);
352 for line in part.snippet.split('\n').skip(1) {
354 highlights.push(std::mem::take(&mut line_highlight));
355 let end: usize = line
362 line_highlight.push(SubstitutionHighlight { start: 0, end });
365 highlights.push(std::mem::take(&mut line_highlight));
366 let only_capitalization = is_case_difference(sm, &buf, bounding_span);
367 // if the replacement already ends with a newline, don't print the next line
368 if !buf.ends_with('\n') {
369 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
371 // remove trailing newlines
372 while buf.ends_with('\n') {
375 Some((buf, substitution.parts, highlights, only_capitalization))
381 pub use rustc_span::fatal_error::{FatalError, FatalErrorMarker};
383 /// Signifies that the compiler died with an explicit call to `.bug`
384 /// or `.span_bug` rather than a failed assertion, etc.
385 #[derive(Copy, Clone, Debug)]
386 pub struct ExplicitBug;
388 impl fmt::Display for ExplicitBug {
389 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
390 write!(f, "parser internal bug")
394 impl error::Error for ExplicitBug {}
396 pub use diagnostic::{Diagnostic, DiagnosticId, DiagnosticStyledString, SubDiagnostic};
397 pub use diagnostic_builder::DiagnosticBuilder;
398 use std::backtrace::Backtrace;
400 /// A handler deals with errors and other compiler output.
401 /// Certain errors (fatal, bug, unimpl) may cause immediate exit,
402 /// others log errors for later reporting.
405 inner: Lock<HandlerInner>,
408 /// This inner struct exists to keep it all behind a single lock;
409 /// this is done to prevent possible deadlocks in a multi-threaded compiler,
410 /// as well as inconsistent state observation.
411 struct HandlerInner {
413 /// The number of lint errors that have been emitted.
414 lint_err_count: usize,
415 /// The number of errors that have been emitted, including duplicates.
417 /// This is not necessarily the count that's reported to the user once
418 /// compilation ends.
421 deduplicated_err_count: usize,
422 emitter: Box<dyn Emitter + sync::Send>,
423 delayed_span_bugs: Vec<Diagnostic>,
424 delayed_good_path_bugs: Vec<DelayedDiagnostic>,
426 /// This set contains the `DiagnosticId` of all emitted diagnostics to avoid
427 /// emitting the same diagnostic with extended help (`--teach`) twice, which
428 /// would be unnecessary repetition.
429 taught_diagnostics: FxHashSet<DiagnosticId>,
431 /// Used to suggest rustc --explain <error code>
432 emitted_diagnostic_codes: FxHashSet<DiagnosticId>,
434 /// This set contains a hash of every diagnostic that has been emitted by
435 /// this handler. These hashes is used to avoid emitting the same error
437 emitted_diagnostics: FxHashSet<u128>,
439 /// Stashed diagnostics emitted in one stage of the compiler that may be
440 /// stolen by other stages (e.g. to improve them and add more information).
441 /// The stashed diagnostics count towards the total error count.
442 /// When `.abort_if_errors()` is called, these are also emitted.
443 stashed_diagnostics: FxIndexMap<(Span, StashKey), Diagnostic>,
445 /// The warning count, used for a recap upon finishing
446 deduplicated_warn_count: usize,
448 future_breakage_diagnostics: Vec<Diagnostic>,
450 /// If set to `true`, no warning or error will be emitted.
454 /// A key denoting where from a diagnostic was stashed.
455 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
460 fn default_track_diagnostic(_: &Diagnostic) {}
462 pub static TRACK_DIAGNOSTICS: AtomicRef<fn(&Diagnostic)> =
463 AtomicRef::new(&(default_track_diagnostic as fn(&_)));
465 #[derive(Copy, Clone, Default)]
466 pub struct HandlerFlags {
467 /// If false, warning-level lints are suppressed.
468 /// (rustc: see `--allow warnings` and `--cap-lints`)
469 pub can_emit_warnings: bool,
470 /// If true, error-level diagnostics are upgraded to bug-level.
471 /// (rustc: see `-Z treat-err-as-bug`)
472 pub treat_err_as_bug: Option<NonZeroUsize>,
473 /// If true, immediately emit diagnostics that would otherwise be buffered.
474 /// (rustc: see `-Z dont-buffer-diagnostics` and `-Z treat-err-as-bug`)
475 pub dont_buffer_diagnostics: bool,
476 /// If true, immediately print bugs registered with `delay_span_bug`.
477 /// (rustc: see `-Z report-delayed-bugs`)
478 pub report_delayed_bugs: bool,
479 /// Show macro backtraces.
480 /// (rustc: see `-Z macro-backtrace`)
481 pub macro_backtrace: bool,
482 /// If true, identical diagnostics are reported only once.
483 pub deduplicate_diagnostics: bool,
486 impl Drop for HandlerInner {
488 self.emit_stashed_diagnostics();
490 if !self.has_errors() {
491 let bugs = std::mem::replace(&mut self.delayed_span_bugs, Vec::new());
492 self.flush_delayed(bugs, "no errors encountered even though `delay_span_bug` issued");
495 if !self.has_any_message() {
496 let bugs = std::mem::replace(&mut self.delayed_good_path_bugs, Vec::new());
498 bugs.into_iter().map(DelayedDiagnostic::decorate).collect(),
499 "no warnings or errors encountered even though `delayed_good_path_bugs` issued",
506 pub fn with_tty_emitter(
507 color_config: ColorConfig,
508 can_emit_warnings: bool,
509 treat_err_as_bug: Option<NonZeroUsize>,
510 sm: Option<Lrc<SourceMap>>,
512 Self::with_tty_emitter_and_flags(
515 HandlerFlags { can_emit_warnings, treat_err_as_bug, ..Default::default() },
519 pub fn with_tty_emitter_and_flags(
520 color_config: ColorConfig,
521 sm: Option<Lrc<SourceMap>>,
524 let emitter = Box::new(EmitterWriter::stderr(
530 flags.macro_backtrace,
532 Self::with_emitter_and_flags(emitter, flags)
536 can_emit_warnings: bool,
537 treat_err_as_bug: Option<NonZeroUsize>,
538 emitter: Box<dyn Emitter + sync::Send>,
540 Handler::with_emitter_and_flags(
542 HandlerFlags { can_emit_warnings, treat_err_as_bug, ..Default::default() },
546 pub fn with_emitter_and_flags(
547 emitter: Box<dyn Emitter + sync::Send>,
552 inner: Lock::new(HandlerInner {
557 deduplicated_err_count: 0,
558 deduplicated_warn_count: 0,
560 delayed_span_bugs: Vec::new(),
561 delayed_good_path_bugs: Vec::new(),
562 taught_diagnostics: Default::default(),
563 emitted_diagnostic_codes: Default::default(),
564 emitted_diagnostics: Default::default(),
565 stashed_diagnostics: Default::default(),
566 future_breakage_diagnostics: Vec::new(),
572 pub fn with_disabled_diagnostic<T, F: FnOnce() -> T>(&self, f: F) -> T {
573 let prev = self.inner.borrow_mut().quiet;
574 self.inner.borrow_mut().quiet = true;
576 self.inner.borrow_mut().quiet = prev;
580 // This is here to not allow mutation of flags;
581 // as of this writing it's only used in tests in librustc_middle.
582 pub fn can_emit_warnings(&self) -> bool {
583 self.flags.can_emit_warnings
586 /// Resets the diagnostic error count as well as the cached emitted diagnostics.
588 /// NOTE: *do not* call this function from rustc. It is only meant to be called from external
589 /// tools that want to reuse a `Parser` cleaning the previously emitted diagnostics as well as
590 /// the overall count of emitted error diagnostics.
591 pub fn reset_err_count(&self) {
592 let mut inner = self.inner.borrow_mut();
594 inner.warn_count = 0;
595 inner.deduplicated_err_count = 0;
596 inner.deduplicated_warn_count = 0;
598 // actually free the underlying memory (which `clear` would not do)
599 inner.delayed_span_bugs = Default::default();
600 inner.delayed_good_path_bugs = Default::default();
601 inner.taught_diagnostics = Default::default();
602 inner.emitted_diagnostic_codes = Default::default();
603 inner.emitted_diagnostics = Default::default();
604 inner.stashed_diagnostics = Default::default();
607 /// Stash a given diagnostic with the given `Span` and `StashKey` as the key for later stealing.
608 pub fn stash_diagnostic(&self, span: Span, key: StashKey, diag: Diagnostic) {
609 let mut inner = self.inner.borrow_mut();
610 // FIXME(Centril, #69537): Consider reintroducing panic on overwriting a stashed diagnostic
611 // if/when we have a more robust macro-friendly replacement for `(span, key)` as a key.
612 // See the PR for a discussion.
613 inner.stashed_diagnostics.insert((span, key), diag);
616 /// Steal a previously stashed diagnostic with the given `Span` and `StashKey` as the key.
617 pub fn steal_diagnostic(&self, span: Span, key: StashKey) -> Option<DiagnosticBuilder<'_>> {
621 .remove(&(span, key))
622 .map(|diag| DiagnosticBuilder::new_diagnostic(self, diag))
625 /// Emit all stashed diagnostics.
626 pub fn emit_stashed_diagnostics(&self) {
627 self.inner.borrow_mut().emit_stashed_diagnostics();
630 /// Construct a dummy builder with `Level::Cancelled`.
632 /// Using this will neither report anything to the user (e.g. a warning),
633 /// nor will compilation cancel as a result.
634 pub fn struct_dummy(&self) -> DiagnosticBuilder<'_> {
635 DiagnosticBuilder::new(self, Level::Cancelled, "")
638 /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
640 /// The builder will be canceled if warnings cannot be emitted.
641 pub fn struct_span_warn(&self, span: impl Into<MultiSpan>, msg: &str) -> DiagnosticBuilder<'_> {
642 let mut result = self.struct_warn(msg);
643 result.set_span(span);
647 /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
649 /// This will "force" the warning meaning it will not be canceled even
650 /// if warnings cannot be emitted.
651 pub fn struct_span_force_warn(
653 span: impl Into<MultiSpan>,
655 ) -> DiagnosticBuilder<'_> {
656 let mut result = self.struct_force_warn(msg);
657 result.set_span(span);
661 /// Construct a builder at the `Allow` level at the given `span` and with the `msg`.
662 pub fn struct_span_allow(
664 span: impl Into<MultiSpan>,
666 ) -> DiagnosticBuilder<'_> {
667 let mut result = self.struct_allow(msg);
668 result.set_span(span);
672 /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
673 /// Also include a code.
674 pub fn struct_span_warn_with_code(
676 span: impl Into<MultiSpan>,
679 ) -> DiagnosticBuilder<'_> {
680 let mut result = self.struct_span_warn(span, msg);
685 /// Construct a builder at the `Warning` level with the `msg`.
687 /// The builder will be canceled if warnings cannot be emitted.
688 pub fn struct_warn(&self, msg: &str) -> DiagnosticBuilder<'_> {
689 let mut result = DiagnosticBuilder::new(self, Level::Warning, msg);
690 if !self.flags.can_emit_warnings {
696 /// Construct a builder at the `Warning` level with the `msg`.
698 /// This will "force" a warning meaning it will not be canceled even
699 /// if warnings cannot be emitted.
700 pub fn struct_force_warn(&self, msg: &str) -> DiagnosticBuilder<'_> {
701 DiagnosticBuilder::new(self, Level::Warning, msg)
704 /// Construct a builder at the `Allow` level with the `msg`.
705 pub fn struct_allow(&self, msg: &str) -> DiagnosticBuilder<'_> {
706 DiagnosticBuilder::new(self, Level::Allow, msg)
709 /// Construct a builder at the `Error` level at the given `span` and with the `msg`.
710 pub fn struct_span_err(&self, span: impl Into<MultiSpan>, msg: &str) -> DiagnosticBuilder<'_> {
711 let mut result = self.struct_err(msg);
712 result.set_span(span);
716 /// Construct a builder at the `Error` level at the given `span`, with the `msg`, and `code`.
717 pub fn struct_span_err_with_code(
719 span: impl Into<MultiSpan>,
722 ) -> DiagnosticBuilder<'_> {
723 let mut result = self.struct_span_err(span, msg);
728 /// Construct a builder at the `Error` level with the `msg`.
729 // FIXME: This method should be removed (every error should have an associated error code).
730 pub fn struct_err(&self, msg: &str) -> DiagnosticBuilder<'_> {
731 DiagnosticBuilder::new(self, Level::Error { lint: false }, msg)
734 /// This should only be used by `rustc_middle::lint::struct_lint_level`. Do not use it for hard errors.
736 pub fn struct_err_lint(&self, msg: &str) -> DiagnosticBuilder<'_> {
737 DiagnosticBuilder::new(self, Level::Error { lint: true }, msg)
740 /// Construct a builder at the `Error` level with the `msg` and the `code`.
741 pub fn struct_err_with_code(&self, msg: &str, code: DiagnosticId) -> DiagnosticBuilder<'_> {
742 let mut result = self.struct_err(msg);
747 /// Construct a builder at the `Fatal` level at the given `span` and with the `msg`.
748 pub fn struct_span_fatal(
750 span: impl Into<MultiSpan>,
752 ) -> DiagnosticBuilder<'_> {
753 let mut result = self.struct_fatal(msg);
754 result.set_span(span);
758 /// Construct a builder at the `Fatal` level at the given `span`, with the `msg`, and `code`.
759 pub fn struct_span_fatal_with_code(
761 span: impl Into<MultiSpan>,
764 ) -> DiagnosticBuilder<'_> {
765 let mut result = self.struct_span_fatal(span, msg);
770 /// Construct a builder at the `Error` level with the `msg`.
771 pub fn struct_fatal(&self, msg: &str) -> DiagnosticBuilder<'_> {
772 DiagnosticBuilder::new(self, Level::Fatal, msg)
775 /// Construct a builder at the `Help` level with the `msg`.
776 pub fn struct_help(&self, msg: &str) -> DiagnosticBuilder<'_> {
777 DiagnosticBuilder::new(self, Level::Help, msg)
780 /// Construct a builder at the `Note` level with the `msg`.
781 pub fn struct_note_without_error(&self, msg: &str) -> DiagnosticBuilder<'_> {
782 DiagnosticBuilder::new(self, Level::Note, msg)
785 pub fn span_fatal(&self, span: impl Into<MultiSpan>, msg: &str) -> ! {
786 self.emit_diag_at_span(Diagnostic::new(Fatal, msg), span);
790 pub fn span_fatal_with_code(
792 span: impl Into<MultiSpan>,
796 self.emit_diag_at_span(Diagnostic::new_with_code(Fatal, Some(code), msg), span);
800 pub fn span_err(&self, span: impl Into<MultiSpan>, msg: &str) {
801 self.emit_diag_at_span(Diagnostic::new(Error { lint: false }, msg), span);
804 pub fn span_err_with_code(&self, span: impl Into<MultiSpan>, msg: &str, code: DiagnosticId) {
805 self.emit_diag_at_span(
806 Diagnostic::new_with_code(Error { lint: false }, Some(code), msg),
811 pub fn span_warn(&self, span: impl Into<MultiSpan>, msg: &str) {
812 self.emit_diag_at_span(Diagnostic::new(Warning, msg), span);
815 pub fn span_warn_with_code(&self, span: impl Into<MultiSpan>, msg: &str, code: DiagnosticId) {
816 self.emit_diag_at_span(Diagnostic::new_with_code(Warning, Some(code), msg), span);
819 pub fn span_bug(&self, span: impl Into<MultiSpan>, msg: &str) -> ! {
820 self.inner.borrow_mut().span_bug(span, msg)
824 pub fn delay_span_bug(&self, span: impl Into<MultiSpan>, msg: &str) {
825 self.inner.borrow_mut().delay_span_bug(span, msg)
828 pub fn delay_good_path_bug(&self, msg: &str) {
829 self.inner.borrow_mut().delay_good_path_bug(msg)
832 pub fn span_bug_no_panic(&self, span: impl Into<MultiSpan>, msg: &str) {
833 self.emit_diag_at_span(Diagnostic::new(Bug, msg), span);
836 pub fn span_note_without_error(&self, span: impl Into<MultiSpan>, msg: &str) {
837 self.emit_diag_at_span(Diagnostic::new(Note, msg), span);
840 pub fn span_note_diag(&self, span: Span, msg: &str) -> DiagnosticBuilder<'_> {
841 let mut db = DiagnosticBuilder::new(self, Note, msg);
846 // NOTE: intentionally doesn't raise an error so rustc_codegen_ssa only reports fatal errors in the main thread
847 pub fn fatal(&self, msg: &str) -> FatalError {
848 self.inner.borrow_mut().fatal(msg)
851 pub fn err(&self, msg: &str) {
852 self.inner.borrow_mut().err(msg);
855 pub fn warn(&self, msg: &str) {
856 let mut db = DiagnosticBuilder::new(self, Warning, msg);
860 pub fn note_without_error(&self, msg: &str) {
861 DiagnosticBuilder::new(self, Note, msg).emit();
864 pub fn bug(&self, msg: &str) -> ! {
865 self.inner.borrow_mut().bug(msg)
869 pub fn err_count(&self) -> usize {
870 self.inner.borrow().err_count()
873 pub fn has_errors(&self) -> bool {
874 self.inner.borrow().has_errors()
876 pub fn has_errors_or_lint_errors(&self) -> bool {
877 self.inner.borrow().has_errors_or_lint_errors()
879 pub fn has_errors_or_delayed_span_bugs(&self) -> bool {
880 self.inner.borrow().has_errors_or_delayed_span_bugs()
883 pub fn print_error_count(&self, registry: &Registry) {
884 self.inner.borrow_mut().print_error_count(registry)
887 pub fn take_future_breakage_diagnostics(&self) -> Vec<Diagnostic> {
888 std::mem::take(&mut self.inner.borrow_mut().future_breakage_diagnostics)
891 pub fn abort_if_errors(&self) {
892 self.inner.borrow_mut().abort_if_errors()
895 /// `true` if we haven't taught a diagnostic with this code already.
896 /// The caller must then teach the user about such a diagnostic.
898 /// Used to suppress emitting the same error multiple times with extended explanation when
899 /// calling `-Zteach`.
900 pub fn must_teach(&self, code: &DiagnosticId) -> bool {
901 self.inner.borrow_mut().must_teach(code)
904 pub fn force_print_diagnostic(&self, db: Diagnostic) {
905 self.inner.borrow_mut().force_print_diagnostic(db)
908 pub fn emit_diagnostic(&self, diagnostic: &Diagnostic) {
909 self.inner.borrow_mut().emit_diagnostic(diagnostic)
912 fn emit_diag_at_span(&self, mut diag: Diagnostic, sp: impl Into<MultiSpan>) {
913 let mut inner = self.inner.borrow_mut();
914 inner.emit_diagnostic(diag.set_span(sp));
917 pub fn emit_artifact_notification(&self, path: &Path, artifact_type: &str) {
918 self.inner.borrow_mut().emit_artifact_notification(path, artifact_type)
921 pub fn emit_future_breakage_report(&self, diags: Vec<Diagnostic>) {
922 self.inner.borrow_mut().emitter.emit_future_breakage_report(diags)
925 pub fn emit_unused_externs(&self, lint_level: &str, unused_externs: &[&str]) {
926 self.inner.borrow_mut().emit_unused_externs(lint_level, unused_externs)
929 pub fn delay_as_bug(&self, diagnostic: Diagnostic) {
930 self.inner.borrow_mut().delay_as_bug(diagnostic)
935 fn must_teach(&mut self, code: &DiagnosticId) -> bool {
936 self.taught_diagnostics.insert(code.clone())
939 fn force_print_diagnostic(&mut self, db: Diagnostic) {
940 self.emitter.emit_diagnostic(&db);
943 /// Emit all stashed diagnostics.
944 fn emit_stashed_diagnostics(&mut self) {
945 let diags = self.stashed_diagnostics.drain(..).map(|x| x.1).collect::<Vec<_>>();
946 diags.iter().for_each(|diag| self.emit_diagnostic(diag));
949 fn emit_diagnostic(&mut self, diagnostic: &Diagnostic) {
950 if diagnostic.cancelled() || self.quiet {
954 if diagnostic.has_future_breakage() {
955 self.future_breakage_diagnostics.push(diagnostic.clone());
958 if diagnostic.level == Warning
959 && !self.flags.can_emit_warnings
960 && !diagnostic.is_force_warn()
962 if diagnostic.has_future_breakage() {
963 (*TRACK_DIAGNOSTICS)(diagnostic);
968 (*TRACK_DIAGNOSTICS)(diagnostic);
970 if diagnostic.level == Allow {
974 if let Some(ref code) = diagnostic.code {
975 self.emitted_diagnostic_codes.insert(code.clone());
978 let already_emitted = |this: &mut Self| {
979 let mut hasher = StableHasher::new();
980 diagnostic.hash(&mut hasher);
981 let diagnostic_hash = hasher.finish();
982 !this.emitted_diagnostics.insert(diagnostic_hash)
985 // Only emit the diagnostic if we've been asked to deduplicate and
986 // haven't already emitted an equivalent diagnostic.
987 if !(self.flags.deduplicate_diagnostics && already_emitted(self)) {
988 self.emitter.emit_diagnostic(diagnostic);
989 if diagnostic.is_error() {
990 self.deduplicated_err_count += 1;
991 } else if diagnostic.level == Warning {
992 self.deduplicated_warn_count += 1;
995 if diagnostic.is_error() {
996 if matches!(diagnostic.level, Level::Error { lint: true }) {
997 self.bump_lint_err_count();
999 self.bump_err_count();
1002 self.bump_warn_count();
1006 fn emit_artifact_notification(&mut self, path: &Path, artifact_type: &str) {
1007 self.emitter.emit_artifact_notification(path, artifact_type);
1010 fn emit_unused_externs(&mut self, lint_level: &str, unused_externs: &[&str]) {
1011 self.emitter.emit_unused_externs(lint_level, unused_externs);
1014 fn treat_err_as_bug(&self) -> bool {
1017 .map_or(false, |c| self.err_count() + self.lint_err_count >= c.get())
1020 fn print_error_count(&mut self, registry: &Registry) {
1021 self.emit_stashed_diagnostics();
1023 let warnings = match self.deduplicated_warn_count {
1025 1 => "1 warning emitted".to_string(),
1026 count => format!("{} warnings emitted", count),
1028 let errors = match self.deduplicated_err_count {
1030 1 => "aborting due to previous error".to_string(),
1031 count => format!("aborting due to {} previous errors", count),
1033 if self.treat_err_as_bug() {
1037 match (errors.len(), warnings.len()) {
1039 (0, _) => self.emitter.emit_diagnostic(&Diagnostic::new(Level::Warning, &warnings)),
1041 let _ = self.fatal(&errors);
1044 let _ = self.fatal(&format!("{}; {}", &errors, &warnings));
1048 let can_show_explain = self.emitter.should_show_explain();
1049 let are_there_diagnostics = !self.emitted_diagnostic_codes.is_empty();
1050 if can_show_explain && are_there_diagnostics {
1051 let mut error_codes = self
1052 .emitted_diagnostic_codes
1054 .filter_map(|x| match &x {
1055 DiagnosticId::Error(s)
1056 if registry.try_find_description(s).map_or(false, |o| o.is_some()) =>
1062 .collect::<Vec<_>>();
1063 if !error_codes.is_empty() {
1065 if error_codes.len() > 1 {
1066 let limit = if error_codes.len() > 9 { 9 } else { error_codes.len() };
1067 self.failure(&format!(
1068 "Some errors have detailed explanations: {}{}",
1069 error_codes[..limit].join(", "),
1070 if error_codes.len() > 9 { "..." } else { "." }
1072 self.failure(&format!(
1073 "For more information about an error, try \
1074 `rustc --explain {}`.",
1078 self.failure(&format!(
1079 "For more information about this error, try \
1080 `rustc --explain {}`.",
1089 fn err_count(&self) -> usize {
1090 self.err_count + self.stashed_diagnostics.len()
1093 fn has_errors(&self) -> bool {
1094 self.err_count() > 0
1096 fn has_errors_or_lint_errors(&self) -> bool {
1097 self.has_errors() || self.lint_err_count > 0
1099 fn has_errors_or_delayed_span_bugs(&self) -> bool {
1100 self.has_errors() || !self.delayed_span_bugs.is_empty()
1102 fn has_any_message(&self) -> bool {
1103 self.err_count() > 0 || self.lint_err_count > 0 || self.warn_count > 0
1106 fn abort_if_errors(&mut self) {
1107 self.emit_stashed_diagnostics();
1109 if self.has_errors() {
1114 fn span_bug(&mut self, sp: impl Into<MultiSpan>, msg: &str) -> ! {
1115 self.emit_diag_at_span(Diagnostic::new(Bug, msg), sp);
1116 panic::panic_any(ExplicitBug);
1119 fn emit_diag_at_span(&mut self, mut diag: Diagnostic, sp: impl Into<MultiSpan>) {
1120 self.emit_diagnostic(diag.set_span(sp));
1124 fn delay_span_bug(&mut self, sp: impl Into<MultiSpan>, msg: &str) {
1125 // This is technically `self.treat_err_as_bug()` but `delay_span_bug` is called before
1126 // incrementing `err_count` by one, so we need to +1 the comparing.
1127 // FIXME: Would be nice to increment err_count in a more coherent way.
1128 if self.flags.treat_err_as_bug.map_or(false, |c| self.err_count() + 1 >= c.get()) {
1129 // FIXME: don't abort here if report_delayed_bugs is off
1130 self.span_bug(sp, msg);
1132 let mut diagnostic = Diagnostic::new(Level::Bug, msg);
1133 diagnostic.set_span(sp.into());
1134 diagnostic.note(&format!("delayed at {}", std::panic::Location::caller()));
1135 self.delay_as_bug(diagnostic)
1138 fn delay_good_path_bug(&mut self, msg: &str) {
1139 let diagnostic = Diagnostic::new(Level::Bug, msg);
1140 if self.flags.report_delayed_bugs {
1141 self.emit_diagnostic(&diagnostic);
1143 let backtrace = std::backtrace::Backtrace::force_capture();
1144 self.delayed_good_path_bugs.push(DelayedDiagnostic::with_backtrace(diagnostic, backtrace));
1147 fn failure(&mut self, msg: &str) {
1148 self.emit_diagnostic(&Diagnostic::new(FailureNote, msg));
1151 fn fatal(&mut self, msg: &str) -> FatalError {
1152 self.emit_error(Fatal, msg);
1156 fn err(&mut self, msg: &str) {
1157 self.emit_error(Error { lint: false }, msg);
1160 /// Emit an error; level should be `Error` or `Fatal`.
1161 fn emit_error(&mut self, level: Level, msg: &str) {
1162 if self.treat_err_as_bug() {
1165 self.emit_diagnostic(&Diagnostic::new(level, msg));
1168 fn bug(&mut self, msg: &str) -> ! {
1169 self.emit_diagnostic(&Diagnostic::new(Bug, msg));
1170 panic::panic_any(ExplicitBug);
1173 fn delay_as_bug(&mut self, diagnostic: Diagnostic) {
1177 if self.flags.report_delayed_bugs {
1178 self.emit_diagnostic(&diagnostic);
1180 self.delayed_span_bugs.push(diagnostic);
1183 fn flush_delayed(&mut self, bugs: Vec<Diagnostic>, explanation: &str) {
1184 let has_bugs = !bugs.is_empty();
1186 self.emit_diagnostic(&bug);
1189 panic!("{}", explanation);
1193 fn bump_lint_err_count(&mut self) {
1194 self.lint_err_count += 1;
1195 self.panic_if_treat_err_as_bug();
1198 fn bump_err_count(&mut self) {
1199 self.err_count += 1;
1200 self.panic_if_treat_err_as_bug();
1203 fn bump_warn_count(&mut self) {
1204 self.warn_count += 1;
1207 fn panic_if_treat_err_as_bug(&self) {
1208 if self.treat_err_as_bug() {
1210 self.err_count() + self.lint_err_count,
1211 self.flags.treat_err_as_bug.map(|c| c.get()).unwrap_or(0),
1213 (1, 1) => panic!("aborting due to `-Z treat-err-as-bug=1`"),
1214 (0, _) | (1, _) => {}
1215 (count, as_bug) => panic!(
1216 "aborting after {} errors due to `-Z treat-err-as-bug={}`",
1224 struct DelayedDiagnostic {
1229 impl DelayedDiagnostic {
1230 fn with_backtrace(diagnostic: Diagnostic, backtrace: Backtrace) -> Self {
1231 DelayedDiagnostic { inner: diagnostic, note: backtrace }
1234 fn decorate(mut self) -> Diagnostic {
1235 self.inner.note(&format!("delayed at {}", self.note));
1240 #[derive(Copy, PartialEq, Clone, Hash, Debug, Encodable, Decodable)]
1245 /// If this error comes from a lint, don't abort compilation even when abort_if_errors() is called.
1256 impl fmt::Display for Level {
1257 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1258 self.to_str().fmt(f)
1263 fn color(self) -> ColorSpec {
1264 let mut spec = ColorSpec::new();
1266 Bug | Fatal | Error { .. } => {
1267 spec.set_fg(Some(Color::Red)).set_intense(true);
1270 spec.set_fg(Some(Color::Yellow)).set_intense(cfg!(windows));
1273 spec.set_fg(Some(Color::Green)).set_intense(true);
1276 spec.set_fg(Some(Color::Cyan)).set_intense(true);
1279 Allow | Cancelled => unreachable!(),
1284 pub fn to_str(self) -> &'static str {
1286 Bug => "error: internal compiler error",
1287 Fatal | Error { .. } => "error",
1288 Warning => "warning",
1291 FailureNote => "failure-note",
1292 Cancelled => panic!("Shouldn't call on cancelled error"),
1293 Allow => panic!("Shouldn't call on allowed error"),
1297 pub fn is_failure_note(&self) -> bool {
1298 matches!(*self, FailureNote)
1302 pub fn add_elided_lifetime_in_path_suggestion(
1303 source_map: &SourceMap,
1304 db: &mut DiagnosticBuilder<'_>,
1307 incl_angl_brckt: bool,
1308 insertion_span: Span,
1311 let (replace_span, suggestion) = if incl_angl_brckt {
1312 (insertion_span, anon_lts)
1314 // When possible, prefer a suggestion that replaces the whole
1315 // `Path<T>` expression with `Path<'_, T>`, rather than inserting `'_, `
1316 // at a point (which makes for an ugly/confusing label)
1317 if let Ok(snippet) = source_map.span_to_snippet(path_span) {
1318 // But our spans can get out of whack due to macros; if the place we think
1319 // we want to insert `'_` isn't even within the path expression's span, we
1320 // should bail out of making any suggestion rather than panicking on a
1321 // subtract-with-overflow or string-slice-out-out-bounds (!)
1322 // FIXME: can we do better?
1323 if insertion_span.lo().0 < path_span.lo().0 {
1326 let insertion_index = (insertion_span.lo().0 - path_span.lo().0) as usize;
1327 if insertion_index > snippet.len() {
1330 let (before, after) = snippet.split_at(insertion_index);
1331 (path_span, format!("{}{}{}", before, anon_lts, after))
1333 (insertion_span, anon_lts)
1338 &format!("indicate the anonymous lifetime{}", pluralize!(n)),
1340 Applicability::MachineApplicable,
1344 // Useful type to use with `Result<>` indicate that an error has already
1345 // been reported to the user, so no need to continue checking.
1346 #[derive(Clone, Copy, Debug, Encodable, Decodable, Hash, PartialEq, Eq)]
1347 pub struct ErrorReported;
1349 rustc_data_structures::impl_stable_hash_via_hash!(ErrorReported);