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;
31 #[derive(Clone, Copy)]
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
44 fn span(self) -> Span {
46 FullSpan(s) | FileLine(s) => s
49 fn is_full_span(&self) -> bool {
51 &FullSpan(..) => true,
52 &FileLine(..) => false,
57 #[derive(Clone, Copy)]
58 pub enum ColorConfig {
65 fn emit(&mut self, cmsp: Option<(&codemap::CodeMap, Span)>,
66 msg: &str, code: Option<&str>, lvl: Level);
67 fn custom_emit(&mut self, cm: &codemap::CodeMap,
68 sp: RenderSpan, msg: &str, lvl: Level);
71 /// This structure is used to signify that a task has panicked with a fatal error
72 /// from the diagnostics. You can use this with the `Any` trait to figure out
73 /// how a rustc task died (if so desired).
75 pub struct FatalError;
77 /// Signifies that the compiler died with an explicit call to `.bug`
78 /// or `.span_bug` rather than a failed assertion, etc.
80 pub struct ExplicitBug;
82 /// A span-handler is like a handler but also
83 /// accepts span information for source-location
85 pub struct SpanHandler {
87 pub cm: codemap::CodeMap,
91 pub fn span_fatal(&self, sp: Span, msg: &str) -> ! {
92 self.handler.emit(Some((&self.cm, sp)), msg, Fatal);
95 pub fn span_err(&self, sp: Span, msg: &str) {
96 self.handler.emit(Some((&self.cm, sp)), msg, Error);
97 self.handler.bump_err_count();
99 pub fn span_err_with_code(&self, sp: Span, msg: &str, code: &str) {
100 self.handler.emit_with_code(Some((&self.cm, sp)), msg, code, Error);
101 self.handler.bump_err_count();
103 pub fn span_warn(&self, sp: Span, msg: &str) {
104 self.handler.emit(Some((&self.cm, sp)), msg, Warning);
106 pub fn span_warn_with_code(&self, sp: Span, msg: &str, code: &str) {
107 self.handler.emit_with_code(Some((&self.cm, sp)), msg, code, Warning);
109 pub fn span_note(&self, sp: Span, msg: &str) {
110 self.handler.emit(Some((&self.cm, sp)), msg, Note);
112 pub fn span_end_note(&self, sp: Span, msg: &str) {
113 self.handler.custom_emit(&self.cm, FullSpan(sp), msg, Note);
115 pub fn span_help(&self, sp: Span, msg: &str) {
116 self.handler.emit(Some((&self.cm, sp)), msg, Help);
118 pub fn fileline_note(&self, sp: Span, msg: &str) {
119 self.handler.custom_emit(&self.cm, FileLine(sp), msg, Note);
121 pub fn span_bug(&self, sp: Span, msg: &str) -> ! {
122 self.handler.emit(Some((&self.cm, sp)), msg, Bug);
125 pub fn span_unimpl(&self, sp: Span, msg: &str) -> ! {
126 self.span_bug(sp, format!("unimplemented {}", msg)[]);
128 pub fn handler<'a>(&'a self) -> &'a Handler {
133 /// A handler deals with errors; certain errors
134 /// (fatal, bug, unimpl) may cause immediate exit,
135 /// others log errors for later reporting.
137 err_count: Cell<uint>,
138 emit: RefCell<Box<Emitter + Send>>,
142 pub fn fatal(&self, msg: &str) -> ! {
143 self.emit.borrow_mut().emit(None, msg, None, Fatal);
146 pub fn err(&self, msg: &str) {
147 self.emit.borrow_mut().emit(None, msg, None, Error);
148 self.bump_err_count();
150 pub fn bump_err_count(&self) {
151 self.err_count.set(self.err_count.get() + 1u);
153 pub fn err_count(&self) -> uint {
156 pub fn has_errors(&self) -> bool {
157 self.err_count.get()> 0u
159 pub fn abort_if_errors(&self) {
161 match self.err_count.get() {
163 1u => s = "aborting due to previous error".to_string(),
165 s = format!("aborting due to {} previous errors",
166 self.err_count.get());
171 pub fn warn(&self, msg: &str) {
172 self.emit.borrow_mut().emit(None, msg, None, Warning);
174 pub fn note(&self, msg: &str) {
175 self.emit.borrow_mut().emit(None, msg, None, Note);
177 pub fn help(&self, msg: &str) {
178 self.emit.borrow_mut().emit(None, msg, None, Help);
180 pub fn bug(&self, msg: &str) -> ! {
181 self.emit.borrow_mut().emit(None, msg, None, Bug);
184 pub fn unimpl(&self, msg: &str) -> ! {
185 self.bug(format!("unimplemented {}", msg)[]);
188 cmsp: Option<(&codemap::CodeMap, Span)>,
191 self.emit.borrow_mut().emit(cmsp, msg, None, lvl);
193 pub fn emit_with_code(&self,
194 cmsp: Option<(&codemap::CodeMap, Span)>,
198 self.emit.borrow_mut().emit(cmsp, msg, Some(code), lvl);
200 pub fn custom_emit(&self, cm: &codemap::CodeMap,
201 sp: RenderSpan, msg: &str, lvl: Level) {
202 self.emit.borrow_mut().custom_emit(cm, sp, msg, lvl);
206 pub fn mk_span_handler(handler: Handler, cm: codemap::CodeMap) -> SpanHandler {
213 pub fn default_handler(color_config: ColorConfig,
214 registry: Option<diagnostics::registry::Registry>) -> Handler {
215 mk_handler(box EmitterWriter::stderr(color_config, registry))
218 pub fn mk_handler(e: Box<Emitter + Send>) -> Handler {
220 err_count: Cell::new(0),
221 emit: RefCell::new(e),
225 #[derive(Copy, PartialEq, Clone)]
235 impl fmt::Show for Level {
236 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
240 Bug => "error: internal compiler error".fmt(f),
241 Fatal | Error => "error".fmt(f),
242 Warning => "warning".fmt(f),
243 Note => "note".fmt(f),
244 Help => "help".fmt(f),
250 fn color(self) -> term::color::Color {
252 Bug | Fatal | Error => term::color::BRIGHT_RED,
253 Warning => term::color::BRIGHT_YELLOW,
254 Note => term::color::BRIGHT_GREEN,
255 Help => term::color::BRIGHT_CYAN,
260 fn print_maybe_styled(w: &mut EmitterWriter,
262 color: term::attr::Attr) -> io::IoResult<()> {
264 Terminal(ref mut t) => {
266 // If `msg` ends in a newline, we need to reset the color before
267 // the newline. We're making the assumption that we end up writing
268 // to a `LineBufferedWriter`, which means that emitting the reset
269 // after the newline ends up buffering the reset until we print
270 // another line or exit. Buffering the reset is a problem if we're
271 // sharing the terminal with any other programs (e.g. other rustc
272 // instances via `make -jN`).
274 // Note that if `msg` contains any internal newlines, this will
275 // result in the `LineBufferedWriter` flushing twice instead of
276 // once, which still leaves the opportunity for interleaved output
277 // to be miscolored. We assume this is rare enough that we don't
278 // have to worry about it.
279 if msg.ends_with("\n") {
280 try!(t.write_str(msg[0..msg.len()-1]));
282 try!(t.write_str("\n"));
284 try!(t.write_str(msg));
295 fn print_diagnostic(dst: &mut EmitterWriter, topic: &str, lvl: Level,
296 msg: &str, code: Option<&str>) -> io::IoResult<()> {
297 if !topic.is_empty() {
298 try!(write!(&mut dst.dst, "{} ", topic));
301 try!(print_maybe_styled(dst,
302 format!("{}: ", lvl.to_string())[],
303 term::attr::ForegroundColor(lvl.color())));
304 try!(print_maybe_styled(dst,
305 format!("{}", msg)[],
310 let style = term::attr::ForegroundColor(term::color::BRIGHT_MAGENTA);
311 try!(print_maybe_styled(dst, format!(" [{}]", code.clone())[], style));
315 try!(dst.dst.write_char('\n'));
319 pub struct EmitterWriter {
321 registry: Option<diagnostics::registry::Registry>
325 Terminal(Box<term::Terminal<WriterWrapper> + Send>),
326 Raw(Box<Writer + Send>),
330 pub fn stderr(color_config: ColorConfig,
331 registry: Option<diagnostics::registry::Registry>) -> EmitterWriter {
332 let stderr = io::stderr();
334 let use_color = match color_config {
337 Auto => stderr.get_ref().isatty()
341 let dst = match term::stderr() {
342 Some(t) => Terminal(t),
343 None => Raw(box stderr),
345 EmitterWriter { dst: dst, registry: registry }
347 EmitterWriter { dst: Raw(box stderr), registry: registry }
351 pub fn new(dst: Box<Writer + Send>,
352 registry: Option<diagnostics::registry::Registry>) -> EmitterWriter {
353 EmitterWriter { dst: Raw(dst), registry: registry }
357 impl Writer for Destination {
358 fn write(&mut self, bytes: &[u8]) -> io::IoResult<()> {
360 Terminal(ref mut t) => t.write(bytes),
361 Raw(ref mut w) => w.write(bytes),
366 impl Emitter for EmitterWriter {
368 cmsp: Option<(&codemap::CodeMap, Span)>,
369 msg: &str, code: Option<&str>, lvl: Level) {
370 let error = match cmsp {
371 Some((cm, sp)) => emit(self, cm, FullSpan(sp), msg, code, lvl, false),
372 None => print_diagnostic(self, "", lvl, msg, code),
377 Err(e) => panic!("failed to print diagnostics: {}", e),
381 fn custom_emit(&mut self, cm: &codemap::CodeMap,
382 sp: RenderSpan, msg: &str, lvl: Level) {
383 match emit(self, cm, sp, msg, None, lvl, true) {
385 Err(e) => panic!("failed to print diagnostics: {}", e),
390 fn emit(dst: &mut EmitterWriter, cm: &codemap::CodeMap, rsp: RenderSpan,
391 msg: &str, code: Option<&str>, lvl: Level, custom: bool) -> io::IoResult<()> {
393 let ss = cm.span_to_string(sp);
394 let lines = cm.span_to_lines(sp);
396 // we want to tell compiletest/runtest to look at the last line of the
397 // span (since `custom_highlight_lines` displays an arrow to the end of
399 let span_end = Span { lo: sp.hi, hi: sp.hi, expn_id: sp.expn_id};
400 let ses = cm.span_to_string(span_end);
401 try!(print_diagnostic(dst, ses[], lvl, msg, code));
402 if rsp.is_full_span() {
403 try!(custom_highlight_lines(dst, cm, sp, lvl, lines));
406 try!(print_diagnostic(dst, ss[], lvl, msg, code));
407 if rsp.is_full_span() {
408 try!(highlight_lines(dst, cm, sp, lvl, lines));
411 try!(print_macro_backtrace(dst, cm, sp));
414 match dst.registry.as_ref().and_then(|registry| registry.find_description(code)) {
416 try!(print_diagnostic(dst, ss[], Help,
417 format!("pass `--explain {}` to see a detailed \
418 explanation", code)[], None));
427 fn highlight_lines(err: &mut EmitterWriter,
428 cm: &codemap::CodeMap,
431 lines: codemap::FileLines) -> io::IoResult<()> {
432 let fm = &*lines.file;
434 let mut elided = false;
435 let mut display_lines = lines.lines[];
436 if display_lines.len() > MAX_LINES {
437 display_lines = display_lines[0u..MAX_LINES];
440 // Print the offending lines
441 for &line_number in display_lines.iter() {
442 if let Some(line) = fm.get_line(line_number) {
443 try!(write!(&mut err.dst, "{}:{} {}\n", fm.name,
444 line_number + 1, line));
448 let last_line = display_lines[display_lines.len() - 1u];
449 let s = format!("{}:{} ", fm.name, last_line + 1u);
450 try!(write!(&mut err.dst, "{0:1$}...\n", "", s.len()));
454 // If there's one line at fault we can easily point to the problem
455 if lines.lines.len() == 1u {
456 let lo = cm.lookup_char_pos(sp.lo);
458 let mut num = (lines.lines[0] + 1u) / 10u;
460 // how many digits must be indent past?
461 while num > 0u { num /= 10u; digits += 1u; }
463 // indent past |name:## | and the 0-offset column location
464 let left = fm.name.len() + digits + lo.col.to_uint() + 3u;
465 let mut s = String::new();
466 // Skip is the number of characters we need to skip because they are
467 // part of the 'filename:line ' part of the previous line.
468 let skip = fm.name.len() + digits + 3u;
469 for _ in range(0, skip) {
472 if let Some(orig) = fm.get_line(lines.lines[0]) {
473 for pos in range(0u, left - skip) {
474 let cur_char = orig.as_bytes()[pos] as char;
475 // Whenever a tab occurs on the previous line, we insert one on
476 // the error-point-squiggly-line as well (instead of a space).
477 // That way the squiggly line will usually appear in the correct
480 '\t' => s.push('\t'),
486 try!(write!(&mut err.dst, "{}", s));
487 let mut s = String::from_str("^");
488 let hi = cm.lookup_char_pos(sp.hi);
489 if hi.col != lo.col {
490 // the ^ already takes up one space
491 let num_squigglies = hi.col.to_uint() - lo.col.to_uint() - 1u;
492 for _ in range(0, num_squigglies) {
496 try!(print_maybe_styled(err,
497 format!("{}\n", s)[],
498 term::attr::ForegroundColor(lvl.color())));
503 /// Here are the differences between this and the normal `highlight_lines`:
504 /// `custom_highlight_lines` will always put arrow on the last byte of the
505 /// span (instead of the first byte). Also, when the span is too long (more
506 /// than 6 lines), `custom_highlight_lines` will print the first line, then
507 /// dot dot dot, then last line, whereas `highlight_lines` prints the first
509 fn custom_highlight_lines(w: &mut EmitterWriter,
510 cm: &codemap::CodeMap,
513 lines: codemap::FileLines)
514 -> io::IoResult<()> {
515 let fm = &*lines.file;
517 let lines = lines.lines[];
518 if lines.len() > MAX_LINES {
519 if let Some(line) = fm.get_line(lines[0]) {
520 try!(write!(&mut w.dst, "{}:{} {}\n", fm.name,
521 lines[0] + 1, line));
523 try!(write!(&mut w.dst, "...\n"));
524 let last_line_number = lines[lines.len() - 1];
525 if let Some(last_line) = fm.get_line(last_line_number) {
526 try!(write!(&mut w.dst, "{}:{} {}\n", fm.name,
527 last_line_number + 1, last_line));
530 for &line_number in lines.iter() {
531 if let Some(line) = fm.get_line(line_number) {
532 try!(write!(&mut w.dst, "{}:{} {}\n", fm.name,
533 line_number + 1, line));
537 let last_line_start = format!("{}:{} ", fm.name, lines[lines.len()-1]+1);
538 let hi = cm.lookup_char_pos(sp.hi);
539 // Span seems to use half-opened interval, so subtract 1
540 let skip = last_line_start.len() + hi.col.to_uint() - 1;
541 let mut s = String::new();
542 for _ in range(0, skip) {
547 print_maybe_styled(w,
549 term::attr::ForegroundColor(lvl.color()))
552 fn print_macro_backtrace(w: &mut EmitterWriter,
553 cm: &codemap::CodeMap,
555 -> io::IoResult<()> {
556 let cs = try!(cm.with_expn_info(sp.expn_id, |expn_info| match expn_info {
558 let ss = ei.callee.span.map_or(String::new(), |span| cm.span_to_string(span));
559 let (pre, post) = match ei.callee.format {
560 codemap::MacroAttribute => ("#[", "]"),
561 codemap::MacroBang => ("", "!")
563 try!(print_diagnostic(w, ss[], Note,
564 format!("in expansion of {}{}{}", pre,
567 let ss = cm.span_to_string(ei.call_site);
568 try!(print_diagnostic(w, ss[], Note, "expansion site", None));
569 Ok(Some(ei.call_site))
573 cs.map_or(Ok(()), |call_site| print_macro_backtrace(w, cm, call_site))
576 pub fn expect<T, M>(diag: &SpanHandler, opt: Option<T>, msg: M) -> T where
577 M: FnOnce() -> String,
581 None => diag.handler().bug(msg()[]),