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