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::strbuf::StrBuf;
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 fn emit(&mut self, cmsp: Option<(&codemap::CodeMap, Span)>,
54 msg: &str, lvl: Level);
55 fn custom_emit(&mut self, cm: &codemap::CodeMap,
56 sp: RenderSpan, msg: &str, lvl: Level);
59 /// This structure is used to signify that a task has failed with a fatal error
60 /// from the diagnostics. You can use this with the `Any` trait to figure out
61 /// how a rustc task died (if so desired).
62 pub struct FatalError;
64 /// Signifies that the compiler died with an explicit call to `.bug`
65 /// or `.span_bug` rather than a failed assertion, etc.
66 pub struct ExplicitBug;
68 // a span-handler is like a handler but also
69 // accepts span information for source-location
71 pub struct SpanHandler {
73 pub cm: codemap::CodeMap,
77 pub fn span_fatal(&self, sp: Span, msg: &str) -> ! {
78 self.handler.emit(Some((&self.cm, sp)), msg, Fatal);
81 pub fn span_err(&self, sp: Span, msg: &str) {
82 self.handler.emit(Some((&self.cm, sp)), msg, Error);
83 self.handler.bump_err_count();
85 pub fn span_warn(&self, sp: Span, msg: &str) {
86 self.handler.emit(Some((&self.cm, sp)), msg, Warning);
88 pub fn span_note(&self, sp: Span, msg: &str) {
89 self.handler.emit(Some((&self.cm, sp)), msg, Note);
91 pub fn span_end_note(&self, sp: Span, msg: &str) {
92 self.handler.custom_emit(&self.cm, FullSpan(sp), msg, Note);
94 pub fn fileline_note(&self, sp: Span, msg: &str) {
95 self.handler.custom_emit(&self.cm, FileLine(sp), msg, Note);
97 pub fn span_bug(&self, sp: Span, msg: &str) -> ! {
98 self.handler.emit(Some((&self.cm, sp)), msg, Bug);
101 pub fn span_unimpl(&self, sp: Span, msg: &str) -> ! {
102 self.span_bug(sp, ~"unimplemented " + msg);
104 pub fn handler<'a>(&'a self) -> &'a Handler {
109 // a handler deals with errors; certain errors
110 // (fatal, bug, unimpl) may cause immediate exit,
111 // others log errors for later reporting.
113 err_count: Cell<uint>,
114 emit: RefCell<~Emitter:Send>,
118 pub fn fatal(&self, msg: &str) -> ! {
119 self.emit.borrow_mut().emit(None, msg, Fatal);
122 pub fn err(&self, msg: &str) {
123 self.emit.borrow_mut().emit(None, msg, Error);
124 self.bump_err_count();
126 pub fn bump_err_count(&self) {
127 self.err_count.set(self.err_count.get() + 1u);
129 pub fn err_count(&self) -> uint {
132 pub fn has_errors(&self) -> bool {
133 self.err_count.get()> 0u
135 pub fn abort_if_errors(&self) {
137 match self.err_count.get() {
139 1u => s = ~"aborting due to previous error",
141 s = format!("aborting due to {} previous errors",
142 self.err_count.get());
147 pub fn warn(&self, msg: &str) {
148 self.emit.borrow_mut().emit(None, msg, Warning);
150 pub fn note(&self, msg: &str) {
151 self.emit.borrow_mut().emit(None, msg, Note);
153 pub fn bug(&self, msg: &str) -> ! {
154 self.emit.borrow_mut().emit(None, msg, Bug);
157 pub fn unimpl(&self, msg: &str) -> ! {
158 self.bug(~"unimplemented " + msg);
161 cmsp: Option<(&codemap::CodeMap, Span)>,
164 self.emit.borrow_mut().emit(cmsp, msg, lvl);
166 pub fn custom_emit(&self, cm: &codemap::CodeMap,
167 sp: RenderSpan, msg: &str, lvl: Level) {
168 self.emit.borrow_mut().custom_emit(cm, sp, msg, lvl);
172 pub fn mk_span_handler(handler: Handler, cm: codemap::CodeMap) -> SpanHandler {
179 pub fn default_handler() -> Handler {
180 mk_handler(~EmitterWriter::stderr())
183 pub fn mk_handler(e: ~Emitter:Send) -> Handler {
185 err_count: Cell::new(0),
186 emit: RefCell::new(e),
199 impl fmt::Show for Level {
200 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
204 Bug => "error: internal compiler error".fmt(f),
205 Fatal | Error => "error".fmt(f),
206 Warning => "warning".fmt(f),
207 Note => "note".fmt(f),
213 fn color(self) -> term::color::Color {
215 Bug | Fatal | Error => term::color::BRIGHT_RED,
216 Warning => term::color::BRIGHT_YELLOW,
217 Note => term::color::BRIGHT_GREEN
222 fn print_maybe_styled(w: &mut EmitterWriter,
224 color: term::attr::Attr) -> io::IoResult<()> {
226 Terminal(ref mut t) => {
228 try!(t.write_str(msg));
238 fn print_diagnostic(dst: &mut EmitterWriter,
239 topic: &str, lvl: Level, msg: &str) -> io::IoResult<()> {
240 if !topic.is_empty() {
241 try!(write!(&mut dst.dst, "{} ", topic));
244 try!(print_maybe_styled(dst, format!("{}: ", lvl.to_str()),
245 term::attr::ForegroundColor(lvl.color())));
246 try!(print_maybe_styled(dst, format!("{}\n", msg), term::attr::Bold));
250 pub struct EmitterWriter {
255 Terminal(term::Terminal<io::stdio::StdWriter>),
260 pub fn stderr() -> EmitterWriter {
261 let stderr = io::stderr();
262 if stderr.get_ref().isatty() {
263 let dst = match term::Terminal::new(stderr.unwrap()) {
264 Ok(t) => Terminal(t),
265 Err(..) => Raw(~io::stderr()),
267 EmitterWriter { dst: dst }
269 EmitterWriter { dst: Raw(~stderr) }
273 pub fn new(dst: ~Writer:Send) -> EmitterWriter {
274 EmitterWriter { dst: Raw(dst) }
278 impl Writer for Destination {
279 fn write(&mut self, bytes: &[u8]) -> io::IoResult<()> {
281 Terminal(ref mut t) => t.write(bytes),
282 Raw(ref mut w) => w.write(bytes),
287 impl Emitter for EmitterWriter {
289 cmsp: Option<(&codemap::CodeMap, Span)>,
292 let error = match cmsp {
293 Some((cm, sp)) => emit(self, cm, FullSpan(sp), msg, lvl, false),
294 None => print_diagnostic(self, "", lvl, msg),
299 Err(e) => fail!("failed to print diagnostics: {}", e),
303 fn custom_emit(&mut self, cm: &codemap::CodeMap,
304 sp: RenderSpan, msg: &str, lvl: Level) {
305 match emit(self, cm, sp, msg, lvl, true) {
307 Err(e) => fail!("failed to print diagnostics: {}", e),
312 fn emit(dst: &mut EmitterWriter, cm: &codemap::CodeMap, rsp: RenderSpan,
313 msg: &str, lvl: Level, custom: bool) -> io::IoResult<()> {
315 let ss = cm.span_to_str(sp);
316 let lines = cm.span_to_lines(sp);
318 // we want to tell compiletest/runtest to look at the last line of the
319 // span (since `custom_highlight_lines` displays an arrow to the end of
321 let span_end = Span { lo: sp.hi, hi: sp.hi, expn_info: sp.expn_info};
322 let ses = cm.span_to_str(span_end);
323 try!(print_diagnostic(dst, ses, lvl, msg));
324 if rsp.is_full_span() {
325 try!(custom_highlight_lines(dst, cm, sp, lvl, lines));
328 try!(print_diagnostic(dst, ss, lvl, msg));
329 if rsp.is_full_span() {
330 try!(highlight_lines(dst, cm, sp, lvl, lines));
333 print_macro_backtrace(dst, cm, sp)
336 fn highlight_lines(err: &mut EmitterWriter,
337 cm: &codemap::CodeMap,
340 lines: codemap::FileLines) -> io::IoResult<()> {
341 let fm = &*lines.file;
343 let mut elided = false;
344 let mut display_lines = lines.lines.as_slice();
345 if display_lines.len() > MAX_LINES {
346 display_lines = display_lines.slice(0u, MAX_LINES);
349 // Print the offending lines
350 for line in display_lines.iter() {
351 try!(write!(&mut err.dst, "{}:{} {}\n", fm.name, *line + 1,
352 fm.get_line(*line as int)));
355 let last_line = display_lines[display_lines.len() - 1u];
356 let s = format!("{}:{} ", fm.name, last_line + 1u);
357 try!(write!(&mut err.dst, "{0:1$}...\n", "", s.len()));
361 // If there's one line at fault we can easily point to the problem
362 if lines.lines.len() == 1u {
363 let lo = cm.lookup_char_pos(sp.lo);
365 let mut num = (*lines.lines.get(0) + 1u) / 10u;
367 // how many digits must be indent past?
368 while num > 0u { num /= 10u; digits += 1u; }
370 // indent past |name:## | and the 0-offset column location
371 let left = fm.name.len() + digits + lo.col.to_uint() + 3u;
372 let mut s = StrBuf::new();
373 // Skip is the number of characters we need to skip because they are
374 // part of the 'filename:line ' part of the previous line.
375 let skip = fm.name.len() + digits + 3u;
376 for _ in range(0, skip) {
379 let orig = fm.get_line(*lines.lines.get(0) as int);
380 for pos in range(0u, left-skip) {
381 let cur_char = orig[pos] as char;
382 // Whenever a tab occurs on the previous line, we insert one on
383 // the error-point-squiggly-line as well (instead of a space).
384 // That way the squiggly line will usually appear in the correct
387 '\t' => s.push_char('\t'),
388 _ => s.push_char(' '),
391 try!(write!(&mut err.dst, "{}", s));
392 let mut s = StrBuf::from_str("^");
393 let hi = cm.lookup_char_pos(sp.hi);
394 if hi.col != lo.col {
395 // the ^ already takes up one space
396 let num_squigglies = hi.col.to_uint()-lo.col.to_uint()-1u;
397 for _ in range(0, num_squigglies) {
401 try!(print_maybe_styled(err, s.into_owned() + "\n",
402 term::attr::ForegroundColor(lvl.color())));
407 // Here are the differences between this and the normal `highlight_lines`:
408 // `custom_highlight_lines` will always put arrow on the last byte of the
409 // span (instead of the first byte). Also, when the span is too long (more
410 // than 6 lines), `custom_highlight_lines` will print the first line, then
411 // dot dot dot, then last line, whereas `highlight_lines` prints the first
413 fn custom_highlight_lines(w: &mut EmitterWriter,
414 cm: &codemap::CodeMap,
417 lines: codemap::FileLines)
418 -> io::IoResult<()> {
419 let fm = &*lines.file;
421 let lines = lines.lines.as_slice();
422 if lines.len() > MAX_LINES {
423 try!(write!(&mut w.dst, "{}:{} {}\n", fm.name,
424 lines[0] + 1, fm.get_line(lines[0] as int)));
425 try!(write!(&mut w.dst, "...\n"));
426 let last_line = lines[lines.len()-1];
427 try!(write!(&mut w.dst, "{}:{} {}\n", fm.name,
428 last_line + 1, fm.get_line(last_line as int)));
430 for line in lines.iter() {
431 try!(write!(&mut w.dst, "{}:{} {}\n", fm.name,
432 *line + 1, fm.get_line(*line as int)));
435 let last_line_start = format!("{}:{} ", fm.name, lines[lines.len()-1]+1);
436 let hi = cm.lookup_char_pos(sp.hi);
437 // Span seems to use half-opened interval, so subtract 1
438 let skip = last_line_start.len() + hi.col.to_uint() - 1;
439 let mut s = StrBuf::new();
440 for _ in range(0, skip) {
445 print_maybe_styled(w,
447 term::attr::ForegroundColor(lvl.color()))
450 fn print_macro_backtrace(w: &mut EmitterWriter,
451 cm: &codemap::CodeMap,
453 -> io::IoResult<()> {
454 for ei in sp.expn_info.iter() {
455 let ss = ei.callee.span.as_ref().map_or(~"", |span| cm.span_to_str(*span));
456 let (pre, post) = match ei.callee.format {
457 codemap::MacroAttribute => ("#[", "]"),
458 codemap::MacroBang => ("", "!")
460 try!(print_diagnostic(w, ss, Note,
461 format!("in expansion of {}{}{}", pre,
462 ei.callee.name, post)));
463 let ss = cm.span_to_str(ei.call_site);
464 try!(print_diagnostic(w, ss, Note, "expansion site"));
465 try!(print_macro_backtrace(w, cm, ei.call_site));
470 pub fn expect<T:Clone>(diag: &SpanHandler, opt: Option<T>, msg: || -> ~str) -> T {
472 Some(ref t) => (*t).clone(),
473 None => diag.handler().bug(msg()),