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