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 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 {
111 Level::FailureNote => {
118 Level::Cancelled => {
124 /// Cancel the diagnostic (a structured diagnostic must either be emitted or
125 /// canceled or it will panic when dropped).
126 pub fn cancel(&mut self) {
127 self.level = Level::Cancelled;
130 pub fn cancelled(&self) -> bool {
131 self.level == Level::Cancelled
134 /// Set the sorting span.
135 pub fn set_sort_span(&mut self, sp: Span) {
139 /// Adds a span/label to be included in the resulting snippet.
140 /// This label will be shown together with the original span/label used when creating the
141 /// diagnostic, *not* a span added by one of the `span_*` methods.
143 /// This is pushed onto the `MultiSpan` that was created when the
144 /// diagnostic was first built. If you don't call this function at
145 /// all, and you just supplied a `Span` to create the diagnostic,
146 /// then the snippet will just include that `Span`, which is
147 /// called the primary span.
148 pub fn span_label<T: Into<String>>(&mut self, span: Span, label: T) -> &mut Self {
149 self.span.push_span_label(span, label.into());
153 pub fn replace_span_with(&mut self, after: Span) -> &mut Self {
154 let before = self.span.clone();
155 self.set_span(after);
156 for span_label in before.span_labels() {
157 if let Some(label) = span_label.label {
158 self.span_label(after, label);
164 pub fn note_expected_found(
166 expected_label: &dyn fmt::Display,
167 expected: DiagnosticStyledString,
168 found_label: &dyn fmt::Display,
169 found: DiagnosticStyledString,
171 self.note_expected_found_extra(expected_label, expected, found_label, found, &"", &"")
174 pub fn note_unsuccessfull_coercion(
176 expected: DiagnosticStyledString,
177 found: DiagnosticStyledString,
179 let mut msg: Vec<_> =
180 vec![(format!("required when trying to coerce from type `"),
182 msg.extend(expected.0.iter()
184 StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
185 StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
187 msg.push((format!("` to type '"), Style::NoStyle));
188 msg.extend(found.0.iter()
190 StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
191 StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
193 msg.push((format!("`"), Style::NoStyle));
195 // For now, just attach these as notes
196 self.highlighted_note(msg);
200 pub fn note_expected_found_extra(
202 expected_label: &dyn fmt::Display,
203 expected: DiagnosticStyledString,
204 found_label: &dyn fmt::Display,
205 found: DiagnosticStyledString,
206 expected_extra: &dyn fmt::Display,
207 found_extra: &dyn fmt::Display,
209 let expected_label = format!("expected {}", expected_label);
210 let found_label = format!("found {}", found_label);
211 let (found_padding, expected_padding) = if expected_label.len() > found_label.len() {
212 (expected_label.len() - found_label.len(), 0)
214 (0, found_label.len() - expected_label.len())
216 let mut msg: Vec<_> = vec![(
217 format!("{}{} `", " ".repeat(expected_padding), expected_label),
220 msg.extend(expected.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!("`{}\n", expected_extra), Style::NoStyle));
226 msg.push((format!("{}{} `", " ".repeat(found_padding), found_label), Style::NoStyle));
227 msg.extend(found.0.iter()
229 StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
230 StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
232 msg.push((format!("`{}", found_extra), Style::NoStyle));
234 // For now, just attach these as notes.
235 self.highlighted_note(msg);
239 pub fn note_trait_signature(&mut self, name: String, signature: String) -> &mut Self {
240 self.highlighted_note(vec![
241 (format!("`{}` from trait: `", name), Style::NoStyle),
242 (signature, Style::Highlight),
243 ("`".to_string(), Style::NoStyle)]);
247 pub fn note(&mut self, msg: &str) -> &mut Self {
248 self.sub(Level::Note, msg, MultiSpan::new(), None);
252 pub fn highlighted_note(&mut self, msg: Vec<(String, Style)>) -> &mut Self {
253 self.sub_with_highlights(Level::Note, msg, MultiSpan::new(), None);
257 /// Prints the span with a note above it.
258 pub fn span_note<S: Into<MultiSpan>>(&mut self,
262 self.sub(Level::Note, msg, sp.into(), None);
266 pub fn warn(&mut self, msg: &str) -> &mut Self {
267 self.sub(Level::Warning, msg, MultiSpan::new(), None);
271 /// Prints the span with a warn above it.
272 pub fn span_warn<S: Into<MultiSpan>>(&mut self,
276 self.sub(Level::Warning, msg, sp.into(), None);
280 pub fn help(&mut self , msg: &str) -> &mut Self {
281 self.sub(Level::Help, msg, MultiSpan::new(), None);
285 /// Prints the span with some help above it.
286 pub fn span_help<S: Into<MultiSpan>>(&mut self,
290 self.sub(Level::Help, msg, sp.into(), None);
294 pub fn multipart_suggestion(
297 suggestion: Vec<(Span, String)>,
298 applicability: Applicability,
300 self.suggestions.push(CodeSuggestion {
301 substitutions: vec![Substitution {
304 .map(|(span, snippet)| SubstitutionPart { snippet, span })
308 style: SuggestionStyle::ShowCode,
314 /// Prints out a message with for a multipart suggestion without showing the suggested code.
316 /// This is intended to be used for suggestions that are obvious in what the changes need to
317 /// be from the message, showing the span label inline would be visually unpleasant
318 /// (marginally overlapping spans or multiline spans) and showing the snippet window wouldn't
319 /// improve understandability.
320 pub fn tool_only_multipart_suggestion(
323 suggestion: Vec<(Span, String)>,
324 applicability: Applicability,
326 self.suggestions.push(CodeSuggestion {
327 substitutions: vec![Substitution {
330 .map(|(span, snippet)| SubstitutionPart { snippet, span })
334 style: SuggestionStyle::CompletelyHidden,
340 /// Prints out a message with a suggested edit of the code.
342 /// In case of short messages and a simple suggestion, rustc displays it as a label:
345 /// try adding parentheses: `(tup.0).1`
350 /// * should not end in any punctuation (a `:` is added automatically)
351 /// * should not be a question (avoid language like "did you mean")
352 /// * should not contain any phrases like "the following", "as shown", etc.
353 /// * may look like "to do xyz, use" or "to do xyz, use abc"
354 /// * may contain a name of a function, variable, or type, but not whole expressions
356 /// See `CodeSuggestion` for more information.
357 pub fn span_suggestion(
362 applicability: Applicability,
364 self.span_suggestion_with_style(
369 SuggestionStyle::ShowCode,
374 pub fn span_suggestion_with_style(
379 applicability: Applicability,
380 style: SuggestionStyle,
382 self.suggestions.push(CodeSuggestion {
383 substitutions: vec![Substitution {
384 parts: vec![SubstitutionPart {
396 pub fn span_suggestion_verbose(
401 applicability: Applicability,
403 self.span_suggestion_with_style(
408 SuggestionStyle::ShowAlways,
413 /// Prints out a message with multiple suggested edits of the code.
414 pub fn span_suggestions(
418 suggestions: impl Iterator<Item = String>,
419 applicability: Applicability,
421 self.suggestions.push(CodeSuggestion {
422 substitutions: suggestions.map(|snippet| Substitution {
423 parts: vec![SubstitutionPart {
429 style: SuggestionStyle::ShowCode,
435 /// Prints out a message with a suggested edit of the code. If the suggestion is presented
436 /// inline, it will only show the message and not the suggestion.
438 /// See `CodeSuggestion` for more information.
439 pub fn span_suggestion_short(
440 &mut self, sp: Span, msg: &str, suggestion: String, applicability: Applicability
442 self.span_suggestion_with_style(
447 SuggestionStyle::HideCodeInline,
452 /// Prints out a message with for a suggestion without showing the suggested code.
454 /// This is intended to be used for suggestions that are obvious in what the changes need to
455 /// be from the message, showing the span label inline would be visually unpleasant
456 /// (marginally overlapping spans or multiline spans) and showing the snippet window wouldn't
457 /// improve understandability.
458 pub fn span_suggestion_hidden(
459 &mut self, sp: Span, msg: &str, suggestion: String, applicability: Applicability
461 self.span_suggestion_with_style(
466 SuggestionStyle::HideCodeAlways,
471 /// Adds a suggestion to the json output, but otherwise remains silent/undisplayed in the cli.
473 /// This is intended to be used for suggestions that are *very* obvious in what the changes
474 /// need to be from the message, but we still want other tools to be able to apply them.
475 pub fn tool_only_span_suggestion(
476 &mut self, sp: Span, msg: &str, suggestion: String, applicability: Applicability
478 self.span_suggestion_with_style(
483 SuggestionStyle::CompletelyHidden,
488 pub fn set_span<S: Into<MultiSpan>>(&mut self, sp: S) -> &mut Self {
489 self.span = sp.into();
490 if let Some(span) = self.span.primary_span() {
491 self.sort_span = span;
496 pub fn code(&mut self, s: DiagnosticId) -> &mut Self {
501 pub fn clear_code(&mut self) -> &mut Self {
506 pub fn get_code(&self) -> Option<DiagnosticId> {
510 pub fn set_primary_message<M: Into<String>>(&mut self, msg: M) -> &mut Self {
511 self.message[0] = (msg.into(), Style::NoStyle);
515 pub fn message(&self) -> String {
516 self.message.iter().map(|i| i.0.as_str()).collect::<String>()
519 pub fn styled_message(&self) -> &Vec<(String, Style)> {
523 /// Used by a lint. Copies over all details *but* the "main
525 pub fn copy_details_not_message(&mut self, from: &Diagnostic) {
526 self.span = from.span.clone();
527 self.code = from.code.clone();
528 self.children.extend(from.children.iter().cloned())
531 /// Convenience function for internal use, clients should use one of the
532 /// public methods above.
533 pub fn sub(&mut self,
537 render_span: Option<MultiSpan>) {
538 let sub = SubDiagnostic {
540 message: vec![(message.to_owned(), Style::NoStyle)],
544 self.children.push(sub);
547 /// Convenience function for internal use, clients should use one of the
548 /// public methods above.
549 fn sub_with_highlights(&mut self,
551 message: Vec<(String, Style)>,
553 render_span: Option<MultiSpan>) {
554 let sub = SubDiagnostic {
560 self.children.push(sub);
565 pub fn message(&self) -> String {
566 self.message.iter().map(|i| i.0.as_str()).collect::<String>()
569 pub fn styled_message(&self) -> &Vec<(String, Style)> {