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