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