1 //! Diagnostics creation and emission for `rustc`.
3 //! This module contains the code for creating and emitting diagnostics.
5 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
6 #![feature(crate_visibility_modifier)]
8 #![feature(if_let_guard)]
11 #![cfg_attr(not(bootstrap), allow(rustc::potential_query_instability))]
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 `DiagnosticBuilder`'s `diagnostic` field.)
59 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
60 rustc_data_structures::static_assert_size!(PResult<'_, ()>, 16);
61 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
62 rustc_data_structures::static_assert_size!(PResult<'_, bool>, 24);
64 #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, Encodable, Decodable)]
65 pub enum SuggestionStyle {
66 /// Hide the suggested code when displaying this suggestion inline.
68 /// Always hide the suggested code but display the message.
70 /// Do not display this suggestion in the cli output, it is only meant for tools.
72 /// Always show the suggested code.
73 /// This will *not* show the code if the suggestion is inline *and* the suggested code is
76 /// Always show the suggested code independently.
80 impl SuggestionStyle {
81 fn hide_inline(&self) -> bool {
82 !matches!(*self, SuggestionStyle::ShowCode)
86 #[derive(Clone, Debug, PartialEq, Default)]
87 pub struct ToolMetadata(pub Option<Json>);
90 fn new(json: Json) -> Self {
91 ToolMetadata(Some(json))
94 fn is_set(&self) -> bool {
99 impl Hash for ToolMetadata {
100 fn hash<H: Hasher>(&self, _state: &mut H) {}
103 // Doesn't really need to round-trip
104 impl<D: Decoder> Decodable<D> for ToolMetadata {
105 fn decode(_d: &mut D) -> Self {
110 impl<S: Encoder> Encodable<S> for ToolMetadata {
111 fn encode(&self, e: &mut S) -> Result<(), S::Error> {
113 None => e.emit_unit(),
114 Some(json) => json.encode(e),
119 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
120 pub struct CodeSuggestion {
121 /// Each substitute can have multiple variants due to multiple
122 /// applicable suggestions
124 /// `foo.bar` might be replaced with `a.b` or `x.y` by replacing
125 /// `foo` and `bar` on their own:
129 /// Substitution { parts: vec![(0..3, "a"), (4..7, "b")] },
130 /// Substitution { parts: vec![(0..3, "x"), (4..7, "y")] },
134 /// or by replacing the entire span:
138 /// Substitution { parts: vec![(0..7, "a.b")] },
139 /// Substitution { parts: vec![(0..7, "x.y")] },
142 pub substitutions: Vec<Substitution>,
144 /// Visual representation of this suggestion.
145 pub style: SuggestionStyle,
146 /// Whether or not the suggestion is approximate
148 /// Sometimes we may show suggestions with placeholders,
149 /// which are useful for users but not useful for
150 /// tools like rustfix
151 pub applicability: Applicability,
152 /// Tool-specific metadata
153 pub tool_metadata: ToolMetadata,
156 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
157 /// See the docs on `CodeSuggestion::substitutions`
158 pub struct Substitution {
159 pub parts: Vec<SubstitutionPart>,
162 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
163 pub struct SubstitutionPart {
168 /// Used to translate between `Span`s and byte positions within a single output line in highlighted
169 /// code of structured suggestions.
170 #[derive(Debug, Clone, Copy)]
171 pub struct SubstitutionHighlight {
176 impl SubstitutionPart {
177 pub fn is_addition(&self, sm: &SourceMap) -> bool {
178 !self.snippet.is_empty()
180 .span_to_snippet(self.span)
181 .map_or(self.span.is_empty(), |snippet| snippet.trim().is_empty())
184 pub fn is_deletion(&self) -> bool {
185 self.snippet.trim().is_empty()
188 pub fn is_replacement(&self, sm: &SourceMap) -> bool {
189 !self.snippet.is_empty()
191 .span_to_snippet(self.span)
192 .map_or(!self.span.is_empty(), |snippet| !snippet.trim().is_empty())
196 impl CodeSuggestion {
197 /// Returns the assembled code suggestions, whether they should be shown with an underline
198 /// and whether the substitution only differs in capitalization.
202 ) -> Vec<(String, Vec<SubstitutionPart>, Vec<Vec<SubstitutionHighlight>>, bool)> {
203 // For the `Vec<Vec<SubstitutionHighlight>>` value, the first level of the vector
204 // corresponds to the output snippet's lines, while the second level corresponds to the
205 // substrings within that line that should be highlighted.
207 use rustc_span::{CharPos, Pos};
209 /// Append to a buffer the remainder of the line of existing source code, and return the
210 /// count of lines that have been added for accurate highlighting.
213 line_opt: Option<&Cow<'_, str>>,
215 hi_opt: Option<&Loc>,
217 let mut line_count = 0;
218 let (lo, hi_opt) = (lo.col.to_usize(), hi_opt.map(|hi| hi.col.to_usize()));
219 if let Some(line) = line_opt {
220 if let Some(lo) = line.char_indices().map(|(i, _)| i).nth(lo) {
221 let hi_opt = hi_opt.and_then(|hi| line.char_indices().map(|(i, _)| i).nth(hi));
223 Some(hi) if hi > lo => {
224 line_count = line[lo..hi].matches('\n').count();
225 buf.push_str(&line[lo..hi])
229 line_count = line[lo..].matches('\n').count();
230 buf.push_str(&line[lo..])
234 if hi_opt.is_none() {
241 assert!(!self.substitutions.is_empty());
246 // Suggestions coming from macros can have malformed spans. This is a heavy
247 // handed approach to avoid ICEs by ignoring the suggestion outright.
248 let invalid = subst.parts.iter().any(|item| sm.is_valid_span(item.span).is_err());
250 debug!("splice_lines: suggestion contains an invalid span: {:?}", subst);
255 .filter_map(|mut substitution| {
256 // Assumption: all spans are in the same file, and all spans
257 // are disjoint. Sort in ascending order.
258 substitution.parts.sort_by_key(|part| part.span.lo());
260 // Find the bounding span.
261 let lo = substitution.parts.iter().map(|part| part.span.lo()).min()?;
262 let hi = substitution.parts.iter().map(|part| part.span.hi()).max()?;
263 let bounding_span = Span::with_root_ctxt(lo, hi);
264 // The different spans might belong to different contexts, if so ignore suggestion.
265 let lines = sm.span_to_lines(bounding_span).ok()?;
266 assert!(!lines.lines.is_empty() || bounding_span.is_dummy());
268 // We can't splice anything if the source is unavailable.
269 if !sm.ensure_source_file_source_present(lines.file.clone()) {
273 let mut highlights = vec![];
274 // To build up the result, we do this for each span:
275 // - push the line segment trailing the previous span
276 // (at the beginning a "phantom" span pointing at the start of the line)
277 // - push lines between the previous and current span (if any)
278 // - if the previous and current span are not on the same line
279 // push the line segment leading up to the current span
280 // - splice in the span substitution
282 // Finally push the trailing line segment of the last span
283 let sf = &lines.file;
284 let mut prev_hi = sm.lookup_char_pos(bounding_span.lo());
285 prev_hi.col = CharPos::from_usize(0);
287 lines.lines.get(0).and_then(|line0| sf.get_line(line0.line_index));
288 let mut buf = String::new();
290 let mut line_highlight = vec![];
291 // We need to keep track of the difference between the existing code and the added
292 // or deleted code in order to point at the correct column *after* substitution.
294 for part in &substitution.parts {
295 let cur_lo = sm.lookup_char_pos(part.span.lo());
296 if prev_hi.line == cur_lo.line {
298 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, Some(&cur_lo));
300 highlights.push(std::mem::take(&mut line_highlight));
306 highlights.push(std::mem::take(&mut line_highlight));
307 let mut count = push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
309 highlights.push(std::mem::take(&mut line_highlight));
312 // push lines between the previous and current span (if any)
313 for idx in prev_hi.line..(cur_lo.line - 1) {
314 if let Some(line) = sf.get_line(idx) {
315 buf.push_str(line.as_ref());
317 highlights.push(std::mem::take(&mut line_highlight));
320 if let Some(cur_line) = sf.get_line(cur_lo.line - 1) {
321 let end = match cur_line.char_indices().nth(cur_lo.col.to_usize()) {
323 None => cur_line.len(),
325 buf.push_str(&cur_line[..end]);
328 // Add a whole line highlight per line in the snippet.
329 let len: isize = part
333 .unwrap_or(&part.snippet)
340 line_highlight.push(SubstitutionHighlight {
341 start: (cur_lo.col.0 as isize + acc) as usize,
342 end: (cur_lo.col.0 as isize + acc + len) as usize,
344 buf.push_str(&part.snippet);
345 let cur_hi = sm.lookup_char_pos(part.span.hi());
346 if prev_hi.line == cur_lo.line && cur_hi.line == cur_lo.line {
347 // Account for the difference between the width of the current code and the
348 // snippet being suggested, so that the *later* suggestions are correctly
349 // aligned on the screen.
350 acc += len as isize - (cur_hi.col.0 - cur_lo.col.0) as isize;
353 prev_line = sf.get_line(prev_hi.line - 1);
354 for line in part.snippet.split('\n').skip(1) {
356 highlights.push(std::mem::take(&mut line_highlight));
357 let end: usize = line
364 line_highlight.push(SubstitutionHighlight { start: 0, end });
367 highlights.push(std::mem::take(&mut line_highlight));
368 let only_capitalization = is_case_difference(sm, &buf, bounding_span);
369 // if the replacement already ends with a newline, don't print the next line
370 if !buf.ends_with('\n') {
371 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
373 // remove trailing newlines
374 while buf.ends_with('\n') {
377 Some((buf, substitution.parts, highlights, only_capitalization))
383 pub use rustc_span::fatal_error::{FatalError, FatalErrorMarker};
385 /// Signifies that the compiler died with an explicit call to `.bug`
386 /// or `.span_bug` rather than a failed assertion, etc.
387 #[derive(Copy, Clone, Debug)]
388 pub struct ExplicitBug;
390 impl fmt::Display for ExplicitBug {
391 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
392 write!(f, "parser internal bug")
396 impl error::Error for ExplicitBug {}
398 pub use diagnostic::{Diagnostic, DiagnosticId, DiagnosticStyledString, SubDiagnostic};
399 pub use diagnostic_builder::DiagnosticBuilder;
400 use std::backtrace::Backtrace;
402 /// A handler deals with errors and other compiler output.
403 /// Certain errors (fatal, bug, unimpl) may cause immediate exit,
404 /// others log errors for later reporting.
407 inner: Lock<HandlerInner>,
410 /// This inner struct exists to keep it all behind a single lock;
411 /// this is done to prevent possible deadlocks in a multi-threaded compiler,
412 /// as well as inconsistent state observation.
413 struct HandlerInner {
415 /// The number of lint errors that have been emitted.
416 lint_err_count: usize,
417 /// The number of errors that have been emitted, including duplicates.
419 /// This is not necessarily the count that's reported to the user once
420 /// compilation ends.
423 deduplicated_err_count: usize,
424 emitter: Box<dyn Emitter + sync::Send>,
425 delayed_span_bugs: Vec<Diagnostic>,
426 delayed_good_path_bugs: Vec<DelayedDiagnostic>,
428 /// This set contains the `DiagnosticId` of all emitted diagnostics to avoid
429 /// emitting the same diagnostic with extended help (`--teach`) twice, which
430 /// would be unnecessary repetition.
431 taught_diagnostics: FxHashSet<DiagnosticId>,
433 /// Used to suggest rustc --explain <error code>
434 emitted_diagnostic_codes: FxHashSet<DiagnosticId>,
436 /// This set contains a hash of every diagnostic that has been emitted by
437 /// this handler. These hashes is used to avoid emitting the same error
439 emitted_diagnostics: FxHashSet<u128>,
441 /// Stashed diagnostics emitted in one stage of the compiler that may be
442 /// stolen by other stages (e.g. to improve them and add more information).
443 /// The stashed diagnostics count towards the total error count.
444 /// When `.abort_if_errors()` is called, these are also emitted.
445 stashed_diagnostics: FxIndexMap<(Span, StashKey), Diagnostic>,
447 /// The warning count, used for a recap upon finishing
448 deduplicated_warn_count: usize,
450 future_breakage_diagnostics: Vec<Diagnostic>,
453 /// A key denoting where from a diagnostic was stashed.
454 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
459 fn default_track_diagnostic(_: &Diagnostic) {}
461 pub static TRACK_DIAGNOSTICS: AtomicRef<fn(&Diagnostic)> =
462 AtomicRef::new(&(default_track_diagnostic as fn(&_)));
464 #[derive(Copy, Clone, Default)]
465 pub struct HandlerFlags {
466 /// If false, warning-level lints are suppressed.
467 /// (rustc: see `--allow warnings` and `--cap-lints`)
468 pub can_emit_warnings: bool,
469 /// If true, error-level diagnostics are upgraded to bug-level.
470 /// (rustc: see `-Z treat-err-as-bug`)
471 pub treat_err_as_bug: Option<NonZeroUsize>,
472 /// If true, immediately emit diagnostics that would otherwise be buffered.
473 /// (rustc: see `-Z dont-buffer-diagnostics` and `-Z treat-err-as-bug`)
474 pub dont_buffer_diagnostics: bool,
475 /// If true, immediately print bugs registered with `delay_span_bug`.
476 /// (rustc: see `-Z report-delayed-bugs`)
477 pub report_delayed_bugs: bool,
478 /// Show macro backtraces.
479 /// (rustc: see `-Z macro-backtrace`)
480 pub macro_backtrace: bool,
481 /// If true, identical diagnostics are reported only once.
482 pub deduplicate_diagnostics: bool,
485 impl Drop for HandlerInner {
487 self.emit_stashed_diagnostics();
489 if !self.has_errors() {
490 let bugs = std::mem::replace(&mut self.delayed_span_bugs, Vec::new());
491 self.flush_delayed(bugs, "no errors encountered even though `delay_span_bug` issued");
494 if !self.has_any_message() {
495 let bugs = std::mem::replace(&mut self.delayed_good_path_bugs, Vec::new());
497 bugs.into_iter().map(DelayedDiagnostic::decorate).collect(),
498 "no warnings or errors encountered even though `delayed_good_path_bugs` issued",
505 pub fn with_tty_emitter(
506 color_config: ColorConfig,
507 can_emit_warnings: bool,
508 treat_err_as_bug: Option<NonZeroUsize>,
509 sm: Option<Lrc<SourceMap>>,
511 Self::with_tty_emitter_and_flags(
514 HandlerFlags { can_emit_warnings, treat_err_as_bug, ..Default::default() },
518 pub fn with_tty_emitter_and_flags(
519 color_config: ColorConfig,
520 sm: Option<Lrc<SourceMap>>,
523 let emitter = Box::new(EmitterWriter::stderr(
529 flags.macro_backtrace,
531 Self::with_emitter_and_flags(emitter, flags)
535 can_emit_warnings: bool,
536 treat_err_as_bug: Option<NonZeroUsize>,
537 emitter: Box<dyn Emitter + sync::Send>,
539 Handler::with_emitter_and_flags(
541 HandlerFlags { can_emit_warnings, treat_err_as_bug, ..Default::default() },
545 pub fn with_emitter_and_flags(
546 emitter: Box<dyn Emitter + sync::Send>,
551 inner: Lock::new(HandlerInner {
556 deduplicated_err_count: 0,
557 deduplicated_warn_count: 0,
559 delayed_span_bugs: Vec::new(),
560 delayed_good_path_bugs: Vec::new(),
561 taught_diagnostics: Default::default(),
562 emitted_diagnostic_codes: Default::default(),
563 emitted_diagnostics: Default::default(),
564 stashed_diagnostics: Default::default(),
565 future_breakage_diagnostics: Vec::new(),
570 // This is here to not allow mutation of flags;
571 // as of this writing it's only used in tests in librustc_middle.
572 pub fn can_emit_warnings(&self) -> bool {
573 self.flags.can_emit_warnings
576 /// Resets the diagnostic error count as well as the cached emitted diagnostics.
578 /// NOTE: *do not* call this function from rustc. It is only meant to be called from external
579 /// tools that want to reuse a `Parser` cleaning the previously emitted diagnostics as well as
580 /// the overall count of emitted error diagnostics.
581 pub fn reset_err_count(&self) {
582 let mut inner = self.inner.borrow_mut();
584 inner.warn_count = 0;
585 inner.deduplicated_err_count = 0;
586 inner.deduplicated_warn_count = 0;
588 // actually free the underlying memory (which `clear` would not do)
589 inner.delayed_span_bugs = Default::default();
590 inner.delayed_good_path_bugs = Default::default();
591 inner.taught_diagnostics = Default::default();
592 inner.emitted_diagnostic_codes = Default::default();
593 inner.emitted_diagnostics = Default::default();
594 inner.stashed_diagnostics = Default::default();
597 /// Stash a given diagnostic with the given `Span` and `StashKey` as the key for later stealing.
598 pub fn stash_diagnostic(&self, span: Span, key: StashKey, diag: Diagnostic) {
599 let mut inner = self.inner.borrow_mut();
600 // FIXME(Centril, #69537): Consider reintroducing panic on overwriting a stashed diagnostic
601 // if/when we have a more robust macro-friendly replacement for `(span, key)` as a key.
602 // See the PR for a discussion.
603 inner.stashed_diagnostics.insert((span, key), diag);
606 /// Steal a previously stashed diagnostic with the given `Span` and `StashKey` as the key.
607 pub fn steal_diagnostic(&self, span: Span, key: StashKey) -> Option<DiagnosticBuilder<'_>> {
611 .remove(&(span, key))
612 .map(|diag| DiagnosticBuilder::new_diagnostic(self, diag))
615 /// Emit all stashed diagnostics.
616 pub fn emit_stashed_diagnostics(&self) {
617 self.inner.borrow_mut().emit_stashed_diagnostics();
620 /// Construct a dummy builder with `Level::Cancelled`.
622 /// Using this will neither report anything to the user (e.g. a warning),
623 /// nor will compilation cancel as a result.
624 pub fn struct_dummy(&self) -> DiagnosticBuilder<'_> {
625 DiagnosticBuilder::new(self, Level::Cancelled, "")
628 /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
630 /// The builder will be canceled if warnings cannot be emitted.
631 pub fn struct_span_warn(&self, span: impl Into<MultiSpan>, msg: &str) -> DiagnosticBuilder<'_> {
632 let mut result = self.struct_warn(msg);
633 result.set_span(span);
637 /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
639 /// This will "force" the warning meaning it will not be canceled even
640 /// if warnings cannot be emitted.
641 pub fn struct_span_force_warn(
643 span: impl Into<MultiSpan>,
645 ) -> DiagnosticBuilder<'_> {
646 let mut result = self.struct_force_warn(msg);
647 result.set_span(span);
651 /// Construct a builder at the `Allow` level at the given `span` and with the `msg`.
652 pub fn struct_span_allow(
654 span: impl Into<MultiSpan>,
656 ) -> DiagnosticBuilder<'_> {
657 let mut result = self.struct_allow(msg);
658 result.set_span(span);
662 /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
663 /// Also include a code.
664 pub fn struct_span_warn_with_code(
666 span: impl Into<MultiSpan>,
669 ) -> DiagnosticBuilder<'_> {
670 let mut result = self.struct_span_warn(span, msg);
675 /// Construct a builder at the `Warning` level with the `msg`.
677 /// The builder will be canceled if warnings cannot be emitted.
678 pub fn struct_warn(&self, msg: &str) -> DiagnosticBuilder<'_> {
679 let mut result = DiagnosticBuilder::new(self, Level::Warning, msg);
680 if !self.flags.can_emit_warnings {
686 /// Construct a builder at the `Warning` level with the `msg`.
688 /// This will "force" a warning meaning it will not be canceled even
689 /// if warnings cannot be emitted.
690 pub fn struct_force_warn(&self, msg: &str) -> DiagnosticBuilder<'_> {
691 DiagnosticBuilder::new(self, Level::Warning, msg)
694 /// Construct a builder at the `Allow` level with the `msg`.
695 pub fn struct_allow(&self, msg: &str) -> DiagnosticBuilder<'_> {
696 DiagnosticBuilder::new(self, Level::Allow, msg)
699 /// Construct a builder at the `Error` level at the given `span` and with the `msg`.
700 pub fn struct_span_err(&self, span: impl Into<MultiSpan>, msg: &str) -> DiagnosticBuilder<'_> {
701 let mut result = self.struct_err(msg);
702 result.set_span(span);
706 /// Construct a builder at the `Error` level at the given `span`, with the `msg`, and `code`.
707 pub fn struct_span_err_with_code(
709 span: impl Into<MultiSpan>,
712 ) -> DiagnosticBuilder<'_> {
713 let mut result = self.struct_span_err(span, msg);
718 /// Construct a builder at the `Error` level with the `msg`.
719 // FIXME: This method should be removed (every error should have an associated error code).
720 pub fn struct_err(&self, msg: &str) -> DiagnosticBuilder<'_> {
721 DiagnosticBuilder::new(self, Level::Error { lint: false }, msg)
724 /// This should only be used by `rustc_middle::lint::struct_lint_level`. Do not use it for hard errors.
726 pub fn struct_err_lint(&self, msg: &str) -> DiagnosticBuilder<'_> {
727 DiagnosticBuilder::new(self, Level::Error { lint: true }, msg)
730 /// Construct a builder at the `Error` level with the `msg` and the `code`.
731 pub fn struct_err_with_code(&self, msg: &str, code: DiagnosticId) -> DiagnosticBuilder<'_> {
732 let mut result = self.struct_err(msg);
737 /// Construct a builder at the `Fatal` level at the given `span` and with the `msg`.
738 pub fn struct_span_fatal(
740 span: impl Into<MultiSpan>,
742 ) -> DiagnosticBuilder<'_> {
743 let mut result = self.struct_fatal(msg);
744 result.set_span(span);
748 /// Construct a builder at the `Fatal` level at the given `span`, with the `msg`, and `code`.
749 pub fn struct_span_fatal_with_code(
751 span: impl Into<MultiSpan>,
754 ) -> DiagnosticBuilder<'_> {
755 let mut result = self.struct_span_fatal(span, msg);
760 /// Construct a builder at the `Error` level with the `msg`.
761 pub fn struct_fatal(&self, msg: &str) -> DiagnosticBuilder<'_> {
762 DiagnosticBuilder::new(self, Level::Fatal, msg)
765 /// Construct a builder at the `Help` level with the `msg`.
766 pub fn struct_help(&self, msg: &str) -> DiagnosticBuilder<'_> {
767 DiagnosticBuilder::new(self, Level::Help, msg)
770 /// Construct a builder at the `Note` level with the `msg`.
771 pub fn struct_note_without_error(&self, msg: &str) -> DiagnosticBuilder<'_> {
772 DiagnosticBuilder::new(self, Level::Note, msg)
775 pub fn span_fatal(&self, span: impl Into<MultiSpan>, msg: &str) -> ! {
776 self.emit_diag_at_span(Diagnostic::new(Fatal, msg), span);
780 pub fn span_fatal_with_code(
782 span: impl Into<MultiSpan>,
786 self.emit_diag_at_span(Diagnostic::new_with_code(Fatal, Some(code), msg), span);
790 pub fn span_err(&self, span: impl Into<MultiSpan>, msg: &str) {
791 self.emit_diag_at_span(Diagnostic::new(Error { lint: false }, msg), span);
794 pub fn span_err_with_code(&self, span: impl Into<MultiSpan>, msg: &str, code: DiagnosticId) {
795 self.emit_diag_at_span(
796 Diagnostic::new_with_code(Error { lint: false }, Some(code), msg),
801 pub fn span_warn(&self, span: impl Into<MultiSpan>, msg: &str) {
802 self.emit_diag_at_span(Diagnostic::new(Warning, msg), span);
805 pub fn span_warn_with_code(&self, span: impl Into<MultiSpan>, msg: &str, code: DiagnosticId) {
806 self.emit_diag_at_span(Diagnostic::new_with_code(Warning, Some(code), msg), span);
809 pub fn span_bug(&self, span: impl Into<MultiSpan>, msg: &str) -> ! {
810 self.inner.borrow_mut().span_bug(span, msg)
814 pub fn delay_span_bug(&self, span: impl Into<MultiSpan>, msg: &str) {
815 self.inner.borrow_mut().delay_span_bug(span, msg)
818 pub fn delay_good_path_bug(&self, msg: &str) {
819 self.inner.borrow_mut().delay_good_path_bug(msg)
822 pub fn span_bug_no_panic(&self, span: impl Into<MultiSpan>, msg: &str) {
823 self.emit_diag_at_span(Diagnostic::new(Bug, msg), span);
826 pub fn span_note_without_error(&self, span: impl Into<MultiSpan>, msg: &str) {
827 self.emit_diag_at_span(Diagnostic::new(Note, msg), span);
830 pub fn span_note_diag(&self, span: Span, msg: &str) -> DiagnosticBuilder<'_> {
831 let mut db = DiagnosticBuilder::new(self, Note, msg);
836 // NOTE: intentionally doesn't raise an error so rustc_codegen_ssa only reports fatal errors in the main thread
837 pub fn fatal(&self, msg: &str) -> FatalError {
838 self.inner.borrow_mut().fatal(msg)
841 pub fn err(&self, msg: &str) {
842 self.inner.borrow_mut().err(msg);
845 pub fn warn(&self, msg: &str) {
846 let mut db = DiagnosticBuilder::new(self, Warning, msg);
850 pub fn note_without_error(&self, msg: &str) {
851 DiagnosticBuilder::new(self, Note, msg).emit();
854 pub fn bug(&self, msg: &str) -> ! {
855 self.inner.borrow_mut().bug(msg)
859 pub fn err_count(&self) -> usize {
860 self.inner.borrow().err_count()
863 pub fn has_errors(&self) -> bool {
864 self.inner.borrow().has_errors()
866 pub fn has_errors_or_lint_errors(&self) -> bool {
867 self.inner.borrow().has_errors_or_lint_errors()
869 pub fn has_errors_or_delayed_span_bugs(&self) -> bool {
870 self.inner.borrow().has_errors_or_delayed_span_bugs()
873 pub fn print_error_count(&self, registry: &Registry) {
874 self.inner.borrow_mut().print_error_count(registry)
877 pub fn take_future_breakage_diagnostics(&self) -> Vec<Diagnostic> {
878 std::mem::take(&mut self.inner.borrow_mut().future_breakage_diagnostics)
881 pub fn abort_if_errors(&self) {
882 self.inner.borrow_mut().abort_if_errors()
885 /// `true` if we haven't taught a diagnostic with this code already.
886 /// The caller must then teach the user about such a diagnostic.
888 /// Used to suppress emitting the same error multiple times with extended explanation when
889 /// calling `-Zteach`.
890 pub fn must_teach(&self, code: &DiagnosticId) -> bool {
891 self.inner.borrow_mut().must_teach(code)
894 pub fn force_print_diagnostic(&self, db: Diagnostic) {
895 self.inner.borrow_mut().force_print_diagnostic(db)
898 pub fn emit_diagnostic(&self, diagnostic: &Diagnostic) {
899 self.inner.borrow_mut().emit_diagnostic(diagnostic)
902 fn emit_diag_at_span(&self, mut diag: Diagnostic, sp: impl Into<MultiSpan>) {
903 let mut inner = self.inner.borrow_mut();
904 inner.emit_diagnostic(diag.set_span(sp));
907 pub fn emit_artifact_notification(&self, path: &Path, artifact_type: &str) {
908 self.inner.borrow_mut().emit_artifact_notification(path, artifact_type)
911 pub fn emit_future_breakage_report(&self, diags: Vec<Diagnostic>) {
912 self.inner.borrow_mut().emitter.emit_future_breakage_report(diags)
915 pub fn emit_unused_externs(&self, lint_level: &str, unused_externs: &[&str]) {
916 self.inner.borrow_mut().emit_unused_externs(lint_level, unused_externs)
919 pub fn delay_as_bug(&self, diagnostic: Diagnostic) {
920 self.inner.borrow_mut().delay_as_bug(diagnostic)
925 fn must_teach(&mut self, code: &DiagnosticId) -> bool {
926 self.taught_diagnostics.insert(code.clone())
929 fn force_print_diagnostic(&mut self, db: Diagnostic) {
930 self.emitter.emit_diagnostic(&db);
933 /// Emit all stashed diagnostics.
934 fn emit_stashed_diagnostics(&mut self) {
935 let diags = self.stashed_diagnostics.drain(..).map(|x| x.1).collect::<Vec<_>>();
936 diags.iter().for_each(|diag| self.emit_diagnostic(diag));
939 fn emit_diagnostic(&mut self, diagnostic: &Diagnostic) {
940 if diagnostic.cancelled() {
944 if diagnostic.has_future_breakage() {
945 self.future_breakage_diagnostics.push(diagnostic.clone());
948 if diagnostic.level == Warning
949 && !self.flags.can_emit_warnings
950 && !diagnostic.is_force_warn()
952 if diagnostic.has_future_breakage() {
953 (*TRACK_DIAGNOSTICS)(diagnostic);
958 (*TRACK_DIAGNOSTICS)(diagnostic);
960 if diagnostic.level == Allow {
964 if let Some(ref code) = diagnostic.code {
965 self.emitted_diagnostic_codes.insert(code.clone());
968 let already_emitted = |this: &mut Self| {
969 let mut hasher = StableHasher::new();
970 diagnostic.hash(&mut hasher);
971 let diagnostic_hash = hasher.finish();
972 !this.emitted_diagnostics.insert(diagnostic_hash)
975 // Only emit the diagnostic if we've been asked to deduplicate and
976 // haven't already emitted an equivalent diagnostic.
977 if !(self.flags.deduplicate_diagnostics && already_emitted(self)) {
978 self.emitter.emit_diagnostic(diagnostic);
979 if diagnostic.is_error() {
980 self.deduplicated_err_count += 1;
981 } else if diagnostic.level == Warning {
982 self.deduplicated_warn_count += 1;
985 if diagnostic.is_error() {
986 if matches!(diagnostic.level, Level::Error { lint: true }) {
987 self.bump_lint_err_count();
989 self.bump_err_count();
992 self.bump_warn_count();
996 fn emit_artifact_notification(&mut self, path: &Path, artifact_type: &str) {
997 self.emitter.emit_artifact_notification(path, artifact_type);
1000 fn emit_unused_externs(&mut self, lint_level: &str, unused_externs: &[&str]) {
1001 self.emitter.emit_unused_externs(lint_level, unused_externs);
1004 fn treat_err_as_bug(&self) -> bool {
1007 .map_or(false, |c| self.err_count() + self.lint_err_count >= c.get())
1010 fn print_error_count(&mut self, registry: &Registry) {
1011 self.emit_stashed_diagnostics();
1013 let warnings = match self.deduplicated_warn_count {
1015 1 => "1 warning emitted".to_string(),
1016 count => format!("{} warnings emitted", count),
1018 let errors = match self.deduplicated_err_count {
1020 1 => "aborting due to previous error".to_string(),
1021 count => format!("aborting due to {} previous errors", count),
1023 if self.treat_err_as_bug() {
1027 match (errors.len(), warnings.len()) {
1029 (0, _) => self.emitter.emit_diagnostic(&Diagnostic::new(Level::Warning, &warnings)),
1031 let _ = self.fatal(&errors);
1034 let _ = self.fatal(&format!("{}; {}", &errors, &warnings));
1038 let can_show_explain = self.emitter.should_show_explain();
1039 let are_there_diagnostics = !self.emitted_diagnostic_codes.is_empty();
1040 if can_show_explain && are_there_diagnostics {
1041 let mut error_codes = self
1042 .emitted_diagnostic_codes
1044 .filter_map(|x| match &x {
1045 DiagnosticId::Error(s)
1046 if registry.try_find_description(s).map_or(false, |o| o.is_some()) =>
1052 .collect::<Vec<_>>();
1053 if !error_codes.is_empty() {
1055 if error_codes.len() > 1 {
1056 let limit = if error_codes.len() > 9 { 9 } else { error_codes.len() };
1057 self.failure(&format!(
1058 "Some errors have detailed explanations: {}{}",
1059 error_codes[..limit].join(", "),
1060 if error_codes.len() > 9 { "..." } else { "." }
1062 self.failure(&format!(
1063 "For more information about an error, try \
1064 `rustc --explain {}`.",
1068 self.failure(&format!(
1069 "For more information about this error, try \
1070 `rustc --explain {}`.",
1079 fn err_count(&self) -> usize {
1080 self.err_count + self.stashed_diagnostics.len()
1083 fn has_errors(&self) -> bool {
1084 self.err_count() > 0
1086 fn has_errors_or_lint_errors(&self) -> bool {
1087 self.has_errors() || self.lint_err_count > 0
1089 fn has_errors_or_delayed_span_bugs(&self) -> bool {
1090 self.has_errors() || !self.delayed_span_bugs.is_empty()
1092 fn has_any_message(&self) -> bool {
1093 self.err_count() > 0 || self.lint_err_count > 0 || self.warn_count > 0
1096 fn abort_if_errors(&mut self) {
1097 self.emit_stashed_diagnostics();
1099 if self.has_errors() {
1104 fn span_bug(&mut self, sp: impl Into<MultiSpan>, msg: &str) -> ! {
1105 self.emit_diag_at_span(Diagnostic::new(Bug, msg), sp);
1106 panic::panic_any(ExplicitBug);
1109 fn emit_diag_at_span(&mut self, mut diag: Diagnostic, sp: impl Into<MultiSpan>) {
1110 self.emit_diagnostic(diag.set_span(sp));
1114 fn delay_span_bug(&mut self, sp: impl Into<MultiSpan>, msg: &str) {
1115 // This is technically `self.treat_err_as_bug()` but `delay_span_bug` is called before
1116 // incrementing `err_count` by one, so we need to +1 the comparing.
1117 // FIXME: Would be nice to increment err_count in a more coherent way.
1118 if self.flags.treat_err_as_bug.map_or(false, |c| self.err_count() + 1 >= c.get()) {
1119 // FIXME: don't abort here if report_delayed_bugs is off
1120 self.span_bug(sp, msg);
1122 let mut diagnostic = Diagnostic::new(Level::Bug, msg);
1123 diagnostic.set_span(sp.into());
1124 diagnostic.note(&format!("delayed at {}", std::panic::Location::caller()));
1125 self.delay_as_bug(diagnostic)
1128 fn delay_good_path_bug(&mut self, msg: &str) {
1129 let diagnostic = Diagnostic::new(Level::Bug, msg);
1130 if self.flags.report_delayed_bugs {
1131 self.emit_diagnostic(&diagnostic);
1133 let backtrace = std::backtrace::Backtrace::force_capture();
1134 self.delayed_good_path_bugs.push(DelayedDiagnostic::with_backtrace(diagnostic, backtrace));
1137 fn failure(&mut self, msg: &str) {
1138 self.emit_diagnostic(&Diagnostic::new(FailureNote, msg));
1141 fn fatal(&mut self, msg: &str) -> FatalError {
1142 self.emit_error(Fatal, msg);
1146 fn err(&mut self, msg: &str) {
1147 self.emit_error(Error { lint: false }, msg);
1150 /// Emit an error; level should be `Error` or `Fatal`.
1151 fn emit_error(&mut self, level: Level, msg: &str) {
1152 if self.treat_err_as_bug() {
1155 self.emit_diagnostic(&Diagnostic::new(level, msg));
1158 fn bug(&mut self, msg: &str) -> ! {
1159 self.emit_diagnostic(&Diagnostic::new(Bug, msg));
1160 panic::panic_any(ExplicitBug);
1163 fn delay_as_bug(&mut self, diagnostic: Diagnostic) {
1164 if self.flags.report_delayed_bugs {
1165 self.emit_diagnostic(&diagnostic);
1167 self.delayed_span_bugs.push(diagnostic);
1170 fn flush_delayed(&mut self, bugs: Vec<Diagnostic>, explanation: &str) {
1171 let has_bugs = !bugs.is_empty();
1173 self.emit_diagnostic(&bug);
1176 panic!("{}", explanation);
1180 fn bump_lint_err_count(&mut self) {
1181 self.lint_err_count += 1;
1182 self.panic_if_treat_err_as_bug();
1185 fn bump_err_count(&mut self) {
1186 self.err_count += 1;
1187 self.panic_if_treat_err_as_bug();
1190 fn bump_warn_count(&mut self) {
1191 self.warn_count += 1;
1194 fn panic_if_treat_err_as_bug(&self) {
1195 if self.treat_err_as_bug() {
1197 self.err_count() + self.lint_err_count,
1198 self.flags.treat_err_as_bug.map(|c| c.get()).unwrap_or(0),
1200 (1, 1) => panic!("aborting due to `-Z treat-err-as-bug=1`"),
1201 (0, _) | (1, _) => {}
1202 (count, as_bug) => panic!(
1203 "aborting after {} errors due to `-Z treat-err-as-bug={}`",
1211 struct DelayedDiagnostic {
1216 impl DelayedDiagnostic {
1217 fn with_backtrace(diagnostic: Diagnostic, backtrace: Backtrace) -> Self {
1218 DelayedDiagnostic { inner: diagnostic, note: backtrace }
1221 fn decorate(mut self) -> Diagnostic {
1222 self.inner.note(&format!("delayed at {}", self.note));
1227 #[derive(Copy, PartialEq, Clone, Hash, Debug, Encodable, Decodable)]
1232 /// If this error comes from a lint, don't abort compilation even when abort_if_errors() is called.
1243 impl fmt::Display for Level {
1244 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1245 self.to_str().fmt(f)
1250 fn color(self) -> ColorSpec {
1251 let mut spec = ColorSpec::new();
1253 Bug | Fatal | Error { .. } => {
1254 spec.set_fg(Some(Color::Red)).set_intense(true);
1257 spec.set_fg(Some(Color::Yellow)).set_intense(cfg!(windows));
1260 spec.set_fg(Some(Color::Green)).set_intense(true);
1263 spec.set_fg(Some(Color::Cyan)).set_intense(true);
1266 Allow | Cancelled => unreachable!(),
1271 pub fn to_str(self) -> &'static str {
1273 Bug => "error: internal compiler error",
1274 Fatal | Error { .. } => "error",
1275 Warning => "warning",
1278 FailureNote => "failure-note",
1279 Cancelled => panic!("Shouldn't call on cancelled error"),
1280 Allow => panic!("Shouldn't call on allowed error"),
1284 pub fn is_failure_note(&self) -> bool {
1285 matches!(*self, FailureNote)
1289 pub fn add_elided_lifetime_in_path_suggestion(
1290 source_map: &SourceMap,
1291 db: &mut DiagnosticBuilder<'_>,
1294 incl_angl_brckt: bool,
1295 insertion_span: Span,
1298 let (replace_span, suggestion) = if incl_angl_brckt {
1299 (insertion_span, anon_lts)
1301 // When possible, prefer a suggestion that replaces the whole
1302 // `Path<T>` expression with `Path<'_, T>`, rather than inserting `'_, `
1303 // at a point (which makes for an ugly/confusing label)
1304 if let Ok(snippet) = source_map.span_to_snippet(path_span) {
1305 // But our spans can get out of whack due to macros; if the place we think
1306 // we want to insert `'_` isn't even within the path expression's span, we
1307 // should bail out of making any suggestion rather than panicking on a
1308 // subtract-with-overflow or string-slice-out-out-bounds (!)
1309 // FIXME: can we do better?
1310 if insertion_span.lo().0 < path_span.lo().0 {
1313 let insertion_index = (insertion_span.lo().0 - path_span.lo().0) as usize;
1314 if insertion_index > snippet.len() {
1317 let (before, after) = snippet.split_at(insertion_index);
1318 (path_span, format!("{}{}{}", before, anon_lts, after))
1320 (insertion_span, anon_lts)
1325 &format!("indicate the anonymous lifetime{}", pluralize!(n)),
1327 Applicability::MachineApplicable,
1331 // Useful type to use with `Result<>` indicate that an error has already
1332 // been reported to the user, so no need to continue checking.
1333 #[derive(Clone, Copy, Debug, Encodable, Decodable, Hash, PartialEq, Eq)]
1334 pub struct ErrorReported;
1336 rustc_data_structures::impl_stable_hash_via_hash!(ErrorReported);