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