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