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 codemap::{CodeMap, FilePathMapping};
23 use syntax_pos::{self, MacroBacktrace, Span, SpanLabel, MultiSpan};
24 use errors::registry::Registry;
25 use errors::{DiagnosticBuilder, SubDiagnostic, CodeSuggestion, CodeMapper};
26 use errors::DiagnosticId;
27 use errors::emitter::{Emitter, EmitterWriter};
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<Write + Send>,
38 registry: Option<Registry>,
39 cm: Rc<CodeMapper + 'static>,
41 /// Whether "approximate suggestions" are enabled in the config
42 approximate_suggestions: bool,
46 pub fn stderr(registry: Option<Registry>,
47 code_map: Rc<CodeMap>,
49 approximate_suggestions: bool) -> JsonEmitter {
51 dst: Box::new(io::stderr()),
55 approximate_suggestions,
59 pub fn basic(pretty: bool) -> JsonEmitter {
60 let file_path_mapping = FilePathMapping::empty();
61 JsonEmitter::stderr(None, Rc::new(CodeMap::new(file_path_mapping)),
65 pub fn new(dst: Box<Write + Send>,
66 registry: Option<Registry>,
67 code_map: Rc<CodeMap>,
69 approximate_suggestions: bool) -> JsonEmitter {
75 approximate_suggestions,
80 impl Emitter for JsonEmitter {
81 fn emit(&mut self, db: &DiagnosticBuilder) {
82 let data = Diagnostic::from_diagnostic_builder(db, self);
83 let result = if self.pretty {
84 writeln!(&mut self.dst, "{}", as_pretty_json(&data))
86 writeln!(&mut self.dst, "{}", as_json(&data))
88 if let Err(e) = result {
89 panic!("failed to print diagnostics: {:?}", e);
94 // The following data types are provided just for serialisation.
96 #[derive(RustcEncodable)]
98 /// The primary error message.
100 code: Option<DiagnosticCode>,
101 /// "error: internal compiler error", "error", "warning", "note", "help".
103 spans: Vec<DiagnosticSpan>,
104 /// Associated diagnostic messages.
105 children: Vec<Diagnostic>,
106 /// The message as rustc would render it.
107 rendered: Option<String>,
110 #[derive(RustcEncodable)]
111 #[allow(unused_attributes)]
112 struct DiagnosticSpan {
119 /// 1-based, character offset.
122 /// Is this a "primary" span -- meaning the point, or one of the points,
123 /// where the error occurred?
125 /// Source text from the start of line_start to the end of line_end.
126 text: Vec<DiagnosticSpanLine>,
127 /// Label that should be placed at this location (if any)
128 label: Option<String>,
129 /// If we are suggesting a replacement, this will contain text
130 /// that should be sliced in atop this span.
131 suggested_replacement: Option<String>,
132 /// If the suggestion is approximate
133 #[rustc_serialize_exclude_null]
134 suggestion_approximate: Option<bool>,
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).emit(db);
203 let output = Arc::try_unwrap(output.0).unwrap().into_inner().unwrap();
204 let output = String::from_utf8(output).unwrap();
207 message: db.message(),
208 code: DiagnosticCode::map_opt_string(db.code.clone(), je),
209 level: db.level.to_str(),
210 spans: DiagnosticSpan::from_multispan(&db.span, je),
211 children: db.children.iter().map(|c| {
212 Diagnostic::from_sub_diagnostic(c, je)
213 }).chain(sugg).collect(),
214 rendered: Some(output),
218 fn from_sub_diagnostic(db: &SubDiagnostic, je: &JsonEmitter) -> Diagnostic {
220 message: db.message(),
222 level: db.level.to_str(),
223 spans: db.render_span.as_ref()
224 .map(|sp| DiagnosticSpan::from_multispan(sp, je))
225 .unwrap_or_else(|| DiagnosticSpan::from_multispan(&db.span, je)),
232 impl DiagnosticSpan {
233 fn from_span_label(span: SpanLabel,
234 suggestion: Option<(&String, bool)>,
237 Self::from_span_etc(span.span,
244 fn from_span_etc(span: Span,
246 label: Option<String>,
247 suggestion: Option<(&String, bool)>,
250 // obtain the full backtrace from the `macro_backtrace`
251 // helper; in some ways, it'd be better to expand the
252 // backtrace ourselves, but the `macro_backtrace` helper makes
253 // some decision, such as dropping some frames, and I don't
254 // want to duplicate that logic here.
255 let backtrace = span.macro_backtrace().into_iter();
256 DiagnosticSpan::from_span_full(span,
264 fn from_span_full(span: Span,
266 label: Option<String>,
267 suggestion: Option<(&String, bool)>,
268 mut backtrace: vec::IntoIter<MacroBacktrace>,
271 let start = je.cm.lookup_char_pos(span.lo());
272 let end = je.cm.lookup_char_pos(span.hi());
273 let backtrace_step = backtrace.next().map(|bt| {
275 Self::from_span_full(bt.call_site,
281 let def_site_span = bt.def_site_span.map(|sp| {
282 Self::from_span_full(sp,
289 Box::new(DiagnosticSpanMacroExpansion {
291 macro_decl_name: bt.macro_decl_name,
296 let suggestion_approximate = if je.approximate_suggestions {
297 suggestion.map(|x| x.1)
303 file_name: start.file.name.to_string(),
304 byte_start: span.lo().0 - start.file.start_pos.0,
305 byte_end: span.hi().0 - start.file.start_pos.0,
306 line_start: start.line,
308 column_start: start.col.0 + 1,
309 column_end: end.col.0 + 1,
311 text: DiagnosticSpanLine::from_span(span, je),
312 suggested_replacement: suggestion.map(|x| x.0.clone()),
313 suggestion_approximate,
314 expansion: backtrace_step,
319 fn from_multispan(msp: &MultiSpan, je: &JsonEmitter) -> Vec<DiagnosticSpan> {
322 .map(|span_str| Self::from_span_label(span_str, None, je))
326 fn from_suggestion(suggestion: &CodeSuggestion, je: &JsonEmitter)
327 -> Vec<DiagnosticSpan> {
328 suggestion.substitutions
330 .flat_map(|substitution| {
331 substitution.parts.iter().map(move |suggestion_inner| {
332 let span_label = SpanLabel {
333 span: suggestion_inner.span,
337 DiagnosticSpan::from_span_label(span_label,
338 Some((&suggestion_inner.snippet,
339 suggestion.approximate)),
347 impl DiagnosticSpanLine {
348 fn line_from_filemap(fm: &syntax_pos::FileMap,
352 -> DiagnosticSpanLine {
354 text: fm.get_line(index).map_or(String::new(), |l| l.into_owned()),
355 highlight_start: h_start,
356 highlight_end: h_end,
360 /// Create a list of DiagnosticSpanLines from span - each line with any part
361 /// of `span` gets a DiagnosticSpanLine, with the highlight indicating the
362 /// `span` within the line.
363 fn from_span(span: Span, je: &JsonEmitter) -> Vec<DiagnosticSpanLine> {
364 je.cm.span_to_lines(span)
366 let fm = &*lines.file;
370 DiagnosticSpanLine::line_from_filemap(fm,
372 line.start_col.0 + 1,
377 .unwrap_or_else(|_| vec![])
381 impl DiagnosticCode {
382 fn map_opt_string(s: Option<DiagnosticId>, je: &JsonEmitter) -> Option<DiagnosticCode> {
385 DiagnosticId::Error(s) => s,
386 DiagnosticId::Lint(s) => s,
388 let explanation = je.registry
390 .and_then(|registry| registry.find_description(&s));