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