solar_interface/diagnostics/emitter/
human.rs1use super::{Diag, Emitter};
6use crate::{
7 SourceMap, Span,
8 diagnostics::{
9 ConfusionType, DiagId, DiagMsg, Level, MultiSpan, SpanLabel, Style, SubDiagnostic,
10 SuggestionStyle, Suggestions, detect_confusion_type, emitter::normalize_whitespace,
11 is_different,
12 },
13 source_map::{FileName, SourceFile},
14};
15use annotate_snippets::{
16 Annotation as ASAnnotation, AnnotationKind, Group, Level as ASLevel, Patch, Renderer, Snippet,
17 renderer::DecorStyle,
18};
19use anstream::{AutoStream, ColorChoice};
20use solar_config::HumanEmitterKind;
21use solar_data_structures::pluralize;
22use std::{
23 any::Any,
24 borrow::Cow,
25 io::{self, Write},
26 sync::{Arc, OnceLock},
27};
28
29type Writer = dyn Write + Send + 'static;
30
31pub(super) const MAX_SUGGESTIONS: usize = 4;
35
36const DEFAULT_RENDERER: Renderer = Renderer::styled()
37 .error(Level::Error.style())
38 .warning(Level::Warning.style())
39 .note(Level::Note.style())
40 .help(Level::Help.style())
41 .line_num(Style::LineNumber.to_color_spec(Level::Note))
42 .addition(Style::Addition.to_color_spec(Level::Note))
43 .removal(Style::Removal.to_color_spec(Level::Note))
44 .context(Style::LabelSecondary.to_color_spec(Level::Note));
45
46pub struct HumanEmitter {
48 writer_type_id: std::any::TypeId,
49 real_writer: *mut Writer,
50 writer: AutoStream<Box<Writer>>,
51 source_map: Option<Arc<SourceMap>>,
52 renderer: Renderer,
53 short_message: bool,
54}
55
56unsafe impl Send for HumanEmitter {}
58
59impl Emitter for HumanEmitter {
60 fn emit_diagnostic(&mut self, diag: &mut Diag) {
61 let mut primary_span = Cow::Owned(std::mem::take(&mut diag.span));
62 let mut suggestions = Cow::Owned(std::mem::take(&mut diag.suggestions));
63 self.primary_span_formatted(&mut primary_span, &mut suggestions);
64
65 self.emit_messages_default(
66 &diag.level,
67 &diag.messages,
68 &diag.code,
69 &primary_span,
70 &diag.children,
71 &suggestions,
72 );
73
74 diag.span = primary_span.into_owned();
75 diag.suggestions = suggestions.into_owned();
76 }
77
78 fn emit_diagnostic_ref(&mut self, diag: &Diag) {
79 let mut primary_span = Cow::Borrowed(&diag.span);
80 let mut suggestions = Cow::Borrowed(&diag.suggestions);
81 self.primary_span_formatted(&mut primary_span, &mut suggestions);
82
83 self.emit_messages_default(
84 &diag.level,
85 &diag.messages,
86 &diag.code,
87 &primary_span,
88 &diag.children,
89 &suggestions,
90 );
91 }
92
93 fn source_map(&self) -> Option<&Arc<SourceMap>> {
94 self.source_map.as_ref()
95 }
96
97 fn supports_color(&self) -> bool {
98 match self.writer.current_choice() {
99 ColorChoice::AlwaysAnsi | ColorChoice::Always => true,
100 ColorChoice::Auto | ColorChoice::Never => false,
101 }
102 }
103}
104
105impl HumanEmitter {
106 pub fn new<W: Write + Send + 'static>(writer: W, color: ColorChoice) -> Self {
112 let writer_type_id = writer.type_id();
113 let mut real_writer = Box::new(writer) as Box<Writer>;
114 Self {
115 writer_type_id,
116 real_writer: &mut *real_writer,
117 writer: AutoStream::new(real_writer, color),
118 source_map: None,
119 renderer: DEFAULT_RENDERER,
120 short_message: false,
121 }
122 .human_kind(Default::default())
123 }
124
125 pub fn test() -> Self {
127 struct TestWriter;
128
129 impl Write for TestWriter {
130 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
131 eprint!("{}", String::from_utf8_lossy(buf));
134 Ok(buf.len())
135 }
136
137 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
138 self.write(buf).map(drop)
139 }
140
141 fn flush(&mut self) -> io::Result<()> {
142 io::stderr().flush()
143 }
144 }
145
146 Self::new(TestWriter, ColorChoice::Always)
147 }
148
149 pub fn stderr(color_choice: ColorChoice) -> Self {
151 Self::new(io::BufWriter::new(io::stderr()), stderr_choice(color_choice))
153 }
154
155 pub fn source_map(mut self, source_map: Option<Arc<SourceMap>>) -> Self {
157 self.set_source_map(source_map);
158 self
159 }
160
161 pub fn set_source_map(&mut self, source_map: Option<Arc<SourceMap>>) {
163 self.source_map = source_map;
164 }
165
166 pub fn ui_testing(mut self, yes: bool) -> Self {
168 self.renderer = self.renderer.anonymized_line_numbers(yes);
169 self
170 }
171
172 pub fn set_ui_testing(&mut self, yes: bool) {
174 self.renderer =
175 std::mem::replace(&mut self.renderer, DEFAULT_RENDERER).anonymized_line_numbers(yes);
176 }
177
178 pub fn human_kind(mut self, kind: HumanEmitterKind) -> Self {
180 match kind {
181 HumanEmitterKind::Ascii => {
182 self.renderer = self.renderer.decor_style(DecorStyle::Ascii);
183 }
184 HumanEmitterKind::Unicode => {
185 self.renderer = self.renderer.decor_style(DecorStyle::Unicode);
186 }
187 HumanEmitterKind::Short => {
188 self.short_message = true;
189 self.renderer = self.renderer.short_message(true);
190 }
191 _ => unimplemented!("{kind:?}"),
192 }
193 self
194 }
195
196 pub fn terminal_width(mut self, width: Option<usize>) -> Self {
198 if let Some(w) = width {
199 self.renderer = self.renderer.term_width(w);
200 }
201 self
202 }
203
204 fn downcast_writer<T: Any>(&self) -> Option<&T> {
206 if self.writer_type_id == std::any::TypeId::of::<T>() {
207 Some(unsafe { &*(self.real_writer as *const T) })
208 } else {
209 None
210 }
211 }
212
213 fn downcast_writer_mut<T: Any>(&mut self) -> Option<&mut T> {
215 if self.writer_type_id == std::any::TypeId::of::<T>() {
216 Some(unsafe { &mut *(self.real_writer as *mut T) })
217 } else {
218 None
219 }
220 }
221
222 fn emit_messages_default(
223 &mut self,
224 level: &Level,
225 msgs: &[(DiagMsg, Style)],
226 code: &Option<DiagId>,
227 msp: &MultiSpan,
228 children: &[SubDiagnostic],
229 suggestions: &Suggestions,
230 ) {
231 let renderer = &self.renderer;
232 let annotation_level = annotation_level_for_level(*level);
233
234 let mut title = if msgs.iter().any(|(_, style)| style != &Style::NoStyle) {
237 annotation_level.clone().secondary_title(Cow::Owned(self.pre_style_msgs(msgs, *level)))
238 } else {
239 annotation_level.clone().primary_title(self.no_style_msgs(msgs))
240 };
241
242 if let Some(c) = code {
243 title = title.id(c.as_str());
244 }
250
251 let mut report = vec![];
252 let mut group = Group::with_title(title);
253
254 let Some(sm) = self.source_map.as_ref() else {
256 group = group.elements(children.iter().map(|c| {
257 let msg = self.no_style_msgs(&c.messages);
258 let level = annotation_level_for_level(c.level);
259 level.message(msg)
260 }));
261
262 report.push(group);
263 if let Err(e) = emit_to_destination(
264 renderer.render(&report),
265 level,
266 &mut self.writer,
267 self.short_message,
268 ) {
269 panic!("failed to emit error: {e}");
270 }
271 return;
272 };
273
274 let mut file_ann = collect_annotations(msp, sm);
275
276 let primary_span = msp.primary_span().unwrap_or_default();
278 if !primary_span.is_dummy() {
279 let primary_lo = sm.lookup_char_pos(primary_span.lo());
280 if let Ok(pos) = file_ann.binary_search_by(|(f, _)| f.name.cmp(&primary_lo.file.name)) {
281 file_ann.swap(0, pos);
282 }
283
284 for (file, annotations) in file_ann.into_iter() {
285 if let Some(snippet) = self.annotated_snippet(annotations, &file.name, sm) {
286 group = group.element(snippet);
287 }
288 }
289 }
290
291 for c in children {
292 let level = annotation_level_for_level(c.level);
293
294 let msg = if c.messages.iter().any(|(_, style)| style != &Style::NoStyle) {
297 Cow::Owned(self.pre_style_msgs(&c.messages, c.level))
298 } else {
299 Cow::Owned(self.no_style_msgs(&c.messages))
300 };
301
302 if !c.span.has_primary_spans() && !c.span.has_span_labels() {
304 group = group.element(level.clone().message(msg));
305 continue;
306 }
307
308 report.push(std::mem::replace(
309 &mut group,
310 Group::with_title(level.clone().secondary_title(msg)),
311 ));
312
313 let mut file_ann = collect_annotations(&c.span, sm);
314 let primary_span = c.span.primary_span().unwrap_or_default();
315 if !primary_span.is_dummy() {
316 let primary_lo = sm.lookup_char_pos(primary_span.lo());
317 if let Ok(pos) =
318 file_ann.binary_search_by(|(f, _)| f.name.cmp(&primary_lo.file.name))
319 {
320 file_ann.swap(0, pos);
321 }
322 }
323
324 for (file, annotations) in file_ann.into_iter() {
325 if let Some(snippet) = self.annotated_snippet(annotations, &file.name, sm) {
326 group = group.element(snippet);
327 }
328 }
329 }
330
331 for suggestion in suggestions.unwrap_tag() {
332 match suggestion.style {
333 SuggestionStyle::CompletelyHidden => {
334 }
336 SuggestionStyle::HideCodeAlways => {
337 let msg = self.no_style_msgs(&[(suggestion.msg.to_owned(), Style::HeaderMsg)]);
338 group = group.element(annotate_snippets::Level::HELP.message(msg));
339 }
340 SuggestionStyle::HideCodeInline
341 | SuggestionStyle::ShowCode
342 | SuggestionStyle::ShowAlways => {
343 let substitutions = suggestion
344 .substitutions
345 .iter()
346 .cloned() .filter_map(|mut subst| {
348 let invalid =
352 subst.parts.iter().any(|item| sm.is_valid_span(item.span).is_err());
353 if invalid {
354 debug!("suggestion contains an invalid span: {:?}", subst);
355 return None;
356 }
357
358 subst.parts.sort_by_key(|part| part.span.lo());
361 debug_assert_eq!(
363 subst.parts.windows(2).find(|s| s[0].span.overlaps(s[1].span)),
364 None,
365 "all spans must be disjoint",
366 );
367
368 let lo = subst.parts.iter().map(|part| part.span.lo()).min()?;
369 let lo_file = sm.lookup_source_file(lo);
370 let hi = subst.parts.iter().map(|part| part.span.hi()).max()?;
371 let hi_file = sm.lookup_source_file(hi);
372
373 if lo_file.start_pos != hi_file.start_pos {
376 return None;
377 }
378
379 subst.parts.retain(|p| is_different(sm, &p.snippet, p.span));
384
385 if subst.parts.is_empty() { None } else { Some(subst) }
386 })
387 .collect::<Vec<_>>();
388
389 if substitutions.is_empty() {
390 continue;
391 }
392 let mut msg = suggestion.msg.to_string();
393
394 let lo = substitutions
395 .iter()
396 .find_map(|sub| sub.parts.first().map(|p| p.span.lo()))
397 .unwrap();
398 let file = sm.lookup_source_file(lo);
399
400 let filename = sm.filename_for_diagnostics(&file.name).to_string();
401
402 let other_suggestions = substitutions.len().saturating_sub(MAX_SUGGESTIONS);
403
404 let subs = substitutions
405 .into_iter()
406 .take(MAX_SUGGESTIONS)
407 .filter_map(|sub| {
408 let mut confusion_type = ConfusionType::None;
409 for part in &sub.parts {
410 let part_confusion =
411 detect_confusion_type(sm, &part.snippet, part.span);
412 confusion_type = confusion_type.combine(part_confusion);
413 }
414
415 if !matches!(confusion_type, ConfusionType::None) {
416 msg.push_str(confusion_type.label_text());
417 }
418
419 let parts = sub
420 .parts
421 .into_iter()
422 .filter_map(|p| {
423 if is_different(sm, &p.snippet, p.span) {
424 Some((p.span, p.snippet))
425 } else {
426 None
427 }
428 })
429 .collect::<Vec<_>>();
430
431 if parts.is_empty() {
432 None
433 } else {
434 let spans = parts.iter().map(|(span, _)| *span).collect::<Vec<_>>();
435
436 let fold = true;
440
441 if let Some((bounding_span, source, line_offset)) =
442 shrink_file(spans.as_slice(), &file.name, sm)
443 {
444 let adj_lo = bounding_span.lo().to_usize();
445 Some(
446 Snippet::source(source)
447 .line_start(line_offset)
448 .path(filename.clone())
449 .fold(fold)
450 .patches(parts.into_iter().map(
451 |(span, replacement)| {
452 let lo =
453 span.lo().to_usize().saturating_sub(adj_lo);
454 let hi =
455 span.hi().to_usize().saturating_sub(adj_lo);
456
457 Patch::new(lo..hi, replacement.into_inner())
458 },
459 )),
460 )
461 } else {
462 None
463 }
464 }
465 })
466 .collect::<Vec<_>>();
467 if !subs.is_empty() {
468 report.push(std::mem::replace(
469 &mut group,
470 Group::with_title(annotate_snippets::Level::HELP.secondary_title(msg)),
471 ));
472
473 group = group.elements(subs);
474 if other_suggestions > 0 {
475 group = group.element(
476 annotate_snippets::Level::NOTE.no_name().message(format!(
477 "and {} other candidate{}",
478 other_suggestions,
479 pluralize!(other_suggestions)
480 )),
481 );
482 }
483 }
484 }
485 }
486 }
487
488 if !group.is_empty() {
489 report.push(group);
490 }
491
492 if let Err(e) = emit_to_destination(
493 renderer.render(&report),
494 level,
495 &mut self.writer,
496 self.short_message,
497 ) {
498 panic!("failed to emit error: {e}");
499 }
500 }
501
502 fn pre_style_msgs(&self, msgs: &[(DiagMsg, Style)], level: Level) -> String {
503 msgs.iter()
504 .filter_map(|(m, style)| {
505 let text = m.as_str();
506 let style = style.to_color_spec(level);
507 if text.is_empty() { None } else { Some(format!("{style}{text}{style:#}")) }
508 })
509 .collect()
510 }
511
512 fn no_style_msgs(&self, msgs: &[(DiagMsg, Style)]) -> String {
515 msgs.iter().map(|(m, _)| m.as_str()).collect()
516 }
517
518 fn annotated_snippet<'a>(
519 &self,
520 annotations: Vec<Annotation>,
521 file_name: &FileName,
522 sm: &Arc<SourceMap>,
523 ) -> Option<Snippet<'a, ASAnnotation<'a>>> {
524 let spans = annotations.iter().map(|a| a.span).collect::<Vec<_>>();
525 if let Some((bounding_span, source, offset_line)) = shrink_file(&spans, file_name, sm) {
526 let adj_lo = bounding_span.lo().to_usize();
527
528 let filename = sm.filename_for_diagnostics(file_name).to_string();
529
530 Some(Snippet::source(source).line_start(offset_line).path(filename).annotations(
531 annotations.into_iter().map(move |a| {
532 let lo = a.span.lo().to_usize().saturating_sub(adj_lo);
533 let hi = a.span.hi().to_usize().saturating_sub(adj_lo);
534 let ann = a.kind.span(lo..hi);
535 if let Some(label) = a.label { ann.label(label) } else { ann }
536 }),
537 ))
538 } else {
539 None
540 }
541 }
542}
543
544pub struct HumanBufferEmitter {
546 inner: HumanEmitter,
547}
548
549impl Emitter for HumanBufferEmitter {
550 #[inline]
551 fn emit_diagnostic(&mut self, diagnostic: &mut Diag) {
552 self.inner.emit_diagnostic(diagnostic);
553 }
554
555 #[inline]
556 fn emit_diagnostic_ref(&mut self, diagnostic: &Diag) {
557 self.inner.emit_diagnostic_ref(diagnostic);
558 }
559
560 #[inline]
561 fn source_map(&self) -> Option<&Arc<SourceMap>> {
562 Emitter::source_map(&self.inner)
563 }
564
565 #[inline]
566 fn supports_color(&self) -> bool {
567 self.inner.supports_color()
568 }
569}
570
571impl HumanBufferEmitter {
572 pub fn new(color_choice: ColorChoice) -> Self {
574 Self { inner: HumanEmitter::new(Vec::<u8>::new(), stderr_choice(color_choice)) }
575 }
576
577 pub fn source_map(mut self, source_map: Option<Arc<SourceMap>>) -> Self {
579 self.inner = self.inner.source_map(source_map);
580 self
581 }
582
583 pub fn ui_testing(mut self, yes: bool) -> Self {
585 self.inner = self.inner.ui_testing(yes);
586 self
587 }
588
589 pub fn human_kind(mut self, kind: HumanEmitterKind) -> Self {
591 self.inner = self.inner.human_kind(kind);
592 self
593 }
594
595 pub fn terminal_width(mut self, width: Option<usize>) -> Self {
597 self.inner = self.inner.terminal_width(width);
598 self
599 }
600
601 pub fn inner(&self) -> &HumanEmitter {
603 &self.inner
604 }
605
606 pub fn inner_mut(&mut self) -> &mut HumanEmitter {
608 &mut self.inner
609 }
610
611 pub fn buffer(&self) -> &str {
613 let buffer = self.inner.downcast_writer::<Vec<u8>>().unwrap();
614 debug_assert!(std::str::from_utf8(buffer).is_ok(), "HumanEmitter wrote invalid UTF-8");
615 unsafe { std::str::from_utf8_unchecked(buffer) }
617 }
618
619 pub fn buffer_mut(&mut self) -> &mut String {
621 let buffer = self.inner.downcast_writer_mut::<Vec<u8>>().unwrap();
622 debug_assert!(std::str::from_utf8(buffer).is_ok(), "HumanEmitter wrote invalid UTF-8");
623 unsafe { &mut *(buffer as *mut Vec<u8> as *mut String) }
625 }
626}
627
628fn annotation_level_for_level<'a>(level: Level) -> ASLevel<'a> {
629 let name = level.to_str();
630 let annotation_level = match level {
631 Level::Bug | Level::Fatal | Level::Error => ASLevel::ERROR,
632 Level::Warning => ASLevel::WARNING,
633 Level::Note | Level::OnceNote => ASLevel::NOTE,
634 Level::Help | Level::OnceHelp => ASLevel::HELP,
635 Level::FailureNote => return ASLevel::NOTE.no_name(),
636 Level::Allow => panic!("should not render a diagnostic with `Allow` level"),
637 };
638 annotation_level.with_name(Some(name))
639}
640
641fn stderr_choice(color_choice: ColorChoice) -> ColorChoice {
642 static AUTO: OnceLock<ColorChoice> = OnceLock::new();
643 if color_choice == ColorChoice::Auto {
644 *AUTO.get_or_init(|| anstream::AutoStream::choice(&std::io::stderr()))
645 } else {
646 color_choice
647 }
648}
649
650fn emit_to_destination(
651 rendered: String,
652 lvl: &Level,
653 dst: &mut Writer,
654 short_message: bool,
655) -> io::Result<()> {
656 writeln!(dst, "{rendered}")?;
661 if !short_message && !lvl.is_failure_note() {
662 writeln!(dst)?;
663 }
664 dst.flush()?;
665 Ok(())
666}
667
668#[derive(Debug)]
669struct Annotation {
670 kind: AnnotationKind,
671 span: Span,
672 label: Option<String>,
673}
674
675fn collect_annotations(
676 msp: &MultiSpan,
677 sm: &Arc<SourceMap>,
678) -> Vec<(Arc<SourceFile>, Vec<Annotation>)> {
679 let mut output: Vec<(Arc<SourceFile>, Vec<Annotation>)> = vec![];
680
681 let labels = msp.span_labels();
682 let files = sm.files();
683 for SpanLabel { span, is_primary, label } in labels {
684 let span = match (span.is_dummy(), msp.primary_span()) {
687 (_, None) | (false, _) => span,
688 (true, Some(span)) => span,
689 };
690 let kind = if is_primary { AnnotationKind::Primary } else { AnnotationKind::Context };
691
692 let label = label.as_ref().map(|m| normalize_whitespace(m));
693
694 let ann = Annotation { kind, span, label };
695 if let Ok(location) = files.is_valid_span(ann.span) {
696 let file = location.file;
697 if let Some((_, annotations)) =
699 output.iter_mut().find(|(f, _)| f.start_pos == file.start_pos)
700 {
701 annotations.push(ann);
702 } else {
703 output.push((file.clone(), vec![ann]));
704 }
705 }
706 }
707 drop(files);
708
709 for (file, ann) in output.iter_mut() {
711 ann.sort_by_key(|a| file.lookup_line(file.relative_position(a.span.lo())));
712 }
713
714 output
715}
716
717fn shrink_file(
718 spans: &[Span],
719 _file_name: &FileName,
720 sm: &Arc<SourceMap>,
721) -> Option<(Span, String, usize)> {
722 let lo_byte = spans.iter().map(|s| s.lo()).min()?;
723 let lo_loc = sm.lookup_char_pos(lo_byte);
724
725 let hi_byte = spans.iter().map(|s| s.hi()).max()?;
726 let hi_loc = sm.lookup_char_pos(hi_byte);
727
728 if lo_loc.file.start_pos != hi_loc.file.start_pos {
729 return None;
731 }
732
733 let lo = lo_loc.file.line_bounds(lo_loc.line.saturating_sub(1)).start;
734 let hi = hi_loc.file.line_bounds(hi_loc.line.saturating_sub(1)).end;
735
736 let bounding_span = Span::new(lo, hi);
737 let source = sm.span_to_snippet(bounding_span).ok()?;
738 let offset_line = lo_loc.line;
739
740 Some((bounding_span, source, offset_line))
741}