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