]> git.lizzy.rs Git - rust.git/blob - src/librustc_errors/emitter.rs
Auto merge of #45741 - oli-obk:refactor_suggestions, r=estebank
[rust.git] / src / librustc_errors / emitter.rs
1 // Copyright 2012-2015 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 use self::Destination::*;
12
13 use syntax_pos::{DUMMY_SP, FileMap, Span, MultiSpan};
14
15 use {Level, CodeSuggestion, DiagnosticBuilder, SubDiagnostic, CodeMapper, DiagnosticId};
16 use RenderSpan::*;
17 use snippet::{Annotation, AnnotationType, Line, MultilineAnnotation, StyledString, Style};
18 use styled_buffer::StyledBuffer;
19
20 use std::borrow::Cow;
21 use std::io::prelude::*;
22 use std::io;
23 use std::rc::Rc;
24 use term;
25 use std::collections::HashMap;
26 use std::cmp::min;
27
28 /// Emitter trait for emitting errors.
29 pub trait Emitter {
30     /// Emit a structured diagnostic.
31     fn emit(&mut self, db: &DiagnosticBuilder);
32 }
33
34 impl Emitter for EmitterWriter {
35     fn emit(&mut self, db: &DiagnosticBuilder) {
36         let mut primary_span = db.span.clone();
37         let mut children = db.children.clone();
38
39         if let Some((sugg, rest)) = db.suggestions.split_first() {
40             if rest.is_empty() &&
41                // don't display multi-suggestions as labels
42                sugg.substitutions.len() == 1 &&
43                // don't display multipart suggestions as labels
44                sugg.substitutions[0].parts.len() == 1 &&
45                // don't display long messages as labels
46                sugg.msg.split_whitespace().count() < 10 &&
47                // don't display multiline suggestions as labels
48                !sugg.substitutions[0].parts[0].snippet.contains('\n') {
49                 let substitution = &sugg.substitutions[0].parts[0].snippet;
50                 let msg = if substitution.len() == 0 || !sugg.show_code_when_inline {
51                     // This substitution is only removal or we explicitly don't want to show the
52                     // code inline, don't show it
53                     format!("help: {}", sugg.msg)
54                 } else {
55                     format!("help: {}: `{}`", sugg.msg, substitution)
56                 };
57                 primary_span.push_span_label(sugg.substitutions[0].parts[0].span, msg);
58             } else {
59                 // if there are multiple suggestions, print them all in full
60                 // to be consistent. We could try to figure out if we can
61                 // make one (or the first one) inline, but that would give
62                 // undue importance to a semi-random suggestion
63                 for sugg in &db.suggestions {
64                     children.push(SubDiagnostic {
65                         level: Level::Help,
66                         message: Vec::new(),
67                         span: MultiSpan::new(),
68                         render_span: Some(Suggestion(sugg.clone())),
69                     });
70                 }
71             }
72         }
73
74         self.fix_multispans_in_std_macros(&mut primary_span, &mut children);
75         self.emit_messages_default(&db.level,
76                                    &db.styled_message(),
77                                    &db.code,
78                                    &primary_span,
79                                    &children);
80     }
81 }
82
83 /// maximum number of lines we will print for each error; arbitrary.
84 pub const MAX_HIGHLIGHT_LINES: usize = 6;
85 /// maximum number of suggestions to be shown
86 ///
87 /// Arbitrary, but taken from trait import suggestion limit
88 pub const MAX_SUGGESTIONS: usize = 4;
89
90 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
91 pub enum ColorConfig {
92     Auto,
93     Always,
94     Never,
95 }
96
97 impl ColorConfig {
98     fn use_color(&self) -> bool {
99         match *self {
100             ColorConfig::Always => true,
101             ColorConfig::Never => false,
102             ColorConfig::Auto => stderr_isatty(),
103         }
104     }
105 }
106
107 pub struct EmitterWriter {
108     dst: Destination,
109     cm: Option<Rc<CodeMapper>>,
110     short_message: bool,
111 }
112
113 struct FileWithAnnotatedLines {
114     file: Rc<FileMap>,
115     lines: Vec<Line>,
116     multiline_depth: usize,
117 }
118
119 impl EmitterWriter {
120     pub fn stderr(color_config: ColorConfig,
121                   code_map: Option<Rc<CodeMapper>>,
122                   short_message: bool)
123                   -> EmitterWriter {
124         if color_config.use_color() {
125             let dst = Destination::from_stderr();
126             EmitterWriter {
127                 dst,
128                 cm: code_map,
129                 short_message: short_message,
130             }
131         } else {
132             EmitterWriter {
133                 dst: Raw(Box::new(io::stderr())),
134                 cm: code_map,
135                 short_message: short_message,
136             }
137         }
138     }
139
140     pub fn new(dst: Box<Write + Send>,
141                code_map: Option<Rc<CodeMapper>>,
142                short_message: bool)
143                -> EmitterWriter {
144         EmitterWriter {
145             dst: Raw(dst),
146             cm: code_map,
147             short_message: short_message,
148         }
149     }
150
151     fn preprocess_annotations(&mut self, msp: &MultiSpan) -> Vec<FileWithAnnotatedLines> {
152         fn add_annotation_to_file(file_vec: &mut Vec<FileWithAnnotatedLines>,
153                                   file: Rc<FileMap>,
154                                   line_index: usize,
155                                   ann: Annotation) {
156
157             for slot in file_vec.iter_mut() {
158                 // Look through each of our files for the one we're adding to
159                 if slot.file.name == file.name {
160                     // See if we already have a line for it
161                     for line_slot in &mut slot.lines {
162                         if line_slot.line_index == line_index {
163                             line_slot.annotations.push(ann);
164                             return;
165                         }
166                     }
167                     // We don't have a line yet, create one
168                     slot.lines.push(Line {
169                         line_index,
170                         annotations: vec![ann],
171                     });
172                     slot.lines.sort();
173                     return;
174                 }
175             }
176             // This is the first time we're seeing the file
177             file_vec.push(FileWithAnnotatedLines {
178                 file,
179                 lines: vec![Line {
180                                 line_index,
181                                 annotations: vec![ann],
182                             }],
183                 multiline_depth: 0,
184             });
185         }
186
187         let mut output = vec![];
188         let mut multiline_annotations = vec![];
189
190         if let Some(ref cm) = self.cm {
191             for span_label in msp.span_labels() {
192                 if span_label.span == DUMMY_SP {
193                     continue;
194                 }
195
196                 let lo = cm.lookup_char_pos(span_label.span.lo());
197                 let mut hi = cm.lookup_char_pos(span_label.span.hi());
198
199                 // Watch out for "empty spans". If we get a span like 6..6, we
200                 // want to just display a `^` at 6, so convert that to
201                 // 6..7. This is degenerate input, but it's best to degrade
202                 // gracefully -- and the parser likes to supply a span like
203                 // that for EOF, in particular.
204                 if lo.col_display == hi.col_display && lo.line == hi.line {
205                     hi.col_display += 1;
206                 }
207
208                 let ann_type = if lo.line != hi.line {
209                     let ml = MultilineAnnotation {
210                         depth: 1,
211                         line_start: lo.line,
212                         line_end: hi.line,
213                         start_col: lo.col_display,
214                         end_col: hi.col_display,
215                         is_primary: span_label.is_primary,
216                         label: span_label.label.clone(),
217                     };
218                     multiline_annotations.push((lo.file.clone(), ml.clone()));
219                     AnnotationType::Multiline(ml)
220                 } else {
221                     AnnotationType::Singleline
222                 };
223                 let ann = Annotation {
224                     start_col: lo.col_display,
225                     end_col: hi.col_display,
226                     is_primary: span_label.is_primary,
227                     label: span_label.label.clone(),
228                     annotation_type: ann_type,
229                 };
230
231                 if !ann.is_multiline() {
232                     add_annotation_to_file(&mut output,
233                                            lo.file,
234                                            lo.line,
235                                            ann);
236                 }
237             }
238         }
239
240         // Find overlapping multiline annotations, put them at different depths
241         multiline_annotations.sort_by(|a, b| {
242             (a.1.line_start, a.1.line_end).cmp(&(b.1.line_start, b.1.line_end))
243         });
244         for item in multiline_annotations.clone() {
245             let ann = item.1;
246             for item in multiline_annotations.iter_mut() {
247                 let ref mut a = item.1;
248                 // Move all other multiline annotations overlapping with this one
249                 // one level to the right.
250                 if &ann != a &&
251                     num_overlap(ann.line_start, ann.line_end, a.line_start, a.line_end, true)
252                 {
253                     a.increase_depth();
254                 } else {
255                     break;
256                 }
257             }
258         }
259
260         let mut max_depth = 0;  // max overlapping multiline spans
261         for (file, ann) in multiline_annotations {
262             if ann.depth > max_depth {
263                 max_depth = ann.depth;
264             }
265             add_annotation_to_file(&mut output, file.clone(), ann.line_start, ann.as_start());
266             let middle = min(ann.line_start + 4, ann.line_end);
267             for line in ann.line_start + 1..middle {
268                 add_annotation_to_file(&mut output, file.clone(), line, ann.as_line());
269             }
270             if middle < ann.line_end - 1 {
271                 for line in ann.line_end - 1..ann.line_end {
272                     add_annotation_to_file(&mut output, file.clone(), line, ann.as_line());
273                 }
274             }
275             add_annotation_to_file(&mut output, file, ann.line_end, ann.as_end());
276         }
277         for file_vec in output.iter_mut() {
278             file_vec.multiline_depth = max_depth;
279         }
280         output
281     }
282
283     fn render_source_line(&self,
284                           buffer: &mut StyledBuffer,
285                           file: Rc<FileMap>,
286                           line: &Line,
287                           width_offset: usize,
288                           code_offset: usize) -> Vec<(usize, Style)> {
289         let source_string = match file.get_line(line.line_index - 1) {
290             Some(s) => s,
291             None => return Vec::new(),
292         };
293
294         let line_offset = buffer.num_lines();
295
296         // First create the source line we will highlight.
297         buffer.puts(line_offset, code_offset, &source_string, Style::Quotation);
298         buffer.puts(line_offset,
299                     0,
300                     &(line.line_index.to_string()),
301                     Style::LineNumber);
302
303         draw_col_separator(buffer, line_offset, width_offset - 2);
304
305         // Special case when there's only one annotation involved, it is the start of a multiline
306         // span and there's no text at the beginning of the code line. Instead of doing the whole
307         // graph:
308         //
309         // 2 |   fn foo() {
310         //   |  _^
311         // 3 | |
312         // 4 | | }
313         //   | |_^ test
314         //
315         // we simplify the output to:
316         //
317         // 2 | / fn foo() {
318         // 3 | |
319         // 4 | | }
320         //   | |_^ test
321         if line.annotations.len() == 1 {
322             if let Some(ref ann) = line.annotations.get(0) {
323                 if let AnnotationType::MultilineStart(depth) = ann.annotation_type {
324                     if source_string.chars()
325                                     .take(ann.start_col)
326                                     .all(|c| c.is_whitespace()) {
327                         let style = if ann.is_primary {
328                             Style::UnderlinePrimary
329                         } else {
330                             Style::UnderlineSecondary
331                         };
332                         buffer.putc(line_offset,
333                                     width_offset + depth - 1,
334                                     '/',
335                                     style);
336                         return vec![(depth, style)];
337                     }
338                 }
339             }
340         }
341
342         // We want to display like this:
343         //
344         //      vec.push(vec.pop().unwrap());
345         //      ---      ^^^               - previous borrow ends here
346         //      |        |
347         //      |        error occurs here
348         //      previous borrow of `vec` occurs here
349         //
350         // But there are some weird edge cases to be aware of:
351         //
352         //      vec.push(vec.pop().unwrap());
353         //      --------                    - previous borrow ends here
354         //      ||
355         //      |this makes no sense
356         //      previous borrow of `vec` occurs here
357         //
358         // For this reason, we group the lines into "highlight lines"
359         // and "annotations lines", where the highlight lines have the `^`.
360
361         // Sort the annotations by (start, end col)
362         // The labels are reversed, sort and then reversed again.
363         // Consider a list of annotations (A1, A2, C1, C2, B1, B2) where
364         // the letter signifies the span. Here we are only sorting by the
365         // span and hence, the order of the elements with the same span will
366         // not change. On reversing the ordering (|a, b| but b.cmp(a)), you get
367         // (C1, C2, B1, B2, A1, A2). All the elements with the same span are
368         // still ordered first to last, but all the elements with different
369         // spans are ordered by their spans in last to first order. Last to
370         // first order is important, because the jiggly lines and | are on
371         // the left, so the rightmost span needs to be rendered first,
372         // otherwise the lines would end up needing to go over a message.
373
374         let mut annotations = line.annotations.clone();
375         annotations.sort_by(|a,b| b.start_col.cmp(&a.start_col));
376
377         // First, figure out where each label will be positioned.
378         //
379         // In the case where you have the following annotations:
380         //
381         //      vec.push(vec.pop().unwrap());
382         //      --------                    - previous borrow ends here [C]
383         //      ||
384         //      |this makes no sense [B]
385         //      previous borrow of `vec` occurs here [A]
386         //
387         // `annotations_position` will hold [(2, A), (1, B), (0, C)].
388         //
389         // We try, when possible, to stick the rightmost annotation at the end
390         // of the highlight line:
391         //
392         //      vec.push(vec.pop().unwrap());
393         //      ---      ---               - previous borrow ends here
394         //
395         // But sometimes that's not possible because one of the other
396         // annotations overlaps it. For example, from the test
397         // `span_overlap_label`, we have the following annotations
398         // (written on distinct lines for clarity):
399         //
400         //      fn foo(x: u32) {
401         //      --------------
402         //             -
403         //
404         // In this case, we can't stick the rightmost-most label on
405         // the highlight line, or we would get:
406         //
407         //      fn foo(x: u32) {
408         //      -------- x_span
409         //      |
410         //      fn_span
411         //
412         // which is totally weird. Instead we want:
413         //
414         //      fn foo(x: u32) {
415         //      --------------
416         //      |      |
417         //      |      x_span
418         //      fn_span
419         //
420         // which is...less weird, at least. In fact, in general, if
421         // the rightmost span overlaps with any other span, we should
422         // use the "hang below" version, so we can at least make it
423         // clear where the span *starts*. There's an exception for this
424         // logic, when the labels do not have a message:
425         //
426         //      fn foo(x: u32) {
427         //      --------------
428         //             |
429         //             x_span
430         //
431         // instead of:
432         //
433         //      fn foo(x: u32) {
434         //      --------------
435         //      |      |
436         //      |      x_span
437         //      <EMPTY LINE>
438         //
439         let mut annotations_position = vec![];
440         let mut line_len = 0;
441         let mut p = 0;
442         for (i, annotation) in annotations.iter().enumerate() {
443             for (j, next) in annotations.iter().enumerate() {
444                 if overlaps(next, annotation, 0)  // This label overlaps with another one and both
445                     && annotation.has_label()     // take space (they have text and are not
446                     && j > i                      // multiline lines).
447                     && p == 0  // We're currently on the first line, move the label one line down
448                 {
449                     // This annotation needs a new line in the output.
450                     p += 1;
451                     break;
452                 }
453             }
454             annotations_position.push((p, annotation));
455             for (j, next) in annotations.iter().enumerate() {
456                 if j > i  {
457                     let l = if let Some(ref label) = next.label {
458                         label.len() + 2
459                     } else {
460                         0
461                     };
462                     if (overlaps(next, annotation, l) // Do not allow two labels to be in the same
463                                                      // line if they overlap including padding, to
464                                                      // avoid situations like:
465                                                      //
466                                                      //      fn foo(x: u32) {
467                                                      //      -------^------
468                                                      //      |      |
469                                                      //      fn_spanx_span
470                                                      //
471                         && annotation.has_label()    // Both labels must have some text, otherwise
472                         && next.has_label())         // they are not overlapping.
473                                                      // Do not add a new line if this annotation
474                                                      // or the next are vertical line placeholders.
475                         || (annotation.takes_space() // If either this or the next annotation is
476                             && next.has_label())     // multiline start/end, move it to a new line
477                         || (annotation.has_label()   // so as not to overlap the orizontal lines.
478                             && next.takes_space())
479                         || (annotation.takes_space() && next.takes_space())
480                         || (overlaps(next, annotation, l)
481                             && next.end_col <= annotation.end_col
482                             && next.has_label()
483                             && p == 0)  // Avoid #42595.
484                     {
485                         // This annotation needs a new line in the output.
486                         p += 1;
487                         break;
488                     }
489                 }
490             }
491             if line_len < p {
492                 line_len = p;
493             }
494         }
495
496         if line_len != 0 {
497             line_len += 1;
498         }
499
500         // If there are no annotations or the only annotations on this line are
501         // MultilineLine, then there's only code being shown, stop processing.
502         if line.annotations.is_empty() || line.annotations.iter()
503             .filter(|a| !a.is_line()).collect::<Vec<_>>().len() == 0
504         {
505             return vec![];
506         }
507
508         // Write the colunmn separator.
509         //
510         // After this we will have:
511         //
512         // 2 |   fn foo() {
513         //   |
514         //   |
515         //   |
516         // 3 |
517         // 4 |   }
518         //   |
519         for pos in 0..line_len + 1 {
520             draw_col_separator(buffer, line_offset + pos + 1, width_offset - 2);
521             buffer.putc(line_offset + pos + 1,
522                         width_offset - 2,
523                         '|',
524                         Style::LineNumber);
525         }
526
527         // Write the horizontal lines for multiline annotations
528         // (only the first and last lines need this).
529         //
530         // After this we will have:
531         //
532         // 2 |   fn foo() {
533         //   |  __________
534         //   |
535         //   |
536         // 3 |
537         // 4 |   }
538         //   |  _
539         for &(pos, annotation) in &annotations_position {
540             let style = if annotation.is_primary {
541                 Style::UnderlinePrimary
542             } else {
543                 Style::UnderlineSecondary
544             };
545             let pos = pos + 1;
546             match annotation.annotation_type {
547                 AnnotationType::MultilineStart(depth) |
548                 AnnotationType::MultilineEnd(depth) => {
549                     draw_range(buffer,
550                                '_',
551                                line_offset + pos,
552                                width_offset + depth,
553                                code_offset + annotation.start_col,
554                                style);
555                 }
556                 _ => (),
557             }
558         }
559
560         // Write the vertical lines for labels that are on a different line as the underline.
561         //
562         // After this we will have:
563         //
564         // 2 |   fn foo() {
565         //   |  __________
566         //   | |    |
567         //   | |
568         // 3 |
569         // 4 | | }
570         //   | |_
571         for &(pos, annotation) in &annotations_position {
572             let style = if annotation.is_primary {
573                 Style::UnderlinePrimary
574             } else {
575                 Style::UnderlineSecondary
576             };
577             let pos = pos + 1;
578
579             if pos > 1 && (annotation.has_label() || annotation.takes_space()) {
580                 for p in line_offset + 1..line_offset + pos + 1 {
581                     buffer.putc(p,
582                                 code_offset + annotation.start_col,
583                                 '|',
584                                 style);
585                 }
586             }
587             match annotation.annotation_type {
588                 AnnotationType::MultilineStart(depth) => {
589                     for p in line_offset + pos + 1..line_offset + line_len + 2 {
590                         buffer.putc(p,
591                                     width_offset + depth - 1,
592                                     '|',
593                                     style);
594                     }
595                 }
596                 AnnotationType::MultilineEnd(depth) => {
597                     for p in line_offset..line_offset + pos + 1 {
598                         buffer.putc(p,
599                                     width_offset + depth - 1,
600                                     '|',
601                                     style);
602                     }
603                 }
604                 _ => (),
605             }
606         }
607
608         // Write the labels on the annotations that actually have a label.
609         //
610         // After this we will have:
611         //
612         // 2 |   fn foo() {
613         //   |  __________
614         //   |      |
615         //   |      something about `foo`
616         // 3 |
617         // 4 |   }
618         //   |  _  test
619         for &(pos, annotation) in &annotations_position {
620             let style = if annotation.is_primary {
621                 Style::LabelPrimary
622             } else {
623                 Style::LabelSecondary
624             };
625             let (pos, col) = if pos == 0 {
626                 (pos + 1, annotation.end_col + 1)
627             } else {
628                 (pos + 2, annotation.start_col)
629             };
630             if let Some(ref label) = annotation.label {
631                 buffer.puts(line_offset + pos,
632                             code_offset + col,
633                             &label,
634                             style);
635             }
636         }
637
638         // Sort from biggest span to smallest span so that smaller spans are
639         // represented in the output:
640         //
641         // x | fn foo()
642         //   | ^^^---^^
643         //   | |  |
644         //   | |  something about `foo`
645         //   | something about `fn foo()`
646         annotations_position.sort_by(|a, b| {
647             // Decreasing order
648             a.1.len().cmp(&b.1.len()).reverse()
649         });
650
651         // Write the underlines.
652         //
653         // After this we will have:
654         //
655         // 2 |   fn foo() {
656         //   |  ____-_____^
657         //   |      |
658         //   |      something about `foo`
659         // 3 |
660         // 4 |   }
661         //   |  _^  test
662         for &(_, annotation) in &annotations_position {
663             let (underline, style) = if annotation.is_primary {
664                 ('^', Style::UnderlinePrimary)
665             } else {
666                 ('-', Style::UnderlineSecondary)
667             };
668             for p in annotation.start_col..annotation.end_col {
669                 buffer.putc(line_offset + 1,
670                             code_offset + p,
671                             underline,
672                             style);
673             }
674         }
675         annotations_position.iter().filter_map(|&(_, annotation)| {
676             match annotation.annotation_type {
677                 AnnotationType::MultilineStart(p) | AnnotationType::MultilineEnd(p) => {
678                     let style = if annotation.is_primary {
679                         Style::LabelPrimary
680                     } else {
681                         Style::LabelSecondary
682                     };
683                     Some((p, style))
684                 }
685                 _ => None
686             }
687
688         }).collect::<Vec<_>>()
689     }
690
691     fn get_multispan_max_line_num(&mut self, msp: &MultiSpan) -> usize {
692         let mut max = 0;
693         if let Some(ref cm) = self.cm {
694             for primary_span in msp.primary_spans() {
695                 if primary_span != &DUMMY_SP {
696                     let hi = cm.lookup_char_pos(primary_span.hi());
697                     if hi.line > max {
698                         max = hi.line;
699                     }
700                 }
701             }
702             if !self.short_message {
703                 for span_label in msp.span_labels() {
704                     if span_label.span != DUMMY_SP {
705                         let hi = cm.lookup_char_pos(span_label.span.hi());
706                         if hi.line > max {
707                             max = hi.line;
708                         }
709                     }
710                 }
711             }
712         }
713         max
714     }
715
716     fn get_max_line_num(&mut self, span: &MultiSpan, children: &Vec<SubDiagnostic>) -> usize {
717         let mut max = 0;
718
719         let primary = self.get_multispan_max_line_num(span);
720         max = if primary > max { primary } else { max };
721
722         for sub in children {
723             let sub_result = self.get_multispan_max_line_num(&sub.span);
724             max = if sub_result > max { primary } else { max };
725         }
726         max
727     }
728
729     // This "fixes" MultiSpans that contain Spans that are pointing to locations inside of
730     // <*macros>. Since these locations are often difficult to read, we move these Spans from
731     // <*macros> to their corresponding use site.
732     fn fix_multispan_in_std_macros(&mut self, span: &mut MultiSpan) -> bool {
733         let mut spans_updated = false;
734
735         if let Some(ref cm) = self.cm {
736             let mut before_after: Vec<(Span, Span)> = vec![];
737             let mut new_labels: Vec<(Span, String)> = vec![];
738
739             // First, find all the spans in <*macros> and point instead at their use site
740             for sp in span.primary_spans() {
741                 if *sp == DUMMY_SP {
742                     continue;
743                 }
744                 let call_sp = cm.call_span_if_macro(*sp);
745                 if call_sp != *sp {
746                     before_after.push((sp.clone(), call_sp));
747                 }
748                 for trace in sp.macro_backtrace().iter().rev() {
749                     // Only show macro locations that are local
750                     // and display them like a span_note
751                     if let Some(def_site) = trace.def_site_span {
752                         if def_site == DUMMY_SP {
753                             continue;
754                         }
755                         // Check to make sure we're not in any <*macros>
756                         if !cm.span_to_filename(def_site).contains("macros>") &&
757                            !trace.macro_decl_name.starts_with("#[") {
758                             new_labels.push((trace.call_site,
759                                              "in this macro invocation".to_string()));
760                             break;
761                         }
762                     }
763                 }
764             }
765             for (label_span, label_text) in new_labels {
766                 span.push_span_label(label_span, label_text);
767             }
768             for sp_label in span.span_labels() {
769                 if sp_label.span == DUMMY_SP {
770                     continue;
771                 }
772                 if cm.span_to_filename(sp_label.span.clone()).contains("macros>") {
773                     let v = sp_label.span.macro_backtrace();
774                     if let Some(use_site) = v.last() {
775                         before_after.push((sp_label.span.clone(), use_site.call_site.clone()));
776                     }
777                 }
778             }
779             // After we have them, make sure we replace these 'bad' def sites with their use sites
780             for (before, after) in before_after {
781                 span.replace(before, after);
782                 spans_updated = true;
783             }
784         }
785
786         spans_updated
787     }
788
789     // This does a small "fix" for multispans by looking to see if it can find any that
790     // point directly at <*macros>. Since these are often difficult to read, this
791     // will change the span to point at the use site.
792     fn fix_multispans_in_std_macros(&mut self,
793                                     span: &mut MultiSpan,
794                                     children: &mut Vec<SubDiagnostic>) {
795         let mut spans_updated = self.fix_multispan_in_std_macros(span);
796         for child in children.iter_mut() {
797             spans_updated |= self.fix_multispan_in_std_macros(&mut child.span);
798         }
799         if spans_updated {
800             children.push(SubDiagnostic {
801                 level: Level::Note,
802                 message: vec![("this error originates in a macro outside of the current crate"
803                     .to_string(), Style::NoStyle)],
804                 span: MultiSpan::new(),
805                 render_span: None,
806             });
807         }
808     }
809
810     /// Add a left margin to every line but the first, given a padding length and the label being
811     /// displayed, keeping the provided highlighting.
812     fn msg_to_buffer(&self,
813                      buffer: &mut StyledBuffer,
814                      msg: &[(String, Style)],
815                      padding: usize,
816                      label: &str,
817                      override_style: Option<Style>) {
818
819         // The extra 5 ` ` is padding that's always needed to align to the `note: `:
820         //
821         //   error: message
822         //     --> file.rs:13:20
823         //      |
824         //   13 |     <CODE>
825         //      |      ^^^^
826         //      |
827         //      = note: multiline
828         //              message
829         //   ++^^^----xx
830         //    |  |   | |
831         //    |  |   | magic `2`
832         //    |  |   length of label
833         //    |  magic `3`
834         //    `max_line_num_len`
835         let padding = (0..padding + label.len() + 5)
836             .map(|_| " ")
837             .collect::<String>();
838
839         /// Return whether `style`, or the override if present and the style is `NoStyle`.
840         fn style_or_override(style: Style, override_style: Option<Style>) -> Style {
841             if let Some(o) = override_style {
842                 if style == Style::NoStyle {
843                     return o;
844                 }
845             }
846             style
847         }
848
849         let mut line_number = 0;
850
851         // Provided the following diagnostic message:
852         //
853         //     let msg = vec![
854         //       ("
855         //       ("highlighted multiline\nstring to\nsee how it ", Style::NoStyle),
856         //       ("looks", Style::Highlight),
857         //       ("with\nvery ", Style::NoStyle),
858         //       ("weird", Style::Highlight),
859         //       (" formats\n", Style::NoStyle),
860         //       ("see?", Style::Highlight),
861         //     ];
862         //
863         // the expected output on a note is (* surround the  highlighted text)
864         //
865         //        = note: highlighted multiline
866         //                string to
867         //                see how it *looks* with
868         //                very *weird* formats
869         //                see?
870         for &(ref text, ref style) in msg.iter() {
871             let lines = text.split('\n').collect::<Vec<_>>();
872             if lines.len() > 1 {
873                 for (i, line) in lines.iter().enumerate() {
874                     if i != 0 {
875                         line_number += 1;
876                         buffer.append(line_number, &padding, Style::NoStyle);
877                     }
878                     buffer.append(line_number, line, style_or_override(*style, override_style));
879                 }
880             } else {
881                 buffer.append(line_number, text, style_or_override(*style, override_style));
882             }
883         }
884     }
885
886     fn emit_message_default(&mut self,
887                             msp: &MultiSpan,
888                             msg: &Vec<(String, Style)>,
889                             code: &Option<DiagnosticId>,
890                             level: &Level,
891                             max_line_num_len: usize,
892                             is_secondary: bool)
893                             -> io::Result<()> {
894         let mut buffer = StyledBuffer::new();
895
896         if msp.primary_spans().is_empty() && msp.span_labels().is_empty() && is_secondary
897            && !self.short_message {
898             // This is a secondary message with no span info
899             for _ in 0..max_line_num_len {
900                 buffer.prepend(0, " ", Style::NoStyle);
901             }
902             draw_note_separator(&mut buffer, 0, max_line_num_len + 1);
903             buffer.append(0, &level.to_string(), Style::HeaderMsg);
904             buffer.append(0, ": ", Style::NoStyle);
905             self.msg_to_buffer(&mut buffer, msg, max_line_num_len, "note", None);
906         } else {
907             buffer.append(0, &level.to_string(), Style::Level(level.clone()));
908             // only render error codes, not lint codes
909             if let Some(DiagnosticId::Error(ref code)) = *code {
910                 buffer.append(0, "[", Style::Level(level.clone()));
911                 buffer.append(0, &code, Style::Level(level.clone()));
912                 buffer.append(0, "]", Style::Level(level.clone()));
913             }
914             buffer.append(0, ": ", Style::HeaderMsg);
915             for &(ref text, _) in msg.iter() {
916                 buffer.append(0, text, Style::HeaderMsg);
917             }
918         }
919
920         // Preprocess all the annotations so that they are grouped by file and by line number
921         // This helps us quickly iterate over the whole message (including secondary file spans)
922         let mut annotated_files = self.preprocess_annotations(msp);
923
924         // Make sure our primary file comes first
925         let (primary_lo, cm) = if let (Some(cm), Some(ref primary_span)) =
926             (self.cm.as_ref(), msp.primary_span().as_ref()) {
927             if primary_span != &&DUMMY_SP {
928                 (cm.lookup_char_pos(primary_span.lo()), cm)
929             } else {
930                 emit_to_destination(&buffer.render(), level, &mut self.dst, self.short_message)?;
931                 return Ok(());
932             }
933         } else {
934             // If we don't have span information, emit and exit
935             emit_to_destination(&buffer.render(), level, &mut self.dst, self.short_message)?;
936             return Ok(());
937         };
938         if let Ok(pos) =
939             annotated_files.binary_search_by(|x| x.file.name.cmp(&primary_lo.file.name)) {
940             annotated_files.swap(0, pos);
941         }
942
943         // Print out the annotate source lines that correspond with the error
944         for annotated_file in annotated_files {
945             // we can't annotate anything if the source is unavailable.
946             if !cm.ensure_filemap_source_present(annotated_file.file.clone()) {
947                 continue;
948             }
949
950             // print out the span location and spacer before we print the annotated source
951             // to do this, we need to know if this span will be primary
952             let is_primary = primary_lo.file.name == annotated_file.file.name;
953             if is_primary {
954                 let loc = primary_lo.clone();
955                 if !self.short_message {
956                     // remember where we are in the output buffer for easy reference
957                     let buffer_msg_line_offset = buffer.num_lines();
958
959                     buffer.prepend(buffer_msg_line_offset, "--> ", Style::LineNumber);
960                     buffer.append(buffer_msg_line_offset,
961                                   &format!("{}:{}:{}", loc.file.name, loc.line, loc.col.0 + 1),
962                                   Style::LineAndColumn);
963                     for _ in 0..max_line_num_len {
964                         buffer.prepend(buffer_msg_line_offset, " ", Style::NoStyle);
965                     }
966                 } else {
967                     buffer.prepend(0,
968                                    &format!("{}:{}:{} - ", loc.file.name, loc.line, loc.col.0 + 1),
969                                    Style::LineAndColumn);
970                 }
971             } else if !self.short_message {
972                 // remember where we are in the output buffer for easy reference
973                 let buffer_msg_line_offset = buffer.num_lines();
974
975                 // Add spacing line
976                 draw_col_separator(&mut buffer, buffer_msg_line_offset, max_line_num_len + 1);
977
978                 // Then, the secondary file indicator
979                 buffer.prepend(buffer_msg_line_offset + 1, "::: ", Style::LineNumber);
980                 buffer.append(buffer_msg_line_offset + 1,
981                               &annotated_file.file.name,
982                               Style::LineAndColumn);
983                 for _ in 0..max_line_num_len {
984                     buffer.prepend(buffer_msg_line_offset + 1, " ", Style::NoStyle);
985                 }
986             }
987
988             if !self.short_message {
989                 // Put in the spacer between the location and annotated source
990                 let buffer_msg_line_offset = buffer.num_lines();
991                 draw_col_separator_no_space(&mut buffer,
992                                             buffer_msg_line_offset,
993                                             max_line_num_len + 1);
994
995                 // Contains the vertical lines' positions for active multiline annotations
996                 let mut multilines = HashMap::new();
997
998                 // Next, output the annotate source for this file
999                 for line_idx in 0..annotated_file.lines.len() {
1000                     let previous_buffer_line = buffer.num_lines();
1001
1002                     let width_offset = 3 + max_line_num_len;
1003                     let code_offset = if annotated_file.multiline_depth == 0 {
1004                         width_offset
1005                     } else {
1006                         width_offset + annotated_file.multiline_depth + 1
1007                     };
1008
1009                     let depths = self.render_source_line(&mut buffer,
1010                                                          annotated_file.file.clone(),
1011                                                          &annotated_file.lines[line_idx],
1012                                                          width_offset,
1013                                                          code_offset);
1014
1015                     let mut to_add = HashMap::new();
1016
1017                     for (depth, style) in depths {
1018                         if multilines.get(&depth).is_some() {
1019                             multilines.remove(&depth);
1020                         } else {
1021                             to_add.insert(depth, style);
1022                         }
1023                     }
1024
1025                     // Set the multiline annotation vertical lines to the left of
1026                     // the code in this line.
1027                     for (depth, style) in &multilines {
1028                         for line in previous_buffer_line..buffer.num_lines() {
1029                             draw_multiline_line(&mut buffer,
1030                                                 line,
1031                                                 width_offset,
1032                                                 *depth,
1033                                                 *style);
1034                         }
1035                     }
1036                     // check to see if we need to print out or elide lines that come between
1037                     // this annotated line and the next one.
1038                     if line_idx < (annotated_file.lines.len() - 1) {
1039                         let line_idx_delta = annotated_file.lines[line_idx + 1].line_index -
1040                                              annotated_file.lines[line_idx].line_index;
1041                         if line_idx_delta > 2 {
1042                             let last_buffer_line_num = buffer.num_lines();
1043                             buffer.puts(last_buffer_line_num, 0, "...", Style::LineNumber);
1044
1045                             // Set the multiline annotation vertical lines on `...` bridging line.
1046                             for (depth, style) in &multilines {
1047                                 draw_multiline_line(&mut buffer,
1048                                                     last_buffer_line_num,
1049                                                     width_offset,
1050                                                     *depth,
1051                                                     *style);
1052                             }
1053                         } else if line_idx_delta == 2 {
1054                             let unannotated_line = annotated_file.file
1055                                 .get_line(annotated_file.lines[line_idx].line_index)
1056                                 .unwrap_or_else(|| Cow::from(""));
1057
1058                             let last_buffer_line_num = buffer.num_lines();
1059
1060                             buffer.puts(last_buffer_line_num,
1061                                         0,
1062                                         &(annotated_file.lines[line_idx + 1].line_index - 1)
1063                                             .to_string(),
1064                                         Style::LineNumber);
1065                             draw_col_separator(&mut buffer,
1066                                                last_buffer_line_num,
1067                                                1 + max_line_num_len);
1068                             buffer.puts(last_buffer_line_num,
1069                                         code_offset,
1070                                         &unannotated_line,
1071                                         Style::Quotation);
1072
1073                             for (depth, style) in &multilines {
1074                                 draw_multiline_line(&mut buffer,
1075                                                     last_buffer_line_num,
1076                                                     width_offset,
1077                                                     *depth,
1078                                                     *style);
1079                             }
1080                         }
1081                     }
1082
1083                     multilines.extend(&to_add);
1084                 }
1085             }
1086         }
1087
1088         // final step: take our styled buffer, render it, then output it
1089         emit_to_destination(&buffer.render(), level, &mut self.dst, self.short_message)?;
1090
1091         Ok(())
1092
1093     }
1094     fn emit_suggestion_default(&mut self,
1095                                suggestion: &CodeSuggestion,
1096                                level: &Level,
1097                                max_line_num_len: usize)
1098                                -> io::Result<()> {
1099         use std::borrow::Borrow;
1100
1101         if let Some(ref cm) = self.cm {
1102             let mut buffer = StyledBuffer::new();
1103
1104             // Render the suggestion message
1105             buffer.append(0, &level.to_string(), Style::Level(level.clone()));
1106             buffer.append(0, ": ", Style::HeaderMsg);
1107             self.msg_to_buffer(&mut buffer,
1108                                &[(suggestion.msg.to_owned(), Style::NoStyle)],
1109                                max_line_num_len,
1110                                "suggestion",
1111                                Some(Style::HeaderMsg));
1112
1113             // Render the replacements for each suggestion
1114             let suggestions = suggestion.splice_lines(cm.borrow());
1115
1116             let mut row_num = 2;
1117             for &(ref complete, ref parts) in suggestions.iter().take(MAX_SUGGESTIONS) {
1118                 let show_underline = parts.len() == 1
1119                     && complete.lines().count() == 1
1120                     && parts[0].snippet.trim() != complete.trim();
1121
1122                 let lines = cm.span_to_lines(parts[0].span).unwrap();
1123
1124                 assert!(!lines.lines.is_empty());
1125
1126                 let span_start_pos = cm.lookup_char_pos(parts[0].span.lo());
1127                 let line_start = span_start_pos.line;
1128                 draw_col_separator_no_space(&mut buffer, 1, max_line_num_len + 1);
1129                 let mut line_pos = 0;
1130                 // Only show underline if there's a single suggestion and it is a single line
1131                 let mut lines = complete.lines();
1132                 for line in lines.by_ref().take(MAX_HIGHLIGHT_LINES) {
1133                     // Print the span column to avoid confusion
1134                     buffer.puts(row_num,
1135                                 0,
1136                                 &((line_start + line_pos).to_string()),
1137                                 Style::LineNumber);
1138                     // print the suggestion
1139                     draw_col_separator(&mut buffer, row_num, max_line_num_len + 1);
1140                     buffer.append(row_num, line, Style::NoStyle);
1141                     line_pos += 1;
1142                     row_num += 1;
1143                 }
1144                 // Only show an underline in the suggestions if the suggestion is not the
1145                 // entirety of the code being shown and the displayed code is not multiline.
1146                 if show_underline {
1147                     draw_col_separator(&mut buffer, row_num, max_line_num_len + 1);
1148                     let start = parts[0].snippet.len() - parts[0].snippet.trim_left().len();
1149                     let sub_len = parts[0].snippet.trim().len();
1150                     let underline_start = span_start_pos.col.0 + start;
1151                     let underline_end = span_start_pos.col.0 + sub_len;
1152                     for p in underline_start..underline_end {
1153                         buffer.putc(row_num,
1154                                     max_line_num_len + 3 + p,
1155                                     '^',
1156                                     Style::UnderlinePrimary);
1157                     }
1158                     row_num += 1;
1159                 }
1160
1161                 // if we elided some lines, add an ellipsis
1162                 if let Some(_) = lines.next() {
1163                     buffer.puts(row_num, max_line_num_len - 1, "...", Style::LineNumber);
1164                 } else if !show_underline {
1165                     draw_col_separator_no_space(&mut buffer, row_num, max_line_num_len + 1);
1166                     row_num += 1;
1167                 }
1168             }
1169             if suggestions.len() > MAX_SUGGESTIONS {
1170                 let msg = format!("and {} other candidates", suggestions.len() - MAX_SUGGESTIONS);
1171                 buffer.puts(row_num, 0, &msg, Style::NoStyle);
1172             }
1173             emit_to_destination(&buffer.render(), level, &mut self.dst, self.short_message)?;
1174         }
1175         Ok(())
1176     }
1177     fn emit_messages_default(&mut self,
1178                              level: &Level,
1179                              message: &Vec<(String, Style)>,
1180                              code: &Option<DiagnosticId>,
1181                              span: &MultiSpan,
1182                              children: &Vec<SubDiagnostic>) {
1183         let max_line_num = self.get_max_line_num(span, children);
1184         let max_line_num_len = max_line_num.to_string().len();
1185
1186         match self.emit_message_default(span, message, code, level, max_line_num_len, false) {
1187             Ok(()) => {
1188                 if !children.is_empty() {
1189                     let mut buffer = StyledBuffer::new();
1190                     if !self.short_message {
1191                         draw_col_separator_no_space(&mut buffer, 0, max_line_num_len + 1);
1192                     }
1193                     match emit_to_destination(&buffer.render(), level, &mut self.dst,
1194                                               self.short_message) {
1195                         Ok(()) => (),
1196                         Err(e) => panic!("failed to emit error: {}", e)
1197                     }
1198                 }
1199                 if !self.short_message {
1200                     for child in children {
1201                         match child.render_span {
1202                             Some(FullSpan(ref msp)) => {
1203                                 match self.emit_message_default(msp,
1204                                                                 &child.styled_message(),
1205                                                                 &None,
1206                                                                 &child.level,
1207                                                                 max_line_num_len,
1208                                                                 true) {
1209                                     Err(e) => panic!("failed to emit error: {}", e),
1210                                     _ => ()
1211                                 }
1212                             }
1213                             Some(Suggestion(ref cs)) => {
1214                                 match self.emit_suggestion_default(cs,
1215                                                                    &child.level,
1216                                                                    max_line_num_len) {
1217                                     Err(e) => panic!("failed to emit error: {}", e),
1218                                     _ => ()
1219                                 }
1220                             }
1221                             None => {
1222                                 match self.emit_message_default(&child.span,
1223                                                                 &child.styled_message(),
1224                                                                 &None,
1225                                                                 &child.level,
1226                                                                 max_line_num_len,
1227                                                                 true) {
1228                                     Err(e) => panic!("failed to emit error: {}", e),
1229                                     _ => (),
1230                                 }
1231                             }
1232                         }
1233                     }
1234                 }
1235             }
1236             Err(e) => panic!("failed to emit error: {}", e),
1237         }
1238         match write!(&mut self.dst, "\n") {
1239             Err(e) => panic!("failed to emit error: {}", e),
1240             _ => {
1241                 match self.dst.flush() {
1242                     Err(e) => panic!("failed to emit error: {}", e),
1243                     _ => (),
1244                 }
1245             }
1246         }
1247     }
1248 }
1249
1250 fn draw_col_separator(buffer: &mut StyledBuffer, line: usize, col: usize) {
1251     buffer.puts(line, col, "| ", Style::LineNumber);
1252 }
1253
1254 fn draw_col_separator_no_space(buffer: &mut StyledBuffer, line: usize, col: usize) {
1255     draw_col_separator_no_space_with_style(buffer, line, col, Style::LineNumber);
1256 }
1257
1258 fn draw_col_separator_no_space_with_style(buffer: &mut StyledBuffer,
1259                                           line: usize,
1260                                           col: usize,
1261                                           style: Style) {
1262     buffer.putc(line, col, '|', style);
1263 }
1264
1265 fn draw_range(buffer: &mut StyledBuffer, symbol: char, line: usize,
1266               col_from: usize, col_to: usize, style: Style) {
1267     for col in col_from..col_to {
1268         buffer.putc(line, col, symbol, style);
1269     }
1270 }
1271
1272 fn draw_note_separator(buffer: &mut StyledBuffer, line: usize, col: usize) {
1273     buffer.puts(line, col, "= ", Style::LineNumber);
1274 }
1275
1276 fn draw_multiline_line(buffer: &mut StyledBuffer,
1277                        line: usize,
1278                        offset: usize,
1279                        depth: usize,
1280                        style: Style)
1281 {
1282     buffer.putc(line, offset + depth - 1, '|', style);
1283 }
1284
1285 fn num_overlap(a_start: usize, a_end: usize, b_start: usize, b_end:usize, inclusive: bool) -> bool {
1286     let extra = if inclusive {
1287         1
1288     } else {
1289         0
1290     };
1291     (b_start..b_end + extra).contains(a_start) ||
1292     (a_start..a_end + extra).contains(b_start)
1293 }
1294 fn overlaps(a1: &Annotation, a2: &Annotation, padding: usize) -> bool {
1295     num_overlap(a1.start_col, a1.end_col + padding, a2.start_col, a2.end_col, false)
1296 }
1297
1298 fn emit_to_destination(rendered_buffer: &Vec<Vec<StyledString>>,
1299                        lvl: &Level,
1300                        dst: &mut Destination,
1301                        short_message: bool)
1302                        -> io::Result<()> {
1303     use lock;
1304
1305     // In order to prevent error message interleaving, where multiple error lines get intermixed
1306     // when multiple compiler processes error simultaneously, we emit errors with additional
1307     // steps.
1308     //
1309     // On Unix systems, we write into a buffered terminal rather than directly to a terminal. When
1310     // the .flush() is called we take the buffer created from the buffered writes and write it at
1311     // one shot.  Because the Unix systems use ANSI for the colors, which is a text-based styling
1312     // scheme, this buffered approach works and maintains the styling.
1313     //
1314     // On Windows, styling happens through calls to a terminal API. This prevents us from using the
1315     // same buffering approach.  Instead, we use a global Windows mutex, which we acquire long
1316     // enough to output the full error message, then we release.
1317     let _buffer_lock = lock::acquire_global_lock("rustc_errors");
1318     for line in rendered_buffer {
1319         for part in line {
1320             dst.apply_style(lvl.clone(), part.style)?;
1321             write!(dst, "{}", part.text)?;
1322             dst.reset_attrs()?;
1323         }
1324         if !short_message {
1325             write!(dst, "\n")?;
1326         }
1327     }
1328     dst.flush()?;
1329     Ok(())
1330 }
1331
1332 #[cfg(unix)]
1333 fn stderr_isatty() -> bool {
1334     use libc;
1335     unsafe { libc::isatty(libc::STDERR_FILENO) != 0 }
1336 }
1337 #[cfg(windows)]
1338 fn stderr_isatty() -> bool {
1339     type DWORD = u32;
1340     type BOOL = i32;
1341     type HANDLE = *mut u8;
1342     const STD_ERROR_HANDLE: DWORD = -12i32 as DWORD;
1343     extern "system" {
1344         fn GetStdHandle(which: DWORD) -> HANDLE;
1345         fn GetConsoleMode(hConsoleHandle: HANDLE, lpMode: *mut DWORD) -> BOOL;
1346     }
1347     unsafe {
1348         let handle = GetStdHandle(STD_ERROR_HANDLE);
1349         let mut out = 0;
1350         GetConsoleMode(handle, &mut out) != 0
1351     }
1352 }
1353
1354 pub type BufferedStderr = term::Terminal<Output = BufferedWriter> + Send;
1355
1356 pub enum Destination {
1357     Terminal(Box<term::StderrTerminal>),
1358     BufferedTerminal(Box<BufferedStderr>),
1359     Raw(Box<Write + Send>),
1360 }
1361
1362 /// Buffered writer gives us a way on Unix to buffer up an entire error message before we output
1363 /// it.  This helps to prevent interleaving of multiple error messages when multiple compiler
1364 /// processes error simultaneously
1365 pub struct BufferedWriter {
1366     buffer: Vec<u8>,
1367 }
1368
1369 impl BufferedWriter {
1370     // note: we use _new because the conditional compilation at its use site may make this
1371     // this function unused on some platforms
1372     fn _new() -> BufferedWriter {
1373         BufferedWriter { buffer: vec![] }
1374     }
1375 }
1376
1377 impl Write for BufferedWriter {
1378     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
1379         for b in buf {
1380             self.buffer.push(*b);
1381         }
1382         Ok(buf.len())
1383     }
1384     fn flush(&mut self) -> io::Result<()> {
1385         let mut stderr = io::stderr();
1386         let result = stderr.write_all(&self.buffer)
1387                            .and_then(|_| stderr.flush());
1388         self.buffer.clear();
1389         result
1390     }
1391 }
1392
1393 impl Destination {
1394     #[cfg(not(windows))]
1395     /// When not on Windows, prefer the buffered terminal so that we can buffer an entire error
1396     /// to be emitted at one time.
1397     fn from_stderr() -> Destination {
1398         let stderr: Option<Box<BufferedStderr>> =
1399             term::TerminfoTerminal::new(BufferedWriter::_new())
1400                 .map(|t| Box::new(t) as Box<BufferedStderr>);
1401
1402         match stderr {
1403             Some(t) => BufferedTerminal(t),
1404             None => Raw(Box::new(io::stderr())),
1405         }
1406     }
1407
1408     #[cfg(windows)]
1409     /// Return a normal, unbuffered terminal when on Windows.
1410     fn from_stderr() -> Destination {
1411         let stderr: Option<Box<term::StderrTerminal>> = term::TerminfoTerminal::new(io::stderr())
1412             .map(|t| Box::new(t) as Box<term::StderrTerminal>)
1413             .or_else(|| {
1414                 term::WinConsole::new(io::stderr())
1415                     .ok()
1416                     .map(|t| Box::new(t) as Box<term::StderrTerminal>)
1417             });
1418
1419         match stderr {
1420             Some(t) => Terminal(t),
1421             None => Raw(Box::new(io::stderr())),
1422         }
1423     }
1424
1425     fn apply_style(&mut self, lvl: Level, style: Style) -> io::Result<()> {
1426         match style {
1427             Style::LineAndColumn => {}
1428             Style::LineNumber => {
1429                 self.start_attr(term::Attr::Bold)?;
1430                 if cfg!(windows) {
1431                     self.start_attr(term::Attr::ForegroundColor(term::color::BRIGHT_CYAN))?;
1432                 } else {
1433                     self.start_attr(term::Attr::ForegroundColor(term::color::BRIGHT_BLUE))?;
1434                 }
1435             }
1436             Style::Quotation => {}
1437             Style::HeaderMsg => {
1438                 self.start_attr(term::Attr::Bold)?;
1439                 if cfg!(windows) {
1440                     self.start_attr(term::Attr::ForegroundColor(term::color::BRIGHT_WHITE))?;
1441                 }
1442             }
1443             Style::UnderlinePrimary | Style::LabelPrimary => {
1444                 self.start_attr(term::Attr::Bold)?;
1445                 self.start_attr(term::Attr::ForegroundColor(lvl.color()))?;
1446             }
1447             Style::UnderlineSecondary |
1448             Style::LabelSecondary => {
1449                 self.start_attr(term::Attr::Bold)?;
1450                 if cfg!(windows) {
1451                     self.start_attr(term::Attr::ForegroundColor(term::color::BRIGHT_CYAN))?;
1452                 } else {
1453                     self.start_attr(term::Attr::ForegroundColor(term::color::BRIGHT_BLUE))?;
1454                 }
1455             }
1456             Style::NoStyle => {}
1457             Style::Level(l) => {
1458                 self.start_attr(term::Attr::Bold)?;
1459                 self.start_attr(term::Attr::ForegroundColor(l.color()))?;
1460             }
1461             Style::Highlight => self.start_attr(term::Attr::Bold)?,
1462         }
1463         Ok(())
1464     }
1465
1466     fn start_attr(&mut self, attr: term::Attr) -> io::Result<()> {
1467         match *self {
1468             Terminal(ref mut t) => {
1469                 t.attr(attr)?;
1470             }
1471             BufferedTerminal(ref mut t) => {
1472                 t.attr(attr)?;
1473             }
1474             Raw(_) => {}
1475         }
1476         Ok(())
1477     }
1478
1479     fn reset_attrs(&mut self) -> io::Result<()> {
1480         match *self {
1481             Terminal(ref mut t) => {
1482                 t.reset()?;
1483             }
1484             BufferedTerminal(ref mut t) => {
1485                 t.reset()?;
1486             }
1487             Raw(_) => {}
1488         }
1489         Ok(())
1490     }
1491 }
1492
1493 impl Write for Destination {
1494     fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
1495         match *self {
1496             Terminal(ref mut t) => t.write(bytes),
1497             BufferedTerminal(ref mut t) => t.write(bytes),
1498             Raw(ref mut w) => w.write(bytes),
1499         }
1500     }
1501     fn flush(&mut self) -> io::Result<()> {
1502         match *self {
1503             Terminal(ref mut t) => t.flush(),
1504             BufferedTerminal(ref mut t) => t.flush(),
1505             Raw(ref mut w) => w.flush(),
1506         }
1507     }
1508 }