]> git.proxmox.com Git - rustc.git/blob - compiler/rustc_errors/src/diagnostic.rs
New upstream version 1.61.0+dfsg1
[rustc.git] / compiler / rustc_errors / src / diagnostic.rs
1 use crate::snippet::Style;
2 use crate::CodeSuggestion;
3 use crate::Level;
4 use crate::Substitution;
5 use crate::SubstitutionPart;
6 use crate::SuggestionStyle;
7 use crate::ToolMetadata;
8 use rustc_data_structures::stable_map::FxHashMap;
9 use rustc_lint_defs::{Applicability, LintExpectationId};
10 use rustc_serialize::json::Json;
11 use rustc_span::edition::LATEST_STABLE_EDITION;
12 use rustc_span::{MultiSpan, Span, DUMMY_SP};
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 #[must_use]
22 #[derive(Clone, Debug, Encodable, Decodable)]
23 pub struct Diagnostic {
24 // NOTE(eddyb) this is private to disallow arbitrary after-the-fact changes,
25 // outside of what methods in this crate themselves allow.
26 crate level: Level,
27
28 pub message: Vec<(String, Style)>,
29 pub code: Option<DiagnosticId>,
30 pub span: MultiSpan,
31 pub children: Vec<SubDiagnostic>,
32 pub suggestions: Result<Vec<CodeSuggestion>, SuggestionsDisabled>,
33
34 /// This is not used for highlighting or rendering any error message. Rather, it can be used
35 /// as a sort key to sort a buffer of diagnostics. By default, it is the primary span of
36 /// `span` if there is one. Otherwise, it is `DUMMY_SP`.
37 pub sort_span: Span,
38
39 /// If diagnostic is from Lint, custom hash function ignores notes
40 /// otherwise hash is based on the all the fields
41 pub is_lint: bool,
42 }
43
44 #[derive(Clone, Debug, PartialEq, Eq, Hash, Encodable, Decodable)]
45 pub enum DiagnosticId {
46 Error(String),
47 Lint { name: String, has_future_breakage: bool, is_force_warn: bool },
48 }
49
50 /// A "sub"-diagnostic attached to a parent diagnostic.
51 /// For example, a note attached to an error.
52 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
53 pub struct SubDiagnostic {
54 pub level: Level,
55 pub message: Vec<(String, Style)>,
56 pub span: MultiSpan,
57 pub render_span: Option<MultiSpan>,
58 }
59
60 #[derive(Debug, PartialEq, Eq)]
61 pub struct DiagnosticStyledString(pub Vec<StringPart>);
62
63 impl DiagnosticStyledString {
64 pub fn new() -> DiagnosticStyledString {
65 DiagnosticStyledString(vec![])
66 }
67 pub fn push_normal<S: Into<String>>(&mut self, t: S) {
68 self.0.push(StringPart::Normal(t.into()));
69 }
70 pub fn push_highlighted<S: Into<String>>(&mut self, t: S) {
71 self.0.push(StringPart::Highlighted(t.into()));
72 }
73 pub fn push<S: Into<String>>(&mut self, t: S, highlight: bool) {
74 if highlight {
75 self.push_highlighted(t);
76 } else {
77 self.push_normal(t);
78 }
79 }
80 pub fn normal<S: Into<String>>(t: S) -> DiagnosticStyledString {
81 DiagnosticStyledString(vec![StringPart::Normal(t.into())])
82 }
83
84 pub fn highlighted<S: Into<String>>(t: S) -> DiagnosticStyledString {
85 DiagnosticStyledString(vec![StringPart::Highlighted(t.into())])
86 }
87
88 pub fn content(&self) -> String {
89 self.0.iter().map(|x| x.content()).collect::<String>()
90 }
91 }
92
93 #[derive(Debug, PartialEq, Eq)]
94 pub enum StringPart {
95 Normal(String),
96 Highlighted(String),
97 }
98
99 impl StringPart {
100 pub fn content(&self) -> &str {
101 match self {
102 &StringPart::Normal(ref s) | &StringPart::Highlighted(ref s) => s,
103 }
104 }
105 }
106
107 impl Diagnostic {
108 pub fn new(level: Level, message: &str) -> Self {
109 Diagnostic::new_with_code(level, None, message)
110 }
111
112 pub fn new_with_code(level: Level, code: Option<DiagnosticId>, message: &str) -> Self {
113 Diagnostic {
114 level,
115 message: vec![(message.to_owned(), Style::NoStyle)],
116 code,
117 span: MultiSpan::new(),
118 children: vec![],
119 suggestions: Ok(vec![]),
120 sort_span: DUMMY_SP,
121 is_lint: false,
122 }
123 }
124
125 #[inline(always)]
126 pub fn level(&self) -> Level {
127 self.level
128 }
129
130 pub fn is_error(&self) -> bool {
131 match self.level {
132 Level::Bug
133 | Level::DelayedBug
134 | Level::Fatal
135 | Level::Error { .. }
136 | Level::FailureNote => true,
137
138 Level::Warning
139 | Level::Note
140 | Level::OnceNote
141 | Level::Help
142 | Level::Allow
143 | Level::Expect(_) => false,
144 }
145 }
146
147 pub fn update_unstable_expectation_id(
148 &mut self,
149 unstable_to_stable: &FxHashMap<LintExpectationId, LintExpectationId>,
150 ) {
151 if let Level::Expect(expectation_id) = &mut self.level {
152 if expectation_id.is_stable() {
153 return;
154 }
155
156 // The unstable to stable map only maps the unstable `AttrId` to a stable `HirId` with an attribute index.
157 // The lint index inside the attribute is manually transferred here.
158 let lint_index = expectation_id.get_lint_index();
159 expectation_id.set_lint_index(None);
160 let mut stable_id = *unstable_to_stable
161 .get(&expectation_id)
162 .expect("each unstable `LintExpectationId` must have a matching stable id");
163
164 stable_id.set_lint_index(lint_index);
165 *expectation_id = stable_id;
166 }
167 }
168
169 pub fn has_future_breakage(&self) -> bool {
170 match self.code {
171 Some(DiagnosticId::Lint { has_future_breakage, .. }) => has_future_breakage,
172 _ => false,
173 }
174 }
175
176 pub fn is_force_warn(&self) -> bool {
177 match self.code {
178 Some(DiagnosticId::Lint { is_force_warn, .. }) => is_force_warn,
179 _ => false,
180 }
181 }
182
183 /// Delay emission of this diagnostic as a bug.
184 ///
185 /// This can be useful in contexts where an error indicates a bug but
186 /// typically this only happens when other compilation errors have already
187 /// happened. In those cases this can be used to defer emission of this
188 /// diagnostic as a bug in the compiler only if no other errors have been
189 /// emitted.
190 ///
191 /// In the meantime, though, callsites are required to deal with the "bug"
192 /// locally in whichever way makes the most sense.
193 #[track_caller]
194 pub fn downgrade_to_delayed_bug(&mut self) -> &mut Self {
195 assert!(
196 self.is_error(),
197 "downgrade_to_delayed_bug: cannot downgrade {:?} to DelayedBug: not an error",
198 self.level
199 );
200 self.level = Level::DelayedBug;
201
202 self
203 }
204
205 /// Adds a span/label to be included in the resulting snippet.
206 ///
207 /// This is pushed onto the [`MultiSpan`] that was created when the diagnostic
208 /// was first built. That means it will be shown together with the original
209 /// span/label, *not* a span added by one of the `span_{note,warn,help,suggestions}` methods.
210 ///
211 /// This span is *not* considered a ["primary span"][`MultiSpan`]; only
212 /// the `Span` supplied when creating the diagnostic is primary.
213 pub fn span_label<T: Into<String>>(&mut self, span: Span, label: T) -> &mut Self {
214 self.span.push_span_label(span, label.into());
215 self
216 }
217
218 /// Labels all the given spans with the provided label.
219 /// See [`Self::span_label()`] for more information.
220 pub fn span_labels(
221 &mut self,
222 spans: impl IntoIterator<Item = Span>,
223 label: impl AsRef<str>,
224 ) -> &mut Self {
225 let label = label.as_ref();
226 for span in spans {
227 self.span_label(span, label);
228 }
229 self
230 }
231
232 pub fn replace_span_with(&mut self, after: Span) -> &mut Self {
233 let before = self.span.clone();
234 self.set_span(after);
235 for span_label in before.span_labels() {
236 if let Some(label) = span_label.label {
237 self.span_label(after, label);
238 }
239 }
240 self
241 }
242
243 pub fn note_expected_found(
244 &mut self,
245 expected_label: &dyn fmt::Display,
246 expected: DiagnosticStyledString,
247 found_label: &dyn fmt::Display,
248 found: DiagnosticStyledString,
249 ) -> &mut Self {
250 self.note_expected_found_extra(expected_label, expected, found_label, found, &"", &"")
251 }
252
253 pub fn note_unsuccessful_coercion(
254 &mut self,
255 expected: DiagnosticStyledString,
256 found: DiagnosticStyledString,
257 ) -> &mut Self {
258 let mut msg: Vec<_> =
259 vec![("required when trying to coerce from type `".to_string(), Style::NoStyle)];
260 msg.extend(expected.0.iter().map(|x| match *x {
261 StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
262 StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
263 }));
264 msg.push(("` to type '".to_string(), Style::NoStyle));
265 msg.extend(found.0.iter().map(|x| match *x {
266 StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
267 StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
268 }));
269 msg.push(("`".to_string(), Style::NoStyle));
270
271 // For now, just attach these as notes
272 self.highlighted_note(msg);
273 self
274 }
275
276 pub fn note_expected_found_extra(
277 &mut self,
278 expected_label: &dyn fmt::Display,
279 expected: DiagnosticStyledString,
280 found_label: &dyn fmt::Display,
281 found: DiagnosticStyledString,
282 expected_extra: &dyn fmt::Display,
283 found_extra: &dyn fmt::Display,
284 ) -> &mut Self {
285 let expected_label = expected_label.to_string();
286 let expected_label = if expected_label.is_empty() {
287 "expected".to_string()
288 } else {
289 format!("expected {}", expected_label)
290 };
291 let found_label = found_label.to_string();
292 let found_label = if found_label.is_empty() {
293 "found".to_string()
294 } else {
295 format!("found {}", found_label)
296 };
297 let (found_padding, expected_padding) = if expected_label.len() > found_label.len() {
298 (expected_label.len() - found_label.len(), 0)
299 } else {
300 (0, found_label.len() - expected_label.len())
301 };
302 let mut msg: Vec<_> =
303 vec![(format!("{}{} `", " ".repeat(expected_padding), expected_label), Style::NoStyle)];
304 msg.extend(expected.0.iter().map(|x| match *x {
305 StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
306 StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
307 }));
308 msg.push((format!("`{}\n", expected_extra), Style::NoStyle));
309 msg.push((format!("{}{} `", " ".repeat(found_padding), found_label), Style::NoStyle));
310 msg.extend(found.0.iter().map(|x| match *x {
311 StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
312 StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
313 }));
314 msg.push((format!("`{}", found_extra), Style::NoStyle));
315
316 // For now, just attach these as notes.
317 self.highlighted_note(msg);
318 self
319 }
320
321 pub fn note_trait_signature(&mut self, name: String, signature: String) -> &mut Self {
322 self.highlighted_note(vec![
323 (format!("`{}` from trait: `", name), Style::NoStyle),
324 (signature, Style::Highlight),
325 ("`".to_string(), Style::NoStyle),
326 ]);
327 self
328 }
329
330 /// Add a note attached to this diagnostic.
331 pub fn note(&mut self, msg: &str) -> &mut Self {
332 self.sub(Level::Note, msg, MultiSpan::new(), None);
333 self
334 }
335
336 pub fn highlighted_note(&mut self, msg: Vec<(String, Style)>) -> &mut Self {
337 self.sub_with_highlights(Level::Note, msg, MultiSpan::new(), None);
338 self
339 }
340
341 /// Prints the span with a note above it.
342 /// This is like [`Diagnostic::note()`], but it gets its own span.
343 pub fn note_once(&mut self, msg: &str) -> &mut Self {
344 self.sub(Level::OnceNote, msg, MultiSpan::new(), None);
345 self
346 }
347
348 /// Prints the span with a note above it.
349 /// This is like [`Diagnostic::note()`], but it gets its own span.
350 pub fn span_note<S: Into<MultiSpan>>(&mut self, sp: S, msg: &str) -> &mut Self {
351 self.sub(Level::Note, msg, sp.into(), None);
352 self
353 }
354
355 /// Prints the span with a note above it.
356 /// This is like [`Diagnostic::note()`], but it gets its own span.
357 pub fn span_note_once<S: Into<MultiSpan>>(&mut self, sp: S, msg: &str) -> &mut Self {
358 self.sub(Level::OnceNote, msg, sp.into(), None);
359 self
360 }
361
362 /// Add a warning attached to this diagnostic.
363 pub fn warn(&mut self, msg: &str) -> &mut Self {
364 self.sub(Level::Warning, msg, MultiSpan::new(), None);
365 self
366 }
367
368 /// Prints the span with a warning above it.
369 /// This is like [`Diagnostic::warn()`], but it gets its own span.
370 pub fn span_warn<S: Into<MultiSpan>>(&mut self, sp: S, msg: &str) -> &mut Self {
371 self.sub(Level::Warning, msg, sp.into(), None);
372 self
373 }
374
375 /// Add a help message attached to this diagnostic.
376 pub fn help(&mut self, msg: &str) -> &mut Self {
377 self.sub(Level::Help, msg, MultiSpan::new(), None);
378 self
379 }
380
381 /// Prints the span with some help above it.
382 /// This is like [`Diagnostic::help()`], but it gets its own span.
383 pub fn span_help<S: Into<MultiSpan>>(&mut self, sp: S, msg: &str) -> &mut Self {
384 self.sub(Level::Help, msg, sp.into(), None);
385 self
386 }
387
388 /// Help the user upgrade to the latest edition.
389 /// This is factored out to make sure it does the right thing with `Cargo.toml`.
390 pub fn help_use_latest_edition(&mut self) -> &mut Self {
391 if std::env::var_os("CARGO").is_some() {
392 self.help(&format!("set `edition = \"{}\"` in `Cargo.toml`", LATEST_STABLE_EDITION));
393 } else {
394 self.help(&format!("pass `--edition {}` to `rustc`", LATEST_STABLE_EDITION));
395 }
396 self.note("for more on editions, read https://doc.rust-lang.org/edition-guide");
397 self
398 }
399
400 /// Disallow attaching suggestions this diagnostic.
401 /// Any suggestions attached e.g. with the `span_suggestion_*` methods
402 /// (before and after the call to `disable_suggestions`) will be ignored.
403 pub fn disable_suggestions(&mut self) -> &mut Self {
404 self.suggestions = Err(SuggestionsDisabled);
405 self
406 }
407
408 /// Helper for pushing to `self.suggestions`, if available (not disable).
409 fn push_suggestion(&mut self, suggestion: CodeSuggestion) {
410 if let Ok(suggestions) = &mut self.suggestions {
411 suggestions.push(suggestion);
412 }
413 }
414
415 /// Show a suggestion that has multiple parts to it.
416 /// In other words, multiple changes need to be applied as part of this suggestion.
417 pub fn multipart_suggestion(
418 &mut self,
419 msg: &str,
420 suggestion: Vec<(Span, String)>,
421 applicability: Applicability,
422 ) -> &mut Self {
423 self.multipart_suggestion_with_style(
424 msg,
425 suggestion,
426 applicability,
427 SuggestionStyle::ShowCode,
428 )
429 }
430
431 /// Show a suggestion that has multiple parts to it, always as it's own subdiagnostic.
432 /// In other words, multiple changes need to be applied as part of this suggestion.
433 pub fn multipart_suggestion_verbose(
434 &mut self,
435 msg: &str,
436 suggestion: Vec<(Span, String)>,
437 applicability: Applicability,
438 ) -> &mut Self {
439 self.multipart_suggestion_with_style(
440 msg,
441 suggestion,
442 applicability,
443 SuggestionStyle::ShowAlways,
444 )
445 }
446 /// [`Diagnostic::multipart_suggestion()`] but you can set the [`SuggestionStyle`].
447 pub fn multipart_suggestion_with_style(
448 &mut self,
449 msg: &str,
450 suggestion: Vec<(Span, String)>,
451 applicability: Applicability,
452 style: SuggestionStyle,
453 ) -> &mut Self {
454 assert!(!suggestion.is_empty());
455 self.push_suggestion(CodeSuggestion {
456 substitutions: vec![Substitution {
457 parts: suggestion
458 .into_iter()
459 .map(|(span, snippet)| SubstitutionPart { snippet, span })
460 .collect(),
461 }],
462 msg: msg.to_owned(),
463 style,
464 applicability,
465 tool_metadata: Default::default(),
466 });
467 self
468 }
469
470 /// Prints out a message with for a multipart suggestion without showing the suggested code.
471 ///
472 /// This is intended to be used for suggestions that are obvious in what the changes need to
473 /// be from the message, showing the span label inline would be visually unpleasant
474 /// (marginally overlapping spans or multiline spans) and showing the snippet window wouldn't
475 /// improve understandability.
476 pub fn tool_only_multipart_suggestion(
477 &mut self,
478 msg: &str,
479 suggestion: Vec<(Span, String)>,
480 applicability: Applicability,
481 ) -> &mut Self {
482 assert!(!suggestion.is_empty());
483 self.push_suggestion(CodeSuggestion {
484 substitutions: vec![Substitution {
485 parts: suggestion
486 .into_iter()
487 .map(|(span, snippet)| SubstitutionPart { snippet, span })
488 .collect(),
489 }],
490 msg: msg.to_owned(),
491 style: SuggestionStyle::CompletelyHidden,
492 applicability,
493 tool_metadata: Default::default(),
494 });
495 self
496 }
497
498 /// Prints out a message with a suggested edit of the code.
499 ///
500 /// In case of short messages and a simple suggestion, rustc displays it as a label:
501 ///
502 /// ```text
503 /// try adding parentheses: `(tup.0).1`
504 /// ```
505 ///
506 /// The message
507 ///
508 /// * should not end in any punctuation (a `:` is added automatically)
509 /// * should not be a question (avoid language like "did you mean")
510 /// * should not contain any phrases like "the following", "as shown", etc.
511 /// * may look like "to do xyz, use" or "to do xyz, use abc"
512 /// * may contain a name of a function, variable, or type, but not whole expressions
513 ///
514 /// See `CodeSuggestion` for more information.
515 pub fn span_suggestion(
516 &mut self,
517 sp: Span,
518 msg: &str,
519 suggestion: String,
520 applicability: Applicability,
521 ) -> &mut Self {
522 self.span_suggestion_with_style(
523 sp,
524 msg,
525 suggestion,
526 applicability,
527 SuggestionStyle::ShowCode,
528 );
529 self
530 }
531
532 /// [`Diagnostic::span_suggestion()`] but you can set the [`SuggestionStyle`].
533 pub fn span_suggestion_with_style(
534 &mut self,
535 sp: Span,
536 msg: &str,
537 suggestion: String,
538 applicability: Applicability,
539 style: SuggestionStyle,
540 ) -> &mut Self {
541 self.push_suggestion(CodeSuggestion {
542 substitutions: vec![Substitution {
543 parts: vec![SubstitutionPart { snippet: suggestion, span: sp }],
544 }],
545 msg: msg.to_owned(),
546 style,
547 applicability,
548 tool_metadata: Default::default(),
549 });
550 self
551 }
552
553 /// Always show the suggested change.
554 pub fn span_suggestion_verbose(
555 &mut self,
556 sp: Span,
557 msg: &str,
558 suggestion: String,
559 applicability: Applicability,
560 ) -> &mut Self {
561 self.span_suggestion_with_style(
562 sp,
563 msg,
564 suggestion,
565 applicability,
566 SuggestionStyle::ShowAlways,
567 );
568 self
569 }
570
571 /// Prints out a message with multiple suggested edits of the code.
572 /// See also [`Diagnostic::span_suggestion()`].
573 pub fn span_suggestions(
574 &mut self,
575 sp: Span,
576 msg: &str,
577 suggestions: impl Iterator<Item = String>,
578 applicability: Applicability,
579 ) -> &mut Self {
580 let mut suggestions: Vec<_> = suggestions.collect();
581 suggestions.sort();
582 let substitutions = suggestions
583 .into_iter()
584 .map(|snippet| Substitution { parts: vec![SubstitutionPart { snippet, span: sp }] })
585 .collect();
586 self.push_suggestion(CodeSuggestion {
587 substitutions,
588 msg: msg.to_owned(),
589 style: SuggestionStyle::ShowCode,
590 applicability,
591 tool_metadata: Default::default(),
592 });
593 self
594 }
595
596 /// Prints out a message with multiple suggested edits of the code.
597 /// See also [`Diagnostic::span_suggestion()`].
598 pub fn multipart_suggestions(
599 &mut self,
600 msg: &str,
601 suggestions: impl Iterator<Item = Vec<(Span, String)>>,
602 applicability: Applicability,
603 ) -> &mut Self {
604 self.push_suggestion(CodeSuggestion {
605 substitutions: suggestions
606 .map(|sugg| Substitution {
607 parts: sugg
608 .into_iter()
609 .map(|(span, snippet)| SubstitutionPart { snippet, span })
610 .collect(),
611 })
612 .collect(),
613 msg: msg.to_owned(),
614 style: SuggestionStyle::ShowCode,
615 applicability,
616 tool_metadata: Default::default(),
617 });
618 self
619 }
620 /// Prints out a message with a suggested edit of the code. If the suggestion is presented
621 /// inline, it will only show the message and not the suggestion.
622 ///
623 /// See `CodeSuggestion` for more information.
624 pub fn span_suggestion_short(
625 &mut self,
626 sp: Span,
627 msg: &str,
628 suggestion: String,
629 applicability: Applicability,
630 ) -> &mut Self {
631 self.span_suggestion_with_style(
632 sp,
633 msg,
634 suggestion,
635 applicability,
636 SuggestionStyle::HideCodeInline,
637 );
638 self
639 }
640
641 /// Prints out a message for a suggestion without showing the suggested code.
642 ///
643 /// This is intended to be used for suggestions that are obvious in what the changes need to
644 /// be from the message, showing the span label inline would be visually unpleasant
645 /// (marginally overlapping spans or multiline spans) and showing the snippet window wouldn't
646 /// improve understandability.
647 pub fn span_suggestion_hidden(
648 &mut self,
649 sp: Span,
650 msg: &str,
651 suggestion: String,
652 applicability: Applicability,
653 ) -> &mut Self {
654 self.span_suggestion_with_style(
655 sp,
656 msg,
657 suggestion,
658 applicability,
659 SuggestionStyle::HideCodeAlways,
660 );
661 self
662 }
663
664 /// Adds a suggestion to the JSON output that will not be shown in the CLI.
665 ///
666 /// This is intended to be used for suggestions that are *very* obvious in what the changes
667 /// need to be from the message, but we still want other tools to be able to apply them.
668 pub fn tool_only_span_suggestion(
669 &mut self,
670 sp: Span,
671 msg: &str,
672 suggestion: String,
673 applicability: Applicability,
674 ) -> &mut Self {
675 self.span_suggestion_with_style(
676 sp,
677 msg,
678 suggestion,
679 applicability,
680 SuggestionStyle::CompletelyHidden,
681 );
682 self
683 }
684
685 /// Adds a suggestion intended only for a tool. The intent is that the metadata encodes
686 /// the suggestion in a tool-specific way, as it may not even directly involve Rust code.
687 pub fn tool_only_suggestion_with_metadata(
688 &mut self,
689 msg: &str,
690 applicability: Applicability,
691 tool_metadata: Json,
692 ) {
693 self.push_suggestion(CodeSuggestion {
694 substitutions: vec![],
695 msg: msg.to_owned(),
696 style: SuggestionStyle::CompletelyHidden,
697 applicability,
698 tool_metadata: ToolMetadata::new(tool_metadata),
699 })
700 }
701
702 pub fn set_span<S: Into<MultiSpan>>(&mut self, sp: S) -> &mut Self {
703 self.span = sp.into();
704 if let Some(span) = self.span.primary_span() {
705 self.sort_span = span;
706 }
707 self
708 }
709
710 pub fn set_is_lint(&mut self) -> &mut Self {
711 self.is_lint = true;
712 self
713 }
714
715 pub fn code(&mut self, s: DiagnosticId) -> &mut Self {
716 self.code = Some(s);
717 self
718 }
719
720 pub fn clear_code(&mut self) -> &mut Self {
721 self.code = None;
722 self
723 }
724
725 pub fn get_code(&self) -> Option<DiagnosticId> {
726 self.code.clone()
727 }
728
729 pub fn set_primary_message<M: Into<String>>(&mut self, msg: M) -> &mut Self {
730 self.message[0] = (msg.into(), Style::NoStyle);
731 self
732 }
733
734 pub fn message(&self) -> String {
735 self.message.iter().map(|i| i.0.as_str()).collect::<String>()
736 }
737
738 pub fn styled_message(&self) -> &Vec<(String, Style)> {
739 &self.message
740 }
741
742 /// Convenience function for internal use, clients should use one of the
743 /// public methods above.
744 ///
745 /// Used by `proc_macro_server` for implementing `server::Diagnostic`.
746 pub fn sub(
747 &mut self,
748 level: Level,
749 message: &str,
750 span: MultiSpan,
751 render_span: Option<MultiSpan>,
752 ) {
753 let sub = SubDiagnostic {
754 level,
755 message: vec![(message.to_owned(), Style::NoStyle)],
756 span,
757 render_span,
758 };
759 self.children.push(sub);
760 }
761
762 /// Convenience function for internal use, clients should use one of the
763 /// public methods above.
764 fn sub_with_highlights(
765 &mut self,
766 level: Level,
767 message: Vec<(String, Style)>,
768 span: MultiSpan,
769 render_span: Option<MultiSpan>,
770 ) {
771 let sub = SubDiagnostic { level, message, span, render_span };
772 self.children.push(sub);
773 }
774
775 /// Fields used for Hash, and PartialEq trait
776 fn keys(
777 &self,
778 ) -> (
779 &Level,
780 &Vec<(String, Style)>,
781 &Option<DiagnosticId>,
782 &MultiSpan,
783 &Result<Vec<CodeSuggestion>, SuggestionsDisabled>,
784 Option<&Vec<SubDiagnostic>>,
785 ) {
786 (
787 &self.level,
788 &self.message,
789 &self.code,
790 &self.span,
791 &self.suggestions,
792 (if self.is_lint { None } else { Some(&self.children) }),
793 )
794 }
795 }
796
797 impl Hash for Diagnostic {
798 fn hash<H>(&self, state: &mut H)
799 where
800 H: Hasher,
801 {
802 self.keys().hash(state);
803 }
804 }
805
806 impl PartialEq for Diagnostic {
807 fn eq(&self, other: &Self) -> bool {
808 self.keys() == other.keys()
809 }
810 }
811
812 impl SubDiagnostic {
813 pub fn message(&self) -> String {
814 self.message.iter().map(|i| i.0.as_str()).collect::<String>()
815 }
816
817 pub fn styled_message(&self) -> &Vec<(String, Style)> {
818 &self.message
819 }
820 }