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