]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_errors/src/diagnostic.rs
Auto merge of #96144 - c410-f3r:z-errors, r=petrochenkov
[rust.git] / compiler / rustc_errors / src / diagnostic.rs
1 use crate::snippet::Style;
2 use crate::{
3     CodeSuggestion, DiagnosticMessage, Level, MultiSpan, Substitution, SubstitutionPart,
4     SuggestionStyle,
5 };
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};
12 use std::borrow::Cow;
13 use std::fmt;
14 use std::hash::{Hash, Hasher};
15
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;
20
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>);
25
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>),
31     Number(usize),
32 }
33
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>;
40 }
41
42 impl IntoDiagnosticArg for String {
43     fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
44         DiagnosticArgValue::Str(Cow::Owned(self))
45     }
46 }
47
48 impl IntoDiagnosticArg for Symbol {
49     fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
50         self.to_ident_string().into_diagnostic_arg()
51     }
52 }
53
54 impl IntoDiagnosticArg for Ident {
55     fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
56         self.to_string().into_diagnostic_arg()
57     }
58 }
59
60 impl<'a> IntoDiagnosticArg for &'a str {
61     fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
62         self.to_string().into_diagnostic_arg()
63     }
64 }
65
66 impl IntoDiagnosticArg for usize {
67     fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
68         DiagnosticArgValue::Number(self)
69     }
70 }
71
72 impl<'source> Into<FluentValue<'source>> for DiagnosticArgValue<'source> {
73     fn into(self) -> FluentValue<'source> {
74         match self {
75             DiagnosticArgValue::Str(s) => From::from(s),
76             DiagnosticArgValue::Number(n) => From::from(n),
77         }
78     }
79 }
80
81 #[must_use]
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.
86     crate level: Level,
87
88     pub message: Vec<(DiagnosticMessage, Style)>,
89     pub code: Option<DiagnosticId>,
90     pub span: MultiSpan,
91     pub children: Vec<SubDiagnostic>,
92     pub suggestions: Result<Vec<CodeSuggestion>, SuggestionsDisabled>,
93     args: Vec<DiagnosticArg<'static>>,
94
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`.
98     pub sort_span: Span,
99
100     /// If diagnostic is from Lint, custom hash function ignores notes
101     /// otherwise hash is based on the all the fields
102     pub is_lint: bool,
103 }
104
105 #[derive(Clone, Debug, PartialEq, Eq, Hash, Encodable, Decodable)]
106 pub enum DiagnosticId {
107     Error(String),
108     Lint { name: String, has_future_breakage: bool, is_force_warn: bool },
109 }
110
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 {
115     pub level: Level,
116     pub message: Vec<(DiagnosticMessage, Style)>,
117     pub span: MultiSpan,
118     pub render_span: Option<MultiSpan>,
119 }
120
121 #[derive(Debug, PartialEq, Eq)]
122 pub struct DiagnosticStyledString(pub Vec<StringPart>);
123
124 impl DiagnosticStyledString {
125     pub fn new() -> DiagnosticStyledString {
126         DiagnosticStyledString(vec![])
127     }
128     pub fn push_normal<S: Into<String>>(&mut self, t: S) {
129         self.0.push(StringPart::Normal(t.into()));
130     }
131     pub fn push_highlighted<S: Into<String>>(&mut self, t: S) {
132         self.0.push(StringPart::Highlighted(t.into()));
133     }
134     pub fn push<S: Into<String>>(&mut self, t: S, highlight: bool) {
135         if highlight {
136             self.push_highlighted(t);
137         } else {
138             self.push_normal(t);
139         }
140     }
141     pub fn normal<S: Into<String>>(t: S) -> DiagnosticStyledString {
142         DiagnosticStyledString(vec![StringPart::Normal(t.into())])
143     }
144
145     pub fn highlighted<S: Into<String>>(t: S) -> DiagnosticStyledString {
146         DiagnosticStyledString(vec![StringPart::Highlighted(t.into())])
147     }
148
149     pub fn content(&self) -> String {
150         self.0.iter().map(|x| x.content()).collect::<String>()
151     }
152 }
153
154 #[derive(Debug, PartialEq, Eq)]
155 pub enum StringPart {
156     Normal(String),
157     Highlighted(String),
158 }
159
160 impl StringPart {
161     pub fn content(&self) -> &str {
162         match self {
163             &StringPart::Normal(ref s) | &StringPart::Highlighted(ref s) => s,
164         }
165     }
166 }
167
168 impl Diagnostic {
169     pub fn new<M: Into<DiagnosticMessage>>(level: Level, message: M) -> Self {
170         Diagnostic::new_with_code(level, None, message)
171     }
172
173     pub fn new_with_code<M: Into<DiagnosticMessage>>(
174         level: Level,
175         code: Option<DiagnosticId>,
176         message: M,
177     ) -> Self {
178         Diagnostic {
179             level,
180             message: vec![(message.into(), Style::NoStyle)],
181             code,
182             span: MultiSpan::new(),
183             children: vec![],
184             suggestions: Ok(vec![]),
185             args: vec![],
186             sort_span: DUMMY_SP,
187             is_lint: false,
188         }
189     }
190
191     #[inline(always)]
192     pub fn level(&self) -> Level {
193         self.level
194     }
195
196     pub fn is_error(&self) -> bool {
197         match self.level {
198             Level::Bug
199             | Level::DelayedBug
200             | Level::Fatal
201             | Level::Error { .. }
202             | Level::FailureNote => true,
203
204             Level::Warning
205             | Level::Note
206             | Level::OnceNote
207             | Level::Help
208             | Level::Allow
209             | Level::Expect(_) => false,
210         }
211     }
212
213     pub fn update_unstable_expectation_id(
214         &mut self,
215         unstable_to_stable: &FxHashMap<LintExpectationId, LintExpectationId>,
216     ) {
217         if let Level::Expect(expectation_id) = &mut self.level {
218             if expectation_id.is_stable() {
219                 return;
220             }
221
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");
229
230             stable_id.set_lint_index(lint_index);
231             *expectation_id = stable_id;
232         }
233     }
234
235     pub fn has_future_breakage(&self) -> bool {
236         match self.code {
237             Some(DiagnosticId::Lint { has_future_breakage, .. }) => has_future_breakage,
238             _ => false,
239         }
240     }
241
242     pub fn is_force_warn(&self) -> bool {
243         match self.code {
244             Some(DiagnosticId::Lint { is_force_warn, .. }) => is_force_warn,
245             _ => false,
246         }
247     }
248
249     /// Delay emission of this diagnostic as a bug.
250     ///
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
255     /// emitted.
256     ///
257     /// In the meantime, though, callsites are required to deal with the "bug"
258     /// locally in whichever way makes the most sense.
259     #[track_caller]
260     pub fn downgrade_to_delayed_bug(&mut self) -> &mut Self {
261         assert!(
262             self.is_error(),
263             "downgrade_to_delayed_bug: cannot downgrade {:?} to DelayedBug: not an error",
264             self.level
265         );
266         self.level = Level::DelayedBug;
267
268         self
269     }
270
271     /// Adds a span/label to be included in the resulting snippet.
272     ///
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.
276     ///
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());
281         self
282     }
283
284     /// Labels all the given spans with the provided label.
285     /// See [`Self::span_label()`] for more information.
286     pub fn span_labels(
287         &mut self,
288         spans: impl IntoIterator<Item = Span>,
289         label: impl AsRef<str>,
290     ) -> &mut Self {
291         let label = label.as_ref();
292         for span in spans {
293             self.span_label(span, label);
294         }
295         self
296     }
297
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);
304             }
305         }
306         self
307     }
308
309     pub fn note_expected_found(
310         &mut self,
311         expected_label: &dyn fmt::Display,
312         expected: DiagnosticStyledString,
313         found_label: &dyn fmt::Display,
314         found: DiagnosticStyledString,
315     ) -> &mut Self {
316         self.note_expected_found_extra(expected_label, expected, found_label, found, &"", &"")
317     }
318
319     pub fn note_unsuccessful_coercion(
320         &mut self,
321         expected: DiagnosticStyledString,
322         found: DiagnosticStyledString,
323     ) -> &mut Self {
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),
329         }));
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),
334         }));
335         msg.push(("`".to_string(), Style::NoStyle));
336
337         // For now, just attach these as notes
338         self.highlighted_note(msg);
339         self
340     }
341
342     pub fn note_expected_found_extra(
343         &mut self,
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,
350     ) -> &mut Self {
351         let expected_label = expected_label.to_string();
352         let expected_label = if expected_label.is_empty() {
353             "expected".to_string()
354         } else {
355             format!("expected {}", expected_label)
356         };
357         let found_label = found_label.to_string();
358         let found_label = if found_label.is_empty() {
359             "found".to_string()
360         } else {
361             format!("found {}", found_label)
362         };
363         let (found_padding, expected_padding) = if expected_label.len() > found_label.len() {
364             (expected_label.len() - found_label.len(), 0)
365         } else {
366             (0, found_label.len() - expected_label.len())
367         };
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),
373         }));
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),
379         }));
380         msg.push((format!("`{}", found_extra), Style::NoStyle));
381
382         // For now, just attach these as notes.
383         self.highlighted_note(msg);
384         self
385     }
386
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),
392         ]);
393         self
394     }
395
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);
399         self
400     }
401
402     pub fn highlighted_note<M: Into<DiagnosticMessage>>(
403         &mut self,
404         msg: Vec<(M, Style)>,
405     ) -> &mut Self {
406         self.sub_with_highlights(Level::Note, msg, MultiSpan::new(), None);
407         self
408     }
409
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);
414         self
415     }
416
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>>(
420         &mut self,
421         sp: S,
422         msg: impl Into<DiagnosticMessage>,
423     ) -> &mut Self {
424         self.sub(Level::Note, msg, sp.into(), None);
425         self
426     }
427
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>>(
431         &mut self,
432         sp: S,
433         msg: impl Into<DiagnosticMessage>,
434     ) -> &mut Self {
435         self.sub(Level::OnceNote, msg, sp.into(), None);
436         self
437     }
438
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);
442         self
443     }
444
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>>(
448         &mut self,
449         sp: S,
450         msg: impl Into<DiagnosticMessage>,
451     ) -> &mut Self {
452         self.sub(Level::Warning, msg, sp.into(), None);
453         self
454     }
455
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);
459         self
460     }
461
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);
465         self
466     }
467
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>>(
471         &mut self,
472         sp: S,
473         msg: impl Into<DiagnosticMessage>,
474     ) -> &mut Self {
475         self.sub(Level::Help, msg, sp.into(), None);
476         self
477     }
478
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));
484         } else {
485             self.help(&format!("pass `--edition {}` to `rustc`", LATEST_STABLE_EDITION));
486         }
487         self.note("for more on editions, read https://doc.rust-lang.org/edition-guide");
488         self
489     }
490
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);
496         self
497     }
498
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);
503         }
504     }
505
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(
509         &mut self,
510         msg: impl Into<DiagnosticMessage>,
511         suggestion: Vec<(Span, String)>,
512         applicability: Applicability,
513     ) -> &mut Self {
514         self.multipart_suggestion_with_style(
515             msg,
516             suggestion,
517             applicability,
518             SuggestionStyle::ShowCode,
519         )
520     }
521
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(
525         &mut self,
526         msg: impl Into<DiagnosticMessage>,
527         suggestion: Vec<(Span, String)>,
528         applicability: Applicability,
529     ) -> &mut Self {
530         self.multipart_suggestion_with_style(
531             msg,
532             suggestion,
533             applicability,
534             SuggestionStyle::ShowAlways,
535         )
536     }
537     /// [`Diagnostic::multipart_suggestion()`] but you can set the [`SuggestionStyle`].
538     pub fn multipart_suggestion_with_style(
539         &mut self,
540         msg: impl Into<DiagnosticMessage>,
541         suggestion: Vec<(Span, String)>,
542         applicability: Applicability,
543         style: SuggestionStyle,
544     ) -> &mut Self {
545         assert!(!suggestion.is_empty());
546         self.push_suggestion(CodeSuggestion {
547             substitutions: vec![Substitution {
548                 parts: suggestion
549                     .into_iter()
550                     .map(|(span, snippet)| SubstitutionPart { snippet, span })
551                     .collect(),
552             }],
553             msg: msg.into(),
554             style,
555             applicability,
556         });
557         self
558     }
559
560     /// Prints out a message with for a multipart suggestion without showing the suggested code.
561     ///
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(
567         &mut self,
568         msg: impl Into<DiagnosticMessage>,
569         suggestion: Vec<(Span, String)>,
570         applicability: Applicability,
571     ) -> &mut Self {
572         assert!(!suggestion.is_empty());
573         self.push_suggestion(CodeSuggestion {
574             substitutions: vec![Substitution {
575                 parts: suggestion
576                     .into_iter()
577                     .map(|(span, snippet)| SubstitutionPart { snippet, span })
578                     .collect(),
579             }],
580             msg: msg.into(),
581             style: SuggestionStyle::CompletelyHidden,
582             applicability,
583         });
584         self
585     }
586
587     /// Prints out a message with a suggested edit of the code.
588     ///
589     /// In case of short messages and a simple suggestion, rustc displays it as a label:
590     ///
591     /// ```text
592     /// try adding parentheses: `(tup.0).1`
593     /// ```
594     ///
595     /// The message
596     ///
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
602     ///
603     /// See `CodeSuggestion` for more information.
604     pub fn span_suggestion(
605         &mut self,
606         sp: Span,
607         msg: impl Into<DiagnosticMessage>,
608         suggestion: String,
609         applicability: Applicability,
610     ) -> &mut Self {
611         self.span_suggestion_with_style(
612             sp,
613             msg,
614             suggestion,
615             applicability,
616             SuggestionStyle::ShowCode,
617         );
618         self
619     }
620
621     /// [`Diagnostic::span_suggestion()`] but you can set the [`SuggestionStyle`].
622     pub fn span_suggestion_with_style(
623         &mut self,
624         sp: Span,
625         msg: impl Into<DiagnosticMessage>,
626         suggestion: String,
627         applicability: Applicability,
628         style: SuggestionStyle,
629     ) -> &mut Self {
630         self.push_suggestion(CodeSuggestion {
631             substitutions: vec![Substitution {
632                 parts: vec![SubstitutionPart { snippet: suggestion, span: sp }],
633             }],
634             msg: msg.into(),
635             style,
636             applicability,
637         });
638         self
639     }
640
641     /// Always show the suggested change.
642     pub fn span_suggestion_verbose(
643         &mut self,
644         sp: Span,
645         msg: impl Into<DiagnosticMessage>,
646         suggestion: String,
647         applicability: Applicability,
648     ) -> &mut Self {
649         self.span_suggestion_with_style(
650             sp,
651             msg,
652             suggestion,
653             applicability,
654             SuggestionStyle::ShowAlways,
655         );
656         self
657     }
658
659     /// Prints out a message with multiple suggested edits of the code.
660     /// See also [`Diagnostic::span_suggestion()`].
661     pub fn span_suggestions(
662         &mut self,
663         sp: Span,
664         msg: impl Into<DiagnosticMessage>,
665         suggestions: impl Iterator<Item = String>,
666         applicability: Applicability,
667     ) -> &mut Self {
668         let mut suggestions: Vec<_> = suggestions.collect();
669         suggestions.sort();
670         let substitutions = suggestions
671             .into_iter()
672             .map(|snippet| Substitution { parts: vec![SubstitutionPart { snippet, span: sp }] })
673             .collect();
674         self.push_suggestion(CodeSuggestion {
675             substitutions,
676             msg: msg.into(),
677             style: SuggestionStyle::ShowCode,
678             applicability,
679         });
680         self
681     }
682
683     /// Prints out a message with multiple suggested edits of the code.
684     /// See also [`Diagnostic::span_suggestion()`].
685     pub fn multipart_suggestions(
686         &mut self,
687         msg: impl Into<DiagnosticMessage>,
688         suggestions: impl Iterator<Item = Vec<(Span, String)>>,
689         applicability: Applicability,
690     ) -> &mut Self {
691         self.push_suggestion(CodeSuggestion {
692             substitutions: suggestions
693                 .map(|sugg| Substitution {
694                     parts: sugg
695                         .into_iter()
696                         .map(|(span, snippet)| SubstitutionPart { snippet, span })
697                         .collect(),
698                 })
699                 .collect(),
700             msg: msg.into(),
701             style: SuggestionStyle::ShowCode,
702             applicability,
703         });
704         self
705     }
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.
708     ///
709     /// See `CodeSuggestion` for more information.
710     pub fn span_suggestion_short(
711         &mut self,
712         sp: Span,
713         msg: impl Into<DiagnosticMessage>,
714         suggestion: String,
715         applicability: Applicability,
716     ) -> &mut Self {
717         self.span_suggestion_with_style(
718             sp,
719             msg,
720             suggestion,
721             applicability,
722             SuggestionStyle::HideCodeInline,
723         );
724         self
725     }
726
727     /// Prints out a message for a suggestion without showing the suggested code.
728     ///
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(
734         &mut self,
735         sp: Span,
736         msg: impl Into<DiagnosticMessage>,
737         suggestion: String,
738         applicability: Applicability,
739     ) -> &mut Self {
740         self.span_suggestion_with_style(
741             sp,
742             msg,
743             suggestion,
744             applicability,
745             SuggestionStyle::HideCodeAlways,
746         );
747         self
748     }
749
750     /// Adds a suggestion to the JSON output that will not be shown in the CLI.
751     ///
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(
755         &mut self,
756         sp: Span,
757         msg: impl Into<DiagnosticMessage>,
758         suggestion: String,
759         applicability: Applicability,
760     ) -> &mut Self {
761         self.span_suggestion_with_style(
762             sp,
763             msg,
764             suggestion,
765             applicability,
766             SuggestionStyle::CompletelyHidden,
767         );
768         self
769     }
770
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;
775         }
776         self
777     }
778
779     pub fn set_is_lint(&mut self) -> &mut Self {
780         self.is_lint = true;
781         self
782     }
783
784     pub fn code(&mut self, s: DiagnosticId) -> &mut Self {
785         self.code = Some(s);
786         self
787     }
788
789     pub fn clear_code(&mut self) -> &mut Self {
790         self.code = None;
791         self
792     }
793
794     pub fn get_code(&self) -> Option<DiagnosticId> {
795         self.code.clone()
796     }
797
798     pub fn set_primary_message(&mut self, msg: impl Into<DiagnosticMessage>) -> &mut Self {
799         self.message[0] = (msg.into(), Style::NoStyle);
800         self
801     }
802
803     pub fn args(&self) -> &[DiagnosticArg<'static>] {
804         &self.args
805     }
806
807     pub fn set_arg(
808         &mut self,
809         name: impl Into<Cow<'static, str>>,
810         arg: DiagnosticArgValue<'static>,
811     ) -> &mut Self {
812         self.args.push((name.into(), arg));
813         self
814     }
815
816     pub fn styled_message(&self) -> &Vec<(DiagnosticMessage, Style)> {
817         &self.message
818     }
819
820     /// Convenience function for internal use, clients should use one of the
821     /// public methods above.
822     ///
823     /// Used by `proc_macro_server` for implementing `server::Diagnostic`.
824     pub fn sub(
825         &mut self,
826         level: Level,
827         message: impl Into<DiagnosticMessage>,
828         span: MultiSpan,
829         render_span: Option<MultiSpan>,
830     ) {
831         let sub = SubDiagnostic {
832             level,
833             message: vec![(message.into(), Style::NoStyle)],
834             span,
835             render_span,
836         };
837         self.children.push(sub);
838     }
839
840     /// Convenience function for internal use, clients should use one of the
841     /// public methods above.
842     fn sub_with_highlights<M: Into<DiagnosticMessage>>(
843         &mut self,
844         level: Level,
845         mut message: Vec<(M, Style)>,
846         span: MultiSpan,
847         render_span: Option<MultiSpan>,
848     ) {
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);
852     }
853
854     /// Fields used for Hash, and PartialEq trait
855     fn keys(
856         &self,
857     ) -> (
858         &Level,
859         &Vec<(DiagnosticMessage, Style)>,
860         &Option<DiagnosticId>,
861         &MultiSpan,
862         &Result<Vec<CodeSuggestion>, SuggestionsDisabled>,
863         Option<&Vec<SubDiagnostic>>,
864     ) {
865         (
866             &self.level,
867             &self.message,
868             &self.code,
869             &self.span,
870             &self.suggestions,
871             (if self.is_lint { None } else { Some(&self.children) }),
872         )
873     }
874 }
875
876 impl Hash for Diagnostic {
877     fn hash<H>(&self, state: &mut H)
878     where
879         H: Hasher,
880     {
881         self.keys().hash(state);
882     }
883 }
884
885 impl PartialEq for Diagnostic {
886     fn eq(&self, other: &Self) -> bool {
887         self.keys() == other.keys()
888     }
889 }