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