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