1 // Copyright 2012 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 pub use self::Level::*;
12 pub use self::RenderSpan::*;
13 pub use self::ColorConfig::*;
14 use self::Destination::*;
16 use codemap::{Pos, Span};
20 use std::cell::{RefCell, Cell};
24 use std::string::String;
25 use term::WriterWrapper;
28 /// maximum number of lines we will print for each error; arbitrary.
29 static MAX_LINES: uint = 6u;
33 /// A FullSpan renders with both with an initial line for the
34 /// message, prefixed by file:linenum, followed by a summary of
35 /// the source code covered by the span.
38 /// A FileLine renders with just a line for the message prefixed
43 impl Copy for RenderSpan {}
46 fn span(self) -> Span {
48 FullSpan(s) | FileLine(s) => s
51 fn is_full_span(&self) -> bool {
53 &FullSpan(..) => true,
54 &FileLine(..) => false,
60 pub enum ColorConfig {
66 impl Copy for ColorConfig {}
69 fn emit(&mut self, cmsp: Option<(&codemap::CodeMap, Span)>,
70 msg: &str, code: Option<&str>, lvl: Level);
71 fn custom_emit(&mut self, cm: &codemap::CodeMap,
72 sp: RenderSpan, msg: &str, lvl: Level);
75 /// This structure is used to signify that a task has panicked with a fatal error
76 /// from the diagnostics. You can use this with the `Any` trait to figure out
77 /// how a rustc task died (if so desired).
78 pub struct FatalError;
80 impl Copy for FatalError {}
82 /// Signifies that the compiler died with an explicit call to `.bug`
83 /// or `.span_bug` rather than a failed assertion, etc.
84 pub struct ExplicitBug;
86 impl Copy for ExplicitBug {}
88 /// A span-handler is like a handler but also
89 /// accepts span information for source-location
91 pub struct SpanHandler {
93 pub cm: codemap::CodeMap,
97 pub fn span_fatal(&self, sp: Span, msg: &str) -> ! {
98 self.handler.emit(Some((&self.cm, sp)), msg, Fatal);
101 pub fn span_err(&self, sp: Span, msg: &str) {
102 self.handler.emit(Some((&self.cm, sp)), msg, Error);
103 self.handler.bump_err_count();
105 pub fn span_err_with_code(&self, sp: Span, msg: &str, code: &str) {
106 self.handler.emit_with_code(Some((&self.cm, sp)), msg, code, Error);
107 self.handler.bump_err_count();
109 pub fn span_warn(&self, sp: Span, msg: &str) {
110 self.handler.emit(Some((&self.cm, sp)), msg, Warning);
112 pub fn span_warn_with_code(&self, sp: Span, msg: &str, code: &str) {
113 self.handler.emit_with_code(Some((&self.cm, sp)), msg, code, Warning);
115 pub fn span_note(&self, sp: Span, msg: &str) {
116 self.handler.emit(Some((&self.cm, sp)), msg, Note);
118 pub fn span_end_note(&self, sp: Span, msg: &str) {
119 self.handler.custom_emit(&self.cm, FullSpan(sp), msg, Note);
121 pub fn span_help(&self, sp: Span, msg: &str) {
122 self.handler.emit(Some((&self.cm, sp)), msg, Help);
124 pub fn fileline_note(&self, sp: Span, msg: &str) {
125 self.handler.custom_emit(&self.cm, FileLine(sp), msg, Note);
127 pub fn span_bug(&self, sp: Span, msg: &str) -> ! {
128 self.handler.emit(Some((&self.cm, sp)), msg, Bug);
131 pub fn span_unimpl(&self, sp: Span, msg: &str) -> ! {
132 self.span_bug(sp, format!("unimplemented {}", msg).as_slice());
134 pub fn handler<'a>(&'a self) -> &'a Handler {
139 /// A handler deals with errors; certain errors
140 /// (fatal, bug, unimpl) may cause immediate exit,
141 /// others log errors for later reporting.
143 err_count: Cell<uint>,
144 emit: RefCell<Box<Emitter + Send>>,
148 pub fn fatal(&self, msg: &str) -> ! {
149 self.emit.borrow_mut().emit(None, msg, None, Fatal);
152 pub fn err(&self, msg: &str) {
153 self.emit.borrow_mut().emit(None, msg, None, Error);
154 self.bump_err_count();
156 pub fn bump_err_count(&self) {
157 self.err_count.set(self.err_count.get() + 1u);
159 pub fn err_count(&self) -> uint {
162 pub fn has_errors(&self) -> bool {
163 self.err_count.get()> 0u
165 pub fn abort_if_errors(&self) {
167 match self.err_count.get() {
169 1u => s = "aborting due to previous error".to_string(),
171 s = format!("aborting due to {} previous errors",
172 self.err_count.get());
175 self.fatal(s.as_slice());
177 pub fn warn(&self, msg: &str) {
178 self.emit.borrow_mut().emit(None, msg, None, Warning);
180 pub fn note(&self, msg: &str) {
181 self.emit.borrow_mut().emit(None, msg, None, Note);
183 pub fn help(&self, msg: &str) {
184 self.emit.borrow_mut().emit(None, msg, None, Help);
186 pub fn bug(&self, msg: &str) -> ! {
187 self.emit.borrow_mut().emit(None, msg, None, Bug);
190 pub fn unimpl(&self, msg: &str) -> ! {
191 self.bug(format!("unimplemented {}", msg).as_slice());
194 cmsp: Option<(&codemap::CodeMap, Span)>,
197 self.emit.borrow_mut().emit(cmsp, msg, None, lvl);
199 pub fn emit_with_code(&self,
200 cmsp: Option<(&codemap::CodeMap, Span)>,
204 self.emit.borrow_mut().emit(cmsp, msg, Some(code), lvl);
206 pub fn custom_emit(&self, cm: &codemap::CodeMap,
207 sp: RenderSpan, msg: &str, lvl: Level) {
208 self.emit.borrow_mut().custom_emit(cm, sp, msg, lvl);
212 pub fn mk_span_handler(handler: Handler, cm: codemap::CodeMap) -> SpanHandler {
219 pub fn default_handler(color_config: ColorConfig,
220 registry: Option<diagnostics::registry::Registry>) -> Handler {
221 mk_handler(box EmitterWriter::stderr(color_config, registry))
224 pub fn mk_handler(e: Box<Emitter + Send>) -> Handler {
226 err_count: Cell::new(0),
227 emit: RefCell::new(e),
231 #[deriving(PartialEq, Clone)]
241 impl Copy for Level {}
243 impl fmt::Show for Level {
244 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
248 Bug => "error: internal compiler error".fmt(f),
249 Fatal | Error => "error".fmt(f),
250 Warning => "warning".fmt(f),
251 Note => "note".fmt(f),
252 Help => "help".fmt(f),
258 fn color(self) -> term::color::Color {
260 Bug | Fatal | Error => term::color::BRIGHT_RED,
261 Warning => term::color::BRIGHT_YELLOW,
262 Note => term::color::BRIGHT_GREEN,
263 Help => term::color::BRIGHT_CYAN,
268 fn print_maybe_styled(w: &mut EmitterWriter,
270 color: term::attr::Attr) -> io::IoResult<()> {
272 Terminal(ref mut t) => {
274 // If `msg` ends in a newline, we need to reset the color before
275 // the newline. We're making the assumption that we end up writing
276 // to a `LineBufferedWriter`, which means that emitting the reset
277 // after the newline ends up buffering the reset until we print
278 // another line or exit. Buffering the reset is a problem if we're
279 // sharing the terminal with any other programs (e.g. other rustc
280 // instances via `make -jN`).
282 // Note that if `msg` contains any internal newlines, this will
283 // result in the `LineBufferedWriter` flushing twice instead of
284 // once, which still leaves the opportunity for interleaved output
285 // to be miscolored. We assume this is rare enough that we don't
286 // have to worry about it.
287 if msg.ends_with("\n") {
288 try!(t.write_str(msg.slice_to(msg.len()-1)));
290 try!(t.write_str("\n"));
292 try!(t.write_str(msg));
303 fn print_diagnostic(dst: &mut EmitterWriter, topic: &str, lvl: Level,
304 msg: &str, code: Option<&str>) -> io::IoResult<()> {
305 if !topic.is_empty() {
306 try!(write!(&mut dst.dst, "{} ", topic));
309 try!(print_maybe_styled(dst,
310 format!("{}: ", lvl.to_string()).as_slice(),
311 term::attr::ForegroundColor(lvl.color())));
312 try!(print_maybe_styled(dst,
313 format!("{}", msg).as_slice(),
318 let style = term::attr::ForegroundColor(term::color::BRIGHT_MAGENTA);
319 try!(print_maybe_styled(dst, format!(" [{}]", code.clone()).as_slice(), style));
323 try!(dst.dst.write_char('\n'));
327 pub struct EmitterWriter {
329 registry: Option<diagnostics::registry::Registry>
333 Terminal(Box<term::Terminal<WriterWrapper> + Send>),
334 Raw(Box<Writer + Send>),
338 pub fn stderr(color_config: ColorConfig,
339 registry: Option<diagnostics::registry::Registry>) -> EmitterWriter {
340 let stderr = io::stderr();
342 let use_color = match color_config {
345 Auto => stderr.get_ref().isatty()
349 let dst = match term::stderr() {
350 Some(t) => Terminal(t),
351 None => Raw(box stderr),
353 EmitterWriter { dst: dst, registry: registry }
355 EmitterWriter { dst: Raw(box stderr), registry: registry }
359 pub fn new(dst: Box<Writer + Send>,
360 registry: Option<diagnostics::registry::Registry>) -> EmitterWriter {
361 EmitterWriter { dst: Raw(dst), registry: registry }
365 impl Writer for Destination {
366 fn write(&mut self, bytes: &[u8]) -> io::IoResult<()> {
368 Terminal(ref mut t) => t.write(bytes),
369 Raw(ref mut w) => w.write(bytes),
374 impl Emitter for EmitterWriter {
376 cmsp: Option<(&codemap::CodeMap, Span)>,
377 msg: &str, code: Option<&str>, lvl: Level) {
378 let error = match cmsp {
379 Some((cm, sp)) => emit(self, cm, FullSpan(sp), msg, code, lvl, false),
380 None => print_diagnostic(self, "", lvl, msg, code),
385 Err(e) => panic!("failed to print diagnostics: {}", e),
389 fn custom_emit(&mut self, cm: &codemap::CodeMap,
390 sp: RenderSpan, msg: &str, lvl: Level) {
391 match emit(self, cm, sp, msg, None, lvl, true) {
393 Err(e) => panic!("failed to print diagnostics: {}", e),
398 fn emit(dst: &mut EmitterWriter, cm: &codemap::CodeMap, rsp: RenderSpan,
399 msg: &str, code: Option<&str>, lvl: Level, custom: bool) -> io::IoResult<()> {
401 let ss = cm.span_to_string(sp);
402 let lines = cm.span_to_lines(sp);
404 // we want to tell compiletest/runtest to look at the last line of the
405 // span (since `custom_highlight_lines` displays an arrow to the end of
407 let span_end = Span { lo: sp.hi, hi: sp.hi, expn_id: sp.expn_id};
408 let ses = cm.span_to_string(span_end);
409 try!(print_diagnostic(dst, ses.as_slice(), lvl, msg, code));
410 if rsp.is_full_span() {
411 try!(custom_highlight_lines(dst, cm, sp, lvl, lines));
414 try!(print_diagnostic(dst, ss.as_slice(), lvl, msg, code));
415 if rsp.is_full_span() {
416 try!(highlight_lines(dst, cm, sp, lvl, lines));
419 try!(print_macro_backtrace(dst, cm, sp));
422 match dst.registry.as_ref().and_then(|registry| registry.find_description(code)) {
424 try!(print_diagnostic(dst, ss.as_slice(), Help,
425 format!("pass `--explain {}` to see a detailed \
426 explanation", code).as_slice(), None));
435 fn highlight_lines(err: &mut EmitterWriter,
436 cm: &codemap::CodeMap,
439 lines: codemap::FileLines) -> io::IoResult<()> {
440 let fm = &*lines.file;
442 let mut elided = false;
443 let mut display_lines = lines.lines.as_slice();
444 if display_lines.len() > MAX_LINES {
445 display_lines = display_lines[0u..MAX_LINES];
448 // Print the offending lines
449 for &line_number in display_lines.iter() {
450 if let Some(line) = fm.get_line(line_number) {
451 try!(write!(&mut err.dst, "{}:{} {}\n", fm.name,
452 line_number + 1, line));
456 let last_line = display_lines[display_lines.len() - 1u];
457 let s = format!("{}:{} ", fm.name, last_line + 1u);
458 try!(write!(&mut err.dst, "{0:1$}...\n", "", s.len()));
462 // If there's one line at fault we can easily point to the problem
463 if lines.lines.len() == 1u {
464 let lo = cm.lookup_char_pos(sp.lo);
466 let mut num = (lines.lines[0] + 1u) / 10u;
468 // how many digits must be indent past?
469 while num > 0u { num /= 10u; digits += 1u; }
471 // indent past |name:## | and the 0-offset column location
472 let left = fm.name.len() + digits + lo.col.to_uint() + 3u;
473 let mut s = String::new();
474 // Skip is the number of characters we need to skip because they are
475 // part of the 'filename:line ' part of the previous line.
476 let skip = fm.name.len() + digits + 3u;
477 for _ in range(0, skip) {
480 if let Some(orig) = fm.get_line(lines.lines[0]) {
481 for pos in range(0u, left - skip) {
482 let cur_char = orig.as_bytes()[pos] as char;
483 // Whenever a tab occurs on the previous line, we insert one on
484 // the error-point-squiggly-line as well (instead of a space).
485 // That way the squiggly line will usually appear in the correct
488 '\t' => s.push('\t'),
494 try!(write!(&mut err.dst, "{}", s));
495 let mut s = String::from_str("^");
496 let hi = cm.lookup_char_pos(sp.hi);
497 if hi.col != lo.col {
498 // the ^ already takes up one space
499 let num_squigglies = hi.col.to_uint() - lo.col.to_uint() - 1u;
500 for _ in range(0, num_squigglies) {
504 try!(print_maybe_styled(err,
505 format!("{}\n", s).as_slice(),
506 term::attr::ForegroundColor(lvl.color())));
511 /// Here are the differences between this and the normal `highlight_lines`:
512 /// `custom_highlight_lines` will always put arrow on the last byte of the
513 /// span (instead of the first byte). Also, when the span is too long (more
514 /// than 6 lines), `custom_highlight_lines` will print the first line, then
515 /// dot dot dot, then last line, whereas `highlight_lines` prints the first
517 fn custom_highlight_lines(w: &mut EmitterWriter,
518 cm: &codemap::CodeMap,
521 lines: codemap::FileLines)
522 -> io::IoResult<()> {
523 let fm = &*lines.file;
525 let lines = lines.lines.as_slice();
526 if lines.len() > MAX_LINES {
527 if let Some(line) = fm.get_line(lines[0]) {
528 try!(write!(&mut w.dst, "{}:{} {}\n", fm.name,
529 lines[0] + 1, line));
531 try!(write!(&mut w.dst, "...\n"));
532 let last_line_number = lines[lines.len() - 1];
533 if let Some(last_line) = fm.get_line(last_line_number) {
534 try!(write!(&mut w.dst, "{}:{} {}\n", fm.name,
535 last_line_number + 1, last_line));
538 for &line_number in lines.iter() {
539 if let Some(line) = fm.get_line(line_number) {
540 try!(write!(&mut w.dst, "{}:{} {}\n", fm.name,
541 line_number + 1, line));
545 let last_line_start = format!("{}:{} ", fm.name, lines[lines.len()-1]+1);
546 let hi = cm.lookup_char_pos(sp.hi);
547 // Span seems to use half-opened interval, so subtract 1
548 let skip = last_line_start.len() + hi.col.to_uint() - 1;
549 let mut s = String::new();
550 for _ in range(0, skip) {
555 print_maybe_styled(w,
557 term::attr::ForegroundColor(lvl.color()))
560 fn print_macro_backtrace(w: &mut EmitterWriter,
561 cm: &codemap::CodeMap,
563 -> io::IoResult<()> {
564 let cs = try!(cm.with_expn_info(sp.expn_id, |expn_info| match expn_info {
566 let ss = ei.callee.span.map_or(String::new(), |span| cm.span_to_string(span));
567 let (pre, post) = match ei.callee.format {
568 codemap::MacroAttribute => ("#[", "]"),
569 codemap::MacroBang => ("", "!")
571 try!(print_diagnostic(w, ss.as_slice(), Note,
572 format!("in expansion of {}{}{}", pre,
574 post).as_slice(), None));
575 let ss = cm.span_to_string(ei.call_site);
576 try!(print_diagnostic(w, ss.as_slice(), Note, "expansion site", None));
577 Ok(Some(ei.call_site))
581 cs.map_or(Ok(()), |call_site| print_macro_backtrace(w, cm, call_site))
584 pub fn expect<T>(diag: &SpanHandler, opt: Option<T>, msg: || -> String) -> T {
587 None => diag.handler().bug(msg().as_slice()),