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