]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/diagnostic.rs
auto merge of #19628 : jbranchaud/rust/add-string-as-string-doctest, r=steveklabnik
[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 pub use self::Level::*;
12 pub use self::RenderSpan::*;
13 pub use self::ColorConfig::*;
14 use self::Destination::*;
15
16 use codemap::{Pos, Span};
17 use codemap;
18 use diagnostics;
19
20 use std::cell::{RefCell, Cell};
21 use std::fmt;
22 use std::io;
23 use std::iter::range;
24 use std::string::String;
25 use term::WriterWrapper;
26 use term;
27
28 /// maximum number of lines we will print for each error; arbitrary.
29 static MAX_LINES: uint = 6u;
30
31 #[deriving(Clone)]
32 pub enum RenderSpan {
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.
36     FullSpan(Span),
37
38     /// A FileLine renders with just a line for the message prefixed
39     /// by file:linenum.
40     FileLine(Span),
41 }
42
43 impl Copy for RenderSpan {}
44
45 impl RenderSpan {
46     fn span(self) -> Span {
47         match self {
48             FullSpan(s) | FileLine(s) => s
49         }
50     }
51     fn is_full_span(&self) -> bool {
52         match self {
53             &FullSpan(..) => true,
54             &FileLine(..) => false,
55         }
56     }
57 }
58
59 #[deriving(Clone)]
60 pub enum ColorConfig {
61     Auto,
62     Always,
63     Never
64 }
65
66 impl Copy for ColorConfig {}
67
68 pub trait Emitter {
69     fn emit(&mut self, cmsp: Option<(&codemap::CodeMap, Span)>,
70             msg: &str, code: Option<&str>, lvl: Level);
71     fn custom_emit(&mut self, cm: &codemap::CodeMap,
72                    sp: RenderSpan, msg: &str, lvl: Level);
73 }
74
75 /// This structure is used to signify that a task has panicked with a fatal error
76 /// from the diagnostics. You can use this with the `Any` trait to figure out
77 /// how a rustc task died (if so desired).
78 pub struct FatalError;
79
80 impl Copy for FatalError {}
81
82 /// Signifies that the compiler died with an explicit call to `.bug`
83 /// or `.span_bug` rather than a failed assertion, etc.
84 pub struct ExplicitBug;
85
86 impl Copy for ExplicitBug {}
87
88 /// A span-handler is like a handler but also
89 /// accepts span information for source-location
90 /// reporting.
91 pub struct SpanHandler {
92     pub handler: Handler,
93     pub cm: codemap::CodeMap,
94 }
95
96 impl SpanHandler {
97     pub fn span_fatal(&self, sp: Span, msg: &str) -> ! {
98         self.handler.emit(Some((&self.cm, sp)), msg, Fatal);
99         panic!(FatalError);
100     }
101     pub fn span_err(&self, sp: Span, msg: &str) {
102         self.handler.emit(Some((&self.cm, sp)), msg, Error);
103         self.handler.bump_err_count();
104     }
105     pub fn span_err_with_code(&self, sp: Span, msg: &str, code: &str) {
106         self.handler.emit_with_code(Some((&self.cm, sp)), msg, code, Error);
107         self.handler.bump_err_count();
108     }
109     pub fn span_warn(&self, sp: Span, msg: &str) {
110         self.handler.emit(Some((&self.cm, sp)), msg, Warning);
111     }
112     pub fn span_warn_with_code(&self, sp: Span, msg: &str, code: &str) {
113         self.handler.emit_with_code(Some((&self.cm, sp)), msg, code, Warning);
114     }
115     pub fn span_note(&self, sp: Span, msg: &str) {
116         self.handler.emit(Some((&self.cm, sp)), msg, Note);
117     }
118     pub fn span_end_note(&self, sp: Span, msg: &str) {
119         self.handler.custom_emit(&self.cm, FullSpan(sp), msg, Note);
120     }
121     pub fn span_help(&self, sp: Span, msg: &str) {
122         self.handler.emit(Some((&self.cm, sp)), msg, Help);
123     }
124     pub fn fileline_note(&self, sp: Span, msg: &str) {
125         self.handler.custom_emit(&self.cm, FileLine(sp), msg, Note);
126     }
127     pub fn span_bug(&self, sp: Span, msg: &str) -> ! {
128         self.handler.emit(Some((&self.cm, sp)), msg, Bug);
129         panic!(ExplicitBug);
130     }
131     pub fn span_unimpl(&self, sp: Span, msg: &str) -> ! {
132         self.span_bug(sp, format!("unimplemented {}", msg).as_slice());
133     }
134     pub fn handler<'a>(&'a self) -> &'a Handler {
135         &self.handler
136     }
137 }
138
139 /// A handler deals with errors; certain errors
140 /// (fatal, bug, unimpl) may cause immediate exit,
141 /// others log errors for later reporting.
142 pub struct Handler {
143     err_count: Cell<uint>,
144     emit: RefCell<Box<Emitter + Send>>,
145 }
146
147 impl Handler {
148     pub fn fatal(&self, msg: &str) -> ! {
149         self.emit.borrow_mut().emit(None, msg, None, Fatal);
150         panic!(FatalError);
151     }
152     pub fn err(&self, msg: &str) {
153         self.emit.borrow_mut().emit(None, msg, None, Error);
154         self.bump_err_count();
155     }
156     pub fn bump_err_count(&self) {
157         self.err_count.set(self.err_count.get() + 1u);
158     }
159     pub fn err_count(&self) -> uint {
160         self.err_count.get()
161     }
162     pub fn has_errors(&self) -> bool {
163         self.err_count.get()> 0u
164     }
165     pub fn abort_if_errors(&self) {
166         let s;
167         match self.err_count.get() {
168           0u => return,
169           1u => s = "aborting due to previous error".to_string(),
170           _  => {
171             s = format!("aborting due to {} previous errors",
172                         self.err_count.get());
173           }
174         }
175         self.fatal(s.as_slice());
176     }
177     pub fn warn(&self, msg: &str) {
178         self.emit.borrow_mut().emit(None, msg, None, Warning);
179     }
180     pub fn note(&self, msg: &str) {
181         self.emit.borrow_mut().emit(None, msg, None, Note);
182     }
183     pub fn help(&self, msg: &str) {
184         self.emit.borrow_mut().emit(None, msg, None, Help);
185     }
186     pub fn bug(&self, msg: &str) -> ! {
187         self.emit.borrow_mut().emit(None, msg, None, Bug);
188         panic!(ExplicitBug);
189     }
190     pub fn unimpl(&self, msg: &str) -> ! {
191         self.bug(format!("unimplemented {}", msg).as_slice());
192     }
193     pub fn emit(&self,
194                 cmsp: Option<(&codemap::CodeMap, Span)>,
195                 msg: &str,
196                 lvl: Level) {
197         self.emit.borrow_mut().emit(cmsp, msg, None, lvl);
198     }
199     pub fn emit_with_code(&self,
200                           cmsp: Option<(&codemap::CodeMap, Span)>,
201                           msg: &str,
202                           code: &str,
203                           lvl: Level) {
204         self.emit.borrow_mut().emit(cmsp, msg, Some(code), lvl);
205     }
206     pub fn custom_emit(&self, cm: &codemap::CodeMap,
207                        sp: RenderSpan, msg: &str, lvl: Level) {
208         self.emit.borrow_mut().custom_emit(cm, sp, msg, lvl);
209     }
210 }
211
212 pub fn mk_span_handler(handler: Handler, cm: codemap::CodeMap) -> SpanHandler {
213     SpanHandler {
214         handler: handler,
215         cm: cm,
216     }
217 }
218
219 pub fn default_handler(color_config: ColorConfig,
220                        registry: Option<diagnostics::registry::Registry>) -> Handler {
221     mk_handler(box EmitterWriter::stderr(color_config, registry))
222 }
223
224 pub fn mk_handler(e: Box<Emitter + Send>) -> Handler {
225     Handler {
226         err_count: Cell::new(0),
227         emit: RefCell::new(e),
228     }
229 }
230
231 #[deriving(PartialEq, Clone)]
232 pub enum Level {
233     Bug,
234     Fatal,
235     Error,
236     Warning,
237     Note,
238     Help,
239 }
240
241 impl Copy for Level {}
242
243 impl fmt::Show for Level {
244     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
245         use std::fmt::Show;
246
247         match *self {
248             Bug => "error: internal compiler error".fmt(f),
249             Fatal | Error => "error".fmt(f),
250             Warning => "warning".fmt(f),
251             Note => "note".fmt(f),
252             Help => "help".fmt(f),
253         }
254     }
255 }
256
257 impl Level {
258     fn color(self) -> term::color::Color {
259         match self {
260             Bug | Fatal | Error => term::color::BRIGHT_RED,
261             Warning => term::color::BRIGHT_YELLOW,
262             Note => term::color::BRIGHT_GREEN,
263             Help => term::color::BRIGHT_CYAN,
264         }
265     }
266 }
267
268 fn print_maybe_styled(w: &mut EmitterWriter,
269                       msg: &str,
270                       color: term::attr::Attr) -> io::IoResult<()> {
271     match w.dst {
272         Terminal(ref mut t) => {
273             try!(t.attr(color));
274             // If `msg` ends in a newline, we need to reset the color before
275             // the newline. We're making the assumption that we end up writing
276             // to a `LineBufferedWriter`, which means that emitting the reset
277             // after the newline ends up buffering the reset until we print
278             // another line or exit. Buffering the reset is a problem if we're
279             // sharing the terminal with any other programs (e.g. other rustc
280             // instances via `make -jN`).
281             //
282             // Note that if `msg` contains any internal newlines, this will
283             // result in the `LineBufferedWriter` flushing twice instead of
284             // once, which still leaves the opportunity for interleaved output
285             // to be miscolored. We assume this is rare enough that we don't
286             // have to worry about it.
287             if msg.ends_with("\n") {
288                 try!(t.write_str(msg.slice_to(msg.len()-1)));
289                 try!(t.reset());
290                 try!(t.write_str("\n"));
291             } else {
292                 try!(t.write_str(msg));
293                 try!(t.reset());
294             }
295             Ok(())
296         }
297         Raw(ref mut w) => {
298             w.write_str(msg)
299         }
300     }
301 }
302
303 fn print_diagnostic(dst: &mut EmitterWriter, topic: &str, lvl: Level,
304                     msg: &str, code: Option<&str>) -> io::IoResult<()> {
305     if !topic.is_empty() {
306         try!(write!(&mut dst.dst, "{} ", topic));
307     }
308
309     try!(print_maybe_styled(dst,
310                             format!("{}: ", lvl.to_string()).as_slice(),
311                             term::attr::ForegroundColor(lvl.color())));
312     try!(print_maybe_styled(dst,
313                             format!("{}", msg).as_slice(),
314                             term::attr::Bold));
315
316     match code {
317         Some(code) => {
318             let style = term::attr::ForegroundColor(term::color::BRIGHT_MAGENTA);
319             try!(print_maybe_styled(dst, format!(" [{}]", code.clone()).as_slice(), style));
320         }
321         None => ()
322     }
323     try!(dst.dst.write_char('\n'));
324     Ok(())
325 }
326
327 pub struct EmitterWriter {
328     dst: Destination,
329     registry: Option<diagnostics::registry::Registry>
330 }
331
332 enum Destination {
333     Terminal(Box<term::Terminal<WriterWrapper> + Send>),
334     Raw(Box<Writer + Send>),
335 }
336
337 impl EmitterWriter {
338     pub fn stderr(color_config: ColorConfig,
339                   registry: Option<diagnostics::registry::Registry>) -> EmitterWriter {
340         let stderr = io::stderr();
341
342         let use_color = match color_config {
343             Always => true,
344             Never  => false,
345             Auto   => stderr.get_ref().isatty()
346         };
347
348         if use_color {
349             let dst = match term::stderr() {
350                 Some(t) => Terminal(t),
351                 None    => Raw(box stderr),
352             };
353             EmitterWriter { dst: dst, registry: registry }
354         } else {
355             EmitterWriter { dst: Raw(box stderr), registry: registry }
356         }
357     }
358
359     pub fn new(dst: Box<Writer + Send>,
360                registry: Option<diagnostics::registry::Registry>) -> EmitterWriter {
361         EmitterWriter { dst: Raw(dst), registry: registry }
362     }
363 }
364
365 impl Writer for Destination {
366     fn write(&mut self, bytes: &[u8]) -> io::IoResult<()> {
367         match *self {
368             Terminal(ref mut t) => t.write(bytes),
369             Raw(ref mut w) => w.write(bytes),
370         }
371     }
372 }
373
374 impl Emitter for EmitterWriter {
375     fn emit(&mut self,
376             cmsp: Option<(&codemap::CodeMap, Span)>,
377             msg: &str, code: Option<&str>, lvl: Level) {
378         let error = match cmsp {
379             Some((cm, sp)) => emit(self, cm, FullSpan(sp), msg, code, lvl, false),
380             None => print_diagnostic(self, "", lvl, msg, code),
381         };
382
383         match error {
384             Ok(()) => {}
385             Err(e) => panic!("failed to print diagnostics: {}", e),
386         }
387     }
388
389     fn custom_emit(&mut self, cm: &codemap::CodeMap,
390                    sp: RenderSpan, msg: &str, lvl: Level) {
391         match emit(self, cm, sp, msg, None, lvl, true) {
392             Ok(()) => {}
393             Err(e) => panic!("failed to print diagnostics: {}", e),
394         }
395     }
396 }
397
398 fn emit(dst: &mut EmitterWriter, cm: &codemap::CodeMap, rsp: RenderSpan,
399         msg: &str, code: Option<&str>, lvl: Level, custom: bool) -> io::IoResult<()> {
400     let sp = rsp.span();
401     let ss = cm.span_to_string(sp);
402     let lines = cm.span_to_lines(sp);
403     if custom {
404         // we want to tell compiletest/runtest to look at the last line of the
405         // span (since `custom_highlight_lines` displays an arrow to the end of
406         // the span)
407         let span_end = Span { lo: sp.hi, hi: sp.hi, expn_id: sp.expn_id};
408         let ses = cm.span_to_string(span_end);
409         try!(print_diagnostic(dst, ses.as_slice(), lvl, msg, code));
410         if rsp.is_full_span() {
411             try!(custom_highlight_lines(dst, cm, sp, lvl, lines));
412         }
413     } else {
414         try!(print_diagnostic(dst, ss.as_slice(), lvl, msg, code));
415         if rsp.is_full_span() {
416             try!(highlight_lines(dst, cm, sp, lvl, lines));
417         }
418     }
419     try!(print_macro_backtrace(dst, cm, sp));
420     match code {
421         Some(code) =>
422             match dst.registry.as_ref().and_then(|registry| registry.find_description(code)) {
423                 Some(_) => {
424                     try!(print_diagnostic(dst, ss.as_slice(), Help,
425                                           format!("pass `--explain {}` to see a detailed \
426                                                    explanation", code).as_slice(), None));
427                 }
428                 None => ()
429             },
430         None => (),
431     }
432     Ok(())
433 }
434
435 fn highlight_lines(err: &mut EmitterWriter,
436                    cm: &codemap::CodeMap,
437                    sp: Span,
438                    lvl: Level,
439                    lines: codemap::FileLines) -> io::IoResult<()> {
440     let fm = &*lines.file;
441
442     let mut elided = false;
443     let mut display_lines = lines.lines.as_slice();
444     if display_lines.len() > MAX_LINES {
445         display_lines = display_lines[0u..MAX_LINES];
446         elided = true;
447     }
448     // Print the offending lines
449     for &line_number in display_lines.iter() {
450         if let Some(line) = fm.get_line(line_number) {
451             try!(write!(&mut err.dst, "{}:{} {}\n", fm.name,
452                         line_number + 1, line));
453         }
454     }
455     if elided {
456         let last_line = display_lines[display_lines.len() - 1u];
457         let s = format!("{}:{} ", fm.name, last_line + 1u);
458         try!(write!(&mut err.dst, "{0:1$}...\n", "", s.len()));
459     }
460
461     // FIXME (#3260)
462     // If there's one line at fault we can easily point to the problem
463     if lines.lines.len() == 1u {
464         let lo = cm.lookup_char_pos(sp.lo);
465         let mut digits = 0u;
466         let mut num = (lines.lines[0] + 1u) / 10u;
467
468         // how many digits must be indent past?
469         while num > 0u { num /= 10u; digits += 1u; }
470
471         // indent past |name:## | and the 0-offset column location
472         let left = fm.name.len() + digits + lo.col.to_uint() + 3u;
473         let mut s = String::new();
474         // Skip is the number of characters we need to skip because they are
475         // part of the 'filename:line ' part of the previous line.
476         let skip = fm.name.len() + digits + 3u;
477         for _ in range(0, skip) {
478             s.push(' ');
479         }
480         if let Some(orig) = fm.get_line(lines.lines[0]) {
481             for pos in range(0u, left - skip) {
482                 let cur_char = orig.as_bytes()[pos] as char;
483                 // Whenever a tab occurs on the previous line, we insert one on
484                 // the error-point-squiggly-line as well (instead of a space).
485                 // That way the squiggly line will usually appear in the correct
486                 // position.
487                 match cur_char {
488                     '\t' => s.push('\t'),
489                     _ => s.push(' '),
490                 };
491             }
492         }
493
494         try!(write!(&mut err.dst, "{}", s));
495         let mut s = String::from_str("^");
496         let hi = cm.lookup_char_pos(sp.hi);
497         if hi.col != lo.col {
498             // the ^ already takes up one space
499             let num_squigglies = hi.col.to_uint() - lo.col.to_uint() - 1u;
500             for _ in range(0, num_squigglies) {
501                 s.push('~');
502             }
503         }
504         try!(print_maybe_styled(err,
505                                 format!("{}\n", s).as_slice(),
506                                 term::attr::ForegroundColor(lvl.color())));
507     }
508     Ok(())
509 }
510
511 /// Here are the differences between this and the normal `highlight_lines`:
512 /// `custom_highlight_lines` will always put arrow on the last byte of the
513 /// span (instead of the first byte). Also, when the span is too long (more
514 /// than 6 lines), `custom_highlight_lines` will print the first line, then
515 /// dot dot dot, then last line, whereas `highlight_lines` prints the first
516 /// six lines.
517 fn custom_highlight_lines(w: &mut EmitterWriter,
518                           cm: &codemap::CodeMap,
519                           sp: Span,
520                           lvl: Level,
521                           lines: codemap::FileLines)
522                           -> io::IoResult<()> {
523     let fm = &*lines.file;
524
525     let lines = lines.lines.as_slice();
526     if lines.len() > MAX_LINES {
527         if let Some(line) = fm.get_line(lines[0]) {
528             try!(write!(&mut w.dst, "{}:{} {}\n", fm.name,
529                         lines[0] + 1, line));
530         }
531         try!(write!(&mut w.dst, "...\n"));
532         let last_line_number = lines[lines.len() - 1];
533         if let Some(last_line) = fm.get_line(last_line_number) {
534             try!(write!(&mut w.dst, "{}:{} {}\n", fm.name,
535                         last_line_number + 1, last_line));
536         }
537     } else {
538         for &line_number in lines.iter() {
539             if let Some(line) = fm.get_line(line_number) {
540                 try!(write!(&mut w.dst, "{}:{} {}\n", fm.name,
541                             line_number + 1, line));
542             }
543         }
544     }
545     let last_line_start = format!("{}:{} ", fm.name, lines[lines.len()-1]+1);
546     let hi = cm.lookup_char_pos(sp.hi);
547     // Span seems to use half-opened interval, so subtract 1
548     let skip = last_line_start.len() + hi.col.to_uint() - 1;
549     let mut s = String::new();
550     for _ in range(0, skip) {
551         s.push(' ');
552     }
553     s.push('^');
554     s.push('\n');
555     print_maybe_styled(w,
556                        s.as_slice(),
557                        term::attr::ForegroundColor(lvl.color()))
558 }
559
560 fn print_macro_backtrace(w: &mut EmitterWriter,
561                          cm: &codemap::CodeMap,
562                          sp: Span)
563                          -> io::IoResult<()> {
564     let cs = try!(cm.with_expn_info(sp.expn_id, |expn_info| match expn_info {
565         Some(ei) => {
566             let ss = ei.callee.span.map_or(String::new(), |span| cm.span_to_string(span));
567             let (pre, post) = match ei.callee.format {
568                 codemap::MacroAttribute => ("#[", "]"),
569                 codemap::MacroBang => ("", "!")
570             };
571             try!(print_diagnostic(w, ss.as_slice(), Note,
572                                   format!("in expansion of {}{}{}", pre,
573                                           ei.callee.name,
574                                           post).as_slice(), None));
575             let ss = cm.span_to_string(ei.call_site);
576             try!(print_diagnostic(w, ss.as_slice(), Note, "expansion site", None));
577             Ok(Some(ei.call_site))
578         }
579         None => Ok(None)
580     }));
581     cs.map_or(Ok(()), |call_site| print_macro_backtrace(w, cm, call_site))
582 }
583
584 pub fn expect<T>(diag: &SpanHandler, opt: Option<T>, msg: || -> String) -> T {
585     match opt {
586         Some(t) => t,
587         None => diag.handler().bug(msg().as_slice()),
588     }
589 }