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