1use std::error::Report;
13use std::io::{self, Write};
14use std::path::Path;
15use std::sync::{Arc, Mutex};
16use std::vec;
17
18use anstream::{AutoStream, ColorChoice};
19use derive_setters::Setters;
20use rustc_data_structures::sync::IntoDynSyncSend;
21use rustc_error_messages::FluentArgs;
22use rustc_lint_defs::Applicability;
23use rustc_span::Span;
24use rustc_span::hygiene::ExpnData;
25use rustc_span::source_map::{FilePathMapping, SourceMap};
26use serde::Serialize;
27
28use crate::diagnostic::IsLint;
29use crate::emitter::{
30 ColorConfig, Destination, Emitter, HumanEmitter, HumanReadableErrorType, OutputTheme,
31 TimingEvent, should_show_source_code,
32};
33use crate::registry::Registry;
34use crate::timings::{TimingRecord, TimingSection};
35use crate::translation::{Translator, to_fluent_args};
36use crate::{CodeSuggestion, MultiSpan, SpanLabel, Subdiag, Suggestions, TerminalUrl};
37
38#[cfg(test)]
39mod tests;
40
41#[derive(Setters)]
42pub struct JsonEmitter {
43 #[setters(skip)]
44 dst: IntoDynSyncSend<Box<dyn Write + Send>>,
45 #[setters(skip)]
46 sm: Option<Arc<SourceMap>>,
47 #[setters(skip)]
48 translator: Translator,
49 #[setters(skip)]
50 pretty: bool,
51 ui_testing: bool,
52 ignored_directories_in_source_blocks: Vec<String>,
53 #[setters(skip)]
54 json_rendered: HumanReadableErrorType,
55 color_config: ColorConfig,
56 diagnostic_width: Option<usize>,
57 macro_backtrace: bool,
58 track_diagnostics: bool,
59 terminal_url: TerminalUrl,
60}
61
62impl JsonEmitter {
63 pub fn new(
64 dst: Box<dyn Write + Send>,
65 sm: Option<Arc<SourceMap>>,
66 translator: Translator,
67 pretty: bool,
68 json_rendered: HumanReadableErrorType,
69 color_config: ColorConfig,
70 ) -> JsonEmitter {
71 JsonEmitter {
72 dst: IntoDynSyncSend(dst),
73 sm,
74 translator,
75 pretty,
76 ui_testing: false,
77 ignored_directories_in_source_blocks: Vec::new(),
78 json_rendered,
79 color_config,
80 diagnostic_width: None,
81 macro_backtrace: false,
82 track_diagnostics: false,
83 terminal_url: TerminalUrl::No,
84 }
85 }
86
87 fn emit(&mut self, val: EmitTyped<'_>) -> io::Result<()> {
88 if self.pretty {
89 serde_json::to_writer_pretty(&mut *self.dst, &val)?
90 } else {
91 serde_json::to_writer(&mut *self.dst, &val)?
92 };
93 self.dst.write_all(b"\n")?;
94 self.dst.flush()
95 }
96}
97
98#[derive(Serialize)]
99#[serde(tag = "$message_type", rename_all = "snake_case")]
100enum EmitTyped<'a> {
101 Diagnostic(Diagnostic),
102 Artifact(ArtifactNotification<'a>),
103 SectionTiming(SectionTimestamp<'a>),
104 FutureIncompat(FutureIncompatReport<'a>),
105 UnusedExtern(UnusedExterns<'a>),
106}
107
108impl Emitter for JsonEmitter {
109 fn emit_diagnostic(&mut self, diag: crate::DiagInner, registry: &Registry) {
110 let data = Diagnostic::from_errors_diagnostic(diag, self, registry);
111 let result = self.emit(EmitTyped::Diagnostic(data));
112 if let Err(e) = result {
113 panic!("failed to print diagnostics: {e:?}");
114 }
115 }
116
117 fn emit_artifact_notification(&mut self, path: &Path, artifact_type: &str) {
118 let data = ArtifactNotification { artifact: path, emit: artifact_type };
119 let result = self.emit(EmitTyped::Artifact(data));
120 if let Err(e) = result {
121 panic!("failed to print notification: {e:?}");
122 }
123 }
124
125 fn emit_timing_section(&mut self, record: TimingRecord, event: TimingEvent) {
126 let event = match event {
127 TimingEvent::Start => "start",
128 TimingEvent::End => "end",
129 };
130 let name = match record.section {
131 TimingSection::Linking => "link",
132 TimingSection::Codegen => "codegen",
133 };
134 let data = SectionTimestamp { name, event, timestamp: record.timestamp };
135 let result = self.emit(EmitTyped::SectionTiming(data));
136 if let Err(e) = result {
137 panic!("failed to print timing section: {e:?}");
138 }
139 }
140
141 fn emit_future_breakage_report(&mut self, diags: Vec<crate::DiagInner>, registry: &Registry) {
142 let data: Vec<FutureBreakageItem<'_>> = diags
143 .into_iter()
144 .map(|mut diag| {
145 if matches!(diag.level, crate::Level::Allow | crate::Level::Expect) {
151 diag.level = crate::Level::Warning;
152 }
153 FutureBreakageItem {
154 diagnostic: EmitTyped::Diagnostic(Diagnostic::from_errors_diagnostic(
155 diag, self, registry,
156 )),
157 }
158 })
159 .collect();
160 let report = FutureIncompatReport { future_incompat_report: data };
161 let result = self.emit(EmitTyped::FutureIncompat(report));
162 if let Err(e) = result {
163 panic!("failed to print future breakage report: {e:?}");
164 }
165 }
166
167 fn emit_unused_externs(&mut self, lint_level: rustc_lint_defs::Level, unused_externs: &[&str]) {
168 let lint_level = lint_level.as_str();
169 let data = UnusedExterns { lint_level, unused_extern_names: unused_externs };
170 let result = self.emit(EmitTyped::UnusedExtern(data));
171 if let Err(e) = result {
172 panic!("failed to print unused externs: {e:?}");
173 }
174 }
175
176 fn source_map(&self) -> Option<&SourceMap> {
177 self.sm.as_deref()
178 }
179
180 fn should_show_explain(&self) -> bool {
181 !self.json_rendered.short()
182 }
183
184 fn translator(&self) -> &Translator {
185 &self.translator
186 }
187}
188
189#[derive(Serialize)]
192struct Diagnostic {
193 message: String,
195 code: Option<DiagnosticCode>,
196 level: &'static str,
198 spans: Vec<DiagnosticSpan>,
199 children: Vec<Diagnostic>,
201 rendered: Option<String>,
203}
204
205#[derive(Serialize)]
206struct DiagnosticSpan {
207 file_name: String,
208 byte_start: u32,
209 byte_end: u32,
210 line_start: usize,
212 line_end: usize,
213 column_start: usize,
215 column_end: usize,
216 is_primary: bool,
219 text: Vec<DiagnosticSpanLine>,
221 label: Option<String>,
223 suggested_replacement: Option<String>,
226 suggestion_applicability: Option<Applicability>,
228 expansion: Option<Box<DiagnosticSpanMacroExpansion>>,
230}
231
232#[derive(Serialize)]
233struct DiagnosticSpanLine {
234 text: String,
235
236 highlight_start: usize,
238
239 highlight_end: usize,
240}
241
242#[derive(Serialize)]
243struct DiagnosticSpanMacroExpansion {
244 span: DiagnosticSpan,
248
249 macro_decl_name: String,
251
252 def_site_span: DiagnosticSpan,
254}
255
256#[derive(Serialize)]
257struct DiagnosticCode {
258 code: String,
261 explanation: Option<&'static str>,
263}
264
265#[derive(Serialize)]
266struct ArtifactNotification<'a> {
267 artifact: &'a Path,
269 emit: &'a str,
271}
272
273#[derive(Serialize)]
274struct SectionTimestamp<'a> {
275 name: &'a str,
277 event: &'a str,
279 timestamp: u128,
281}
282
283#[derive(Serialize)]
284struct FutureBreakageItem<'a> {
285 diagnostic: EmitTyped<'a>,
288}
289
290#[derive(Serialize)]
291struct FutureIncompatReport<'a> {
292 future_incompat_report: Vec<FutureBreakageItem<'a>>,
293}
294
295#[derive(Serialize)]
300struct UnusedExterns<'a> {
301 lint_level: &'a str,
303 unused_extern_names: &'a [&'a str],
305}
306
307impl Diagnostic {
308 fn from_errors_diagnostic(
310 diag: crate::DiagInner,
311 je: &JsonEmitter,
312 registry: &Registry,
313 ) -> Diagnostic {
314 let args = to_fluent_args(diag.args.iter());
315 let sugg_to_diag = |sugg: &CodeSuggestion| {
316 let translated_message =
317 je.translator.translate_message(&sugg.msg, &args).map_err(Report::new).unwrap();
318 Diagnostic {
319 message: translated_message.to_string(),
320 code: None,
321 level: "help",
322 spans: DiagnosticSpan::from_suggestion(sugg, &args, je),
323 children: vec![],
324 rendered: None,
325 }
326 };
327 let sugg = match &diag.suggestions {
328 Suggestions::Enabled(suggestions) => suggestions.iter().map(sugg_to_diag),
329 Suggestions::Sealed(suggestions) => suggestions.iter().map(sugg_to_diag),
330 Suggestions::Disabled => [].iter().map(sugg_to_diag),
331 };
332
333 #[derive(Clone)]
337 struct BufWriter(Arc<Mutex<Vec<u8>>>);
338
339 impl Write for BufWriter {
340 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
341 self.0.lock().unwrap().write(buf)
342 }
343 fn flush(&mut self) -> io::Result<()> {
344 self.0.lock().unwrap().flush()
345 }
346 }
347
348 let translated_message = je.translator.translate_messages(&diag.messages, &args);
349
350 let code = if let Some(code) = diag.code {
351 Some(DiagnosticCode {
352 code: code.to_string(),
353 explanation: registry.try_find_description(code).ok(),
354 })
355 } else if let Some(IsLint { name, .. }) = &diag.is_lint {
356 Some(DiagnosticCode { code: name.to_string(), explanation: None })
357 } else {
358 None
359 };
360 let level = diag.level.to_str();
361 let spans = DiagnosticSpan::from_multispan(&diag.span, &args, je);
362 let mut children: Vec<Diagnostic> = diag
363 .children
364 .iter()
365 .map(|c| Diagnostic::from_sub_diagnostic(c, &args, je))
366 .chain(sugg)
367 .collect();
368 if je.track_diagnostics && diag.span.has_primary_spans() && !diag.span.is_dummy() {
369 children
370 .insert(0, Diagnostic::from_sub_diagnostic(&diag.emitted_at_sub_diag(), &args, je));
371 }
372 let buf = BufWriter(Arc::new(Mutex::new(Vec::new())));
373 let short = je.json_rendered.short();
374 let dst: Destination = AutoStream::new(
375 Box::new(buf.clone()),
376 match je.color_config.to_color_choice() {
377 ColorChoice::Auto => ColorChoice::Always,
378 choice => choice,
379 },
380 );
381 HumanEmitter::new(dst, je.translator.clone())
382 .short_message(short)
383 .sm(je.sm.clone())
384 .diagnostic_width(je.diagnostic_width)
385 .macro_backtrace(je.macro_backtrace)
386 .track_diagnostics(je.track_diagnostics)
387 .terminal_url(je.terminal_url)
388 .ui_testing(je.ui_testing)
389 .ignored_directories_in_source_blocks(je.ignored_directories_in_source_blocks.clone())
390 .theme(if let HumanReadableErrorType::Unicode = je.json_rendered {
391 OutputTheme::Unicode
392 } else {
393 OutputTheme::Ascii
394 })
395 .emit_diagnostic(diag, registry);
396 let buf = Arc::try_unwrap(buf.0).unwrap().into_inner().unwrap();
397 let buf = String::from_utf8(buf).unwrap();
398
399 Diagnostic {
400 message: translated_message.to_string(),
401 code,
402 level,
403 spans,
404 children,
405 rendered: Some(buf),
406 }
407 }
408
409 fn from_sub_diagnostic(
410 subdiag: &Subdiag,
411 args: &FluentArgs<'_>,
412 je: &JsonEmitter,
413 ) -> Diagnostic {
414 let translated_message = je.translator.translate_messages(&subdiag.messages, args);
415 Diagnostic {
416 message: translated_message.to_string(),
417 code: None,
418 level: subdiag.level.to_str(),
419 spans: DiagnosticSpan::from_multispan(&subdiag.span, args, je),
420 children: vec![],
421 rendered: None,
422 }
423 }
424}
425
426impl DiagnosticSpan {
427 fn from_span_label(
428 span: SpanLabel,
429 suggestion: Option<(&String, Applicability)>,
430 args: &FluentArgs<'_>,
431 je: &JsonEmitter,
432 ) -> DiagnosticSpan {
433 Self::from_span_etc(
434 span.span,
435 span.is_primary,
436 span.label
437 .as_ref()
438 .map(|m| je.translator.translate_message(m, args).unwrap())
439 .map(|m| m.to_string()),
440 suggestion,
441 je,
442 )
443 }
444
445 fn from_span_etc(
446 span: Span,
447 is_primary: bool,
448 label: Option<String>,
449 suggestion: Option<(&String, Applicability)>,
450 je: &JsonEmitter,
451 ) -> DiagnosticSpan {
452 let backtrace = span.macro_backtrace();
458 DiagnosticSpan::from_span_full(span, is_primary, label, suggestion, backtrace, je)
459 }
460
461 fn from_span_full(
462 mut span: Span,
463 is_primary: bool,
464 label: Option<String>,
465 suggestion: Option<(&String, Applicability)>,
466 mut backtrace: impl Iterator<Item = ExpnData>,
467 je: &JsonEmitter,
468 ) -> DiagnosticSpan {
469 let empty_source_map;
470 let sm = match &je.sm {
471 Some(s) => s,
472 None => {
473 span = rustc_span::DUMMY_SP;
474 empty_source_map = Arc::new(SourceMap::new(FilePathMapping::empty()));
475 empty_source_map
476 .new_source_file(std::path::PathBuf::from("empty.rs").into(), String::new());
477 &empty_source_map
478 }
479 };
480 let start = sm.lookup_char_pos(span.lo());
481 if start.col.0 == 0
485 && let Some((suggestion, _)) = suggestion
486 && suggestion.is_empty()
487 && let Ok(after) = sm.span_to_next_source(span)
488 && after.starts_with('\n')
489 {
490 span = span.with_hi(span.hi() + rustc_span::BytePos(1));
491 }
492 let end = sm.lookup_char_pos(span.hi());
493 let backtrace_step = backtrace.next().map(|bt| {
494 let call_site = Self::from_span_full(bt.call_site, false, None, None, backtrace, je);
495 let def_site_span = Self::from_span_full(
496 sm.guess_head_span(bt.def_site),
497 false,
498 None,
499 None,
500 [].into_iter(),
501 je,
502 );
503 Box::new(DiagnosticSpanMacroExpansion {
504 span: call_site,
505 macro_decl_name: bt.kind.descr(),
506 def_site_span,
507 })
508 });
509
510 DiagnosticSpan {
511 file_name: sm.filename_for_diagnostics(&start.file.name).to_string(),
512 byte_start: start.file.original_relative_byte_pos(span.lo()).0,
513 byte_end: start.file.original_relative_byte_pos(span.hi()).0,
514 line_start: start.line,
515 line_end: end.line,
516 column_start: start.col.0 + 1,
517 column_end: end.col.0 + 1,
518 is_primary,
519 text: DiagnosticSpanLine::from_span(span, je),
520 suggested_replacement: suggestion.map(|x| x.0.clone()),
521 suggestion_applicability: suggestion.map(|x| x.1),
522 expansion: backtrace_step,
523 label,
524 }
525 }
526
527 fn from_multispan(
528 msp: &MultiSpan,
529 args: &FluentArgs<'_>,
530 je: &JsonEmitter,
531 ) -> Vec<DiagnosticSpan> {
532 msp.span_labels()
533 .into_iter()
534 .map(|span_str| Self::from_span_label(span_str, None, args, je))
535 .collect()
536 }
537
538 fn from_suggestion(
539 suggestion: &CodeSuggestion,
540 args: &FluentArgs<'_>,
541 je: &JsonEmitter,
542 ) -> Vec<DiagnosticSpan> {
543 suggestion
544 .substitutions
545 .iter()
546 .flat_map(|substitution| {
547 substitution.parts.iter().map(move |suggestion_inner| {
548 let span_label =
549 SpanLabel { span: suggestion_inner.span, is_primary: true, label: None };
550 DiagnosticSpan::from_span_label(
551 span_label,
552 Some((&suggestion_inner.snippet, suggestion.applicability)),
553 args,
554 je,
555 )
556 })
557 })
558 .collect()
559 }
560}
561
562impl DiagnosticSpanLine {
563 fn line_from_source_file(
564 sf: &rustc_span::SourceFile,
565 index: usize,
566 h_start: usize,
567 h_end: usize,
568 ) -> DiagnosticSpanLine {
569 DiagnosticSpanLine {
570 text: sf.get_line(index).map_or_else(String::new, |l| l.into_owned()),
571 highlight_start: h_start,
572 highlight_end: h_end,
573 }
574 }
575
576 fn from_span(span: Span, je: &JsonEmitter) -> Vec<DiagnosticSpanLine> {
580 je.sm
581 .as_ref()
582 .and_then(|sm| {
583 let lines = sm.span_to_lines(span).ok()?;
584 if !should_show_source_code(
586 &je.ignored_directories_in_source_blocks,
587 &sm,
588 &lines.file,
589 ) {
590 return None;
591 }
592
593 let sf = &*lines.file;
594 let span_lines = lines
595 .lines
596 .iter()
597 .map(|line| {
598 DiagnosticSpanLine::line_from_source_file(
599 sf,
600 line.line_index,
601 line.start_col.0 + 1,
602 line.end_col.0 + 1,
603 )
604 })
605 .collect();
606 Some(span_lines)
607 })
608 .unwrap_or_default()
609 }
610}