1 use crate::CodeSuggestion;
2 use crate::SuggestionStyle;
3 use crate::SubstitutionPart;
4 use crate::Substitution;
5 use crate::Applicability;
7 use crate::snippet::Style;
9 use syntax_pos::{MultiSpan, Span, DUMMY_SP};
12 #[derive(Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
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, RustcEncodable, RustcDecodable)]
28 pub enum DiagnosticId {
33 /// For example a note attached to an error.
34 #[derive(Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
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 normal<S: Into<String>>(t: S) -> DiagnosticStyledString {
56 DiagnosticStyledString(vec![StringPart::Normal(t.into())])
59 pub fn highlighted<S: Into<String>>(t: S) -> DiagnosticStyledString {
60 DiagnosticStyledString(vec![StringPart::Highlighted(t.into())])
63 pub fn content(&self) -> String {
64 self.0.iter().map(|x| x.content()).collect::<String>()
68 #[derive(Debug, PartialEq, Eq)]
75 pub fn content(&self) -> &str {
77 &StringPart::Normal(ref s) | & StringPart::Highlighted(ref s) => s
83 pub fn new(level: Level, message: &str) -> Self {
84 Diagnostic::new_with_code(level, None, message)
87 pub fn new_with_code(level: Level, code: Option<DiagnosticId>, message: &str) -> Self {
90 message: vec![(message.to_owned(), Style::NoStyle)],
92 span: MultiSpan::new(),
99 pub fn is_error(&self) -> bool {
104 Level::FailureNote => {
111 Level::Cancelled => {
117 /// Cancel the diagnostic (a structured diagnostic must either be emitted or
118 /// canceled or it will panic when dropped).
119 pub fn cancel(&mut self) {
120 self.level = Level::Cancelled;
123 pub fn cancelled(&self) -> bool {
124 self.level == Level::Cancelled
127 /// Set the sorting span.
128 pub fn set_sort_span(&mut self, sp: Span) {
132 /// Adds a span/label to be included in the resulting snippet.
133 /// This label will be shown together with the original span/label used when creating the
134 /// diagnostic, *not* a span added by one of the `span_*` methods.
136 /// This is pushed onto the `MultiSpan` that was created when the
137 /// diagnostic was first built. If you don't call this function at
138 /// all, and you just supplied a `Span` to create the diagnostic,
139 /// then the snippet will just include that `Span`, which is
140 /// called the primary span.
141 pub fn span_label<T: Into<String>>(&mut self, span: Span, label: T) -> &mut Self {
142 self.span.push_span_label(span, label.into());
146 pub fn replace_span_with(&mut self, after: Span) -> &mut Self {
147 let before = self.span.clone();
148 self.set_span(after);
149 for span_label in before.span_labels() {
150 if let Some(label) = span_label.label {
151 self.span_label(after, label);
157 pub fn note_expected_found(
159 expected_label: &dyn fmt::Display,
160 expected: DiagnosticStyledString,
161 found_label: &dyn fmt::Display,
162 found: DiagnosticStyledString,
164 self.note_expected_found_extra(expected_label, expected, found_label, found, &"", &"")
167 pub fn note_unsuccessfull_coercion(
169 expected: DiagnosticStyledString,
170 found: DiagnosticStyledString,
172 let mut msg: Vec<_> =
173 vec![(format!("required when trying to coerce from type `"),
175 msg.extend(expected.0.iter()
177 StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
178 StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
180 msg.push((format!("` to type '"), Style::NoStyle));
181 msg.extend(found.0.iter()
183 StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
184 StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
186 msg.push((format!("`"), Style::NoStyle));
188 // For now, just attach these as notes
189 self.highlighted_note(msg);
193 pub fn note_expected_found_extra(
195 expected_label: &dyn fmt::Display,
196 expected: DiagnosticStyledString,
197 found_label: &dyn fmt::Display,
198 found: DiagnosticStyledString,
199 expected_extra: &dyn fmt::Display,
200 found_extra: &dyn fmt::Display,
202 let expected_label = format!("expected {}", expected_label);
203 let found_label = format!("found {}", found_label);
204 let (found_padding, expected_padding) = if expected_label.len() > found_label.len() {
205 (expected_label.len() - found_label.len(), 0)
207 (0, found_label.len() - expected_label.len())
209 let mut msg: Vec<_> = vec![(
210 format!("{}{} `", " ".repeat(expected_padding), expected_label),
213 msg.extend(expected.0.iter()
215 StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
216 StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
218 msg.push((format!("`{}\n", expected_extra), Style::NoStyle));
219 msg.push((format!("{}{} `", " ".repeat(found_padding), found_label), Style::NoStyle));
220 msg.extend(found.0.iter()
222 StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
223 StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
225 msg.push((format!("`{}", found_extra), Style::NoStyle));
227 // For now, just attach these as notes.
228 self.highlighted_note(msg);
232 pub fn note_trait_signature(&mut self, name: String, signature: String) -> &mut Self {
233 self.highlighted_note(vec![
234 (format!("`{}` from trait: `", name), Style::NoStyle),
235 (signature, Style::Highlight),
236 ("`".to_string(), Style::NoStyle)]);
240 pub fn note(&mut self, msg: &str) -> &mut Self {
241 self.sub(Level::Note, msg, MultiSpan::new(), None);
245 pub fn highlighted_note(&mut self, msg: Vec<(String, Style)>) -> &mut Self {
246 self.sub_with_highlights(Level::Note, msg, MultiSpan::new(), None);
250 /// Prints the span with a note above it.
251 pub fn span_note<S: Into<MultiSpan>>(&mut self,
255 self.sub(Level::Note, msg, sp.into(), None);
259 pub fn warn(&mut self, msg: &str) -> &mut Self {
260 self.sub(Level::Warning, msg, MultiSpan::new(), None);
264 /// Prints the span with a warn above it.
265 pub fn span_warn<S: Into<MultiSpan>>(&mut self,
269 self.sub(Level::Warning, msg, sp.into(), None);
273 pub fn help(&mut self , msg: &str) -> &mut Self {
274 self.sub(Level::Help, msg, MultiSpan::new(), None);
278 /// Prints the span with some help above it.
279 pub fn span_help<S: Into<MultiSpan>>(&mut self,
283 self.sub(Level::Help, msg, sp.into(), None);
287 pub fn multipart_suggestion(
290 suggestion: Vec<(Span, String)>,
291 applicability: Applicability,
293 self.suggestions.push(CodeSuggestion {
294 substitutions: vec![Substitution {
297 .map(|(span, snippet)| SubstitutionPart { snippet, span })
301 style: SuggestionStyle::ShowCode,
307 /// Prints out a message with for a multipart suggestion without showing the suggested code.
309 /// This is intended to be used for suggestions that are obvious in what the changes need to
310 /// be from the message, showing the span label inline would be visually unpleasant
311 /// (marginally overlapping spans or multiline spans) and showing the snippet window wouldn't
312 /// improve understandability.
313 pub fn tool_only_multipart_suggestion(
316 suggestion: Vec<(Span, String)>,
317 applicability: Applicability,
319 self.suggestions.push(CodeSuggestion {
320 substitutions: vec![Substitution {
323 .map(|(span, snippet)| SubstitutionPart { snippet, span })
327 style: SuggestionStyle::CompletelyHidden,
333 /// Prints out a message with a suggested edit of the code.
335 /// In case of short messages and a simple suggestion, rustc displays it as a label:
338 /// try adding parentheses: `(tup.0).1`
343 /// * should not end in any punctuation (a `:` is added automatically)
344 /// * should not be a question (avoid language like "did you mean")
345 /// * should not contain any phrases like "the following", "as shown", etc.
346 /// * may look like "to do xyz, use" or "to do xyz, use abc"
347 /// * may contain a name of a function, variable, or type, but not whole expressions
349 /// See `CodeSuggestion` for more information.
350 pub fn span_suggestion(
355 applicability: Applicability,
357 self.span_suggestion_with_style(
362 SuggestionStyle::ShowCode,
367 pub fn span_suggestion_with_style(
372 applicability: Applicability,
373 style: SuggestionStyle,
375 self.suggestions.push(CodeSuggestion {
376 substitutions: vec![Substitution {
377 parts: vec![SubstitutionPart {
389 pub fn span_suggestion_verbose(
394 applicability: Applicability,
396 self.span_suggestion_with_style(
401 SuggestionStyle::ShowAlways,
406 /// Prints out a message with multiple suggested edits of the code.
407 pub fn span_suggestions(
411 suggestions: impl Iterator<Item = String>,
412 applicability: Applicability,
414 self.suggestions.push(CodeSuggestion {
415 substitutions: suggestions.map(|snippet| Substitution {
416 parts: vec![SubstitutionPart {
422 style: SuggestionStyle::ShowCode,
428 /// Prints out a message with a suggested edit of the code. If the suggestion is presented
429 /// inline, it will only show the message and not the suggestion.
431 /// See `CodeSuggestion` for more information.
432 pub fn span_suggestion_short(
433 &mut self, sp: Span, msg: &str, suggestion: String, applicability: Applicability
435 self.span_suggestion_with_style(
440 SuggestionStyle::HideCodeInline,
445 /// Prints out a message with for a suggestion without showing the suggested code.
447 /// This is intended to be used for suggestions that are obvious in what the changes need to
448 /// be from the message, showing the span label inline would be visually unpleasant
449 /// (marginally overlapping spans or multiline spans) and showing the snippet window wouldn't
450 /// improve understandability.
451 pub fn span_suggestion_hidden(
452 &mut self, sp: Span, msg: &str, suggestion: String, applicability: Applicability
454 self.span_suggestion_with_style(
459 SuggestionStyle::HideCodeAlways,
464 /// Adds a suggestion to the json output, but otherwise remains silent/undisplayed in the cli.
466 /// This is intended to be used for suggestions that are *very* obvious in what the changes
467 /// need to be from the message, but we still want other tools to be able to apply them.
468 pub fn tool_only_span_suggestion(
469 &mut self, sp: Span, msg: &str, suggestion: String, applicability: Applicability
471 self.span_suggestion_with_style(
476 SuggestionStyle::CompletelyHidden,
481 pub fn set_span<S: Into<MultiSpan>>(&mut self, sp: S) -> &mut Self {
482 self.span = sp.into();
483 if let Some(span) = self.span.primary_span() {
484 self.sort_span = span;
489 pub fn code(&mut self, s: DiagnosticId) -> &mut Self {
494 pub fn get_code(&self) -> Option<DiagnosticId> {
498 pub fn message(&self) -> String {
499 self.message.iter().map(|i| i.0.as_str()).collect::<String>()
502 pub fn styled_message(&self) -> &Vec<(String, Style)> {
506 /// Used by a lint. Copies over all details *but* the "main
508 pub fn copy_details_not_message(&mut self, from: &Diagnostic) {
509 self.span = from.span.clone();
510 self.code = from.code.clone();
511 self.children.extend(from.children.iter().cloned())
514 /// Convenience function for internal use, clients should use one of the
515 /// public methods above.
516 pub fn sub(&mut self,
520 render_span: Option<MultiSpan>) {
521 let sub = SubDiagnostic {
523 message: vec![(message.to_owned(), Style::NoStyle)],
527 self.children.push(sub);
530 /// Convenience function for internal use, clients should use one of the
531 /// public methods above.
532 fn sub_with_highlights(&mut self,
534 message: Vec<(String, Style)>,
536 render_span: Option<MultiSpan>) {
537 let sub = SubDiagnostic {
543 self.children.push(sub);
548 pub fn message(&self) -> String {
549 self.message.iter().map(|i| i.0.as_str()).collect::<String>()
552 pub fn styled_message(&self) -> &Vec<(String, Style)> {