1 use crate::snippet::Style;
3 CodeSuggestion, DiagnosticMessage, Level, MultiSpan, Substitution, SubstitutionPart,
6 use rustc_data_structures::stable_map::FxHashMap;
7 use rustc_error_messages::FluentValue;
8 use rustc_lint_defs::{Applicability, LintExpectationId};
9 use rustc_span::edition::LATEST_STABLE_EDITION;
10 use rustc_span::symbol::{Ident, Symbol};
11 use rustc_span::{Span, DUMMY_SP};
14 use std::hash::{Hash, Hasher};
16 /// Error type for `Diagnostic`'s `suggestions` field, indicating that
17 /// `.disable_suggestions()` was called on the `Diagnostic`.
18 #[derive(Clone, Debug, PartialEq, Eq, Hash, Encodable, Decodable)]
19 pub struct SuggestionsDisabled;
21 /// Simplified version of `FluentArg` that can implement `Encodable` and `Decodable`. Collection of
22 /// `DiagnosticArg` are converted to `FluentArgs` (consuming the collection) at the start of
23 /// diagnostic emission.
24 pub type DiagnosticArg<'source> = (Cow<'source, str>, DiagnosticArgValue<'source>);
26 /// Simplified version of `FluentValue` that can implement `Encodable` and `Decodable`. Converted
27 /// to a `FluentValue` by the emitter to be used in diagnostic translation.
28 #[derive(Clone, Debug, PartialEq, Eq, Hash, Encodable, Decodable)]
29 pub enum DiagnosticArgValue<'source> {
30 Str(Cow<'source, str>),
34 /// Converts a value of a type into a `DiagnosticArg` (typically a field of a `SessionDiagnostic`
35 /// struct). Implemented as a custom trait rather than `From` so that it is implemented on the type
36 /// being converted rather than on `DiagnosticArgValue`, which enables types from other `rustc_*`
37 /// crates to implement this.
38 pub trait IntoDiagnosticArg {
39 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static>;
42 impl IntoDiagnosticArg for String {
43 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
44 DiagnosticArgValue::Str(Cow::Owned(self))
48 impl IntoDiagnosticArg for Symbol {
49 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
50 self.to_ident_string().into_diagnostic_arg()
54 impl IntoDiagnosticArg for Ident {
55 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
56 self.to_string().into_diagnostic_arg()
60 impl<'a> IntoDiagnosticArg for &'a str {
61 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
62 self.to_string().into_diagnostic_arg()
66 impl IntoDiagnosticArg for usize {
67 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
68 DiagnosticArgValue::Number(self)
72 impl<'source> Into<FluentValue<'source>> for DiagnosticArgValue<'source> {
73 fn into(self) -> FluentValue<'source> {
75 DiagnosticArgValue::Str(s) => From::from(s),
76 DiagnosticArgValue::Number(n) => From::from(n),
82 #[derive(Clone, Debug, Encodable, Decodable)]
83 pub struct Diagnostic {
84 // NOTE(eddyb) this is private to disallow arbitrary after-the-fact changes,
85 // outside of what methods in this crate themselves allow.
88 pub message: Vec<(DiagnosticMessage, Style)>,
89 pub code: Option<DiagnosticId>,
91 pub children: Vec<SubDiagnostic>,
92 pub suggestions: Result<Vec<CodeSuggestion>, SuggestionsDisabled>,
93 args: Vec<DiagnosticArg<'static>>,
95 /// This is not used for highlighting or rendering any error message. Rather, it can be used
96 /// as a sort key to sort a buffer of diagnostics. By default, it is the primary span of
97 /// `span` if there is one. Otherwise, it is `DUMMY_SP`.
100 /// If diagnostic is from Lint, custom hash function ignores notes
101 /// otherwise hash is based on the all the fields
105 #[derive(Clone, Debug, PartialEq, Eq, Hash, Encodable, Decodable)]
106 pub enum DiagnosticId {
108 Lint { name: String, has_future_breakage: bool, is_force_warn: bool },
111 /// A "sub"-diagnostic attached to a parent diagnostic.
112 /// For example, a note attached to an error.
113 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
114 pub struct SubDiagnostic {
116 pub message: Vec<(DiagnosticMessage, Style)>,
118 pub render_span: Option<MultiSpan>,
121 #[derive(Debug, PartialEq, Eq)]
122 pub struct DiagnosticStyledString(pub Vec<StringPart>);
124 impl DiagnosticStyledString {
125 pub fn new() -> DiagnosticStyledString {
126 DiagnosticStyledString(vec![])
128 pub fn push_normal<S: Into<String>>(&mut self, t: S) {
129 self.0.push(StringPart::Normal(t.into()));
131 pub fn push_highlighted<S: Into<String>>(&mut self, t: S) {
132 self.0.push(StringPart::Highlighted(t.into()));
134 pub fn push<S: Into<String>>(&mut self, t: S, highlight: bool) {
136 self.push_highlighted(t);
141 pub fn normal<S: Into<String>>(t: S) -> DiagnosticStyledString {
142 DiagnosticStyledString(vec![StringPart::Normal(t.into())])
145 pub fn highlighted<S: Into<String>>(t: S) -> DiagnosticStyledString {
146 DiagnosticStyledString(vec![StringPart::Highlighted(t.into())])
149 pub fn content(&self) -> String {
150 self.0.iter().map(|x| x.content()).collect::<String>()
154 #[derive(Debug, PartialEq, Eq)]
155 pub enum StringPart {
161 pub fn content(&self) -> &str {
163 &StringPart::Normal(ref s) | &StringPart::Highlighted(ref s) => s,
169 pub fn new<M: Into<DiagnosticMessage>>(level: Level, message: M) -> Self {
170 Diagnostic::new_with_code(level, None, message)
173 pub fn new_with_code<M: Into<DiagnosticMessage>>(
175 code: Option<DiagnosticId>,
180 message: vec![(message.into(), Style::NoStyle)],
182 span: MultiSpan::new(),
184 suggestions: Ok(vec![]),
192 pub fn level(&self) -> Level {
196 pub fn is_error(&self) -> bool {
201 | Level::Error { .. }
202 | Level::FailureNote => true,
209 | Level::Expect(_) => false,
213 pub fn update_unstable_expectation_id(
215 unstable_to_stable: &FxHashMap<LintExpectationId, LintExpectationId>,
217 if let Level::Expect(expectation_id) = &mut self.level {
218 if expectation_id.is_stable() {
222 // The unstable to stable map only maps the unstable `AttrId` to a stable `HirId` with an attribute index.
223 // The lint index inside the attribute is manually transferred here.
224 let lint_index = expectation_id.get_lint_index();
225 expectation_id.set_lint_index(None);
226 let mut stable_id = *unstable_to_stable
227 .get(&expectation_id)
228 .expect("each unstable `LintExpectationId` must have a matching stable id");
230 stable_id.set_lint_index(lint_index);
231 *expectation_id = stable_id;
235 pub fn has_future_breakage(&self) -> bool {
237 Some(DiagnosticId::Lint { has_future_breakage, .. }) => has_future_breakage,
242 pub fn is_force_warn(&self) -> bool {
244 Some(DiagnosticId::Lint { is_force_warn, .. }) => is_force_warn,
249 /// Delay emission of this diagnostic as a bug.
251 /// This can be useful in contexts where an error indicates a bug but
252 /// typically this only happens when other compilation errors have already
253 /// happened. In those cases this can be used to defer emission of this
254 /// diagnostic as a bug in the compiler only if no other errors have been
257 /// In the meantime, though, callsites are required to deal with the "bug"
258 /// locally in whichever way makes the most sense.
260 pub fn downgrade_to_delayed_bug(&mut self) -> &mut Self {
263 "downgrade_to_delayed_bug: cannot downgrade {:?} to DelayedBug: not an error",
266 self.level = Level::DelayedBug;
271 /// Adds a span/label to be included in the resulting snippet.
273 /// This is pushed onto the [`MultiSpan`] that was created when the diagnostic
274 /// was first built. That means it will be shown together with the original
275 /// span/label, *not* a span added by one of the `span_{note,warn,help,suggestions}` methods.
277 /// This span is *not* considered a ["primary span"][`MultiSpan`]; only
278 /// the `Span` supplied when creating the diagnostic is primary.
279 pub fn span_label(&mut self, span: Span, label: impl Into<DiagnosticMessage>) -> &mut Self {
280 self.span.push_span_label(span, label.into());
284 /// Labels all the given spans with the provided label.
285 /// See [`Self::span_label()`] for more information.
288 spans: impl IntoIterator<Item = Span>,
289 label: impl AsRef<str>,
291 let label = label.as_ref();
293 self.span_label(span, label);
298 pub fn replace_span_with(&mut self, after: Span) -> &mut Self {
299 let before = self.span.clone();
300 self.set_span(after);
301 for span_label in before.span_labels() {
302 if let Some(label) = span_label.label {
303 self.span.push_span_label(after, label);
309 pub fn note_expected_found(
311 expected_label: &dyn fmt::Display,
312 expected: DiagnosticStyledString,
313 found_label: &dyn fmt::Display,
314 found: DiagnosticStyledString,
316 self.note_expected_found_extra(expected_label, expected, found_label, found, &"", &"")
319 pub fn note_unsuccessful_coercion(
321 expected: DiagnosticStyledString,
322 found: DiagnosticStyledString,
324 let mut msg: Vec<_> =
325 vec![("required when trying to coerce from type `".to_string(), Style::NoStyle)];
326 msg.extend(expected.0.iter().map(|x| match *x {
327 StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
328 StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
330 msg.push(("` to type '".to_string(), Style::NoStyle));
331 msg.extend(found.0.iter().map(|x| match *x {
332 StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
333 StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
335 msg.push(("`".to_string(), Style::NoStyle));
337 // For now, just attach these as notes
338 self.highlighted_note(msg);
342 pub fn note_expected_found_extra(
344 expected_label: &dyn fmt::Display,
345 expected: DiagnosticStyledString,
346 found_label: &dyn fmt::Display,
347 found: DiagnosticStyledString,
348 expected_extra: &dyn fmt::Display,
349 found_extra: &dyn fmt::Display,
351 let expected_label = expected_label.to_string();
352 let expected_label = if expected_label.is_empty() {
353 "expected".to_string()
355 format!("expected {}", expected_label)
357 let found_label = found_label.to_string();
358 let found_label = if found_label.is_empty() {
361 format!("found {}", found_label)
363 let (found_padding, expected_padding) = if expected_label.len() > found_label.len() {
364 (expected_label.len() - found_label.len(), 0)
366 (0, found_label.len() - expected_label.len())
368 let mut msg: Vec<_> =
369 vec![(format!("{}{} `", " ".repeat(expected_padding), expected_label), Style::NoStyle)];
370 msg.extend(expected.0.iter().map(|x| match *x {
371 StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
372 StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
374 msg.push((format!("`{}\n", expected_extra), Style::NoStyle));
375 msg.push((format!("{}{} `", " ".repeat(found_padding), found_label), Style::NoStyle));
376 msg.extend(found.0.iter().map(|x| match *x {
377 StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
378 StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
380 msg.push((format!("`{}", found_extra), Style::NoStyle));
382 // For now, just attach these as notes.
383 self.highlighted_note(msg);
387 pub fn note_trait_signature(&mut self, name: String, signature: String) -> &mut Self {
388 self.highlighted_note(vec![
389 (format!("`{}` from trait: `", name), Style::NoStyle),
390 (signature, Style::Highlight),
391 ("`".to_string(), Style::NoStyle),
396 /// Add a note attached to this diagnostic.
397 pub fn note(&mut self, msg: impl Into<DiagnosticMessage>) -> &mut Self {
398 self.sub(Level::Note, msg, MultiSpan::new(), None);
402 pub fn highlighted_note<M: Into<DiagnosticMessage>>(
404 msg: Vec<(M, Style)>,
406 self.sub_with_highlights(Level::Note, msg, MultiSpan::new(), None);
410 /// Prints the span with a note above it.
411 /// This is like [`Diagnostic::note()`], but it gets its own span.
412 pub fn note_once(&mut self, msg: impl Into<DiagnosticMessage>) -> &mut Self {
413 self.sub(Level::OnceNote, msg, MultiSpan::new(), None);
417 /// Prints the span with a note above it.
418 /// This is like [`Diagnostic::note()`], but it gets its own span.
419 pub fn span_note<S: Into<MultiSpan>>(
422 msg: impl Into<DiagnosticMessage>,
424 self.sub(Level::Note, msg, sp.into(), None);
428 /// Prints the span with a note above it.
429 /// This is like [`Diagnostic::note()`], but it gets its own span.
430 pub fn span_note_once<S: Into<MultiSpan>>(
433 msg: impl Into<DiagnosticMessage>,
435 self.sub(Level::OnceNote, msg, sp.into(), None);
439 /// Add a warning attached to this diagnostic.
440 pub fn warn(&mut self, msg: impl Into<DiagnosticMessage>) -> &mut Self {
441 self.sub(Level::Warning, msg, MultiSpan::new(), None);
445 /// Prints the span with a warning above it.
446 /// This is like [`Diagnostic::warn()`], but it gets its own span.
447 pub fn span_warn<S: Into<MultiSpan>>(
450 msg: impl Into<DiagnosticMessage>,
452 self.sub(Level::Warning, msg, sp.into(), None);
456 /// Add a help message attached to this diagnostic.
457 pub fn help(&mut self, msg: impl Into<DiagnosticMessage>) -> &mut Self {
458 self.sub(Level::Help, msg, MultiSpan::new(), None);
462 /// Add a help message attached to this diagnostic with a customizable highlighted message.
463 pub fn highlighted_help(&mut self, msg: Vec<(String, Style)>) -> &mut Self {
464 self.sub_with_highlights(Level::Help, msg, MultiSpan::new(), None);
468 /// Prints the span with some help above it.
469 /// This is like [`Diagnostic::help()`], but it gets its own span.
470 pub fn span_help<S: Into<MultiSpan>>(
473 msg: impl Into<DiagnosticMessage>,
475 self.sub(Level::Help, msg, sp.into(), None);
479 /// Help the user upgrade to the latest edition.
480 /// This is factored out to make sure it does the right thing with `Cargo.toml`.
481 pub fn help_use_latest_edition(&mut self) -> &mut Self {
482 if std::env::var_os("CARGO").is_some() {
483 self.help(&format!("set `edition = \"{}\"` in `Cargo.toml`", LATEST_STABLE_EDITION));
485 self.help(&format!("pass `--edition {}` to `rustc`", LATEST_STABLE_EDITION));
487 self.note("for more on editions, read https://doc.rust-lang.org/edition-guide");
491 /// Disallow attaching suggestions this diagnostic.
492 /// Any suggestions attached e.g. with the `span_suggestion_*` methods
493 /// (before and after the call to `disable_suggestions`) will be ignored.
494 pub fn disable_suggestions(&mut self) -> &mut Self {
495 self.suggestions = Err(SuggestionsDisabled);
499 /// Helper for pushing to `self.suggestions`, if available (not disable).
500 fn push_suggestion(&mut self, suggestion: CodeSuggestion) {
501 if let Ok(suggestions) = &mut self.suggestions {
502 suggestions.push(suggestion);
506 /// Show a suggestion that has multiple parts to it.
507 /// In other words, multiple changes need to be applied as part of this suggestion.
508 pub fn multipart_suggestion(
510 msg: impl Into<DiagnosticMessage>,
511 suggestion: Vec<(Span, String)>,
512 applicability: Applicability,
514 self.multipart_suggestion_with_style(
518 SuggestionStyle::ShowCode,
522 /// Show a suggestion that has multiple parts to it, always as it's own subdiagnostic.
523 /// In other words, multiple changes need to be applied as part of this suggestion.
524 pub fn multipart_suggestion_verbose(
526 msg: impl Into<DiagnosticMessage>,
527 suggestion: Vec<(Span, String)>,
528 applicability: Applicability,
530 self.multipart_suggestion_with_style(
534 SuggestionStyle::ShowAlways,
537 /// [`Diagnostic::multipart_suggestion()`] but you can set the [`SuggestionStyle`].
538 pub fn multipart_suggestion_with_style(
540 msg: impl Into<DiagnosticMessage>,
541 suggestion: Vec<(Span, String)>,
542 applicability: Applicability,
543 style: SuggestionStyle,
545 assert!(!suggestion.is_empty());
546 self.push_suggestion(CodeSuggestion {
547 substitutions: vec![Substitution {
550 .map(|(span, snippet)| SubstitutionPart { snippet, span })
560 /// Prints out a message with for a multipart suggestion without showing the suggested code.
562 /// This is intended to be used for suggestions that are obvious in what the changes need to
563 /// be from the message, showing the span label inline would be visually unpleasant
564 /// (marginally overlapping spans or multiline spans) and showing the snippet window wouldn't
565 /// improve understandability.
566 pub fn tool_only_multipart_suggestion(
568 msg: impl Into<DiagnosticMessage>,
569 suggestion: Vec<(Span, String)>,
570 applicability: Applicability,
572 assert!(!suggestion.is_empty());
573 self.push_suggestion(CodeSuggestion {
574 substitutions: vec![Substitution {
577 .map(|(span, snippet)| SubstitutionPart { snippet, span })
581 style: SuggestionStyle::CompletelyHidden,
587 /// Prints out a message with a suggested edit of the code.
589 /// In case of short messages and a simple suggestion, rustc displays it as a label:
592 /// try adding parentheses: `(tup.0).1`
597 /// * should not end in any punctuation (a `:` is added automatically)
598 /// * should not be a question (avoid language like "did you mean")
599 /// * should not contain any phrases like "the following", "as shown", etc.
600 /// * may look like "to do xyz, use" or "to do xyz, use abc"
601 /// * may contain a name of a function, variable, or type, but not whole expressions
603 /// See `CodeSuggestion` for more information.
604 pub fn span_suggestion(
607 msg: impl Into<DiagnosticMessage>,
609 applicability: Applicability,
611 self.span_suggestion_with_style(
616 SuggestionStyle::ShowCode,
621 /// [`Diagnostic::span_suggestion()`] but you can set the [`SuggestionStyle`].
622 pub fn span_suggestion_with_style(
625 msg: impl Into<DiagnosticMessage>,
627 applicability: Applicability,
628 style: SuggestionStyle,
630 self.push_suggestion(CodeSuggestion {
631 substitutions: vec![Substitution {
632 parts: vec![SubstitutionPart { snippet: suggestion, span: sp }],
641 /// Always show the suggested change.
642 pub fn span_suggestion_verbose(
645 msg: impl Into<DiagnosticMessage>,
647 applicability: Applicability,
649 self.span_suggestion_with_style(
654 SuggestionStyle::ShowAlways,
659 /// Prints out a message with multiple suggested edits of the code.
660 /// See also [`Diagnostic::span_suggestion()`].
661 pub fn span_suggestions(
664 msg: impl Into<DiagnosticMessage>,
665 suggestions: impl Iterator<Item = String>,
666 applicability: Applicability,
668 let mut suggestions: Vec<_> = suggestions.collect();
670 let substitutions = suggestions
672 .map(|snippet| Substitution { parts: vec![SubstitutionPart { snippet, span: sp }] })
674 self.push_suggestion(CodeSuggestion {
677 style: SuggestionStyle::ShowCode,
683 /// Prints out a message with multiple suggested edits of the code.
684 /// See also [`Diagnostic::span_suggestion()`].
685 pub fn multipart_suggestions(
687 msg: impl Into<DiagnosticMessage>,
688 suggestions: impl Iterator<Item = Vec<(Span, String)>>,
689 applicability: Applicability,
691 self.push_suggestion(CodeSuggestion {
692 substitutions: suggestions
693 .map(|sugg| Substitution {
696 .map(|(span, snippet)| SubstitutionPart { snippet, span })
701 style: SuggestionStyle::ShowCode,
706 /// Prints out a message with a suggested edit of the code. If the suggestion is presented
707 /// inline, it will only show the message and not the suggestion.
709 /// See `CodeSuggestion` for more information.
710 pub fn span_suggestion_short(
713 msg: impl Into<DiagnosticMessage>,
715 applicability: Applicability,
717 self.span_suggestion_with_style(
722 SuggestionStyle::HideCodeInline,
727 /// Prints out a message for a suggestion without showing the suggested code.
729 /// This is intended to be used for suggestions that are obvious in what the changes need to
730 /// be from the message, showing the span label inline would be visually unpleasant
731 /// (marginally overlapping spans or multiline spans) and showing the snippet window wouldn't
732 /// improve understandability.
733 pub fn span_suggestion_hidden(
736 msg: impl Into<DiagnosticMessage>,
738 applicability: Applicability,
740 self.span_suggestion_with_style(
745 SuggestionStyle::HideCodeAlways,
750 /// Adds a suggestion to the JSON output that will not be shown in the CLI.
752 /// This is intended to be used for suggestions that are *very* obvious in what the changes
753 /// need to be from the message, but we still want other tools to be able to apply them.
754 pub fn tool_only_span_suggestion(
757 msg: impl Into<DiagnosticMessage>,
759 applicability: Applicability,
761 self.span_suggestion_with_style(
766 SuggestionStyle::CompletelyHidden,
771 pub fn set_span<S: Into<MultiSpan>>(&mut self, sp: S) -> &mut Self {
772 self.span = sp.into();
773 if let Some(span) = self.span.primary_span() {
774 self.sort_span = span;
779 pub fn set_is_lint(&mut self) -> &mut Self {
784 pub fn code(&mut self, s: DiagnosticId) -> &mut Self {
789 pub fn clear_code(&mut self) -> &mut Self {
794 pub fn get_code(&self) -> Option<DiagnosticId> {
798 pub fn set_primary_message(&mut self, msg: impl Into<DiagnosticMessage>) -> &mut Self {
799 self.message[0] = (msg.into(), Style::NoStyle);
803 pub fn args(&self) -> &[DiagnosticArg<'static>] {
809 name: impl Into<Cow<'static, str>>,
810 arg: DiagnosticArgValue<'static>,
812 self.args.push((name.into(), arg));
816 pub fn styled_message(&self) -> &Vec<(DiagnosticMessage, Style)> {
820 /// Convenience function for internal use, clients should use one of the
821 /// public methods above.
823 /// Used by `proc_macro_server` for implementing `server::Diagnostic`.
827 message: impl Into<DiagnosticMessage>,
829 render_span: Option<MultiSpan>,
831 let sub = SubDiagnostic {
833 message: vec![(message.into(), Style::NoStyle)],
837 self.children.push(sub);
840 /// Convenience function for internal use, clients should use one of the
841 /// public methods above.
842 fn sub_with_highlights<M: Into<DiagnosticMessage>>(
845 mut message: Vec<(M, Style)>,
847 render_span: Option<MultiSpan>,
849 let message = message.drain(..).map(|m| (m.0.into(), m.1)).collect();
850 let sub = SubDiagnostic { level, message, span, render_span };
851 self.children.push(sub);
854 /// Fields used for Hash, and PartialEq trait
859 &Vec<(DiagnosticMessage, Style)>,
860 &Option<DiagnosticId>,
862 &Result<Vec<CodeSuggestion>, SuggestionsDisabled>,
863 Option<&Vec<SubDiagnostic>>,
871 (if self.is_lint { None } else { Some(&self.children) }),
876 impl Hash for Diagnostic {
877 fn hash<H>(&self, state: &mut H)
881 self.keys().hash(state);
885 impl PartialEq for Diagnostic {
886 fn eq(&self, other: &Self) -> bool {
887 self.keys() == other.keys()