]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_errors/src/emitter.rs
Auto merge of #78429 - casey:doctest-attribute-splitting, r=jyn514
[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     /// Checks if should show explanations about "rustc --explain"
199     fn should_show_explain(&self) -> bool {
200         true
201     }
202
203     /// Checks if we can use colors in the current output stream.
204     fn supports_color(&self) -> bool {
205         false
206     }
207
208     fn source_map(&self) -> Option<&Lrc<SourceMap>>;
209
210     /// Formats the substitutions of the primary_span
211     ///
212     /// The are a lot of conditions to this method, but in short:
213     ///
214     /// * If the current `Diagnostic` has only one visible `CodeSuggestion`,
215     ///   we format the `help` suggestion depending on the content of the
216     ///   substitutions. In that case, we return the modified span only.
217     ///
218     /// * If the current `Diagnostic` has multiple suggestions,
219     ///   we return the original `primary_span` and the original suggestions.
220     fn primary_span_formatted<'a>(
221         &mut self,
222         diag: &'a Diagnostic,
223     ) -> (MultiSpan, &'a [CodeSuggestion]) {
224         let mut primary_span = diag.span.clone();
225         if let Some((sugg, rest)) = diag.suggestions.split_first() {
226             if rest.is_empty() &&
227                // ^ if there is only one suggestion
228                // don't display multi-suggestions as labels
229                sugg.substitutions.len() == 1 &&
230                // don't display multipart suggestions as labels
231                sugg.substitutions[0].parts.len() == 1 &&
232                // don't display long messages as labels
233                sugg.msg.split_whitespace().count() < 10 &&
234                // don't display multiline suggestions as labels
235                !sugg.substitutions[0].parts[0].snippet.contains('\n') &&
236                ![
237                     // when this style is set we want the suggestion to be a message, not inline
238                     SuggestionStyle::HideCodeAlways,
239                     // trivial suggestion for tooling's sake, never shown
240                     SuggestionStyle::CompletelyHidden,
241                     // subtle suggestion, never shown inline
242                     SuggestionStyle::ShowAlways,
243                ].contains(&sugg.style)
244             {
245                 let substitution = &sugg.substitutions[0].parts[0].snippet.trim();
246                 let msg = if substitution.is_empty() || sugg.style.hide_inline() {
247                     // This substitution is only removal OR we explicitly don't want to show the
248                     // code inline (`hide_inline`). Therefore, we don't show the substitution.
249                     format!("help: {}", sugg.msg)
250                 } else {
251                     // Show the default suggestion text with the substitution
252                     format!(
253                         "help: {}{}: `{}`",
254                         sugg.msg,
255                         if self
256                             .source_map()
257                             .map(|sm| is_case_difference(
258                                 &**sm,
259                                 substitution,
260                                 sugg.substitutions[0].parts[0].span,
261                             ))
262                             .unwrap_or(false)
263                         {
264                             " (notice the capitalization)"
265                         } else {
266                             ""
267                         },
268                         substitution,
269                     )
270                 };
271                 primary_span.push_span_label(sugg.substitutions[0].parts[0].span, msg);
272
273                 // We return only the modified primary_span
274                 (primary_span, &[])
275             } else {
276                 // if there are multiple suggestions, print them all in full
277                 // to be consistent. We could try to figure out if we can
278                 // make one (or the first one) inline, but that would give
279                 // undue importance to a semi-random suggestion
280                 (primary_span, &diag.suggestions)
281             }
282         } else {
283             (primary_span, &diag.suggestions)
284         }
285     }
286
287     fn fix_multispans_in_extern_macros_and_render_macro_backtrace(
288         &self,
289         source_map: &Option<Lrc<SourceMap>>,
290         span: &mut MultiSpan,
291         children: &mut Vec<SubDiagnostic>,
292         level: &Level,
293         backtrace: bool,
294     ) {
295         // Check for spans in macros, before `fix_multispans_in_extern_macros`
296         // has a chance to replace them.
297         let has_macro_spans = iter::once(&*span)
298             .chain(children.iter().map(|child| &child.span))
299             .flat_map(|span| span.primary_spans())
300             .flat_map(|sp| sp.macro_backtrace())
301             .find_map(|expn_data| {
302                 match expn_data.kind {
303                     ExpnKind::Root => None,
304
305                     // Skip past non-macro entries, just in case there
306                     // are some which do actually involve macros.
307                     ExpnKind::Inlined | ExpnKind::Desugaring(..) | ExpnKind::AstPass(..) => None,
308
309                     ExpnKind::Macro(macro_kind, _) => Some(macro_kind),
310                 }
311             });
312
313         if !backtrace {
314             self.fix_multispans_in_extern_macros(source_map, span, children);
315         }
316
317         self.render_multispans_macro_backtrace(span, children, backtrace);
318
319         if !backtrace {
320             if let Some(macro_kind) = has_macro_spans {
321                 let msg = format!(
322                     "this {} originates in {} {} \
323                     (in Nightly builds, run with -Z macro-backtrace for more info)",
324                     level,
325                     macro_kind.article(),
326                     macro_kind.descr(),
327                 );
328
329                 children.push(SubDiagnostic {
330                     level: Level::Note,
331                     message: vec![(msg, Style::NoStyle)],
332                     span: MultiSpan::new(),
333                     render_span: None,
334                 });
335             }
336         }
337     }
338
339     fn render_multispans_macro_backtrace(
340         &self,
341         span: &mut MultiSpan,
342         children: &mut Vec<SubDiagnostic>,
343         backtrace: bool,
344     ) {
345         for span in iter::once(span).chain(children.iter_mut().map(|child| &mut child.span)) {
346             self.render_multispan_macro_backtrace(span, backtrace);
347         }
348     }
349
350     fn render_multispan_macro_backtrace(&self, span: &mut MultiSpan, always_backtrace: bool) {
351         let mut new_labels: Vec<(Span, String)> = vec![];
352
353         for &sp in span.primary_spans() {
354             if sp.is_dummy() {
355                 continue;
356             }
357
358             // FIXME(eddyb) use `retain` on `macro_backtrace` to remove all the
359             // entries we don't want to print, to make sure the indices being
360             // printed are contiguous (or omitted if there's only one entry).
361             let macro_backtrace: Vec<_> = sp.macro_backtrace().collect();
362             for (i, trace) in macro_backtrace.iter().rev().enumerate() {
363                 if trace.def_site.is_dummy() {
364                     continue;
365                 }
366
367                 if matches!(trace.kind, ExpnKind::Inlined) {
368                     new_labels
369                         .push((trace.call_site, "in the inlined copy of this code".to_string()));
370                 } else if always_backtrace {
371                     new_labels.push((
372                         trace.def_site,
373                         format!(
374                             "in this expansion of `{}`{}",
375                             trace.kind.descr(),
376                             if macro_backtrace.len() > 1 {
377                                 // if macro_backtrace.len() == 1 it'll be
378                                 // pointed at by "in this macro invocation"
379                                 format!(" (#{})", i + 1)
380                             } else {
381                                 String::new()
382                             },
383                         ),
384                     ));
385                 }
386
387                 // Don't add a label on the call site if the diagnostic itself
388                 // already points to (a part of) that call site, as the label
389                 // is meant for showing the relevant invocation when the actual
390                 // diagnostic is pointing to some part of macro definition.
391                 //
392                 // This also handles the case where an external span got replaced
393                 // with the call site span by `fix_multispans_in_extern_macros`.
394                 //
395                 // NB: `-Zmacro-backtrace` overrides this, for uniformity, as the
396                 // "in this expansion of" label above is always added in that mode,
397                 // and it needs an "in this macro invocation" label to match that.
398                 let redundant_span = trace.call_site.contains(sp);
399
400                 if !redundant_span && matches!(trace.kind, ExpnKind::Macro(MacroKind::Bang, _))
401                     || always_backtrace
402                 {
403                     new_labels.push((
404                         trace.call_site,
405                         format!(
406                             "in this macro invocation{}",
407                             if macro_backtrace.len() > 1 && always_backtrace {
408                                 // only specify order when the macro
409                                 // backtrace is multiple levels deep
410                                 format!(" (#{})", i + 1)
411                             } else {
412                                 String::new()
413                             },
414                         ),
415                     ));
416                 }
417                 if !always_backtrace {
418                     break;
419                 }
420             }
421         }
422
423         for (label_span, label_text) in new_labels {
424             span.push_span_label(label_span, label_text);
425         }
426     }
427
428     // This does a small "fix" for multispans by looking to see if it can find any that
429     // point directly at external macros. Since these are often difficult to read,
430     // this will change the span to point at the use site.
431     fn fix_multispans_in_extern_macros(
432         &self,
433         source_map: &Option<Lrc<SourceMap>>,
434         span: &mut MultiSpan,
435         children: &mut Vec<SubDiagnostic>,
436     ) {
437         debug!("fix_multispans_in_extern_macros: before: span={:?} children={:?}", span, children);
438         for span in iter::once(&mut *span).chain(children.iter_mut().map(|child| &mut child.span)) {
439             self.fix_multispan_in_extern_macros(source_map, span);
440         }
441         debug!("fix_multispans_in_extern_macros: after: span={:?} children={:?}", span, children);
442     }
443
444     // This "fixes" MultiSpans that contain `Span`s pointing to locations inside of external macros.
445     // Since these locations are often difficult to read,
446     // we move these spans from the external macros to their corresponding use site.
447     fn fix_multispan_in_extern_macros(
448         &self,
449         source_map: &Option<Lrc<SourceMap>>,
450         span: &mut MultiSpan,
451     ) {
452         let sm = match source_map {
453             Some(ref sm) => sm,
454             None => return,
455         };
456
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() && sm.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         let header_style = if is_secondary { Style::HeaderMsg } else { Style::MainHeaderMsg };
1236
1237         if !msp.has_primary_spans() && !msp.has_span_labels() && is_secondary && !self.short_message
1238         {
1239             // This is a secondary message with no span info
1240             for _ in 0..max_line_num_len {
1241                 buffer.prepend(0, " ", Style::NoStyle);
1242             }
1243             draw_note_separator(&mut buffer, 0, max_line_num_len + 1);
1244             if *level != Level::FailureNote {
1245                 buffer.append(0, level.to_str(), Style::MainHeaderMsg);
1246                 buffer.append(0, ": ", Style::NoStyle);
1247             }
1248             self.msg_to_buffer(&mut buffer, msg, max_line_num_len, "note", None);
1249         } else {
1250             // The failure note level itself does not provide any useful diagnostic information
1251             if *level != Level::FailureNote {
1252                 buffer.append(0, level.to_str(), Style::Level(*level));
1253             }
1254             // only render error codes, not lint codes
1255             if let Some(DiagnosticId::Error(ref code)) = *code {
1256                 buffer.append(0, "[", Style::Level(*level));
1257                 buffer.append(0, &code, Style::Level(*level));
1258                 buffer.append(0, "]", Style::Level(*level));
1259             }
1260             if *level != Level::FailureNote {
1261                 buffer.append(0, ": ", header_style);
1262             }
1263             for &(ref text, _) in msg.iter() {
1264                 buffer.append(0, 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,
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,
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,
1351                         sm.doctest_offset_line(&annotated_file.file.name, first_line.line_index),
1352                         col
1353                     )
1354                 } else {
1355                     annotated_file.file.name.to_string()
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.get(&depth).is_some() {
1474                             multilines.remove(&depth);
1475                         } else {
1476                             to_add.insert(depth, style);
1477                         }
1478                     }
1479
1480                     // Set the multiline annotation vertical lines to the left of
1481                     // the code in this line.
1482                     for (depth, style) in &multilines {
1483                         for line in previous_buffer_line..buffer.num_lines() {
1484                             draw_multiline_line(&mut buffer, line, width_offset, *depth, *style);
1485                         }
1486                     }
1487                     // check to see if we need to print out or elide lines that come between
1488                     // this annotated line and the next one.
1489                     if line_idx < (annotated_file.lines.len() - 1) {
1490                         let line_idx_delta = annotated_file.lines[line_idx + 1].line_index
1491                             - annotated_file.lines[line_idx].line_index;
1492                         if line_idx_delta > 2 {
1493                             let last_buffer_line_num = buffer.num_lines();
1494                             buffer.puts(last_buffer_line_num, 0, "...", Style::LineNumber);
1495
1496                             // Set the multiline annotation vertical lines on `...` bridging line.
1497                             for (depth, style) in &multilines {
1498                                 draw_multiline_line(
1499                                     &mut buffer,
1500                                     last_buffer_line_num,
1501                                     width_offset,
1502                                     *depth,
1503                                     *style,
1504                                 );
1505                             }
1506                         } else if line_idx_delta == 2 {
1507                             let unannotated_line = annotated_file
1508                                 .file
1509                                 .get_line(annotated_file.lines[line_idx].line_index)
1510                                 .unwrap_or_else(|| Cow::from(""));
1511
1512                             let last_buffer_line_num = buffer.num_lines();
1513
1514                             self.draw_line(
1515                                 &mut buffer,
1516                                 &replace_tabs(&unannotated_line),
1517                                 annotated_file.lines[line_idx + 1].line_index - 1,
1518                                 last_buffer_line_num,
1519                                 width_offset,
1520                                 code_offset,
1521                                 margin,
1522                             );
1523
1524                             for (depth, style) in &multilines {
1525                                 draw_multiline_line(
1526                                     &mut buffer,
1527                                     last_buffer_line_num,
1528                                     width_offset,
1529                                     *depth,
1530                                     *style,
1531                                 );
1532                             }
1533                         }
1534                     }
1535
1536                     multilines.extend(&to_add);
1537                 }
1538             }
1539         }
1540
1541         // final step: take our styled buffer, render it, then output it
1542         emit_to_destination(&buffer.render(), level, &mut self.dst, self.short_message)?;
1543
1544         Ok(())
1545     }
1546
1547     fn emit_suggestion_default(
1548         &mut self,
1549         suggestion: &CodeSuggestion,
1550         level: &Level,
1551         max_line_num_len: usize,
1552     ) -> io::Result<()> {
1553         let sm = match self.sm {
1554             Some(ref sm) => sm,
1555             None => return Ok(()),
1556         };
1557
1558         // Render the replacements for each suggestion
1559         let suggestions = suggestion.splice_lines(&**sm);
1560         debug!("emit_suggestion_default: suggestions={:?}", suggestions);
1561
1562         if suggestions.is_empty() {
1563             // Suggestions coming from macros can have malformed spans. This is a heavy handed
1564             // approach to avoid ICEs by ignoring the suggestion outright.
1565             return Ok(());
1566         }
1567
1568         let mut buffer = StyledBuffer::new();
1569
1570         // Render the suggestion message
1571         buffer.append(0, level.to_str(), Style::Level(*level));
1572         buffer.append(0, ": ", Style::HeaderMsg);
1573
1574         self.msg_to_buffer(
1575             &mut buffer,
1576             &[(suggestion.msg.to_owned(), Style::NoStyle)],
1577             max_line_num_len,
1578             "suggestion",
1579             Some(Style::HeaderMsg),
1580         );
1581
1582         let mut row_num = 2;
1583         let mut notice_capitalization = false;
1584         for (complete, parts, only_capitalization) in suggestions.iter().take(MAX_SUGGESTIONS) {
1585             notice_capitalization |= only_capitalization;
1586             // Only show underline if the suggestion spans a single line and doesn't cover the
1587             // entirety of the code output. If you have multiple replacements in the same line
1588             // of code, show the underline.
1589             let show_underline = !(parts.len() == 1 && parts[0].snippet.trim() == complete.trim())
1590                 && complete.lines().count() == 1;
1591
1592             let lines = sm
1593                 .span_to_lines(parts[0].span)
1594                 .expect("span_to_lines failed when emitting suggestion");
1595
1596             assert!(!lines.lines.is_empty() || parts[0].span.is_dummy());
1597
1598             let line_start = sm.lookup_char_pos(parts[0].span.lo()).line;
1599             draw_col_separator_no_space(&mut buffer, 1, max_line_num_len + 1);
1600             let mut lines = complete.lines();
1601             for (line_pos, line) in lines.by_ref().take(MAX_SUGGESTION_HIGHLIGHT_LINES).enumerate()
1602             {
1603                 // Print the span column to avoid confusion
1604                 buffer.puts(
1605                     row_num,
1606                     0,
1607                     &self.maybe_anonymized(line_start + line_pos),
1608                     Style::LineNumber,
1609                 );
1610                 // print the suggestion
1611                 draw_col_separator(&mut buffer, row_num, max_line_num_len + 1);
1612                 buffer.append(row_num, &replace_tabs(line), Style::NoStyle);
1613                 row_num += 1;
1614             }
1615
1616             // This offset and the ones below need to be signed to account for replacement code
1617             // that is shorter than the original code.
1618             let mut offsets: Vec<(usize, isize)> = Vec::new();
1619             // Only show an underline in the suggestions if the suggestion is not the
1620             // entirety of the code being shown and the displayed code is not multiline.
1621             if show_underline {
1622                 draw_col_separator(&mut buffer, row_num, max_line_num_len + 1);
1623                 for part in parts {
1624                     let span_start_pos = sm.lookup_char_pos(part.span.lo()).col_display;
1625                     let span_end_pos = sm.lookup_char_pos(part.span.hi()).col_display;
1626
1627                     // Do not underline the leading...
1628                     let start = part.snippet.len().saturating_sub(part.snippet.trim_start().len());
1629                     // ...or trailing spaces. Account for substitutions containing unicode
1630                     // characters.
1631                     let sub_len: usize = part
1632                         .snippet
1633                         .trim()
1634                         .chars()
1635                         .map(|ch| unicode_width::UnicodeWidthChar::width(ch).unwrap_or(1))
1636                         .sum();
1637
1638                     let offset: isize = offsets
1639                         .iter()
1640                         .filter_map(
1641                             |(start, v)| if span_start_pos <= *start { None } else { Some(v) },
1642                         )
1643                         .sum();
1644                     let underline_start = (span_start_pos + start) as isize + offset;
1645                     let underline_end = (span_start_pos + start + sub_len) as isize + offset;
1646                     assert!(underline_start >= 0 && underline_end >= 0);
1647                     for p in underline_start..underline_end {
1648                         buffer.putc(
1649                             row_num,
1650                             ((max_line_num_len + 3) as isize + p) as usize,
1651                             '^',
1652                             Style::UnderlinePrimary,
1653                         );
1654                     }
1655                     // underline removals too
1656                     if underline_start == underline_end {
1657                         for p in underline_start - 1..underline_start + 1 {
1658                             buffer.putc(
1659                                 row_num,
1660                                 ((max_line_num_len + 3) as isize + p) as usize,
1661                                 '-',
1662                                 Style::UnderlineSecondary,
1663                             );
1664                         }
1665                     }
1666
1667                     // length of the code after substitution
1668                     let full_sub_len = part
1669                         .snippet
1670                         .chars()
1671                         .map(|ch| unicode_width::UnicodeWidthChar::width(ch).unwrap_or(1))
1672                         .sum::<usize>() as isize;
1673
1674                     // length of the code to be substituted
1675                     let snippet_len = span_end_pos as isize - span_start_pos as isize;
1676                     // For multiple substitutions, use the position *after* the previous
1677                     // substitutions have happened, only when further substitutions are
1678                     // located strictly after.
1679                     offsets.push((span_end_pos, full_sub_len - snippet_len));
1680                 }
1681                 row_num += 1;
1682             }
1683
1684             // if we elided some lines, add an ellipsis
1685             if lines.next().is_some() {
1686                 buffer.puts(row_num, max_line_num_len - 1, "...", Style::LineNumber);
1687             } else if !show_underline {
1688                 draw_col_separator_no_space(&mut buffer, row_num, max_line_num_len + 1);
1689                 row_num += 1;
1690             }
1691         }
1692         if suggestions.len() > MAX_SUGGESTIONS {
1693             let others = suggestions.len() - MAX_SUGGESTIONS;
1694             let msg = format!("and {} other candidate{}", others, pluralize!(others));
1695             buffer.puts(row_num, max_line_num_len + 3, &msg, Style::NoStyle);
1696         } else if notice_capitalization {
1697             let msg = "notice the capitalization difference";
1698             buffer.puts(row_num, max_line_num_len + 3, &msg, Style::NoStyle);
1699         }
1700         emit_to_destination(&buffer.render(), level, &mut self.dst, self.short_message)?;
1701         Ok(())
1702     }
1703
1704     fn emit_messages_default(
1705         &mut self,
1706         level: &Level,
1707         message: &[(String, Style)],
1708         code: &Option<DiagnosticId>,
1709         span: &MultiSpan,
1710         children: &[SubDiagnostic],
1711         suggestions: &[CodeSuggestion],
1712     ) {
1713         let max_line_num_len = if self.ui_testing {
1714             ANONYMIZED_LINE_NUM.len()
1715         } else {
1716             // Instead of using .to_string().len(), we iteratively count the
1717             // number of digits to avoid allocation. This strategy has sizable
1718             // performance gains over the old string strategy.
1719             let mut n = self.get_max_line_num(span, children);
1720             let mut num_digits = 0;
1721             loop {
1722                 num_digits += 1;
1723                 n /= 10;
1724                 if n == 0 {
1725                     break num_digits;
1726                 }
1727             }
1728         };
1729
1730         match self.emit_message_default(span, message, code, level, max_line_num_len, false) {
1731             Ok(()) => {
1732                 if !children.is_empty()
1733                     || suggestions.iter().any(|s| s.style != SuggestionStyle::CompletelyHidden)
1734                 {
1735                     let mut buffer = StyledBuffer::new();
1736                     if !self.short_message {
1737                         draw_col_separator_no_space(&mut buffer, 0, max_line_num_len + 1);
1738                     }
1739                     match emit_to_destination(
1740                         &buffer.render(),
1741                         level,
1742                         &mut self.dst,
1743                         self.short_message,
1744                     ) {
1745                         Ok(()) => (),
1746                         Err(e) => panic!("failed to emit error: {}", e),
1747                     }
1748                 }
1749                 if !self.short_message {
1750                     for child in children {
1751                         let span = child.render_span.as_ref().unwrap_or(&child.span);
1752                         if let Err(err) = self.emit_message_default(
1753                             &span,
1754                             &child.styled_message(),
1755                             &None,
1756                             &child.level,
1757                             max_line_num_len,
1758                             true,
1759                         ) {
1760                             panic!("failed to emit error: {}", err);
1761                         }
1762                     }
1763                     for sugg in suggestions {
1764                         if sugg.style == SuggestionStyle::CompletelyHidden {
1765                             // do not display this suggestion, it is meant only for tools
1766                         } else if sugg.style == SuggestionStyle::HideCodeAlways {
1767                             if let Err(e) = self.emit_message_default(
1768                                 &MultiSpan::new(),
1769                                 &[(sugg.msg.to_owned(), Style::HeaderMsg)],
1770                                 &None,
1771                                 &Level::Help,
1772                                 max_line_num_len,
1773                                 true,
1774                             ) {
1775                                 panic!("failed to emit error: {}", e);
1776                             }
1777                         } else if let Err(e) =
1778                             self.emit_suggestion_default(sugg, &Level::Help, max_line_num_len)
1779                         {
1780                             panic!("failed to emit error: {}", e);
1781                         };
1782                     }
1783                 }
1784             }
1785             Err(e) => panic!("failed to emit error: {}", e),
1786         }
1787
1788         let mut dst = self.dst.writable();
1789         match writeln!(dst) {
1790             Err(e) => panic!("failed to emit error: {}", e),
1791             _ => {
1792                 if let Err(e) = dst.flush() {
1793                     panic!("failed to emit error: {}", e)
1794                 }
1795             }
1796         }
1797     }
1798 }
1799
1800 impl FileWithAnnotatedLines {
1801     /// Preprocess all the annotations so that they are grouped by file and by line number
1802     /// This helps us quickly iterate over the whole message (including secondary file spans)
1803     pub fn collect_annotations(
1804         msp: &MultiSpan,
1805         source_map: &Option<Lrc<SourceMap>>,
1806     ) -> Vec<FileWithAnnotatedLines> {
1807         fn add_annotation_to_file(
1808             file_vec: &mut Vec<FileWithAnnotatedLines>,
1809             file: Lrc<SourceFile>,
1810             line_index: usize,
1811             ann: Annotation,
1812         ) {
1813             for slot in file_vec.iter_mut() {
1814                 // Look through each of our files for the one we're adding to
1815                 if slot.file.name == file.name {
1816                     // See if we already have a line for it
1817                     for line_slot in &mut slot.lines {
1818                         if line_slot.line_index == line_index {
1819                             line_slot.annotations.push(ann);
1820                             return;
1821                         }
1822                     }
1823                     // We don't have a line yet, create one
1824                     slot.lines.push(Line { line_index, annotations: vec![ann] });
1825                     slot.lines.sort();
1826                     return;
1827                 }
1828             }
1829             // This is the first time we're seeing the file
1830             file_vec.push(FileWithAnnotatedLines {
1831                 file,
1832                 lines: vec![Line { line_index, annotations: vec![ann] }],
1833                 multiline_depth: 0,
1834             });
1835         }
1836
1837         let mut output = vec![];
1838         let mut multiline_annotations = vec![];
1839
1840         if let Some(ref sm) = source_map {
1841             for span_label in msp.span_labels() {
1842                 if span_label.span.is_dummy() {
1843                     continue;
1844                 }
1845
1846                 let lo = sm.lookup_char_pos(span_label.span.lo());
1847                 let mut hi = sm.lookup_char_pos(span_label.span.hi());
1848
1849                 // Watch out for "empty spans". If we get a span like 6..6, we
1850                 // want to just display a `^` at 6, so convert that to
1851                 // 6..7. This is degenerate input, but it's best to degrade
1852                 // gracefully -- and the parser likes to supply a span like
1853                 // that for EOF, in particular.
1854
1855                 if lo.col_display == hi.col_display && lo.line == hi.line {
1856                     hi.col_display += 1;
1857                 }
1858
1859                 if lo.line != hi.line {
1860                     let ml = MultilineAnnotation {
1861                         depth: 1,
1862                         line_start: lo.line,
1863                         line_end: hi.line,
1864                         start_col: lo.col_display,
1865                         end_col: hi.col_display,
1866                         is_primary: span_label.is_primary,
1867                         label: span_label.label,
1868                         overlaps_exactly: false,
1869                     };
1870                     multiline_annotations.push((lo.file, ml));
1871                 } else {
1872                     let ann = Annotation {
1873                         start_col: lo.col_display,
1874                         end_col: hi.col_display,
1875                         is_primary: span_label.is_primary,
1876                         label: span_label.label,
1877                         annotation_type: AnnotationType::Singleline,
1878                     };
1879                     add_annotation_to_file(&mut output, lo.file, lo.line, ann);
1880                 };
1881             }
1882         }
1883
1884         // Find overlapping multiline annotations, put them at different depths
1885         multiline_annotations.sort_by_key(|&(_, ref ml)| (ml.line_start, ml.line_end));
1886         for (_, ann) in multiline_annotations.clone() {
1887             for (_, a) in multiline_annotations.iter_mut() {
1888                 // Move all other multiline annotations overlapping with this one
1889                 // one level to the right.
1890                 if !(ann.same_span(a))
1891                     && num_overlap(ann.line_start, ann.line_end, a.line_start, a.line_end, true)
1892                 {
1893                     a.increase_depth();
1894                 } else if ann.same_span(a) && &ann != a {
1895                     a.overlaps_exactly = true;
1896                 } else {
1897                     break;
1898                 }
1899             }
1900         }
1901
1902         let mut max_depth = 0; // max overlapping multiline spans
1903         for (file, ann) in multiline_annotations {
1904             max_depth = max(max_depth, ann.depth);
1905             let mut end_ann = ann.as_end();
1906             if !ann.overlaps_exactly {
1907                 // avoid output like
1908                 //
1909                 //  |        foo(
1910                 //  |   _____^
1911                 //  |  |_____|
1912                 //  | ||         bar,
1913                 //  | ||     );
1914                 //  | ||      ^
1915                 //  | ||______|
1916                 //  |  |______foo
1917                 //  |         baz
1918                 //
1919                 // and instead get
1920                 //
1921                 //  |       foo(
1922                 //  |  _____^
1923                 //  | |         bar,
1924                 //  | |     );
1925                 //  | |      ^
1926                 //  | |      |
1927                 //  | |______foo
1928                 //  |        baz
1929                 add_annotation_to_file(&mut output, file.clone(), ann.line_start, ann.as_start());
1930                 // 4 is the minimum vertical length of a multiline span when presented: two lines
1931                 // of code and two lines of underline. This is not true for the special case where
1932                 // the beginning doesn't have an underline, but the current logic seems to be
1933                 // working correctly.
1934                 let middle = min(ann.line_start + 4, ann.line_end);
1935                 for line in ann.line_start + 1..middle {
1936                     // Every `|` that joins the beginning of the span (`___^`) to the end (`|__^`).
1937                     add_annotation_to_file(&mut output, file.clone(), line, ann.as_line());
1938                 }
1939                 let line_end = ann.line_end - 1;
1940                 if middle < line_end {
1941                     add_annotation_to_file(&mut output, file.clone(), line_end, ann.as_line());
1942                 }
1943             } else {
1944                 end_ann.annotation_type = AnnotationType::Singleline;
1945             }
1946             add_annotation_to_file(&mut output, file, ann.line_end, end_ann);
1947         }
1948         for file_vec in output.iter_mut() {
1949             file_vec.multiline_depth = max_depth;
1950         }
1951         output
1952     }
1953 }
1954
1955 fn replace_tabs(str: &str) -> String {
1956     str.replace('\t', "    ")
1957 }
1958
1959 fn draw_col_separator(buffer: &mut StyledBuffer, line: usize, col: usize) {
1960     buffer.puts(line, col, "| ", Style::LineNumber);
1961 }
1962
1963 fn draw_col_separator_no_space(buffer: &mut StyledBuffer, line: usize, col: usize) {
1964     draw_col_separator_no_space_with_style(buffer, line, col, Style::LineNumber);
1965 }
1966
1967 fn draw_col_separator_no_space_with_style(
1968     buffer: &mut StyledBuffer,
1969     line: usize,
1970     col: usize,
1971     style: Style,
1972 ) {
1973     buffer.putc(line, col, '|', style);
1974 }
1975
1976 fn draw_range(
1977     buffer: &mut StyledBuffer,
1978     symbol: char,
1979     line: usize,
1980     col_from: usize,
1981     col_to: usize,
1982     style: Style,
1983 ) {
1984     for col in col_from..col_to {
1985         buffer.putc(line, col, symbol, style);
1986     }
1987 }
1988
1989 fn draw_note_separator(buffer: &mut StyledBuffer, line: usize, col: usize) {
1990     buffer.puts(line, col, "= ", Style::LineNumber);
1991 }
1992
1993 fn draw_multiline_line(
1994     buffer: &mut StyledBuffer,
1995     line: usize,
1996     offset: usize,
1997     depth: usize,
1998     style: Style,
1999 ) {
2000     buffer.putc(line, offset + depth - 1, '|', style);
2001 }
2002
2003 fn num_overlap(
2004     a_start: usize,
2005     a_end: usize,
2006     b_start: usize,
2007     b_end: usize,
2008     inclusive: bool,
2009 ) -> bool {
2010     let extra = if inclusive { 1 } else { 0 };
2011     (b_start..b_end + extra).contains(&a_start) || (a_start..a_end + extra).contains(&b_start)
2012 }
2013 fn overlaps(a1: &Annotation, a2: &Annotation, padding: usize) -> bool {
2014     num_overlap(a1.start_col, a1.end_col + padding, a2.start_col, a2.end_col, false)
2015 }
2016
2017 fn emit_to_destination(
2018     rendered_buffer: &[Vec<StyledString>],
2019     lvl: &Level,
2020     dst: &mut Destination,
2021     short_message: bool,
2022 ) -> io::Result<()> {
2023     use crate::lock;
2024
2025     let mut dst = dst.writable();
2026
2027     // In order to prevent error message interleaving, where multiple error lines get intermixed
2028     // when multiple compiler processes error simultaneously, we emit errors with additional
2029     // steps.
2030     //
2031     // On Unix systems, we write into a buffered terminal rather than directly to a terminal. When
2032     // the .flush() is called we take the buffer created from the buffered writes and write it at
2033     // one shot.  Because the Unix systems use ANSI for the colors, which is a text-based styling
2034     // scheme, this buffered approach works and maintains the styling.
2035     //
2036     // On Windows, styling happens through calls to a terminal API. This prevents us from using the
2037     // same buffering approach.  Instead, we use a global Windows mutex, which we acquire long
2038     // enough to output the full error message, then we release.
2039     let _buffer_lock = lock::acquire_global_lock("rustc_errors");
2040     for (pos, line) in rendered_buffer.iter().enumerate() {
2041         for part in line {
2042             dst.apply_style(*lvl, part.style)?;
2043             write!(dst, "{}", part.text)?;
2044             dst.reset()?;
2045         }
2046         if !short_message && (!lvl.is_failure_note() || pos != rendered_buffer.len() - 1) {
2047             writeln!(dst)?;
2048         }
2049     }
2050     dst.flush()?;
2051     Ok(())
2052 }
2053
2054 pub enum Destination {
2055     Terminal(StandardStream),
2056     Buffered(BufferWriter),
2057     // The bool denotes whether we should be emitting ansi color codes or not
2058     Raw(Box<(dyn Write + Send)>, bool),
2059 }
2060
2061 pub enum WritableDst<'a> {
2062     Terminal(&'a mut StandardStream),
2063     Buffered(&'a mut BufferWriter, Buffer),
2064     Raw(&'a mut (dyn Write + Send)),
2065     ColoredRaw(Ansi<&'a mut (dyn Write + Send)>),
2066 }
2067
2068 impl Destination {
2069     fn from_stderr(color: ColorConfig) -> Destination {
2070         let choice = color.to_color_choice();
2071         // On Windows we'll be performing global synchronization on the entire
2072         // system for emitting rustc errors, so there's no need to buffer
2073         // anything.
2074         //
2075         // On non-Windows we rely on the atomicity of `write` to ensure errors
2076         // don't get all jumbled up.
2077         if cfg!(windows) {
2078             Terminal(StandardStream::stderr(choice))
2079         } else {
2080             Buffered(BufferWriter::stderr(choice))
2081         }
2082     }
2083
2084     fn writable(&mut self) -> WritableDst<'_> {
2085         match *self {
2086             Destination::Terminal(ref mut t) => WritableDst::Terminal(t),
2087             Destination::Buffered(ref mut t) => {
2088                 let buf = t.buffer();
2089                 WritableDst::Buffered(t, buf)
2090             }
2091             Destination::Raw(ref mut t, false) => WritableDst::Raw(t),
2092             Destination::Raw(ref mut t, true) => WritableDst::ColoredRaw(Ansi::new(t)),
2093         }
2094     }
2095
2096     fn supports_color(&self) -> bool {
2097         match *self {
2098             Self::Terminal(ref stream) => stream.supports_color(),
2099             Self::Buffered(ref buffer) => buffer.buffer().supports_color(),
2100             Self::Raw(_, supports_color) => supports_color,
2101         }
2102     }
2103 }
2104
2105 impl<'a> WritableDst<'a> {
2106     fn apply_style(&mut self, lvl: Level, style: Style) -> io::Result<()> {
2107         let mut spec = ColorSpec::new();
2108         match style {
2109             Style::LineAndColumn => {}
2110             Style::LineNumber => {
2111                 spec.set_bold(true);
2112                 spec.set_intense(true);
2113                 if cfg!(windows) {
2114                     spec.set_fg(Some(Color::Cyan));
2115                 } else {
2116                     spec.set_fg(Some(Color::Blue));
2117                 }
2118             }
2119             Style::Quotation => {}
2120             Style::MainHeaderMsg => {
2121                 spec.set_bold(true);
2122                 if cfg!(windows) {
2123                     spec.set_intense(true).set_fg(Some(Color::White));
2124                 }
2125             }
2126             Style::UnderlinePrimary | Style::LabelPrimary => {
2127                 spec = lvl.color();
2128                 spec.set_bold(true);
2129             }
2130             Style::UnderlineSecondary | Style::LabelSecondary => {
2131                 spec.set_bold(true).set_intense(true);
2132                 if cfg!(windows) {
2133                     spec.set_fg(Some(Color::Cyan));
2134                 } else {
2135                     spec.set_fg(Some(Color::Blue));
2136                 }
2137             }
2138             Style::HeaderMsg | Style::NoStyle => {}
2139             Style::Level(lvl) => {
2140                 spec = lvl.color();
2141                 spec.set_bold(true);
2142             }
2143             Style::Highlight => {
2144                 spec.set_bold(true);
2145             }
2146         }
2147         self.set_color(&spec)
2148     }
2149
2150     fn set_color(&mut self, color: &ColorSpec) -> io::Result<()> {
2151         match *self {
2152             WritableDst::Terminal(ref mut t) => t.set_color(color),
2153             WritableDst::Buffered(_, ref mut t) => t.set_color(color),
2154             WritableDst::ColoredRaw(ref mut t) => t.set_color(color),
2155             WritableDst::Raw(_) => Ok(()),
2156         }
2157     }
2158
2159     fn reset(&mut self) -> io::Result<()> {
2160         match *self {
2161             WritableDst::Terminal(ref mut t) => t.reset(),
2162             WritableDst::Buffered(_, ref mut t) => t.reset(),
2163             WritableDst::ColoredRaw(ref mut t) => t.reset(),
2164             WritableDst::Raw(_) => Ok(()),
2165         }
2166     }
2167 }
2168
2169 impl<'a> Write for WritableDst<'a> {
2170     fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
2171         match *self {
2172             WritableDst::Terminal(ref mut t) => t.write(bytes),
2173             WritableDst::Buffered(_, ref mut buf) => buf.write(bytes),
2174             WritableDst::Raw(ref mut w) => w.write(bytes),
2175             WritableDst::ColoredRaw(ref mut t) => t.write(bytes),
2176         }
2177     }
2178
2179     fn flush(&mut self) -> io::Result<()> {
2180         match *self {
2181             WritableDst::Terminal(ref mut t) => t.flush(),
2182             WritableDst::Buffered(_, ref mut buf) => buf.flush(),
2183             WritableDst::Raw(ref mut w) => w.flush(),
2184             WritableDst::ColoredRaw(ref mut w) => w.flush(),
2185         }
2186     }
2187 }
2188
2189 impl<'a> Drop for WritableDst<'a> {
2190     fn drop(&mut self) {
2191         if let WritableDst::Buffered(ref mut dst, ref mut buf) = self {
2192             drop(dst.print(buf));
2193         }
2194     }
2195 }
2196
2197 /// Whether the original and suggested code are visually similar enough to warrant extra wording.
2198 pub fn is_case_difference(sm: &SourceMap, suggested: &str, sp: Span) -> bool {
2199     // FIXME: this should probably be extended to also account for `FO0` → `FOO` and unicode.
2200     let found = match sm.span_to_snippet(sp) {
2201         Ok(snippet) => snippet,
2202         Err(e) => {
2203             warn!("Invalid span {:?}. Err={:?}", sp, e);
2204             return false;
2205         }
2206     };
2207     let ascii_confusables = &['c', 'f', 'i', 'k', 'o', 's', 'u', 'v', 'w', 'x', 'y', 'z'];
2208     // All the chars that differ in capitalization are confusable (above):
2209     let confusable = found
2210         .chars()
2211         .zip(suggested.chars())
2212         .filter(|(f, s)| f != s)
2213         .all(|(f, s)| (ascii_confusables.contains(&f) || ascii_confusables.contains(&s)));
2214     confusable && found.to_lowercase() == suggested.to_lowercase()
2215             // FIXME: We sometimes suggest the same thing we already have, which is a
2216             //        bug, but be defensive against that here.
2217             && found != suggested
2218 }