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