1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! A JSON emitter for errors.
13 //! This works by converting errors to a simplified structural format (see the
14 //! structs at the start of the file) and then serializing them. These should
15 //! contain as much information about the error as possible.
17 //! The format of the JSON output should be considered *unstable*. For now the
18 //! structs at the end of this file (Diagnostic*) specify the error format.
20 // FIXME spec the JSON output properly.
22 use source_map::{SourceMap, FilePathMapping};
23 use syntax_pos::{self, MacroBacktrace, Span, SpanLabel, MultiSpan};
24 use errors::registry::Registry;
25 use errors::{DiagnosticBuilder, SubDiagnostic, CodeSuggestion, SourceMapper};
26 use errors::{DiagnosticId, Applicability};
27 use errors::emitter::{Emitter, EmitterWriter};
29 use rustc_data_structures::sync::{self, Lrc};
30 use std::io::{self, Write};
32 use std::sync::{Arc, Mutex};
34 use rustc_serialize::json::{as_json, as_pretty_json};
36 pub struct JsonEmitter {
37 dst: Box<dyn Write + Send>,
38 registry: Option<Registry>,
39 cm: Lrc<dyn SourceMapper + sync::Send + sync::Sync>,
45 pub fn stderr(registry: Option<Registry>,
46 code_map: Lrc<SourceMap>,
47 pretty: bool) -> JsonEmitter {
49 dst: Box::new(io::stderr()),
57 pub fn basic(pretty: bool) -> JsonEmitter {
58 let file_path_mapping = FilePathMapping::empty();
59 JsonEmitter::stderr(None, Lrc::new(SourceMap::new(file_path_mapping)),
63 pub fn new(dst: Box<dyn Write + Send>,
64 registry: Option<Registry>,
65 code_map: Lrc<SourceMap>,
66 pretty: bool) -> JsonEmitter {
76 pub fn ui_testing(self, ui_testing: bool) -> Self {
77 Self { ui_testing, ..self }
81 impl Emitter for JsonEmitter {
82 fn emit(&mut self, db: &DiagnosticBuilder) {
83 let data = Diagnostic::from_diagnostic_builder(db, self);
84 let result = if self.pretty {
85 writeln!(&mut self.dst, "{}", as_pretty_json(&data))
87 writeln!(&mut self.dst, "{}", as_json(&data))
89 if let Err(e) = result {
90 panic!("failed to print diagnostics: {:?}", e);
95 // The following data types are provided just for serialisation.
97 #[derive(RustcEncodable)]
99 /// The primary error message.
101 code: Option<DiagnosticCode>,
102 /// "error: internal compiler error", "error", "warning", "note", "help".
104 spans: Vec<DiagnosticSpan>,
105 /// Associated diagnostic messages.
106 children: Vec<Diagnostic>,
107 /// The message as rustc would render it.
108 rendered: Option<String>,
111 #[derive(RustcEncodable)]
112 #[allow(unused_attributes)]
113 struct DiagnosticSpan {
120 /// 1-based, character offset.
123 /// Is this a "primary" span -- meaning the point, or one of the points,
124 /// where the error occurred?
126 /// Source text from the start of line_start to the end of line_end.
127 text: Vec<DiagnosticSpanLine>,
128 /// Label that should be placed at this location (if any)
129 label: Option<String>,
130 /// If we are suggesting a replacement, this will contain text
131 /// that should be sliced in atop this span.
132 suggested_replacement: Option<String>,
133 /// If the suggestion is approximate
134 suggestion_applicability: Option<Applicability>,
135 /// Macro invocations that created the code at this span, if any.
136 expansion: Option<Box<DiagnosticSpanMacroExpansion>>,
139 #[derive(RustcEncodable)]
140 struct DiagnosticSpanLine {
143 /// 1-based, character offset in self.text.
144 highlight_start: usize,
146 highlight_end: usize,
149 #[derive(RustcEncodable)]
150 struct DiagnosticSpanMacroExpansion {
151 /// span where macro was applied to generate this code; note that
152 /// this may itself derive from a macro (if
153 /// `span.expansion.is_some()`)
154 span: DiagnosticSpan,
156 /// name of macro that was applied (e.g., "foo!" or "#[derive(Eq)]")
157 macro_decl_name: String,
159 /// span where macro was defined (if known)
160 def_site_span: Option<DiagnosticSpan>,
163 #[derive(RustcEncodable)]
164 struct DiagnosticCode {
167 /// An explanation for the code.
168 explanation: Option<&'static str>,
172 fn from_diagnostic_builder(db: &DiagnosticBuilder,
175 let sugg = db.suggestions.iter().map(|sugg| {
177 message: sugg.msg.clone(),
180 spans: DiagnosticSpan::from_suggestion(sugg, je),
186 // generate regular command line output and store it in the json
188 // A threadsafe buffer for writing.
189 #[derive(Default, Clone)]
190 struct BufWriter(Arc<Mutex<Vec<u8>>>);
192 impl Write for BufWriter {
193 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
194 self.0.lock().unwrap().write(buf)
196 fn flush(&mut self) -> io::Result<()> {
197 self.0.lock().unwrap().flush()
200 let buf = BufWriter::default();
201 let output = buf.clone();
202 EmitterWriter::new(Box::new(buf), Some(je.cm.clone()), false, false)
203 .ui_testing(je.ui_testing).emit(db);
204 let output = Arc::try_unwrap(output.0).unwrap().into_inner().unwrap();
205 let output = String::from_utf8(output).unwrap();
208 message: db.message(),
209 code: DiagnosticCode::map_opt_string(db.code.clone(), je),
210 level: db.level.to_str(),
211 spans: DiagnosticSpan::from_multispan(&db.span, je),
212 children: db.children.iter().map(|c| {
213 Diagnostic::from_sub_diagnostic(c, je)
214 }).chain(sugg).collect(),
215 rendered: Some(output),
219 fn from_sub_diagnostic(db: &SubDiagnostic, je: &JsonEmitter) -> Diagnostic {
221 message: db.message(),
223 level: db.level.to_str(),
224 spans: db.render_span.as_ref()
225 .map(|sp| DiagnosticSpan::from_multispan(sp, je))
226 .unwrap_or_else(|| DiagnosticSpan::from_multispan(&db.span, je)),
233 impl DiagnosticSpan {
234 fn from_span_label(span: SpanLabel,
235 suggestion: Option<(&String, Applicability)>,
238 Self::from_span_etc(span.span,
245 fn from_span_etc(span: Span,
247 label: Option<String>,
248 suggestion: Option<(&String, Applicability)>,
251 // obtain the full backtrace from the `macro_backtrace`
252 // helper; in some ways, it'd be better to expand the
253 // backtrace ourselves, but the `macro_backtrace` helper makes
254 // some decision, such as dropping some frames, and I don't
255 // want to duplicate that logic here.
256 let backtrace = span.macro_backtrace().into_iter();
257 DiagnosticSpan::from_span_full(span,
265 fn from_span_full(span: Span,
267 label: Option<String>,
268 suggestion: Option<(&String, Applicability)>,
269 mut backtrace: vec::IntoIter<MacroBacktrace>,
272 let start = je.cm.lookup_char_pos(span.lo());
273 let end = je.cm.lookup_char_pos(span.hi());
274 let backtrace_step = backtrace.next().map(|bt| {
276 Self::from_span_full(bt.call_site,
282 let def_site_span = bt.def_site_span.map(|sp| {
283 Self::from_span_full(sp,
290 Box::new(DiagnosticSpanMacroExpansion {
292 macro_decl_name: bt.macro_decl_name,
298 file_name: start.file.name.to_string(),
299 byte_start: span.lo().0 - start.file.start_pos.0,
300 byte_end: span.hi().0 - start.file.start_pos.0,
301 line_start: start.line,
303 column_start: start.col.0 + 1,
304 column_end: end.col.0 + 1,
306 text: DiagnosticSpanLine::from_span(span, je),
307 suggested_replacement: suggestion.map(|x| x.0.clone()),
308 suggestion_applicability: suggestion.map(|x| x.1),
309 expansion: backtrace_step,
314 fn from_multispan(msp: &MultiSpan, je: &JsonEmitter) -> Vec<DiagnosticSpan> {
317 .map(|span_str| Self::from_span_label(span_str, None, je))
321 fn from_suggestion(suggestion: &CodeSuggestion, je: &JsonEmitter)
322 -> Vec<DiagnosticSpan> {
323 suggestion.substitutions
325 .flat_map(|substitution| {
326 substitution.parts.iter().map(move |suggestion_inner| {
327 let span_label = SpanLabel {
328 span: suggestion_inner.span,
332 DiagnosticSpan::from_span_label(span_label,
333 Some((&suggestion_inner.snippet,
334 suggestion.applicability)),
342 impl DiagnosticSpanLine {
343 fn line_from_source_file(fm: &syntax_pos::SourceFile,
347 -> DiagnosticSpanLine {
349 text: fm.get_line(index).map_or(String::new(), |l| l.into_owned()),
350 highlight_start: h_start,
351 highlight_end: h_end,
355 /// Create a list of DiagnosticSpanLines from span - each line with any part
356 /// of `span` gets a DiagnosticSpanLine, with the highlight indicating the
357 /// `span` within the line.
358 fn from_span(span: Span, je: &JsonEmitter) -> Vec<DiagnosticSpanLine> {
359 je.cm.span_to_lines(span)
361 let fm = &*lines.file;
365 DiagnosticSpanLine::line_from_source_file(fm,
367 line.start_col.0 + 1,
372 .unwrap_or_else(|_| vec![])
376 impl DiagnosticCode {
377 fn map_opt_string(s: Option<DiagnosticId>, je: &JsonEmitter) -> Option<DiagnosticCode> {
380 DiagnosticId::Error(s) => s,
381 DiagnosticId::Lint(s) => s,
383 let explanation = je.registry
385 .and_then(|registry| registry.find_description(&s));