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)]
11 extern crate rustc_macros;
13 pub use emitter::ColorConfig;
18 use emitter::{is_case_difference, Emitter, EmitterWriter};
19 use registry::Registry;
20 use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
21 use rustc_data_structures::stable_hasher::StableHasher;
22 use rustc_data_structures::sync::{self, Lock, Lrc};
23 use rustc_data_structures::AtomicRef;
24 use rustc_lint_defs::FutureBreakage;
25 pub use rustc_lint_defs::{pluralize, Applicability};
26 use rustc_serialize::json::Json;
27 use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
28 use rustc_span::source_map::SourceMap;
29 use rustc_span::{Loc, MultiSpan, Span};
32 use std::hash::{Hash, Hasher};
33 use std::num::NonZeroUsize;
36 use std::{error, fmt};
38 use termcolor::{Color, ColorSpec};
40 pub mod annotate_snippet_emitter_writer;
42 mod diagnostic_builder;
49 pub use snippet::Style;
51 pub type PResult<'a, T> = Result<T, DiagnosticBuilder<'a>>;
53 // `PResult` is used a lot. Make sure it doesn't unintentionally get bigger.
54 // (See also the comment on `DiagnosticBuilderInner`.)
55 #[cfg(target_arch = "x86_64")]
56 rustc_data_structures::static_assert_size!(PResult<'_, bool>, 16);
58 #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, Encodable, Decodable)]
59 pub enum SuggestionStyle {
60 /// Hide the suggested code when displaying this suggestion inline.
62 /// Always hide the suggested code but display the message.
64 /// Do not display this suggestion in the cli output, it is only meant for tools.
66 /// Always show the suggested code.
67 /// This will *not* show the code if the suggestion is inline *and* the suggested code is
70 /// Always show the suggested code independently.
74 impl SuggestionStyle {
75 fn hide_inline(&self) -> bool {
76 !matches!(*self, SuggestionStyle::ShowCode)
80 #[derive(Clone, Debug, PartialEq, Default)]
81 pub struct ToolMetadata(pub Option<Json>);
84 fn new(json: Json) -> Self {
85 ToolMetadata(Some(json))
88 fn is_set(&self) -> bool {
93 impl Hash for ToolMetadata {
94 fn hash<H: Hasher>(&self, _state: &mut H) {}
97 // Doesn't really need to round-trip
98 impl<D: Decoder> Decodable<D> for ToolMetadata {
99 fn decode(_d: &mut D) -> Result<Self, D::Error> {
100 Ok(ToolMetadata(None))
104 impl<S: Encoder> Encodable<S> for ToolMetadata {
105 fn encode(&self, e: &mut S) -> Result<(), S::Error> {
107 None => e.emit_unit(),
108 Some(json) => json.encode(e),
113 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
114 pub struct CodeSuggestion {
115 /// Each substitute can have multiple variants due to multiple
116 /// applicable suggestions
118 /// `foo.bar` might be replaced with `a.b` or `x.y` by replacing
119 /// `foo` and `bar` on their own:
123 /// Substitution { parts: vec![(0..3, "a"), (4..7, "b")] },
124 /// Substitution { parts: vec![(0..3, "x"), (4..7, "y")] },
128 /// or by replacing the entire span:
132 /// Substitution { parts: vec![(0..7, "a.b")] },
133 /// Substitution { parts: vec![(0..7, "x.y")] },
136 pub substitutions: Vec<Substitution>,
138 /// Visual representation of this suggestion.
139 pub style: SuggestionStyle,
140 /// Whether or not the suggestion is approximate
142 /// Sometimes we may show suggestions with placeholders,
143 /// which are useful for users but not useful for
144 /// tools like rustfix
145 pub applicability: Applicability,
146 /// Tool-specific metadata
147 pub tool_metadata: ToolMetadata,
150 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
151 /// See the docs on `CodeSuggestion::substitutions`
152 pub struct Substitution {
153 pub parts: Vec<SubstitutionPart>,
156 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
157 pub struct SubstitutionPart {
162 impl CodeSuggestion {
163 /// Returns the assembled code suggestions, whether they should be shown with an underline
164 /// and whether the substitution only differs in capitalization.
165 pub fn splice_lines(&self, sm: &SourceMap) -> Vec<(String, Vec<SubstitutionPart>, bool)> {
166 use rustc_span::{CharPos, Pos};
170 line_opt: Option<&Cow<'_, str>>,
172 hi_opt: Option<&Loc>,
174 let (lo, hi_opt) = (lo.col.to_usize(), hi_opt.map(|hi| hi.col.to_usize()));
175 if let Some(line) = line_opt {
176 if let Some(lo) = line.char_indices().map(|(i, _)| i).nth(lo) {
177 let hi_opt = hi_opt.and_then(|hi| line.char_indices().map(|(i, _)| i).nth(hi));
179 Some(hi) if hi > lo => buf.push_str(&line[lo..hi]),
181 None => buf.push_str(&line[lo..]),
184 if hi_opt.is_none() {
190 assert!(!self.substitutions.is_empty());
195 // Suggestions coming from macros can have malformed spans. This is a heavy
196 // handed approach to avoid ICEs by ignoring the suggestion outright.
197 let invalid = subst.parts.iter().any(|item| sm.is_valid_span(item.span).is_err());
199 debug!("splice_lines: suggestion contains an invalid span: {:?}", subst);
204 .filter_map(|mut substitution| {
205 // Assumption: all spans are in the same file, and all spans
206 // are disjoint. Sort in ascending order.
207 substitution.parts.sort_by_key(|part| part.span.lo());
209 // Find the bounding span.
210 let lo = substitution.parts.iter().map(|part| part.span.lo()).min()?;
211 let hi = substitution.parts.iter().map(|part| part.span.hi()).max()?;
212 let bounding_span = Span::with_root_ctxt(lo, hi);
213 // The different spans might belong to different contexts, if so ignore suggestion.
214 let lines = sm.span_to_lines(bounding_span).ok()?;
215 assert!(!lines.lines.is_empty() || bounding_span.is_dummy());
217 // We can't splice anything if the source is unavailable.
218 if !sm.ensure_source_file_source_present(lines.file.clone()) {
222 // To build up the result, we do this for each span:
223 // - push the line segment trailing the previous span
224 // (at the beginning a "phantom" span pointing at the start of the line)
225 // - push lines between the previous and current span (if any)
226 // - if the previous and current span are not on the same line
227 // push the line segment leading up to the current span
228 // - splice in the span substitution
230 // Finally push the trailing line segment of the last span
231 let sf = &lines.file;
232 let mut prev_hi = sm.lookup_char_pos(bounding_span.lo());
233 prev_hi.col = CharPos::from_usize(0);
235 lines.lines.get(0).and_then(|line0| sf.get_line(line0.line_index));
236 let mut buf = String::new();
238 for part in &substitution.parts {
239 let cur_lo = sm.lookup_char_pos(part.span.lo());
240 if prev_hi.line == cur_lo.line {
241 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, Some(&cur_lo));
243 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
244 // push lines between the previous and current span (if any)
245 for idx in prev_hi.line..(cur_lo.line - 1) {
246 if let Some(line) = sf.get_line(idx) {
247 buf.push_str(line.as_ref());
251 if let Some(cur_line) = sf.get_line(cur_lo.line - 1) {
252 let end = match cur_line.char_indices().nth(cur_lo.col.to_usize()) {
254 None => cur_line.len(),
256 buf.push_str(&cur_line[..end]);
259 buf.push_str(&part.snippet);
260 prev_hi = sm.lookup_char_pos(part.span.hi());
261 prev_line = sf.get_line(prev_hi.line - 1);
263 let only_capitalization = is_case_difference(sm, &buf, bounding_span);
264 // if the replacement already ends with a newline, don't print the next line
265 if !buf.ends_with('\n') {
266 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
268 // remove trailing newlines
269 while buf.ends_with('\n') {
272 Some((buf, substitution.parts, only_capitalization))
278 pub use rustc_span::fatal_error::{FatalError, FatalErrorMarker};
280 /// Signifies that the compiler died with an explicit call to `.bug`
281 /// or `.span_bug` rather than a failed assertion, etc.
282 #[derive(Copy, Clone, Debug)]
283 pub struct ExplicitBug;
285 impl fmt::Display for ExplicitBug {
286 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
287 write!(f, "parser internal bug")
291 impl error::Error for ExplicitBug {}
293 pub use diagnostic::{Diagnostic, DiagnosticId, DiagnosticStyledString, SubDiagnostic};
294 pub use diagnostic_builder::DiagnosticBuilder;
296 /// A handler deals with errors and other compiler output.
297 /// Certain errors (fatal, bug, unimpl) may cause immediate exit,
298 /// others log errors for later reporting.
301 inner: Lock<HandlerInner>,
304 /// This inner struct exists to keep it all behind a single lock;
305 /// this is done to prevent possible deadlocks in a multi-threaded compiler,
306 /// as well as inconsistent state observation.
307 struct HandlerInner {
309 /// The number of errors that have been emitted, including duplicates.
311 /// This is not necessarily the count that's reported to the user once
312 /// compilation ends.
315 deduplicated_err_count: usize,
316 emitter: Box<dyn Emitter + sync::Send>,
317 delayed_span_bugs: Vec<Diagnostic>,
318 delayed_good_path_bugs: Vec<Diagnostic>,
320 /// This set contains the `DiagnosticId` of all emitted diagnostics to avoid
321 /// emitting the same diagnostic with extended help (`--teach`) twice, which
322 /// would be uneccessary repetition.
323 taught_diagnostics: FxHashSet<DiagnosticId>,
325 /// Used to suggest rustc --explain <error code>
326 emitted_diagnostic_codes: FxHashSet<DiagnosticId>,
328 /// This set contains a hash of every diagnostic that has been emitted by
329 /// this handler. These hashes is used to avoid emitting the same error
331 emitted_diagnostics: FxHashSet<u128>,
333 /// Stashed diagnostics emitted in one stage of the compiler that may be
334 /// stolen by other stages (e.g. to improve them and add more information).
335 /// The stashed diagnostics count towards the total error count.
336 /// When `.abort_if_errors()` is called, these are also emitted.
337 stashed_diagnostics: FxIndexMap<(Span, StashKey), Diagnostic>,
339 /// The warning count, used for a recap upon finishing
340 deduplicated_warn_count: usize,
342 future_breakage_diagnostics: Vec<Diagnostic>,
345 /// A key denoting where from a diagnostic was stashed.
346 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
351 fn default_track_diagnostic(_: &Diagnostic) {}
353 pub static TRACK_DIAGNOSTICS: AtomicRef<fn(&Diagnostic)> =
354 AtomicRef::new(&(default_track_diagnostic as fn(&_)));
356 #[derive(Copy, Clone, Default)]
357 pub struct HandlerFlags {
358 /// If false, warning-level lints are suppressed.
359 /// (rustc: see `--allow warnings` and `--cap-lints`)
360 pub can_emit_warnings: bool,
361 /// If true, error-level diagnostics are upgraded to bug-level.
362 /// (rustc: see `-Z treat-err-as-bug`)
363 pub treat_err_as_bug: Option<NonZeroUsize>,
364 /// If true, immediately emit diagnostics that would otherwise be buffered.
365 /// (rustc: see `-Z dont-buffer-diagnostics` and `-Z treat-err-as-bug`)
366 pub dont_buffer_diagnostics: bool,
367 /// If true, immediately print bugs registered with `delay_span_bug`.
368 /// (rustc: see `-Z report-delayed-bugs`)
369 pub report_delayed_bugs: bool,
370 /// Show macro backtraces.
371 /// (rustc: see `-Z macro-backtrace`)
372 pub macro_backtrace: bool,
373 /// If true, identical diagnostics are reported only once.
374 pub deduplicate_diagnostics: bool,
377 impl Drop for HandlerInner {
379 self.emit_stashed_diagnostics();
381 if !self.has_errors() {
382 let bugs = std::mem::replace(&mut self.delayed_span_bugs, Vec::new());
383 self.flush_delayed(bugs, "no errors encountered even though `delay_span_bug` issued");
386 if !self.has_any_message() {
387 let bugs = std::mem::replace(&mut self.delayed_good_path_bugs, Vec::new());
390 "no warnings or errors encountered even though `delayed_good_path_bugs` issued",
397 pub fn with_tty_emitter(
398 color_config: ColorConfig,
399 can_emit_warnings: bool,
400 treat_err_as_bug: Option<NonZeroUsize>,
401 sm: Option<Lrc<SourceMap>>,
403 Self::with_tty_emitter_and_flags(
406 HandlerFlags { can_emit_warnings, treat_err_as_bug, ..Default::default() },
410 pub fn with_tty_emitter_and_flags(
411 color_config: ColorConfig,
412 sm: Option<Lrc<SourceMap>>,
415 let emitter = Box::new(EmitterWriter::stderr(
421 flags.macro_backtrace,
423 Self::with_emitter_and_flags(emitter, flags)
427 can_emit_warnings: bool,
428 treat_err_as_bug: Option<NonZeroUsize>,
429 emitter: Box<dyn Emitter + sync::Send>,
431 Handler::with_emitter_and_flags(
433 HandlerFlags { can_emit_warnings, treat_err_as_bug, ..Default::default() },
437 pub fn with_emitter_and_flags(
438 emitter: Box<dyn Emitter + sync::Send>,
443 inner: Lock::new(HandlerInner {
447 deduplicated_err_count: 0,
448 deduplicated_warn_count: 0,
450 delayed_span_bugs: Vec::new(),
451 delayed_good_path_bugs: Vec::new(),
452 taught_diagnostics: Default::default(),
453 emitted_diagnostic_codes: Default::default(),
454 emitted_diagnostics: Default::default(),
455 stashed_diagnostics: Default::default(),
456 future_breakage_diagnostics: Vec::new(),
461 // This is here to not allow mutation of flags;
462 // as of this writing it's only used in tests in librustc_middle.
463 pub fn can_emit_warnings(&self) -> bool {
464 self.flags.can_emit_warnings
467 /// Resets the diagnostic error count as well as the cached emitted diagnostics.
469 /// NOTE: *do not* call this function from rustc. It is only meant to be called from external
470 /// tools that want to reuse a `Parser` cleaning the previously emitted diagnostics as well as
471 /// the overall count of emitted error diagnostics.
472 pub fn reset_err_count(&self) {
473 let mut inner = self.inner.borrow_mut();
475 inner.warn_count = 0;
476 inner.deduplicated_err_count = 0;
477 inner.deduplicated_warn_count = 0;
479 // actually free the underlying memory (which `clear` would not do)
480 inner.delayed_span_bugs = Default::default();
481 inner.delayed_good_path_bugs = Default::default();
482 inner.taught_diagnostics = Default::default();
483 inner.emitted_diagnostic_codes = Default::default();
484 inner.emitted_diagnostics = Default::default();
485 inner.stashed_diagnostics = Default::default();
488 /// Stash a given diagnostic with the given `Span` and `StashKey` as the key for later stealing.
489 pub fn stash_diagnostic(&self, span: Span, key: StashKey, diag: Diagnostic) {
490 let mut inner = self.inner.borrow_mut();
491 // FIXME(Centril, #69537): Consider reintroducing panic on overwriting a stashed diagnostic
492 // if/when we have a more robust macro-friendly replacement for `(span, key)` as a key.
493 // See the PR for a discussion.
494 inner.stashed_diagnostics.insert((span, key), diag);
497 /// Steal a previously stashed diagnostic with the given `Span` and `StashKey` as the key.
498 pub fn steal_diagnostic(&self, span: Span, key: StashKey) -> Option<DiagnosticBuilder<'_>> {
502 .remove(&(span, key))
503 .map(|diag| DiagnosticBuilder::new_diagnostic(self, diag))
506 /// Emit all stashed diagnostics.
507 pub fn emit_stashed_diagnostics(&self) {
508 self.inner.borrow_mut().emit_stashed_diagnostics();
511 /// Construct a dummy builder with `Level::Cancelled`.
513 /// Using this will neither report anything to the user (e.g. a warning),
514 /// nor will compilation cancel as a result.
515 pub fn struct_dummy(&self) -> DiagnosticBuilder<'_> {
516 DiagnosticBuilder::new(self, Level::Cancelled, "")
519 /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
520 pub fn struct_span_warn(&self, span: impl Into<MultiSpan>, msg: &str) -> DiagnosticBuilder<'_> {
521 let mut result = self.struct_warn(msg);
522 result.set_span(span);
526 /// Construct a builder at the `Allow` level at the given `span` and with the `msg`.
527 pub fn struct_span_allow(
529 span: impl Into<MultiSpan>,
531 ) -> DiagnosticBuilder<'_> {
532 let mut result = self.struct_allow(msg);
533 result.set_span(span);
537 /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
538 /// Also include a code.
539 pub fn struct_span_warn_with_code(
541 span: impl Into<MultiSpan>,
544 ) -> DiagnosticBuilder<'_> {
545 let mut result = self.struct_span_warn(span, msg);
550 /// Construct a builder at the `Warning` level with the `msg`.
551 pub fn struct_warn(&self, msg: &str) -> DiagnosticBuilder<'_> {
552 let mut result = DiagnosticBuilder::new(self, Level::Warning, msg);
553 if !self.flags.can_emit_warnings {
559 /// Construct a builder at the `Allow` level with the `msg`.
560 pub fn struct_allow(&self, msg: &str) -> DiagnosticBuilder<'_> {
561 DiagnosticBuilder::new(self, Level::Allow, msg)
564 /// Construct a builder at the `Error` level at the given `span` and with the `msg`.
565 pub fn struct_span_err(&self, span: impl Into<MultiSpan>, msg: &str) -> DiagnosticBuilder<'_> {
566 let mut result = self.struct_err(msg);
567 result.set_span(span);
571 /// Construct a builder at the `Error` level at the given `span`, with the `msg`, and `code`.
572 pub fn struct_span_err_with_code(
574 span: impl Into<MultiSpan>,
577 ) -> DiagnosticBuilder<'_> {
578 let mut result = self.struct_span_err(span, msg);
583 /// Construct a builder at the `Error` level with the `msg`.
584 // FIXME: This method should be removed (every error should have an associated error code).
585 pub fn struct_err(&self, msg: &str) -> DiagnosticBuilder<'_> {
586 DiagnosticBuilder::new(self, Level::Error, msg)
589 /// Construct a builder at the `Error` level with the `msg` and the `code`.
590 pub fn struct_err_with_code(&self, msg: &str, code: DiagnosticId) -> DiagnosticBuilder<'_> {
591 let mut result = self.struct_err(msg);
596 /// Construct a builder at the `Fatal` level at the given `span` and with the `msg`.
597 pub fn struct_span_fatal(
599 span: impl Into<MultiSpan>,
601 ) -> DiagnosticBuilder<'_> {
602 let mut result = self.struct_fatal(msg);
603 result.set_span(span);
607 /// Construct a builder at the `Fatal` level at the given `span`, with the `msg`, and `code`.
608 pub fn struct_span_fatal_with_code(
610 span: impl Into<MultiSpan>,
613 ) -> DiagnosticBuilder<'_> {
614 let mut result = self.struct_span_fatal(span, msg);
619 /// Construct a builder at the `Error` level with the `msg`.
620 pub fn struct_fatal(&self, msg: &str) -> DiagnosticBuilder<'_> {
621 DiagnosticBuilder::new(self, Level::Fatal, msg)
624 /// Construct a builder at the `Help` level with the `msg`.
625 pub fn struct_help(&self, msg: &str) -> DiagnosticBuilder<'_> {
626 DiagnosticBuilder::new(self, Level::Help, msg)
629 /// Construct a builder at the `Note` level with the `msg`.
630 pub fn struct_note_without_error(&self, msg: &str) -> DiagnosticBuilder<'_> {
631 DiagnosticBuilder::new(self, Level::Note, msg)
634 pub fn span_fatal(&self, span: impl Into<MultiSpan>, msg: &str) -> FatalError {
635 self.emit_diag_at_span(Diagnostic::new(Fatal, msg), span);
639 pub fn span_fatal_with_code(
641 span: impl Into<MultiSpan>,
645 self.emit_diag_at_span(Diagnostic::new_with_code(Fatal, Some(code), msg), span);
649 pub fn span_err(&self, span: impl Into<MultiSpan>, msg: &str) {
650 self.emit_diag_at_span(Diagnostic::new(Error, msg), span);
653 pub fn span_err_with_code(&self, span: impl Into<MultiSpan>, msg: &str, code: DiagnosticId) {
654 self.emit_diag_at_span(Diagnostic::new_with_code(Error, Some(code), msg), span);
657 pub fn span_warn(&self, span: impl Into<MultiSpan>, msg: &str) {
658 self.emit_diag_at_span(Diagnostic::new(Warning, msg), span);
661 pub fn span_warn_with_code(&self, span: impl Into<MultiSpan>, msg: &str, code: DiagnosticId) {
662 self.emit_diag_at_span(Diagnostic::new_with_code(Warning, Some(code), msg), span);
665 pub fn span_bug(&self, span: impl Into<MultiSpan>, msg: &str) -> ! {
666 self.inner.borrow_mut().span_bug(span, msg)
670 pub fn delay_span_bug(&self, span: impl Into<MultiSpan>, msg: &str) {
671 self.inner.borrow_mut().delay_span_bug(span, msg)
674 pub fn delay_good_path_bug(&self, msg: &str) {
675 self.inner.borrow_mut().delay_good_path_bug(msg)
678 pub fn span_bug_no_panic(&self, span: impl Into<MultiSpan>, msg: &str) {
679 self.emit_diag_at_span(Diagnostic::new(Bug, msg), span);
682 pub fn span_note_without_error(&self, span: impl Into<MultiSpan>, msg: &str) {
683 self.emit_diag_at_span(Diagnostic::new(Note, msg), span);
686 pub fn span_note_diag(&self, span: Span, msg: &str) -> DiagnosticBuilder<'_> {
687 let mut db = DiagnosticBuilder::new(self, Note, msg);
692 pub fn failure(&self, msg: &str) {
693 self.inner.borrow_mut().failure(msg);
696 pub fn fatal(&self, msg: &str) -> FatalError {
697 self.inner.borrow_mut().fatal(msg)
700 pub fn err(&self, msg: &str) {
701 self.inner.borrow_mut().err(msg);
704 pub fn warn(&self, msg: &str) {
705 let mut db = DiagnosticBuilder::new(self, Warning, msg);
709 pub fn note_without_error(&self, msg: &str) {
710 DiagnosticBuilder::new(self, Note, msg).emit();
713 pub fn bug(&self, msg: &str) -> ! {
714 self.inner.borrow_mut().bug(msg)
717 pub fn err_count(&self) -> usize {
718 self.inner.borrow().err_count()
721 pub fn has_errors(&self) -> bool {
722 self.inner.borrow().has_errors()
724 pub fn has_errors_or_delayed_span_bugs(&self) -> bool {
725 self.inner.borrow().has_errors_or_delayed_span_bugs()
728 pub fn print_error_count(&self, registry: &Registry) {
729 self.inner.borrow_mut().print_error_count(registry)
732 pub fn take_future_breakage_diagnostics(&self) -> Vec<Diagnostic> {
733 std::mem::take(&mut self.inner.borrow_mut().future_breakage_diagnostics)
736 pub fn abort_if_errors(&self) {
737 self.inner.borrow_mut().abort_if_errors()
740 /// `true` if we haven't taught a diagnostic with this code already.
741 /// The caller must then teach the user about such a diagnostic.
743 /// Used to suppress emitting the same error multiple times with extended explanation when
744 /// calling `-Zteach`.
745 pub fn must_teach(&self, code: &DiagnosticId) -> bool {
746 self.inner.borrow_mut().must_teach(code)
749 pub fn force_print_diagnostic(&self, db: Diagnostic) {
750 self.inner.borrow_mut().force_print_diagnostic(db)
753 pub fn emit_diagnostic(&self, diagnostic: &Diagnostic) {
754 self.inner.borrow_mut().emit_diagnostic(diagnostic)
757 fn emit_diag_at_span(&self, mut diag: Diagnostic, sp: impl Into<MultiSpan>) {
758 let mut inner = self.inner.borrow_mut();
759 inner.emit_diagnostic(diag.set_span(sp));
762 pub fn emit_artifact_notification(&self, path: &Path, artifact_type: &str) {
763 self.inner.borrow_mut().emit_artifact_notification(path, artifact_type)
766 pub fn emit_future_breakage_report(&self, diags: Vec<(FutureBreakage, Diagnostic)>) {
767 self.inner.borrow_mut().emitter.emit_future_breakage_report(diags)
770 pub fn delay_as_bug(&self, diagnostic: Diagnostic) {
771 self.inner.borrow_mut().delay_as_bug(diagnostic)
776 fn must_teach(&mut self, code: &DiagnosticId) -> bool {
777 self.taught_diagnostics.insert(code.clone())
780 fn force_print_diagnostic(&mut self, db: Diagnostic) {
781 self.emitter.emit_diagnostic(&db);
784 /// Emit all stashed diagnostics.
785 fn emit_stashed_diagnostics(&mut self) {
786 let diags = self.stashed_diagnostics.drain(..).map(|x| x.1).collect::<Vec<_>>();
787 diags.iter().for_each(|diag| self.emit_diagnostic(diag));
790 fn emit_diagnostic(&mut self, diagnostic: &Diagnostic) {
791 if diagnostic.cancelled() {
795 if diagnostic.has_future_breakage() {
796 self.future_breakage_diagnostics.push(diagnostic.clone());
799 if diagnostic.level == Warning && !self.flags.can_emit_warnings {
800 if diagnostic.has_future_breakage() {
801 (*TRACK_DIAGNOSTICS)(diagnostic);
806 (*TRACK_DIAGNOSTICS)(diagnostic);
808 if diagnostic.level == Allow {
812 if let Some(ref code) = diagnostic.code {
813 self.emitted_diagnostic_codes.insert(code.clone());
816 let already_emitted = |this: &mut Self| {
817 let mut hasher = StableHasher::new();
818 diagnostic.hash(&mut hasher);
819 let diagnostic_hash = hasher.finish();
820 !this.emitted_diagnostics.insert(diagnostic_hash)
823 // Only emit the diagnostic if we've been asked to deduplicate and
824 // haven't already emitted an equivalent diagnostic.
825 if !(self.flags.deduplicate_diagnostics && already_emitted(self)) {
826 self.emitter.emit_diagnostic(diagnostic);
827 if diagnostic.is_error() {
828 self.deduplicated_err_count += 1;
829 } else if diagnostic.level == Warning {
830 self.deduplicated_warn_count += 1;
833 if diagnostic.is_error() {
834 self.bump_err_count();
836 self.bump_warn_count();
840 fn emit_artifact_notification(&mut self, path: &Path, artifact_type: &str) {
841 self.emitter.emit_artifact_notification(path, artifact_type);
844 fn treat_err_as_bug(&self) -> bool {
845 self.flags.treat_err_as_bug.map_or(false, |c| self.err_count() >= c.get())
848 fn print_error_count(&mut self, registry: &Registry) {
849 self.emit_stashed_diagnostics();
851 let warnings = match self.deduplicated_warn_count {
853 1 => "1 warning emitted".to_string(),
854 count => format!("{} warnings emitted", count),
856 let errors = match self.deduplicated_err_count {
858 1 => "aborting due to previous error".to_string(),
859 count => format!("aborting due to {} previous errors", count),
861 if self.treat_err_as_bug() {
865 match (errors.len(), warnings.len()) {
867 (0, _) => self.emit_diagnostic(&Diagnostic::new(Level::Warning, &warnings)),
869 let _ = self.fatal(&errors);
872 let _ = self.fatal(&format!("{}; {}", &errors, &warnings));
876 let can_show_explain = self.emitter.should_show_explain();
877 let are_there_diagnostics = !self.emitted_diagnostic_codes.is_empty();
878 if can_show_explain && are_there_diagnostics {
879 let mut error_codes = self
880 .emitted_diagnostic_codes
882 .filter_map(|x| match &x {
883 DiagnosticId::Error(s) => {
884 if let Ok(Some(_explanation)) = registry.try_find_description(s) {
892 .collect::<Vec<_>>();
893 if !error_codes.is_empty() {
895 if error_codes.len() > 1 {
896 let limit = if error_codes.len() > 9 { 9 } else { error_codes.len() };
897 self.failure(&format!(
898 "Some errors have detailed explanations: {}{}",
899 error_codes[..limit].join(", "),
900 if error_codes.len() > 9 { "..." } else { "." }
902 self.failure(&format!(
903 "For more information about an error, try \
904 `rustc --explain {}`.",
908 self.failure(&format!(
909 "For more information about this error, try \
910 `rustc --explain {}`.",
918 fn err_count(&self) -> usize {
919 self.err_count + self.stashed_diagnostics.len()
922 fn has_errors(&self) -> bool {
925 fn has_errors_or_delayed_span_bugs(&self) -> bool {
926 self.has_errors() || !self.delayed_span_bugs.is_empty()
928 fn has_any_message(&self) -> bool {
929 self.err_count() > 0 || self.warn_count > 0
932 fn abort_if_errors(&mut self) {
933 self.emit_stashed_diagnostics();
935 if self.has_errors() {
940 fn span_bug(&mut self, sp: impl Into<MultiSpan>, msg: &str) -> ! {
941 self.emit_diag_at_span(Diagnostic::new(Bug, msg), sp);
942 panic::panic_any(ExplicitBug);
945 fn emit_diag_at_span(&mut self, mut diag: Diagnostic, sp: impl Into<MultiSpan>) {
946 self.emit_diagnostic(diag.set_span(sp));
950 fn delay_span_bug(&mut self, sp: impl Into<MultiSpan>, msg: &str) {
951 // This is technically `self.treat_err_as_bug()` but `delay_span_bug` is called before
952 // incrementing `err_count` by one, so we need to +1 the comparing.
953 // FIXME: Would be nice to increment err_count in a more coherent way.
954 if self.flags.treat_err_as_bug.map_or(false, |c| self.err_count() + 1 >= c.get()) {
955 // FIXME: don't abort here if report_delayed_bugs is off
956 self.span_bug(sp, msg);
958 let mut diagnostic = Diagnostic::new(Level::Bug, msg);
959 diagnostic.set_span(sp.into());
960 diagnostic.note(&format!("delayed at {}", std::panic::Location::caller()));
961 self.delay_as_bug(diagnostic)
964 fn delay_good_path_bug(&mut self, msg: &str) {
965 let mut diagnostic = Diagnostic::new(Level::Bug, msg);
966 if self.flags.report_delayed_bugs {
967 self.emit_diagnostic(&diagnostic);
969 diagnostic.note(&format!("delayed at {}", std::backtrace::Backtrace::force_capture()));
970 self.delayed_good_path_bugs.push(diagnostic);
973 fn failure(&mut self, msg: &str) {
974 self.emit_diagnostic(&Diagnostic::new(FailureNote, msg));
977 fn fatal(&mut self, msg: &str) -> FatalError {
978 self.emit_error(Fatal, msg);
982 fn err(&mut self, msg: &str) {
983 self.emit_error(Error, msg);
986 /// Emit an error; level should be `Error` or `Fatal`.
987 fn emit_error(&mut self, level: Level, msg: &str) {
988 if self.treat_err_as_bug() {
991 self.emit_diagnostic(&Diagnostic::new(level, msg));
994 fn bug(&mut self, msg: &str) -> ! {
995 self.emit_diagnostic(&Diagnostic::new(Bug, msg));
996 panic::panic_any(ExplicitBug);
999 fn delay_as_bug(&mut self, diagnostic: Diagnostic) {
1000 if self.flags.report_delayed_bugs {
1001 self.emit_diagnostic(&diagnostic);
1003 self.delayed_span_bugs.push(diagnostic);
1006 fn flush_delayed(&mut self, bugs: Vec<Diagnostic>, explanation: &str) {
1007 let has_bugs = !bugs.is_empty();
1009 self.emit_diagnostic(&bug);
1012 panic!("{}", explanation);
1016 fn bump_err_count(&mut self) {
1017 self.err_count += 1;
1018 self.panic_if_treat_err_as_bug();
1021 fn bump_warn_count(&mut self) {
1022 self.warn_count += 1;
1025 fn panic_if_treat_err_as_bug(&self) {
1026 if self.treat_err_as_bug() {
1027 match (self.err_count(), self.flags.treat_err_as_bug.map(|c| c.get()).unwrap_or(0)) {
1028 (1, 1) => panic!("aborting due to `-Z treat-err-as-bug=1`"),
1029 (0, _) | (1, _) => {}
1030 (count, as_bug) => panic!(
1031 "aborting after {} errors due to `-Z treat-err-as-bug={}`",
1039 #[derive(Copy, PartialEq, Clone, Hash, Debug, Encodable, Decodable)]
1052 impl fmt::Display for Level {
1053 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1054 self.to_str().fmt(f)
1059 fn color(self) -> ColorSpec {
1060 let mut spec = ColorSpec::new();
1062 Bug | Fatal | Error => {
1063 spec.set_fg(Some(Color::Red)).set_intense(true);
1066 spec.set_fg(Some(Color::Yellow)).set_intense(cfg!(windows));
1069 spec.set_fg(Some(Color::Green)).set_intense(true);
1072 spec.set_fg(Some(Color::Cyan)).set_intense(true);
1075 Allow | Cancelled => unreachable!(),
1080 pub fn to_str(self) -> &'static str {
1082 Bug => "error: internal compiler error",
1083 Fatal | Error => "error",
1084 Warning => "warning",
1087 FailureNote => "failure-note",
1088 Cancelled => panic!("Shouldn't call on cancelled error"),
1089 Allow => panic!("Shouldn't call on allowed error"),
1093 pub fn is_failure_note(&self) -> bool {
1094 matches!(*self, FailureNote)
1098 pub fn add_elided_lifetime_in_path_suggestion(
1099 source_map: &SourceMap,
1100 db: &mut DiagnosticBuilder<'_>,
1103 incl_angl_brckt: bool,
1104 insertion_span: Span,
1107 let (replace_span, suggestion) = if incl_angl_brckt {
1108 (insertion_span, anon_lts)
1110 // When possible, prefer a suggestion that replaces the whole
1111 // `Path<T>` expression with `Path<'_, T>`, rather than inserting `'_, `
1112 // at a point (which makes for an ugly/confusing label)
1113 if let Ok(snippet) = source_map.span_to_snippet(path_span) {
1114 // But our spans can get out of whack due to macros; if the place we think
1115 // we want to insert `'_` isn't even within the path expression's span, we
1116 // should bail out of making any suggestion rather than panicking on a
1117 // subtract-with-overflow or string-slice-out-out-bounds (!)
1118 // FIXME: can we do better?
1119 if insertion_span.lo().0 < path_span.lo().0 {
1122 let insertion_index = (insertion_span.lo().0 - path_span.lo().0) as usize;
1123 if insertion_index > snippet.len() {
1126 let (before, after) = snippet.split_at(insertion_index);
1127 (path_span, format!("{}{}{}", before, anon_lts, after))
1129 (insertion_span, anon_lts)
1134 &format!("indicate the anonymous lifetime{}", pluralize!(n)),
1136 Applicability::MachineApplicable,
1140 // Useful type to use with `Result<>` indicate that an error has already
1141 // been reported to the user, so no need to continue checking.
1142 #[derive(Clone, Copy, Debug, Encodable, Decodable, Hash, PartialEq, Eq)]
1143 pub struct ErrorReported;
1145 rustc_data_structures::impl_stable_hash_via_hash!(ErrorReported);