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