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