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