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