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