]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_errors/src/emitter.rs
Use local and remapped paths where appropriate
[rust.git] / compiler / rustc_errors / src / emitter.rs
1 //! The current rustc diagnostics emitter.
2 //!
3 //! An `Emitter` takes care of generating the output from a `DiagnosticBuilder` struct.
4 //!
5 //! There are various `Emitter` implementations that generate different output formats such as
6 //! JSON and human readable output.
7 //!
8 //! The output types are defined in `rustc_session::config::ErrorOutputType`.
9
10 use Destination::*;
11
12 use rustc_lint_defs::FutureBreakage;
13 use rustc_span::source_map::SourceMap;
14 use rustc_span::{MultiSpan, SourceFile, Span};
15
16 use crate::snippet::{Annotation, AnnotationType, Line, MultilineAnnotation, Style, StyledString};
17 use crate::styled_buffer::StyledBuffer;
18 use crate::{CodeSuggestion, Diagnostic, DiagnosticId, Level, SubDiagnostic, SuggestionStyle};
19
20 use rustc_lint_defs::pluralize;
21
22 use rustc_data_structures::fx::FxHashMap;
23 use rustc_data_structures::sync::Lrc;
24 use rustc_span::hygiene::{ExpnKind, MacroKind};
25 use std::borrow::Cow;
26 use std::cmp::{max, min, Reverse};
27 use std::io;
28 use std::io::prelude::*;
29 use std::iter;
30 use std::path::Path;
31 use termcolor::{Ansi, BufferWriter, ColorChoice, ColorSpec, StandardStream};
32 use termcolor::{Buffer, Color, WriteColor};
33 use tracing::*;
34
35 /// Default column width, used in tests and when terminal dimensions cannot be determined.
36 const DEFAULT_COLUMN_WIDTH: usize = 140;
37
38 /// Describes the way the content of the `rendered` field of the json output is generated
39 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
40 pub enum HumanReadableErrorType {
41     Default(ColorConfig),
42     AnnotateSnippet(ColorConfig),
43     Short(ColorConfig),
44 }
45
46 impl HumanReadableErrorType {
47     /// Returns a (`short`, `color`) tuple
48     pub fn unzip(self) -> (bool, ColorConfig) {
49         match self {
50             HumanReadableErrorType::Default(cc) => (false, cc),
51             HumanReadableErrorType::Short(cc) => (true, cc),
52             HumanReadableErrorType::AnnotateSnippet(cc) => (false, cc),
53         }
54     }
55     pub fn new_emitter(
56         self,
57         dst: Box<dyn Write + Send>,
58         source_map: Option<Lrc<SourceMap>>,
59         teach: bool,
60         terminal_width: Option<usize>,
61         macro_backtrace: bool,
62     ) -> EmitterWriter {
63         let (short, color_config) = self.unzip();
64         let color = color_config.suggests_using_colors();
65         EmitterWriter::new(dst, source_map, short, teach, color, terminal_width, macro_backtrace)
66     }
67 }
68
69 #[derive(Clone, Copy, Debug)]
70 struct Margin {
71     /// The available whitespace in the left that can be consumed when centering.
72     pub whitespace_left: usize,
73     /// The column of the beginning of left-most span.
74     pub span_left: usize,
75     /// The column of the end of right-most span.
76     pub span_right: usize,
77     /// The beginning of the line to be displayed.
78     pub computed_left: usize,
79     /// The end of the line to be displayed.
80     pub computed_right: usize,
81     /// The current width of the terminal. Uses value of `DEFAULT_COLUMN_WIDTH` constant by default
82     /// and in tests.
83     pub column_width: usize,
84     /// The end column of a span label, including the span. Doesn't account for labels not in the
85     /// same line as the span.
86     pub label_right: usize,
87 }
88
89 impl Margin {
90     fn new(
91         whitespace_left: usize,
92         span_left: usize,
93         span_right: usize,
94         label_right: usize,
95         column_width: usize,
96         max_line_len: usize,
97     ) -> Self {
98         // The 6 is padding to give a bit of room for `...` when displaying:
99         // ```
100         // error: message
101         //   --> file.rs:16:58
102         //    |
103         // 16 | ... fn foo(self) -> Self::Bar {
104         //    |                     ^^^^^^^^^
105         // ```
106
107         let mut m = Margin {
108             whitespace_left: whitespace_left.saturating_sub(6),
109             span_left: span_left.saturating_sub(6),
110             span_right: span_right + 6,
111             computed_left: 0,
112             computed_right: 0,
113             column_width,
114             label_right: label_right + 6,
115         };
116         m.compute(max_line_len);
117         m
118     }
119
120     fn was_cut_left(&self) -> bool {
121         self.computed_left > 0
122     }
123
124     fn was_cut_right(&self, line_len: usize) -> bool {
125         let right =
126             if self.computed_right == self.span_right || self.computed_right == self.label_right {
127                 // Account for the "..." padding given above. Otherwise we end up with code lines that
128                 // do fit but end in "..." as if they were trimmed.
129                 self.computed_right - 6
130             } else {
131                 self.computed_right
132             };
133         right < line_len && self.computed_left + self.column_width < line_len
134     }
135
136     fn compute(&mut self, max_line_len: usize) {
137         // When there's a lot of whitespace (>20), we want to trim it as it is useless.
138         self.computed_left = if self.whitespace_left > 20 {
139             self.whitespace_left - 16 // We want some padding.
140         } else {
141             0
142         };
143         // We want to show as much as possible, max_line_len is the right-most boundary for the
144         // relevant code.
145         self.computed_right = max(max_line_len, self.computed_left);
146
147         if self.computed_right - self.computed_left > self.column_width {
148             // Trimming only whitespace isn't enough, let's get craftier.
149             if self.label_right - self.whitespace_left <= self.column_width {
150                 // Attempt to fit the code window only trimming whitespace.
151                 self.computed_left = self.whitespace_left;
152                 self.computed_right = self.computed_left + self.column_width;
153             } else if self.label_right - self.span_left <= self.column_width {
154                 // Attempt to fit the code window considering only the spans and labels.
155                 let padding_left = (self.column_width - (self.label_right - self.span_left)) / 2;
156                 self.computed_left = self.span_left.saturating_sub(padding_left);
157                 self.computed_right = self.computed_left + self.column_width;
158             } else if self.span_right - self.span_left <= self.column_width {
159                 // Attempt to fit the code window considering the spans and labels plus padding.
160                 let padding_left = (self.column_width - (self.span_right - self.span_left)) / 5 * 2;
161                 self.computed_left = self.span_left.saturating_sub(padding_left);
162                 self.computed_right = self.computed_left + self.column_width;
163             } else {
164                 // Mostly give up but still don't show the full line.
165                 self.computed_left = self.span_left;
166                 self.computed_right = self.span_right;
167             }
168         }
169     }
170
171     fn left(&self, line_len: usize) -> usize {
172         min(self.computed_left, line_len)
173     }
174
175     fn right(&self, line_len: usize) -> usize {
176         if line_len.saturating_sub(self.computed_left) <= self.column_width {
177             line_len
178         } else {
179             min(line_len, self.computed_right)
180         }
181     }
182 }
183
184 const ANONYMIZED_LINE_NUM: &str = "LL";
185
186 /// Emitter trait for emitting errors.
187 pub trait Emitter {
188     /// Emit a structured diagnostic.
189     fn emit_diagnostic(&mut self, diag: &Diagnostic);
190
191     /// Emit a notification that an artifact has been output.
192     /// This is currently only supported for the JSON format,
193     /// other formats can, and will, simply ignore it.
194     fn emit_artifact_notification(&mut self, _path: &Path, _artifact_type: &str) {}
195
196     fn emit_future_breakage_report(&mut self, _diags: Vec<(FutureBreakage, Diagnostic)>) {}
197
198     /// Emit list of unused externs
199     fn emit_unused_externs(&mut self, _lint_level: &str, _unused_externs: &[&str]) {}
200
201     /// Checks if should show explanations about "rustc --explain"
202     fn should_show_explain(&self) -> bool {
203         true
204     }
205
206     /// Checks if we can use colors in the current output stream.
207     fn supports_color(&self) -> bool {
208         false
209     }
210
211     fn source_map(&self) -> Option<&Lrc<SourceMap>>;
212
213     /// Formats the substitutions of the primary_span
214     ///
215     /// The are a lot of conditions to this method, but in short:
216     ///
217     /// * If the current `Diagnostic` has only one visible `CodeSuggestion`,
218     ///   we format the `help` suggestion depending on the content of the
219     ///   substitutions. In that case, we return the modified span only.
220     ///
221     /// * If the current `Diagnostic` has multiple suggestions,
222     ///   we return the original `primary_span` and the original suggestions.
223     fn primary_span_formatted<'a>(
224         &mut self,
225         diag: &'a Diagnostic,
226     ) -> (MultiSpan, &'a [CodeSuggestion]) {
227         let mut primary_span = diag.span.clone();
228         if let Some((sugg, rest)) = diag.suggestions.split_first() {
229             if rest.is_empty() &&
230                // ^ if there is only one suggestion
231                // don't display multi-suggestions as labels
232                sugg.substitutions.len() == 1 &&
233                // don't display multipart suggestions as labels
234                sugg.substitutions[0].parts.len() == 1 &&
235                // don't display long messages as labels
236                sugg.msg.split_whitespace().count() < 10 &&
237                // don't display multiline suggestions as labels
238                !sugg.substitutions[0].parts[0].snippet.contains('\n') &&
239                ![
240                     // when this style is set we want the suggestion to be a message, not inline
241                     SuggestionStyle::HideCodeAlways,
242                     // trivial suggestion for tooling's sake, never shown
243                     SuggestionStyle::CompletelyHidden,
244                     // subtle suggestion, never shown inline
245                     SuggestionStyle::ShowAlways,
246                ].contains(&sugg.style)
247             {
248                 let substitution = &sugg.substitutions[0].parts[0].snippet.trim();
249                 let msg = if substitution.is_empty() || sugg.style.hide_inline() {
250                     // This substitution is only removal OR we explicitly don't want to show the
251                     // code inline (`hide_inline`). Therefore, we don't show the substitution.
252                     format!("help: {}", sugg.msg)
253                 } else {
254                     // Show the default suggestion text with the substitution
255                     format!(
256                         "help: {}{}: `{}`",
257                         sugg.msg,
258                         if self
259                             .source_map()
260                             .map(|sm| is_case_difference(
261                                 &**sm,
262                                 substitution,
263                                 sugg.substitutions[0].parts[0].span,
264                             ))
265                             .unwrap_or(false)
266                         {
267                             " (notice the capitalization)"
268                         } else {
269                             ""
270                         },
271                         substitution,
272                     )
273                 };
274                 primary_span.push_span_label(sugg.substitutions[0].parts[0].span, msg);
275
276                 // We return only the modified primary_span
277                 (primary_span, &[])
278             } else {
279                 // if there are multiple suggestions, print them all in full
280                 // to be consistent. We could try to figure out if we can
281                 // make one (or the first one) inline, but that would give
282                 // undue importance to a semi-random suggestion
283                 (primary_span, &diag.suggestions)
284             }
285         } else {
286             (primary_span, &diag.suggestions)
287         }
288     }
289
290     fn fix_multispans_in_extern_macros_and_render_macro_backtrace(
291         &self,
292         source_map: &Option<Lrc<SourceMap>>,
293         span: &mut MultiSpan,
294         children: &mut Vec<SubDiagnostic>,
295         level: &Level,
296         backtrace: bool,
297     ) {
298         // Check for spans in macros, before `fix_multispans_in_extern_macros`
299         // has a chance to replace them.
300         let has_macro_spans = iter::once(&*span)
301             .chain(children.iter().map(|child| &child.span))
302             .flat_map(|span| span.primary_spans())
303             .flat_map(|sp| sp.macro_backtrace())
304             .find_map(|expn_data| {
305                 match expn_data.kind {
306                     ExpnKind::Root => None,
307
308                     // Skip past non-macro entries, just in case there
309                     // are some which do actually involve macros.
310                     ExpnKind::Inlined | ExpnKind::Desugaring(..) | ExpnKind::AstPass(..) => None,
311
312                     ExpnKind::Macro(macro_kind, _) => Some(macro_kind),
313                 }
314             });
315
316         if !backtrace {
317             self.fix_multispans_in_extern_macros(source_map, span, children);
318         }
319
320         self.render_multispans_macro_backtrace(span, children, backtrace);
321
322         if !backtrace {
323             if let Some(macro_kind) = has_macro_spans {
324                 let msg = format!(
325                     "this {} originates in {} {} \
326                     (in Nightly builds, run with -Z macro-backtrace for more info)",
327                     level,
328                     macro_kind.article(),
329                     macro_kind.descr(),
330                 );
331
332                 children.push(SubDiagnostic {
333                     level: Level::Note,
334                     message: vec![(msg, Style::NoStyle)],
335                     span: MultiSpan::new(),
336                     render_span: None,
337                 });
338             }
339         }
340     }
341
342     fn render_multispans_macro_backtrace(
343         &self,
344         span: &mut MultiSpan,
345         children: &mut Vec<SubDiagnostic>,
346         backtrace: bool,
347     ) {
348         for span in iter::once(span).chain(children.iter_mut().map(|child| &mut child.span)) {
349             self.render_multispan_macro_backtrace(span, backtrace);
350         }
351     }
352
353     fn render_multispan_macro_backtrace(&self, span: &mut MultiSpan, always_backtrace: bool) {
354         let mut new_labels: Vec<(Span, String)> = vec![];
355
356         for &sp in span.primary_spans() {
357             if sp.is_dummy() {
358                 continue;
359             }
360
361             // FIXME(eddyb) use `retain` on `macro_backtrace` to remove all the
362             // entries we don't want to print, to make sure the indices being
363             // printed are contiguous (or omitted if there's only one entry).
364             let macro_backtrace: Vec<_> = sp.macro_backtrace().collect();
365             for (i, trace) in macro_backtrace.iter().rev().enumerate() {
366                 if trace.def_site.is_dummy() {
367                     continue;
368                 }
369
370                 if matches!(trace.kind, ExpnKind::Inlined) {
371                     new_labels
372                         .push((trace.call_site, "in the inlined copy of this code".to_string()));
373                 } else if always_backtrace {
374                     new_labels.push((
375                         trace.def_site,
376                         format!(
377                             "in this expansion of `{}`{}",
378                             trace.kind.descr(),
379                             if macro_backtrace.len() > 1 {
380                                 // if macro_backtrace.len() == 1 it'll be
381                                 // pointed at by "in this macro invocation"
382                                 format!(" (#{})", i + 1)
383                             } else {
384                                 String::new()
385                             },
386                         ),
387                     ));
388                 }
389
390                 // Don't add a label on the call site if the diagnostic itself
391                 // already points to (a part of) that call site, as the label
392                 // is meant for showing the relevant invocation when the actual
393                 // diagnostic is pointing to some part of macro definition.
394                 //
395                 // This also handles the case where an external span got replaced
396                 // with the call site span by `fix_multispans_in_extern_macros`.
397                 //
398                 // NB: `-Zmacro-backtrace` overrides this, for uniformity, as the
399                 // "in this expansion of" label above is always added in that mode,
400                 // and it needs an "in this macro invocation" label to match that.
401                 let redundant_span = trace.call_site.contains(sp);
402
403                 if !redundant_span && matches!(trace.kind, ExpnKind::Macro(MacroKind::Bang, _))
404                     || always_backtrace
405                 {
406                     new_labels.push((
407                         trace.call_site,
408                         format!(
409                             "in this macro invocation{}",
410                             if macro_backtrace.len() > 1 && always_backtrace {
411                                 // only specify order when the macro
412                                 // backtrace is multiple levels deep
413                                 format!(" (#{})", i + 1)
414                             } else {
415                                 String::new()
416                             },
417                         ),
418                     ));
419                 }
420                 if !always_backtrace {
421                     break;
422                 }
423             }
424         }
425
426         for (label_span, label_text) in new_labels {
427             span.push_span_label(label_span, label_text);
428         }
429     }
430
431     // This does a small "fix" for multispans by looking to see if it can find any that
432     // point directly at external macros. Since these are often difficult to read,
433     // this will change the span to point at the use site.
434     fn fix_multispans_in_extern_macros(
435         &self,
436         source_map: &Option<Lrc<SourceMap>>,
437         span: &mut MultiSpan,
438         children: &mut Vec<SubDiagnostic>,
439     ) {
440         let source_map = if let Some(ref sm) = source_map {
441             sm
442         } else {
443             return;
444         };
445         debug!("fix_multispans_in_extern_macros: before: span={:?} children={:?}", span, children);
446         self.fix_multispan_in_extern_macros(source_map, span);
447         for child in children.iter_mut() {
448             self.fix_multispan_in_extern_macros(source_map, &mut child.span);
449         }
450         debug!("fix_multispans_in_extern_macros: after: span={:?} children={:?}", span, children);
451     }
452
453     // This "fixes" MultiSpans that contain `Span`s pointing to locations inside of external macros.
454     // Since these locations are often difficult to read,
455     // we move these spans from the external macros to their corresponding use site.
456     fn fix_multispan_in_extern_macros(&self, source_map: &Lrc<SourceMap>, span: &mut MultiSpan) {
457         // First, find all the spans in external macros and point instead at their use site.
458         let replacements: Vec<(Span, Span)> = span
459             .primary_spans()
460             .iter()
461             .copied()
462             .chain(span.span_labels().iter().map(|sp_label| sp_label.span))
463             .filter_map(|sp| {
464                 if !sp.is_dummy() && source_map.is_imported(sp) {
465                     let maybe_callsite = sp.source_callsite();
466                     if sp != maybe_callsite {
467                         return Some((sp, maybe_callsite));
468                     }
469                 }
470                 None
471             })
472             .collect();
473
474         // After we have them, make sure we replace these 'bad' def sites with their use sites.
475         for (from, to) in replacements {
476             span.replace(from, to);
477         }
478     }
479 }
480
481 impl Emitter for EmitterWriter {
482     fn source_map(&self) -> Option<&Lrc<SourceMap>> {
483         self.sm.as_ref()
484     }
485
486     fn emit_diagnostic(&mut self, diag: &Diagnostic) {
487         let mut children = diag.children.clone();
488         let (mut primary_span, suggestions) = self.primary_span_formatted(&diag);
489         debug!("emit_diagnostic: suggestions={:?}", suggestions);
490
491         self.fix_multispans_in_extern_macros_and_render_macro_backtrace(
492             &self.sm,
493             &mut primary_span,
494             &mut children,
495             &diag.level,
496             self.macro_backtrace,
497         );
498
499         self.emit_messages_default(
500             &diag.level,
501             &diag.styled_message(),
502             &diag.code,
503             &primary_span,
504             &children,
505             &suggestions,
506         );
507     }
508
509     fn should_show_explain(&self) -> bool {
510         !self.short_message
511     }
512
513     fn supports_color(&self) -> bool {
514         self.dst.supports_color()
515     }
516 }
517
518 /// An emitter that does nothing when emitting a diagnostic.
519 pub struct SilentEmitter;
520
521 impl Emitter for SilentEmitter {
522     fn source_map(&self) -> Option<&Lrc<SourceMap>> {
523         None
524     }
525     fn emit_diagnostic(&mut self, _: &Diagnostic) {}
526 }
527
528 /// Maximum number of lines we will print for a multiline suggestion; arbitrary.
529 ///
530 /// This should be replaced with a more involved mechanism to output multiline suggestions that
531 /// more closely mimics the regular diagnostic output, where irrelevant code lines are elided.
532 pub const MAX_SUGGESTION_HIGHLIGHT_LINES: usize = 6;
533 /// Maximum number of suggestions to be shown
534 ///
535 /// Arbitrary, but taken from trait import suggestion limit
536 pub const MAX_SUGGESTIONS: usize = 4;
537
538 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
539 pub enum ColorConfig {
540     Auto,
541     Always,
542     Never,
543 }
544
545 impl ColorConfig {
546     fn to_color_choice(self) -> ColorChoice {
547         match self {
548             ColorConfig::Always => {
549                 if atty::is(atty::Stream::Stderr) {
550                     ColorChoice::Always
551                 } else {
552                     ColorChoice::AlwaysAnsi
553                 }
554             }
555             ColorConfig::Never => ColorChoice::Never,
556             ColorConfig::Auto if atty::is(atty::Stream::Stderr) => ColorChoice::Auto,
557             ColorConfig::Auto => ColorChoice::Never,
558         }
559     }
560     fn suggests_using_colors(self) -> bool {
561         match self {
562             ColorConfig::Always | ColorConfig::Auto => true,
563             ColorConfig::Never => false,
564         }
565     }
566 }
567
568 /// Handles the writing of `HumanReadableErrorType::Default` and `HumanReadableErrorType::Short`
569 pub struct EmitterWriter {
570     dst: Destination,
571     sm: Option<Lrc<SourceMap>>,
572     short_message: bool,
573     teach: bool,
574     ui_testing: bool,
575     terminal_width: Option<usize>,
576
577     macro_backtrace: bool,
578 }
579
580 #[derive(Debug)]
581 pub struct FileWithAnnotatedLines {
582     pub file: Lrc<SourceFile>,
583     pub lines: Vec<Line>,
584     multiline_depth: usize,
585 }
586
587 impl EmitterWriter {
588     pub fn stderr(
589         color_config: ColorConfig,
590         source_map: Option<Lrc<SourceMap>>,
591         short_message: bool,
592         teach: bool,
593         terminal_width: Option<usize>,
594         macro_backtrace: bool,
595     ) -> EmitterWriter {
596         let dst = Destination::from_stderr(color_config);
597         EmitterWriter {
598             dst,
599             sm: source_map,
600             short_message,
601             teach,
602             ui_testing: false,
603             terminal_width,
604             macro_backtrace,
605         }
606     }
607
608     pub fn new(
609         dst: Box<dyn Write + Send>,
610         source_map: Option<Lrc<SourceMap>>,
611         short_message: bool,
612         teach: bool,
613         colored: bool,
614         terminal_width: Option<usize>,
615         macro_backtrace: bool,
616     ) -> EmitterWriter {
617         EmitterWriter {
618             dst: Raw(dst, colored),
619             sm: source_map,
620             short_message,
621             teach,
622             ui_testing: false,
623             terminal_width,
624             macro_backtrace,
625         }
626     }
627
628     pub fn ui_testing(mut self, ui_testing: bool) -> Self {
629         self.ui_testing = ui_testing;
630         self
631     }
632
633     fn maybe_anonymized(&self, line_num: usize) -> String {
634         if self.ui_testing { ANONYMIZED_LINE_NUM.to_string() } else { line_num.to_string() }
635     }
636
637     fn draw_line(
638         &self,
639         buffer: &mut StyledBuffer,
640         source_string: &str,
641         line_index: usize,
642         line_offset: usize,
643         width_offset: usize,
644         code_offset: usize,
645         margin: Margin,
646     ) {
647         // Tabs are assumed to have been replaced by spaces in calling code.
648         debug_assert!(!source_string.contains('\t'));
649         let line_len = source_string.len();
650         // Create the source line we will highlight.
651         let left = margin.left(line_len);
652         let right = margin.right(line_len);
653         // On long lines, we strip the source line, accounting for unicode.
654         let mut taken = 0;
655         let code: String = source_string
656             .chars()
657             .skip(left)
658             .take_while(|ch| {
659                 // Make sure that the trimming on the right will fall within the terminal width.
660                 // FIXME: `unicode_width` sometimes disagrees with terminals on how wide a `char` is.
661                 // For now, just accept that sometimes the code line will be longer than desired.
662                 let next = unicode_width::UnicodeWidthChar::width(*ch).unwrap_or(1);
663                 if taken + next > right - left {
664                     return false;
665                 }
666                 taken += next;
667                 true
668             })
669             .collect();
670         buffer.puts(line_offset, code_offset, &code, Style::Quotation);
671         if margin.was_cut_left() {
672             // We have stripped some code/whitespace from the beginning, make it clear.
673             buffer.puts(line_offset, code_offset, "...", Style::LineNumber);
674         }
675         if margin.was_cut_right(line_len) {
676             // We have stripped some code after the right-most span end, make it clear we did so.
677             buffer.puts(line_offset, code_offset + taken - 3, "...", Style::LineNumber);
678         }
679         buffer.puts(line_offset, 0, &self.maybe_anonymized(line_index), Style::LineNumber);
680
681         draw_col_separator(buffer, line_offset, width_offset - 2);
682     }
683
684     fn render_source_line(
685         &self,
686         buffer: &mut StyledBuffer,
687         file: Lrc<SourceFile>,
688         line: &Line,
689         width_offset: usize,
690         code_offset: usize,
691         margin: Margin,
692     ) -> Vec<(usize, Style)> {
693         // Draw:
694         //
695         //   LL | ... code ...
696         //      |     ^^-^ span label
697         //      |       |
698         //      |       secondary span label
699         //
700         //   ^^ ^ ^^^ ^^^^ ^^^ we don't care about code too far to the right of a span, we trim it
701         //   |  | |   |
702         //   |  | |   actual code found in your source code and the spans we use to mark it
703         //   |  | when there's too much wasted space to the left, trim it
704         //   |  vertical divider between the column number and the code
705         //   column number
706
707         if line.line_index == 0 {
708             return Vec::new();
709         }
710
711         let source_string = match file.get_line(line.line_index - 1) {
712             Some(s) => replace_tabs(&*s),
713             None => return Vec::new(),
714         };
715
716         let line_offset = buffer.num_lines();
717
718         let left = margin.left(source_string.len()); // Left trim
719         // Account for unicode characters of width !=0 that were removed.
720         let left = source_string
721             .chars()
722             .take(left)
723             .map(|ch| unicode_width::UnicodeWidthChar::width(ch).unwrap_or(1))
724             .sum();
725
726         self.draw_line(
727             buffer,
728             &source_string,
729             line.line_index,
730             line_offset,
731             width_offset,
732             code_offset,
733             margin,
734         );
735
736         // Special case when there's only one annotation involved, it is the start of a multiline
737         // span and there's no text at the beginning of the code line. Instead of doing the whole
738         // graph:
739         //
740         // 2 |   fn foo() {
741         //   |  _^
742         // 3 | |
743         // 4 | | }
744         //   | |_^ test
745         //
746         // we simplify the output to:
747         //
748         // 2 | / fn foo() {
749         // 3 | |
750         // 4 | | }
751         //   | |_^ test
752         if let [ann] = &line.annotations[..] {
753             if let AnnotationType::MultilineStart(depth) = ann.annotation_type {
754                 if source_string.chars().take(ann.start_col).all(|c| c.is_whitespace()) {
755                     let style = if ann.is_primary {
756                         Style::UnderlinePrimary
757                     } else {
758                         Style::UnderlineSecondary
759                     };
760                     buffer.putc(line_offset, width_offset + depth - 1, '/', style);
761                     return vec![(depth, style)];
762                 }
763             }
764         }
765
766         // We want to display like this:
767         //
768         //      vec.push(vec.pop().unwrap());
769         //      ---      ^^^               - previous borrow ends here
770         //      |        |
771         //      |        error occurs here
772         //      previous borrow of `vec` occurs here
773         //
774         // But there are some weird edge cases to be aware of:
775         //
776         //      vec.push(vec.pop().unwrap());
777         //      --------                    - previous borrow ends here
778         //      ||
779         //      |this makes no sense
780         //      previous borrow of `vec` occurs here
781         //
782         // For this reason, we group the lines into "highlight lines"
783         // and "annotations lines", where the highlight lines have the `^`.
784
785         // Sort the annotations by (start, end col)
786         // The labels are reversed, sort and then reversed again.
787         // Consider a list of annotations (A1, A2, C1, C2, B1, B2) where
788         // the letter signifies the span. Here we are only sorting by the
789         // span and hence, the order of the elements with the same span will
790         // not change. On reversing the ordering (|a, b| but b.cmp(a)), you get
791         // (C1, C2, B1, B2, A1, A2). All the elements with the same span are
792         // still ordered first to last, but all the elements with different
793         // spans are ordered by their spans in last to first order. Last to
794         // first order is important, because the jiggly lines and | are on
795         // the left, so the rightmost span needs to be rendered first,
796         // otherwise the lines would end up needing to go over a message.
797
798         let mut annotations = line.annotations.clone();
799         annotations.sort_by_key(|a| Reverse(a.start_col));
800
801         // First, figure out where each label will be positioned.
802         //
803         // In the case where you have the following annotations:
804         //
805         //      vec.push(vec.pop().unwrap());
806         //      --------                    - previous borrow ends here [C]
807         //      ||
808         //      |this makes no sense [B]
809         //      previous borrow of `vec` occurs here [A]
810         //
811         // `annotations_position` will hold [(2, A), (1, B), (0, C)].
812         //
813         // We try, when possible, to stick the rightmost annotation at the end
814         // of the highlight line:
815         //
816         //      vec.push(vec.pop().unwrap());
817         //      ---      ---               - previous borrow ends here
818         //
819         // But sometimes that's not possible because one of the other
820         // annotations overlaps it. For example, from the test
821         // `span_overlap_label`, we have the following annotations
822         // (written on distinct lines for clarity):
823         //
824         //      fn foo(x: u32) {
825         //      --------------
826         //             -
827         //
828         // In this case, we can't stick the rightmost-most label on
829         // the highlight line, or we would get:
830         //
831         //      fn foo(x: u32) {
832         //      -------- x_span
833         //      |
834         //      fn_span
835         //
836         // which is totally weird. Instead we want:
837         //
838         //      fn foo(x: u32) {
839         //      --------------
840         //      |      |
841         //      |      x_span
842         //      fn_span
843         //
844         // which is...less weird, at least. In fact, in general, if
845         // the rightmost span overlaps with any other span, we should
846         // use the "hang below" version, so we can at least make it
847         // clear where the span *starts*. There's an exception for this
848         // logic, when the labels do not have a message:
849         //
850         //      fn foo(x: u32) {
851         //      --------------
852         //             |
853         //             x_span
854         //
855         // instead of:
856         //
857         //      fn foo(x: u32) {
858         //      --------------
859         //      |      |
860         //      |      x_span
861         //      <EMPTY LINE>
862         //
863         let mut annotations_position = vec![];
864         let mut line_len = 0;
865         let mut p = 0;
866         for (i, annotation) in annotations.iter().enumerate() {
867             for (j, next) in annotations.iter().enumerate() {
868                 if overlaps(next, annotation, 0)  // This label overlaps with another one and both
869                     && annotation.has_label()     // take space (they have text and are not
870                     && j > i                      // multiline lines).
871                     && p == 0
872                 // We're currently on the first line, move the label one line down
873                 {
874                     // If we're overlapping with an un-labelled annotation with the same span
875                     // we can just merge them in the output
876                     if next.start_col == annotation.start_col
877                         && next.end_col == annotation.end_col
878                         && !next.has_label()
879                     {
880                         continue;
881                     }
882
883                     // This annotation needs a new line in the output.
884                     p += 1;
885                     break;
886                 }
887             }
888             annotations_position.push((p, annotation));
889             for (j, next) in annotations.iter().enumerate() {
890                 if j > i {
891                     let l = next.label.as_ref().map_or(0, |label| label.len() + 2);
892                     if (overlaps(next, annotation, l) // Do not allow two labels to be in the same
893                                                      // line if they overlap including padding, to
894                                                      // avoid situations like:
895                                                      //
896                                                      //      fn foo(x: u32) {
897                                                      //      -------^------
898                                                      //      |      |
899                                                      //      fn_spanx_span
900                                                      //
901                         && annotation.has_label()    // Both labels must have some text, otherwise
902                         && next.has_label())         // they are not overlapping.
903                                                      // Do not add a new line if this annotation
904                                                      // or the next are vertical line placeholders.
905                         || (annotation.takes_space() // If either this or the next annotation is
906                             && next.has_label())     // multiline start/end, move it to a new line
907                         || (annotation.has_label()   // so as not to overlap the horizontal lines.
908                             && next.takes_space())
909                         || (annotation.takes_space() && next.takes_space())
910                         || (overlaps(next, annotation, l)
911                             && next.end_col <= annotation.end_col
912                             && next.has_label()
913                             && p == 0)
914                     // Avoid #42595.
915                     {
916                         // This annotation needs a new line in the output.
917                         p += 1;
918                         break;
919                     }
920                 }
921             }
922             line_len = max(line_len, p);
923         }
924
925         if line_len != 0 {
926             line_len += 1;
927         }
928
929         // If there are no annotations or the only annotations on this line are
930         // MultilineLine, then there's only code being shown, stop processing.
931         if line.annotations.iter().all(|a| a.is_line()) {
932             return vec![];
933         }
934
935         // Write the column separator.
936         //
937         // After this we will have:
938         //
939         // 2 |   fn foo() {
940         //   |
941         //   |
942         //   |
943         // 3 |
944         // 4 |   }
945         //   |
946         for pos in 0..=line_len {
947             draw_col_separator(buffer, line_offset + pos + 1, width_offset - 2);
948             buffer.putc(line_offset + pos + 1, width_offset - 2, '|', Style::LineNumber);
949         }
950
951         // Write the horizontal lines for multiline annotations
952         // (only the first and last lines need this).
953         //
954         // After this we will have:
955         //
956         // 2 |   fn foo() {
957         //   |  __________
958         //   |
959         //   |
960         // 3 |
961         // 4 |   }
962         //   |  _
963         for &(pos, annotation) in &annotations_position {
964             let style = if annotation.is_primary {
965                 Style::UnderlinePrimary
966             } else {
967                 Style::UnderlineSecondary
968             };
969             let pos = pos + 1;
970             match annotation.annotation_type {
971                 AnnotationType::MultilineStart(depth) | AnnotationType::MultilineEnd(depth) => {
972                     draw_range(
973                         buffer,
974                         '_',
975                         line_offset + pos,
976                         width_offset + depth,
977                         (code_offset + annotation.start_col).saturating_sub(left),
978                         style,
979                     );
980                 }
981                 _ if self.teach => {
982                     buffer.set_style_range(
983                         line_offset,
984                         (code_offset + annotation.start_col).saturating_sub(left),
985                         (code_offset + annotation.end_col).saturating_sub(left),
986                         style,
987                         annotation.is_primary,
988                     );
989                 }
990                 _ => {}
991             }
992         }
993
994         // Write the vertical lines for labels that are on a different line as the underline.
995         //
996         // After this we will have:
997         //
998         // 2 |   fn foo() {
999         //   |  __________
1000         //   | |    |
1001         //   | |
1002         // 3 | |
1003         // 4 | | }
1004         //   | |_
1005         for &(pos, annotation) in &annotations_position {
1006             let style = if annotation.is_primary {
1007                 Style::UnderlinePrimary
1008             } else {
1009                 Style::UnderlineSecondary
1010             };
1011             let pos = pos + 1;
1012
1013             if pos > 1 && (annotation.has_label() || annotation.takes_space()) {
1014                 for p in line_offset + 1..=line_offset + pos {
1015                     buffer.putc(
1016                         p,
1017                         (code_offset + annotation.start_col).saturating_sub(left),
1018                         '|',
1019                         style,
1020                     );
1021                 }
1022             }
1023             match annotation.annotation_type {
1024                 AnnotationType::MultilineStart(depth) => {
1025                     for p in line_offset + pos + 1..line_offset + line_len + 2 {
1026                         buffer.putc(p, width_offset + depth - 1, '|', style);
1027                     }
1028                 }
1029                 AnnotationType::MultilineEnd(depth) => {
1030                     for p in line_offset..=line_offset + pos {
1031                         buffer.putc(p, width_offset + depth - 1, '|', style);
1032                     }
1033                 }
1034                 _ => (),
1035             }
1036         }
1037
1038         // Write the labels on the annotations that actually have a label.
1039         //
1040         // After this we will have:
1041         //
1042         // 2 |   fn foo() {
1043         //   |  __________
1044         //   |      |
1045         //   |      something about `foo`
1046         // 3 |
1047         // 4 |   }
1048         //   |  _  test
1049         for &(pos, annotation) in &annotations_position {
1050             let style =
1051                 if annotation.is_primary { Style::LabelPrimary } else { Style::LabelSecondary };
1052             let (pos, col) = if pos == 0 {
1053                 (pos + 1, (annotation.end_col + 1).saturating_sub(left))
1054             } else {
1055                 (pos + 2, annotation.start_col.saturating_sub(left))
1056             };
1057             if let Some(ref label) = annotation.label {
1058                 buffer.puts(line_offset + pos, code_offset + col, &label, style);
1059             }
1060         }
1061
1062         // Sort from biggest span to smallest span so that smaller spans are
1063         // represented in the output:
1064         //
1065         // x | fn foo()
1066         //   | ^^^---^^
1067         //   | |  |
1068         //   | |  something about `foo`
1069         //   | something about `fn foo()`
1070         annotations_position.sort_by_key(|(_, ann)| {
1071             // Decreasing order. When annotations share the same length, prefer `Primary`.
1072             (Reverse(ann.len()), ann.is_primary)
1073         });
1074
1075         // Write the underlines.
1076         //
1077         // After this we will have:
1078         //
1079         // 2 |   fn foo() {
1080         //   |  ____-_____^
1081         //   |      |
1082         //   |      something about `foo`
1083         // 3 |
1084         // 4 |   }
1085         //   |  _^  test
1086         for &(_, annotation) in &annotations_position {
1087             let (underline, style) = if annotation.is_primary {
1088                 ('^', Style::UnderlinePrimary)
1089             } else {
1090                 ('-', Style::UnderlineSecondary)
1091             };
1092             for p in annotation.start_col..annotation.end_col {
1093                 buffer.putc(
1094                     line_offset + 1,
1095                     (code_offset + p).saturating_sub(left),
1096                     underline,
1097                     style,
1098                 );
1099             }
1100         }
1101         annotations_position
1102             .iter()
1103             .filter_map(|&(_, annotation)| match annotation.annotation_type {
1104                 AnnotationType::MultilineStart(p) | AnnotationType::MultilineEnd(p) => {
1105                     let style = if annotation.is_primary {
1106                         Style::LabelPrimary
1107                     } else {
1108                         Style::LabelSecondary
1109                     };
1110                     Some((p, style))
1111                 }
1112                 _ => None,
1113             })
1114             .collect::<Vec<_>>()
1115     }
1116
1117     fn get_multispan_max_line_num(&mut self, msp: &MultiSpan) -> usize {
1118         let sm = match self.sm {
1119             Some(ref sm) => sm,
1120             None => return 0,
1121         };
1122
1123         let mut max = 0;
1124         for primary_span in msp.primary_spans() {
1125             if !primary_span.is_dummy() {
1126                 let hi = sm.lookup_char_pos(primary_span.hi());
1127                 max = (hi.line).max(max);
1128             }
1129         }
1130         if !self.short_message {
1131             for span_label in msp.span_labels() {
1132                 if !span_label.span.is_dummy() {
1133                     let hi = sm.lookup_char_pos(span_label.span.hi());
1134                     max = (hi.line).max(max);
1135                 }
1136             }
1137         }
1138
1139         max
1140     }
1141
1142     fn get_max_line_num(&mut self, span: &MultiSpan, children: &[SubDiagnostic]) -> usize {
1143         let primary = self.get_multispan_max_line_num(span);
1144         children
1145             .iter()
1146             .map(|sub| self.get_multispan_max_line_num(&sub.span))
1147             .max()
1148             .unwrap_or(0)
1149             .max(primary)
1150     }
1151
1152     /// Adds a left margin to every line but the first, given a padding length and the label being
1153     /// displayed, keeping the provided highlighting.
1154     fn msg_to_buffer(
1155         &self,
1156         buffer: &mut StyledBuffer,
1157         msg: &[(String, Style)],
1158         padding: usize,
1159         label: &str,
1160         override_style: Option<Style>,
1161     ) {
1162         // The extra 5 ` ` is padding that's always needed to align to the `note: `:
1163         //
1164         //   error: message
1165         //     --> file.rs:13:20
1166         //      |
1167         //   13 |     <CODE>
1168         //      |      ^^^^
1169         //      |
1170         //      = note: multiline
1171         //              message
1172         //   ++^^^----xx
1173         //    |  |   | |
1174         //    |  |   | magic `2`
1175         //    |  |   length of label
1176         //    |  magic `3`
1177         //    `max_line_num_len`
1178         let padding = " ".repeat(padding + label.len() + 5);
1179
1180         /// Returns `override` if it is present and `style` is `NoStyle` or `style` otherwise
1181         fn style_or_override(style: Style, override_: Option<Style>) -> Style {
1182             match (style, override_) {
1183                 (Style::NoStyle, Some(override_)) => override_,
1184                 _ => style,
1185             }
1186         }
1187
1188         let mut line_number = 0;
1189
1190         // Provided the following diagnostic message:
1191         //
1192         //     let msg = vec![
1193         //       ("
1194         //       ("highlighted multiline\nstring to\nsee how it ", Style::NoStyle),
1195         //       ("looks", Style::Highlight),
1196         //       ("with\nvery ", Style::NoStyle),
1197         //       ("weird", Style::Highlight),
1198         //       (" formats\n", Style::NoStyle),
1199         //       ("see?", Style::Highlight),
1200         //     ];
1201         //
1202         // the expected output on a note is (* surround the highlighted text)
1203         //
1204         //        = note: highlighted multiline
1205         //                string to
1206         //                see how it *looks* with
1207         //                very *weird* formats
1208         //                see?
1209         for &(ref text, ref style) in msg.iter() {
1210             let lines = text.split('\n').collect::<Vec<_>>();
1211             if lines.len() > 1 {
1212                 for (i, line) in lines.iter().enumerate() {
1213                     if i != 0 {
1214                         line_number += 1;
1215                         buffer.append(line_number, &padding, Style::NoStyle);
1216                     }
1217                     buffer.append(line_number, line, style_or_override(*style, override_style));
1218                 }
1219             } else {
1220                 buffer.append(line_number, text, style_or_override(*style, override_style));
1221             }
1222         }
1223     }
1224
1225     fn emit_message_default(
1226         &mut self,
1227         msp: &MultiSpan,
1228         msg: &[(String, Style)],
1229         code: &Option<DiagnosticId>,
1230         level: &Level,
1231         max_line_num_len: usize,
1232         is_secondary: bool,
1233     ) -> io::Result<()> {
1234         let mut buffer = StyledBuffer::new();
1235
1236         if !msp.has_primary_spans() && !msp.has_span_labels() && is_secondary && !self.short_message
1237         {
1238             // This is a secondary message with no span info
1239             for _ in 0..max_line_num_len {
1240                 buffer.prepend(0, " ", Style::NoStyle);
1241             }
1242             draw_note_separator(&mut buffer, 0, max_line_num_len + 1);
1243             if *level != Level::FailureNote {
1244                 buffer.append(0, level.to_str(), Style::MainHeaderMsg);
1245                 buffer.append(0, ": ", Style::NoStyle);
1246             }
1247             self.msg_to_buffer(&mut buffer, msg, max_line_num_len, "note", None);
1248         } else {
1249             // The failure note level itself does not provide any useful diagnostic information
1250             if *level != Level::FailureNote {
1251                 buffer.append(0, level.to_str(), Style::Level(*level));
1252             }
1253             // only render error codes, not lint codes
1254             if let Some(DiagnosticId::Error(ref code)) = *code {
1255                 buffer.append(0, "[", Style::Level(*level));
1256                 buffer.append(0, &code, Style::Level(*level));
1257                 buffer.append(0, "]", Style::Level(*level));
1258             }
1259             let header_style = if is_secondary { Style::HeaderMsg } else { Style::MainHeaderMsg };
1260             if *level != Level::FailureNote {
1261                 buffer.append(0, ": ", header_style);
1262             }
1263             for &(ref text, _) in msg.iter() {
1264                 buffer.append(0, &replace_tabs(text), header_style);
1265             }
1266         }
1267
1268         let mut annotated_files = FileWithAnnotatedLines::collect_annotations(msp, &self.sm);
1269
1270         // Make sure our primary file comes first
1271         let (primary_lo, sm) = if let (Some(sm), Some(ref primary_span)) =
1272             (self.sm.as_ref(), msp.primary_span().as_ref())
1273         {
1274             if !primary_span.is_dummy() {
1275                 (sm.lookup_char_pos(primary_span.lo()), sm)
1276             } else {
1277                 emit_to_destination(&buffer.render(), level, &mut self.dst, self.short_message)?;
1278                 return Ok(());
1279             }
1280         } else {
1281             // If we don't have span information, emit and exit
1282             emit_to_destination(&buffer.render(), level, &mut self.dst, self.short_message)?;
1283             return Ok(());
1284         };
1285         if let Ok(pos) =
1286             annotated_files.binary_search_by(|x| x.file.name.cmp(&primary_lo.file.name))
1287         {
1288             annotated_files.swap(0, pos);
1289         }
1290
1291         // Print out the annotate source lines that correspond with the error
1292         for annotated_file in annotated_files {
1293             // we can't annotate anything if the source is unavailable.
1294             if !sm.ensure_source_file_source_present(annotated_file.file.clone()) {
1295                 continue;
1296             }
1297
1298             // print out the span location and spacer before we print the annotated source
1299             // to do this, we need to know if this span will be primary
1300             let is_primary = primary_lo.file.name == annotated_file.file.name;
1301             if is_primary {
1302                 let loc = primary_lo.clone();
1303                 if !self.short_message {
1304                     // remember where we are in the output buffer for easy reference
1305                     let buffer_msg_line_offset = buffer.num_lines();
1306
1307                     buffer.prepend(buffer_msg_line_offset, "--> ", Style::LineNumber);
1308                     buffer.append(
1309                         buffer_msg_line_offset,
1310                         &format!(
1311                             "{}:{}:{}",
1312                             loc.file.name.prefer_local(),
1313                             sm.doctest_offset_line(&loc.file.name, loc.line),
1314                             loc.col.0 + 1,
1315                         ),
1316                         Style::LineAndColumn,
1317                     );
1318                     for _ in 0..max_line_num_len {
1319                         buffer.prepend(buffer_msg_line_offset, " ", Style::NoStyle);
1320                     }
1321                 } else {
1322                     buffer.prepend(
1323                         0,
1324                         &format!(
1325                             "{}:{}:{}: ",
1326                             loc.file.name.prefer_local(),
1327                             sm.doctest_offset_line(&loc.file.name, loc.line),
1328                             loc.col.0 + 1,
1329                         ),
1330                         Style::LineAndColumn,
1331                     );
1332                 }
1333             } else if !self.short_message {
1334                 // remember where we are in the output buffer for easy reference
1335                 let buffer_msg_line_offset = buffer.num_lines();
1336
1337                 // Add spacing line
1338                 draw_col_separator(&mut buffer, buffer_msg_line_offset, max_line_num_len + 1);
1339
1340                 // Then, the secondary file indicator
1341                 buffer.prepend(buffer_msg_line_offset + 1, "::: ", Style::LineNumber);
1342                 let loc = if let Some(first_line) = annotated_file.lines.first() {
1343                     let col = if let Some(first_annotation) = first_line.annotations.first() {
1344                         format!(":{}", first_annotation.start_col + 1)
1345                     } else {
1346                         String::new()
1347                     };
1348                     format!(
1349                         "{}:{}{}",
1350                         annotated_file.file.name.prefer_local(),
1351                         sm.doctest_offset_line(&annotated_file.file.name, first_line.line_index),
1352                         col
1353                     )
1354                 } else {
1355                     format!("{}", annotated_file.file.name.prefer_local())
1356                 };
1357                 buffer.append(buffer_msg_line_offset + 1, &loc, Style::LineAndColumn);
1358                 for _ in 0..max_line_num_len {
1359                     buffer.prepend(buffer_msg_line_offset + 1, " ", Style::NoStyle);
1360                 }
1361             }
1362
1363             if !self.short_message {
1364                 // Put in the spacer between the location and annotated source
1365                 let buffer_msg_line_offset = buffer.num_lines();
1366                 draw_col_separator_no_space(
1367                     &mut buffer,
1368                     buffer_msg_line_offset,
1369                     max_line_num_len + 1,
1370                 );
1371
1372                 // Contains the vertical lines' positions for active multiline annotations
1373                 let mut multilines = FxHashMap::default();
1374
1375                 // Get the left-side margin to remove it
1376                 let mut whitespace_margin = usize::MAX;
1377                 for line_idx in 0..annotated_file.lines.len() {
1378                     let file = annotated_file.file.clone();
1379                     let line = &annotated_file.lines[line_idx];
1380                     if let Some(source_string) = file.get_line(line.line_index - 1) {
1381                         let leading_whitespace = source_string
1382                             .chars()
1383                             .take_while(|c| c.is_whitespace())
1384                             .map(|c| {
1385                                 match c {
1386                                     // Tabs are displayed as 4 spaces
1387                                     '\t' => 4,
1388                                     _ => 1,
1389                                 }
1390                             })
1391                             .sum();
1392                         if source_string.chars().any(|c| !c.is_whitespace()) {
1393                             whitespace_margin = min(whitespace_margin, leading_whitespace);
1394                         }
1395                     }
1396                 }
1397                 if whitespace_margin == usize::MAX {
1398                     whitespace_margin = 0;
1399                 }
1400
1401                 // Left-most column any visible span points at.
1402                 let mut span_left_margin = usize::MAX;
1403                 for line in &annotated_file.lines {
1404                     for ann in &line.annotations {
1405                         span_left_margin = min(span_left_margin, ann.start_col);
1406                         span_left_margin = min(span_left_margin, ann.end_col);
1407                     }
1408                 }
1409                 if span_left_margin == usize::MAX {
1410                     span_left_margin = 0;
1411                 }
1412
1413                 // Right-most column any visible span points at.
1414                 let mut span_right_margin = 0;
1415                 let mut label_right_margin = 0;
1416                 let mut max_line_len = 0;
1417                 for line in &annotated_file.lines {
1418                     max_line_len = max(
1419                         max_line_len,
1420                         annotated_file.file.get_line(line.line_index - 1).map_or(0, |s| s.len()),
1421                     );
1422                     for ann in &line.annotations {
1423                         span_right_margin = max(span_right_margin, ann.start_col);
1424                         span_right_margin = max(span_right_margin, ann.end_col);
1425                         // FIXME: account for labels not in the same line
1426                         let label_right = ann.label.as_ref().map_or(0, |l| l.len() + 1);
1427                         label_right_margin = max(label_right_margin, ann.end_col + label_right);
1428                     }
1429                 }
1430
1431                 let width_offset = 3 + max_line_num_len;
1432                 let code_offset = if annotated_file.multiline_depth == 0 {
1433                     width_offset
1434                 } else {
1435                     width_offset + annotated_file.multiline_depth + 1
1436                 };
1437
1438                 let column_width = if let Some(width) = self.terminal_width {
1439                     width.saturating_sub(code_offset)
1440                 } else if self.ui_testing {
1441                     DEFAULT_COLUMN_WIDTH
1442                 } else {
1443                     termize::dimensions()
1444                         .map(|(w, _)| w.saturating_sub(code_offset))
1445                         .unwrap_or(DEFAULT_COLUMN_WIDTH)
1446                 };
1447
1448                 let margin = Margin::new(
1449                     whitespace_margin,
1450                     span_left_margin,
1451                     span_right_margin,
1452                     label_right_margin,
1453                     column_width,
1454                     max_line_len,
1455                 );
1456
1457                 // Next, output the annotate source for this file
1458                 for line_idx in 0..annotated_file.lines.len() {
1459                     let previous_buffer_line = buffer.num_lines();
1460
1461                     let depths = self.render_source_line(
1462                         &mut buffer,
1463                         annotated_file.file.clone(),
1464                         &annotated_file.lines[line_idx],
1465                         width_offset,
1466                         code_offset,
1467                         margin,
1468                     );
1469
1470                     let mut to_add = FxHashMap::default();
1471
1472                     for (depth, style) in depths {
1473                         if multilines.remove(&depth).is_none() {
1474                             to_add.insert(depth, style);
1475                         }
1476                     }
1477
1478                     // Set the multiline annotation vertical lines to the left of
1479                     // the code in this line.
1480                     for (depth, style) in &multilines {
1481                         for line in previous_buffer_line..buffer.num_lines() {
1482                             draw_multiline_line(&mut buffer, line, width_offset, *depth, *style);
1483                         }
1484                     }
1485                     // check to see if we need to print out or elide lines that come between
1486                     // this annotated line and the next one.
1487                     if line_idx < (annotated_file.lines.len() - 1) {
1488                         let line_idx_delta = annotated_file.lines[line_idx + 1].line_index
1489                             - annotated_file.lines[line_idx].line_index;
1490                         if line_idx_delta > 2 {
1491                             let last_buffer_line_num = buffer.num_lines();
1492                             buffer.puts(last_buffer_line_num, 0, "...", Style::LineNumber);
1493
1494                             // Set the multiline annotation vertical lines on `...` bridging line.
1495                             for (depth, style) in &multilines {
1496                                 draw_multiline_line(
1497                                     &mut buffer,
1498                                     last_buffer_line_num,
1499                                     width_offset,
1500                                     *depth,
1501                                     *style,
1502                                 );
1503                             }
1504                         } else if line_idx_delta == 2 {
1505                             let unannotated_line = annotated_file
1506                                 .file
1507                                 .get_line(annotated_file.lines[line_idx].line_index)
1508                                 .unwrap_or_else(|| Cow::from(""));
1509
1510                             let last_buffer_line_num = buffer.num_lines();
1511
1512                             self.draw_line(
1513                                 &mut buffer,
1514                                 &replace_tabs(&unannotated_line),
1515                                 annotated_file.lines[line_idx + 1].line_index - 1,
1516                                 last_buffer_line_num,
1517                                 width_offset,
1518                                 code_offset,
1519                                 margin,
1520                             );
1521
1522                             for (depth, style) in &multilines {
1523                                 draw_multiline_line(
1524                                     &mut buffer,
1525                                     last_buffer_line_num,
1526                                     width_offset,
1527                                     *depth,
1528                                     *style,
1529                                 );
1530                             }
1531                         }
1532                     }
1533
1534                     multilines.extend(&to_add);
1535                 }
1536             }
1537         }
1538
1539         // final step: take our styled buffer, render it, then output it
1540         emit_to_destination(&buffer.render(), level, &mut self.dst, self.short_message)?;
1541
1542         Ok(())
1543     }
1544
1545     fn emit_suggestion_default(
1546         &mut self,
1547         suggestion: &CodeSuggestion,
1548         level: &Level,
1549         max_line_num_len: usize,
1550     ) -> io::Result<()> {
1551         let sm = match self.sm {
1552             Some(ref sm) => sm,
1553             None => return Ok(()),
1554         };
1555
1556         // Render the replacements for each suggestion
1557         let suggestions = suggestion.splice_lines(&**sm);
1558         debug!("emit_suggestion_default: suggestions={:?}", suggestions);
1559
1560         if suggestions.is_empty() {
1561             // Suggestions coming from macros can have malformed spans. This is a heavy handed
1562             // approach to avoid ICEs by ignoring the suggestion outright.
1563             return Ok(());
1564         }
1565
1566         let mut buffer = StyledBuffer::new();
1567
1568         // Render the suggestion message
1569         buffer.append(0, level.to_str(), Style::Level(*level));
1570         buffer.append(0, ": ", Style::HeaderMsg);
1571
1572         self.msg_to_buffer(
1573             &mut buffer,
1574             &[(suggestion.msg.to_owned(), Style::NoStyle)],
1575             max_line_num_len,
1576             "suggestion",
1577             Some(Style::HeaderMsg),
1578         );
1579
1580         let mut row_num = 2;
1581         let mut notice_capitalization = false;
1582         for (complete, parts, only_capitalization) in suggestions.iter().take(MAX_SUGGESTIONS) {
1583             notice_capitalization |= only_capitalization;
1584             // Only show underline if the suggestion spans a single line and doesn't cover the
1585             // entirety of the code output. If you have multiple replacements in the same line
1586             // of code, show the underline.
1587             let show_underline = !(parts.len() == 1 && parts[0].snippet.trim() == complete.trim())
1588                 && complete.lines().count() == 1;
1589
1590             let lines = sm
1591                 .span_to_lines(parts[0].span)
1592                 .expect("span_to_lines failed when emitting suggestion");
1593
1594             assert!(!lines.lines.is_empty() || parts[0].span.is_dummy());
1595
1596             let line_start = sm.lookup_char_pos(parts[0].span.lo()).line;
1597             draw_col_separator_no_space(&mut buffer, 1, max_line_num_len + 1);
1598             let mut lines = complete.lines();
1599             for (line_pos, line) in lines.by_ref().take(MAX_SUGGESTION_HIGHLIGHT_LINES).enumerate()
1600             {
1601                 // Print the span column to avoid confusion
1602                 buffer.puts(
1603                     row_num,
1604                     0,
1605                     &self.maybe_anonymized(line_start + line_pos),
1606                     Style::LineNumber,
1607                 );
1608                 // print the suggestion
1609                 draw_col_separator(&mut buffer, row_num, max_line_num_len + 1);
1610                 buffer.append(row_num, &replace_tabs(line), Style::NoStyle);
1611                 row_num += 1;
1612             }
1613
1614             // This offset and the ones below need to be signed to account for replacement code
1615             // that is shorter than the original code.
1616             let mut offsets: Vec<(usize, isize)> = Vec::new();
1617             // Only show an underline in the suggestions if the suggestion is not the
1618             // entirety of the code being shown and the displayed code is not multiline.
1619             if show_underline {
1620                 draw_col_separator(&mut buffer, row_num, max_line_num_len + 1);
1621                 for part in parts {
1622                     let span_start_pos = sm.lookup_char_pos(part.span.lo()).col_display;
1623                     let span_end_pos = sm.lookup_char_pos(part.span.hi()).col_display;
1624
1625                     // Do not underline the leading...
1626                     let start = part.snippet.len().saturating_sub(part.snippet.trim_start().len());
1627                     // ...or trailing spaces. Account for substitutions containing unicode
1628                     // characters.
1629                     let sub_len: usize = part
1630                         .snippet
1631                         .trim()
1632                         .chars()
1633                         .map(|ch| unicode_width::UnicodeWidthChar::width(ch).unwrap_or(1))
1634                         .sum();
1635
1636                     let offset: isize = offsets
1637                         .iter()
1638                         .filter_map(
1639                             |(start, v)| if span_start_pos <= *start { None } else { Some(v) },
1640                         )
1641                         .sum();
1642                     let underline_start = (span_start_pos + start) as isize + offset;
1643                     let underline_end = (span_start_pos + start + sub_len) as isize + offset;
1644                     assert!(underline_start >= 0 && underline_end >= 0);
1645                     for p in underline_start..underline_end {
1646                         buffer.putc(
1647                             row_num,
1648                             ((max_line_num_len + 3) as isize + p) as usize,
1649                             '^',
1650                             Style::UnderlinePrimary,
1651                         );
1652                     }
1653                     // underline removals too
1654                     if underline_start == underline_end {
1655                         for p in underline_start - 1..underline_start + 1 {
1656                             buffer.putc(
1657                                 row_num,
1658                                 ((max_line_num_len + 3) as isize + p) as usize,
1659                                 '-',
1660                                 Style::UnderlineSecondary,
1661                             );
1662                         }
1663                     }
1664
1665                     // length of the code after substitution
1666                     let full_sub_len = part
1667                         .snippet
1668                         .chars()
1669                         .map(|ch| unicode_width::UnicodeWidthChar::width(ch).unwrap_or(1))
1670                         .sum::<usize>() as isize;
1671
1672                     // length of the code to be substituted
1673                     let snippet_len = span_end_pos as isize - span_start_pos as isize;
1674                     // For multiple substitutions, use the position *after* the previous
1675                     // substitutions have happened, only when further substitutions are
1676                     // located strictly after.
1677                     offsets.push((span_end_pos, full_sub_len - snippet_len));
1678                 }
1679                 row_num += 1;
1680             }
1681
1682             // if we elided some lines, add an ellipsis
1683             if lines.next().is_some() {
1684                 buffer.puts(row_num, max_line_num_len - 1, "...", Style::LineNumber);
1685             } else if !show_underline {
1686                 draw_col_separator_no_space(&mut buffer, row_num, max_line_num_len + 1);
1687                 row_num += 1;
1688             }
1689         }
1690         if suggestions.len() > MAX_SUGGESTIONS {
1691             let others = suggestions.len() - MAX_SUGGESTIONS;
1692             let msg = format!("and {} other candidate{}", others, pluralize!(others));
1693             buffer.puts(row_num, max_line_num_len + 3, &msg, Style::NoStyle);
1694         } else if notice_capitalization {
1695             let msg = "notice the capitalization difference";
1696             buffer.puts(row_num, max_line_num_len + 3, &msg, Style::NoStyle);
1697         }
1698         emit_to_destination(&buffer.render(), level, &mut self.dst, self.short_message)?;
1699         Ok(())
1700     }
1701
1702     fn emit_messages_default(
1703         &mut self,
1704         level: &Level,
1705         message: &[(String, Style)],
1706         code: &Option<DiagnosticId>,
1707         span: &MultiSpan,
1708         children: &[SubDiagnostic],
1709         suggestions: &[CodeSuggestion],
1710     ) {
1711         let max_line_num_len = if self.ui_testing {
1712             ANONYMIZED_LINE_NUM.len()
1713         } else {
1714             let n = self.get_max_line_num(span, children);
1715             num_decimal_digits(n)
1716         };
1717
1718         match self.emit_message_default(span, message, code, level, max_line_num_len, false) {
1719             Ok(()) => {
1720                 if !children.is_empty()
1721                     || suggestions.iter().any(|s| s.style != SuggestionStyle::CompletelyHidden)
1722                 {
1723                     let mut buffer = StyledBuffer::new();
1724                     if !self.short_message {
1725                         draw_col_separator_no_space(&mut buffer, 0, max_line_num_len + 1);
1726                     }
1727                     if let Err(e) = emit_to_destination(
1728                         &buffer.render(),
1729                         level,
1730                         &mut self.dst,
1731                         self.short_message,
1732                     ) {
1733                         panic!("failed to emit error: {}", e)
1734                     }
1735                 }
1736                 if !self.short_message {
1737                     for child in children {
1738                         let span = child.render_span.as_ref().unwrap_or(&child.span);
1739                         if let Err(err) = self.emit_message_default(
1740                             &span,
1741                             &child.styled_message(),
1742                             &None,
1743                             &child.level,
1744                             max_line_num_len,
1745                             true,
1746                         ) {
1747                             panic!("failed to emit error: {}", err);
1748                         }
1749                     }
1750                     for sugg in suggestions {
1751                         if sugg.style == SuggestionStyle::CompletelyHidden {
1752                             // do not display this suggestion, it is meant only for tools
1753                         } else if sugg.style == SuggestionStyle::HideCodeAlways {
1754                             if let Err(e) = self.emit_message_default(
1755                                 &MultiSpan::new(),
1756                                 &[(sugg.msg.to_owned(), Style::HeaderMsg)],
1757                                 &None,
1758                                 &Level::Help,
1759                                 max_line_num_len,
1760                                 true,
1761                             ) {
1762                                 panic!("failed to emit error: {}", e);
1763                             }
1764                         } else if let Err(e) =
1765                             self.emit_suggestion_default(sugg, &Level::Help, max_line_num_len)
1766                         {
1767                             panic!("failed to emit error: {}", e);
1768                         };
1769                     }
1770                 }
1771             }
1772             Err(e) => panic!("failed to emit error: {}", e),
1773         }
1774
1775         let mut dst = self.dst.writable();
1776         match writeln!(dst) {
1777             Err(e) => panic!("failed to emit error: {}", e),
1778             _ => {
1779                 if let Err(e) = dst.flush() {
1780                     panic!("failed to emit error: {}", e)
1781                 }
1782             }
1783         }
1784     }
1785 }
1786
1787 impl FileWithAnnotatedLines {
1788     /// Preprocess all the annotations so that they are grouped by file and by line number
1789     /// This helps us quickly iterate over the whole message (including secondary file spans)
1790     pub fn collect_annotations(
1791         msp: &MultiSpan,
1792         source_map: &Option<Lrc<SourceMap>>,
1793     ) -> Vec<FileWithAnnotatedLines> {
1794         fn add_annotation_to_file(
1795             file_vec: &mut Vec<FileWithAnnotatedLines>,
1796             file: Lrc<SourceFile>,
1797             line_index: usize,
1798             ann: Annotation,
1799         ) {
1800             for slot in file_vec.iter_mut() {
1801                 // Look through each of our files for the one we're adding to
1802                 if slot.file.name == file.name {
1803                     // See if we already have a line for it
1804                     for line_slot in &mut slot.lines {
1805                         if line_slot.line_index == line_index {
1806                             line_slot.annotations.push(ann);
1807                             return;
1808                         }
1809                     }
1810                     // We don't have a line yet, create one
1811                     slot.lines.push(Line { line_index, annotations: vec![ann] });
1812                     slot.lines.sort();
1813                     return;
1814                 }
1815             }
1816             // This is the first time we're seeing the file
1817             file_vec.push(FileWithAnnotatedLines {
1818                 file,
1819                 lines: vec![Line { line_index, annotations: vec![ann] }],
1820                 multiline_depth: 0,
1821             });
1822         }
1823
1824         let mut output = vec![];
1825         let mut multiline_annotations = vec![];
1826
1827         if let Some(ref sm) = source_map {
1828             for span_label in msp.span_labels() {
1829                 if span_label.span.is_dummy() {
1830                     continue;
1831                 }
1832
1833                 let lo = sm.lookup_char_pos(span_label.span.lo());
1834                 let mut hi = sm.lookup_char_pos(span_label.span.hi());
1835
1836                 // Watch out for "empty spans". If we get a span like 6..6, we
1837                 // want to just display a `^` at 6, so convert that to
1838                 // 6..7. This is degenerate input, but it's best to degrade
1839                 // gracefully -- and the parser likes to supply a span like
1840                 // that for EOF, in particular.
1841
1842                 if lo.col_display == hi.col_display && lo.line == hi.line {
1843                     hi.col_display += 1;
1844                 }
1845
1846                 if lo.line != hi.line {
1847                     let ml = MultilineAnnotation {
1848                         depth: 1,
1849                         line_start: lo.line,
1850                         line_end: hi.line,
1851                         start_col: lo.col_display,
1852                         end_col: hi.col_display,
1853                         is_primary: span_label.is_primary,
1854                         label: span_label.label,
1855                         overlaps_exactly: false,
1856                     };
1857                     multiline_annotations.push((lo.file, ml));
1858                 } else {
1859                     let ann = Annotation {
1860                         start_col: lo.col_display,
1861                         end_col: hi.col_display,
1862                         is_primary: span_label.is_primary,
1863                         label: span_label.label,
1864                         annotation_type: AnnotationType::Singleline,
1865                     };
1866                     add_annotation_to_file(&mut output, lo.file, lo.line, ann);
1867                 };
1868             }
1869         }
1870
1871         // Find overlapping multiline annotations, put them at different depths
1872         multiline_annotations.sort_by_key(|&(_, ref ml)| (ml.line_start, ml.line_end));
1873         for (_, ann) in multiline_annotations.clone() {
1874             for (_, a) in multiline_annotations.iter_mut() {
1875                 // Move all other multiline annotations overlapping with this one
1876                 // one level to the right.
1877                 if !(ann.same_span(a))
1878                     && num_overlap(ann.line_start, ann.line_end, a.line_start, a.line_end, true)
1879                 {
1880                     a.increase_depth();
1881                 } else if ann.same_span(a) && &ann != a {
1882                     a.overlaps_exactly = true;
1883                 } else {
1884                     break;
1885                 }
1886             }
1887         }
1888
1889         let mut max_depth = 0; // max overlapping multiline spans
1890         for (file, ann) in multiline_annotations {
1891             max_depth = max(max_depth, ann.depth);
1892             let mut end_ann = ann.as_end();
1893             if !ann.overlaps_exactly {
1894                 // avoid output like
1895                 //
1896                 //  |        foo(
1897                 //  |   _____^
1898                 //  |  |_____|
1899                 //  | ||         bar,
1900                 //  | ||     );
1901                 //  | ||      ^
1902                 //  | ||______|
1903                 //  |  |______foo
1904                 //  |         baz
1905                 //
1906                 // and instead get
1907                 //
1908                 //  |       foo(
1909                 //  |  _____^
1910                 //  | |         bar,
1911                 //  | |     );
1912                 //  | |      ^
1913                 //  | |      |
1914                 //  | |______foo
1915                 //  |        baz
1916                 add_annotation_to_file(&mut output, file.clone(), ann.line_start, ann.as_start());
1917                 // 4 is the minimum vertical length of a multiline span when presented: two lines
1918                 // of code and two lines of underline. This is not true for the special case where
1919                 // the beginning doesn't have an underline, but the current logic seems to be
1920                 // working correctly.
1921                 let middle = min(ann.line_start + 4, ann.line_end);
1922                 for line in ann.line_start + 1..middle {
1923                     // Every `|` that joins the beginning of the span (`___^`) to the end (`|__^`).
1924                     add_annotation_to_file(&mut output, file.clone(), line, ann.as_line());
1925                 }
1926                 let line_end = ann.line_end - 1;
1927                 if middle < line_end {
1928                     add_annotation_to_file(&mut output, file.clone(), line_end, ann.as_line());
1929                 }
1930             } else {
1931                 end_ann.annotation_type = AnnotationType::Singleline;
1932             }
1933             add_annotation_to_file(&mut output, file, ann.line_end, end_ann);
1934         }
1935         for file_vec in output.iter_mut() {
1936             file_vec.multiline_depth = max_depth;
1937         }
1938         output
1939     }
1940 }
1941
1942 // instead of taking the String length or dividing by 10 while > 0, we multiply a limit by 10 until
1943 // we're higher. If the loop isn't exited by the `return`, the last multiplication will wrap, which
1944 // is OK, because while we cannot fit a higher power of 10 in a usize, the loop will end anyway.
1945 // This is also why we need the max number of decimal digits within a `usize`.
1946 fn num_decimal_digits(num: usize) -> usize {
1947     #[cfg(target_pointer_width = "64")]
1948     const MAX_DIGITS: usize = 20;
1949
1950     #[cfg(target_pointer_width = "32")]
1951     const MAX_DIGITS: usize = 10;
1952
1953     #[cfg(target_pointer_width = "16")]
1954     const MAX_DIGITS: usize = 5;
1955
1956     let mut lim = 10;
1957     for num_digits in 1..MAX_DIGITS {
1958         if num < lim {
1959             return num_digits;
1960         }
1961         lim = lim.wrapping_mul(10);
1962     }
1963     MAX_DIGITS
1964 }
1965
1966 fn replace_tabs(str: &str) -> String {
1967     str.replace('\t', "    ")
1968 }
1969
1970 fn draw_col_separator(buffer: &mut StyledBuffer, line: usize, col: usize) {
1971     buffer.puts(line, col, "| ", Style::LineNumber);
1972 }
1973
1974 fn draw_col_separator_no_space(buffer: &mut StyledBuffer, line: usize, col: usize) {
1975     draw_col_separator_no_space_with_style(buffer, line, col, Style::LineNumber);
1976 }
1977
1978 fn draw_col_separator_no_space_with_style(
1979     buffer: &mut StyledBuffer,
1980     line: usize,
1981     col: usize,
1982     style: Style,
1983 ) {
1984     buffer.putc(line, col, '|', style);
1985 }
1986
1987 fn draw_range(
1988     buffer: &mut StyledBuffer,
1989     symbol: char,
1990     line: usize,
1991     col_from: usize,
1992     col_to: usize,
1993     style: Style,
1994 ) {
1995     for col in col_from..col_to {
1996         buffer.putc(line, col, symbol, style);
1997     }
1998 }
1999
2000 fn draw_note_separator(buffer: &mut StyledBuffer, line: usize, col: usize) {
2001     buffer.puts(line, col, "= ", Style::LineNumber);
2002 }
2003
2004 fn draw_multiline_line(
2005     buffer: &mut StyledBuffer,
2006     line: usize,
2007     offset: usize,
2008     depth: usize,
2009     style: Style,
2010 ) {
2011     buffer.putc(line, offset + depth - 1, '|', style);
2012 }
2013
2014 fn num_overlap(
2015     a_start: usize,
2016     a_end: usize,
2017     b_start: usize,
2018     b_end: usize,
2019     inclusive: bool,
2020 ) -> bool {
2021     let extra = if inclusive { 1 } else { 0 };
2022     (b_start..b_end + extra).contains(&a_start) || (a_start..a_end + extra).contains(&b_start)
2023 }
2024 fn overlaps(a1: &Annotation, a2: &Annotation, padding: usize) -> bool {
2025     num_overlap(a1.start_col, a1.end_col + padding, a2.start_col, a2.end_col, false)
2026 }
2027
2028 fn emit_to_destination(
2029     rendered_buffer: &[Vec<StyledString>],
2030     lvl: &Level,
2031     dst: &mut Destination,
2032     short_message: bool,
2033 ) -> io::Result<()> {
2034     use crate::lock;
2035
2036     let mut dst = dst.writable();
2037
2038     // In order to prevent error message interleaving, where multiple error lines get intermixed
2039     // when multiple compiler processes error simultaneously, we emit errors with additional
2040     // steps.
2041     //
2042     // On Unix systems, we write into a buffered terminal rather than directly to a terminal. When
2043     // the .flush() is called we take the buffer created from the buffered writes and write it at
2044     // one shot.  Because the Unix systems use ANSI for the colors, which is a text-based styling
2045     // scheme, this buffered approach works and maintains the styling.
2046     //
2047     // On Windows, styling happens through calls to a terminal API. This prevents us from using the
2048     // same buffering approach.  Instead, we use a global Windows mutex, which we acquire long
2049     // enough to output the full error message, then we release.
2050     let _buffer_lock = lock::acquire_global_lock("rustc_errors");
2051     for (pos, line) in rendered_buffer.iter().enumerate() {
2052         for part in line {
2053             dst.apply_style(*lvl, part.style)?;
2054             write!(dst, "{}", part.text)?;
2055             dst.reset()?;
2056         }
2057         if !short_message && (!lvl.is_failure_note() || pos != rendered_buffer.len() - 1) {
2058             writeln!(dst)?;
2059         }
2060     }
2061     dst.flush()?;
2062     Ok(())
2063 }
2064
2065 pub enum Destination {
2066     Terminal(StandardStream),
2067     Buffered(BufferWriter),
2068     // The bool denotes whether we should be emitting ansi color codes or not
2069     Raw(Box<(dyn Write + Send)>, bool),
2070 }
2071
2072 pub enum WritableDst<'a> {
2073     Terminal(&'a mut StandardStream),
2074     Buffered(&'a mut BufferWriter, Buffer),
2075     Raw(&'a mut (dyn Write + Send)),
2076     ColoredRaw(Ansi<&'a mut (dyn Write + Send)>),
2077 }
2078
2079 impl Destination {
2080     fn from_stderr(color: ColorConfig) -> Destination {
2081         let choice = color.to_color_choice();
2082         // On Windows we'll be performing global synchronization on the entire
2083         // system for emitting rustc errors, so there's no need to buffer
2084         // anything.
2085         //
2086         // On non-Windows we rely on the atomicity of `write` to ensure errors
2087         // don't get all jumbled up.
2088         if cfg!(windows) {
2089             Terminal(StandardStream::stderr(choice))
2090         } else {
2091             Buffered(BufferWriter::stderr(choice))
2092         }
2093     }
2094
2095     fn writable(&mut self) -> WritableDst<'_> {
2096         match *self {
2097             Destination::Terminal(ref mut t) => WritableDst::Terminal(t),
2098             Destination::Buffered(ref mut t) => {
2099                 let buf = t.buffer();
2100                 WritableDst::Buffered(t, buf)
2101             }
2102             Destination::Raw(ref mut t, false) => WritableDst::Raw(t),
2103             Destination::Raw(ref mut t, true) => WritableDst::ColoredRaw(Ansi::new(t)),
2104         }
2105     }
2106
2107     fn supports_color(&self) -> bool {
2108         match *self {
2109             Self::Terminal(ref stream) => stream.supports_color(),
2110             Self::Buffered(ref buffer) => buffer.buffer().supports_color(),
2111             Self::Raw(_, supports_color) => supports_color,
2112         }
2113     }
2114 }
2115
2116 impl<'a> WritableDst<'a> {
2117     fn apply_style(&mut self, lvl: Level, style: Style) -> io::Result<()> {
2118         let mut spec = ColorSpec::new();
2119         match style {
2120             Style::LineAndColumn => {}
2121             Style::LineNumber => {
2122                 spec.set_bold(true);
2123                 spec.set_intense(true);
2124                 if cfg!(windows) {
2125                     spec.set_fg(Some(Color::Cyan));
2126                 } else {
2127                     spec.set_fg(Some(Color::Blue));
2128                 }
2129             }
2130             Style::Quotation => {}
2131             Style::MainHeaderMsg => {
2132                 spec.set_bold(true);
2133                 if cfg!(windows) {
2134                     spec.set_intense(true).set_fg(Some(Color::White));
2135                 }
2136             }
2137             Style::UnderlinePrimary | Style::LabelPrimary => {
2138                 spec = lvl.color();
2139                 spec.set_bold(true);
2140             }
2141             Style::UnderlineSecondary | Style::LabelSecondary => {
2142                 spec.set_bold(true).set_intense(true);
2143                 if cfg!(windows) {
2144                     spec.set_fg(Some(Color::Cyan));
2145                 } else {
2146                     spec.set_fg(Some(Color::Blue));
2147                 }
2148             }
2149             Style::HeaderMsg | Style::NoStyle => {}
2150             Style::Level(lvl) => {
2151                 spec = lvl.color();
2152                 spec.set_bold(true);
2153             }
2154             Style::Highlight => {
2155                 spec.set_bold(true);
2156             }
2157         }
2158         self.set_color(&spec)
2159     }
2160
2161     fn set_color(&mut self, color: &ColorSpec) -> io::Result<()> {
2162         match *self {
2163             WritableDst::Terminal(ref mut t) => t.set_color(color),
2164             WritableDst::Buffered(_, ref mut t) => t.set_color(color),
2165             WritableDst::ColoredRaw(ref mut t) => t.set_color(color),
2166             WritableDst::Raw(_) => Ok(()),
2167         }
2168     }
2169
2170     fn reset(&mut self) -> io::Result<()> {
2171         match *self {
2172             WritableDst::Terminal(ref mut t) => t.reset(),
2173             WritableDst::Buffered(_, ref mut t) => t.reset(),
2174             WritableDst::ColoredRaw(ref mut t) => t.reset(),
2175             WritableDst::Raw(_) => Ok(()),
2176         }
2177     }
2178 }
2179
2180 impl<'a> Write for WritableDst<'a> {
2181     fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
2182         match *self {
2183             WritableDst::Terminal(ref mut t) => t.write(bytes),
2184             WritableDst::Buffered(_, ref mut buf) => buf.write(bytes),
2185             WritableDst::Raw(ref mut w) => w.write(bytes),
2186             WritableDst::ColoredRaw(ref mut t) => t.write(bytes),
2187         }
2188     }
2189
2190     fn flush(&mut self) -> io::Result<()> {
2191         match *self {
2192             WritableDst::Terminal(ref mut t) => t.flush(),
2193             WritableDst::Buffered(_, ref mut buf) => buf.flush(),
2194             WritableDst::Raw(ref mut w) => w.flush(),
2195             WritableDst::ColoredRaw(ref mut w) => w.flush(),
2196         }
2197     }
2198 }
2199
2200 impl<'a> Drop for WritableDst<'a> {
2201     fn drop(&mut self) {
2202         if let WritableDst::Buffered(ref mut dst, ref mut buf) = self {
2203             drop(dst.print(buf));
2204         }
2205     }
2206 }
2207
2208 /// Whether the original and suggested code are visually similar enough to warrant extra wording.
2209 pub fn is_case_difference(sm: &SourceMap, suggested: &str, sp: Span) -> bool {
2210     // FIXME: this should probably be extended to also account for `FO0` → `FOO` and unicode.
2211     let found = match sm.span_to_snippet(sp) {
2212         Ok(snippet) => snippet,
2213         Err(e) => {
2214             warn!("Invalid span {:?}. Err={:?}", sp, e);
2215             return false;
2216         }
2217     };
2218     let ascii_confusables = &['c', 'f', 'i', 'k', 'o', 's', 'u', 'v', 'w', 'x', 'y', 'z'];
2219     // All the chars that differ in capitalization are confusable (above):
2220     let confusable = iter::zip(found.chars(), suggested.chars())
2221         .filter(|(f, s)| f != s)
2222         .all(|(f, s)| (ascii_confusables.contains(&f) || ascii_confusables.contains(&s)));
2223     confusable && found.to_lowercase() == suggested.to_lowercase()
2224             // FIXME: We sometimes suggest the same thing we already have, which is a
2225             //        bug, but be defensive against that here.
2226             && found != suggested
2227 }