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