1use crate::{SourceMap, Span};
7use anstyle::{AnsiColor, Color};
8use std::{
9 borrow::Cow,
10 fmt::{self, Write},
11 hash::{Hash, Hasher},
12 iter,
13 ops::Deref,
14 panic::Location,
15};
16
17mod builder;
18pub use builder::{DiagBuilder, EmissionGuarantee};
19
20mod context;
21pub use context::{DeferredDiagnostics, DiagCtxt, DiagCtxtFlags, flush_withheld};
22
23mod emitter;
24pub use emitter::{
25 DynEmitter, Emitter, HumanBufferEmitter, HumanEmitter, InMemoryEmitter, LocalEmitter,
26 SilentEmitter,
27};
28#[cfg(feature = "json")]
29pub use emitter::{
30 JsonDiagnostic, JsonDiagnosticCode, JsonDiagnosticMessage, JsonDiagnosticSpan,
31 JsonDiagnosticSpanLine, JsonDiagnosticSpanMacroExpansion, JsonEmitter, Severity,
32 SolcDiagnostic, SourceLocation,
33};
34
35mod message;
36pub use message::{DiagMsg, MultiSpan, SpanLabel};
37
38pub struct EmittedDiagnostics(pub(crate) String);
42
43impl fmt::Debug for EmittedDiagnostics {
44 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45 f.write_str(&self.0)
46 }
47}
48
49impl fmt::Display for EmittedDiagnostics {
50 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
51 f.write_str(&self.0)
52 }
53}
54
55impl std::error::Error for EmittedDiagnostics {}
56
57impl EmittedDiagnostics {
58 pub fn is_empty(&self) -> bool {
60 self.0.is_empty()
61 }
62}
63
64#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
67pub struct ErrorGuaranteed(());
68
69impl fmt::Debug for ErrorGuaranteed {
70 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
71 f.write_str("ErrorGuaranteed")
72 }
73}
74
75impl ErrorGuaranteed {
76 #[inline]
80 pub const fn new_unchecked() -> Self {
81 Self(())
82 }
83}
84
85#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
88pub struct BugAbort;
89
90pub struct ExplicitBug;
93
94pub struct FatalAbort;
96
97#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
108pub struct DiagId {
109 s: Cow<'static, str>,
110}
111
112impl DiagId {
113 pub fn new_str(s: impl Into<Cow<'static, str>>) -> Self {
118 Self { s: s.into() }
119 }
120
121 #[doc(hidden)]
125 #[cfg_attr(debug_assertions, track_caller)]
126 pub fn new_from_macro(id: u32) -> Self {
127 debug_assert!((1..=9999).contains(&id), "error code must be in range 0001-9999");
128 Self { s: Cow::Owned(format!("{id:04}")) }
129 }
130
131 pub fn as_str(&self) -> &str {
133 &self.s
134 }
135}
136
137#[macro_export]
146macro_rules! error_code {
147 ($id:literal) => {
148 $crate::diagnostics::DiagId::new_from_macro($id)
149 };
150}
151
152#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
154pub enum Level {
155 Bug,
159
160 Fatal,
165
166 Error,
171
172 Warning,
176
177 Note,
182
183 OnceNote,
187
188 Help,
193
194 OnceHelp,
198
199 FailureNote,
203
204 Allow,
208}
209
210impl Level {
211 pub fn to_str(self) -> &'static str {
213 match self {
214 Self::Bug => "error: internal compiler error",
215 Self::Fatal | Self::Error => "error",
216 Self::Warning => "warning",
217 Self::Note | Self::OnceNote => "note",
218 Self::Help | Self::OnceHelp => "help",
219 Self::FailureNote => "failure-note",
220 Self::Allow
221 => unreachable!(),
223 }
224 }
225
226 #[inline]
228 pub fn is_error(self) -> bool {
229 match self {
230 Self::Bug | Self::Fatal | Self::Error => true,
231
232 Self::Warning
233 | Self::Note
234 | Self::OnceNote
235 | Self::Help
236 | Self::OnceHelp
237 | Self::FailureNote
238 | Self::Allow => false,
239 }
240 }
241
242 #[inline]
244 pub fn is_note(self) -> bool {
245 match self {
246 Self::Note | Self::OnceNote => true,
247
248 Self::Bug
249 | Self::Fatal
250 | Self::Error
251 | Self::FailureNote
252 | Self::Warning
253 | Self::Help
254 | Self::OnceHelp
255 | Self::Allow => false,
256 }
257 }
258
259 pub fn is_failure_note(&self) -> bool {
260 matches!(*self, Self::FailureNote)
261 }
262
263 #[inline]
265 pub const fn style(self) -> anstyle::Style {
266 anstyle::Style::new().fg_color(self.color()).bold()
267 }
268
269 #[inline]
271 pub const fn color(self) -> Option<Color> {
272 match self.ansi_color() {
273 Some(c) => Some(Color::Ansi(c)),
274 None => None,
275 }
276 }
277
278 #[inline]
280 pub const fn ansi_color(self) -> Option<AnsiColor> {
281 match self {
283 Self::Bug | Self::Fatal | Self::Error => Some(AnsiColor::BrightRed),
284 Self::Warning => {
285 Some(if cfg!(windows) { AnsiColor::BrightYellow } else { AnsiColor::Yellow })
286 }
287 Self::Note | Self::OnceNote => Some(AnsiColor::BrightGreen),
288 Self::Help | Self::OnceHelp => Some(AnsiColor::BrightCyan),
289 Self::FailureNote | Self::Allow => None,
290 }
291 }
292}
293
294impl fmt::Display for Level {
295 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
296 self.to_str().fmt(f)
297 }
298}
299
300#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
301pub enum Style {
302 MainHeaderMsg,
303 HeaderMsg,
304 LineAndColumn,
305 LineNumber,
306 Quotation,
307 UnderlinePrimary,
308 UnderlineSecondary,
309 LabelPrimary,
310 LabelSecondary,
311 NoStyle,
312 Level(Level),
313 Highlight,
314 Addition,
315 Removal,
316}
317
318impl Style {
319 pub const fn to_color_spec(self, level: Level) -> anstyle::Style {
321 use AnsiColor::*;
322
323 const BRIGHT_BLUE: Color = Color::Ansi(if cfg!(windows) { BrightCyan } else { BrightBlue });
327 const GREEN: Color = Color::Ansi(BrightGreen);
328 const RED: Color = Color::Ansi(BrightRed);
329 const WHITE: Color = Color::Ansi(BrightWhite);
330
331 let s = anstyle::Style::new();
332 match self {
333 Self::Addition => s.fg_color(Some(GREEN)),
334 Self::Removal => s.fg_color(Some(RED)),
335 Self::LineAndColumn => s,
336 Self::LineNumber => s.fg_color(Some(BRIGHT_BLUE)).bold(),
337 Self::Quotation => s,
338 Self::MainHeaderMsg => if cfg!(windows) { s.fg_color(Some(WHITE)) } else { s }.bold(),
339 Self::UnderlinePrimary | Self::LabelPrimary => s.fg_color(level.color()).bold(),
340 Self::UnderlineSecondary | Self::LabelSecondary => s.fg_color(Some(BRIGHT_BLUE)).bold(),
341 Self::HeaderMsg | Self::NoStyle => s,
342 Self::Level(level2) => s.fg_color(level2.color()).bold(),
343 Self::Highlight => s.fg_color(Some(Color::Ansi(Magenta))).bold(),
344 }
345 }
346}
347
348pub fn is_different(sm: &SourceMap, suggested: &str, sp: Span) -> bool {
350 let found = match sm.span_to_snippet(sp) {
351 Ok(snippet) => snippet,
352 Err(e) => {
353 warn!(error = ?e, "Invalid span {:?}", sp);
354 return true;
355 }
356 };
357 found != suggested
358}
359
360pub fn detect_confusion_type(sm: &SourceMap, suggested: &str, sp: Span) -> ConfusionType {
362 let found = match sm.span_to_snippet(sp) {
363 Ok(snippet) => snippet,
364 Err(e) => {
365 warn!(error = ?e, "Invalid span {:?}", sp);
366 return ConfusionType::None;
367 }
368 };
369
370 let mut has_case_confusion = false;
371 let mut has_digit_letter_confusion = false;
372
373 if found.len() == suggested.len() {
374 let mut has_case_diff = false;
375 let mut has_digit_letter_confusable = false;
376 let mut has_other_diff = false;
377
378 let ascii_confusables = &['c', 'f', 'i', 'k', 'o', 's', 'u', 'v', 'w', 'x', 'y', 'z'];
379
380 let digit_letter_confusables = [('0', 'O'), ('1', 'l'), ('5', 'S'), ('8', 'B'), ('9', 'g')];
381
382 for (f, s) in iter::zip(found.chars(), suggested.chars()) {
383 if f != s {
384 if f.eq_ignore_ascii_case(&s) {
385 if ascii_confusables.contains(&f) || ascii_confusables.contains(&s) {
387 has_case_diff = true;
388 } else {
389 has_other_diff = true;
390 }
391 } else if digit_letter_confusables.contains(&(f, s))
392 || digit_letter_confusables.contains(&(s, f))
393 {
394 has_digit_letter_confusable = true;
396 } else {
397 has_other_diff = true;
398 }
399 }
400 }
401
402 if has_case_diff && !has_other_diff && found != suggested {
404 has_case_confusion = true;
405 }
406 if has_digit_letter_confusable && !has_other_diff && found != suggested {
407 has_digit_letter_confusion = true;
408 }
409 }
410
411 match (has_case_confusion, has_digit_letter_confusion) {
412 (true, true) => ConfusionType::Both,
413 (true, false) => ConfusionType::Case,
414 (false, true) => ConfusionType::DigitLetter,
415 (false, false) => ConfusionType::None,
416 }
417}
418
419#[derive(Debug, Clone, Copy, PartialEq, Eq)]
421pub enum ConfusionType {
422 None,
424 Case,
426 DigitLetter,
428 Both,
430}
431
432impl ConfusionType {
433 pub fn label_text(&self) -> &'static str {
435 match self {
436 Self::None => "",
437 Self::Case => " (notice the capitalization)",
438 Self::DigitLetter => " (notice the digit/letter confusion)",
439 Self::Both => " (notice the capitalization and digit/letter confusion)",
440 }
441 }
442
443 pub fn combine(self, other: Self) -> Self {
447 match (self, other) {
448 (Self::None, other) => other,
449 (this, Self::None) => this,
450 (Self::Both, _) | (_, Self::Both) => Self::Both,
451 (Self::Case, Self::DigitLetter) | (Self::DigitLetter, Self::Case) => Self::Both,
452 (Self::Case, Self::Case) => Self::Case,
453 (Self::DigitLetter, Self::DigitLetter) => Self::DigitLetter,
454 }
455 }
456
457 pub fn has_confusion(&self) -> bool {
459 *self != Self::None
460 }
461}
462
463#[cfg_attr(feature = "json", derive(serde::Serialize, serde::Deserialize))]
469#[derive(Copy, Clone, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
470pub enum Applicability {
471 MachineApplicable,
478
479 MaybeIncorrect,
482
483 HasPlaceholders,
487
488 #[default]
490 Unspecified,
491}
492
493#[derive(Debug, Default, PartialEq, Eq, Clone, Copy, Hash)]
494pub enum SuggestionStyle {
495 HideCodeInline,
497 HideCodeAlways,
499 CompletelyHidden,
501 #[default]
505 ShowCode,
506 ShowAlways,
508}
509
510impl SuggestionStyle {
511 fn hide_inline(&self) -> bool {
512 !matches!(*self, Self::ShowCode)
513 }
514}
515
516#[derive(Clone, Debug, PartialEq, Hash)]
518pub enum Suggestions {
519 Enabled(Vec<CodeSuggestion>),
524 Sealed(Box<[CodeSuggestion]>),
528 Disabled,
532}
533
534impl Suggestions {
535 pub fn unwrap_tag(&self) -> &[CodeSuggestion] {
537 match self {
538 Self::Enabled(suggestions) => suggestions,
539 Self::Sealed(suggestions) => suggestions,
540 Self::Disabled => &[],
541 }
542 }
543}
544
545impl Default for Suggestions {
546 fn default() -> Self {
547 Self::Enabled(vec![])
548 }
549}
550
551impl Deref for Suggestions {
552 type Target = [CodeSuggestion];
553
554 fn deref(&self) -> &Self::Target {
555 self.unwrap_tag()
556 }
557}
558
559#[derive(Clone, Debug, PartialEq, Eq, Hash)]
562pub struct CodeSuggestion {
563 pub substitutions: Vec<Substitution>,
585 pub msg: DiagMsg,
586 pub style: SuggestionStyle,
588 pub applicability: Applicability,
594}
595
596#[derive(Clone, Debug, PartialEq, Eq, Hash)]
598pub struct SubstitutionPart {
599 pub span: Span,
600 pub snippet: DiagMsg,
601}
602
603impl SubstitutionPart {
604 pub fn is_addition(&self) -> bool {
605 self.span.lo() == self.span.hi() && !self.snippet.is_empty()
606 }
607
608 pub fn is_deletion(&self) -> bool {
609 self.span.lo() != self.span.hi() && self.snippet.is_empty()
610 }
611
612 pub fn is_replacement(&self) -> bool {
613 self.span.lo() != self.span.hi() && !self.snippet.is_empty()
614 }
615}
616
617#[derive(Clone, Debug, PartialEq, Eq, Hash)]
619pub struct Substitution {
620 pub parts: Vec<SubstitutionPart>,
621}
622
623#[derive(Clone, Debug, PartialEq, Hash)]
626pub struct SubDiagnostic {
627 pub level: Level,
628 pub messages: Vec<(DiagMsg, Style)>,
629 pub span: MultiSpan,
630}
631
632impl SubDiagnostic {
633 pub fn label(&self) -> Cow<'_, str> {
635 self.label_with_style(false)
636 }
637
638 pub fn label_with_style(&self, supports_color: bool) -> Cow<'_, str> {
640 flatten_messages(&self.messages, supports_color, self.level)
641 }
642}
643
644#[must_use]
646#[derive(Clone, Debug)]
647pub struct Diag {
648 pub(crate) level: Level,
649
650 pub messages: Vec<(DiagMsg, Style)>,
651 pub span: MultiSpan,
652 pub children: Vec<SubDiagnostic>,
653 pub code: Option<DiagId>,
654 pub suggestions: Suggestions,
655
656 pub created_at: &'static Location<'static>,
657}
658
659impl PartialEq for Diag {
660 fn eq(&self, other: &Self) -> bool {
661 self.keys() == other.keys()
662 }
663}
664
665impl Hash for Diag {
666 fn hash<H: Hasher>(&self, state: &mut H) {
667 self.keys().hash(state);
668 }
669}
670
671impl Diag {
672 #[track_caller]
674 pub fn new<M: Into<DiagMsg>>(level: Level, msg: M) -> Self {
675 Self::new_with_messages(level, vec![(msg.into(), Style::NoStyle)])
676 }
677
678 #[track_caller]
680 pub fn new_with_messages(level: Level, messages: Vec<(DiagMsg, Style)>) -> Self {
681 Self {
682 level,
683 messages,
684 code: None,
685 span: MultiSpan::new(),
686 children: vec![],
687 suggestions: Suggestions::default(),
688 created_at: Location::caller(),
692 }
693 }
694
695 #[inline]
697 pub fn is_error(&self) -> bool {
698 self.level.is_error()
699 }
700
701 #[inline]
703 pub fn is_note(&self) -> bool {
704 self.level.is_note()
705 }
706
707 pub fn label(&self) -> Cow<'_, str> {
709 flatten_messages(&self.messages, false, self.level)
710 }
711
712 pub fn label_with_style(&self, supports_color: bool) -> Cow<'_, str> {
714 flatten_messages(&self.messages, supports_color, self.level)
715 }
716
717 pub fn messages(&self) -> &[(DiagMsg, Style)] {
719 &self.messages
720 }
721
722 pub fn level(&self) -> Level {
724 self.level
725 }
726
727 pub fn id(&self) -> Option<&str> {
729 self.code.as_ref().map(|code| code.as_str())
730 }
731
732 fn keys(&self) -> impl PartialEq + std::hash::Hash {
734 (
735 &self.level,
736 &self.messages,
737 &self.code,
738 &self.span,
739 &self.children,
740 &self.suggestions,
741 )
746 }
747}
748
749impl Diag {
751 pub fn span(&mut self, span: impl Into<MultiSpan>) -> &mut Self {
753 self.span = span.into();
754 self
755 }
756
757 pub fn code(&mut self, code: impl Into<DiagId>) -> &mut Self {
759 self.code = Some(code.into());
760 self
761 }
762
763 pub fn primary_message(&mut self, msg: impl Into<DiagMsg>) -> &mut Self {
765 self.messages[0] = (msg.into(), Style::NoStyle);
766 self
767 }
768
769 pub fn span_label(&mut self, span: Span, label: impl Into<DiagMsg>) -> &mut Self {
778 self.span.push_span_label(span, label);
779 self
780 }
781
782 pub fn span_labels(
785 &mut self,
786 spans: impl IntoIterator<Item = Span>,
787 label: impl Into<DiagMsg>,
788 ) -> &mut Self {
789 let label = label.into();
790 for span in spans {
791 self.span_label(span, label.clone());
792 }
793 self
794 }
795
796 pub fn replace_span_with(&mut self, after: Span, keep_label: bool) -> &mut Self {
798 let before = self.span.clone();
799 self.span(after);
800 for span_label in before.span_labels() {
801 if let Some(label) = span_label.label {
802 if span_label.is_primary && keep_label {
803 self.span.push_span_label(after, label);
804 } else {
805 self.span.push_span_label(span_label.span, label);
806 }
807 }
808 }
809 self
810 }
811
812 pub(crate) fn locations_note(&mut self, emitted_at: &Location<'_>) -> &mut Self {
814 let msg = format!(
815 "created at {},\n\
816 emitted at {}",
817 self.created_at, emitted_at
818 );
819 self.note(msg)
820 }
821}
822
823impl Diag {
825 pub fn warn(&mut self, msg: impl Into<DiagMsg>) -> &mut Self {
827 self.sub(Level::Warning, msg, MultiSpan::new())
828 }
829
830 pub fn span_warn(&mut self, span: impl Into<MultiSpan>, msg: impl Into<DiagMsg>) -> &mut Self {
833 self.sub(Level::Warning, msg, span)
834 }
835
836 pub fn note(&mut self, msg: impl Into<DiagMsg>) -> &mut Self {
838 self.sub(Level::Note, msg, MultiSpan::new())
839 }
840
841 pub fn span_note(&mut self, span: impl Into<MultiSpan>, msg: impl Into<DiagMsg>) -> &mut Self {
844 self.sub(Level::Note, msg, span)
845 }
846
847 pub fn highlighted_note(&mut self, messages: Vec<(impl Into<DiagMsg>, Style)>) -> &mut Self {
848 self.sub_with_highlights(Level::Note, messages, MultiSpan::new())
849 }
850
851 pub fn highlighted_span_note(
853 &mut self,
854 span: impl Into<MultiSpan>,
855 messages: Vec<(impl Into<DiagMsg>, Style)>,
856 ) -> &mut Self {
857 self.sub_with_highlights(Level::Note, messages, span.into())
858 }
859
860 pub fn note_once(&mut self, msg: impl Into<DiagMsg>) -> &mut Self {
863 self.sub(Level::OnceNote, msg, MultiSpan::new())
864 }
865
866 pub fn span_note_once(
869 &mut self,
870 span: impl Into<MultiSpan>,
871 msg: impl Into<DiagMsg>,
872 ) -> &mut Self {
873 self.sub(Level::OnceNote, msg, span)
874 }
875
876 pub fn help(&mut self, msg: impl Into<DiagMsg>) -> &mut Self {
878 self.sub(Level::Help, msg, MultiSpan::new())
879 }
880
881 pub fn help_once(&mut self, msg: impl Into<DiagMsg>) -> &mut Self {
884 self.sub(Level::OnceHelp, msg, MultiSpan::new())
885 }
886
887 pub fn highlighted_help(&mut self, msgs: Vec<(impl Into<DiagMsg>, Style)>) -> &mut Self {
889 self.sub_with_highlights(Level::Help, msgs, MultiSpan::new())
890 }
891
892 pub fn highlighted_span_help(
894 &mut self,
895 span: impl Into<MultiSpan>,
896 messages: Vec<(impl Into<DiagMsg>, Style)>,
897 ) -> &mut Self {
898 self.sub_with_highlights(Level::Help, messages, span.into())
899 }
900
901 pub fn span_help(&mut self, span: impl Into<MultiSpan>, msg: impl Into<DiagMsg>) -> &mut Self {
904 self.sub(Level::Help, msg, span)
905 }
906
907 fn sub(
908 &mut self,
909 level: Level,
910 msg: impl Into<DiagMsg>,
911 span: impl Into<MultiSpan>,
912 ) -> &mut Self {
913 self.children.push(SubDiagnostic {
914 level,
915 messages: vec![(msg.into(), Style::NoStyle)],
916 span: span.into(),
917 });
918 self
919 }
920
921 fn sub_with_highlights(
922 &mut self,
923 level: Level,
924 messages: Vec<(impl Into<DiagMsg>, Style)>,
925 span: MultiSpan,
926 ) -> &mut Self {
927 let messages = messages.into_iter().map(|(m, s)| (m.into(), s)).collect();
928 self.children.push(SubDiagnostic { level, messages, span });
929 self
930 }
931}
932
933impl Diag {
935 pub fn disable_suggestions(&mut self) -> &mut Self {
939 self.suggestions = Suggestions::Disabled;
940 self
941 }
942
943 pub fn seal_suggestions(&mut self) -> &mut Self {
948 if let Suggestions::Enabled(suggestions) = &mut self.suggestions {
949 let suggestions_slice = std::mem::take(suggestions).into_boxed_slice();
950 self.suggestions = Suggestions::Sealed(suggestions_slice);
951 }
952 self
953 }
954
955 fn push_suggestion(&mut self, suggestion: CodeSuggestion) {
960 if let Suggestions::Enabled(suggestions) = &mut self.suggestions {
961 suggestions.push(suggestion);
962 }
963 }
964
965 pub fn span_suggestion(
983 &mut self,
984 span: Span,
985 msg: impl Into<DiagMsg>,
986 suggestion: impl Into<DiagMsg>,
987 applicability: Applicability,
988 ) -> &mut Self {
989 self.span_suggestion_with_style(
990 span,
991 msg,
992 suggestion,
993 applicability,
994 SuggestionStyle::ShowCode,
995 );
996 self
997 }
998
999 pub fn span_suggestion_with_style(
1001 &mut self,
1002 span: Span,
1003 msg: impl Into<DiagMsg>,
1004 suggestion: impl Into<DiagMsg>,
1005 applicability: Applicability,
1006 style: SuggestionStyle,
1007 ) -> &mut Self {
1008 let suggestion = suggestion.into();
1009 debug_assert!(
1010 !(span.lo() == span.hi() && suggestion.is_empty()),
1011 "span must not be empty and have no suggestion"
1012 );
1013 self.push_suggestion(CodeSuggestion {
1014 substitutions: vec![Substitution {
1015 parts: vec![SubstitutionPart { snippet: suggestion, span }],
1016 }],
1017 msg: msg.into(),
1018 style,
1019 applicability,
1020 });
1021 self
1022 }
1023
1024 pub fn span_suggestion_verbose(
1026 &mut self,
1027 span: Span,
1028 msg: impl Into<DiagMsg>,
1029 suggestion: impl Into<DiagMsg>,
1030 applicability: Applicability,
1031 ) -> &mut Self {
1032 self.span_suggestion_with_style(
1033 span,
1034 msg,
1035 suggestion,
1036 applicability,
1037 SuggestionStyle::ShowAlways,
1038 )
1039 }
1040
1041 pub fn span_suggestions(
1043 &mut self,
1044 span: Span,
1045 msg: impl Into<DiagMsg>,
1046 suggestions: impl IntoIterator<Item = DiagMsg>,
1047 applicability: Applicability,
1048 ) -> &mut Self {
1049 self.span_suggestions_with_style(
1050 span,
1051 msg,
1052 suggestions,
1053 applicability,
1054 SuggestionStyle::ShowAlways,
1055 )
1056 }
1057
1058 pub fn span_suggestions_with_style(
1060 &mut self,
1061 span: Span,
1062 msg: impl Into<DiagMsg>,
1063 suggestions: impl IntoIterator<Item = DiagMsg>,
1064 applicability: Applicability,
1065 style: SuggestionStyle,
1066 ) -> &mut Self {
1067 let substitutions = suggestions
1068 .into_iter()
1069 .map(|snippet| {
1070 debug_assert!(
1071 !(span.lo() == span.hi() && snippet.is_empty()),
1072 "span `{span:?}` must not be empty and have no suggestion"
1073 );
1074 Substitution { parts: vec![SubstitutionPart { span, snippet }] }
1075 })
1076 .collect();
1077 self.push_suggestion(CodeSuggestion {
1078 substitutions,
1079 msg: msg.into(),
1080 style,
1081 applicability,
1082 });
1083 self
1084 }
1085
1086 pub fn span_suggestion_short(
1088 &mut self,
1089 span: Span,
1090 msg: impl Into<DiagMsg>,
1091 suggestion: impl Into<DiagMsg>,
1092 applicability: Applicability,
1093 ) -> &mut Self {
1094 self.span_suggestion_with_style(
1095 span,
1096 msg,
1097 suggestion,
1098 applicability,
1099 SuggestionStyle::HideCodeInline,
1100 )
1101 }
1102
1103 pub fn span_suggestion_hidden(
1105 &mut self,
1106 span: Span,
1107 msg: impl Into<DiagMsg>,
1108 suggestion: impl Into<DiagMsg>,
1109 applicability: Applicability,
1110 ) -> &mut Self {
1111 self.span_suggestion_with_style(
1112 span,
1113 msg,
1114 suggestion,
1115 applicability,
1116 SuggestionStyle::HideCodeAlways,
1117 )
1118 }
1119
1120 pub fn tool_only_span_suggestion(
1122 &mut self,
1123 span: Span,
1124 msg: impl Into<DiagMsg>,
1125 suggestion: impl Into<DiagMsg>,
1126 applicability: Applicability,
1127 ) -> &mut Self {
1128 self.span_suggestion_with_style(
1129 span,
1130 msg,
1131 suggestion,
1132 applicability,
1133 SuggestionStyle::CompletelyHidden,
1134 )
1135 }
1136
1137 pub fn multipart_suggestion(
1140 &mut self,
1141 msg: impl Into<DiagMsg>,
1142 substitutions: Vec<(Span, DiagMsg)>,
1143 applicability: Applicability,
1144 ) -> &mut Self {
1145 self.multipart_suggestion_with_style(
1146 msg,
1147 substitutions,
1148 applicability,
1149 SuggestionStyle::ShowAlways,
1150 );
1151 self
1152 }
1153
1154 pub fn multipart_suggestion_with_style(
1156 &mut self,
1157 msg: impl Into<DiagMsg>,
1158 mut substitutions: Vec<(Span, DiagMsg)>,
1159 applicability: Applicability,
1160 style: SuggestionStyle,
1161 ) -> &mut Self {
1162 let mut seen = solar_data_structures::map::FxHashSet::default();
1163 substitutions.retain(|(span, msg)| seen.insert((span.lo(), span.hi(), msg.clone())));
1164
1165 let parts = substitutions
1166 .into_iter()
1167 .map(|(span, snippet)| SubstitutionPart { span, snippet })
1168 .collect::<Vec<_>>();
1169
1170 assert!(!parts.is_empty());
1171 debug_assert_eq!(
1172 parts.iter().find(|part| part.span.lo() == part.span.hi() && part.snippet.is_empty()),
1173 None,
1174 "span must not be empty and have no suggestion",
1175 );
1176 debug_assert_eq!(
1177 parts.windows(2).find(|parts| parts[0].span.overlaps(parts[1].span)),
1178 None,
1179 "suggestion must not have overlapping parts",
1180 );
1181
1182 self.push_suggestion(CodeSuggestion {
1183 substitutions: vec![Substitution { parts }],
1184 msg: msg.into(),
1185 style,
1186 applicability,
1187 });
1188 self
1189 }
1190
1191 pub fn tool_only_multipart_suggestion(
1193 &mut self,
1194 msg: impl Into<DiagMsg>,
1195 substitutions: Vec<(Span, DiagMsg)>,
1196 applicability: Applicability,
1197 ) -> &mut Self {
1198 self.multipart_suggestion_with_style(
1199 msg,
1200 substitutions,
1201 applicability,
1202 SuggestionStyle::CompletelyHidden,
1203 )
1204 }
1205
1206 pub fn multipart_suggestions(
1208 &mut self,
1209 msg: impl Into<DiagMsg>,
1210 suggestions: impl IntoIterator<Item = Vec<(Span, DiagMsg)>>,
1211 applicability: Applicability,
1212 ) -> &mut Self {
1213 let substitutions = suggestions
1214 .into_iter()
1215 .map(|suggestion| {
1216 let mut parts = suggestion
1217 .into_iter()
1218 .map(|(span, snippet)| SubstitutionPart { span, snippet })
1219 .collect::<Vec<_>>();
1220 parts.sort_unstable_by_key(|part| part.span);
1221
1222 assert!(!parts.is_empty());
1223 debug_assert_eq!(
1224 parts
1225 .iter()
1226 .find(|part| part.span.lo() == part.span.hi() && part.snippet.is_empty()),
1227 None,
1228 "span must not be empty and have no suggestion",
1229 );
1230 debug_assert_eq!(
1231 parts.windows(2).find(|parts| parts[0].span.overlaps(parts[1].span)),
1232 None,
1233 "suggestion must not have overlapping parts",
1234 );
1235
1236 Substitution { parts }
1237 })
1238 .collect();
1239
1240 self.push_suggestion(CodeSuggestion {
1241 substitutions,
1242 msg: msg.into(),
1243 style: SuggestionStyle::ShowAlways,
1244 applicability,
1245 });
1246 self
1247 }
1248}
1249
1250fn flatten_messages(messages: &[(DiagMsg, Style)], with_style: bool, level: Level) -> Cow<'_, str> {
1252 if with_style {
1253 match messages {
1254 [] => Cow::Borrowed(""),
1255 [(msg, Style::NoStyle)] => Cow::Borrowed(msg.as_str()),
1256 [(msg, style)] => {
1257 let mut res = String::new();
1258 write_fmt(&mut res, msg, style, level);
1259 Cow::Owned(res)
1260 }
1261 messages => {
1262 let mut res = String::new();
1263 for (msg, style) in messages {
1264 match style {
1265 Style::NoStyle => res.push_str(msg.as_str()),
1266 _ => write_fmt(&mut res, msg, style, level),
1267 }
1268 }
1269 Cow::Owned(res)
1270 }
1271 }
1272 } else {
1273 match messages {
1274 [] => Cow::Borrowed(""),
1275 [(message, _)] => Cow::Borrowed(message.as_str()),
1276 messages => messages.iter().map(|(msg, _)| msg.as_str()).collect(),
1277 }
1278 }
1279}
1280
1281fn write_fmt(output: &mut String, msg: &DiagMsg, style: &Style, level: Level) {
1282 let style = style.to_color_spec(level);
1283 let _ = write!(output, "{style}{}{style:#}", msg.as_str());
1284}
1285
1286#[cfg(test)]
1287mod tests {
1288 use super::*;
1289 use crate::{BytePos, ColorChoice, Span, source_map};
1290 use rayon::prelude::*;
1291 #[cfg(feature = "json")]
1292 use snapbox::IntoData as _;
1293 use snapbox::{assert_data_eq, str};
1294 use solar_config::HumanEmitterKind;
1295 use std::sync::Arc;
1296
1297 #[test]
1298 fn test_styled_messages() {
1299 let mut diag = Diag::new(Level::Note, "test");
1300
1301 diag.highlighted_note(vec![
1302 ("plain text ", Style::NoStyle),
1303 ("removed", Style::Removal),
1304 (" middle ", Style::NoStyle),
1305 ("added", Style::Addition),
1306 ]);
1307
1308 let sub = &diag.children[0];
1309
1310 assert_data_eq!(&*sub.label(), str!["plain text removed middle added"]);
1311
1312 assert_data_eq!(
1313 &*sub.label_with_style(true),
1314 str!["plain text [91mremoved[0m middle [92madded[0m"]
1315 );
1316 }
1317
1318 #[test]
1319 fn test_short_message_has_no_extra_separator() {
1320 let mut emitter =
1321 HumanBufferEmitter::new(ColorChoice::Never).human_kind(HumanEmitterKind::Short);
1322 emitter.inner_mut().set_ui_testing(true);
1323 emitter.emit_diagnostic(&mut Diag::new(Level::Error, "boom"));
1324
1325 assert_data_eq!(
1326 emitter.buffer(),
1327 str![[r#"
1328error: boom
1329
1330"#]]
1331 );
1332 }
1333
1334 #[test]
1335 fn test_inline_suggestion() {
1336 let (var_span, var_sugg) = (Span::new(BytePos(66), BytePos(72)), "myVar");
1337 let mut diag = Diag::new(Level::Note, "mutable variables should use mixedCase");
1338 diag.span(var_span).span_suggestion(
1339 var_span,
1340 "mutable variables should use mixedCase",
1341 var_sugg,
1342 Applicability::MachineApplicable,
1343 );
1344
1345 assert_eq!(diag.suggestions.len(), 1);
1346 assert_eq!(diag.suggestions[0].applicability, Applicability::MachineApplicable);
1347 assert_eq!(diag.suggestions[0].style, SuggestionStyle::ShowCode);
1348
1349 assert_data_eq!(
1350 emit_human_diagnostics(diag),
1351 str![[r#"
1352note: mutable variables should use mixedCase
1353 ╭▸ <test.sol>:4:17
1354 │
13554 │ uint256 my_var = 0;
1356 ╰╴ ━━━━━━ help: mutable variables should use mixedCase: `myVar`
1357
1358
1359"#]]
1360 );
1361 }
1362
1363 #[test]
1364 fn test_emit_diagnostic_ref_preserves_inline_suggestion() {
1365 let (var_span, var_sugg) = (Span::new(BytePos(66), BytePos(72)), "myVar");
1366 let mut diag = Diag::new(Level::Note, "mutable variables should use mixedCase");
1367 diag.span(var_span).span_suggestion(
1368 var_span,
1369 "mutable variables should use mixedCase",
1370 var_sugg,
1371 Applicability::MachineApplicable,
1372 );
1373
1374 let sm = std::sync::Arc::new(source_map::SourceMap::empty());
1375 sm.new_source_file(source_map::FileName::custom("test.sol"), CONTRACT.to_string()).unwrap();
1376 let mut emitter = HumanBufferEmitter::new(ColorChoice::Never).source_map(Some(sm));
1377 emitter.emit_diagnostic_ref(&diag);
1378
1379 assert_eq!(diag.suggestions.len(), 1);
1380 assert_eq!(diag.suggestions[0].style, SuggestionStyle::ShowCode);
1381 }
1382
1383 #[cfg(feature = "json")]
1384 #[test]
1385 fn test_solc_diagnostic_color() {
1386 let sm = Arc::new(source_map::SourceMap::empty());
1387 sm.new_source_file(source_map::FileName::custom("test.sol"), CONTRACT.to_string()).unwrap();
1388 let diagnostic = Diag::new(Level::Error, "mismatched types");
1389
1390 for (color, expected) in [(ColorChoice::Always, true), (ColorChoice::Auto, false)] {
1391 let mut emitter = JsonEmitter::new(Box::new(std::io::sink()), Arc::clone(&sm), color);
1392 let formatted = emitter.solc_diagnostic(&diagnostic).formatted_message.unwrap();
1393 assert_eq!(formatted.contains("\x1b["), expected, "{formatted:?}");
1394 }
1395 }
1396
1397 #[test]
1398 fn test_inline_suggestion_marks_confusable_case() {
1399 let span = Span::new(BytePos(43), BytePos(47));
1400 let mut diag = Diag::new(Level::Warning, "confusable spelling");
1401 diag.span(span).span_suggestion(
1402 span,
1403 "capitalize this",
1404 "View",
1405 Applicability::MachineApplicable,
1406 );
1407
1408 assert_data_eq!(
1409 emit_human_diagnostics(diag),
1410 str![[r#"
1411warning: confusable spelling
1412 ╭▸ <test.sol>:3:27
1413 │
14143 │ function foo() public view {
1415 ╰╴ ━━━━ help: capitalize this (notice the capitalization): `View`
1416
1417
1418"#]]
1419 );
1420 }
1421
1422 #[test]
1423 fn test_allowed_diagnostic_code_suppresses_warning() {
1424 let dcx = DiagCtxt::with_buffer_emitter(None, ColorChoice::Never)
1425 .with_allowed_diagnostic_codes(["1234".to_string()]);
1426
1427 dcx.warn("suppressed warning").code(crate::error_code!(1234)).emit();
1428 dcx.warn("emitted warning").code(crate::error_code!(5678)).emit();
1429
1430 let diagnostics = dcx.emitted_diagnostics().unwrap().to_string();
1431 assert_eq!(dcx.warn_count(), 1);
1432 assert!(diagnostics.contains("emitted warning"));
1433 assert!(!diagnostics.contains("suppressed warning"));
1434 }
1435
1436 #[test]
1437 fn test_allowed_diagnostic_code_does_not_suppress_error() {
1438 let dcx = DiagCtxt::with_buffer_emitter(None, ColorChoice::Never)
1439 .with_allowed_diagnostic_codes(["1234".to_string()]);
1440
1441 let _ = dcx.err("emitted error").code(crate::error_code!(1234)).emit();
1442
1443 assert!(dcx.has_errors().is_err());
1444 assert!(dcx.emitted_diagnostics().unwrap().to_string().contains("emitted error"));
1445 }
1446
1447 #[test]
1448 fn test_reset_err_count_clears_deduplication_cache() {
1449 let (emitter, diagnostics) = InMemoryEmitter::new();
1450 let dcx = DiagCtxt::new(Box::new(emitter)).with_flags(|flags| {
1451 flags.track_diagnostics = false;
1452 });
1453
1454 for _ in 0..2 {
1455 let _ = dcx.err("duplicate").emit();
1456 }
1457 assert_eq!(dcx.err_count(), 2);
1458 assert_eq!(diagnostics.read().len(), 1);
1459
1460 dcx.reset_err_count();
1461 assert_eq!(dcx.err_count(), 0);
1462
1463 let _ = dcx.err("duplicate").emit();
1464 assert_eq!(dcx.err_count(), 1);
1465 assert_eq!(diagnostics.read().len(), 2);
1466 }
1467
1468 #[test]
1469 fn test_once_subdiagnostic_is_collected_once() {
1470 let (emitter, diagnostics) = InMemoryEmitter::new();
1471 let dcx = DiagCtxt::new(Box::new(emitter)).with_flags(|flags| {
1472 flags.track_diagnostics = false;
1473 });
1474
1475 let _ = dcx.err("first").note_once("shared note").emit();
1476 let _ = dcx.err("second").note_once("shared note").emit();
1477
1478 let diagnostics = diagnostics.read();
1479 assert_eq!(diagnostics.len(), 2);
1480 assert_eq!(diagnostics[0].children.len(), 1);
1481 assert!(diagnostics[1].children.is_empty());
1482 }
1483
1484 #[test]
1485 fn test_deferred_diagnostics_are_counted_at_once_and_emitted_in_order() {
1486 let (emitter, diagnostics) = InMemoryEmitter::new();
1487 let dcx = DiagCtxt::new(Box::new(emitter)).with_flags(|flags| {
1488 flags.track_diagnostics = false;
1489 });
1490
1491 let (_, outer) = dcx.defer(|| {
1492 let _ = dcx.err("first").emit();
1493 let (_, inner) = dcx.defer(|| {
1494 let _ = dcx.err("inner").emit();
1495 let _ = dcx.err("inner").emit();
1496 });
1497 let _ = dcx.err("second").emit();
1498 dcx.emit_deferred(inner);
1499 });
1500 let _ = dcx.err("direct").emit();
1501
1502 assert_eq!(dcx.err_count(), 5);
1503 let messages = || {
1504 diagnostics
1505 .read()
1506 .iter()
1507 .map(|diag| diag.messages[0].0.as_str().to_string())
1508 .collect::<Vec<_>>()
1509 };
1510 assert_eq!(messages(), ["direct"]);
1511
1512 dcx.emit_deferred(outer);
1513 assert_eq!(messages(), ["direct", "first", "second", "inner"]);
1514 }
1515
1516 #[test]
1517 fn test_deferred_diagnostics_are_emitted_when_the_deferring_code_panics() {
1518 let (emitter, diagnostics) = InMemoryEmitter::new();
1519 let dcx = DiagCtxt::new(Box::new(emitter)).with_flags(|flags| {
1520 flags.track_diagnostics = false;
1521 });
1522
1523 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1524 dcx.defer(|| {
1525 let _ = dcx.err("withheld").emit();
1526 panic!("boom");
1527 })
1528 }));
1529
1530 assert!(result.is_err());
1531 assert_eq!(diagnostics.read().len(), 1);
1532 }
1533
1534 fn buffer_dcx() -> (DiagCtxt, Arc<solar_data_structures::sync::RwLock<Vec<Diag>>>) {
1535 let (emitter, diagnostics) = InMemoryEmitter::new();
1536 let dcx = DiagCtxt::new(Box::new(emitter)).with_flags(|flags| {
1537 flags.track_diagnostics = false;
1538 });
1539 (dcx, diagnostics)
1540 }
1541
1542 fn messages(diagnostics: &solar_data_structures::sync::RwLock<Vec<Diag>>) -> Vec<String> {
1543 diagnostics.read().iter().map(|diag| diag.messages[0].0.as_str().to_string()).collect()
1544 }
1545
1546 #[test]
1547 fn test_flush_withheld_emits_batches_that_are_still_held() {
1548 let (dcx, diagnostics) = buffer_dcx();
1549
1550 let (_, first) = dcx.defer(|| dcx.warn("first").emit());
1551 let (_, second) = dcx.defer(|| dcx.warn("second").emit());
1552 assert!(messages(&diagnostics).is_empty());
1553
1554 dcx.flush_withheld();
1555 assert_eq!(messages(&diagnostics), ["first", "second"]);
1556
1557 dcx.emit_deferred(second);
1559 dcx.emit_deferred(first);
1560 assert_eq!(messages(&diagnostics), ["first", "second"]);
1561 }
1562
1563 #[test]
1564 fn test_bug_and_fatal_emit_withheld_diagnostics_first() {
1565 for fatal in [false, true] {
1566 let (dcx, diagnostics) = buffer_dcx();
1567 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1568 let (_, _held) = dcx.defer(|| {
1569 dcx.err("earlier").emit();
1570 if fatal {
1571 dcx.fatal("last").emit();
1572 } else {
1573 dcx.bug("last").emit();
1574 }
1575 });
1576 }));
1577 assert!(result.is_err());
1578 assert_eq!(messages(&diagnostics), ["earlier", "last"]);
1579 }
1580 }
1581
1582 #[test]
1583 fn test_deferred_diagnostics_are_emitted_when_a_sibling_panics() {
1584 let (dcx, diagnostics) = buffer_dcx();
1585
1586 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1587 dcx.par_for_each((0..64).into_par_iter(), |i| {
1588 dcx.warn(format!("{i}")).emit();
1589 if i == 63 {
1590 panic!("boom");
1591 }
1592 });
1593 }));
1594
1595 assert!(result.is_err());
1596 assert_eq!(diagnostics.read().len(), 64);
1597 }
1598
1599 #[test]
1600 fn test_emitter_can_forward_to_another_context() {
1601 struct Forward(Arc<DiagCtxt>);
1602 impl Emitter for Forward {
1603 fn emit_diagnostic(&mut self, diagnostic: &mut Diag) {
1604 let _ = self.0.err(diagnostic.messages[0].0.as_str().to_string()).emit();
1605 }
1606 }
1607
1608 let (target, diagnostics) = buffer_dcx();
1609 let dcx = DiagCtxt::new(Box::new(Forward(Arc::new(target))));
1610
1611 let (_, deferred) = dcx.defer(|| dcx.err("forwarded").emit());
1612 dcx.emit_deferred(deferred);
1613 let _ = dcx.err("direct").emit();
1614
1615 assert_eq!(messages(&diagnostics), ["forwarded", "direct"]);
1616 }
1617
1618 #[test]
1619 fn test_nested_deferrals_of_distinct_contexts() {
1620 let (a, a_diagnostics) = buffer_dcx();
1621 let (b, b_diagnostics) = buffer_dcx();
1622
1623 let ((_, inner), outer) = a.defer(|| b.defer(|| a.warn("from a").emit()));
1624 assert_eq!(messages(&a_diagnostics), ["from a"]);
1626 a.emit_deferred(outer);
1627 b.emit_deferred(inner);
1628 assert!(messages(&b_diagnostics).is_empty());
1629 }
1630
1631 #[test]
1632 fn test_session_keeps_the_source_map_of_a_context_that_deferred() {
1633 let source_map = std::sync::Arc::new(source_map::SourceMap::empty());
1634 let dcx = DiagCtxt::with_buffer_emitter(Some(source_map.clone()), ColorChoice::Never);
1635 let (_, deferred) = dcx.defer(|| dcx.warn("withheld").emit());
1636 dcx.emit_deferred(deferred);
1637
1638 let sess = crate::Session::builder().dcx(dcx).build();
1639
1640 assert!(std::ptr::eq(sess.source_map(), &*source_map));
1641 }
1642
1643 #[cfg(debug_assertions)]
1644 #[test]
1645 fn test_emission_from_unwrapped_parallel_work_is_asserted() {
1646 let (dcx, _) = buffer_dcx();
1647
1648 let (panicked, _) = dcx.defer(|| {
1649 std::thread::scope(|scope| {
1650 scope
1651 .spawn(|| {
1652 std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1653 let _ = dcx.err("from a thread without a deferral").emit();
1654 }))
1655 .is_err()
1656 })
1657 .join()
1658 .unwrap()
1659 })
1660 });
1661
1662 assert!(panicked);
1663 }
1664
1665 #[test]
1666 fn test_par_for_each_emits_in_item_order() {
1667 let (emitter, diagnostics) = InMemoryEmitter::new();
1668 let dcx = DiagCtxt::new(Box::new(emitter)).with_flags(|flags| {
1669 flags.track_diagnostics = false;
1670 });
1671
1672 dcx.par_for_each((0..256).into_par_iter(), |i| {
1673 dcx.warn(format!("{i}")).emit();
1674 dcx.warn(format!("{i} again")).emit();
1675 });
1676
1677 let expected =
1678 (0..256).flat_map(|i| [format!("{i}"), format!("{i} again")]).collect::<Vec<_>>();
1679 let actual = diagnostics
1680 .read()
1681 .iter()
1682 .map(|diag| diag.messages[0].0.as_str().to_string())
1683 .collect::<Vec<_>>();
1684 assert_eq!(actual, expected);
1685 }
1686
1687 #[test]
1688 fn test_treat_first_error_as_bug() {
1689 let dcx = DiagCtxt::with_buffer_emitter(None, ColorChoice::Never).with_flags(|flags| {
1690 flags.track_diagnostics = false;
1691 flags.treat_err_as_bug = std::num::NonZeroUsize::new(1);
1692 });
1693
1694 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1695 dcx.err("boom").emit();
1696 }));
1697
1698 assert!(result.is_err());
1699 assert_data_eq!(
1700 dcx.emitted_diagnostics().unwrap().to_string(),
1701 str![[r#"
1702error: internal compiler error: boom
1703
1704
1705"#]]
1706 );
1707 }
1708
1709 #[test]
1710 fn test_failure_note_is_not_an_error() {
1711 assert!(!Level::FailureNote.is_error());
1712 }
1713
1714 #[test]
1715 fn test_suggestion() {
1716 let (var_span, var_sugg) = (Span::new(BytePos(66), BytePos(72)), "myVar");
1717 let mut diag = Diag::new(Level::Note, "mutable variables should use mixedCase");
1718 diag.span(var_span).span_suggestion_with_style(
1719 var_span,
1720 "mutable variables should use mixedCase",
1721 var_sugg,
1722 Applicability::MachineApplicable,
1723 SuggestionStyle::ShowAlways,
1724 );
1725
1726 assert_eq!(diag.suggestions.len(), 1);
1727 assert_eq!(diag.suggestions[0].applicability, Applicability::MachineApplicable);
1728 assert_eq!(diag.suggestions[0].style, SuggestionStyle::ShowAlways);
1729
1730 assert_data_eq!(
1731 emit_human_diagnostics(diag),
1732 str![[r#"
1733note: mutable variables should use mixedCase
1734 ╭▸ <test.sol>:4:17
1735 │
17364 │ uint256 my_var = 0;
1737 │ ━━━━━━
1738 ╰╴
1739help: mutable variables should use mixedCase
1740 ╭╴
17414 - uint256 my_var = 0;
17424 + uint256 myVar = 0;
1743 ╰╴
1744
1745
1746"#]]
1747 );
1748 }
1749
1750 #[test]
1751 fn test_suggestion_with_footer() {
1752 let (var_span, var_sugg) = (Span::new(BytePos(66), BytePos(72)), "myVar");
1753 let mut diag = Diag::new(Level::Note, "mutable variables should use mixedCase");
1754 diag.span(var_span)
1755 .span_suggestion_with_style(
1756 var_span,
1757 "mutable variables should use mixedCase",
1758 var_sugg,
1759 Applicability::MachineApplicable,
1760 SuggestionStyle::ShowAlways,
1761 )
1762 .help("some footer help msg that should be displayed at the very bottom");
1763
1764 assert_eq!(diag.suggestions.len(), 1);
1765 assert_eq!(diag.suggestions[0].applicability, Applicability::MachineApplicable);
1766 assert_eq!(diag.suggestions[0].style, SuggestionStyle::ShowAlways);
1767
1768 assert_data_eq!(
1769 emit_human_diagnostics(diag),
1770 str![[r#"
1771note: mutable variables should use mixedCase
1772 ╭▸ <test.sol>:4:17
1773 │
17744 │ uint256 my_var = 0;
1775 │ ━━━━━━
1776 │
1777 ╰ help: some footer help msg that should be displayed at the very bottom
1778help: mutable variables should use mixedCase
1779 ╭╴
17804 - uint256 my_var = 0;
17814 + uint256 myVar = 0;
1782 ╰╴
1783
1784
1785"#]]
1786 );
1787 }
1788
1789 #[test]
1790 fn test_multispan_suggestion() {
1791 let (pub_span, pub_sugg) = (Span::new(BytePos(36), BytePos(42)), DiagMsg::from("external"));
1792 let (view_span, view_sugg) = (Span::new(BytePos(43), BytePos(47)), DiagMsg::from("pure"));
1793 let mut diag = Diag::new(Level::Warning, "inefficient visibility and mutability");
1794 diag.span(vec![pub_span, view_span]).multipart_suggestion(
1795 "consider changing visibility and mutability",
1796 vec![(pub_span, pub_sugg.clone()), (pub_span, pub_sugg), (view_span, view_sugg)],
1797 Applicability::MaybeIncorrect,
1798 );
1799
1800 assert_eq!(diag.suggestions[0].substitutions.len(), 1);
1801 assert_eq!(diag.suggestions[0].substitutions[0].parts.len(), 2);
1802 assert_eq!(diag.suggestions[0].applicability, Applicability::MaybeIncorrect);
1803 assert_eq!(diag.suggestions[0].style, SuggestionStyle::ShowAlways);
1804
1805 assert_data_eq!(
1806 emit_human_diagnostics(diag),
1807 str![[r#"
1808warning: inefficient visibility and mutability
1809 ╭▸ <test.sol>:3:20
1810 │
18113 │ function foo() public view {
1812 │ ━━━━━━ ━━━━
1813 ╰╴
1814help: consider changing visibility and mutability
1815 ╭╴
18163 - function foo() public view {
18173 + function foo() external pure {
1818 ╰╴
1819
1820
1821"#]]
1822 );
1823 }
1824
1825 #[test]
1826 #[cfg(feature = "json")]
1827 fn test_json_suggestion() {
1828 let (var_span, var_sugg) = (Span::new(BytePos(66), BytePos(72)), "myVar");
1829 let mut diag = Diag::new(Level::Note, "mutable variables should use mixedCase");
1830 diag.span(var_span).span_suggestion(
1831 var_span,
1832 "mutable variables should use mixedCase",
1833 var_sugg,
1834 Applicability::MachineApplicable,
1835 );
1836
1837 assert_eq!(diag.suggestions.len(), 1);
1838 assert_eq!(diag.suggestions[0].applicability, Applicability::MachineApplicable);
1839 assert_eq!(diag.suggestions[0].style, SuggestionStyle::ShowCode);
1840
1841 assert_data_eq!(
1842 emit_json_diagnostics(diag),
1843 str![[r#"
1844{
1845 "$message_type": "diagnostic",
1846 "children": [
1847 {
1848 "children": [],
1849 "code": null,
1850 "level": "help",
1851 "message": "mutable variables should use mixedCase",
1852 "rendered": null,
1853 "spans": [
1854 {
1855 "byte_end": 72,
1856 "byte_start": 66,
1857 "column_end": 23,
1858 "column_start": 17,
1859 "file_name": "<test.sol>",
1860 "is_primary": true,
1861 "label": null,
1862 "line_end": 4,
1863 "line_start": 4,
1864 "suggested_replacement": "myVar",
1865 "suggestion_applicability": "MachineApplicable",
1866 "expansion": null,
1867 "text": [
1868 {
1869 "highlight_end": 23,
1870 "highlight_start": 17,
1871 "text": " uint256 my_var = 0;"
1872 }
1873 ]
1874 }
1875 ]
1876 }
1877 ],
1878 "code": null,
1879 "level": "note",
1880 "message": "mutable variables should use mixedCase",
1881 "rendered": "note: mutable variables should use mixedCase\n ╭▸ <test.sol>:4:17\n │\n4 │ uint256 my_var = 0;\n ╰╴ ━━━━━━ help: mutable variables should use mixedCase: `myVar`\n\n",
1882 "spans": [
1883 {
1884 "byte_end": 72,
1885 "byte_start": 66,
1886 "column_end": 23,
1887 "column_start": 17,
1888 "file_name": "<test.sol>",
1889 "is_primary": true,
1890 "label": null,
1891 "line_end": 4,
1892 "line_start": 4,
1893 "suggested_replacement": null,
1894 "suggestion_applicability": null,
1895 "expansion": null,
1896 "text": [
1897 {
1898 "highlight_end": 23,
1899 "highlight_start": 17,
1900 "text": " uint256 my_var = 0;"
1901 }
1902 ]
1903 }
1904 ]
1905}
1906"#]].is_json()
1907 );
1908 }
1909
1910 #[test]
1911 #[cfg(feature = "json")]
1912 fn test_multispan_json_suggestion() {
1913 let (pub_span, pub_sugg) = (Span::new(BytePos(36), BytePos(42)), "external".into());
1914 let (view_span, view_sugg) = (Span::new(BytePos(43), BytePos(47)), "pure".into());
1915 let mut diag = Diag::new(Level::Warning, "inefficient visibility and mutability");
1916 diag.span(vec![pub_span, view_span]).multipart_suggestion(
1917 "consider changing visibility and mutability",
1918 vec![(pub_span, pub_sugg), (view_span, view_sugg)],
1919 Applicability::MaybeIncorrect,
1920 );
1921
1922 assert_eq!(diag.suggestions[0].substitutions.len(), 1);
1923 assert_eq!(diag.suggestions[0].substitutions[0].parts.len(), 2);
1924 assert_eq!(diag.suggestions[0].applicability, Applicability::MaybeIncorrect);
1925 assert_eq!(diag.suggestions[0].style, SuggestionStyle::ShowAlways);
1926
1927 assert_data_eq!(
1928 emit_json_diagnostics(diag),
1929 str![[r#"
1930{
1931 "$message_type": "diagnostic",
1932 "children": [
1933 {
1934 "children": [],
1935 "code": null,
1936 "level": "help",
1937 "message": "consider changing visibility and mutability",
1938 "rendered": null,
1939 "spans": [
1940 {
1941 "byte_end": 42,
1942 "byte_start": 36,
1943 "column_end": 26,
1944 "column_start": 20,
1945 "file_name": "<test.sol>",
1946 "is_primary": true,
1947 "label": null,
1948 "line_end": 3,
1949 "line_start": 3,
1950 "suggested_replacement": "external",
1951 "suggestion_applicability": "MaybeIncorrect",
1952 "expansion": null,
1953 "text": [
1954 {
1955 "highlight_end": 26,
1956 "highlight_start": 20,
1957 "text": " function foo() public view {"
1958 }
1959 ]
1960 },
1961 {
1962 "byte_end": 47,
1963 "byte_start": 43,
1964 "column_end": 31,
1965 "column_start": 27,
1966 "file_name": "<test.sol>",
1967 "is_primary": true,
1968 "label": null,
1969 "line_end": 3,
1970 "line_start": 3,
1971 "suggested_replacement": "pure",
1972 "suggestion_applicability": "MaybeIncorrect",
1973 "expansion": null,
1974 "text": [
1975 {
1976 "highlight_end": 31,
1977 "highlight_start": 27,
1978 "text": " function foo() public view {"
1979 }
1980 ]
1981 }
1982 ]
1983 }
1984 ],
1985 "code": null,
1986 "level": "warning",
1987 "message": "inefficient visibility and mutability",
1988 "rendered": "warning: inefficient visibility and mutability\n ╭▸ <test.sol>:3:20\n │\n3 │ function foo() public view {\n │ ━━━━━━ ━━━━\n ╰╴\nhelp: consider changing visibility and mutability\n ╭╴\n3 - function foo() public view {\n3 + function foo() external pure {\n ╰╴\n\n",
1989 "spans": [
1990 {
1991 "byte_end": 42,
1992 "byte_start": 36,
1993 "column_end": 26,
1994 "column_start": 20,
1995 "file_name": "<test.sol>",
1996 "is_primary": true,
1997 "label": null,
1998 "line_end": 3,
1999 "line_start": 3,
2000 "suggested_replacement": null,
2001 "suggestion_applicability": null,
2002 "expansion": null,
2003 "text": [
2004 {
2005 "highlight_end": 26,
2006 "highlight_start": 20,
2007 "text": " function foo() public view {"
2008 }
2009 ]
2010 },
2011 {
2012 "byte_end": 47,
2013 "byte_start": 43,
2014 "column_end": 31,
2015 "column_start": 27,
2016 "file_name": "<test.sol>",
2017 "is_primary": true,
2018 "label": null,
2019 "line_end": 3,
2020 "line_start": 3,
2021 "suggested_replacement": null,
2022 "suggestion_applicability": null,
2023 "expansion": null,
2024 "text": [
2025 {
2026 "highlight_end": 31,
2027 "highlight_start": 27,
2028 "text": " function foo() public view {"
2029 }
2030 ]
2031 }
2032 ]
2033}
2034"#]].is_json()
2035 );
2036 }
2037
2038 #[test]
2039 #[cfg(feature = "json")]
2040 fn test_json_suggestion_alternatives_are_separate_children() {
2041 let public = Span::new(BytePos(36), BytePos(42));
2042 let view = Span::new(BytePos(43), BytePos(47));
2043 let mut diag = Diag::new(Level::Warning, "inefficient visibility and mutability");
2044 diag.span(vec![public, view]).multipart_suggestions(
2045 "consider changing visibility and mutability",
2046 [
2047 vec![(public, "external".into()), (view, "pure".into())],
2048 vec![(public, "internal".into()), (view, "payable".into())],
2049 ],
2050 Applicability::MaybeIncorrect,
2051 );
2052
2053 let diagnostic: serde_json::Value =
2054 serde_json::from_str(&emit_json_diagnostics(diag)).unwrap();
2055 let replacements = diagnostic["children"]
2056 .as_array()
2057 .unwrap()
2058 .iter()
2059 .map(|child| {
2060 child["spans"]
2061 .as_array()
2062 .unwrap()
2063 .iter()
2064 .map(|span| span["suggested_replacement"].as_str().unwrap())
2065 .collect::<Vec<_>>()
2066 })
2067 .collect::<Vec<_>>();
2068
2069 assert_eq!(replacements, [["external", "pure"], ["internal", "payable"]]);
2070 }
2071
2072 const CONTRACT: &str = r#"
2075contract Test {
2076 function foo() public view {
2077 uint256 my_var = 0;
2078 }
2079}"#;
2080
2081 fn emit_human_diagnostics(diag: Diag) -> String {
2083 let sm = source_map::SourceMap::empty();
2084 sm.new_source_file(source_map::FileName::custom("test.sol"), CONTRACT.to_string()).unwrap();
2085
2086 let dcx = DiagCtxt::with_buffer_emitter(Some(std::sync::Arc::new(sm)), ColorChoice::Never);
2087 let _ = dcx.emit_diagnostic(diag);
2088
2089 dcx.emitted_diagnostics().unwrap().0
2090 }
2091
2092 #[cfg(feature = "json")]
2093 use std::sync::Mutex;
2094
2095 #[cfg(feature = "json")]
2096 #[derive(Clone)]
2097 struct SharedWriter(Arc<Mutex<Vec<u8>>>);
2098
2099 #[cfg(feature = "json")]
2100 impl std::io::Write for SharedWriter {
2101 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
2102 self.0.lock().unwrap().write(buf)
2103 }
2104 fn flush(&mut self) -> std::io::Result<()> {
2105 self.0.lock().unwrap().flush()
2106 }
2107 }
2108
2109 #[cfg(feature = "json")]
2110 fn emit_json_diagnostics(diag: Diag) -> String {
2111 let sm = Arc::new(source_map::SourceMap::empty());
2112 sm.new_source_file(source_map::FileName::custom("test.sol"), CONTRACT.to_string()).unwrap();
2113
2114 let writer = Arc::new(Mutex::new(Vec::new()));
2115 let emitter = JsonEmitter::new(
2116 Box::new(SharedWriter(writer.clone())),
2117 Arc::clone(&sm),
2118 ColorChoice::Never,
2119 )
2120 .rustc_like(true);
2121 let dcx = DiagCtxt::new(Box::new(emitter));
2122 let _ = dcx.emit_diagnostic(diag);
2123
2124 let buffer = writer.lock().unwrap();
2125 String::from_utf8(buffer.clone()).expect("JSON output was not valid UTF-8")
2126 }
2127}