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};
35 use std::{error, fmt};
37 use termcolor::{Color, ColorSpec};
39 pub mod annotate_snippet_emitter_writer;
41 mod diagnostic_builder;
48 pub use snippet::Style;
50 pub type PResult<'a, T> = Result<T, DiagnosticBuilder<'a>>;
52 // `PResult` is used a lot. Make sure it doesn't unintentionally get bigger.
53 // (See also the comment on `DiagnosticBuilderInner`.)
54 #[cfg(target_arch = "x86_64")]
55 rustc_data_structures::static_assert_size!(PResult<'_, bool>, 16);
57 #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, Encodable, Decodable)]
58 pub enum SuggestionStyle {
59 /// Hide the suggested code when displaying this suggestion inline.
61 /// Always hide the suggested code but display the message.
63 /// Do not display this suggestion in the cli output, it is only meant for tools.
65 /// Always show the suggested code.
66 /// This will *not* show the code if the suggestion is inline *and* the suggested code is
69 /// Always show the suggested code independently.
73 impl SuggestionStyle {
74 fn hide_inline(&self) -> bool {
75 !matches!(*self, SuggestionStyle::ShowCode)
79 #[derive(Clone, Debug, PartialEq, Default)]
80 pub struct ToolMetadata(pub Option<Json>);
83 fn new(json: Json) -> Self {
84 ToolMetadata(Some(json))
87 fn is_set(&self) -> bool {
92 impl Hash for ToolMetadata {
93 fn hash<H: Hasher>(&self, _state: &mut H) {}
96 // Doesn't really need to round-trip
97 impl<D: Decoder> Decodable<D> for ToolMetadata {
98 fn decode(_d: &mut D) -> Result<Self, D::Error> {
99 Ok(ToolMetadata(None))
103 impl<S: Encoder> Encodable<S> for ToolMetadata {
104 fn encode(&self, e: &mut S) -> Result<(), S::Error> {
106 None => e.emit_unit(),
107 Some(json) => json.encode(e),
112 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
113 pub struct CodeSuggestion {
114 /// Each substitute can have multiple variants due to multiple
115 /// applicable suggestions
117 /// `foo.bar` might be replaced with `a.b` or `x.y` by replacing
118 /// `foo` and `bar` on their own:
122 /// Substitution { parts: vec![(0..3, "a"), (4..7, "b")] },
123 /// Substitution { parts: vec![(0..3, "x"), (4..7, "y")] },
127 /// or by replacing the entire span:
131 /// Substitution { parts: vec![(0..7, "a.b")] },
132 /// Substitution { parts: vec![(0..7, "x.y")] },
135 pub substitutions: Vec<Substitution>,
137 /// Visual representation of this suggestion.
138 pub style: SuggestionStyle,
139 /// Whether or not the suggestion is approximate
141 /// Sometimes we may show suggestions with placeholders,
142 /// which are useful for users but not useful for
143 /// tools like rustfix
144 pub applicability: Applicability,
145 /// Tool-specific metadata
146 pub tool_metadata: ToolMetadata,
149 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
150 /// See the docs on `CodeSuggestion::substitutions`
151 pub struct Substitution {
152 pub parts: Vec<SubstitutionPart>,
155 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
156 pub struct SubstitutionPart {
161 impl CodeSuggestion {
162 /// Returns the assembled code suggestions, whether they should be shown with an underline
163 /// and whether the substitution only differs in capitalization.
164 pub fn splice_lines(&self, sm: &SourceMap) -> Vec<(String, Vec<SubstitutionPart>, bool)> {
165 use rustc_span::{CharPos, Pos};
169 line_opt: Option<&Cow<'_, str>>,
171 hi_opt: Option<&Loc>,
173 let (lo, hi_opt) = (lo.col.to_usize(), hi_opt.map(|hi| hi.col.to_usize()));
174 if let Some(line) = line_opt {
175 if let Some(lo) = line.char_indices().map(|(i, _)| i).nth(lo) {
176 let hi_opt = hi_opt.and_then(|hi| line.char_indices().map(|(i, _)| i).nth(hi));
178 Some(hi) if hi > lo => buf.push_str(&line[lo..hi]),
180 None => buf.push_str(&line[lo..]),
183 if hi_opt.is_none() {
189 assert!(!self.substitutions.is_empty());
194 // Suggestions coming from macros can have malformed spans. This is a heavy
195 // handed approach to avoid ICEs by ignoring the suggestion outright.
196 let invalid = subst.parts.iter().any(|item| sm.is_valid_span(item.span).is_err());
198 debug!("splice_lines: suggestion contains an invalid span: {:?}", subst);
203 .filter_map(|mut substitution| {
204 // Assumption: all spans are in the same file, and all spans
205 // are disjoint. Sort in ascending order.
206 substitution.parts.sort_by_key(|part| part.span.lo());
208 // Find the bounding span.
209 let lo = substitution.parts.iter().map(|part| part.span.lo()).min()?;
210 let hi = substitution.parts.iter().map(|part| part.span.hi()).max()?;
211 let bounding_span = Span::with_root_ctxt(lo, hi);
212 // The different spans might belong to different contexts, if so ignore suggestion.
213 let lines = sm.span_to_lines(bounding_span).ok()?;
214 assert!(!lines.lines.is_empty() || bounding_span.is_dummy());
216 // We can't splice anything if the source is unavailable.
217 if !sm.ensure_source_file_source_present(lines.file.clone()) {
221 // To build up the result, we do this for each span:
222 // - push the line segment trailing the previous span
223 // (at the beginning a "phantom" span pointing at the start of the line)
224 // - push lines between the previous and current span (if any)
225 // - if the previous and current span are not on the same line
226 // push the line segment leading up to the current span
227 // - splice in the span substitution
229 // Finally push the trailing line segment of the last span
230 let sf = &lines.file;
231 let mut prev_hi = sm.lookup_char_pos(bounding_span.lo());
232 prev_hi.col = CharPos::from_usize(0);
234 lines.lines.get(0).and_then(|line0| sf.get_line(line0.line_index));
235 let mut buf = String::new();
237 for part in &substitution.parts {
238 let cur_lo = sm.lookup_char_pos(part.span.lo());
239 if prev_hi.line == cur_lo.line {
240 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, Some(&cur_lo));
242 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
243 // push lines between the previous and current span (if any)
244 for idx in prev_hi.line..(cur_lo.line - 1) {
245 if let Some(line) = sf.get_line(idx) {
246 buf.push_str(line.as_ref());
250 if let Some(cur_line) = sf.get_line(cur_lo.line - 1) {
251 let end = match cur_line.char_indices().nth(cur_lo.col.to_usize()) {
253 None => cur_line.len(),
255 buf.push_str(&cur_line[..end]);
258 buf.push_str(&part.snippet);
259 prev_hi = sm.lookup_char_pos(part.span.hi());
260 prev_line = sf.get_line(prev_hi.line - 1);
262 let only_capitalization = is_case_difference(sm, &buf, bounding_span);
263 // if the replacement already ends with a newline, don't print the next line
264 if !buf.ends_with('\n') {
265 push_trailing(&mut buf, prev_line.as_ref(), &prev_hi, None);
267 // remove trailing newlines
268 while buf.ends_with('\n') {
271 Some((buf, substitution.parts, only_capitalization))
277 pub use rustc_span::fatal_error::{FatalError, FatalErrorMarker};
279 /// Signifies that the compiler died with an explicit call to `.bug`
280 /// or `.span_bug` rather than a failed assertion, etc.
281 #[derive(Copy, Clone, Debug)]
282 pub struct ExplicitBug;
284 impl fmt::Display for ExplicitBug {
285 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
286 write!(f, "parser internal bug")
290 impl error::Error for ExplicitBug {}
292 pub use diagnostic::{Diagnostic, DiagnosticId, DiagnosticStyledString, SubDiagnostic};
293 pub use diagnostic_builder::DiagnosticBuilder;
295 /// A handler deals with errors and other compiler output.
296 /// Certain errors (fatal, bug, unimpl) may cause immediate exit,
297 /// others log errors for later reporting.
300 inner: Lock<HandlerInner>,
303 /// This inner struct exists to keep it all behind a single lock;
304 /// this is done to prevent possible deadlocks in a multi-threaded compiler,
305 /// as well as inconsistent state observation.
306 struct HandlerInner {
308 /// The number of errors that have been emitted, including duplicates.
310 /// This is not necessarily the count that's reported to the user once
311 /// compilation ends.
314 deduplicated_err_count: usize,
315 emitter: Box<dyn Emitter + sync::Send>,
316 delayed_span_bugs: Vec<Diagnostic>,
317 delayed_good_path_bugs: Vec<Diagnostic>,
319 /// This set contains the `DiagnosticId` of all emitted diagnostics to avoid
320 /// emitting the same diagnostic with extended help (`--teach`) twice, which
321 /// would be uneccessary repetition.
322 taught_diagnostics: FxHashSet<DiagnosticId>,
324 /// Used to suggest rustc --explain <error code>
325 emitted_diagnostic_codes: FxHashSet<DiagnosticId>,
327 /// This set contains a hash of every diagnostic that has been emitted by
328 /// this handler. These hashes is used to avoid emitting the same error
330 emitted_diagnostics: FxHashSet<u128>,
332 /// Stashed diagnostics emitted in one stage of the compiler that may be
333 /// stolen by other stages (e.g. to improve them and add more information).
334 /// The stashed diagnostics count towards the total error count.
335 /// When `.abort_if_errors()` is called, these are also emitted.
336 stashed_diagnostics: FxIndexMap<(Span, StashKey), Diagnostic>,
338 /// The warning count, used for a recap upon finishing
339 deduplicated_warn_count: usize,
341 future_breakage_diagnostics: Vec<Diagnostic>,
344 /// A key denoting where from a diagnostic was stashed.
345 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
350 fn default_track_diagnostic(_: &Diagnostic) {}
352 pub static TRACK_DIAGNOSTICS: AtomicRef<fn(&Diagnostic)> =
353 AtomicRef::new(&(default_track_diagnostic as fn(&_)));
355 #[derive(Copy, Clone, Default)]
356 pub struct HandlerFlags {
357 /// If false, warning-level lints are suppressed.
358 /// (rustc: see `--allow warnings` and `--cap-lints`)
359 pub can_emit_warnings: bool,
360 /// If true, error-level diagnostics are upgraded to bug-level.
361 /// (rustc: see `-Z treat-err-as-bug`)
362 pub treat_err_as_bug: Option<usize>,
363 /// If true, immediately emit diagnostics that would otherwise be buffered.
364 /// (rustc: see `-Z dont-buffer-diagnostics` and `-Z treat-err-as-bug`)
365 pub dont_buffer_diagnostics: bool,
366 /// If true, immediately print bugs registered with `delay_span_bug`.
367 /// (rustc: see `-Z report-delayed-bugs`)
368 pub report_delayed_bugs: bool,
369 /// Show macro backtraces.
370 /// (rustc: see `-Z macro-backtrace`)
371 pub macro_backtrace: bool,
372 /// If true, identical diagnostics are reported only once.
373 pub deduplicate_diagnostics: bool,
376 impl Drop for HandlerInner {
378 self.emit_stashed_diagnostics();
380 if !self.has_errors() {
381 let bugs = std::mem::replace(&mut self.delayed_span_bugs, Vec::new());
382 self.flush_delayed(bugs, "no errors encountered even though `delay_span_bug` issued");
385 if !self.has_any_message() {
386 let bugs = std::mem::replace(&mut self.delayed_good_path_bugs, Vec::new());
389 "no warnings or errors encountered even though `delayed_good_path_bugs` issued",
396 pub fn with_tty_emitter(
397 color_config: ColorConfig,
398 can_emit_warnings: bool,
399 treat_err_as_bug: Option<usize>,
400 sm: Option<Lrc<SourceMap>>,
402 Self::with_tty_emitter_and_flags(
405 HandlerFlags { can_emit_warnings, treat_err_as_bug, ..Default::default() },
409 pub fn with_tty_emitter_and_flags(
410 color_config: ColorConfig,
411 sm: Option<Lrc<SourceMap>>,
414 let emitter = Box::new(EmitterWriter::stderr(
420 flags.macro_backtrace,
422 Self::with_emitter_and_flags(emitter, flags)
426 can_emit_warnings: bool,
427 treat_err_as_bug: Option<usize>,
428 emitter: Box<dyn Emitter + sync::Send>,
430 Handler::with_emitter_and_flags(
432 HandlerFlags { can_emit_warnings, treat_err_as_bug, ..Default::default() },
436 pub fn with_emitter_and_flags(
437 emitter: Box<dyn Emitter + sync::Send>,
442 inner: Lock::new(HandlerInner {
446 deduplicated_err_count: 0,
447 deduplicated_warn_count: 0,
449 delayed_span_bugs: Vec::new(),
450 delayed_good_path_bugs: Vec::new(),
451 taught_diagnostics: Default::default(),
452 emitted_diagnostic_codes: Default::default(),
453 emitted_diagnostics: Default::default(),
454 stashed_diagnostics: Default::default(),
455 future_breakage_diagnostics: Vec::new(),
460 // This is here to not allow mutation of flags;
461 // as of this writing it's only used in tests in librustc_middle.
462 pub fn can_emit_warnings(&self) -> bool {
463 self.flags.can_emit_warnings
466 /// Resets the diagnostic error count as well as the cached emitted diagnostics.
468 /// NOTE: *do not* call this function from rustc. It is only meant to be called from external
469 /// tools that want to reuse a `Parser` cleaning the previously emitted diagnostics as well as
470 /// the overall count of emitted error diagnostics.
471 pub fn reset_err_count(&self) {
472 let mut inner = self.inner.borrow_mut();
474 inner.warn_count = 0;
475 inner.deduplicated_err_count = 0;
476 inner.deduplicated_warn_count = 0;
478 // actually free the underlying memory (which `clear` would not do)
479 inner.delayed_span_bugs = Default::default();
480 inner.delayed_good_path_bugs = Default::default();
481 inner.taught_diagnostics = Default::default();
482 inner.emitted_diagnostic_codes = Default::default();
483 inner.emitted_diagnostics = Default::default();
484 inner.stashed_diagnostics = Default::default();
487 /// Stash a given diagnostic with the given `Span` and `StashKey` as the key for later stealing.
488 pub fn stash_diagnostic(&self, span: Span, key: StashKey, diag: Diagnostic) {
489 let mut inner = self.inner.borrow_mut();
490 // FIXME(Centril, #69537): Consider reintroducing panic on overwriting a stashed diagnostic
491 // if/when we have a more robust macro-friendly replacement for `(span, key)` as a key.
492 // See the PR for a discussion.
493 inner.stashed_diagnostics.insert((span, key), diag);
496 /// Steal a previously stashed diagnostic with the given `Span` and `StashKey` as the key.
497 pub fn steal_diagnostic(&self, span: Span, key: StashKey) -> Option<DiagnosticBuilder<'_>> {
501 .remove(&(span, key))
502 .map(|diag| DiagnosticBuilder::new_diagnostic(self, diag))
505 /// Emit all stashed diagnostics.
506 pub fn emit_stashed_diagnostics(&self) {
507 self.inner.borrow_mut().emit_stashed_diagnostics();
510 /// Construct a dummy builder with `Level::Cancelled`.
512 /// Using this will neither report anything to the user (e.g. a warning),
513 /// nor will compilation cancel as a result.
514 pub fn struct_dummy(&self) -> DiagnosticBuilder<'_> {
515 DiagnosticBuilder::new(self, Level::Cancelled, "")
518 /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
519 pub fn struct_span_warn(&self, span: impl Into<MultiSpan>, msg: &str) -> DiagnosticBuilder<'_> {
520 let mut result = self.struct_warn(msg);
521 result.set_span(span);
525 /// Construct a builder at the `Allow` level at the given `span` and with the `msg`.
526 pub fn struct_span_allow(
528 span: impl Into<MultiSpan>,
530 ) -> DiagnosticBuilder<'_> {
531 let mut result = self.struct_allow(msg);
532 result.set_span(span);
536 /// Construct a builder at the `Warning` level at the given `span` and with the `msg`.
537 /// Also include a code.
538 pub fn struct_span_warn_with_code(
540 span: impl Into<MultiSpan>,
543 ) -> DiagnosticBuilder<'_> {
544 let mut result = self.struct_span_warn(span, msg);
549 /// Construct a builder at the `Warning` level with the `msg`.
550 pub fn struct_warn(&self, msg: &str) -> DiagnosticBuilder<'_> {
551 let mut result = DiagnosticBuilder::new(self, Level::Warning, msg);
552 if !self.flags.can_emit_warnings {
558 /// Construct a builder at the `Allow` level with the `msg`.
559 pub fn struct_allow(&self, msg: &str) -> DiagnosticBuilder<'_> {
560 DiagnosticBuilder::new(self, Level::Allow, msg)
563 /// Construct a builder at the `Error` level at the given `span` and with the `msg`.
564 pub fn struct_span_err(&self, span: impl Into<MultiSpan>, msg: &str) -> DiagnosticBuilder<'_> {
565 let mut result = self.struct_err(msg);
566 result.set_span(span);
570 /// Construct a builder at the `Error` level at the given `span`, with the `msg`, and `code`.
571 pub fn struct_span_err_with_code(
573 span: impl Into<MultiSpan>,
576 ) -> DiagnosticBuilder<'_> {
577 let mut result = self.struct_span_err(span, msg);
582 /// Construct a builder at the `Error` level with the `msg`.
583 // FIXME: This method should be removed (every error should have an associated error code).
584 pub fn struct_err(&self, msg: &str) -> DiagnosticBuilder<'_> {
585 DiagnosticBuilder::new(self, Level::Error, msg)
588 /// Construct a builder at the `Error` level with the `msg` and the `code`.
589 pub fn struct_err_with_code(&self, msg: &str, code: DiagnosticId) -> DiagnosticBuilder<'_> {
590 let mut result = self.struct_err(msg);
595 /// Construct a builder at the `Fatal` level at the given `span` and with the `msg`.
596 pub fn struct_span_fatal(
598 span: impl Into<MultiSpan>,
600 ) -> DiagnosticBuilder<'_> {
601 let mut result = self.struct_fatal(msg);
602 result.set_span(span);
606 /// Construct a builder at the `Fatal` level at the given `span`, with the `msg`, and `code`.
607 pub fn struct_span_fatal_with_code(
609 span: impl Into<MultiSpan>,
612 ) -> DiagnosticBuilder<'_> {
613 let mut result = self.struct_span_fatal(span, msg);
618 /// Construct a builder at the `Error` level with the `msg`.
619 pub fn struct_fatal(&self, msg: &str) -> DiagnosticBuilder<'_> {
620 DiagnosticBuilder::new(self, Level::Fatal, msg)
623 /// Construct a builder at the `Help` level with the `msg`.
624 pub fn struct_help(&self, msg: &str) -> DiagnosticBuilder<'_> {
625 DiagnosticBuilder::new(self, Level::Help, msg)
628 /// Construct a builder at the `Note` level with the `msg`.
629 pub fn struct_note_without_error(&self, msg: &str) -> DiagnosticBuilder<'_> {
630 DiagnosticBuilder::new(self, Level::Note, msg)
633 pub fn span_fatal(&self, span: impl Into<MultiSpan>, msg: &str) -> FatalError {
634 self.emit_diag_at_span(Diagnostic::new(Fatal, msg), span);
638 pub fn span_fatal_with_code(
640 span: impl Into<MultiSpan>,
644 self.emit_diag_at_span(Diagnostic::new_with_code(Fatal, Some(code), msg), span);
648 pub fn span_err(&self, span: impl Into<MultiSpan>, msg: &str) {
649 self.emit_diag_at_span(Diagnostic::new(Error, msg), span);
652 pub fn span_err_with_code(&self, span: impl Into<MultiSpan>, msg: &str, code: DiagnosticId) {
653 self.emit_diag_at_span(Diagnostic::new_with_code(Error, Some(code), msg), span);
656 pub fn span_warn(&self, span: impl Into<MultiSpan>, msg: &str) {
657 self.emit_diag_at_span(Diagnostic::new(Warning, msg), span);
660 pub fn span_warn_with_code(&self, span: impl Into<MultiSpan>, msg: &str, code: DiagnosticId) {
661 self.emit_diag_at_span(Diagnostic::new_with_code(Warning, Some(code), msg), span);
664 pub fn span_bug(&self, span: impl Into<MultiSpan>, msg: &str) -> ! {
665 self.inner.borrow_mut().span_bug(span, msg)
669 pub fn delay_span_bug(&self, span: impl Into<MultiSpan>, msg: &str) {
670 self.inner.borrow_mut().delay_span_bug(span, msg)
673 pub fn delay_good_path_bug(&self, msg: &str) {
674 self.inner.borrow_mut().delay_good_path_bug(msg)
677 pub fn span_bug_no_panic(&self, span: impl Into<MultiSpan>, msg: &str) {
678 self.emit_diag_at_span(Diagnostic::new(Bug, msg), span);
681 pub fn span_note_without_error(&self, span: impl Into<MultiSpan>, msg: &str) {
682 self.emit_diag_at_span(Diagnostic::new(Note, msg), span);
685 pub fn span_note_diag(&self, span: Span, msg: &str) -> DiagnosticBuilder<'_> {
686 let mut db = DiagnosticBuilder::new(self, Note, msg);
691 pub fn failure(&self, msg: &str) {
692 self.inner.borrow_mut().failure(msg);
695 pub fn fatal(&self, msg: &str) -> FatalError {
696 self.inner.borrow_mut().fatal(msg)
699 pub fn err(&self, msg: &str) {
700 self.inner.borrow_mut().err(msg);
703 pub fn warn(&self, msg: &str) {
704 let mut db = DiagnosticBuilder::new(self, Warning, msg);
708 pub fn note_without_error(&self, msg: &str) {
709 DiagnosticBuilder::new(self, Note, msg).emit();
712 pub fn bug(&self, msg: &str) -> ! {
713 self.inner.borrow_mut().bug(msg)
716 pub fn err_count(&self) -> usize {
717 self.inner.borrow().err_count()
720 pub fn has_errors(&self) -> bool {
721 self.inner.borrow().has_errors()
723 pub fn has_errors_or_delayed_span_bugs(&self) -> bool {
724 self.inner.borrow().has_errors_or_delayed_span_bugs()
727 pub fn print_error_count(&self, registry: &Registry) {
728 self.inner.borrow_mut().print_error_count(registry)
731 pub fn take_future_breakage_diagnostics(&self) -> Vec<Diagnostic> {
732 std::mem::take(&mut self.inner.borrow_mut().future_breakage_diagnostics)
735 pub fn abort_if_errors(&self) {
736 self.inner.borrow_mut().abort_if_errors()
739 /// `true` if we haven't taught a diagnostic with this code already.
740 /// The caller must then teach the user about such a diagnostic.
742 /// Used to suppress emitting the same error multiple times with extended explanation when
743 /// calling `-Zteach`.
744 pub fn must_teach(&self, code: &DiagnosticId) -> bool {
745 self.inner.borrow_mut().must_teach(code)
748 pub fn force_print_diagnostic(&self, db: Diagnostic) {
749 self.inner.borrow_mut().force_print_diagnostic(db)
752 pub fn emit_diagnostic(&self, diagnostic: &Diagnostic) {
753 self.inner.borrow_mut().emit_diagnostic(diagnostic)
756 fn emit_diag_at_span(&self, mut diag: Diagnostic, sp: impl Into<MultiSpan>) {
757 let mut inner = self.inner.borrow_mut();
758 inner.emit_diagnostic(diag.set_span(sp));
761 pub fn emit_artifact_notification(&self, path: &Path, artifact_type: &str) {
762 self.inner.borrow_mut().emit_artifact_notification(path, artifact_type)
765 pub fn emit_future_breakage_report(&self, diags: Vec<(FutureBreakage, Diagnostic)>) {
766 self.inner.borrow_mut().emitter.emit_future_breakage_report(diags)
769 pub fn delay_as_bug(&self, diagnostic: Diagnostic) {
770 self.inner.borrow_mut().delay_as_bug(diagnostic)
775 fn must_teach(&mut self, code: &DiagnosticId) -> bool {
776 self.taught_diagnostics.insert(code.clone())
779 fn force_print_diagnostic(&mut self, db: Diagnostic) {
780 self.emitter.emit_diagnostic(&db);
783 /// Emit all stashed diagnostics.
784 fn emit_stashed_diagnostics(&mut self) {
785 let diags = self.stashed_diagnostics.drain(..).map(|x| x.1).collect::<Vec<_>>();
786 diags.iter().for_each(|diag| self.emit_diagnostic(diag));
789 fn emit_diagnostic(&mut self, diagnostic: &Diagnostic) {
790 if diagnostic.cancelled() {
794 if diagnostic.has_future_breakage() {
795 self.future_breakage_diagnostics.push(diagnostic.clone());
798 if diagnostic.level == Warning && !self.flags.can_emit_warnings {
799 if diagnostic.has_future_breakage() {
800 (*TRACK_DIAGNOSTICS)(diagnostic);
805 (*TRACK_DIAGNOSTICS)(diagnostic);
807 if diagnostic.level == Allow {
811 if let Some(ref code) = diagnostic.code {
812 self.emitted_diagnostic_codes.insert(code.clone());
815 let already_emitted = |this: &mut Self| {
816 let mut hasher = StableHasher::new();
817 diagnostic.hash(&mut hasher);
818 let diagnostic_hash = hasher.finish();
819 !this.emitted_diagnostics.insert(diagnostic_hash)
822 // Only emit the diagnostic if we've been asked to deduplicate and
823 // haven't already emitted an equivalent diagnostic.
824 if !(self.flags.deduplicate_diagnostics && already_emitted(self)) {
825 self.emitter.emit_diagnostic(diagnostic);
826 if diagnostic.is_error() {
827 self.deduplicated_err_count += 1;
828 } else if diagnostic.level == Warning {
829 self.deduplicated_warn_count += 1;
832 if diagnostic.is_error() {
833 self.bump_err_count();
835 self.bump_warn_count();
839 fn emit_artifact_notification(&mut self, path: &Path, artifact_type: &str) {
840 self.emitter.emit_artifact_notification(path, artifact_type);
843 fn treat_err_as_bug(&self) -> bool {
844 self.flags.treat_err_as_bug.map_or(false, |c| self.err_count() >= c)
847 fn print_error_count(&mut self, registry: &Registry) {
848 self.emit_stashed_diagnostics();
850 let warnings = match self.deduplicated_warn_count {
852 1 => "1 warning emitted".to_string(),
853 count => format!("{} warnings emitted", count),
855 let errors = match self.deduplicated_err_count {
857 1 => "aborting due to previous error".to_string(),
858 count => format!("aborting due to {} previous errors", count),
860 if self.treat_err_as_bug() {
864 match (errors.len(), warnings.len()) {
866 (0, _) => self.emit_diagnostic(&Diagnostic::new(Level::Warning, &warnings)),
868 let _ = self.fatal(&errors);
871 let _ = self.fatal(&format!("{}; {}", &errors, &warnings));
875 let can_show_explain = self.emitter.should_show_explain();
876 let are_there_diagnostics = !self.emitted_diagnostic_codes.is_empty();
877 if can_show_explain && are_there_diagnostics {
878 let mut error_codes = self
879 .emitted_diagnostic_codes
881 .filter_map(|x| match &x {
882 DiagnosticId::Error(s) => {
883 if let Ok(Some(_explanation)) = registry.try_find_description(s) {
891 .collect::<Vec<_>>();
892 if !error_codes.is_empty() {
894 if error_codes.len() > 1 {
895 let limit = if error_codes.len() > 9 { 9 } else { error_codes.len() };
896 self.failure(&format!(
897 "Some errors have detailed explanations: {}{}",
898 error_codes[..limit].join(", "),
899 if error_codes.len() > 9 { "..." } else { "." }
901 self.failure(&format!(
902 "For more information about an error, try \
903 `rustc --explain {}`.",
907 self.failure(&format!(
908 "For more information about this error, try \
909 `rustc --explain {}`.",
917 fn err_count(&self) -> usize {
918 self.err_count + self.stashed_diagnostics.len()
921 fn has_errors(&self) -> bool {
924 fn has_errors_or_delayed_span_bugs(&self) -> bool {
925 self.has_errors() || !self.delayed_span_bugs.is_empty()
927 fn has_any_message(&self) -> bool {
928 self.err_count() > 0 || self.warn_count > 0
931 fn abort_if_errors(&mut self) {
932 self.emit_stashed_diagnostics();
934 if self.has_errors() {
939 fn span_bug(&mut self, sp: impl Into<MultiSpan>, msg: &str) -> ! {
940 self.emit_diag_at_span(Diagnostic::new(Bug, msg), sp);
941 panic::panic_any(ExplicitBug);
944 fn emit_diag_at_span(&mut self, mut diag: Diagnostic, sp: impl Into<MultiSpan>) {
945 self.emit_diagnostic(diag.set_span(sp));
949 fn delay_span_bug(&mut self, sp: impl Into<MultiSpan>, msg: &str) {
950 // This is technically `self.treat_err_as_bug()` but `delay_span_bug` is called before
951 // incrementing `err_count` by one, so we need to +1 the comparing.
952 // FIXME: Would be nice to increment err_count in a more coherent way.
953 if self.flags.treat_err_as_bug.map_or(false, |c| self.err_count() + 1 >= c) {
954 // FIXME: don't abort here if report_delayed_bugs is off
955 self.span_bug(sp, msg);
957 let mut diagnostic = Diagnostic::new(Level::Bug, msg);
958 diagnostic.set_span(sp.into());
959 diagnostic.note(&format!("delayed at {}", std::panic::Location::caller()));
960 self.delay_as_bug(diagnostic)
963 fn delay_good_path_bug(&mut self, msg: &str) {
964 let mut diagnostic = Diagnostic::new(Level::Bug, msg);
965 if self.flags.report_delayed_bugs {
966 self.emit_diagnostic(&diagnostic);
968 diagnostic.note(&format!("delayed at {}", std::backtrace::Backtrace::force_capture()));
969 self.delayed_good_path_bugs.push(diagnostic);
972 fn failure(&mut self, msg: &str) {
973 self.emit_diagnostic(&Diagnostic::new(FailureNote, msg));
976 fn fatal(&mut self, msg: &str) -> FatalError {
977 self.emit_error(Fatal, msg);
981 fn err(&mut self, msg: &str) {
982 self.emit_error(Error, msg);
985 /// Emit an error; level should be `Error` or `Fatal`.
986 fn emit_error(&mut self, level: Level, msg: &str) {
987 if self.treat_err_as_bug() {
990 self.emit_diagnostic(&Diagnostic::new(level, msg));
993 fn bug(&mut self, msg: &str) -> ! {
994 self.emit_diagnostic(&Diagnostic::new(Bug, msg));
995 panic::panic_any(ExplicitBug);
998 fn delay_as_bug(&mut self, diagnostic: Diagnostic) {
999 if self.flags.report_delayed_bugs {
1000 self.emit_diagnostic(&diagnostic);
1002 self.delayed_span_bugs.push(diagnostic);
1005 fn flush_delayed(&mut self, bugs: Vec<Diagnostic>, explanation: &str) {
1006 let has_bugs = !bugs.is_empty();
1008 self.emit_diagnostic(&bug);
1011 panic!("{}", explanation);
1015 fn bump_err_count(&mut self) {
1016 self.err_count += 1;
1017 self.panic_if_treat_err_as_bug();
1020 fn bump_warn_count(&mut self) {
1021 self.warn_count += 1;
1024 fn panic_if_treat_err_as_bug(&self) {
1025 if self.treat_err_as_bug() {
1026 match (self.err_count(), self.flags.treat_err_as_bug.unwrap_or(0)) {
1027 (1, 1) => panic!("aborting due to `-Z treat-err-as-bug=1`"),
1028 (0, _) | (1, _) => {}
1029 (count, as_bug) => panic!(
1030 "aborting after {} errors due to `-Z treat-err-as-bug={}`",
1038 #[derive(Copy, PartialEq, Clone, Hash, Debug, Encodable, Decodable)]
1051 impl fmt::Display for Level {
1052 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1053 self.to_str().fmt(f)
1058 fn color(self) -> ColorSpec {
1059 let mut spec = ColorSpec::new();
1061 Bug | Fatal | Error => {
1062 spec.set_fg(Some(Color::Red)).set_intense(true);
1065 spec.set_fg(Some(Color::Yellow)).set_intense(cfg!(windows));
1068 spec.set_fg(Some(Color::Green)).set_intense(true);
1071 spec.set_fg(Some(Color::Cyan)).set_intense(true);
1074 Allow | Cancelled => unreachable!(),
1079 pub fn to_str(self) -> &'static str {
1081 Bug => "error: internal compiler error",
1082 Fatal | Error => "error",
1083 Warning => "warning",
1086 FailureNote => "failure-note",
1087 Cancelled => panic!("Shouldn't call on cancelled error"),
1088 Allow => panic!("Shouldn't call on allowed error"),
1092 pub fn is_failure_note(&self) -> bool {
1093 matches!(*self, FailureNote)
1097 pub fn add_elided_lifetime_in_path_suggestion(
1098 source_map: &SourceMap,
1099 db: &mut DiagnosticBuilder<'_>,
1102 incl_angl_brckt: bool,
1103 insertion_span: Span,
1106 let (replace_span, suggestion) = if incl_angl_brckt {
1107 (insertion_span, anon_lts)
1109 // When possible, prefer a suggestion that replaces the whole
1110 // `Path<T>` expression with `Path<'_, T>`, rather than inserting `'_, `
1111 // at a point (which makes for an ugly/confusing label)
1112 if let Ok(snippet) = source_map.span_to_snippet(path_span) {
1113 // But our spans can get out of whack due to macros; if the place we think
1114 // we want to insert `'_` isn't even within the path expression's span, we
1115 // should bail out of making any suggestion rather than panicking on a
1116 // subtract-with-overflow or string-slice-out-out-bounds (!)
1117 // FIXME: can we do better?
1118 if insertion_span.lo().0 < path_span.lo().0 {
1121 let insertion_index = (insertion_span.lo().0 - path_span.lo().0) as usize;
1122 if insertion_index > snippet.len() {
1125 let (before, after) = snippet.split_at(insertion_index);
1126 (path_span, format!("{}{}{}", before, anon_lts, after))
1128 (insertion_span, anon_lts)
1133 &format!("indicate the anonymous lifetime{}", pluralize!(n)),
1135 Applicability::MachineApplicable,
1139 // Useful type to use with `Result<>` indicate that an error has already
1140 // been reported to the user, so no need to continue checking.
1141 #[derive(Clone, Copy, Debug, Encodable, Decodable, Hash, PartialEq, Eq)]
1142 pub struct ErrorReported;
1144 rustc_data_structures::impl_stable_hash_via_hash!(ErrorReported);