]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/diagnostic.rs
Auto merge of #30337 - wesleywiser:mir_switch, r=nikomatsakis
[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::{self, COMMAND_LINE_SP, COMMAND_LINE_EXPN, Pos, Span};
17 use diagnostics;
18
19 use std::cell::{RefCell, Cell};
20 use std::{cmp, error, fmt};
21 use std::io::prelude::*;
22 use std::io;
23 use term;
24
25 /// maximum number of lines we will print for each error; arbitrary.
26 const MAX_LINES: usize = 6;
27
28 #[derive(Clone)]
29 pub enum RenderSpan {
30     /// A FullSpan renders with both with an initial line for the
31     /// message, prefixed by file:linenum, followed by a summary of
32     /// the source code covered by the span.
33     FullSpan(Span),
34
35     /// Similar to a FullSpan, but the cited position is the end of
36     /// the span, instead of the start. Used, at least, for telling
37     /// compiletest/runtest to look at the last line of the span
38     /// (since `end_highlight_lines` displays an arrow to the end
39     /// of the span).
40     EndSpan(Span),
41
42     /// A suggestion renders with both with an initial line for the
43     /// message, prefixed by file:linenum, followed by a summary
44     /// of hypothetical source code, where the `String` is spliced
45     /// into the lines in place of the code covered by the span.
46     Suggestion(Span, String),
47
48     /// A FileLine renders with just a line for the message prefixed
49     /// by file:linenum.
50     FileLine(Span),
51 }
52
53 impl RenderSpan {
54     fn span(&self) -> Span {
55         match *self {
56             FullSpan(s) |
57             Suggestion(s, _) |
58             EndSpan(s) |
59             FileLine(s) =>
60                 s
61         }
62     }
63 }
64
65 #[derive(Clone, Copy)]
66 pub enum ColorConfig {
67     Auto,
68     Always,
69     Never
70 }
71
72 pub trait Emitter {
73     fn emit(&mut self, cmsp: Option<(&codemap::CodeMap, Span)>,
74             msg: &str, code: Option<&str>, lvl: Level);
75     fn custom_emit(&mut self, cm: &codemap::CodeMap,
76                    sp: RenderSpan, msg: &str, lvl: Level);
77 }
78
79 /// Used as a return value to signify a fatal error occurred. (It is also
80 /// used as the argument to panic at the moment, but that will eventually
81 /// not be true.)
82 #[derive(Copy, Clone, Debug)]
83 #[must_use]
84 pub struct FatalError;
85
86 impl fmt::Display for FatalError {
87     fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
88         write!(f, "parser fatal error")
89     }
90 }
91
92 impl error::Error for FatalError {
93     fn description(&self) -> &str {
94         "The parser has encountered a fatal error"
95     }
96 }
97
98 /// Signifies that the compiler died with an explicit call to `.bug`
99 /// or `.span_bug` rather than a failed assertion, etc.
100 #[derive(Copy, Clone, Debug)]
101 pub struct ExplicitBug;
102
103 impl fmt::Display for ExplicitBug {
104     fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
105         write!(f, "parser internal bug")
106     }
107 }
108
109 impl error::Error for ExplicitBug {
110     fn description(&self) -> &str {
111         "The parser has encountered an internal bug"
112     }
113 }
114
115 /// A span-handler is like a handler but also
116 /// accepts span information for source-location
117 /// reporting.
118 pub struct SpanHandler {
119     pub handler: Handler,
120     pub cm: codemap::CodeMap,
121 }
122
123 impl SpanHandler {
124     pub fn new(handler: Handler, cm: codemap::CodeMap) -> SpanHandler {
125         SpanHandler {
126             handler: handler,
127             cm: cm,
128         }
129     }
130     pub fn span_fatal(&self, sp: Span, msg: &str) -> FatalError {
131         self.handler.emit(Some((&self.cm, sp)), msg, Fatal);
132         return FatalError;
133     }
134     pub fn span_fatal_with_code(&self, sp: Span, msg: &str, code: &str) -> FatalError {
135         self.handler.emit_with_code(Some((&self.cm, sp)), msg, code, Fatal);
136         return FatalError;
137     }
138     pub fn span_err(&self, sp: Span, msg: &str) {
139         self.handler.emit(Some((&self.cm, sp)), msg, Error);
140         self.handler.bump_err_count();
141     }
142     pub fn span_err_with_code(&self, sp: Span, msg: &str, code: &str) {
143         self.handler.emit_with_code(Some((&self.cm, sp)), msg, code, Error);
144         self.handler.bump_err_count();
145     }
146     pub fn span_warn(&self, sp: Span, msg: &str) {
147         self.handler.emit(Some((&self.cm, sp)), msg, Warning);
148     }
149     pub fn span_warn_with_code(&self, sp: Span, msg: &str, code: &str) {
150         self.handler.emit_with_code(Some((&self.cm, sp)), msg, code, Warning);
151     }
152     pub fn span_note(&self, sp: Span, msg: &str) {
153         self.handler.emit(Some((&self.cm, sp)), msg, Note);
154     }
155     pub fn span_end_note(&self, sp: Span, msg: &str) {
156         self.handler.custom_emit(&self.cm, EndSpan(sp), msg, Note);
157     }
158     pub fn span_help(&self, sp: Span, msg: &str) {
159         self.handler.emit(Some((&self.cm, sp)), msg, Help);
160     }
161     /// Prints out a message with a suggested edit of the code.
162     ///
163     /// See `diagnostic::RenderSpan::Suggestion` for more information.
164     pub fn span_suggestion(&self, sp: Span, msg: &str, suggestion: String) {
165         self.handler.custom_emit(&self.cm, Suggestion(sp, suggestion), msg, Help);
166     }
167     pub fn fileline_note(&self, sp: Span, msg: &str) {
168         self.handler.custom_emit(&self.cm, FileLine(sp), msg, Note);
169     }
170     pub fn fileline_help(&self, sp: Span, msg: &str) {
171         self.handler.custom_emit(&self.cm, FileLine(sp), msg, Help);
172     }
173     pub fn span_bug(&self, sp: Span, msg: &str) -> ! {
174         self.handler.emit(Some((&self.cm, sp)), msg, Bug);
175         panic!(ExplicitBug);
176     }
177     pub fn span_bug_no_panic(&self, sp: Span, msg: &str) {
178         self.handler.emit(Some((&self.cm, sp)), msg, Bug);
179         self.handler.bump_err_count();
180     }
181     pub fn span_unimpl(&self, sp: Span, msg: &str) -> ! {
182         self.span_bug(sp, &format!("unimplemented {}", msg));
183     }
184     pub fn handler<'a>(&'a self) -> &'a Handler {
185         &self.handler
186     }
187 }
188
189 /// A handler deals with errors; certain errors
190 /// (fatal, bug, unimpl) may cause immediate exit,
191 /// others log errors for later reporting.
192 pub struct Handler {
193     err_count: Cell<usize>,
194     emit: RefCell<Box<Emitter + Send>>,
195     pub can_emit_warnings: bool
196 }
197
198 impl Handler {
199     pub fn new(color_config: ColorConfig,
200                registry: Option<diagnostics::registry::Registry>,
201                can_emit_warnings: bool) -> Handler {
202         let emitter = Box::new(EmitterWriter::stderr(color_config, registry));
203         Handler::with_emitter(can_emit_warnings, emitter)
204     }
205     pub fn with_emitter(can_emit_warnings: bool, e: Box<Emitter + Send>) -> Handler {
206         Handler {
207             err_count: Cell::new(0),
208             emit: RefCell::new(e),
209             can_emit_warnings: can_emit_warnings
210         }
211     }
212     pub fn fatal(&self, msg: &str) -> FatalError {
213         self.emit.borrow_mut().emit(None, msg, None, Fatal);
214         FatalError
215     }
216     pub fn err(&self, msg: &str) {
217         self.emit.borrow_mut().emit(None, msg, None, Error);
218         self.bump_err_count();
219     }
220     pub fn bump_err_count(&self) {
221         self.err_count.set(self.err_count.get() + 1);
222     }
223     pub fn err_count(&self) -> usize {
224         self.err_count.get()
225     }
226     pub fn has_errors(&self) -> bool {
227         self.err_count.get() > 0
228     }
229     pub fn abort_if_errors(&self) {
230         let s;
231         match self.err_count.get() {
232             0 => return,
233             1 => s = "aborting due to previous error".to_string(),
234             _  => {
235                 s = format!("aborting due to {} previous errors",
236                             self.err_count.get());
237             }
238         }
239
240         panic!(self.fatal(&s[..]));
241     }
242     pub fn warn(&self, msg: &str) {
243         self.emit.borrow_mut().emit(None, msg, None, Warning);
244     }
245     pub fn note(&self, msg: &str) {
246         self.emit.borrow_mut().emit(None, msg, None, Note);
247     }
248     pub fn help(&self, msg: &str) {
249         self.emit.borrow_mut().emit(None, msg, None, Help);
250     }
251     pub fn bug(&self, msg: &str) -> ! {
252         self.emit.borrow_mut().emit(None, msg, None, Bug);
253         panic!(ExplicitBug);
254     }
255     pub fn unimpl(&self, msg: &str) -> ! {
256         self.bug(&format!("unimplemented {}", msg));
257     }
258     pub fn emit(&self,
259                 cmsp: Option<(&codemap::CodeMap, Span)>,
260                 msg: &str,
261                 lvl: Level) {
262         if lvl == Warning && !self.can_emit_warnings { return }
263         self.emit.borrow_mut().emit(cmsp, msg, None, lvl);
264     }
265     pub fn emit_with_code(&self,
266                           cmsp: Option<(&codemap::CodeMap, Span)>,
267                           msg: &str,
268                           code: &str,
269                           lvl: Level) {
270         if lvl == Warning && !self.can_emit_warnings { return }
271         self.emit.borrow_mut().emit(cmsp, msg, Some(code), lvl);
272     }
273     pub fn custom_emit(&self, cm: &codemap::CodeMap,
274                        sp: RenderSpan, msg: &str, lvl: Level) {
275         if lvl == Warning && !self.can_emit_warnings { return }
276         self.emit.borrow_mut().custom_emit(cm, sp, msg, lvl);
277     }
278 }
279
280 #[derive(Copy, PartialEq, Clone, Debug)]
281 pub enum Level {
282     Bug,
283     Fatal,
284     Error,
285     Warning,
286     Note,
287     Help,
288 }
289
290 impl fmt::Display for Level {
291     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
292         use std::fmt::Display;
293
294         match *self {
295             Bug => "error: internal compiler error".fmt(f),
296             Fatal | Error => "error".fmt(f),
297             Warning => "warning".fmt(f),
298             Note => "note".fmt(f),
299             Help => "help".fmt(f),
300         }
301     }
302 }
303
304 impl Level {
305     fn color(self) -> term::color::Color {
306         match self {
307             Bug | Fatal | Error => term::color::BRIGHT_RED,
308             Warning => term::color::BRIGHT_YELLOW,
309             Note => term::color::BRIGHT_GREEN,
310             Help => term::color::BRIGHT_CYAN,
311         }
312     }
313 }
314
315 pub struct EmitterWriter {
316     dst: Destination,
317     registry: Option<diagnostics::registry::Registry>
318 }
319
320 enum Destination {
321     Terminal(Box<term::StderrTerminal>),
322     Raw(Box<Write + Send>),
323 }
324
325 /// Do not use this for messages that end in `\n` – use `println_maybe_styled` instead. See
326 /// `EmitterWriter::print_maybe_styled` for details.
327 macro_rules! print_maybe_styled {
328     ($writer: expr, $style: expr, $($arg: tt)*) => {
329         $writer.print_maybe_styled(format_args!($($arg)*), $style, false)
330     }
331 }
332
333 macro_rules! println_maybe_styled {
334     ($writer: expr, $style: expr, $($arg: tt)*) => {
335         $writer.print_maybe_styled(format_args!($($arg)*), $style, true)
336     }
337 }
338
339 impl EmitterWriter {
340     pub fn stderr(color_config: ColorConfig,
341                   registry: Option<diagnostics::registry::Registry>) -> EmitterWriter {
342         let stderr = io::stderr();
343
344         let use_color = match color_config {
345             Always => true,
346             Never  => false,
347             Auto   => stderr_isatty(),
348         };
349
350         if use_color {
351             let dst = match term::stderr() {
352                 Some(t) => Terminal(t),
353                 None    => Raw(Box::new(stderr)),
354             };
355             EmitterWriter { dst: dst, registry: registry }
356         } else {
357             EmitterWriter { dst: Raw(Box::new(stderr)), registry: registry }
358         }
359     }
360
361     pub fn new(dst: Box<Write + Send>,
362                registry: Option<diagnostics::registry::Registry>) -> EmitterWriter {
363         EmitterWriter { dst: Raw(dst), registry: registry }
364     }
365
366     fn print_maybe_styled(&mut self,
367                           args: fmt::Arguments,
368                           color: term::Attr,
369                           print_newline_at_end: bool) -> io::Result<()> {
370         match self.dst {
371             Terminal(ref mut t) => {
372                 try!(t.attr(color));
373                 // If `msg` ends in a newline, we need to reset the color before
374                 // the newline. We're making the assumption that we end up writing
375                 // to a `LineBufferedWriter`, which means that emitting the reset
376                 // after the newline ends up buffering the reset until we print
377                 // another line or exit. Buffering the reset is a problem if we're
378                 // sharing the terminal with any other programs (e.g. other rustc
379                 // instances via `make -jN`).
380                 //
381                 // Note that if `msg` contains any internal newlines, this will
382                 // result in the `LineBufferedWriter` flushing twice instead of
383                 // once, which still leaves the opportunity for interleaved output
384                 // to be miscolored. We assume this is rare enough that we don't
385                 // have to worry about it.
386                 try!(t.write_fmt(args));
387                 try!(t.reset());
388                 if print_newline_at_end {
389                     t.write_all(b"\n")
390                 } else {
391                     Ok(())
392                 }
393             }
394             Raw(ref mut w) => {
395                 try!(w.write_fmt(args));
396                 if print_newline_at_end {
397                     w.write_all(b"\n")
398                 } else {
399                     Ok(())
400                 }
401             }
402         }
403     }
404
405     fn print_diagnostic(&mut self, topic: &str, lvl: Level,
406                         msg: &str, code: Option<&str>) -> io::Result<()> {
407         if !topic.is_empty() {
408             try!(write!(&mut self.dst, "{} ", topic));
409         }
410
411         try!(print_maybe_styled!(self, term::Attr::ForegroundColor(lvl.color()),
412                                  "{}: ", lvl.to_string()));
413         try!(print_maybe_styled!(self, term::Attr::Bold, "{}", msg));
414
415         match code {
416             Some(code) => {
417                 let style = term::Attr::ForegroundColor(term::color::BRIGHT_MAGENTA);
418                 try!(print_maybe_styled!(self, style, " [{}]", code.clone()));
419             }
420             None => ()
421         }
422         try!(write!(&mut self.dst, "\n"));
423         Ok(())
424     }
425
426     fn emit_(&mut self, cm: &codemap::CodeMap, rsp: RenderSpan,
427              msg: &str, code: Option<&str>, lvl: Level) -> io::Result<()> {
428         let sp = rsp.span();
429
430         // We cannot check equality directly with COMMAND_LINE_SP
431         // since PartialEq is manually implemented to ignore the ExpnId
432         let ss = if sp.expn_id == COMMAND_LINE_EXPN {
433             "<command line option>".to_string()
434         } else if let EndSpan(_) = rsp {
435             let span_end = Span { lo: sp.hi, hi: sp.hi, expn_id: sp.expn_id};
436             cm.span_to_string(span_end)
437         } else {
438             cm.span_to_string(sp)
439         };
440
441         try!(self.print_diagnostic(&ss[..], lvl, msg, code));
442
443         match rsp {
444             FullSpan(_) => {
445                 try!(self.highlight_lines(cm, sp, lvl, cm.span_to_lines(sp)));
446                 try!(self.print_macro_backtrace(cm, sp));
447             }
448             EndSpan(_) => {
449                 try!(self.end_highlight_lines(cm, sp, lvl, cm.span_to_lines(sp)));
450                 try!(self.print_macro_backtrace(cm, sp));
451             }
452             Suggestion(_, ref suggestion) => {
453                 try!(self.highlight_suggestion(cm, sp, suggestion));
454                 try!(self.print_macro_backtrace(cm, sp));
455             }
456             FileLine(..) => {
457                 // no source text in this case!
458             }
459         }
460
461         match code {
462             Some(code) =>
463                 match self.registry.as_ref().and_then(|registry| registry.find_description(code)) {
464                     Some(_) => {
465                         try!(self.print_diagnostic(&ss[..], Help,
466                                                    &format!("run `rustc --explain {}` to see a \
467                                                              detailed explanation", code), None));
468                     }
469                     None => ()
470                 },
471             None => (),
472         }
473         Ok(())
474     }
475
476     fn highlight_suggestion(&mut self,
477                             cm: &codemap::CodeMap,
478                             sp: Span,
479                             suggestion: &str)
480                             -> io::Result<()>
481     {
482         let lines = cm.span_to_lines(sp).unwrap();
483         assert!(!lines.lines.is_empty());
484
485         // To build up the result, we want to take the snippet from the first
486         // line that precedes the span, prepend that with the suggestion, and
487         // then append the snippet from the last line that trails the span.
488         let fm = &lines.file;
489
490         let first_line = &lines.lines[0];
491         let prefix = fm.get_line(first_line.line_index)
492                        .map(|l| &l[..first_line.start_col.0])
493                        .unwrap_or("");
494
495         let last_line = lines.lines.last().unwrap();
496         let suffix = fm.get_line(last_line.line_index)
497                        .map(|l| &l[last_line.end_col.0..])
498                        .unwrap_or("");
499
500         let complete = format!("{}{}{}", prefix, suggestion, suffix);
501
502         // print the suggestion without any line numbers, but leave
503         // space for them. This helps with lining up with previous
504         // snippets from the actual error being reported.
505         let fm = &*lines.file;
506         let mut lines = complete.lines();
507         for (line, line_index) in lines.by_ref().take(MAX_LINES).zip(first_line.line_index..) {
508             let elided_line_num = format!("{}", line_index+1);
509             try!(write!(&mut self.dst, "{0}:{1:2$} {3}\n",
510                         fm.name, "", elided_line_num.len(), line));
511         }
512
513         // if we elided some lines, add an ellipsis
514         if lines.next().is_some() {
515             let elided_line_num = format!("{}", first_line.line_index + MAX_LINES + 1);
516             try!(write!(&mut self.dst, "{0:1$} {0:2$} ...\n",
517                         "", fm.name.len(), elided_line_num.len()));
518         }
519
520         Ok(())
521     }
522
523     fn highlight_lines(&mut self,
524                        cm: &codemap::CodeMap,
525                        sp: Span,
526                        lvl: Level,
527                        lines: codemap::FileLinesResult)
528                        -> io::Result<()>
529     {
530         let lines = match lines {
531             Ok(lines) => lines,
532             Err(_) => {
533                 try!(write!(&mut self.dst, "(internal compiler error: unprintable span)\n"));
534                 return Ok(());
535             }
536         };
537
538         let fm = &*lines.file;
539
540         let line_strings: Option<Vec<&str>> =
541             lines.lines.iter()
542                        .map(|info| fm.get_line(info.line_index))
543                        .collect();
544
545         let line_strings = match line_strings {
546             None => { return Ok(()); }
547             Some(line_strings) => line_strings
548         };
549
550         // Display only the first MAX_LINES lines.
551         let all_lines = lines.lines.len();
552         let display_lines = cmp::min(all_lines, MAX_LINES);
553         let display_line_infos = &lines.lines[..display_lines];
554         let display_line_strings = &line_strings[..display_lines];
555
556         // Calculate the widest number to format evenly and fix #11715
557         assert!(display_line_infos.len() > 0);
558         let mut max_line_num = display_line_infos[display_line_infos.len() - 1].line_index + 1;
559         let mut digits = 0;
560         while max_line_num > 0 {
561             max_line_num /= 10;
562             digits += 1;
563         }
564
565         // Print the offending lines
566         for (line_info, line) in display_line_infos.iter().zip(display_line_strings) {
567             try!(write!(&mut self.dst, "{}:{:>width$} {}\n",
568                         fm.name,
569                         line_info.line_index + 1,
570                         line,
571                         width=digits));
572         }
573
574         // If we elided something, put an ellipsis.
575         if display_lines < all_lines {
576             let last_line_index = display_line_infos.last().unwrap().line_index;
577             let s = format!("{}:{} ", fm.name, last_line_index + 1);
578             try!(write!(&mut self.dst, "{0:1$}...\n", "", s.len()));
579         }
580
581         // FIXME (#3260)
582         // If there's one line at fault we can easily point to the problem
583         if lines.lines.len() == 1 {
584             let lo = cm.lookup_char_pos(sp.lo);
585             let mut digits = 0;
586             let mut num = (lines.lines[0].line_index + 1) / 10;
587
588             // how many digits must be indent past?
589             while num > 0 { num /= 10; digits += 1; }
590
591             let mut s = String::new();
592             // Skip is the number of characters we need to skip because they are
593             // part of the 'filename:line ' part of the previous line.
594             let skip = fm.name.chars().count() + digits + 3;
595             for _ in 0..skip {
596                 s.push(' ');
597             }
598             if let Some(orig) = fm.get_line(lines.lines[0].line_index) {
599                 let mut col = skip;
600                 let mut lastc = ' ';
601                 let mut iter = orig.chars().enumerate();
602                 for (pos, ch) in iter.by_ref() {
603                     lastc = ch;
604                     if pos >= lo.col.to_usize() { break; }
605                     // Whenever a tab occurs on the previous line, we insert one on
606                     // the error-point-squiggly-line as well (instead of a space).
607                     // That way the squiggly line will usually appear in the correct
608                     // position.
609                     match ch {
610                         '\t' => {
611                             col += 8 - col%8;
612                             s.push('\t');
613                         },
614                         _ => {
615                             col += 1;
616                             s.push(' ');
617                         },
618                     }
619                 }
620
621                 try!(write!(&mut self.dst, "{}", s));
622                 let mut s = String::from("^");
623                 let count = match lastc {
624                     // Most terminals have a tab stop every eight columns by default
625                     '\t' => 8 - col%8,
626                     _ => 1,
627                 };
628                 col += count;
629                 s.extend(::std::iter::repeat('~').take(count));
630
631                 let hi = cm.lookup_char_pos(sp.hi);
632                 if hi.col != lo.col {
633                     for (pos, ch) in iter {
634                         if pos >= hi.col.to_usize() { break; }
635                         let count = match ch {
636                             '\t' => 8 - col%8,
637                             _ => 1,
638                         };
639                         col += count;
640                         s.extend(::std::iter::repeat('~').take(count));
641                     }
642                 }
643
644                 if s.len() > 1 {
645                     // One extra squiggly is replaced by a "^"
646                     s.pop();
647                 }
648
649                 try!(println_maybe_styled!(self, term::Attr::ForegroundColor(lvl.color()),
650                                            "{}", s));
651             }
652         }
653         Ok(())
654     }
655
656     /// Here are the differences between this and the normal `highlight_lines`:
657     /// `end_highlight_lines` will always put arrow on the last byte of the
658     /// span (instead of the first byte). Also, when the span is too long (more
659     /// than 6 lines), `end_highlight_lines` will print the first line, then
660     /// dot dot dot, then last line, whereas `highlight_lines` prints the first
661     /// six lines.
662     #[allow(deprecated)]
663     fn end_highlight_lines(&mut self,
664                            cm: &codemap::CodeMap,
665                            sp: Span,
666                            lvl: Level,
667                            lines: codemap::FileLinesResult)
668                           -> io::Result<()> {
669         let lines = match lines {
670             Ok(lines) => lines,
671             Err(_) => {
672                 try!(write!(&mut self.dst, "(internal compiler error: unprintable span)\n"));
673                 return Ok(());
674             }
675         };
676
677         let fm = &*lines.file;
678
679         let lines = &lines.lines[..];
680         if lines.len() > MAX_LINES {
681             if let Some(line) = fm.get_line(lines[0].line_index) {
682                 try!(write!(&mut self.dst, "{}:{} {}\n", fm.name,
683                             lines[0].line_index + 1, line));
684             }
685             try!(write!(&mut self.dst, "...\n"));
686             let last_line_index = lines[lines.len() - 1].line_index;
687             if let Some(last_line) = fm.get_line(last_line_index) {
688                 try!(write!(&mut self.dst, "{}:{} {}\n", fm.name,
689                             last_line_index + 1, last_line));
690             }
691         } else {
692             for line_info in lines {
693                 if let Some(line) = fm.get_line(line_info.line_index) {
694                     try!(write!(&mut self.dst, "{}:{} {}\n", fm.name,
695                                 line_info.line_index + 1, line));
696                 }
697             }
698         }
699         let last_line_start = format!("{}:{} ", fm.name, lines[lines.len()-1].line_index + 1);
700         let hi = cm.lookup_char_pos(sp.hi);
701         let skip = last_line_start.chars().count();
702         let mut s = String::new();
703         for _ in 0..skip {
704             s.push(' ');
705         }
706         if let Some(orig) = fm.get_line(lines[0].line_index) {
707             let iter = orig.chars().enumerate();
708             for (pos, ch) in iter {
709                 // Span seems to use half-opened interval, so subtract 1
710                 if pos >= hi.col.to_usize() - 1 { break; }
711                 // Whenever a tab occurs on the previous line, we insert one on
712                 // the error-point-squiggly-line as well (instead of a space).
713                 // That way the squiggly line will usually appear in the correct
714                 // position.
715                 match ch {
716                     '\t' => s.push('\t'),
717                     _ => s.push(' '),
718                 }
719             }
720         }
721         s.push('^');
722         println_maybe_styled!(self, term::Attr::ForegroundColor(lvl.color()),
723                               "{}", s)
724     }
725
726     fn print_macro_backtrace(&mut self,
727                              cm: &codemap::CodeMap,
728                              sp: Span)
729                              -> io::Result<()> {
730         let mut last_span = codemap::DUMMY_SP;
731         let mut sp_opt = Some(sp);
732
733         while let Some(sp) = sp_opt {
734             sp_opt = try!(cm.with_expn_info(sp.expn_id, |expn_info| -> io::Result<_> {
735                 match expn_info {
736                     Some(ei) => {
737                         let (pre, post) = match ei.callee.format {
738                             codemap::MacroAttribute(..) => ("#[", "]"),
739                             codemap::MacroBang(..) => ("", "!"),
740                         };
741                         // Don't print recursive invocations
742                         if ei.call_site != last_span {
743                             last_span = ei.call_site;
744
745                             let mut diag_string = format!("in this expansion of {}{}{}",
746                                                           pre,
747                                                           ei.callee.name(),
748                                                           post);
749
750                             if let Some(def_site_span) = ei.callee.span {
751                                 diag_string.push_str(&format!(" (defined in {})",
752                                                               cm.span_to_filename(def_site_span)));
753                             }
754
755                             try!(self.print_diagnostic(&cm.span_to_string(ei.call_site),
756                                                        Note,
757                                                        &diag_string,
758                                                        None));
759                         }
760                         Ok(Some(ei.call_site))
761                     }
762                     None => Ok(None)
763                 }
764             }));
765         }
766
767         Ok(())
768     }
769 }
770
771 #[cfg(unix)]
772 fn stderr_isatty() -> bool {
773     use libc;
774     unsafe { libc::isatty(libc::STDERR_FILENO) != 0 }
775 }
776 #[cfg(windows)]
777 fn stderr_isatty() -> bool {
778     type DWORD = u32;
779     type BOOL = i32;
780     type HANDLE = *mut u8;
781     const STD_ERROR_HANDLE: DWORD = -12i32 as DWORD;
782     extern "system" {
783         fn GetStdHandle(which: DWORD) -> HANDLE;
784         fn GetConsoleMode(hConsoleHandle: HANDLE,
785                           lpMode: *mut DWORD) -> BOOL;
786     }
787     unsafe {
788         let handle = GetStdHandle(STD_ERROR_HANDLE);
789         let mut out = 0;
790         GetConsoleMode(handle, &mut out) != 0
791     }
792 }
793
794 impl Write for Destination {
795     fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
796         match *self {
797             Terminal(ref mut t) => t.write(bytes),
798             Raw(ref mut w) => w.write(bytes),
799         }
800     }
801     fn flush(&mut self) -> io::Result<()> {
802         match *self {
803             Terminal(ref mut t) => t.flush(),
804             Raw(ref mut w) => w.flush(),
805         }
806     }
807 }
808
809 impl Emitter for EmitterWriter {
810     fn emit(&mut self,
811             cmsp: Option<(&codemap::CodeMap, Span)>,
812             msg: &str, code: Option<&str>, lvl: Level) {
813         let error = match cmsp {
814             Some((cm, COMMAND_LINE_SP)) => self.emit_(cm,
815                                                 FileLine(COMMAND_LINE_SP),
816                                                 msg, code, lvl),
817             Some((cm, sp)) => self.emit_(cm, FullSpan(sp), msg, code, lvl),
818             None => self.print_diagnostic("", lvl, msg, code),
819         };
820
821         match error {
822             Ok(()) => {}
823             Err(e) => panic!("failed to print diagnostics: {:?}", e),
824         }
825     }
826
827     fn custom_emit(&mut self, cm: &codemap::CodeMap,
828                    sp: RenderSpan, msg: &str, lvl: Level) {
829         match self.emit_(cm, sp, msg, None, lvl) {
830             Ok(()) => {}
831             Err(e) => panic!("failed to print diagnostics: {:?}", e),
832         }
833     }
834 }
835
836 pub fn expect<T, M>(diag: &SpanHandler, opt: Option<T>, msg: M) -> T where
837     M: FnOnce() -> String,
838 {
839     match opt {
840         Some(t) => t,
841         None => diag.handler().bug(&msg()),
842     }
843 }
844
845 #[cfg(test)]
846 mod test {
847     use super::{EmitterWriter, Level};
848     use codemap::{mk_sp, CodeMap};
849     use std::sync::{Arc, Mutex};
850     use std::io::{self, Write};
851     use std::str::from_utf8;
852
853     // Diagnostic doesn't align properly in span where line number increases by one digit
854     #[test]
855     fn test_hilight_suggestion_issue_11715() {
856         struct Sink(Arc<Mutex<Vec<u8>>>);
857         impl Write for Sink {
858             fn write(&mut self, data: &[u8]) -> io::Result<usize> {
859                 Write::write(&mut *self.0.lock().unwrap(), data)
860             }
861             fn flush(&mut self) -> io::Result<()> { Ok(()) }
862         }
863         let data = Arc::new(Mutex::new(Vec::new()));
864         let mut ew = EmitterWriter::new(Box::new(Sink(data.clone())), None);
865         let cm = CodeMap::new();
866         let content = "abcdefg
867         koksi
868         line3
869         line4
870         cinq
871         line6
872         line7
873         line8
874         line9
875         line10
876         e-lä-vän
877         tolv
878         dreizehn
879         ";
880         let file = cm.new_filemap_and_lines("dummy.txt", content);
881         let start = file.lines.borrow()[7];
882         let end = file.lines.borrow()[11];
883         let sp = mk_sp(start, end);
884         let lvl = Level::Error;
885         println!("span_to_lines");
886         let lines = cm.span_to_lines(sp);
887         println!("highlight_lines");
888         ew.highlight_lines(&cm, sp, lvl, lines).unwrap();
889         println!("done");
890         let vec = data.lock().unwrap().clone();
891         let vec: &[u8] = &vec;
892         let str = from_utf8(vec).unwrap();
893         println!("{}", str);
894         assert_eq!(str, "dummy.txt: 8         line8\n\
895                          dummy.txt: 9         line9\n\
896                          dummy.txt:10         line10\n\
897                          dummy.txt:11         e-lä-vän\n\
898                          dummy.txt:12         tolv\n");
899     }
900 }