]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/errors/emitter.rs
Add an --output option for specifying an error emitter
[rust.git] / src / libsyntax / errors / emitter.rs
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.
4 //
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.
10
11 use self::Destination::*;
12
13 use codemap::{self, COMMAND_LINE_SP, COMMAND_LINE_EXPN, Pos, Span};
14 use diagnostics;
15
16 use errors::{Level, RenderSpan, DiagnosticBuilder};
17 use errors::RenderSpan::*;
18 use errors::Level::*;
19
20 use std::{cmp, fmt};
21 use std::io::prelude::*;
22 use std::io;
23 use std::rc::Rc;
24 use term;
25
26
27 pub trait Emitter {
28     fn emit(&mut self, span: Option<Span>, msg: &str, code: Option<&str>, lvl: Level);
29     fn custom_emit(&mut self, sp: RenderSpan, msg: &str, lvl: Level);
30
31     /// Emit a structured diagnostic.
32     fn emit_struct(&mut self, db: &DiagnosticBuilder) {
33         self.emit(db.span, &db.message, db.code.as_ref().map(|s| &**s), db.level);
34         for child in &db.children {
35             match child.render_span {
36                 Some(ref sp) => self.custom_emit(sp.clone(), &child.message, child.level),
37                 None => self.emit(child.span, &child.message, None, child.level),
38             }
39         }
40     }
41 }
42
43 /// maximum number of lines we will print for each error; arbitrary.
44 const MAX_LINES: usize = 6;
45
46 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
47 pub enum ColorConfig {
48     Auto,
49     Always,
50     Never,
51 }
52
53 impl ColorConfig {
54     fn use_color(&self) -> bool {
55         match *self {
56             ColorConfig::Always => true,
57             ColorConfig::Never  => false,
58             ColorConfig::Auto   => stderr_isatty(),
59         }
60     }
61 }
62
63 /// A basic emitter for when we don't have access to a codemap or registry. Used
64 /// for reporting very early errors, etc.
65 pub struct BasicEmitter {
66     dst: Destination,
67 }
68
69 impl Emitter for BasicEmitter {
70     fn emit(&mut self,
71             sp: Option<Span>,
72             msg: &str,
73             code: Option<&str>,
74             lvl: Level) {
75         assert!(sp.is_none(), "BasicEmitter can't handle spans");
76         if let Err(e) = print_diagnostic(&mut self.dst, "", lvl, msg, code) {
77             panic!("failed to print diagnostics: {:?}", e);
78         }
79
80     }
81
82     fn custom_emit(&mut self, _: RenderSpan, _: &str, _: Level) {
83         panic!("BasicEmitter can't handle custom_emit");
84     }
85 }
86
87 impl BasicEmitter {
88     pub fn stderr(color_config: ColorConfig) -> BasicEmitter {
89         if color_config.use_color() {
90             let dst = Destination::from_stderr();
91             BasicEmitter { dst: dst }
92         } else {
93             BasicEmitter { dst: Raw(Box::new(io::stderr())) }
94         }
95     }
96 }
97
98 pub struct EmitterWriter {
99     dst: Destination,
100     registry: Option<diagnostics::registry::Registry>,
101     cm: Rc<codemap::CodeMap>,
102 }
103
104 impl Emitter for EmitterWriter {
105     fn emit(&mut self,
106             sp: Option<Span>,
107             msg: &str,
108             code: Option<&str>,
109             lvl: Level) {
110         let error = match sp {
111             Some(COMMAND_LINE_SP) => self.emit_(FileLine(COMMAND_LINE_SP), msg, code, lvl),
112             Some(sp) => self.emit_(FullSpan(sp), msg, code, lvl),
113             None => print_diagnostic(&mut self.dst, "", lvl, msg, code),
114         };
115
116         if let Err(e) = error {
117             panic!("failed to print diagnostics: {:?}", e);
118         }
119     }
120
121     fn custom_emit(&mut self,
122                    sp: RenderSpan,
123                    msg: &str,
124                    lvl: Level) {
125         if let Err(e) = self.emit_(sp, msg, None, lvl) {
126             panic!("failed to print diagnostics: {:?}", e);
127         }
128     }
129 }
130
131 /// Do not use this for messages that end in `\n` – use `println_maybe_styled` instead. See
132 /// `EmitterWriter::print_maybe_styled` for details.
133 macro_rules! print_maybe_styled {
134     ($dst: expr, $style: expr, $($arg: tt)*) => {
135         $dst.print_maybe_styled(format_args!($($arg)*), $style, false)
136     }
137 }
138
139 macro_rules! println_maybe_styled {
140     ($dst: expr, $style: expr, $($arg: tt)*) => {
141         $dst.print_maybe_styled(format_args!($($arg)*), $style, true)
142     }
143 }
144
145 impl EmitterWriter {
146     pub fn stderr(color_config: ColorConfig,
147                   registry: Option<diagnostics::registry::Registry>,
148                   code_map: Rc<codemap::CodeMap>)
149                   -> EmitterWriter {
150         if color_config.use_color() {
151             let dst = Destination::from_stderr();
152             EmitterWriter { dst: dst, registry: registry, cm: code_map }
153         } else {
154             EmitterWriter { dst: Raw(Box::new(io::stderr())), registry: registry, cm: code_map }
155         }
156     }
157
158     pub fn new(dst: Box<Write + Send>,
159                registry: Option<diagnostics::registry::Registry>,
160                code_map: Rc<codemap::CodeMap>)
161                -> EmitterWriter {
162         EmitterWriter { dst: Raw(dst), registry: registry, cm: code_map }
163     }
164
165     fn emit_(&mut self,
166              rsp: RenderSpan,
167              msg: &str,
168              code: Option<&str>,
169              lvl: Level)
170              -> io::Result<()> {
171         let sp = rsp.span();
172
173         // We cannot check equality directly with COMMAND_LINE_SP
174         // since PartialEq is manually implemented to ignore the ExpnId
175         let ss = if sp.expn_id == COMMAND_LINE_EXPN {
176             "<command line option>".to_string()
177         } else if let EndSpan(_) = rsp {
178             let span_end = Span { lo: sp.hi, hi: sp.hi, expn_id: sp.expn_id};
179             self.cm.span_to_string(span_end)
180         } else {
181             self.cm.span_to_string(sp)
182         };
183
184         try!(print_diagnostic(&mut self.dst, &ss[..], lvl, msg, code));
185
186         match rsp {
187             FullSpan(_) => {
188                 let lines = self.cm.span_to_lines(sp);
189                 try!(self.highlight_lines(sp, lvl, lines));
190                 try!(self.print_macro_backtrace(sp));
191             }
192             EndSpan(_) => {
193                 let lines = self.cm.span_to_lines(sp);
194                 try!(self.end_highlight_lines(sp, lvl, lines));
195                 try!(self.print_macro_backtrace(sp));
196             }
197             Suggestion(_, ref suggestion) => {
198                 try!(self.highlight_suggestion(sp, suggestion));
199                 try!(self.print_macro_backtrace(sp));
200             }
201             FileLine(..) => {
202                 // no source text in this case!
203             }
204         }
205
206         match code {
207             Some(code) =>
208                 match self.registry.as_ref().and_then(|registry| registry.find_description(code)) {
209                     Some(_) => {
210                         try!(print_diagnostic(&mut self.dst, &ss[..], Help,
211                                               &format!("run `rustc --explain {}` to see a \
212                                                        detailed explanation", code), None));
213                     }
214                     None => ()
215                 },
216             None => (),
217         }
218         Ok(())
219     }
220
221     fn highlight_suggestion(&mut self,
222                             sp: Span,
223                             suggestion: &str)
224                             -> io::Result<()>
225     {
226         let lines = self.cm.span_to_lines(sp).unwrap();
227         assert!(!lines.lines.is_empty());
228
229         // To build up the result, we want to take the snippet from the first
230         // line that precedes the span, prepend that with the suggestion, and
231         // then append the snippet from the last line that trails the span.
232         let fm = &lines.file;
233
234         let first_line = &lines.lines[0];
235         let prefix = fm.get_line(first_line.line_index)
236                        .map(|l| &l[..first_line.start_col.0])
237                        .unwrap_or("");
238
239         let last_line = lines.lines.last().unwrap();
240         let suffix = fm.get_line(last_line.line_index)
241                        .map(|l| &l[last_line.end_col.0..])
242                        .unwrap_or("");
243
244         let complete = format!("{}{}{}", prefix, suggestion, suffix);
245
246         // print the suggestion without any line numbers, but leave
247         // space for them. This helps with lining up with previous
248         // snippets from the actual error being reported.
249         let fm = &*lines.file;
250         let mut lines = complete.lines();
251         for (line, line_index) in lines.by_ref().take(MAX_LINES).zip(first_line.line_index..) {
252             let elided_line_num = format!("{}", line_index+1);
253             try!(write!(&mut self.dst, "{0}:{1:2$} {3}\n",
254                         fm.name, "", elided_line_num.len(), line));
255         }
256
257         // if we elided some lines, add an ellipsis
258         if lines.next().is_some() {
259             let elided_line_num = format!("{}", first_line.line_index + MAX_LINES + 1);
260             try!(write!(&mut self.dst, "{0:1$} {0:2$} ...\n",
261                         "", fm.name.len(), elided_line_num.len()));
262         }
263
264         Ok(())
265     }
266
267     fn highlight_lines(&mut self,
268                        sp: Span,
269                        lvl: Level,
270                        lines: codemap::FileLinesResult)
271                        -> io::Result<()>
272     {
273         let lines = match lines {
274             Ok(lines) => lines,
275             Err(_) => {
276                 try!(write!(&mut self.dst, "(internal compiler error: unprintable span)\n"));
277                 return Ok(());
278             }
279         };
280
281         let fm = &*lines.file;
282
283         let line_strings: Option<Vec<&str>> =
284             lines.lines.iter()
285                        .map(|info| fm.get_line(info.line_index))
286                        .collect();
287
288         let line_strings = match line_strings {
289             None => { return Ok(()); }
290             Some(line_strings) => line_strings
291         };
292
293         // Display only the first MAX_LINES lines.
294         let all_lines = lines.lines.len();
295         let display_lines = cmp::min(all_lines, MAX_LINES);
296         let display_line_infos = &lines.lines[..display_lines];
297         let display_line_strings = &line_strings[..display_lines];
298
299         // Calculate the widest number to format evenly and fix #11715
300         assert!(display_line_infos.len() > 0);
301         let mut max_line_num = display_line_infos[display_line_infos.len() - 1].line_index + 1;
302         let mut digits = 0;
303         while max_line_num > 0 {
304             max_line_num /= 10;
305             digits += 1;
306         }
307
308         // Print the offending lines
309         for (line_info, line) in display_line_infos.iter().zip(display_line_strings) {
310             try!(write!(&mut self.dst, "{}:{:>width$} {}\n",
311                         fm.name,
312                         line_info.line_index + 1,
313                         line,
314                         width=digits));
315         }
316
317         // If we elided something, put an ellipsis.
318         if display_lines < all_lines {
319             let last_line_index = display_line_infos.last().unwrap().line_index;
320             let s = format!("{}:{} ", fm.name, last_line_index + 1);
321             try!(write!(&mut self.dst, "{0:1$}...\n", "", s.len()));
322         }
323
324         // FIXME (#3260)
325         // If there's one line at fault we can easily point to the problem
326         if lines.lines.len() == 1 {
327             let lo = self.cm.lookup_char_pos(sp.lo);
328             let mut digits = 0;
329             let mut num = (lines.lines[0].line_index + 1) / 10;
330
331             // how many digits must be indent past?
332             while num > 0 { num /= 10; digits += 1; }
333
334             let mut s = String::new();
335             // Skip is the number of characters we need to skip because they are
336             // part of the 'filename:line ' part of the previous line.
337             let skip = fm.name.chars().count() + digits + 3;
338             for _ in 0..skip {
339                 s.push(' ');
340             }
341             if let Some(orig) = fm.get_line(lines.lines[0].line_index) {
342                 let mut col = skip;
343                 let mut lastc = ' ';
344                 let mut iter = orig.chars().enumerate();
345                 for (pos, ch) in iter.by_ref() {
346                     lastc = ch;
347                     if pos >= lo.col.to_usize() { break; }
348                     // Whenever a tab occurs on the previous line, we insert one on
349                     // the error-point-squiggly-line as well (instead of a space).
350                     // That way the squiggly line will usually appear in the correct
351                     // position.
352                     match ch {
353                         '\t' => {
354                             col += 8 - col%8;
355                             s.push('\t');
356                         },
357                         _ => {
358                             col += 1;
359                             s.push(' ');
360                         },
361                     }
362                 }
363
364                 try!(write!(&mut self.dst, "{}", s));
365                 let mut s = String::from("^");
366                 let count = match lastc {
367                     // Most terminals have a tab stop every eight columns by default
368                     '\t' => 8 - col%8,
369                     _ => 1,
370                 };
371                 col += count;
372                 s.extend(::std::iter::repeat('~').take(count));
373
374                 let hi = self.cm.lookup_char_pos(sp.hi);
375                 if hi.col != lo.col {
376                     for (pos, ch) in iter {
377                         if pos >= hi.col.to_usize() { break; }
378                         let count = match ch {
379                             '\t' => 8 - col%8,
380                             _ => 1,
381                         };
382                         col += count;
383                         s.extend(::std::iter::repeat('~').take(count));
384                     }
385                 }
386
387                 if s.len() > 1 {
388                     // One extra squiggly is replaced by a "^"
389                     s.pop();
390                 }
391
392                 try!(println_maybe_styled!(&mut self.dst, term::Attr::ForegroundColor(lvl.color()),
393                                            "{}", s));
394             }
395         }
396         Ok(())
397     }
398
399     /// Here are the differences between this and the normal `highlight_lines`:
400     /// `end_highlight_lines` will always put arrow on the last byte of the
401     /// span (instead of the first byte). Also, when the span is too long (more
402     /// than 6 lines), `end_highlight_lines` will print the first line, then
403     /// dot dot dot, then last line, whereas `highlight_lines` prints the first
404     /// six lines.
405     #[allow(deprecated)]
406     fn end_highlight_lines(&mut self,
407                            sp: Span,
408                            lvl: Level,
409                            lines: codemap::FileLinesResult)
410                           -> io::Result<()> {
411         let lines = match lines {
412             Ok(lines) => lines,
413             Err(_) => {
414                 try!(write!(&mut self.dst, "(internal compiler error: unprintable span)\n"));
415                 return Ok(());
416             }
417         };
418
419         let fm = &*lines.file;
420
421         let lines = &lines.lines[..];
422         if lines.len() > MAX_LINES {
423             if let Some(line) = fm.get_line(lines[0].line_index) {
424                 try!(write!(&mut self.dst, "{}:{} {}\n", fm.name,
425                             lines[0].line_index + 1, line));
426             }
427             try!(write!(&mut self.dst, "...\n"));
428             let last_line_index = lines[lines.len() - 1].line_index;
429             if let Some(last_line) = fm.get_line(last_line_index) {
430                 try!(write!(&mut self.dst, "{}:{} {}\n", fm.name,
431                             last_line_index + 1, last_line));
432             }
433         } else {
434             for line_info in lines {
435                 if let Some(line) = fm.get_line(line_info.line_index) {
436                     try!(write!(&mut self.dst, "{}:{} {}\n", fm.name,
437                                 line_info.line_index + 1, line));
438                 }
439             }
440         }
441         let last_line_start = format!("{}:{} ", fm.name, lines[lines.len()-1].line_index + 1);
442         let hi = self.cm.lookup_char_pos(sp.hi);
443         let skip = last_line_start.chars().count();
444         let mut s = String::new();
445         for _ in 0..skip {
446             s.push(' ');
447         }
448         if let Some(orig) = fm.get_line(lines[0].line_index) {
449             let iter = orig.chars().enumerate();
450             for (pos, ch) in iter {
451                 // Span seems to use half-opened interval, so subtract 1
452                 if pos >= hi.col.to_usize() - 1 { break; }
453                 // Whenever a tab occurs on the previous line, we insert one on
454                 // the error-point-squiggly-line as well (instead of a space).
455                 // That way the squiggly line will usually appear in the correct
456                 // position.
457                 match ch {
458                     '\t' => s.push('\t'),
459                     _ => s.push(' '),
460                 }
461             }
462         }
463         s.push('^');
464         println_maybe_styled!(&mut self.dst, term::Attr::ForegroundColor(lvl.color()),
465                               "{}", s)
466     }
467
468     fn print_macro_backtrace(&mut self,
469                              sp: Span)
470                              -> io::Result<()> {
471         let mut last_span = codemap::DUMMY_SP;
472         let mut span = sp;
473
474         loop {
475             let span_name_span = self.cm.with_expn_info(span.expn_id, |expn_info| {
476                 expn_info.map(|ei| {
477                     let (pre, post) = match ei.callee.format {
478                         codemap::MacroAttribute(..) => ("#[", "]"),
479                         codemap::MacroBang(..) => ("", "!"),
480                     };
481                     let macro_decl_name = format!("in this expansion of {}{}{}",
482                                                   pre,
483                                                   ei.callee.name(),
484                                                   post);
485                     let def_site_span = ei.callee.span;
486                     (ei.call_site, macro_decl_name, def_site_span)
487                 })
488             });
489             let (macro_decl_name, def_site_span) = match span_name_span {
490                 None => break,
491                 Some((sp, macro_decl_name, def_site_span)) => {
492                     span = sp;
493                     (macro_decl_name, def_site_span)
494                 }
495             };
496
497             // Don't print recursive invocations
498             if span != last_span {
499                 let mut diag_string = macro_decl_name;
500                 if let Some(def_site_span) = def_site_span {
501                     diag_string.push_str(&format!(" (defined in {})",
502                                                   self.cm.span_to_filename(def_site_span)));
503                 }
504
505                 let snippet = self.cm.span_to_string(span);
506                 try!(print_diagnostic(&mut self.dst, &snippet, Note, &diag_string, None));
507             }
508             last_span = span;
509         }
510
511         Ok(())
512     }
513 }
514
515 fn print_diagnostic(dst: &mut Destination,
516                     topic: &str,
517                     lvl: Level,
518                     msg: &str,
519                     code: Option<&str>)
520                     -> io::Result<()> {
521     if !topic.is_empty() {
522         try!(write!(dst, "{} ", topic));
523     }
524
525     try!(print_maybe_styled!(dst, term::Attr::ForegroundColor(lvl.color()),
526                              "{}: ", lvl.to_string()));
527     try!(print_maybe_styled!(dst, term::Attr::Bold, "{}", msg));
528
529     match code {
530         Some(code) => {
531             let style = term::Attr::ForegroundColor(term::color::BRIGHT_MAGENTA);
532             try!(print_maybe_styled!(dst, style, " [{}]", code.clone()));
533         }
534         None => ()
535     }
536     try!(write!(dst, "\n"));
537     Ok(())
538 }
539
540 #[cfg(unix)]
541 fn stderr_isatty() -> bool {
542     use libc;
543     unsafe { libc::isatty(libc::STDERR_FILENO) != 0 }
544 }
545 #[cfg(windows)]
546 fn stderr_isatty() -> bool {
547     type DWORD = u32;
548     type BOOL = i32;
549     type HANDLE = *mut u8;
550     const STD_ERROR_HANDLE: DWORD = -12i32 as DWORD;
551     extern "system" {
552         fn GetStdHandle(which: DWORD) -> HANDLE;
553         fn GetConsoleMode(hConsoleHandle: HANDLE,
554                           lpMode: *mut DWORD) -> BOOL;
555     }
556     unsafe {
557         let handle = GetStdHandle(STD_ERROR_HANDLE);
558         let mut out = 0;
559         GetConsoleMode(handle, &mut out) != 0
560     }
561 }
562
563 enum Destination {
564     Terminal(Box<term::StderrTerminal>),
565     Raw(Box<Write + Send>),
566 }
567
568 impl Destination {
569     fn from_stderr() -> Destination {
570         match term::stderr() {
571             Some(t) => Terminal(t),
572             None    => Raw(Box::new(io::stderr())),
573         }
574     }
575
576     fn print_maybe_styled(&mut self,
577                           args: fmt::Arguments,
578                           color: term::Attr,
579                           print_newline_at_end: bool)
580                           -> io::Result<()> {
581         match *self {
582             Terminal(ref mut t) => {
583                 try!(t.attr(color));
584                 // If `msg` ends in a newline, we need to reset the color before
585                 // the newline. We're making the assumption that we end up writing
586                 // to a `LineBufferedWriter`, which means that emitting the reset
587                 // after the newline ends up buffering the reset until we print
588                 // another line or exit. Buffering the reset is a problem if we're
589                 // sharing the terminal with any other programs (e.g. other rustc
590                 // instances via `make -jN`).
591                 //
592                 // Note that if `msg` contains any internal newlines, this will
593                 // result in the `LineBufferedWriter` flushing twice instead of
594                 // once, which still leaves the opportunity for interleaved output
595                 // to be miscolored. We assume this is rare enough that we don't
596                 // have to worry about it.
597                 try!(t.write_fmt(args));
598                 try!(t.reset());
599                 if print_newline_at_end {
600                     t.write_all(b"\n")
601                 } else {
602                     Ok(())
603                 }
604             }
605             Raw(ref mut w) => {
606                 try!(w.write_fmt(args));
607                 if print_newline_at_end {
608                     w.write_all(b"\n")
609                 } else {
610                     Ok(())
611                 }
612             }
613         }
614     }
615 }
616
617 impl Write for Destination {
618     fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
619         match *self {
620             Terminal(ref mut t) => t.write(bytes),
621             Raw(ref mut w) => w.write(bytes),
622         }
623     }
624     fn flush(&mut self) -> io::Result<()> {
625         match *self {
626             Terminal(ref mut t) => t.flush(),
627             Raw(ref mut w) => w.flush(),
628         }
629     }
630 }
631
632
633 #[cfg(test)]
634 mod test {
635     use errors::Level;
636     use super::EmitterWriter;
637     use codemap::{mk_sp, CodeMap};
638     use std::sync::{Arc, Mutex};
639     use std::io::{self, Write};
640     use std::str::from_utf8;
641     use std::rc::Rc;
642
643     // Diagnostic doesn't align properly in span where line number increases by one digit
644     #[test]
645     fn test_hilight_suggestion_issue_11715() {
646         struct Sink(Arc<Mutex<Vec<u8>>>);
647         impl Write for Sink {
648             fn write(&mut self, data: &[u8]) -> io::Result<usize> {
649                 Write::write(&mut *self.0.lock().unwrap(), data)
650             }
651             fn flush(&mut self) -> io::Result<()> { Ok(()) }
652         }
653         let data = Arc::new(Mutex::new(Vec::new()));
654         let cm = Rc::new(CodeMap::new());
655         let mut ew = EmitterWriter::new(Box::new(Sink(data.clone())), None, cm.clone());
656         let content = "abcdefg
657         koksi
658         line3
659         line4
660         cinq
661         line6
662         line7
663         line8
664         line9
665         line10
666         e-lä-vän
667         tolv
668         dreizehn
669         ";
670         let file = cm.new_filemap_and_lines("dummy.txt", content);
671         let start = file.lines.borrow()[7];
672         let end = file.lines.borrow()[11];
673         let sp = mk_sp(start, end);
674         let lvl = Level::Error;
675         println!("span_to_lines");
676         let lines = cm.span_to_lines(sp);
677         println!("highlight_lines");
678         ew.highlight_lines(sp, lvl, lines).unwrap();
679         println!("done");
680         let vec = data.lock().unwrap().clone();
681         let vec: &[u8] = &vec;
682         let str = from_utf8(vec).unwrap();
683         println!("{}", str);
684         assert_eq!(str, "dummy.txt: 8         line8\n\
685                          dummy.txt: 9         line9\n\
686                          dummy.txt:10         line10\n\
687                          dummy.txt:11         e-lä-vän\n\
688                          dummy.txt:12         tolv\n");
689     }
690 }