]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/diagnostic.rs
ee06efbec134376164aee599b294e190408b3ef8
[rust.git] / src / libsyntax / diagnostic.rs
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.
4 //
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.
10
11 extern crate libc;
12
13 use codemap::{Pos, Span};
14 use codemap;
15
16 use std::cell::{RefCell, Cell};
17 use std::fmt;
18 use std::io;
19 use std::iter::range;
20 use std::string::String;
21 use term;
22
23 // maximum number of lines we will print for each error; arbitrary.
24 static MAX_LINES: uint = 6u;
25
26 #[deriving(Clone)]
27 pub enum RenderSpan {
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.
31     FullSpan(Span),
32
33     /// A FileLine renders with just a line for the message prefixed
34     /// by file:linenum.
35     FileLine(Span),
36 }
37
38 impl RenderSpan {
39     fn span(self) -> Span {
40         match self {
41             FullSpan(s) | FileLine(s) => s
42         }
43     }
44     fn is_full_span(&self) -> bool {
45         match self {
46             &FullSpan(..) => true,
47             &FileLine(..) => false,
48         }
49     }
50 }
51
52 #[deriving(Clone)]
53 pub enum ColorConfig {
54     Auto,
55     Always,
56     Never
57 }
58
59 pub trait Emitter {
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);
64 }
65
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;
70
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;
74
75 // a span-handler is like a handler but also
76 // accepts span information for source-location
77 // reporting.
78 pub struct SpanHandler {
79     pub handler: Handler,
80     pub cm: codemap::CodeMap,
81 }
82
83 impl SpanHandler {
84     pub fn span_fatal(&self, sp: Span, msg: &str) -> ! {
85         self.handler.emit(Some((&self.cm, sp)), msg, Fatal);
86         fail!(FatalError);
87     }
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();
91     }
92     pub fn span_warn(&self, sp: Span, msg: &str) {
93         self.handler.emit(Some((&self.cm, sp)), msg, Warning);
94     }
95     pub fn span_note(&self, sp: Span, msg: &str) {
96         self.handler.emit(Some((&self.cm, sp)), msg, Note);
97     }
98     pub fn span_end_note(&self, sp: Span, msg: &str) {
99         self.handler.custom_emit(&self.cm, FullSpan(sp), msg, Note);
100     }
101     pub fn fileline_note(&self, sp: Span, msg: &str) {
102         self.handler.custom_emit(&self.cm, FileLine(sp), msg, Note);
103     }
104     pub fn span_bug(&self, sp: Span, msg: &str) -> ! {
105         self.handler.emit(Some((&self.cm, sp)), msg, Bug);
106         fail!(ExplicitBug);
107     }
108     pub fn span_unimpl(&self, sp: Span, msg: &str) -> ! {
109         self.span_bug(sp, format!("unimplemented {}", msg).as_slice());
110     }
111     pub fn handler<'a>(&'a self) -> &'a Handler {
112         &self.handler
113     }
114 }
115
116 // a handler deals with errors; certain errors
117 // (fatal, bug, unimpl) may cause immediate exit,
118 // others log errors for later reporting.
119 pub struct Handler {
120     err_count: Cell<uint>,
121     emit: RefCell<Box<Emitter:Send>>,
122 }
123
124 impl Handler {
125     pub fn fatal(&self, msg: &str) -> ! {
126         self.emit.borrow_mut().emit(None, msg, Fatal);
127         fail!(FatalError);
128     }
129     pub fn err(&self, msg: &str) {
130         self.emit.borrow_mut().emit(None, msg, Error);
131         self.bump_err_count();
132     }
133     pub fn bump_err_count(&self) {
134         self.err_count.set(self.err_count.get() + 1u);
135     }
136     pub fn err_count(&self) -> uint {
137         self.err_count.get()
138     }
139     pub fn has_errors(&self) -> bool {
140         self.err_count.get()> 0u
141     }
142     pub fn abort_if_errors(&self) {
143         let s;
144         match self.err_count.get() {
145           0u => return,
146           1u => s = "aborting due to previous error".to_string(),
147           _  => {
148             s = format!("aborting due to {} previous errors",
149                         self.err_count.get());
150           }
151         }
152         self.fatal(s.as_slice());
153     }
154     pub fn warn(&self, msg: &str) {
155         self.emit.borrow_mut().emit(None, msg, Warning);
156     }
157     pub fn note(&self, msg: &str) {
158         self.emit.borrow_mut().emit(None, msg, Note);
159     }
160     pub fn bug(&self, msg: &str) -> ! {
161         self.emit.borrow_mut().emit(None, msg, Bug);
162         fail!(ExplicitBug);
163     }
164     pub fn unimpl(&self, msg: &str) -> ! {
165         self.bug(format!("unimplemented {}", msg).as_slice());
166     }
167     pub fn emit(&self,
168                 cmsp: Option<(&codemap::CodeMap, Span)>,
169                 msg: &str,
170                 lvl: Level) {
171         self.emit.borrow_mut().emit(cmsp, msg, lvl);
172     }
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);
176     }
177 }
178
179 pub fn mk_span_handler(handler: Handler, cm: codemap::CodeMap) -> SpanHandler {
180     SpanHandler {
181         handler: handler,
182         cm: cm,
183     }
184 }
185
186 pub fn default_handler(color_config: ColorConfig) -> Handler {
187     mk_handler(box EmitterWriter::stderr(color_config))
188 }
189
190 pub fn mk_handler(e: Box<Emitter:Send>) -> Handler {
191     Handler {
192         err_count: Cell::new(0),
193         emit: RefCell::new(e),
194     }
195 }
196
197 #[deriving(PartialEq)]
198 pub enum Level {
199     Bug,
200     Fatal,
201     Error,
202     Warning,
203     Note,
204 }
205
206 impl fmt::Show for Level {
207     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
208         use std::fmt::Show;
209
210         match *self {
211             Bug => "error: internal compiler error".fmt(f),
212             Fatal | Error => "error".fmt(f),
213             Warning => "warning".fmt(f),
214             Note => "note".fmt(f),
215         }
216     }
217 }
218
219 impl Level {
220     fn color(self) -> term::color::Color {
221         match self {
222             Bug | Fatal | Error => term::color::BRIGHT_RED,
223             Warning => term::color::BRIGHT_YELLOW,
224             Note => term::color::BRIGHT_GREEN
225         }
226     }
227 }
228
229 fn print_maybe_styled(w: &mut EmitterWriter,
230                       msg: &str,
231                       color: term::attr::Attr) -> io::IoResult<()> {
232     match w.dst {
233         Terminal(ref mut t) => {
234             try!(t.attr(color));
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`).
242             //
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)));
250                 try!(t.reset());
251                 try!(t.write_str("\n"));
252             } else {
253                 try!(t.write_str(msg));
254                 try!(t.reset());
255             }
256             Ok(())
257         }
258         Raw(ref mut w) => {
259             w.write_str(msg)
260         }
261     }
262 }
263
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));
268     }
269
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(),
275                             term::attr::Bold));
276     Ok(())
277 }
278
279 pub struct EmitterWriter {
280     dst: Destination,
281 }
282
283 enum Destination {
284     Terminal(Box<term::Terminal<Box<Writer:Send>>:Send>),
285     Raw(Box<Writer:Send>),
286 }
287
288 impl EmitterWriter {
289     pub fn stderr(color_config: ColorConfig) -> EmitterWriter {
290         let stderr = io::stderr();
291
292         let use_color = match color_config {
293             Always => true,
294             Never  => false,
295             Auto   => stderr.get_ref().isatty()
296         };
297
298         if use_color {
299             let dst = match term::stderr() {
300                 Some(t) => Terminal(t),
301                 None    => Raw(box stderr),
302             };
303             EmitterWriter { dst: dst }
304         } else {
305             EmitterWriter { dst: Raw(box stderr) }
306         }
307     }
308
309     pub fn new(dst: Box<Writer:Send>) -> EmitterWriter {
310         EmitterWriter { dst: Raw(dst) }
311     }
312 }
313
314 impl Writer for Destination {
315     fn write(&mut self, bytes: &[u8]) -> io::IoResult<()> {
316         match *self {
317             Terminal(ref mut t) => t.write(bytes),
318             Raw(ref mut w) => w.write(bytes),
319         }
320     }
321 }
322
323 impl Emitter for EmitterWriter {
324     fn emit(&mut self,
325             cmsp: Option<(&codemap::CodeMap, Span)>,
326             msg: &str,
327             lvl: Level) {
328         let error = match cmsp {
329             Some((cm, sp)) => emit(self, cm, FullSpan(sp), msg, lvl, false),
330             None => print_diagnostic(self, "", lvl, msg),
331         };
332
333         match error {
334             Ok(()) => {}
335             Err(e) => fail!("failed to print diagnostics: {}", e),
336         }
337     }
338
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) {
342             Ok(()) => {}
343             Err(e) => fail!("failed to print diagnostics: {}", e),
344         }
345     }
346 }
347
348 fn emit(dst: &mut EmitterWriter, cm: &codemap::CodeMap, rsp: RenderSpan,
349         msg: &str, lvl: Level, custom: bool) -> io::IoResult<()> {
350     let sp = rsp.span();
351     let ss = cm.span_to_str(sp);
352     let lines = cm.span_to_lines(sp);
353     if custom {
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
356         // the span)
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));
362         }
363     } else {
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));
367         }
368     }
369     print_macro_backtrace(dst, cm, sp)
370 }
371
372 fn highlight_lines(err: &mut EmitterWriter,
373                    cm: &codemap::CodeMap,
374                    sp: Span,
375                    lvl: Level,
376                    lines: codemap::FileLines) -> io::IoResult<()> {
377     let fm = &*lines.file;
378
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);
383         elided = true;
384     }
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)));
389     }
390     if elided {
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()));
394     }
395
396     // FIXME (#3260)
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);
400         let mut digits = 0u;
401         let mut num = (*lines.lines.get(0) + 1u) / 10u;
402
403         // how many digits must be indent past?
404         while num > 0u { num /= 10u; digits += 1u; }
405
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) {
413             s.push_char(' ');
414         }
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
421             // position.
422             match cur_char {
423                 '\t' => s.push_char('\t'),
424                 _ => s.push_char(' '),
425             };
426         }
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) {
434                 s.push_char('~');
435             }
436         }
437         try!(print_maybe_styled(err,
438                                 format!("{}\n", s).as_slice(),
439                                 term::attr::ForegroundColor(lvl.color())));
440     }
441     Ok(())
442 }
443
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
449 // six lines.
450 fn custom_highlight_lines(w: &mut EmitterWriter,
451                           cm: &codemap::CodeMap,
452                           sp: Span,
453                           lvl: Level,
454                           lines: codemap::FileLines)
455                           -> io::IoResult<()> {
456     let fm = &*lines.file;
457
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)));
466     } else {
467         for line in lines.iter() {
468             try!(write!(&mut w.dst, "{}:{} {}\n", fm.name,
469                         *line + 1, fm.get_line(*line as int)));
470         }
471     }
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) {
478         s.push_char(' ');
479     }
480     s.push_char('^');
481     s.push_char('\n');
482     print_maybe_styled(w,
483                        s.as_slice(),
484                        term::attr::ForegroundColor(lvl.color()))
485 }
486
487 fn print_macro_backtrace(w: &mut EmitterWriter,
488                          cm: &codemap::CodeMap,
489                          sp: Span)
490                          -> io::IoResult<()> {
491     for ei in sp.expn_info.iter() {
492         let ss = ei.callee
493                    .span
494                    .as_ref()
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 => ("", "!")
499         };
500         try!(print_diagnostic(w, ss.as_slice(), Note,
501                               format!("in expansion of {}{}{}", pre,
502                                       ei.callee.name,
503                                       post).as_slice()));
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));
507     }
508     Ok(())
509 }
510
511 pub fn expect<T:Clone>(diag: &SpanHandler, opt: Option<T>, msg: || -> String)
512               -> T {
513     match opt {
514        Some(ref t) => (*t).clone(),
515        None => diag.handler().bug(msg().as_slice()),
516     }
517 }