solar_interface/diagnostics/emitter/
human.rs1use super::{Diag, Emitter, io_panic, rustc::FileWithAnnotatedLines};
2use crate::{
3 SourceMap,
4 diagnostics::{Level, MultiSpan, Style, SubDiagnostic, SuggestionStyle},
5 source_map::SourceFile,
6};
7use annotate_snippets::{
8 Annotation, AnnotationKind, Group, Level as ASLevel, Message, Patch, Renderer, Report, Snippet,
9 Title, renderer::DecorStyle,
10};
11use anstream::{AutoStream, ColorChoice};
12use solar_config::HumanEmitterKind;
13use std::{
14 any::Any,
15 borrow::Cow,
16 collections::BTreeMap,
17 io::{self, Write},
18 sync::{Arc, OnceLock},
19};
20
21type Writer = dyn Write + Send + 'static;
24
25const DEFAULT_RENDERER: Renderer = Renderer::styled()
26 .error(Level::Error.style())
27 .warning(Level::Warning.style())
28 .note(Level::Note.style())
29 .help(Level::Help.style())
30 .line_num(Style::LineNumber.to_color_spec(Level::Note))
31 .addition(Style::Addition.to_color_spec(Level::Note))
32 .removal(Style::Removal.to_color_spec(Level::Note))
33 .context(Style::LabelSecondary.to_color_spec(Level::Note));
34
35pub struct HumanEmitter {
37 writer_type_id: std::any::TypeId,
38 real_writer: *mut Writer,
39 writer: AutoStream<Box<Writer>>,
40 source_map: Option<Arc<SourceMap>>,
41 renderer: Renderer,
42}
43
44unsafe impl Send for HumanEmitter {}
46
47impl Emitter for HumanEmitter {
48 fn emit_diagnostic(&mut self, diagnostic: &mut Diag) {
49 self.snippet(diagnostic, |this, snippet| {
50 writeln!(this.writer, "{}\n", this.renderer.render(snippet))?;
51 this.writer.flush()
52 })
53 .unwrap_or_else(|e| io_panic(e));
54 }
55
56 fn source_map(&self) -> Option<&Arc<SourceMap>> {
57 self.source_map.as_ref()
58 }
59
60 fn supports_color(&self) -> bool {
61 match self.writer.current_choice() {
62 ColorChoice::AlwaysAnsi | ColorChoice::Always => true,
63 ColorChoice::Auto | ColorChoice::Never => false,
64 }
65 }
66}
67
68impl HumanEmitter {
69 pub fn new<W: Write + Send + 'static>(writer: W, color: ColorChoice) -> Self {
75 let writer_type_id = writer.type_id();
76 let mut real_writer = Box::new(writer) as Box<Writer>;
77 Self {
78 writer_type_id,
79 real_writer: &mut *real_writer,
80 writer: AutoStream::new(real_writer, color),
81 source_map: None,
82 renderer: DEFAULT_RENDERER,
83 }
84 }
85
86 pub fn test() -> Self {
88 struct TestWriter;
89
90 impl Write for TestWriter {
91 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
92 eprint!("{}", String::from_utf8_lossy(buf));
95 Ok(buf.len())
96 }
97
98 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
99 self.write(buf).map(drop)
100 }
101
102 fn flush(&mut self) -> io::Result<()> {
103 io::stderr().flush()
104 }
105 }
106
107 Self::new(TestWriter, ColorChoice::Always)
108 }
109
110 pub fn stderr(color_choice: ColorChoice) -> Self {
112 Self::new(io::BufWriter::new(io::stderr()), stderr_choice(color_choice))
114 }
115
116 pub fn source_map(mut self, source_map: Option<Arc<SourceMap>>) -> Self {
118 self.set_source_map(source_map);
119 self
120 }
121
122 pub fn set_source_map(&mut self, source_map: Option<Arc<SourceMap>>) {
124 self.source_map = source_map;
125 }
126
127 pub fn ui_testing(mut self, yes: bool) -> Self {
129 self.renderer = self.renderer.anonymized_line_numbers(yes);
130 self
131 }
132
133 pub fn set_ui_testing(&mut self, yes: bool) {
135 self.renderer =
136 std::mem::replace(&mut self.renderer, DEFAULT_RENDERER).anonymized_line_numbers(yes);
137 }
138
139 pub fn human_kind(mut self, kind: HumanEmitterKind) -> Self {
141 match kind {
142 HumanEmitterKind::Ascii => {
143 self.renderer = self.renderer.decor_style(DecorStyle::Ascii);
144 }
145 HumanEmitterKind::Unicode => {
146 self.renderer = self.renderer.decor_style(DecorStyle::Unicode);
147 }
148 HumanEmitterKind::Short => {
149 self.renderer = self.renderer.short_message(true);
150 }
151 _ => unimplemented!("{kind:?}"),
152 }
153 self
154 }
155
156 pub fn terminal_width(mut self, width: Option<usize>) -> Self {
158 if let Some(w) = width {
159 self.renderer = self.renderer.term_width(w);
160 }
161 self
162 }
163
164 fn downcast_writer<T: Any>(&self) -> Option<&T> {
166 if self.writer_type_id == std::any::TypeId::of::<T>() {
167 Some(unsafe { &*(self.real_writer as *const T) })
168 } else {
169 None
170 }
171 }
172
173 fn downcast_writer_mut<T: Any>(&mut self) -> Option<&mut T> {
175 if self.writer_type_id == std::any::TypeId::of::<T>() {
176 Some(unsafe { &mut *(self.real_writer as *mut T) })
177 } else {
178 None
179 }
180 }
181
182 fn snippet<R>(
184 &mut self,
185 diagnostic: &mut Diag,
186 f: impl FnOnce(&mut Self, Report<'_>) -> R,
187 ) -> R {
188 let mut primary_span = Cow::Borrowed(&diagnostic.span);
210 self.primary_span_formatted(&mut primary_span, &mut diagnostic.suggestions);
211
212 let children = diagnostic
215 .suggestions
216 .iter()
217 .filter(|sugg| sugg.style != SuggestionStyle::HideCodeAlways)
218 .collect::<Vec<_>>();
219
220 let sm = self.source_map.as_deref();
221 let title = title_from_diagnostic(diagnostic);
222 let snippets = sm.map(|sm| iter_snippets(sm, &primary_span)).into_iter().flatten();
223
224 let subs = |d| diagnostic.children.iter().filter(move |sub| sub.span.is_dummy() == d);
226 let footers = subs(true).map(|sub| message_from_subdiagnostic(sub, self.supports_color()));
227 let sub_groups = subs(false).map(|sub| {
228 let mut g = Group::with_title(title_from_subdiagnostic(sub, self.supports_color()));
229 if let Some(sm) = sm {
230 g = g.elements(iter_snippets(sm, &sub.span));
231 }
232 g
233 });
234
235 let suggestion_groups = children.iter().flat_map(|suggestion| {
237 let sm = self.source_map.as_deref()?;
238
239 for substitution in &suggestion.substitutions {
242 let mut parts_by_file: BTreeMap<_, Vec<_>> = BTreeMap::new();
244 for part in &substitution.parts {
245 let file = sm.lookup_source_file(part.span.lo());
246 parts_by_file.entry(file.name.clone()).or_default().push(part);
247 }
248
249 if parts_by_file.is_empty() {
250 continue;
251 }
252
253 let mut snippets = vec![];
254 for (filename, parts) in parts_by_file {
255 let file = sm.get_file_ref(&filename)?;
256 let mut snippet = Snippet::source(file.src.to_string())
257 .path(sm.filename_for_diagnostics(&file.name).to_string())
258 .fold(true);
259
260 for part in parts {
261 if let Ok(range) = sm.span_to_range(part.span) {
262 snippet = snippet.patch(Patch::new(range, part.snippet.as_str()));
263 }
264 }
265 snippets.push(snippet);
266 }
267
268 if !snippets.is_empty() {
269 let title = ASLevel::HELP.secondary_title(suggestion.msg.as_str());
270 return Some(Group::with_title(title).elements(snippets));
271 }
272 }
273
274 None
275 });
276
277 let main_group = Group::with_title(title).elements(snippets).elements(footers);
278 let report = std::iter::once(main_group)
279 .chain(sub_groups)
280 .chain(suggestion_groups)
281 .collect::<Vec<_>>();
282 f(self, &report)
283 }
284}
285
286pub struct HumanBufferEmitter {
288 inner: HumanEmitter,
289}
290
291impl Emitter for HumanBufferEmitter {
292 #[inline]
293 fn emit_diagnostic(&mut self, diagnostic: &mut Diag) {
294 self.inner.emit_diagnostic(diagnostic);
295 }
296
297 #[inline]
298 fn source_map(&self) -> Option<&Arc<SourceMap>> {
299 Emitter::source_map(&self.inner)
300 }
301
302 #[inline]
303 fn supports_color(&self) -> bool {
304 self.inner.supports_color()
305 }
306}
307
308impl HumanBufferEmitter {
309 pub fn new(color_choice: ColorChoice) -> Self {
311 Self { inner: HumanEmitter::new(Vec::<u8>::new(), stderr_choice(color_choice)) }
312 }
313
314 pub fn source_map(mut self, source_map: Option<Arc<SourceMap>>) -> Self {
316 self.inner = self.inner.source_map(source_map);
317 self
318 }
319
320 pub fn ui_testing(mut self, yes: bool) -> Self {
322 self.inner = self.inner.ui_testing(yes);
323 self
324 }
325
326 pub fn human_kind(mut self, kind: HumanEmitterKind) -> Self {
328 self.inner = self.inner.human_kind(kind);
329 self
330 }
331
332 pub fn terminal_width(mut self, width: Option<usize>) -> Self {
334 self.inner = self.inner.terminal_width(width);
335 self
336 }
337
338 pub fn inner(&self) -> &HumanEmitter {
340 &self.inner
341 }
342
343 pub fn inner_mut(&mut self) -> &mut HumanEmitter {
345 &mut self.inner
346 }
347
348 pub fn buffer(&self) -> &str {
350 let buffer = self.inner.downcast_writer::<Vec<u8>>().unwrap();
351 debug_assert!(std::str::from_utf8(buffer).is_ok(), "HumanEmitter wrote invalid UTF-8");
352 unsafe { std::str::from_utf8_unchecked(buffer) }
354 }
355
356 pub fn buffer_mut(&mut self) -> &mut String {
358 let buffer = self.inner.downcast_writer_mut::<Vec<u8>>().unwrap();
359 debug_assert!(std::str::from_utf8(buffer).is_ok(), "HumanEmitter wrote invalid UTF-8");
360 unsafe { &mut *(buffer as *mut Vec<u8> as *mut String) }
362 }
363}
364
365fn title_from_diagnostic(diag: &Diag) -> Title<'_> {
366 let mut title = to_as_level(diag.level).primary_title(diag.label());
367 if let Some(id) = diag.id() {
368 title = title.id(id);
369 }
370 title
371}
372
373fn title_from_subdiagnostic(sub: &SubDiagnostic, supports_color: bool) -> Title<'_> {
374 to_as_level(sub.level).secondary_title(sub.label_with_style(supports_color))
375}
376
377fn message_from_subdiagnostic(sub: &SubDiagnostic, supports_color: bool) -> Message<'_> {
378 to_as_level(sub.level).message(sub.label_with_style(supports_color))
379}
380
381fn iter_snippets<'a>(
382 sm: &SourceMap,
383 msp: &MultiSpan,
384) -> impl Iterator<Item = Snippet<'a, Annotation<'a>>> {
385 collect_files(sm, msp).into_iter().map(|file| file_to_snippet(sm, &file.file, &file.lines))
386}
387
388fn collect_files(sm: &SourceMap, msp: &MultiSpan) -> Vec<FileWithAnnotatedLines> {
389 let mut annotated_files = FileWithAnnotatedLines::collect_annotations(sm, msp);
390 if let Some(primary_span) = msp.primary_span()
392 && !primary_span.is_dummy()
393 && annotated_files.len() > 1
394 {
395 let primary_lo = sm.lookup_char_pos(primary_span.lo());
396 if let Ok(pos) =
397 annotated_files.binary_search_by(|x| x.file.name.cmp(&primary_lo.file.name))
398 {
399 annotated_files.swap(0, pos);
400 }
401 }
402 annotated_files
403}
404
405fn file_to_snippet<'a>(
410 sm: &SourceMap,
411 file: &SourceFile,
412 lines: &[super::rustc::Line],
413) -> Snippet<'a, Annotation<'a>> {
414 type MultiLine<'a> = (Option<&'a String>, usize);
416 fn multi_line_at<'a, 'b>(
417 mls: &'a mut Vec<MultiLine<'b>>,
418 depth: usize,
419 ) -> &'a mut MultiLine<'b> {
420 assert!(depth > 0);
421 if mls.len() < depth {
422 mls.resize_with(depth, || (None, 0));
423 }
424 &mut mls[depth - 1]
425 }
426
427 debug_assert!(!lines.is_empty());
428
429 let first_line = lines.first().unwrap().line_index;
430 debug_assert!(first_line > 0, "line index is 1-based");
431 let last_line = lines.last().unwrap().line_index;
432 debug_assert!(last_line >= first_line);
433 debug_assert!(lines.is_sorted());
434 let snippet_base = file.line_position(first_line - 1).unwrap();
435
436 let source = file.get_lines(first_line - 1..=last_line - 1).unwrap_or_default();
437 let mut annotations = Vec::new();
438 let mut push_annotation = |kind: AnnotationKind, span, label| {
439 annotations.push(kind.span(span).label(label));
440 };
441 let annotation_kind = |is_primary: bool| {
442 if is_primary { AnnotationKind::Primary } else { AnnotationKind::Context }
443 };
444
445 let mut mls = Vec::new();
446 for line in lines {
447 let line_abs_pos = file.line_position(line.line_index - 1).unwrap();
448 let line_rel_pos = line_abs_pos - snippet_base;
449 let rel_pos = |c: &super::rustc::AnnotationColumn| {
452 line_rel_pos + char_to_byte_pos(&source[line_rel_pos..], c.file)
453 };
454
455 for ann in &line.annotations {
456 match ann.annotation_type {
457 super::rustc::AnnotationType::Singleline => {
458 push_annotation(
459 annotation_kind(ann.is_primary),
460 rel_pos(&ann.start_col)..rel_pos(&ann.end_col),
461 ann.label.clone().unwrap_or_default(),
462 );
463 }
464 super::rustc::AnnotationType::MultilineStart(depth) => {
465 *multi_line_at(&mut mls, depth) = (ann.label.as_ref(), rel_pos(&ann.start_col));
466 }
467 super::rustc::AnnotationType::MultilineLine(_depth) => {
468 push_annotation(
470 AnnotationKind::Visible,
471 line_rel_pos..line_rel_pos,
472 String::new(),
473 );
474 }
475 super::rustc::AnnotationType::MultilineEnd(depth) => {
476 let (label, multiline_start_idx) = *multi_line_at(&mut mls, depth);
477 let end_idx = rel_pos(&ann.end_col);
478 debug_assert!(end_idx >= multiline_start_idx);
479 push_annotation(
480 annotation_kind(ann.is_primary),
481 multiline_start_idx..end_idx,
482 label.or(ann.label.as_ref()).cloned().unwrap_or_default(),
483 );
484 }
485 }
486 }
487 }
488 Snippet::source(source.to_string())
489 .path(sm.filename_for_diagnostics(&file.name).to_string())
490 .line_start(first_line)
491 .fold(true)
492 .annotations(annotations)
493}
494
495fn to_as_level<'a>(level: Level) -> ASLevel<'a> {
496 match level {
497 Level::Bug | Level::Fatal | Level::Error | Level::FailureNote => ASLevel::ERROR,
498 Level::Warning => ASLevel::WARNING,
499 Level::Note | Level::OnceNote => ASLevel::NOTE,
500 Level::Help | Level::OnceHelp => ASLevel::HELP,
501 Level::Allow => ASLevel::INFO,
502 }
503 .with_name(if level == Level::FailureNote { None } else { Some(level.to_str()) })
504}
505
506fn char_to_byte_pos(s: &str, char_pos: usize) -> usize {
507 s.chars().take(char_pos).map(char::len_utf8).sum()
508}
509
510fn stderr_choice(color_choice: ColorChoice) -> ColorChoice {
511 static AUTO: OnceLock<ColorChoice> = OnceLock::new();
512 if color_choice == ColorChoice::Auto {
513 *AUTO.get_or_init(|| anstream::AutoStream::choice(&std::io::stderr()))
514 } else {
515 color_choice
516 }
517}