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.
13 use codemap::{Pos, Span};
16 use std::cell::{RefCell, Cell};
20 use std::string::String;
21 use term::WriterWrapper;
24 // maximum number of lines we will print for each error; arbitrary.
25 static MAX_LINES: uint = 6u;
29 /// A FullSpan renders with both with an initial line for the
30 /// message, prefixed by file:linenum, followed by a summary of
31 /// the source code covered by the span.
34 /// A FileLine renders with just a line for the message prefixed
40 fn span(self) -> Span {
42 FullSpan(s) | FileLine(s) => s
45 fn is_full_span(&self) -> bool {
47 &FullSpan(..) => true,
48 &FileLine(..) => false,
54 pub enum ColorConfig {
61 fn emit(&mut self, cmsp: Option<(&codemap::CodeMap, Span)>,
62 msg: &str, lvl: Level);
63 fn custom_emit(&mut self, cm: &codemap::CodeMap,
64 sp: RenderSpan, msg: &str, lvl: Level);
67 /// This structure is used to signify that a task has failed with a fatal error
68 /// from the diagnostics. You can use this with the `Any` trait to figure out
69 /// how a rustc task died (if so desired).
70 pub struct FatalError;
72 /// Signifies that the compiler died with an explicit call to `.bug`
73 /// or `.span_bug` rather than a failed assertion, etc.
74 pub struct ExplicitBug;
76 // a span-handler is like a handler but also
77 // accepts span information for source-location
79 pub struct SpanHandler {
81 pub cm: codemap::CodeMap,
85 pub fn span_fatal(&self, sp: Span, msg: &str) -> ! {
86 self.handler.emit(Some((&self.cm, sp)), msg, Fatal);
89 pub fn span_err(&self, sp: Span, msg: &str) {
90 self.handler.emit(Some((&self.cm, sp)), msg, Error);
91 self.handler.bump_err_count();
93 pub fn span_warn(&self, sp: Span, msg: &str) {
94 self.handler.emit(Some((&self.cm, sp)), msg, Warning);
96 pub fn span_note(&self, sp: Span, msg: &str) {
97 self.handler.emit(Some((&self.cm, sp)), msg, Note);
99 pub fn span_end_note(&self, sp: Span, msg: &str) {
100 self.handler.custom_emit(&self.cm, FullSpan(sp), msg, Note);
102 pub fn fileline_note(&self, sp: Span, msg: &str) {
103 self.handler.custom_emit(&self.cm, FileLine(sp), msg, Note);
105 pub fn span_bug(&self, sp: Span, msg: &str) -> ! {
106 self.handler.emit(Some((&self.cm, sp)), msg, Bug);
109 pub fn span_unimpl(&self, sp: Span, msg: &str) -> ! {
110 self.span_bug(sp, format!("unimplemented {}", msg).as_slice());
112 pub fn handler<'a>(&'a self) -> &'a Handler {
117 // a handler deals with errors; certain errors
118 // (fatal, bug, unimpl) may cause immediate exit,
119 // others log errors for later reporting.
121 err_count: Cell<uint>,
122 emit: RefCell<Box<Emitter + Send>>,
126 pub fn fatal(&self, msg: &str) -> ! {
127 self.emit.borrow_mut().emit(None, msg, Fatal);
130 pub fn err(&self, msg: &str) {
131 self.emit.borrow_mut().emit(None, msg, Error);
132 self.bump_err_count();
134 pub fn bump_err_count(&self) {
135 self.err_count.set(self.err_count.get() + 1u);
137 pub fn err_count(&self) -> uint {
140 pub fn has_errors(&self) -> bool {
141 self.err_count.get()> 0u
143 pub fn abort_if_errors(&self) {
145 match self.err_count.get() {
147 1u => s = "aborting due to previous error".to_string(),
149 s = format!("aborting due to {} previous errors",
150 self.err_count.get());
153 self.fatal(s.as_slice());
155 pub fn warn(&self, msg: &str) {
156 self.emit.borrow_mut().emit(None, msg, Warning);
158 pub fn note(&self, msg: &str) {
159 self.emit.borrow_mut().emit(None, msg, Note);
161 pub fn bug(&self, msg: &str) -> ! {
162 self.emit.borrow_mut().emit(None, msg, Bug);
165 pub fn unimpl(&self, msg: &str) -> ! {
166 self.bug(format!("unimplemented {}", msg).as_slice());
169 cmsp: Option<(&codemap::CodeMap, Span)>,
172 self.emit.borrow_mut().emit(cmsp, msg, lvl);
174 pub fn custom_emit(&self, cm: &codemap::CodeMap,
175 sp: RenderSpan, msg: &str, lvl: Level) {
176 self.emit.borrow_mut().custom_emit(cm, sp, msg, lvl);
180 pub fn mk_span_handler(handler: Handler, cm: codemap::CodeMap) -> SpanHandler {
187 pub fn default_handler(color_config: ColorConfig) -> Handler {
188 mk_handler(box EmitterWriter::stderr(color_config))
191 pub fn mk_handler(e: Box<Emitter + Send>) -> Handler {
193 err_count: Cell::new(0),
194 emit: RefCell::new(e),
198 #[deriving(PartialEq)]
207 impl fmt::Show for Level {
208 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
212 Bug => "error: internal compiler error".fmt(f),
213 Fatal | Error => "error".fmt(f),
214 Warning => "warning".fmt(f),
215 Note => "note".fmt(f),
221 fn color(self) -> term::color::Color {
223 Bug | Fatal | Error => term::color::BRIGHT_RED,
224 Warning => term::color::BRIGHT_YELLOW,
225 Note => term::color::BRIGHT_GREEN
230 fn print_maybe_styled(w: &mut EmitterWriter,
232 color: term::attr::Attr) -> io::IoResult<()> {
234 Terminal(ref mut t) => {
236 // If `msg` ends in a newline, we need to reset the color before
237 // the newline. We're making the assumption that we end up writing
238 // to a `LineBufferedWriter`, which means that emitting the reset
239 // after the newline ends up buffering the reset until we print
240 // another line or exit. Buffering the reset is a problem if we're
241 // sharing the terminal with any other programs (e.g. other rustc
242 // instances via `make -jN`).
244 // Note that if `msg` contains any internal newlines, this will
245 // result in the `LineBufferedWriter` flushing twice instead of
246 // once, which still leaves the opportunity for interleaved output
247 // to be miscolored. We assume this is rare enough that we don't
248 // have to worry about it.
249 if msg.ends_with("\n") {
250 try!(t.write_str(msg.slice_to(msg.len()-1)));
252 try!(t.write_str("\n"));
254 try!(t.write_str(msg));
265 fn print_diagnostic(dst: &mut EmitterWriter,
266 topic: &str, lvl: Level, msg: &str) -> io::IoResult<()> {
267 if !topic.is_empty() {
268 try!(write!(&mut dst.dst, "{} ", topic));
271 try!(print_maybe_styled(dst,
272 format!("{}: ", lvl.to_str()).as_slice(),
273 term::attr::ForegroundColor(lvl.color())));
274 try!(print_maybe_styled(dst,
275 format!("{}\n", msg).as_slice(),
280 pub struct EmitterWriter {
285 Terminal(Box<term::Terminal<WriterWrapper> + Send>),
286 Raw(Box<Writer + Send>),
290 pub fn stderr(color_config: ColorConfig) -> EmitterWriter {
291 let stderr = io::stderr();
293 let use_color = match color_config {
296 Auto => stderr.get_ref().isatty()
300 let dst = match term::stderr() {
301 Some(t) => Terminal(t),
302 None => Raw(box stderr),
304 EmitterWriter { dst: dst }
306 EmitterWriter { dst: Raw(box stderr) }
310 pub fn new(dst: Box<Writer + Send>) -> EmitterWriter {
311 EmitterWriter { dst: Raw(dst) }
315 impl Writer for Destination {
316 fn write(&mut self, bytes: &[u8]) -> io::IoResult<()> {
318 Terminal(ref mut t) => t.write(bytes),
319 Raw(ref mut w) => w.write(bytes),
324 impl Emitter for EmitterWriter {
326 cmsp: Option<(&codemap::CodeMap, Span)>,
329 let error = match cmsp {
330 Some((cm, sp)) => emit(self, cm, FullSpan(sp), msg, lvl, false),
331 None => print_diagnostic(self, "", lvl, msg),
336 Err(e) => fail!("failed to print diagnostics: {}", e),
340 fn custom_emit(&mut self, cm: &codemap::CodeMap,
341 sp: RenderSpan, msg: &str, lvl: Level) {
342 match emit(self, cm, sp, msg, lvl, true) {
344 Err(e) => fail!("failed to print diagnostics: {}", e),
349 fn emit(dst: &mut EmitterWriter, cm: &codemap::CodeMap, rsp: RenderSpan,
350 msg: &str, lvl: Level, custom: bool) -> io::IoResult<()> {
352 let ss = cm.span_to_str(sp);
353 let lines = cm.span_to_lines(sp);
355 // we want to tell compiletest/runtest to look at the last line of the
356 // span (since `custom_highlight_lines` displays an arrow to the end of
358 let span_end = Span { lo: sp.hi, hi: sp.hi, expn_info: sp.expn_info};
359 let ses = cm.span_to_str(span_end);
360 try!(print_diagnostic(dst, ses.as_slice(), lvl, msg));
361 if rsp.is_full_span() {
362 try!(custom_highlight_lines(dst, cm, sp, lvl, lines));
365 try!(print_diagnostic(dst, ss.as_slice(), lvl, msg));
366 if rsp.is_full_span() {
367 try!(highlight_lines(dst, cm, sp, lvl, lines));
370 print_macro_backtrace(dst, cm, sp)
373 fn highlight_lines(err: &mut EmitterWriter,
374 cm: &codemap::CodeMap,
377 lines: codemap::FileLines) -> io::IoResult<()> {
378 let fm = &*lines.file;
380 let mut elided = false;
381 let mut display_lines = lines.lines.as_slice();
382 if display_lines.len() > MAX_LINES {
383 display_lines = display_lines.slice(0u, MAX_LINES);
386 // Print the offending lines
387 for line in display_lines.iter() {
388 try!(write!(&mut err.dst, "{}:{} {}\n", fm.name, *line + 1,
389 fm.get_line(*line as int)));
392 let last_line = display_lines[display_lines.len() - 1u];
393 let s = format!("{}:{} ", fm.name, last_line + 1u);
394 try!(write!(&mut err.dst, "{0:1$}...\n", "", s.len()));
398 // If there's one line at fault we can easily point to the problem
399 if lines.lines.len() == 1u {
400 let lo = cm.lookup_char_pos(sp.lo);
402 let mut num = (*lines.lines.get(0) + 1u) / 10u;
404 // how many digits must be indent past?
405 while num > 0u { num /= 10u; digits += 1u; }
407 // indent past |name:## | and the 0-offset column location
408 let left = fm.name.len() + digits + lo.col.to_uint() + 3u;
409 let mut s = String::new();
410 // Skip is the number of characters we need to skip because they are
411 // part of the 'filename:line ' part of the previous line.
412 let skip = fm.name.len() + digits + 3u;
413 for _ in range(0, skip) {
416 let orig = fm.get_line(*lines.lines.get(0) as int);
417 for pos in range(0u, left-skip) {
418 let cur_char = orig.as_bytes()[pos] as char;
419 // Whenever a tab occurs on the previous line, we insert one on
420 // the error-point-squiggly-line as well (instead of a space).
421 // That way the squiggly line will usually appear in the correct
424 '\t' => s.push_char('\t'),
425 _ => s.push_char(' '),
428 try!(write!(&mut err.dst, "{}", s));
429 let mut s = String::from_str("^");
430 let hi = cm.lookup_char_pos(sp.hi);
431 if hi.col != lo.col {
432 // the ^ already takes up one space
433 let num_squigglies = hi.col.to_uint()-lo.col.to_uint()-1u;
434 for _ in range(0, num_squigglies) {
438 try!(print_maybe_styled(err,
439 format!("{}\n", s).as_slice(),
440 term::attr::ForegroundColor(lvl.color())));
445 // Here are the differences between this and the normal `highlight_lines`:
446 // `custom_highlight_lines` will always put arrow on the last byte of the
447 // span (instead of the first byte). Also, when the span is too long (more
448 // than 6 lines), `custom_highlight_lines` will print the first line, then
449 // dot dot dot, then last line, whereas `highlight_lines` prints the first
451 fn custom_highlight_lines(w: &mut EmitterWriter,
452 cm: &codemap::CodeMap,
455 lines: codemap::FileLines)
456 -> io::IoResult<()> {
457 let fm = &*lines.file;
459 let lines = lines.lines.as_slice();
460 if lines.len() > MAX_LINES {
461 try!(write!(&mut w.dst, "{}:{} {}\n", fm.name,
462 lines[0] + 1, fm.get_line(lines[0] as int)));
463 try!(write!(&mut w.dst, "...\n"));
464 let last_line = lines[lines.len()-1];
465 try!(write!(&mut w.dst, "{}:{} {}\n", fm.name,
466 last_line + 1, fm.get_line(last_line as int)));
468 for line in lines.iter() {
469 try!(write!(&mut w.dst, "{}:{} {}\n", fm.name,
470 *line + 1, fm.get_line(*line as int)));
473 let last_line_start = format!("{}:{} ", fm.name, lines[lines.len()-1]+1);
474 let hi = cm.lookup_char_pos(sp.hi);
475 // Span seems to use half-opened interval, so subtract 1
476 let skip = last_line_start.len() + hi.col.to_uint() - 1;
477 let mut s = String::new();
478 for _ in range(0, skip) {
483 print_maybe_styled(w,
485 term::attr::ForegroundColor(lvl.color()))
488 fn print_macro_backtrace(w: &mut EmitterWriter,
489 cm: &codemap::CodeMap,
491 -> io::IoResult<()> {
492 for ei in sp.expn_info.iter() {
496 .map_or("".to_string(), |span| cm.span_to_str(*span));
497 let (pre, post) = match ei.callee.format {
498 codemap::MacroAttribute => ("#[", "]"),
499 codemap::MacroBang => ("", "!")
501 try!(print_diagnostic(w, ss.as_slice(), Note,
502 format!("in expansion of {}{}{}", pre,
505 let ss = cm.span_to_str(ei.call_site);
506 try!(print_diagnostic(w, ss.as_slice(), Note, "expansion site"));
507 try!(print_macro_backtrace(w, cm, ei.call_site));
512 pub fn expect<T:Clone>(diag: &SpanHandler, opt: Option<T>, msg: || -> String)
515 Some(ref t) => (*t).clone(),
516 None => diag.handler().bug(msg().as_slice()),