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;
23 // maximum number of lines we will print for each error; arbitrary.
24 static MAX_LINES: uint = 6u;
28 /// A FullSpan renders with both with an initial line for the
29 /// message, prefixed by file:linenum, followed by a summary of
30 /// the source code covered by the span.
33 /// A FileLine renders with just a line for the message prefixed
39 fn span(self) -> Span {
41 FullSpan(s) | FileLine(s) => s
44 fn is_full_span(&self) -> bool {
46 &FullSpan(..) => true,
47 &FileLine(..) => false,
53 pub enum ColorConfig {
60 fn emit(&mut self, cmsp: Option<(&codemap::CodeMap, Span)>,
61 msg: &str, lvl: Level);
62 fn custom_emit(&mut self, cm: &codemap::CodeMap,
63 sp: RenderSpan, msg: &str, lvl: Level);
66 /// This structure is used to signify that a task has failed with a fatal error
67 /// from the diagnostics. You can use this with the `Any` trait to figure out
68 /// how a rustc task died (if so desired).
69 pub struct FatalError;
71 /// Signifies that the compiler died with an explicit call to `.bug`
72 /// or `.span_bug` rather than a failed assertion, etc.
73 pub struct ExplicitBug;
75 // a span-handler is like a handler but also
76 // accepts span information for source-location
78 pub struct SpanHandler {
80 pub cm: codemap::CodeMap,
84 pub fn span_fatal(&self, sp: Span, msg: &str) -> ! {
85 self.handler.emit(Some((&self.cm, sp)), msg, Fatal);
88 pub fn span_err(&self, sp: Span, msg: &str) {
89 self.handler.emit(Some((&self.cm, sp)), msg, Error);
90 self.handler.bump_err_count();
92 pub fn span_warn(&self, sp: Span, msg: &str) {
93 self.handler.emit(Some((&self.cm, sp)), msg, Warning);
95 pub fn span_note(&self, sp: Span, msg: &str) {
96 self.handler.emit(Some((&self.cm, sp)), msg, Note);
98 pub fn span_end_note(&self, sp: Span, msg: &str) {
99 self.handler.custom_emit(&self.cm, FullSpan(sp), msg, Note);
101 pub fn fileline_note(&self, sp: Span, msg: &str) {
102 self.handler.custom_emit(&self.cm, FileLine(sp), msg, Note);
104 pub fn span_bug(&self, sp: Span, msg: &str) -> ! {
105 self.handler.emit(Some((&self.cm, sp)), msg, Bug);
108 pub fn span_unimpl(&self, sp: Span, msg: &str) -> ! {
109 self.span_bug(sp, format!("unimplemented {}", msg).as_slice());
111 pub fn handler<'a>(&'a self) -> &'a Handler {
116 // a handler deals with errors; certain errors
117 // (fatal, bug, unimpl) may cause immediate exit,
118 // others log errors for later reporting.
120 err_count: Cell<uint>,
121 emit: RefCell<Box<Emitter:Send>>,
125 pub fn fatal(&self, msg: &str) -> ! {
126 self.emit.borrow_mut().emit(None, msg, Fatal);
129 pub fn err(&self, msg: &str) {
130 self.emit.borrow_mut().emit(None, msg, Error);
131 self.bump_err_count();
133 pub fn bump_err_count(&self) {
134 self.err_count.set(self.err_count.get() + 1u);
136 pub fn err_count(&self) -> uint {
139 pub fn has_errors(&self) -> bool {
140 self.err_count.get()> 0u
142 pub fn abort_if_errors(&self) {
144 match self.err_count.get() {
146 1u => s = "aborting due to previous error".to_string(),
148 s = format!("aborting due to {} previous errors",
149 self.err_count.get());
152 self.fatal(s.as_slice());
154 pub fn warn(&self, msg: &str) {
155 self.emit.borrow_mut().emit(None, msg, Warning);
157 pub fn note(&self, msg: &str) {
158 self.emit.borrow_mut().emit(None, msg, Note);
160 pub fn bug(&self, msg: &str) -> ! {
161 self.emit.borrow_mut().emit(None, msg, Bug);
164 pub fn unimpl(&self, msg: &str) -> ! {
165 self.bug(format!("unimplemented {}", msg).as_slice());
168 cmsp: Option<(&codemap::CodeMap, Span)>,
171 self.emit.borrow_mut().emit(cmsp, msg, lvl);
173 pub fn custom_emit(&self, cm: &codemap::CodeMap,
174 sp: RenderSpan, msg: &str, lvl: Level) {
175 self.emit.borrow_mut().custom_emit(cm, sp, msg, lvl);
179 pub fn mk_span_handler(handler: Handler, cm: codemap::CodeMap) -> SpanHandler {
186 pub fn default_handler(color_config: ColorConfig) -> Handler {
187 mk_handler(box EmitterWriter::stderr(color_config))
190 pub fn mk_handler(e: Box<Emitter:Send>) -> Handler {
192 err_count: Cell::new(0),
193 emit: RefCell::new(e),
197 #[deriving(PartialEq)]
206 impl fmt::Show for Level {
207 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
211 Bug => "error: internal compiler error".fmt(f),
212 Fatal | Error => "error".fmt(f),
213 Warning => "warning".fmt(f),
214 Note => "note".fmt(f),
220 fn color(self) -> term::color::Color {
222 Bug | Fatal | Error => term::color::BRIGHT_RED,
223 Warning => term::color::BRIGHT_YELLOW,
224 Note => term::color::BRIGHT_GREEN
229 fn print_maybe_styled(w: &mut EmitterWriter,
231 color: term::attr::Attr) -> io::IoResult<()> {
233 Terminal(ref mut t) => {
235 // If `msg` ends in a newline, we need to reset the color before
236 // the newline. We're making the assumption that we end up writing
237 // to a `LineBufferedWriter`, which means that emitting the reset
238 // after the newline ends up buffering the reset until we print
239 // another line or exit. Buffering the reset is a problem if we're
240 // sharing the terminal with any other programs (e.g. other rustc
241 // instances via `make -jN`).
243 // Note that if `msg` contains any internal newlines, this will
244 // result in the `LineBufferedWriter` flushing twice instead of
245 // once, which still leaves the opportunity for interleaved output
246 // to be miscolored. We assume this is rare enough that we don't
247 // have to worry about it.
248 if msg.ends_with("\n") {
249 try!(t.write_str(msg.slice_to(msg.len()-1)));
251 try!(t.write_str("\n"));
253 try!(t.write_str(msg));
264 fn print_diagnostic(dst: &mut EmitterWriter,
265 topic: &str, lvl: Level, msg: &str) -> io::IoResult<()> {
266 if !topic.is_empty() {
267 try!(write!(&mut dst.dst, "{} ", topic));
270 try!(print_maybe_styled(dst,
271 format!("{}: ", lvl.to_str()).as_slice(),
272 term::attr::ForegroundColor(lvl.color())));
273 try!(print_maybe_styled(dst,
274 format!("{}\n", msg).as_slice(),
279 pub struct EmitterWriter {
284 Terminal(Box<term::Terminal<Box<Writer:Send>>:Send>),
285 Raw(Box<Writer:Send>),
289 pub fn stderr(color_config: ColorConfig) -> EmitterWriter {
290 let stderr = io::stderr();
292 let use_color = match color_config {
295 Auto => stderr.get_ref().isatty()
299 let dst = match term::stderr() {
300 Some(t) => Terminal(t),
301 None => Raw(box stderr),
303 EmitterWriter { dst: dst }
305 EmitterWriter { dst: Raw(box stderr) }
309 pub fn new(dst: Box<Writer:Send>) -> EmitterWriter {
310 EmitterWriter { dst: Raw(dst) }
314 impl Writer for Destination {
315 fn write(&mut self, bytes: &[u8]) -> io::IoResult<()> {
317 Terminal(ref mut t) => t.write(bytes),
318 Raw(ref mut w) => w.write(bytes),
323 impl Emitter for EmitterWriter {
325 cmsp: Option<(&codemap::CodeMap, Span)>,
328 let error = match cmsp {
329 Some((cm, sp)) => emit(self, cm, FullSpan(sp), msg, lvl, false),
330 None => print_diagnostic(self, "", lvl, msg),
335 Err(e) => fail!("failed to print diagnostics: {}", e),
339 fn custom_emit(&mut self, cm: &codemap::CodeMap,
340 sp: RenderSpan, msg: &str, lvl: Level) {
341 match emit(self, cm, sp, msg, lvl, true) {
343 Err(e) => fail!("failed to print diagnostics: {}", e),
348 fn emit(dst: &mut EmitterWriter, cm: &codemap::CodeMap, rsp: RenderSpan,
349 msg: &str, lvl: Level, custom: bool) -> io::IoResult<()> {
351 let ss = cm.span_to_str(sp);
352 let lines = cm.span_to_lines(sp);
354 // we want to tell compiletest/runtest to look at the last line of the
355 // span (since `custom_highlight_lines` displays an arrow to the end of
357 let span_end = Span { lo: sp.hi, hi: sp.hi, expn_info: sp.expn_info};
358 let ses = cm.span_to_str(span_end);
359 try!(print_diagnostic(dst, ses.as_slice(), lvl, msg));
360 if rsp.is_full_span() {
361 try!(custom_highlight_lines(dst, cm, sp, lvl, lines));
364 try!(print_diagnostic(dst, ss.as_slice(), lvl, msg));
365 if rsp.is_full_span() {
366 try!(highlight_lines(dst, cm, sp, lvl, lines));
369 print_macro_backtrace(dst, cm, sp)
372 fn highlight_lines(err: &mut EmitterWriter,
373 cm: &codemap::CodeMap,
376 lines: codemap::FileLines) -> io::IoResult<()> {
377 let fm = &*lines.file;
379 let mut elided = false;
380 let mut display_lines = lines.lines.as_slice();
381 if display_lines.len() > MAX_LINES {
382 display_lines = display_lines.slice(0u, MAX_LINES);
385 // Print the offending lines
386 for line in display_lines.iter() {
387 try!(write!(&mut err.dst, "{}:{} {}\n", fm.name, *line + 1,
388 fm.get_line(*line as int)));
391 let last_line = display_lines[display_lines.len() - 1u];
392 let s = format!("{}:{} ", fm.name, last_line + 1u);
393 try!(write!(&mut err.dst, "{0:1$}...\n", "", s.len()));
397 // If there's one line at fault we can easily point to the problem
398 if lines.lines.len() == 1u {
399 let lo = cm.lookup_char_pos(sp.lo);
401 let mut num = (*lines.lines.get(0) + 1u) / 10u;
403 // how many digits must be indent past?
404 while num > 0u { num /= 10u; digits += 1u; }
406 // indent past |name:## | and the 0-offset column location
407 let left = fm.name.len() + digits + lo.col.to_uint() + 3u;
408 let mut s = String::new();
409 // Skip is the number of characters we need to skip because they are
410 // part of the 'filename:line ' part of the previous line.
411 let skip = fm.name.len() + digits + 3u;
412 for _ in range(0, skip) {
415 let orig = fm.get_line(*lines.lines.get(0) as int);
416 for pos in range(0u, left-skip) {
417 let cur_char = orig.as_slice()[pos] as char;
418 // Whenever a tab occurs on the previous line, we insert one on
419 // the error-point-squiggly-line as well (instead of a space).
420 // That way the squiggly line will usually appear in the correct
423 '\t' => s.push_char('\t'),
424 _ => s.push_char(' '),
427 try!(write!(&mut err.dst, "{}", s));
428 let mut s = String::from_str("^");
429 let hi = cm.lookup_char_pos(sp.hi);
430 if hi.col != lo.col {
431 // the ^ already takes up one space
432 let num_squigglies = hi.col.to_uint()-lo.col.to_uint()-1u;
433 for _ in range(0, num_squigglies) {
437 try!(print_maybe_styled(err,
438 format!("{}\n", s).as_slice(),
439 term::attr::ForegroundColor(lvl.color())));
444 // Here are the differences between this and the normal `highlight_lines`:
445 // `custom_highlight_lines` will always put arrow on the last byte of the
446 // span (instead of the first byte). Also, when the span is too long (more
447 // than 6 lines), `custom_highlight_lines` will print the first line, then
448 // dot dot dot, then last line, whereas `highlight_lines` prints the first
450 fn custom_highlight_lines(w: &mut EmitterWriter,
451 cm: &codemap::CodeMap,
454 lines: codemap::FileLines)
455 -> io::IoResult<()> {
456 let fm = &*lines.file;
458 let lines = lines.lines.as_slice();
459 if lines.len() > MAX_LINES {
460 try!(write!(&mut w.dst, "{}:{} {}\n", fm.name,
461 lines[0] + 1, fm.get_line(lines[0] as int)));
462 try!(write!(&mut w.dst, "...\n"));
463 let last_line = lines[lines.len()-1];
464 try!(write!(&mut w.dst, "{}:{} {}\n", fm.name,
465 last_line + 1, fm.get_line(last_line as int)));
467 for line in lines.iter() {
468 try!(write!(&mut w.dst, "{}:{} {}\n", fm.name,
469 *line + 1, fm.get_line(*line as int)));
472 let last_line_start = format!("{}:{} ", fm.name, lines[lines.len()-1]+1);
473 let hi = cm.lookup_char_pos(sp.hi);
474 // Span seems to use half-opened interval, so subtract 1
475 let skip = last_line_start.len() + hi.col.to_uint() - 1;
476 let mut s = String::new();
477 for _ in range(0, skip) {
482 print_maybe_styled(w,
484 term::attr::ForegroundColor(lvl.color()))
487 fn print_macro_backtrace(w: &mut EmitterWriter,
488 cm: &codemap::CodeMap,
490 -> io::IoResult<()> {
491 for ei in sp.expn_info.iter() {
495 .map_or("".to_string(), |span| cm.span_to_str(*span));
496 let (pre, post) = match ei.callee.format {
497 codemap::MacroAttribute => ("#[", "]"),
498 codemap::MacroBang => ("", "!")
500 try!(print_diagnostic(w, ss.as_slice(), Note,
501 format!("in expansion of {}{}{}", pre,
504 let ss = cm.span_to_str(ei.call_site);
505 try!(print_diagnostic(w, ss.as_slice(), Note, "expansion site"));
506 try!(print_macro_backtrace(w, cm, ei.call_site));
511 pub fn expect<T:Clone>(diag: &SpanHandler, opt: Option<T>, msg: || -> String)
514 Some(ref t) => (*t).clone(),
515 None => diag.handler().bug(msg().as_slice()),