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