1 use crate::snippet::Style;
2 use crate::CodeSuggestion;
4 use crate::Substitution;
5 use crate::SubstitutionPart;
6 use crate::SuggestionStyle;
7 use crate::ToolMetadata;
8 use rustc_lint_defs::Applicability;
9 use rustc_serialize::json::Json;
10 use rustc_span::edition::LATEST_STABLE_EDITION;
11 use rustc_span::{MultiSpan, Span, DUMMY_SP};
13 use std::hash::{Hash, Hasher};
15 /// Error type for `Diagnostic`'s `suggestions` field, indicating that
16 /// `.disable_suggestions()` was called on the `Diagnostic`.
17 #[derive(Clone, Debug, PartialEq, Eq, Hash, Encodable, Decodable)]
18 pub struct SuggestionsDisabled;
21 #[derive(Clone, Debug, Encodable, Decodable)]
22 pub struct Diagnostic {
23 // NOTE(eddyb) this is private to disallow arbitrary after-the-fact changes,
24 // outside of what methods in this crate themselves allow.
27 pub message: Vec<(String, Style)>,
28 pub code: Option<DiagnosticId>,
30 pub children: Vec<SubDiagnostic>,
31 pub suggestions: Result<Vec<CodeSuggestion>, SuggestionsDisabled>,
33 /// This is not used for highlighting or rendering any error message. Rather, it can be used
34 /// as a sort key to sort a buffer of diagnostics. By default, it is the primary span of
35 /// `span` if there is one. Otherwise, it is `DUMMY_SP`.
38 /// If diagnostic is from Lint, custom hash function ignores notes
39 /// otherwise hash is based on the all the fields
43 #[derive(Clone, Debug, PartialEq, Eq, Hash, Encodable, Decodable)]
44 pub enum DiagnosticId {
46 Lint { name: String, has_future_breakage: bool, is_force_warn: bool },
49 /// A "sub"-diagnostic attached to a parent diagnostic.
50 /// For example, a note attached to an error.
51 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
52 pub struct SubDiagnostic {
54 pub message: Vec<(String, Style)>,
56 pub render_span: Option<MultiSpan>,
59 #[derive(Debug, PartialEq, Eq)]
60 pub struct DiagnosticStyledString(pub Vec<StringPart>);
62 impl DiagnosticStyledString {
63 pub fn new() -> DiagnosticStyledString {
64 DiagnosticStyledString(vec![])
66 pub fn push_normal<S: Into<String>>(&mut self, t: S) {
67 self.0.push(StringPart::Normal(t.into()));
69 pub fn push_highlighted<S: Into<String>>(&mut self, t: S) {
70 self.0.push(StringPart::Highlighted(t.into()));
72 pub fn push<S: Into<String>>(&mut self, t: S, highlight: bool) {
74 self.push_highlighted(t);
79 pub fn normal<S: Into<String>>(t: S) -> DiagnosticStyledString {
80 DiagnosticStyledString(vec![StringPart::Normal(t.into())])
83 pub fn highlighted<S: Into<String>>(t: S) -> DiagnosticStyledString {
84 DiagnosticStyledString(vec![StringPart::Highlighted(t.into())])
87 pub fn content(&self) -> String {
88 self.0.iter().map(|x| x.content()).collect::<String>()
92 #[derive(Debug, PartialEq, Eq)]
99 pub fn content(&self) -> &str {
101 &StringPart::Normal(ref s) | &StringPart::Highlighted(ref s) => s,
107 pub fn new(level: Level, message: &str) -> Self {
108 Diagnostic::new_with_code(level, None, message)
111 pub fn new_with_code(level: Level, code: Option<DiagnosticId>, message: &str) -> Self {
114 message: vec![(message.to_owned(), Style::NoStyle)],
116 span: MultiSpan::new(),
118 suggestions: Ok(vec![]),
125 pub fn level(&self) -> Level {
129 pub fn is_error(&self) -> bool {
134 | Level::Error { .. }
135 | Level::FailureNote => true,
137 Level::Warning | Level::Note | Level::Help | Level::Allow | Level::Expect(_) => false,
141 pub fn has_future_breakage(&self) -> bool {
143 Some(DiagnosticId::Lint { has_future_breakage, .. }) => has_future_breakage,
148 pub fn is_force_warn(&self) -> bool {
150 Some(DiagnosticId::Lint { is_force_warn, .. }) => is_force_warn,
155 /// Delay emission of this diagnostic as a bug.
157 /// This can be useful in contexts where an error indicates a bug but
158 /// typically this only happens when other compilation errors have already
159 /// happened. In those cases this can be used to defer emission of this
160 /// diagnostic as a bug in the compiler only if no other errors have been
163 /// In the meantime, though, callsites are required to deal with the "bug"
164 /// locally in whichever way makes the most sense.
166 pub fn downgrade_to_delayed_bug(&mut self) -> &mut Self {
169 "downgrade_to_delayed_bug: cannot downgrade {:?} to DelayedBug: not an error",
172 self.level = Level::DelayedBug;
177 /// Adds a span/label to be included in the resulting snippet.
179 /// This is pushed onto the [`MultiSpan`] that was created when the diagnostic
180 /// was first built. That means it will be shown together with the original
181 /// span/label, *not* a span added by one of the `span_{note,warn,help,suggestions}` methods.
183 /// This span is *not* considered a ["primary span"][`MultiSpan`]; only
184 /// the `Span` supplied when creating the diagnostic is primary.
185 pub fn span_label<T: Into<String>>(&mut self, span: Span, label: T) -> &mut Self {
186 self.span.push_span_label(span, label.into());
190 /// Labels all the given spans with the provided label.
191 /// See [`Self::span_label()`] for more information.
194 spans: impl IntoIterator<Item = Span>,
195 label: impl AsRef<str>,
197 let label = label.as_ref();
199 self.span_label(span, label);
204 pub fn replace_span_with(&mut self, after: Span) -> &mut Self {
205 let before = self.span.clone();
206 self.set_span(after);
207 for span_label in before.span_labels() {
208 if let Some(label) = span_label.label {
209 self.span_label(after, label);
215 pub fn note_expected_found(
217 expected_label: &dyn fmt::Display,
218 expected: DiagnosticStyledString,
219 found_label: &dyn fmt::Display,
220 found: DiagnosticStyledString,
222 self.note_expected_found_extra(expected_label, expected, found_label, found, &"", &"")
225 pub fn note_unsuccessful_coercion(
227 expected: DiagnosticStyledString,
228 found: DiagnosticStyledString,
230 let mut msg: Vec<_> =
231 vec![("required when trying to coerce from type `".to_string(), Style::NoStyle)];
232 msg.extend(expected.0.iter().map(|x| match *x {
233 StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
234 StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
236 msg.push(("` to type '".to_string(), Style::NoStyle));
237 msg.extend(found.0.iter().map(|x| match *x {
238 StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
239 StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
241 msg.push(("`".to_string(), Style::NoStyle));
243 // For now, just attach these as notes
244 self.highlighted_note(msg);
248 pub fn note_expected_found_extra(
250 expected_label: &dyn fmt::Display,
251 expected: DiagnosticStyledString,
252 found_label: &dyn fmt::Display,
253 found: DiagnosticStyledString,
254 expected_extra: &dyn fmt::Display,
255 found_extra: &dyn fmt::Display,
257 let expected_label = expected_label.to_string();
258 let expected_label = if expected_label.is_empty() {
259 "expected".to_string()
261 format!("expected {}", expected_label)
263 let found_label = found_label.to_string();
264 let found_label = if found_label.is_empty() {
267 format!("found {}", found_label)
269 let (found_padding, expected_padding) = if expected_label.len() > found_label.len() {
270 (expected_label.len() - found_label.len(), 0)
272 (0, found_label.len() - expected_label.len())
274 let mut msg: Vec<_> =
275 vec![(format!("{}{} `", " ".repeat(expected_padding), expected_label), Style::NoStyle)];
276 msg.extend(expected.0.iter().map(|x| match *x {
277 StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
278 StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
280 msg.push((format!("`{}\n", expected_extra), Style::NoStyle));
281 msg.push((format!("{}{} `", " ".repeat(found_padding), found_label), Style::NoStyle));
282 msg.extend(found.0.iter().map(|x| match *x {
283 StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
284 StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
286 msg.push((format!("`{}", found_extra), Style::NoStyle));
288 // For now, just attach these as notes.
289 self.highlighted_note(msg);
293 pub fn note_trait_signature(&mut self, name: String, signature: String) -> &mut Self {
294 self.highlighted_note(vec![
295 (format!("`{}` from trait: `", name), Style::NoStyle),
296 (signature, Style::Highlight),
297 ("`".to_string(), Style::NoStyle),
302 /// Add a note attached to this diagnostic.
303 pub fn note(&mut self, msg: &str) -> &mut Self {
304 self.sub(Level::Note, msg, MultiSpan::new(), None);
308 pub fn highlighted_note(&mut self, msg: Vec<(String, Style)>) -> &mut Self {
309 self.sub_with_highlights(Level::Note, msg, MultiSpan::new(), None);
313 /// Prints the span with a note above it.
314 /// This is like [`Diagnostic::note()`], but it gets its own span.
315 pub fn span_note<S: Into<MultiSpan>>(&mut self, sp: S, msg: &str) -> &mut Self {
316 self.sub(Level::Note, msg, sp.into(), None);
320 /// Add a warning attached to this diagnostic.
321 pub fn warn(&mut self, msg: &str) -> &mut Self {
322 self.sub(Level::Warning, msg, MultiSpan::new(), None);
326 /// Prints the span with a warning above it.
327 /// This is like [`Diagnostic::warn()`], but it gets its own span.
328 pub fn span_warn<S: Into<MultiSpan>>(&mut self, sp: S, msg: &str) -> &mut Self {
329 self.sub(Level::Warning, msg, sp.into(), None);
333 /// Add a help message attached to this diagnostic.
334 pub fn help(&mut self, msg: &str) -> &mut Self {
335 self.sub(Level::Help, msg, MultiSpan::new(), None);
339 /// Prints the span with some help above it.
340 /// This is like [`Diagnostic::help()`], but it gets its own span.
341 pub fn span_help<S: Into<MultiSpan>>(&mut self, sp: S, msg: &str) -> &mut Self {
342 self.sub(Level::Help, msg, sp.into(), None);
346 /// Help the user upgrade to the latest edition.
347 /// This is factored out to make sure it does the right thing with `Cargo.toml`.
348 pub fn help_use_latest_edition(&mut self) -> &mut Self {
349 if std::env::var_os("CARGO").is_some() {
350 self.help(&format!("set `edition = \"{}\"` in `Cargo.toml`", LATEST_STABLE_EDITION));
352 self.help(&format!("pass `--edition {}` to `rustc`", LATEST_STABLE_EDITION));
354 self.note("for more on editions, read https://doc.rust-lang.org/edition-guide");
358 /// Disallow attaching suggestions this diagnostic.
359 /// Any suggestions attached e.g. with the `span_suggestion_*` methods
360 /// (before and after the call to `disable_suggestions`) will be ignored.
361 pub fn disable_suggestions(&mut self) -> &mut Self {
362 self.suggestions = Err(SuggestionsDisabled);
366 /// Helper for pushing to `self.suggestions`, if available (not disable).
367 fn push_suggestion(&mut self, suggestion: CodeSuggestion) {
368 if let Ok(suggestions) = &mut self.suggestions {
369 suggestions.push(suggestion);
373 /// Show a suggestion that has multiple parts to it.
374 /// In other words, multiple changes need to be applied as part of this suggestion.
375 pub fn multipart_suggestion(
378 suggestion: Vec<(Span, String)>,
379 applicability: Applicability,
381 self.multipart_suggestion_with_style(
385 SuggestionStyle::ShowCode,
389 /// Show a suggestion that has multiple parts to it, always as it's own subdiagnostic.
390 /// In other words, multiple changes need to be applied as part of this suggestion.
391 pub fn multipart_suggestion_verbose(
394 suggestion: Vec<(Span, String)>,
395 applicability: Applicability,
397 self.multipart_suggestion_with_style(
401 SuggestionStyle::ShowAlways,
404 /// [`Diagnostic::multipart_suggestion()`] but you can set the [`SuggestionStyle`].
405 pub fn multipart_suggestion_with_style(
408 suggestion: Vec<(Span, String)>,
409 applicability: Applicability,
410 style: SuggestionStyle,
412 assert!(!suggestion.is_empty());
413 self.push_suggestion(CodeSuggestion {
414 substitutions: vec![Substitution {
417 .map(|(span, snippet)| SubstitutionPart { snippet, span })
423 tool_metadata: Default::default(),
428 /// Prints out a message with for a multipart suggestion without showing the suggested code.
430 /// This is intended to be used for suggestions that are obvious in what the changes need to
431 /// be from the message, showing the span label inline would be visually unpleasant
432 /// (marginally overlapping spans or multiline spans) and showing the snippet window wouldn't
433 /// improve understandability.
434 pub fn tool_only_multipart_suggestion(
437 suggestion: Vec<(Span, String)>,
438 applicability: Applicability,
440 assert!(!suggestion.is_empty());
441 self.push_suggestion(CodeSuggestion {
442 substitutions: vec![Substitution {
445 .map(|(span, snippet)| SubstitutionPart { snippet, span })
449 style: SuggestionStyle::CompletelyHidden,
451 tool_metadata: Default::default(),
456 /// Prints out a message with a suggested edit of the code.
458 /// In case of short messages and a simple suggestion, rustc displays it as a label:
461 /// try adding parentheses: `(tup.0).1`
466 /// * should not end in any punctuation (a `:` is added automatically)
467 /// * should not be a question (avoid language like "did you mean")
468 /// * should not contain any phrases like "the following", "as shown", etc.
469 /// * may look like "to do xyz, use" or "to do xyz, use abc"
470 /// * may contain a name of a function, variable, or type, but not whole expressions
472 /// See `CodeSuggestion` for more information.
473 pub fn span_suggestion(
478 applicability: Applicability,
480 self.span_suggestion_with_style(
485 SuggestionStyle::ShowCode,
490 /// [`Diagnostic::span_suggestion()`] but you can set the [`SuggestionStyle`].
491 pub fn span_suggestion_with_style(
496 applicability: Applicability,
497 style: SuggestionStyle,
499 self.push_suggestion(CodeSuggestion {
500 substitutions: vec![Substitution {
501 parts: vec![SubstitutionPart { snippet: suggestion, span: sp }],
506 tool_metadata: Default::default(),
511 /// Always show the suggested change.
512 pub fn span_suggestion_verbose(
517 applicability: Applicability,
519 self.span_suggestion_with_style(
524 SuggestionStyle::ShowAlways,
529 /// Prints out a message with multiple suggested edits of the code.
530 /// See also [`Diagnostic::span_suggestion()`].
531 pub fn span_suggestions(
535 suggestions: impl Iterator<Item = String>,
536 applicability: Applicability,
538 let mut suggestions: Vec<_> = suggestions.collect();
540 let substitutions = suggestions
542 .map(|snippet| Substitution { parts: vec![SubstitutionPart { snippet, span: sp }] })
544 self.push_suggestion(CodeSuggestion {
547 style: SuggestionStyle::ShowCode,
549 tool_metadata: Default::default(),
554 /// Prints out a message with multiple suggested edits of the code.
555 /// See also [`Diagnostic::span_suggestion()`].
556 pub fn multipart_suggestions(
559 suggestions: impl Iterator<Item = Vec<(Span, String)>>,
560 applicability: Applicability,
562 self.push_suggestion(CodeSuggestion {
563 substitutions: suggestions
564 .map(|sugg| Substitution {
567 .map(|(span, snippet)| SubstitutionPart { snippet, span })
572 style: SuggestionStyle::ShowCode,
574 tool_metadata: Default::default(),
578 /// Prints out a message with a suggested edit of the code. If the suggestion is presented
579 /// inline, it will only show the message and not the suggestion.
581 /// See `CodeSuggestion` for more information.
582 pub fn span_suggestion_short(
587 applicability: Applicability,
589 self.span_suggestion_with_style(
594 SuggestionStyle::HideCodeInline,
599 /// Prints out a message for a suggestion without showing the suggested code.
601 /// This is intended to be used for suggestions that are obvious in what the changes need to
602 /// be from the message, showing the span label inline would be visually unpleasant
603 /// (marginally overlapping spans or multiline spans) and showing the snippet window wouldn't
604 /// improve understandability.
605 pub fn span_suggestion_hidden(
610 applicability: Applicability,
612 self.span_suggestion_with_style(
617 SuggestionStyle::HideCodeAlways,
622 /// Adds a suggestion to the JSON output that will not be shown in the CLI.
624 /// This is intended to be used for suggestions that are *very* obvious in what the changes
625 /// need to be from the message, but we still want other tools to be able to apply them.
626 pub fn tool_only_span_suggestion(
631 applicability: Applicability,
633 self.span_suggestion_with_style(
638 SuggestionStyle::CompletelyHidden,
643 /// Adds a suggestion intended only for a tool. The intent is that the metadata encodes
644 /// the suggestion in a tool-specific way, as it may not even directly involve Rust code.
645 pub fn tool_only_suggestion_with_metadata(
648 applicability: Applicability,
651 self.push_suggestion(CodeSuggestion {
652 substitutions: vec![],
654 style: SuggestionStyle::CompletelyHidden,
656 tool_metadata: ToolMetadata::new(tool_metadata),
660 pub fn set_span<S: Into<MultiSpan>>(&mut self, sp: S) -> &mut Self {
661 self.span = sp.into();
662 if let Some(span) = self.span.primary_span() {
663 self.sort_span = span;
668 pub fn set_is_lint(&mut self) -> &mut Self {
673 pub fn code(&mut self, s: DiagnosticId) -> &mut Self {
678 pub fn clear_code(&mut self) -> &mut Self {
683 pub fn get_code(&self) -> Option<DiagnosticId> {
687 pub fn set_primary_message<M: Into<String>>(&mut self, msg: M) -> &mut Self {
688 self.message[0] = (msg.into(), Style::NoStyle);
692 pub fn message(&self) -> String {
693 self.message.iter().map(|i| i.0.as_str()).collect::<String>()
696 pub fn styled_message(&self) -> &Vec<(String, Style)> {
700 /// Convenience function for internal use, clients should use one of the
701 /// public methods above.
703 /// Used by `proc_macro_server` for implementing `server::Diagnostic`.
709 render_span: Option<MultiSpan>,
711 let sub = SubDiagnostic {
713 message: vec![(message.to_owned(), Style::NoStyle)],
717 self.children.push(sub);
720 /// Convenience function for internal use, clients should use one of the
721 /// public methods above.
722 fn sub_with_highlights(
725 message: Vec<(String, Style)>,
727 render_span: Option<MultiSpan>,
729 let sub = SubDiagnostic { level, message, span, render_span };
730 self.children.push(sub);
733 /// Fields used for Hash, and PartialEq trait
738 &Vec<(String, Style)>,
739 &Option<DiagnosticId>,
741 &Result<Vec<CodeSuggestion>, SuggestionsDisabled>,
742 Option<&Vec<SubDiagnostic>>,
750 (if self.is_lint { None } else { Some(&self.children) }),
755 impl Hash for Diagnostic {
756 fn hash<H>(&self, state: &mut H)
760 self.keys().hash(state);
764 impl PartialEq for Diagnostic {
765 fn eq(&self, other: &Self) -> bool {
766 self.keys() == other.keys()
771 pub fn message(&self) -> String {
772 self.message.iter().map(|i| i.0.as_str()).collect::<String>()
775 pub fn styled_message(&self) -> &Vec<(String, Style)> {