1 //! Diagnostics creation and emission for `rustc`.
3 //! This module contains the code for creating and emitting diagnostics.
5 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
6 #![feature(crate_visibility_modifier)]
8 #![feature(format_args_capture)]
13 extern crate rustc_macros;
15 pub use emitter::ColorConfig;
20 use emitter::{is_case_difference, Emitter, EmitterWriter};
21 use registry::Registry;
22 use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
23 use rustc_data_structures::stable_hasher::StableHasher;
24 use rustc_data_structures::sync::{self, Lock, Lrc};
25 use rustc_data_structures::AtomicRef;
26 pub use rustc_lint_defs::{pluralize, Applicability};
27 use rustc_serialize::json::Json;
28 use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
29 use rustc_span::source_map::SourceMap;
30 use rustc_span::{Loc, MultiSpan, Span};
33 use std::hash::{Hash, Hasher};
34 use std::num::NonZeroUsize;
37 use std::{error, fmt};
39 use termcolor::{Color, ColorSpec};
41 pub mod annotate_snippet_emitter_writer;
43 mod diagnostic_builder;
50 pub use snippet::Style;
52 pub type PResult<'a, T> = Result<T, DiagnosticBuilder<'a>>;
54 // `PResult` is used a lot. Make sure it doesn't unintentionally get bigger.
55 // (See also the comment on `DiagnosticBuilderInner`.)
56 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
57 rustc_data_structures::static_assert_size!(PResult<'_, bool>, 16);
59 #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, Encodable, Decodable)]
60 pub enum SuggestionStyle {
61 /// Hide the suggested code when displaying this suggestion inline.
63 /// Always hide the suggested code but display the message.
65 /// Do not display this suggestion in the cli output, it is only meant for tools.
67 /// Always show the suggested code.
68 /// This will *not* show the code if the suggestion is inline *and* the suggested code is
71 /// Always show the suggested code independently.
75 impl SuggestionStyle {
76 fn hide_inline(&self) -> bool {
77 !matches!(*self, SuggestionStyle::ShowCode)
81 #[derive(Clone, Debug, PartialEq, Default)]
82 pub struct ToolMetadata(pub Option<Json>);
85 fn new(json: Json) -> Self {
86 ToolMetadata(Some(json))
89 fn is_set(&self) -> bool {
94 impl Hash for ToolMetadata {
95 fn hash<H: Hasher>(&self, _state: &mut H) {}
98 // Doesn't really need to round-trip
99 impl<D: Decoder> Decodable<D> for ToolMetadata {
100 fn decode(_d: &mut D) -> Result<Self, D::Error> {
101 Ok(ToolMetadata(None))
105 impl<S: Encoder> Encodable<S> for ToolMetadata {
106 fn encode(&self, e: &mut S) -> Result<(), S::Error> {
108 None => e.emit_unit(),
109 Some(json) => json.encode(e),
114 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
115 pub struct CodeSuggestion {
116 /// Each substitute can have multiple variants due to multiple
117 /// applicable suggestions
119 /// `foo.bar` might be replaced with `a.b` or `x.y` by replacing
120 /// `foo` and `bar` on their own:
124 /// Substitution { parts: vec![(0..3, "a"), (4..7, "b")] },
125 /// Substitution { parts: vec![(0..3, "x"), (4..7, "y")] },
129 /// or by replacing the entire span:
133 /// Substitution { parts: vec![(0..7, "a.b")] },
134 /// Substitution { parts: vec![(0..7, "x.y")] },
137 pub substitutions: Vec<Substitution>,
139 /// Visual representation of this suggestion.
140 pub style: SuggestionStyle,
141 /// Whether or not the suggestion is approximate
143 /// Sometimes we may show suggestions with placeholders,
144 /// which are useful for users but not useful for
145 /// tools like rustfix
146 pub applicability: Applicability,
147 /// Tool-specific metadata
148 pub tool_metadata: ToolMetadata,
151 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
152 /// See the docs on `CodeSuggestion::substitutions`
153 pub struct Substitution {
154 pub parts: Vec<SubstitutionPart>,
157 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
158 pub struct SubstitutionPart {
163 /// Used to translate between `Span`s and byte positions within a single output line in highlighted
164 /// code of structured suggestions.
165 #[derive(Debug, Clone, Copy)]
166 pub struct SubstitutionHighlight {
171 impl SubstitutionPart {
172 pub fn is_addition(&self, sm: &SourceMap) -> bool {
173 !self.snippet.is_empty()
175 .span_to_snippet(self.span)
176 .map_or(self.span.is_empty(), |snippet| snippet.trim().is_empty())
179 pub fn is_deletion(&self) -> bool {
180 self.snippet.trim().is_empty()
183 pub fn is_replacement(&self, sm: &SourceMap) -> bool {
184 !self.snippet.is_empty()
186 .span_to_snippet(self.span)
187 .map_or(!self.span.is_empty(), |snippet| !snippet.trim().is_empty())
191 impl CodeSuggestion {
192 /// Returns the assembled code suggestions, whether they should be shown with an underline
193 /// and whether the substitution only differs in capitalization.
197 ) -> Vec<(String, Vec<SubstitutionPart>, Vec<Vec<SubstitutionHighlight>>, bool)> {
198 // For the `Vec<Vec<SubstitutionHighlight>>` value, the first level of the vector
199 // corresponds to the output snippet's lines, while the second level corresponds to the
200 // substrings within that line that should be highlighted.
202 use rustc_span::{CharPos, Pos};
204 /// Append to a buffer the remainder of the line of existing source code, and return the
205 /// count of lines that have been added for accurate highlighting.
208 line_opt: Option<&Cow<'_, str>>,
210 hi_opt: Option<&Loc>,
212 let mut line_count = 0;
213 let (lo, hi_opt) = (lo.col.to_usize(), hi_opt.map(|hi| hi.col.to_usize()));
214 if let Some(line) = line_opt {
215 if let Some(lo) = line.char_indices().map(|(i, _)| i).nth(lo) {
216 let hi_opt = hi_opt.and_then(|hi| line.char_indices().map(|(i, _)| i).nth(hi));
218 Some(hi) if hi > lo => {
219 line_count = line[lo..hi].matches('\n').count();
220 buf.push_str(&line[lo..hi])
224 line_count = line[lo..].matches('\n').count();
225 buf.push_str(&line[lo..])
229 if hi_opt.is_none() {
236 assert!(!self.substitutions.is_empty());
241 // Suggestions coming from macros can have malformed spans. This is a heavy
242 // handed approach to avoid ICEs by ignoring the suggestion outright.
243 let invalid = subst.parts.iter().any(|item| sm.is_valid_span(item.span).is_err());
245 debug!("splice_lines: suggestion contains an invalid span: {:?}", subst);
250 .filter_map(|mut substitution| {
251 // Assumption: all spans are in the same file, and all spans
252 // are disjoint. Sort in ascending order.
253 substitution.parts.sort_by_key(|part| part.span.lo());
255 // Find the bounding span.
256 let lo = substitution.parts.iter().map(|part| part.span.lo()).min()?;
257 let hi = substitution.parts.iter().map(|part| part.span.hi()).max()?;
258 let bounding_span = Span::with_root_ctxt(lo, hi);
259 // The different spans might belong to different contexts, if so ignore suggestion.
260 let lines = sm.span_to_lines(bounding_span).ok()?;
261 assert!(!lines.lines.is_empty() || bounding_span.is_dummy());
263 // We can't splice anything if the source is unavailable.
264 if !sm.ensure_source_file_source_present(lines.file.clone()) {
268 let mut highlights = vec![];
269 // To build up the result, we do this for each span:
270 // - push the line segment trailing the previous span
271 // (at the beginning a "phantom" span pointing at the start of the line)
272 // - push lines between the previous and current span (if any)
273 // - if the previous and current span are not on the same line
274 // push the line segment leading up to the current span
275 // - splice in the span substitution
277 // Finally push the trailing line segment of the last span
278 let sf = &lines.file;
279 let mut prev_hi = sm.lookup_char_pos(bounding_span.lo());
280 prev_hi.col = CharPos::from_usize(0);
282 lines.lines.get(0).and_then(|line0| sf.get_line(line0.line_index));
283 let mut buf = String::new();
285 let mut line_highlight = vec![];
286 for part in &substitution.parts {
287 let cur_lo = sm.lookup_char_pos(part.span.lo());
288 if prev_hi.line == cur_lo.line {
290 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, Some(&cur_lo));
292 highlights.push(std::mem::take(&mut line_highlight));
296 highlights.push(std::mem::take(&mut line_highlight));
297 let mut count = push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
299 highlights.push(std::mem::take(&mut line_highlight));
302 // push lines between the previous and current span (if any)
303 for idx in prev_hi.line..(cur_lo.line - 1) {
304 if let Some(line) = sf.get_line(idx) {
305 buf.push_str(line.as_ref());
307 highlights.push(std::mem::take(&mut line_highlight));
310 if let Some(cur_line) = sf.get_line(cur_lo.line - 1) {
311 let end = match cur_line.char_indices().nth(cur_lo.col.to_usize()) {
313 None => cur_line.len(),
315 buf.push_str(&cur_line[..end]);
318 // Add a whole line highlight per line in the snippet.
319 line_highlight.push(SubstitutionHighlight {
322 + part.snippet.split('\n').next().unwrap_or(&part.snippet).len(),
324 for line in part.snippet.split('\n').skip(1) {
325 highlights.push(std::mem::take(&mut line_highlight));
326 line_highlight.push(SubstitutionHighlight { start: 0, end: line.len() });
328 buf.push_str(&part.snippet);
329 prev_hi = sm.lookup_char_pos(part.span.hi());
330 prev_line = sf.get_line(prev_hi.line - 1);
332 highlights.push(std::mem::take(&mut line_highlight));
333 let only_capitalization = is_case_difference(sm, &buf, bounding_span);
334 // if the replacement already ends with a newline, don't print the next line
335 if !buf.ends_with('\n') {
336 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
338 // remove trailing newlines
339 while buf.ends_with('\n') {
342 Some((buf, substitution.parts, highlights, only_capitalization))
348 pub use rustc_span::fatal_error::{FatalError, FatalErrorMarker};
350 /// Signifies that the compiler died with an explicit call to `.bug`
351 /// or `.span_bug` rather than a failed assertion, etc.
352 #[derive(Copy, Clone, Debug)]
353 pub struct ExplicitBug;
355 impl fmt::Display for ExplicitBug {
356 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
357 write!(f, "parser internal bug")
361 impl error::Error for ExplicitBug {}
363 pub use diagnostic::{Diagnostic, DiagnosticId, DiagnosticStyledString, SubDiagnostic};
364 pub use diagnostic_builder::DiagnosticBuilder;
365 use std::backtrace::Backtrace;
367 /// A handler deals with errors and other compiler output.
368 /// Certain errors (fatal, bug, unimpl) may cause immediate exit,
369 /// others log errors for later reporting.
372 inner: Lock<HandlerInner>,
375 /// This inner struct exists to keep it all behind a single lock;
376 /// this is done to prevent possible deadlocks in a multi-threaded compiler,
377 /// as well as inconsistent state observation.
378 struct HandlerInner {
380 /// The number of errors that have been emitted, including duplicates.
382 /// This is not necessarily the count that's reported to the user once
383 /// compilation ends.
386 deduplicated_err_count: usize,
387 emitter: Box<dyn Emitter + sync::Send>,
388 delayed_span_bugs: Vec<Diagnostic>,
389 delayed_good_path_bugs: Vec<DelayedDiagnostic>,
391 /// This set contains the `DiagnosticId` of all emitted diagnostics to avoid
392 /// emitting the same diagnostic with extended help (`--teach`) twice, which
393 /// would be unnecessary repetition.
394 taught_diagnostics: FxHashSet<DiagnosticId>,
396 /// Used to suggest rustc --explain <error code>
397 emitted_diagnostic_codes: FxHashSet<DiagnosticId>,
399 /// This set contains a hash of every diagnostic that has been emitted by
400 /// this handler. These hashes is used to avoid emitting the same error
402 emitted_diagnostics: FxHashSet<u128>,
404 /// Stashed diagnostics emitted in one stage of the compiler that may be
405 /// stolen by other stages (e.g. to improve them and add more information).
406 /// The stashed diagnostics count towards the total error count.
407 /// When `.abort_if_errors()` is called, these are also emitted.
408 stashed_diagnostics: FxIndexMap<(Span, StashKey), Diagnostic>,
410 /// The warning count, used for a recap upon finishing
411 deduplicated_warn_count: usize,
413 future_breakage_diagnostics: Vec<Diagnostic>,
415 /// If set to `true`, no warning or error will be emitted.
419 /// A key denoting where from a diagnostic was stashed.
420 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
425 fn default_track_diagnostic(_: &Diagnostic) {}
427 pub static TRACK_DIAGNOSTICS: AtomicRef<fn(&Diagnostic)> =
428 AtomicRef::new(&(default_track_diagnostic as fn(&_)));
430 #[derive(Copy, Clone, Default)]
431 pub struct HandlerFlags {
432 /// If false, warning-level lints are suppressed.
433 /// (rustc: see `--allow warnings` and `--cap-lints`)
434 pub can_emit_warnings: bool,
435 /// If true, error-level diagnostics are upgraded to bug-level.
436 /// (rustc: see `-Z treat-err-as-bug`)
437 pub treat_err_as_bug: Option<NonZeroUsize>,
438 /// If true, immediately emit diagnostics that would otherwise be buffered.
439 /// (rustc: see `-Z dont-buffer-diagnostics` and `-Z treat-err-as-bug`)
440 pub dont_buffer_diagnostics: bool,
441 /// If true, immediately print bugs registered with `delay_span_bug`.
442 /// (rustc: see `-Z report-delayed-bugs`)
443 pub report_delayed_bugs: bool,
444 /// Show macro backtraces.
445 /// (rustc: see `-Z macro-backtrace`)
446 pub macro_backtrace: bool,
447 /// If true, identical diagnostics are reported only once.
448 pub deduplicate_diagnostics: bool,
451 impl Drop for HandlerInner {
453 self.emit_stashed_diagnostics();
455 if !self.has_errors() {
456 let bugs = std::mem::replace(&mut self.delayed_span_bugs, Vec::new());
457 self.flush_delayed(bugs, "no errors encountered even though `delay_span_bug` issued");
460 if !self.has_any_message() {
461 let bugs = std::mem::replace(&mut self.delayed_good_path_bugs, Vec::new());
463 bugs.into_iter().map(DelayedDiagnostic::decorate).collect(),
464 "no warnings or errors encountered even though `delayed_good_path_bugs` issued",
471 pub fn with_tty_emitter(
472 color_config: ColorConfig,
473 can_emit_warnings: bool,
474 treat_err_as_bug: Option<NonZeroUsize>,
475 sm: Option<Lrc<SourceMap>>,
477 Self::with_tty_emitter_and_flags(
480 HandlerFlags { can_emit_warnings, treat_err_as_bug, ..Default::default() },
484 pub fn with_tty_emitter_and_flags(
485 color_config: ColorConfig,
486 sm: Option<Lrc<SourceMap>>,
489 let emitter = Box::new(EmitterWriter::stderr(
495 flags.macro_backtrace,
497 Self::with_emitter_and_flags(emitter, flags)
501 can_emit_warnings: bool,
502 treat_err_as_bug: Option<NonZeroUsize>,
503 emitter: Box<dyn Emitter + sync::Send>,
505 Handler::with_emitter_and_flags(
507 HandlerFlags { can_emit_warnings, treat_err_as_bug, ..Default::default() },
511 pub fn with_emitter_and_flags(
512 emitter: Box<dyn Emitter + sync::Send>,
517 inner: Lock::new(HandlerInner {
521 deduplicated_err_count: 0,
522 deduplicated_warn_count: 0,
524 delayed_span_bugs: Vec::new(),
525 delayed_good_path_bugs: Vec::new(),
526 taught_diagnostics: Default::default(),
527 emitted_diagnostic_codes: Default::default(),
528 emitted_diagnostics: Default::default(),
529 stashed_diagnostics: Default::default(),
530 future_breakage_diagnostics: Vec::new(),
536 pub fn with_disabled_diagnostic<T, F: FnOnce() -> T>(&self, f: F) -> T {
537 let prev = self.inner.borrow_mut().quiet;
538 self.inner.borrow_mut().quiet = true;
540 self.inner.borrow_mut().quiet = prev;
544 // This is here to not allow mutation of flags;
545 // as of this writing it's only used in tests in librustc_middle.
546 pub fn can_emit_warnings(&self) -> bool {
547 self.flags.can_emit_warnings
550 /// Resets the diagnostic error count as well as the cached emitted diagnostics.
552 /// NOTE: *do not* call this function from rustc. It is only meant to be called from external
553 /// tools that want to reuse a `Parser` cleaning the previously emitted diagnostics as well as
554 /// the overall count of emitted error diagnostics.
555 pub fn reset_err_count(&self) {
556 let mut inner = self.inner.borrow_mut();
558 inner.warn_count = 0;
559 inner.deduplicated_err_count = 0;
560 inner.deduplicated_warn_count = 0;
562 // actually free the underlying memory (which `clear` would not do)
563 inner.delayed_span_bugs = Default::default();
564 inner.delayed_good_path_bugs = Default::default();
565 inner.taught_diagnostics = Default::default();
566 inner.emitted_diagnostic_codes = Default::default();
567 inner.emitted_diagnostics = Default::default();
568 inner.stashed_diagnostics = Default::default();
571 /// Stash a given diagnostic with the given `Span` and `StashKey` as the key for later stealing.
572 pub fn stash_diagnostic(&self, span: Span, key: StashKey, diag: Diagnostic) {
573 let mut inner = self.inner.borrow_mut();
574 // FIXME(Centril, #69537): Consider reintroducing panic on overwriting a stashed diagnostic
575 // if/when we have a more robust macro-friendly replacement for `(span, key)` as a key.
576 // See the PR for a discussion.
577 inner.stashed_diagnostics.insert((span, key), diag);
580 /// Steal a previously stashed diagnostic with the given `Span` and `StashKey` as the key.
581 pub fn steal_diagnostic(&self, span: Span, key: StashKey) -> Option<DiagnosticBuilder<'_>> {
585 .remove(&(span, key))
586 .map(|diag| DiagnosticBuilder::new_diagnostic(self, diag))
589 /// Emit all stashed diagnostics.
590 pub fn emit_stashed_diagnostics(&self) {
591 self.inner.borrow_mut().emit_stashed_diagnostics();
594 /// Construct a dummy builder with `Level::Cancelled`.
596 /// Using this will neither report anything to the user (e.g. a warning),
597 /// nor will compilation cancel as a result.
598 pub fn struct_dummy(&self) -> DiagnosticBuilder<'_> {
599 DiagnosticBuilder::new(self, Level::Cancelled, "")
602 /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
604 /// The builder will be canceled if warnings cannot be emitted.
605 pub fn struct_span_warn(&self, span: impl Into<MultiSpan>, msg: &str) -> DiagnosticBuilder<'_> {
606 let mut result = self.struct_warn(msg);
607 result.set_span(span);
611 /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
613 /// This will "force" the warning meaning it will not be canceled even
614 /// if warnings cannot be emitted.
615 pub fn struct_span_force_warn(
617 span: impl Into<MultiSpan>,
619 ) -> DiagnosticBuilder<'_> {
620 let mut result = self.struct_force_warn(msg);
621 result.set_span(span);
625 /// Construct a builder at the `Allow` level at the given `span` and with the `msg`.
626 pub fn struct_span_allow(
628 span: impl Into<MultiSpan>,
630 ) -> DiagnosticBuilder<'_> {
631 let mut result = self.struct_allow(msg);
632 result.set_span(span);
636 /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
637 /// Also include a code.
638 pub fn struct_span_warn_with_code(
640 span: impl Into<MultiSpan>,
643 ) -> DiagnosticBuilder<'_> {
644 let mut result = self.struct_span_warn(span, msg);
649 /// Construct a builder at the `Warning` level with the `msg`.
651 /// The builder will be canceled if warnings cannot be emitted.
652 pub fn struct_warn(&self, msg: &str) -> DiagnosticBuilder<'_> {
653 let mut result = DiagnosticBuilder::new(self, Level::Warning, msg);
654 if !self.flags.can_emit_warnings {
660 /// Construct a builder at the `Warning` level with the `msg`.
662 /// This will "force" a warning meaning it will not be canceled even
663 /// if warnings cannot be emitted.
664 pub fn struct_force_warn(&self, msg: &str) -> DiagnosticBuilder<'_> {
665 DiagnosticBuilder::new(self, Level::Warning, msg)
668 /// Construct a builder at the `Allow` level with the `msg`.
669 pub fn struct_allow(&self, msg: &str) -> DiagnosticBuilder<'_> {
670 DiagnosticBuilder::new(self, Level::Allow, msg)
673 /// Construct a builder at the `Error` level at the given `span` and with the `msg`.
674 pub fn struct_span_err(&self, span: impl Into<MultiSpan>, msg: &str) -> DiagnosticBuilder<'_> {
675 let mut result = self.struct_err(msg);
676 result.set_span(span);
680 /// Construct a builder at the `Error` level at the given `span`, with the `msg`, and `code`.
681 pub fn struct_span_err_with_code(
683 span: impl Into<MultiSpan>,
686 ) -> DiagnosticBuilder<'_> {
687 let mut result = self.struct_span_err(span, msg);
692 /// Construct a builder at the `Error` level with the `msg`.
693 // FIXME: This method should be removed (every error should have an associated error code).
694 pub fn struct_err(&self, msg: &str) -> DiagnosticBuilder<'_> {
695 DiagnosticBuilder::new(self, Level::Error, msg)
698 /// Construct a builder at the `Error` level with the `msg` and the `code`.
699 pub fn struct_err_with_code(&self, msg: &str, code: DiagnosticId) -> DiagnosticBuilder<'_> {
700 let mut result = self.struct_err(msg);
705 /// Construct a builder at the `Fatal` level at the given `span` and with the `msg`.
706 pub fn struct_span_fatal(
708 span: impl Into<MultiSpan>,
710 ) -> DiagnosticBuilder<'_> {
711 let mut result = self.struct_fatal(msg);
712 result.set_span(span);
716 /// Construct a builder at the `Fatal` level at the given `span`, with the `msg`, and `code`.
717 pub fn struct_span_fatal_with_code(
719 span: impl Into<MultiSpan>,
722 ) -> DiagnosticBuilder<'_> {
723 let mut result = self.struct_span_fatal(span, msg);
728 /// Construct a builder at the `Error` level with the `msg`.
729 pub fn struct_fatal(&self, msg: &str) -> DiagnosticBuilder<'_> {
730 DiagnosticBuilder::new(self, Level::Fatal, msg)
733 /// Construct a builder at the `Help` level with the `msg`.
734 pub fn struct_help(&self, msg: &str) -> DiagnosticBuilder<'_> {
735 DiagnosticBuilder::new(self, Level::Help, msg)
738 /// Construct a builder at the `Note` level with the `msg`.
739 pub fn struct_note_without_error(&self, msg: &str) -> DiagnosticBuilder<'_> {
740 DiagnosticBuilder::new(self, Level::Note, msg)
743 pub fn span_fatal(&self, span: impl Into<MultiSpan>, msg: &str) -> ! {
744 self.emit_diag_at_span(Diagnostic::new(Fatal, msg), span);
748 pub fn span_fatal_with_code(
750 span: impl Into<MultiSpan>,
754 self.emit_diag_at_span(Diagnostic::new_with_code(Fatal, Some(code), msg), span);
758 pub fn span_err(&self, span: impl Into<MultiSpan>, msg: &str) {
759 self.emit_diag_at_span(Diagnostic::new(Error, msg), span);
762 pub fn span_err_with_code(&self, span: impl Into<MultiSpan>, msg: &str, code: DiagnosticId) {
763 self.emit_diag_at_span(Diagnostic::new_with_code(Error, Some(code), msg), span);
766 pub fn span_warn(&self, span: impl Into<MultiSpan>, msg: &str) {
767 self.emit_diag_at_span(Diagnostic::new(Warning, msg), span);
770 pub fn span_warn_with_code(&self, span: impl Into<MultiSpan>, msg: &str, code: DiagnosticId) {
771 self.emit_diag_at_span(Diagnostic::new_with_code(Warning, Some(code), msg), span);
774 pub fn span_bug(&self, span: impl Into<MultiSpan>, msg: &str) -> ! {
775 self.inner.borrow_mut().span_bug(span, msg)
779 pub fn delay_span_bug(&self, span: impl Into<MultiSpan>, msg: &str) {
780 self.inner.borrow_mut().delay_span_bug(span, msg)
783 pub fn delay_good_path_bug(&self, msg: &str) {
784 self.inner.borrow_mut().delay_good_path_bug(msg)
787 pub fn span_bug_no_panic(&self, span: impl Into<MultiSpan>, msg: &str) {
788 self.emit_diag_at_span(Diagnostic::new(Bug, msg), span);
791 pub fn span_note_without_error(&self, span: impl Into<MultiSpan>, msg: &str) {
792 self.emit_diag_at_span(Diagnostic::new(Note, msg), span);
795 pub fn span_note_diag(&self, span: Span, msg: &str) -> DiagnosticBuilder<'_> {
796 let mut db = DiagnosticBuilder::new(self, Note, msg);
801 // NOTE: intentionally doesn't raise an error so rustc_codegen_ssa only reports fatal errors in the main thread
802 pub fn fatal(&self, msg: &str) -> FatalError {
803 self.inner.borrow_mut().fatal(msg)
806 pub fn err(&self, msg: &str) {
807 self.inner.borrow_mut().err(msg);
810 pub fn warn(&self, msg: &str) {
811 let mut db = DiagnosticBuilder::new(self, Warning, msg);
815 pub fn note_without_error(&self, msg: &str) {
816 DiagnosticBuilder::new(self, Note, msg).emit();
819 pub fn bug(&self, msg: &str) -> ! {
820 self.inner.borrow_mut().bug(msg)
824 pub fn err_count(&self) -> usize {
825 self.inner.borrow().err_count()
828 pub fn has_errors(&self) -> bool {
829 self.inner.borrow().has_errors()
831 pub fn has_errors_or_delayed_span_bugs(&self) -> bool {
832 self.inner.borrow().has_errors_or_delayed_span_bugs()
835 pub fn print_error_count(&self, registry: &Registry) {
836 self.inner.borrow_mut().print_error_count(registry)
839 pub fn take_future_breakage_diagnostics(&self) -> Vec<Diagnostic> {
840 std::mem::take(&mut self.inner.borrow_mut().future_breakage_diagnostics)
843 pub fn abort_if_errors(&self) {
844 self.inner.borrow_mut().abort_if_errors()
847 /// `true` if we haven't taught a diagnostic with this code already.
848 /// The caller must then teach the user about such a diagnostic.
850 /// Used to suppress emitting the same error multiple times with extended explanation when
851 /// calling `-Zteach`.
852 pub fn must_teach(&self, code: &DiagnosticId) -> bool {
853 self.inner.borrow_mut().must_teach(code)
856 pub fn force_print_diagnostic(&self, db: Diagnostic) {
857 self.inner.borrow_mut().force_print_diagnostic(db)
860 pub fn emit_diagnostic(&self, diagnostic: &Diagnostic) {
861 self.inner.borrow_mut().emit_diagnostic(diagnostic)
864 fn emit_diag_at_span(&self, mut diag: Diagnostic, sp: impl Into<MultiSpan>) {
865 let mut inner = self.inner.borrow_mut();
866 inner.emit_diagnostic(diag.set_span(sp));
869 pub fn emit_artifact_notification(&self, path: &Path, artifact_type: &str) {
870 self.inner.borrow_mut().emit_artifact_notification(path, artifact_type)
873 pub fn emit_future_breakage_report(&self, diags: Vec<Diagnostic>) {
874 self.inner.borrow_mut().emitter.emit_future_breakage_report(diags)
877 pub fn emit_unused_externs(&self, lint_level: &str, unused_externs: &[&str]) {
878 self.inner.borrow_mut().emit_unused_externs(lint_level, unused_externs)
881 pub fn delay_as_bug(&self, diagnostic: Diagnostic) {
882 self.inner.borrow_mut().delay_as_bug(diagnostic)
887 fn must_teach(&mut self, code: &DiagnosticId) -> bool {
888 self.taught_diagnostics.insert(code.clone())
891 fn force_print_diagnostic(&mut self, db: Diagnostic) {
892 self.emitter.emit_diagnostic(&db);
895 /// Emit all stashed diagnostics.
896 fn emit_stashed_diagnostics(&mut self) {
897 let diags = self.stashed_diagnostics.drain(..).map(|x| x.1).collect::<Vec<_>>();
898 diags.iter().for_each(|diag| self.emit_diagnostic(diag));
901 fn emit_diagnostic(&mut self, diagnostic: &Diagnostic) {
902 if diagnostic.cancelled() || self.quiet {
906 if diagnostic.has_future_breakage() {
907 self.future_breakage_diagnostics.push(diagnostic.clone());
910 if diagnostic.level == Warning
911 && !self.flags.can_emit_warnings
912 && !diagnostic.is_force_warn()
914 if diagnostic.has_future_breakage() {
915 (*TRACK_DIAGNOSTICS)(diagnostic);
920 (*TRACK_DIAGNOSTICS)(diagnostic);
922 if diagnostic.level == Allow {
926 if let Some(ref code) = diagnostic.code {
927 self.emitted_diagnostic_codes.insert(code.clone());
930 let already_emitted = |this: &mut Self| {
931 let mut hasher = StableHasher::new();
932 diagnostic.hash(&mut hasher);
933 let diagnostic_hash = hasher.finish();
934 !this.emitted_diagnostics.insert(diagnostic_hash)
937 // Only emit the diagnostic if we've been asked to deduplicate and
938 // haven't already emitted an equivalent diagnostic.
939 if !(self.flags.deduplicate_diagnostics && already_emitted(self)) {
940 self.emitter.emit_diagnostic(diagnostic);
941 if diagnostic.is_error() {
942 self.deduplicated_err_count += 1;
943 } else if diagnostic.level == Warning {
944 self.deduplicated_warn_count += 1;
947 if diagnostic.is_error() {
948 self.bump_err_count();
950 self.bump_warn_count();
954 fn emit_artifact_notification(&mut self, path: &Path, artifact_type: &str) {
955 self.emitter.emit_artifact_notification(path, artifact_type);
958 fn emit_unused_externs(&mut self, lint_level: &str, unused_externs: &[&str]) {
959 self.emitter.emit_unused_externs(lint_level, unused_externs);
962 fn treat_err_as_bug(&self) -> bool {
963 self.flags.treat_err_as_bug.map_or(false, |c| self.err_count() >= c.get())
966 fn print_error_count(&mut self, registry: &Registry) {
967 self.emit_stashed_diagnostics();
969 let warnings = match self.deduplicated_warn_count {
971 1 => "1 warning emitted".to_string(),
972 count => format!("{} warnings emitted", count),
974 let errors = match self.deduplicated_err_count {
976 1 => "aborting due to previous error".to_string(),
977 count => format!("aborting due to {} previous errors", count),
979 if self.treat_err_as_bug() {
983 match (errors.len(), warnings.len()) {
985 (0, _) => self.emitter.emit_diagnostic(&Diagnostic::new(Level::Warning, &warnings)),
987 let _ = self.fatal(&errors);
990 let _ = self.fatal(&format!("{}; {}", &errors, &warnings));
994 let can_show_explain = self.emitter.should_show_explain();
995 let are_there_diagnostics = !self.emitted_diagnostic_codes.is_empty();
996 if can_show_explain && are_there_diagnostics {
997 let mut error_codes = self
998 .emitted_diagnostic_codes
1000 .filter_map(|x| match &x {
1001 DiagnosticId::Error(s) => {
1002 if let Ok(Some(_explanation)) = registry.try_find_description(s) {
1010 .collect::<Vec<_>>();
1011 if !error_codes.is_empty() {
1013 if error_codes.len() > 1 {
1014 let limit = if error_codes.len() > 9 { 9 } else { error_codes.len() };
1015 self.failure(&format!(
1016 "Some errors have detailed explanations: {}{}",
1017 error_codes[..limit].join(", "),
1018 if error_codes.len() > 9 { "..." } else { "." }
1020 self.failure(&format!(
1021 "For more information about an error, try \
1022 `rustc --explain {}`.",
1026 self.failure(&format!(
1027 "For more information about this error, try \
1028 `rustc --explain {}`.",
1037 fn err_count(&self) -> usize {
1038 self.err_count + self.stashed_diagnostics.len()
1041 fn has_errors(&self) -> bool {
1042 self.err_count() > 0
1044 fn has_errors_or_delayed_span_bugs(&self) -> bool {
1045 self.has_errors() || !self.delayed_span_bugs.is_empty()
1047 fn has_any_message(&self) -> bool {
1048 self.err_count() > 0 || self.warn_count > 0
1051 fn abort_if_errors(&mut self) {
1052 self.emit_stashed_diagnostics();
1054 if self.has_errors() {
1059 fn span_bug(&mut self, sp: impl Into<MultiSpan>, msg: &str) -> ! {
1060 self.emit_diag_at_span(Diagnostic::new(Bug, msg), sp);
1061 panic::panic_any(ExplicitBug);
1064 fn emit_diag_at_span(&mut self, mut diag: Diagnostic, sp: impl Into<MultiSpan>) {
1065 self.emit_diagnostic(diag.set_span(sp));
1069 fn delay_span_bug(&mut self, sp: impl Into<MultiSpan>, msg: &str) {
1070 // This is technically `self.treat_err_as_bug()` but `delay_span_bug` is called before
1071 // incrementing `err_count` by one, so we need to +1 the comparing.
1072 // FIXME: Would be nice to increment err_count in a more coherent way.
1073 if self.flags.treat_err_as_bug.map_or(false, |c| self.err_count() + 1 >= c.get()) {
1074 // FIXME: don't abort here if report_delayed_bugs is off
1075 self.span_bug(sp, msg);
1077 let mut diagnostic = Diagnostic::new(Level::Bug, msg);
1078 diagnostic.set_span(sp.into());
1079 diagnostic.note(&format!("delayed at {}", std::panic::Location::caller()));
1080 self.delay_as_bug(diagnostic)
1083 fn delay_good_path_bug(&mut self, msg: &str) {
1084 let diagnostic = Diagnostic::new(Level::Bug, msg);
1085 if self.flags.report_delayed_bugs {
1086 self.emit_diagnostic(&diagnostic);
1088 let backtrace = std::backtrace::Backtrace::force_capture();
1089 self.delayed_good_path_bugs.push(DelayedDiagnostic::with_backtrace(diagnostic, backtrace));
1092 fn failure(&mut self, msg: &str) {
1093 self.emit_diagnostic(&Diagnostic::new(FailureNote, msg));
1096 fn fatal(&mut self, msg: &str) -> FatalError {
1097 self.emit_error(Fatal, msg);
1101 fn err(&mut self, msg: &str) {
1102 self.emit_error(Error, msg);
1105 /// Emit an error; level should be `Error` or `Fatal`.
1106 fn emit_error(&mut self, level: Level, msg: &str) {
1107 if self.treat_err_as_bug() {
1110 self.emit_diagnostic(&Diagnostic::new(level, msg));
1113 fn bug(&mut self, msg: &str) -> ! {
1114 self.emit_diagnostic(&Diagnostic::new(Bug, msg));
1115 panic::panic_any(ExplicitBug);
1118 fn delay_as_bug(&mut self, diagnostic: Diagnostic) {
1122 if self.flags.report_delayed_bugs {
1123 self.emit_diagnostic(&diagnostic);
1125 self.delayed_span_bugs.push(diagnostic);
1128 fn flush_delayed(&mut self, bugs: Vec<Diagnostic>, explanation: &str) {
1129 let has_bugs = !bugs.is_empty();
1131 self.emit_diagnostic(&bug);
1134 panic!("{}", explanation);
1138 fn bump_err_count(&mut self) {
1139 self.err_count += 1;
1140 self.panic_if_treat_err_as_bug();
1143 fn bump_warn_count(&mut self) {
1144 self.warn_count += 1;
1147 fn panic_if_treat_err_as_bug(&self) {
1148 if self.treat_err_as_bug() {
1149 match (self.err_count(), self.flags.treat_err_as_bug.map(|c| c.get()).unwrap_or(0)) {
1150 (1, 1) => panic!("aborting due to `-Z treat-err-as-bug=1`"),
1151 (0, _) | (1, _) => {}
1152 (count, as_bug) => panic!(
1153 "aborting after {} errors due to `-Z treat-err-as-bug={}`",
1161 struct DelayedDiagnostic {
1166 impl DelayedDiagnostic {
1167 fn with_backtrace(diagnostic: Diagnostic, backtrace: Backtrace) -> Self {
1168 DelayedDiagnostic { inner: diagnostic, note: backtrace }
1171 fn decorate(mut self) -> Diagnostic {
1172 self.inner.note(&format!("delayed at {}", self.note));
1177 #[derive(Copy, PartialEq, Clone, Hash, Debug, Encodable, Decodable)]
1190 impl fmt::Display for Level {
1191 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1192 self.to_str().fmt(f)
1197 fn color(self) -> ColorSpec {
1198 let mut spec = ColorSpec::new();
1200 Bug | Fatal | Error => {
1201 spec.set_fg(Some(Color::Red)).set_intense(true);
1204 spec.set_fg(Some(Color::Yellow)).set_intense(cfg!(windows));
1207 spec.set_fg(Some(Color::Green)).set_intense(true);
1210 spec.set_fg(Some(Color::Cyan)).set_intense(true);
1213 Allow | Cancelled => unreachable!(),
1218 pub fn to_str(self) -> &'static str {
1220 Bug => "error: internal compiler error",
1221 Fatal | Error => "error",
1222 Warning => "warning",
1225 FailureNote => "failure-note",
1226 Cancelled => panic!("Shouldn't call on cancelled error"),
1227 Allow => panic!("Shouldn't call on allowed error"),
1231 pub fn is_failure_note(&self) -> bool {
1232 matches!(*self, FailureNote)
1236 pub fn add_elided_lifetime_in_path_suggestion(
1237 source_map: &SourceMap,
1238 db: &mut DiagnosticBuilder<'_>,
1241 incl_angl_brckt: bool,
1242 insertion_span: Span,
1245 let (replace_span, suggestion) = if incl_angl_brckt {
1246 (insertion_span, anon_lts)
1248 // When possible, prefer a suggestion that replaces the whole
1249 // `Path<T>` expression with `Path<'_, T>`, rather than inserting `'_, `
1250 // at a point (which makes for an ugly/confusing label)
1251 if let Ok(snippet) = source_map.span_to_snippet(path_span) {
1252 // But our spans can get out of whack due to macros; if the place we think
1253 // we want to insert `'_` isn't even within the path expression's span, we
1254 // should bail out of making any suggestion rather than panicking on a
1255 // subtract-with-overflow or string-slice-out-out-bounds (!)
1256 // FIXME: can we do better?
1257 if insertion_span.lo().0 < path_span.lo().0 {
1260 let insertion_index = (insertion_span.lo().0 - path_span.lo().0) as usize;
1261 if insertion_index > snippet.len() {
1264 let (before, after) = snippet.split_at(insertion_index);
1265 (path_span, format!("{}{}{}", before, anon_lts, after))
1267 (insertion_span, anon_lts)
1272 &format!("indicate the anonymous lifetime{}", pluralize!(n)),
1274 Applicability::MachineApplicable,
1278 // Useful type to use with `Result<>` indicate that an error has already
1279 // been reported to the user, so no need to continue checking.
1280 #[derive(Clone, Copy, Debug, Encodable, Decodable, Hash, PartialEq, Eq)]
1281 pub struct ErrorReported;
1283 rustc_data_structures::impl_stable_hash_via_hash!(ErrorReported);