1 use crate::snippet::Style;
2 use crate::Applicability;
3 use crate::CodeSuggestion;
5 use crate::Substitution;
6 use crate::SubstitutionPart;
7 use crate::SuggestionStyle;
8 use rustc_span::{MultiSpan, Span, DUMMY_SP};
12 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
13 pub struct Diagnostic {
15 pub message: Vec<(String, Style)>,
16 pub code: Option<DiagnosticId>,
18 pub children: Vec<SubDiagnostic>,
19 pub suggestions: Vec<CodeSuggestion>,
21 /// This is not used for highlighting or rendering any error message. Rather, it can be used
22 /// as a sort key to sort a buffer of diagnostics. By default, it is the primary span of
23 /// `span` if there is one. Otherwise, it is `DUMMY_SP`.
27 #[derive(Clone, Debug, PartialEq, Eq, Hash, Encodable, Decodable)]
28 pub enum DiagnosticId {
33 /// For example a note attached to an error.
34 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
35 pub struct SubDiagnostic {
37 pub message: Vec<(String, Style)>,
39 pub render_span: Option<MultiSpan>,
42 #[derive(Debug, PartialEq, Eq)]
43 pub struct DiagnosticStyledString(pub Vec<StringPart>);
45 impl DiagnosticStyledString {
46 pub fn new() -> DiagnosticStyledString {
47 DiagnosticStyledString(vec![])
49 pub fn push_normal<S: Into<String>>(&mut self, t: S) {
50 self.0.push(StringPart::Normal(t.into()));
52 pub fn push_highlighted<S: Into<String>>(&mut self, t: S) {
53 self.0.push(StringPart::Highlighted(t.into()));
55 pub fn push<S: Into<String>>(&mut self, t: S, highlight: bool) {
57 self.push_highlighted(t);
62 pub fn normal<S: Into<String>>(t: S) -> DiagnosticStyledString {
63 DiagnosticStyledString(vec![StringPart::Normal(t.into())])
66 pub fn highlighted<S: Into<String>>(t: S) -> DiagnosticStyledString {
67 DiagnosticStyledString(vec![StringPart::Highlighted(t.into())])
70 pub fn content(&self) -> String {
71 self.0.iter().map(|x| x.content()).collect::<String>()
75 #[derive(Debug, PartialEq, Eq)]
82 pub fn content(&self) -> &str {
84 &StringPart::Normal(ref s) | &StringPart::Highlighted(ref s) => s,
90 pub fn new(level: Level, message: &str) -> Self {
91 Diagnostic::new_with_code(level, None, message)
94 pub fn new_with_code(level: Level, code: Option<DiagnosticId>, message: &str) -> Self {
97 message: vec![(message.to_owned(), Style::NoStyle)],
99 span: MultiSpan::new(),
106 pub fn is_error(&self) -> bool {
108 Level::Bug | Level::Fatal | Level::Error | Level::FailureNote => true,
110 Level::Warning | Level::Note | Level::Help | Level::Cancelled => false,
114 /// Cancel the diagnostic (a structured diagnostic must either be emitted or
115 /// canceled or it will panic when dropped).
116 pub fn cancel(&mut self) {
117 self.level = Level::Cancelled;
120 pub fn cancelled(&self) -> bool {
121 self.level == Level::Cancelled
124 /// Set the sorting span.
125 pub fn set_sort_span(&mut self, sp: Span) {
129 /// Adds a span/label to be included in the resulting snippet.
131 /// This is pushed onto the [`MultiSpan`] that was created when the diagnostic
132 /// was first built. That means it will be shown together with the original
133 /// span/label, *not* a span added by one of the `span_{note,warn,help,suggestions}` methods.
135 /// This span is *not* considered a ["primary span"][`MultiSpan`]; only
136 /// the `Span` supplied when creating the diagnostic is primary.
138 /// [`MultiSpan`]: ../rustc_span/struct.MultiSpan.html
139 pub fn span_label<T: Into<String>>(&mut self, span: Span, label: T) -> &mut Self {
140 self.span.push_span_label(span, label.into());
144 pub fn replace_span_with(&mut self, after: Span) -> &mut Self {
145 let before = self.span.clone();
146 self.set_span(after);
147 for span_label in before.span_labels() {
148 if let Some(label) = span_label.label {
149 self.span_label(after, label);
155 pub fn note_expected_found(
157 expected_label: &dyn fmt::Display,
158 expected: DiagnosticStyledString,
159 found_label: &dyn fmt::Display,
160 found: DiagnosticStyledString,
162 self.note_expected_found_extra(expected_label, expected, found_label, found, &"", &"")
165 pub fn note_unsuccessfull_coercion(
167 expected: DiagnosticStyledString,
168 found: DiagnosticStyledString,
170 let mut msg: Vec<_> =
171 vec![("required when trying to coerce from type `".to_string(), Style::NoStyle)];
172 msg.extend(expected.0.iter().map(|x| match *x {
173 StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
174 StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
176 msg.push(("` to type '".to_string(), Style::NoStyle));
177 msg.extend(found.0.iter().map(|x| match *x {
178 StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
179 StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
181 msg.push(("`".to_string(), Style::NoStyle));
183 // For now, just attach these as notes
184 self.highlighted_note(msg);
188 pub fn note_expected_found_extra(
190 expected_label: &dyn fmt::Display,
191 expected: DiagnosticStyledString,
192 found_label: &dyn fmt::Display,
193 found: DiagnosticStyledString,
194 expected_extra: &dyn fmt::Display,
195 found_extra: &dyn fmt::Display,
197 let expected_label = expected_label.to_string();
198 let expected_label = if expected_label.is_empty() {
199 "expected".to_string()
201 format!("expected {}", expected_label)
203 let found_label = found_label.to_string();
204 let found_label = if found_label.is_empty() {
207 format!("found {}", found_label)
209 let (found_padding, expected_padding) = if expected_label.len() > found_label.len() {
210 (expected_label.len() - found_label.len(), 0)
212 (0, found_label.len() - expected_label.len())
214 let mut msg: Vec<_> =
215 vec![(format!("{}{} `", " ".repeat(expected_padding), expected_label), Style::NoStyle)];
216 msg.extend(expected.0.iter().map(|x| match *x {
217 StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
218 StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
220 msg.push((format!("`{}\n", expected_extra), Style::NoStyle));
221 msg.push((format!("{}{} `", " ".repeat(found_padding), found_label), Style::NoStyle));
222 msg.extend(found.0.iter().map(|x| match *x {
223 StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
224 StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
226 msg.push((format!("`{}", found_extra), Style::NoStyle));
228 // For now, just attach these as notes.
229 self.highlighted_note(msg);
233 pub fn note_trait_signature(&mut self, name: String, signature: String) -> &mut Self {
234 self.highlighted_note(vec![
235 (format!("`{}` from trait: `", name), Style::NoStyle),
236 (signature, Style::Highlight),
237 ("`".to_string(), Style::NoStyle),
242 pub fn note(&mut self, msg: &str) -> &mut Self {
243 self.sub(Level::Note, msg, MultiSpan::new(), None);
247 pub fn highlighted_note(&mut self, msg: Vec<(String, Style)>) -> &mut Self {
248 self.sub_with_highlights(Level::Note, msg, MultiSpan::new(), None);
252 /// Prints the span with a note above it.
253 pub fn span_note<S: Into<MultiSpan>>(&mut self, sp: S, msg: &str) -> &mut Self {
254 self.sub(Level::Note, msg, sp.into(), None);
258 pub fn warn(&mut self, msg: &str) -> &mut Self {
259 self.sub(Level::Warning, msg, MultiSpan::new(), None);
263 /// Prints the span with a warn above it.
264 pub fn span_warn<S: Into<MultiSpan>>(&mut self, sp: S, msg: &str) -> &mut Self {
265 self.sub(Level::Warning, msg, sp.into(), None);
269 pub fn help(&mut self, msg: &str) -> &mut Self {
270 self.sub(Level::Help, msg, MultiSpan::new(), None);
274 /// Prints the span with some help above it.
275 pub fn span_help<S: Into<MultiSpan>>(&mut self, sp: S, msg: &str) -> &mut Self {
276 self.sub(Level::Help, msg, sp.into(), None);
280 pub fn multipart_suggestion(
283 suggestion: Vec<(Span, String)>,
284 applicability: Applicability,
286 self.suggestions.push(CodeSuggestion {
287 substitutions: vec![Substitution {
290 .map(|(span, snippet)| SubstitutionPart { snippet, span })
294 style: SuggestionStyle::ShowCode,
300 pub fn multipart_suggestions(
303 suggestions: Vec<Vec<(Span, String)>>,
304 applicability: Applicability,
306 self.suggestions.push(CodeSuggestion {
307 substitutions: suggestions
309 .map(|suggestion| Substitution {
312 .map(|(span, snippet)| SubstitutionPart { snippet, span })
317 style: SuggestionStyle::ShowCode,
323 /// Prints out a message with for a multipart suggestion without showing the suggested code.
325 /// This is intended to be used for suggestions that are obvious in what the changes need to
326 /// be from the message, showing the span label inline would be visually unpleasant
327 /// (marginally overlapping spans or multiline spans) and showing the snippet window wouldn't
328 /// improve understandability.
329 pub fn tool_only_multipart_suggestion(
332 suggestion: Vec<(Span, String)>,
333 applicability: Applicability,
335 self.suggestions.push(CodeSuggestion {
336 substitutions: vec![Substitution {
339 .map(|(span, snippet)| SubstitutionPart { snippet, span })
343 style: SuggestionStyle::CompletelyHidden,
349 /// Prints out a message with a suggested edit of the code.
351 /// In case of short messages and a simple suggestion, rustc displays it as a label:
354 /// try adding parentheses: `(tup.0).1`
359 /// * should not end in any punctuation (a `:` is added automatically)
360 /// * should not be a question (avoid language like "did you mean")
361 /// * should not contain any phrases like "the following", "as shown", etc.
362 /// * may look like "to do xyz, use" or "to do xyz, use abc"
363 /// * may contain a name of a function, variable, or type, but not whole expressions
365 /// See `CodeSuggestion` for more information.
366 pub fn span_suggestion(
371 applicability: Applicability,
373 self.span_suggestion_with_style(
378 SuggestionStyle::ShowCode,
383 pub fn span_suggestion_with_style(
388 applicability: Applicability,
389 style: SuggestionStyle,
391 self.suggestions.push(CodeSuggestion {
392 substitutions: vec![Substitution {
393 parts: vec![SubstitutionPart { snippet: suggestion, span: sp }],
402 pub fn span_suggestion_verbose(
407 applicability: Applicability,
409 self.span_suggestion_with_style(
414 SuggestionStyle::ShowAlways,
419 /// Prints out a message with multiple suggested edits of the code.
420 pub fn span_suggestions(
424 suggestions: impl Iterator<Item = String>,
425 applicability: Applicability,
427 self.suggestions.push(CodeSuggestion {
428 substitutions: suggestions
429 .map(|snippet| Substitution { parts: vec![SubstitutionPart { snippet, span: sp }] })
432 style: SuggestionStyle::ShowCode,
438 /// Prints out a message with a suggested edit of the code. If the suggestion is presented
439 /// inline, it will only show the message and not the suggestion.
441 /// See `CodeSuggestion` for more information.
442 pub fn span_suggestion_short(
447 applicability: Applicability,
449 self.span_suggestion_with_style(
454 SuggestionStyle::HideCodeInline,
459 /// Prints out a message with for a suggestion without showing the suggested code.
461 /// This is intended to be used for suggestions that are obvious in what the changes need to
462 /// be from the message, showing the span label inline would be visually unpleasant
463 /// (marginally overlapping spans or multiline spans) and showing the snippet window wouldn't
464 /// improve understandability.
465 pub fn span_suggestion_hidden(
470 applicability: Applicability,
472 self.span_suggestion_with_style(
477 SuggestionStyle::HideCodeAlways,
482 /// Adds a suggestion to the json output, but otherwise remains silent/undisplayed in the cli.
484 /// This is intended to be used for suggestions that are *very* obvious in what the changes
485 /// need to be from the message, but we still want other tools to be able to apply them.
486 pub fn tool_only_span_suggestion(
491 applicability: Applicability,
493 self.span_suggestion_with_style(
498 SuggestionStyle::CompletelyHidden,
503 pub fn set_span<S: Into<MultiSpan>>(&mut self, sp: S) -> &mut Self {
504 self.span = sp.into();
505 if let Some(span) = self.span.primary_span() {
506 self.sort_span = span;
511 pub fn code(&mut self, s: DiagnosticId) -> &mut Self {
516 pub fn clear_code(&mut self) -> &mut Self {
521 pub fn get_code(&self) -> Option<DiagnosticId> {
525 pub fn set_primary_message<M: Into<String>>(&mut self, msg: M) -> &mut Self {
526 self.message[0] = (msg.into(), Style::NoStyle);
530 pub fn message(&self) -> String {
531 self.message.iter().map(|i| i.0.as_str()).collect::<String>()
534 pub fn styled_message(&self) -> &Vec<(String, Style)> {
538 /// Used by a lint. Copies over all details *but* the "main
540 pub fn copy_details_not_message(&mut self, from: &Diagnostic) {
541 self.span = from.span.clone();
542 self.code = from.code.clone();
543 self.children.extend(from.children.iter().cloned())
546 /// Convenience function for internal use, clients should use one of the
547 /// public methods above.
553 render_span: Option<MultiSpan>,
555 let sub = SubDiagnostic {
557 message: vec![(message.to_owned(), Style::NoStyle)],
561 self.children.push(sub);
564 /// Convenience function for internal use, clients should use one of the
565 /// public methods above.
566 fn sub_with_highlights(
569 message: Vec<(String, Style)>,
571 render_span: Option<MultiSpan>,
573 let sub = SubDiagnostic { level, message, span, render_span };
574 self.children.push(sub);
579 pub fn message(&self) -> String {
580 self.message.iter().map(|i| i.0.as_str()).collect::<String>()
583 pub fn styled_message(&self) -> &Vec<(String, Style)> {