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