rust/compiler/rustc_errors/src/json.rs

475 lines
15 KiB
Rust
Raw Normal View History

2015-12-31 02:43:42 +01:00
//! A JSON emitter for errors.
//!
//! This works by converting errors to a simplified structural format (see the
2017-08-15 21:45:21 +02:00
//! structs at the start of the file) and then serializing them. These should
//! contain as much information about the error as possible.
//!
//! The format of the JSON output should be considered *unstable*. For now the
//! structs at the end of this file (Diagnostic*) specify the error format.
2019-01-11 17:32:31 +01:00
// FIXME: spec the JSON output properly.
use rustc_span::source_map::{FilePathMapping, SourceMap};
2015-12-31 02:43:42 +01:00
2019-11-14 23:24:44 +01:00
use crate::emitter::{Emitter, HumanReadableErrorType};
2019-12-22 23:42:04 +01:00
use crate::registry::Registry;
use crate::DiagnosticId;
2019-12-22 23:42:04 +01:00
use crate::{CodeSuggestion, SubDiagnostic};
use rustc_lint_defs::{Applicability, FutureBreakage};
2015-12-31 02:43:42 +01:00
2019-11-14 23:24:44 +01:00
use rustc_data_structures::sync::Lrc;
use rustc_span::hygiene::ExpnData;
use rustc_span::{MultiSpan, Span, SpanLabel};
use std::io::{self, Write};
use std::path::Path;
2017-11-17 08:55:22 +01:00
use std::sync::{Arc, Mutex};
2019-12-22 23:42:04 +01:00
use std::vec;
2017-11-03 13:38:26 +01:00
use rustc_serialize::json::{as_json, as_pretty_json};
2015-12-31 02:43:42 +01:00
#[cfg(test)]
mod tests;
2015-12-31 02:43:42 +01:00
pub struct JsonEmitter {
dst: Box<dyn Write + Send>,
registry: Option<Registry>,
sm: Lrc<SourceMap>,
2017-11-03 13:38:26 +01:00
pretty: bool,
ui_testing: bool,
json_rendered: HumanReadableErrorType,
terminal_width: Option<usize>,
macro_backtrace: bool,
2015-12-31 02:43:42 +01:00
}
impl JsonEmitter {
pub fn stderr(
registry: Option<Registry>,
source_map: Lrc<SourceMap>,
pretty: bool,
json_rendered: HumanReadableErrorType,
terminal_width: Option<usize>,
macro_backtrace: bool,
) -> JsonEmitter {
JsonEmitter {
dst: Box::new(io::BufWriter::new(io::stderr())),
registry,
sm: source_map,
2017-11-03 13:38:26 +01:00
pretty,
ui_testing: false,
json_rendered,
terminal_width,
macro_backtrace,
}
}
pub fn basic(
pretty: bool,
json_rendered: HumanReadableErrorType,
terminal_width: Option<usize>,
macro_backtrace: bool,
) -> JsonEmitter {
let file_path_mapping = FilePathMapping::empty();
2019-12-22 23:42:04 +01:00
JsonEmitter::stderr(
None,
Lrc::new(SourceMap::new(file_path_mapping)),
pretty,
json_rendered,
terminal_width,
macro_backtrace,
2019-12-22 23:42:04 +01:00
)
2015-12-31 02:43:42 +01:00
}
pub fn new(
dst: Box<dyn Write + Send>,
registry: Option<Registry>,
source_map: Lrc<SourceMap>,
pretty: bool,
json_rendered: HumanReadableErrorType,
terminal_width: Option<usize>,
macro_backtrace: bool,
) -> JsonEmitter {
2015-12-31 02:43:42 +01:00
JsonEmitter {
dst,
registry,
sm: source_map,
2017-11-03 13:38:26 +01:00
pretty,
ui_testing: false,
json_rendered,
terminal_width,
macro_backtrace,
2015-12-31 02:43:42 +01:00
}
}
pub fn ui_testing(self, ui_testing: bool) -> Self {
Self { ui_testing, ..self }
}
2015-12-31 02:43:42 +01:00
}
impl Emitter for JsonEmitter {
2019-11-14 23:24:44 +01:00
fn emit_diagnostic(&mut self, diag: &crate::Diagnostic) {
let data = Diagnostic::from_errors_diagnostic(diag, self);
2017-11-03 13:38:26 +01:00
let result = if self.pretty {
writeln!(&mut self.dst, "{}", as_pretty_json(&data))
} else {
writeln!(&mut self.dst, "{}", as_json(&data))
}
.and_then(|_| self.dst.flush());
2017-11-03 13:38:26 +01:00
if let Err(e) = result {
panic!("failed to print diagnostics: {:?}", e);
}
}
fn emit_artifact_notification(&mut self, path: &Path, artifact_type: &str) {
let data = ArtifactNotification { artifact: path, emit: artifact_type };
let result = if self.pretty {
writeln!(&mut self.dst, "{}", as_pretty_json(&data))
} else {
writeln!(&mut self.dst, "{}", as_json(&data))
}
.and_then(|_| self.dst.flush());
if let Err(e) = result {
panic!("failed to print notification: {:?}", e);
}
}
fn emit_future_breakage_report(&mut self, diags: Vec<(FutureBreakage, crate::Diagnostic)>) {
let data: Vec<FutureBreakageItem> = diags
.into_iter()
.map(|(breakage, mut diag)| {
if diag.level == crate::Level::Allow {
diag.level = crate::Level::Warning;
}
FutureBreakageItem {
future_breakage_date: breakage.date,
diagnostic: Diagnostic::from_errors_diagnostic(&diag, self),
}
})
.collect();
let result = if self.pretty {
writeln!(&mut self.dst, "{}", as_pretty_json(&data))
} else {
writeln!(&mut self.dst, "{}", as_json(&data))
}
.and_then(|_| self.dst.flush());
if let Err(e) = result {
panic!("failed to print future breakage report: {:?}", e);
}
}
fn source_map(&self) -> Option<&Lrc<SourceMap>> {
Some(&self.sm)
}
fn should_show_explain(&self) -> bool {
2020-10-27 02:02:48 +01:00
!matches!(self.json_rendered, HumanReadableErrorType::Short(_))
}
}
// The following data types are provided just for serialisation.
#[derive(Encodable)]
2017-01-11 22:55:41 +01:00
struct Diagnostic {
/// The primary error message.
2017-01-11 22:55:41 +01:00
message: String,
code: Option<DiagnosticCode>,
/// "error: internal compiler error", "error", "warning", "note", "help".
level: &'static str,
spans: Vec<DiagnosticSpan>,
/// Associated diagnostic messages.
2017-01-11 22:55:41 +01:00
children: Vec<Diagnostic>,
2017-11-17 08:55:22 +01:00
/// The message as rustc would render it.
rendered: Option<String>,
}
#[derive(Encodable)]
struct DiagnosticSpan {
file_name: String,
byte_start: u32,
byte_end: u32,
/// 1-based.
line_start: usize,
line_end: usize,
/// 1-based, character offset.
column_start: usize,
column_end: usize,
/// Is this a "primary" span -- meaning the point, or one of the points,
/// where the error occurred?
is_primary: bool,
2016-03-24 03:32:42 +01:00
/// Source text from the start of line_start to the end of line_end.
text: Vec<DiagnosticSpanLine>,
/// Label that should be placed at this location (if any)
label: Option<String>,
/// If we are suggesting a replacement, this will contain text
2017-11-03 12:37:11 +01:00
/// that should be sliced in atop this span.
suggested_replacement: Option<String>,
/// If the suggestion is approximate
2018-04-25 23:51:06 +02:00
suggestion_applicability: Option<Applicability>,
/// Macro invocations that created the code at this span, if any.
expansion: Option<Box<DiagnosticSpanMacroExpansion>>,
2016-03-24 03:32:42 +01:00
}
#[derive(Encodable)]
2016-03-24 03:32:42 +01:00
struct DiagnosticSpanLine {
text: String,
2016-03-24 03:32:42 +01:00
/// 1-based, character offset in self.text.
highlight_start: usize,
2016-03-24 03:32:42 +01:00
highlight_end: usize,
}
2015-12-31 02:43:42 +01:00
#[derive(Encodable)]
struct DiagnosticSpanMacroExpansion {
/// span where macro was applied to generate this code; note that
/// this may itself derive from a macro (if
/// `span.expansion.is_some()`)
span: DiagnosticSpan,
/// name of macro that was applied (e.g., "foo!" or "#[derive(Eq)]")
macro_decl_name: String,
/// span where macro was defined (if known)
def_site_span: DiagnosticSpan,
}
#[derive(Encodable)]
struct DiagnosticCode {
/// The code itself.
code: String,
/// An explanation for the code.
explanation: Option<&'static str>,
}
#[derive(Encodable)]
struct ArtifactNotification<'a> {
/// The path of the artifact.
artifact: &'a Path,
/// What kind of artifact we're emitting.
emit: &'a str,
}
#[derive(Encodable)]
struct FutureBreakageItem {
future_breakage_date: Option<&'static str>,
diagnostic: Diagnostic,
}
2017-01-11 22:55:41 +01:00
impl Diagnostic {
2019-12-22 23:42:04 +01:00
fn from_errors_diagnostic(diag: &crate::Diagnostic, je: &JsonEmitter) -> Diagnostic {
let sugg = diag.suggestions.iter().map(|sugg| Diagnostic {
message: sugg.msg.clone(),
code: None,
level: "help",
spans: DiagnosticSpan::from_suggestion(sugg, je),
children: vec![],
rendered: None,
});
2017-11-17 08:55:22 +01:00
// generate regular command line output and store it in the json
// A threadsafe buffer for writing.
#[derive(Default, Clone)]
struct BufWriter(Arc<Mutex<Vec<u8>>>);
impl Write for BufWriter {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.0.lock().unwrap().write(buf)
}
fn flush(&mut self) -> io::Result<()> {
self.0.lock().unwrap().flush()
}
}
let buf = BufWriter::default();
let output = buf.clone();
2019-12-22 23:42:04 +01:00
je.json_rendered
.new_emitter(
Box::new(buf),
Some(je.sm.clone()),
false,
je.terminal_width,
je.macro_backtrace,
)
2019-12-22 23:42:04 +01:00
.ui_testing(je.ui_testing)
.emit_diagnostic(diag);
2017-11-17 08:55:22 +01:00
let output = Arc::try_unwrap(output.0).unwrap().into_inner().unwrap();
let output = String::from_utf8(output).unwrap();
Diagnostic {
message: diag.message(),
code: DiagnosticCode::map_opt_string(diag.code.clone(), je),
level: diag.level.to_str(),
spans: DiagnosticSpan::from_multispan(&diag.span, je),
2019-12-22 23:42:04 +01:00
children: diag
.children
.iter()
.map(|c| Diagnostic::from_sub_diagnostic(c, je))
.chain(sugg)
.collect(),
2017-11-20 09:40:55 +01:00
rendered: Some(output),
}
2015-12-31 02:43:42 +01:00
}
fn from_sub_diagnostic(diag: &SubDiagnostic, je: &JsonEmitter) -> Diagnostic {
Diagnostic {
message: diag.message(),
code: None,
level: diag.level.to_str(),
2019-12-22 23:42:04 +01:00
spans: diag
.render_span
.as_ref()
.map(|sp| DiagnosticSpan::from_multispan(sp, je))
.unwrap_or_else(|| DiagnosticSpan::from_multispan(&diag.span, je)),
children: vec![],
rendered: None,
}
}
}
impl DiagnosticSpan {
2019-12-22 23:42:04 +01:00
fn from_span_label(
span: SpanLabel,
suggestion: Option<(&String, Applicability)>,
je: &JsonEmitter,
) -> DiagnosticSpan {
Self::from_span_etc(span.span, span.is_primary, span.label, suggestion, je)
}
2019-12-22 23:42:04 +01:00
fn from_span_etc(
span: Span,
is_primary: bool,
label: Option<String>,
suggestion: Option<(&String, Applicability)>,
je: &JsonEmitter,
) -> DiagnosticSpan {
// obtain the full backtrace from the `macro_backtrace`
// helper; in some ways, it'd be better to expand the
// backtrace ourselves, but the `macro_backtrace` helper makes
// some decision, such as dropping some frames, and I don't
// want to duplicate that logic here.
let backtrace = span.macro_backtrace();
2019-12-22 23:42:04 +01:00
DiagnosticSpan::from_span_full(span, is_primary, label, suggestion, backtrace, je)
}
2019-12-22 23:42:04 +01:00
fn from_span_full(
span: Span,
is_primary: bool,
label: Option<String>,
suggestion: Option<(&String, Applicability)>,
mut backtrace: impl Iterator<Item = ExpnData>,
2019-12-22 23:42:04 +01:00
je: &JsonEmitter,
) -> DiagnosticSpan {
let start = je.sm.lookup_char_pos(span.lo());
let end = je.sm.lookup_char_pos(span.hi());
let backtrace_step = backtrace.next().map(|bt| {
2019-12-22 23:42:04 +01:00
let call_site = Self::from_span_full(bt.call_site, false, None, None, backtrace, je);
let def_site_span =
Self::from_span_full(bt.def_site, false, None, None, vec![].into_iter(), je);
Box::new(DiagnosticSpanMacroExpansion {
span: call_site,
macro_decl_name: bt.kind.descr(),
def_site_span,
})
});
2018-01-19 08:34:14 +01:00
DiagnosticSpan {
file_name: start.file.name.to_string(),
byte_start: start.file.original_relative_byte_pos(span.lo()).0,
byte_end: start.file.original_relative_byte_pos(span.hi()).0,
line_start: start.line,
line_end: end.line,
column_start: start.col.0 + 1,
column_end: end.col.0 + 1,
is_primary,
text: DiagnosticSpanLine::from_span(span, je),
suggested_replacement: suggestion.map(|x| x.0.clone()),
suggestion_applicability: suggestion.map(|x| x.1),
expansion: backtrace_step,
label,
}
}
fn from_multispan(msp: &MultiSpan, je: &JsonEmitter) -> Vec<DiagnosticSpan> {
msp.span_labels()
2019-12-22 23:42:04 +01:00
.into_iter()
.map(|span_str| Self::from_span_label(span_str, None, je))
.collect()
}
2019-12-22 23:42:04 +01:00
fn from_suggestion(suggestion: &CodeSuggestion, je: &JsonEmitter) -> Vec<DiagnosticSpan> {
suggestion
.substitutions
.iter()
.flat_map(|substitution| {
substitution.parts.iter().map(move |suggestion_inner| {
let span_label =
SpanLabel { span: suggestion_inner.span, is_primary: true, label: None };
DiagnosticSpan::from_span_label(
span_label,
Some((&suggestion_inner.snippet, suggestion.applicability)),
je,
)
})
})
.collect()
}
2016-04-04 00:32:37 +02:00
}
impl DiagnosticSpanLine {
2019-12-22 23:42:04 +01:00
fn line_from_source_file(
2020-02-22 15:07:05 +01:00
sf: &rustc_span::SourceFile,
2019-12-22 23:42:04 +01:00
index: usize,
h_start: usize,
h_end: usize,
) -> DiagnosticSpanLine {
2016-04-04 00:32:37 +02:00
DiagnosticSpanLine {
2020-02-22 15:07:05 +01:00
text: sf.get_line(index).map_or(String::new(), |l| l.into_owned()),
2016-04-04 00:32:37 +02:00
highlight_start: h_start,
highlight_end: h_end,
}
}
2019-02-08 14:53:55 +01:00
/// Creates a list of DiagnosticSpanLines from span - each line with any part
2016-04-04 00:32:37 +02:00
/// of `span` gets a DiagnosticSpanLine, with the highlight indicating the
/// `span` within the line.
fn from_span(span: Span, je: &JsonEmitter) -> Vec<DiagnosticSpanLine> {
2019-12-22 23:42:04 +01:00
je.sm
.span_to_lines(span)
2019-04-11 01:40:12 +02:00
.map(|lines| {
// We can't get any lines if the source is unavailable.
if !je.sm.ensure_source_file_source_present(lines.file.clone()) {
return vec![];
}
2020-02-22 15:07:05 +01:00
let sf = &*lines.file;
2019-12-22 23:42:04 +01:00
lines
.lines
2019-04-11 01:40:12 +02:00
.iter()
2019-12-22 23:42:04 +01:00
.map(|line| {
DiagnosticSpanLine::line_from_source_file(
2020-02-22 15:07:05 +01:00
sf,
2019-12-22 23:42:04 +01:00
line.line_index,
line.start_col.0 + 1,
line.end_col.0 + 1,
)
})
.collect()
})
.unwrap_or_else(|_| vec![])
2016-04-04 00:32:37 +02:00
}
2016-03-24 03:32:42 +01:00
}
impl DiagnosticCode {
fn map_opt_string(s: Option<DiagnosticId>, je: &JsonEmitter) -> Option<DiagnosticCode> {
s.map(|s| {
let s = match s {
DiagnosticId::Error(s) => s,
DiagnosticId::Lint { name, has_future_breakage: _ } => name,
};
let je_result =
je.registry.as_ref().map(|registry| registry.try_find_description(&s)).unwrap();
DiagnosticCode { code: s, explanation: je_result.unwrap_or(None) }
})
2015-12-31 02:43:42 +01:00
}
}