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 use self::Destination::*;
13 use codemap::{self, COMMAND_LINE_SP, COMMAND_LINE_EXPN, Pos, Span};
16 use errors::{Level, RenderSpan, DiagnosticBuilder};
17 use errors::RenderSpan::*;
21 use std::io::prelude::*;
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);
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),
43 /// maximum number of lines we will print for each error; arbitrary.
44 const MAX_LINES: usize = 6;
46 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
47 pub enum ColorConfig {
54 fn use_color(&self) -> bool {
56 ColorConfig::Always => true,
57 ColorConfig::Never => false,
58 ColorConfig::Auto => stderr_isatty(),
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 {
69 impl Emitter for BasicEmitter {
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);
82 fn custom_emit(&mut self, _: RenderSpan, _: &str, _: Level) {
83 panic!("BasicEmitter can't handle custom_emit");
88 pub fn stderr(color_config: ColorConfig) -> BasicEmitter {
89 if color_config.use_color() {
90 let dst = Destination::from_stderr();
91 BasicEmitter { dst: dst }
93 BasicEmitter { dst: Raw(Box::new(io::stderr())) }
98 pub struct EmitterWriter {
100 registry: Option<diagnostics::registry::Registry>,
101 cm: Rc<codemap::CodeMap>,
104 impl Emitter for EmitterWriter {
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),
116 if let Err(e) = error {
117 panic!("failed to print diagnostics: {:?}", e);
121 fn custom_emit(&mut self,
125 if let Err(e) = self.emit_(sp, msg, None, lvl) {
126 panic!("failed to print diagnostics: {:?}", e);
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)
139 macro_rules! println_maybe_styled {
140 ($dst: expr, $style: expr, $($arg: tt)*) => {
141 $dst.print_maybe_styled(format_args!($($arg)*), $style, true)
146 pub fn stderr(color_config: ColorConfig,
147 registry: Option<diagnostics::registry::Registry>,
148 code_map: Rc<codemap::CodeMap>)
150 if color_config.use_color() {
151 let dst = Destination::from_stderr();
152 EmitterWriter { dst: dst, registry: registry, cm: code_map }
154 EmitterWriter { dst: Raw(Box::new(io::stderr())), registry: registry, cm: code_map }
158 pub fn new(dst: Box<Write + Send>,
159 registry: Option<diagnostics::registry::Registry>,
160 code_map: Rc<codemap::CodeMap>)
162 EmitterWriter { dst: Raw(dst), registry: registry, cm: code_map }
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)
181 self.cm.span_to_string(sp)
184 try!(print_diagnostic(&mut self.dst, &ss[..], lvl, msg, code));
188 let lines = self.cm.span_to_lines(sp);
189 try!(self.highlight_lines(sp, lvl, lines));
190 try!(self.print_macro_backtrace(sp));
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));
197 Suggestion(_, ref suggestion) => {
198 try!(self.highlight_suggestion(sp, suggestion));
199 try!(self.print_macro_backtrace(sp));
202 // no source text in this case!
208 match self.registry.as_ref().and_then(|registry| registry.find_description(code)) {
210 try!(print_diagnostic(&mut self.dst, &ss[..], Help,
211 &format!("run `rustc --explain {}` to see a \
212 detailed explanation", code), None));
221 fn highlight_suggestion(&mut self,
226 let lines = self.cm.span_to_lines(sp).unwrap();
227 assert!(!lines.lines.is_empty());
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;
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])
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..])
244 let complete = format!("{}{}{}", prefix, suggestion, suffix);
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));
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()));
267 fn highlight_lines(&mut self,
270 lines: codemap::FileLinesResult)
273 let lines = match lines {
276 try!(write!(&mut self.dst, "(internal compiler error: unprintable span)\n"));
281 let fm = &*lines.file;
283 let line_strings: Option<Vec<&str>> =
285 .map(|info| fm.get_line(info.line_index))
288 let line_strings = match line_strings {
289 None => { return Ok(()); }
290 Some(line_strings) => line_strings
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];
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;
303 while max_line_num > 0 {
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",
312 line_info.line_index + 1,
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()));
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);
329 let mut num = (lines.lines[0].line_index + 1) / 10;
331 // how many digits must be indent past?
332 while num > 0 { num /= 10; digits += 1; }
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;
341 if let Some(orig) = fm.get_line(lines.lines[0].line_index) {
344 let mut iter = orig.chars().enumerate();
345 for (pos, ch) in iter.by_ref() {
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
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
372 s.extend(::std::iter::repeat('~').take(count));
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 {
383 s.extend(::std::iter::repeat('~').take(count));
388 // One extra squiggly is replaced by a "^"
392 try!(println_maybe_styled!(&mut self.dst, term::Attr::ForegroundColor(lvl.color()),
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
406 fn end_highlight_lines(&mut self,
409 lines: codemap::FileLinesResult)
411 let lines = match lines {
414 try!(write!(&mut self.dst, "(internal compiler error: unprintable span)\n"));
419 let fm = &*lines.file;
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));
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));
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));
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();
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
458 '\t' => s.push('\t'),
464 println_maybe_styled!(&mut self.dst, term::Attr::ForegroundColor(lvl.color()),
468 fn print_macro_backtrace(&mut self,
471 let mut last_span = codemap::DUMMY_SP;
475 let span_name_span = self.cm.with_expn_info(span.expn_id, |expn_info| {
477 let (pre, post) = match ei.callee.format {
478 codemap::MacroAttribute(..) => ("#[", "]"),
479 codemap::MacroBang(..) => ("", "!"),
481 let macro_decl_name = format!("in this expansion of {}{}{}",
485 let def_site_span = ei.callee.span;
486 (ei.call_site, macro_decl_name, def_site_span)
489 let (macro_decl_name, def_site_span) = match span_name_span {
491 Some((sp, macro_decl_name, def_site_span)) => {
493 (macro_decl_name, def_site_span)
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)));
505 let snippet = self.cm.span_to_string(span);
506 try!(print_diagnostic(&mut self.dst, &snippet, Note, &diag_string, None));
515 fn print_diagnostic(dst: &mut Destination,
521 if !topic.is_empty() {
522 try!(write!(dst, "{} ", topic));
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));
531 let style = term::Attr::ForegroundColor(term::color::BRIGHT_MAGENTA);
532 try!(print_maybe_styled!(dst, style, " [{}]", code.clone()));
536 try!(write!(dst, "\n"));
541 fn stderr_isatty() -> bool {
543 unsafe { libc::isatty(libc::STDERR_FILENO) != 0 }
546 fn stderr_isatty() -> bool {
549 type HANDLE = *mut u8;
550 const STD_ERROR_HANDLE: DWORD = -12i32 as DWORD;
552 fn GetStdHandle(which: DWORD) -> HANDLE;
553 fn GetConsoleMode(hConsoleHandle: HANDLE,
554 lpMode: *mut DWORD) -> BOOL;
557 let handle = GetStdHandle(STD_ERROR_HANDLE);
559 GetConsoleMode(handle, &mut out) != 0
564 Terminal(Box<term::StderrTerminal>),
565 Raw(Box<Write + Send>),
569 fn from_stderr() -> Destination {
570 match term::stderr() {
571 Some(t) => Terminal(t),
572 None => Raw(Box::new(io::stderr())),
576 fn print_maybe_styled(&mut self,
577 args: fmt::Arguments,
579 print_newline_at_end: bool)
582 Terminal(ref mut t) => {
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`).
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));
599 if print_newline_at_end {
606 try!(w.write_fmt(args));
607 if print_newline_at_end {
617 impl Write for Destination {
618 fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
620 Terminal(ref mut t) => t.write(bytes),
621 Raw(ref mut w) => w.write(bytes),
624 fn flush(&mut self) -> io::Result<()> {
626 Terminal(ref mut t) => t.flush(),
627 Raw(ref mut w) => w.flush(),
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;
643 // Diagnostic doesn't align properly in span where line number increases by one digit
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)
651 fn flush(&mut self) -> io::Result<()> { Ok(()) }
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
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();
680 let vec = data.lock().unwrap().clone();
681 let vec: &[u8] = &vec;
682 let str = from_utf8(vec).unwrap();
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");