1 //! The current rustc diagnostics emitter.
3 //! An `Emitter` takes care of generating the output from a `DiagnosticBuilder` struct.
5 //! There are various `Emitter` implementations that generate different output formats such as
6 //! JSON and human readable output.
8 //! The output types are defined in `rustc_session::config::ErrorOutputType`.
12 use rustc_lint_defs::FutureBreakage;
13 use rustc_span::source_map::SourceMap;
14 use rustc_span::{MultiSpan, SourceFile, Span};
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};
20 use rustc_lint_defs::pluralize;
22 use rustc_data_structures::fx::FxHashMap;
23 use rustc_data_structures::sync::Lrc;
24 use rustc_span::hygiene::{ExpnKind, MacroKind};
26 use std::cmp::{max, min, Reverse};
28 use std::io::prelude::*;
31 use termcolor::{Ansi, BufferWriter, ColorChoice, ColorSpec, StandardStream};
32 use termcolor::{Buffer, Color, WriteColor};
35 /// Default column width, used in tests and when terminal dimensions cannot be determined.
36 const DEFAULT_COLUMN_WIDTH: usize = 140;
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 {
42 AnnotateSnippet(ColorConfig),
46 impl HumanReadableErrorType {
47 /// Returns a (`short`, `color`) tuple
48 pub fn unzip(self) -> (bool, ColorConfig) {
50 HumanReadableErrorType::Default(cc) => (false, cc),
51 HumanReadableErrorType::Short(cc) => (true, cc),
52 HumanReadableErrorType::AnnotateSnippet(cc) => (false, cc),
57 dst: Box<dyn Write + Send>,
58 source_map: Option<Lrc<SourceMap>>,
60 terminal_width: Option<usize>,
61 macro_backtrace: bool,
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)
69 #[derive(Clone, Copy, Debug)]
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.
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
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,
91 whitespace_left: usize,
98 // The 6 is padding to give a bit of room for `...` when displaying:
103 // 16 | ... fn foo(self) -> Self::Bar {
108 whitespace_left: whitespace_left.saturating_sub(6),
109 span_left: span_left.saturating_sub(6),
110 span_right: span_right + 6,
114 label_right: label_right + 6,
116 m.compute(max_line_len);
120 fn was_cut_left(&self) -> bool {
121 self.computed_left > 0
124 fn was_cut_right(&self, line_len: usize) -> bool {
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
133 right < line_len && self.computed_left + self.column_width < line_len
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.
143 // We want to show as much as possible, max_line_len is the right-most boundary for the
145 self.computed_right = max(max_line_len, self.computed_left);
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;
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;
171 fn left(&self, line_len: usize) -> usize {
172 min(self.computed_left, line_len)
175 fn right(&self, line_len: usize) -> usize {
176 if line_len.saturating_sub(self.computed_left) <= self.column_width {
179 min(line_len, self.computed_right)
184 const ANONYMIZED_LINE_NUM: &str = "LL";
186 /// Emitter trait for emitting errors.
188 /// Emit a structured diagnostic.
189 fn emit_diagnostic(&mut self, diag: &Diagnostic);
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) {}
196 fn emit_future_breakage_report(&mut self, _diags: Vec<(FutureBreakage, Diagnostic)>) {}
198 /// Emit list of unused externs
199 fn emit_unused_externs(&mut self, _lint_level: &str, _unused_externs: &[&str]) {}
201 /// Checks if should show explanations about "rustc --explain"
202 fn should_show_explain(&self) -> bool {
206 /// Checks if we can use colors in the current output stream.
207 fn supports_color(&self) -> bool {
211 fn source_map(&self) -> Option<&Lrc<SourceMap>>;
213 /// Formats the substitutions of the primary_span
215 /// The are a lot of conditions to this method, but in short:
217 /// * If the current `Diagnostic` has only one visible `CodeSuggestion`,
218 /// we format the `help` suggestion depending on the content of the
219 /// substitutions. In that case, we return the modified span only.
221 /// * If the current `Diagnostic` has multiple suggestions,
222 /// we return the original `primary_span` and the original suggestions.
223 fn primary_span_formatted<'a>(
225 diag: &'a Diagnostic,
226 ) -> (MultiSpan, &'a [CodeSuggestion]) {
227 let mut primary_span = diag.span.clone();
228 if let Some((sugg, rest)) = diag.suggestions.split_first() {
229 if rest.is_empty() &&
230 // ^ if there is only one suggestion
231 // don't display multi-suggestions as labels
232 sugg.substitutions.len() == 1 &&
233 // don't display multipart suggestions as labels
234 sugg.substitutions[0].parts.len() == 1 &&
235 // don't display long messages as labels
236 sugg.msg.split_whitespace().count() < 10 &&
237 // don't display multiline suggestions as labels
238 !sugg.substitutions[0].parts[0].snippet.contains('\n') &&
240 // when this style is set we want the suggestion to be a message, not inline
241 SuggestionStyle::HideCodeAlways,
242 // trivial suggestion for tooling's sake, never shown
243 SuggestionStyle::CompletelyHidden,
244 // subtle suggestion, never shown inline
245 SuggestionStyle::ShowAlways,
246 ].contains(&sugg.style)
248 let substitution = &sugg.substitutions[0].parts[0].snippet.trim();
249 let msg = if substitution.is_empty() || sugg.style.hide_inline() {
250 // This substitution is only removal OR we explicitly don't want to show the
251 // code inline (`hide_inline`). Therefore, we don't show the substitution.
252 format!("help: {}", sugg.msg)
254 // Show the default suggestion text with the substitution
260 .map(|sm| is_case_difference(
263 sugg.substitutions[0].parts[0].span,
267 " (notice the capitalization)"
274 primary_span.push_span_label(sugg.substitutions[0].parts[0].span, msg);
276 // We return only the modified primary_span
279 // if there are multiple suggestions, print them all in full
280 // to be consistent. We could try to figure out if we can
281 // make one (or the first one) inline, but that would give
282 // undue importance to a semi-random suggestion
283 (primary_span, &diag.suggestions)
286 (primary_span, &diag.suggestions)
290 fn fix_multispans_in_extern_macros_and_render_macro_backtrace(
292 source_map: &Option<Lrc<SourceMap>>,
293 span: &mut MultiSpan,
294 children: &mut Vec<SubDiagnostic>,
298 // Check for spans in macros, before `fix_multispans_in_extern_macros`
299 // has a chance to replace them.
300 let has_macro_spans = iter::once(&*span)
301 .chain(children.iter().map(|child| &child.span))
302 .flat_map(|span| span.primary_spans())
303 .flat_map(|sp| sp.macro_backtrace())
304 .find_map(|expn_data| {
305 match expn_data.kind {
306 ExpnKind::Root => None,
308 // Skip past non-macro entries, just in case there
309 // are some which do actually involve macros.
310 ExpnKind::Inlined | ExpnKind::Desugaring(..) | ExpnKind::AstPass(..) => None,
312 ExpnKind::Macro(macro_kind, _) => Some(macro_kind),
317 self.fix_multispans_in_extern_macros(source_map, span, children);
320 self.render_multispans_macro_backtrace(span, children, backtrace);
323 if let Some(macro_kind) = has_macro_spans {
325 "this {} originates in {} {} \
326 (in Nightly builds, run with -Z macro-backtrace for more info)",
328 macro_kind.article(),
332 children.push(SubDiagnostic {
334 message: vec![(msg, Style::NoStyle)],
335 span: MultiSpan::new(),
342 fn render_multispans_macro_backtrace(
344 span: &mut MultiSpan,
345 children: &mut Vec<SubDiagnostic>,
348 for span in iter::once(span).chain(children.iter_mut().map(|child| &mut child.span)) {
349 self.render_multispan_macro_backtrace(span, backtrace);
353 fn render_multispan_macro_backtrace(&self, span: &mut MultiSpan, always_backtrace: bool) {
354 let mut new_labels: Vec<(Span, String)> = vec![];
356 for &sp in span.primary_spans() {
361 // FIXME(eddyb) use `retain` on `macro_backtrace` to remove all the
362 // entries we don't want to print, to make sure the indices being
363 // printed are contiguous (or omitted if there's only one entry).
364 let macro_backtrace: Vec<_> = sp.macro_backtrace().collect();
365 for (i, trace) in macro_backtrace.iter().rev().enumerate() {
366 if trace.def_site.is_dummy() {
370 if matches!(trace.kind, ExpnKind::Inlined) {
372 .push((trace.call_site, "in the inlined copy of this code".to_string()));
373 } else if always_backtrace {
377 "in this expansion of `{}`{}",
379 if macro_backtrace.len() > 1 {
380 // if macro_backtrace.len() == 1 it'll be
381 // pointed at by "in this macro invocation"
382 format!(" (#{})", i + 1)
390 // Don't add a label on the call site if the diagnostic itself
391 // already points to (a part of) that call site, as the label
392 // is meant for showing the relevant invocation when the actual
393 // diagnostic is pointing to some part of macro definition.
395 // This also handles the case where an external span got replaced
396 // with the call site span by `fix_multispans_in_extern_macros`.
398 // NB: `-Zmacro-backtrace` overrides this, for uniformity, as the
399 // "in this expansion of" label above is always added in that mode,
400 // and it needs an "in this macro invocation" label to match that.
401 let redundant_span = trace.call_site.contains(sp);
403 if !redundant_span && matches!(trace.kind, ExpnKind::Macro(MacroKind::Bang, _))
409 "in this macro invocation{}",
410 if macro_backtrace.len() > 1 && always_backtrace {
411 // only specify order when the macro
412 // backtrace is multiple levels deep
413 format!(" (#{})", i + 1)
420 if !always_backtrace {
426 for (label_span, label_text) in new_labels {
427 span.push_span_label(label_span, label_text);
431 // This does a small "fix" for multispans by looking to see if it can find any that
432 // point directly at external macros. Since these are often difficult to read,
433 // this will change the span to point at the use site.
434 fn fix_multispans_in_extern_macros(
436 source_map: &Option<Lrc<SourceMap>>,
437 span: &mut MultiSpan,
438 children: &mut Vec<SubDiagnostic>,
440 let source_map = if let Some(ref sm) = source_map {
445 debug!("fix_multispans_in_extern_macros: before: span={:?} children={:?}", span, children);
446 self.fix_multispan_in_extern_macros(source_map, span);
447 for child in children.iter_mut() {
448 self.fix_multispan_in_extern_macros(source_map, &mut child.span);
450 debug!("fix_multispans_in_extern_macros: after: span={:?} children={:?}", span, children);
453 // This "fixes" MultiSpans that contain `Span`s pointing to locations inside of external macros.
454 // Since these locations are often difficult to read,
455 // we move these spans from the external macros to their corresponding use site.
456 fn fix_multispan_in_extern_macros(&self, source_map: &Lrc<SourceMap>, span: &mut MultiSpan) {
457 // First, find all the spans in external macros and point instead at their use site.
458 let replacements: Vec<(Span, Span)> = span
462 .chain(span.span_labels().iter().map(|sp_label| sp_label.span))
464 if !sp.is_dummy() && source_map.is_imported(sp) {
465 let maybe_callsite = sp.source_callsite();
466 if sp != maybe_callsite {
467 return Some((sp, maybe_callsite));
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);
481 impl Emitter for EmitterWriter {
482 fn source_map(&self) -> Option<&Lrc<SourceMap>> {
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);
491 self.fix_multispans_in_extern_macros_and_render_macro_backtrace(
496 self.macro_backtrace,
499 self.emit_messages_default(
501 &diag.styled_message(),
509 fn should_show_explain(&self) -> bool {
513 fn supports_color(&self) -> bool {
514 self.dst.supports_color()
518 /// An emitter that does nothing when emitting a diagnostic.
519 pub struct SilentEmitter;
521 impl Emitter for SilentEmitter {
522 fn source_map(&self) -> Option<&Lrc<SourceMap>> {
525 fn emit_diagnostic(&mut self, _: &Diagnostic) {}
528 /// Maximum number of lines we will print for a multiline suggestion; arbitrary.
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
535 /// Arbitrary, but taken from trait import suggestion limit
536 pub const MAX_SUGGESTIONS: usize = 4;
538 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
539 pub enum ColorConfig {
546 fn to_color_choice(self) -> ColorChoice {
548 ColorConfig::Always => {
549 if atty::is(atty::Stream::Stderr) {
552 ColorChoice::AlwaysAnsi
555 ColorConfig::Never => ColorChoice::Never,
556 ColorConfig::Auto if atty::is(atty::Stream::Stderr) => ColorChoice::Auto,
557 ColorConfig::Auto => ColorChoice::Never,
560 fn suggests_using_colors(self) -> bool {
562 ColorConfig::Always | ColorConfig::Auto => true,
563 ColorConfig::Never => false,
568 /// Handles the writing of `HumanReadableErrorType::Default` and `HumanReadableErrorType::Short`
569 pub struct EmitterWriter {
571 sm: Option<Lrc<SourceMap>>,
575 terminal_width: Option<usize>,
577 macro_backtrace: bool,
581 pub struct FileWithAnnotatedLines {
582 pub file: Lrc<SourceFile>,
583 pub lines: Vec<Line>,
584 multiline_depth: usize,
589 color_config: ColorConfig,
590 source_map: Option<Lrc<SourceMap>>,
593 terminal_width: Option<usize>,
594 macro_backtrace: bool,
596 let dst = Destination::from_stderr(color_config);
609 dst: Box<dyn Write + Send>,
610 source_map: Option<Lrc<SourceMap>>,
614 terminal_width: Option<usize>,
615 macro_backtrace: bool,
618 dst: Raw(dst, colored),
628 pub fn ui_testing(mut self, ui_testing: bool) -> Self {
629 self.ui_testing = ui_testing;
633 fn maybe_anonymized(&self, line_num: usize) -> String {
634 if self.ui_testing { ANONYMIZED_LINE_NUM.to_string() } else { line_num.to_string() }
639 buffer: &mut StyledBuffer,
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.
655 let code: String = source_string
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 {
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);
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);
679 buffer.puts(line_offset, 0, &self.maybe_anonymized(line_index), Style::LineNumber);
681 draw_col_separator(buffer, line_offset, width_offset - 2);
684 fn render_source_line(
686 buffer: &mut StyledBuffer,
687 file: Lrc<SourceFile>,
692 ) -> Vec<(usize, Style)> {
698 // | secondary span label
700 // ^^ ^ ^^^ ^^^^ ^^^ we don't care about code too far to the right of a span, we trim it
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
707 if line.line_index == 0 {
711 let source_string = match file.get_line(line.line_index - 1) {
712 Some(s) => replace_tabs(&*s),
713 None => return Vec::new(),
716 let line_offset = buffer.num_lines();
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
723 .map(|ch| unicode_width::UnicodeWidthChar::width(ch).unwrap_or(1))
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
746 // we simplify the output to:
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
758 Style::UnderlineSecondary
760 buffer.putc(line_offset, width_offset + depth - 1, '/', style);
761 return vec![(depth, style)];
766 // We want to display like this:
768 // vec.push(vec.pop().unwrap());
769 // --- ^^^ - previous borrow ends here
771 // | error occurs here
772 // previous borrow of `vec` occurs here
774 // But there are some weird edge cases to be aware of:
776 // vec.push(vec.pop().unwrap());
777 // -------- - previous borrow ends here
779 // |this makes no sense
780 // previous borrow of `vec` occurs here
782 // For this reason, we group the lines into "highlight lines"
783 // and "annotations lines", where the highlight lines have the `^`.
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.
798 let mut annotations = line.annotations.clone();
799 annotations.sort_by_key(|a| Reverse(a.start_col));
801 // First, figure out where each label will be positioned.
803 // In the case where you have the following annotations:
805 // vec.push(vec.pop().unwrap());
806 // -------- - previous borrow ends here [C]
808 // |this makes no sense [B]
809 // previous borrow of `vec` occurs here [A]
811 // `annotations_position` will hold [(2, A), (1, B), (0, C)].
813 // We try, when possible, to stick the rightmost annotation at the end
814 // of the highlight line:
816 // vec.push(vec.pop().unwrap());
817 // --- --- - previous borrow ends here
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):
828 // In this case, we can't stick the rightmost-most label on
829 // the highlight line, or we would get:
836 // which is totally weird. Instead we want:
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:
863 let mut annotations_position = vec![];
864 let mut line_len = 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).
872 // We're currently on the first line, move the label one line down
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
883 // This annotation needs a new line in the output.
888 annotations_position.push((p, annotation));
889 for (j, next) in annotations.iter().enumerate() {
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:
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
916 // This annotation needs a new line in the output.
922 line_len = max(line_len, p);
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()) {
935 // Write the column separator.
937 // After this we will have:
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);
951 // Write the horizontal lines for multiline annotations
952 // (only the first and last lines need this).
954 // After this we will have:
963 for &(pos, annotation) in &annotations_position {
964 let style = if annotation.is_primary {
965 Style::UnderlinePrimary
967 Style::UnderlineSecondary
970 match annotation.annotation_type {
971 AnnotationType::MultilineStart(depth) | AnnotationType::MultilineEnd(depth) => {
976 width_offset + depth,
977 (code_offset + annotation.start_col).saturating_sub(left),
982 buffer.set_style_range(
984 (code_offset + annotation.start_col).saturating_sub(left),
985 (code_offset + annotation.end_col).saturating_sub(left),
987 annotation.is_primary,
994 // Write the vertical lines for labels that are on a different line as the underline.
996 // After this we will have:
1005 for &(pos, annotation) in &annotations_position {
1006 let style = if annotation.is_primary {
1007 Style::UnderlinePrimary
1009 Style::UnderlineSecondary
1013 if pos > 1 && (annotation.has_label() || annotation.takes_space()) {
1014 for p in line_offset + 1..=line_offset + pos {
1017 (code_offset + annotation.start_col).saturating_sub(left),
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);
1029 AnnotationType::MultilineEnd(depth) => {
1030 for p in line_offset..=line_offset + pos {
1031 buffer.putc(p, width_offset + depth - 1, '|', style);
1038 // Write the labels on the annotations that actually have a label.
1040 // After this we will have:
1045 // | something about `foo`
1049 for &(pos, annotation) in &annotations_position {
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))
1055 (pos + 2, annotation.start_col.saturating_sub(left))
1057 if let Some(ref label) = annotation.label {
1058 buffer.puts(line_offset + pos, code_offset + col, &label, style);
1062 // Sort from biggest span to smallest span so that smaller spans are
1063 // represented in the output:
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)
1075 // Write the underlines.
1077 // After this we will have:
1082 // | something about `foo`
1086 for &(_, annotation) in &annotations_position {
1087 let (underline, style) = if annotation.is_primary {
1088 ('^', Style::UnderlinePrimary)
1090 ('-', Style::UnderlineSecondary)
1092 for p in annotation.start_col..annotation.end_col {
1095 (code_offset + p).saturating_sub(left),
1101 annotations_position
1103 .filter_map(|&(_, annotation)| match annotation.annotation_type {
1104 AnnotationType::MultilineStart(p) | AnnotationType::MultilineEnd(p) => {
1105 let style = if annotation.is_primary {
1108 Style::LabelSecondary
1114 .collect::<Vec<_>>()
1117 fn get_multispan_max_line_num(&mut self, msp: &MultiSpan) -> usize {
1118 let sm = match self.sm {
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);
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);
1142 fn get_max_line_num(&mut self, span: &MultiSpan, children: &[SubDiagnostic]) -> usize {
1143 let primary = self.get_multispan_max_line_num(span);
1146 .map(|sub| self.get_multispan_max_line_num(&sub.span))
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.
1156 buffer: &mut StyledBuffer,
1157 msg: &[(String, Style)],
1160 override_style: Option<Style>,
1162 // The extra 5 ` ` is padding that's always needed to align to the `note: `:
1165 // --> file.rs:13:20
1170 // = note: multiline
1175 // | | length of label
1177 // `max_line_num_len`
1178 let padding = " ".repeat(padding + label.len() + 5);
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_,
1188 let mut line_number = 0;
1190 // Provided the following diagnostic message:
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),
1202 // the expected output on a note is (* surround the highlighted text)
1204 // = note: highlighted multiline
1206 // see how it *looks* with
1207 // very *weird* formats
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() {
1215 buffer.append(line_number, &padding, Style::NoStyle);
1217 buffer.append(line_number, line, style_or_override(*style, override_style));
1220 buffer.append(line_number, text, style_or_override(*style, override_style));
1225 fn emit_message_default(
1228 msg: &[(String, Style)],
1229 code: &Option<DiagnosticId>,
1231 max_line_num_len: usize,
1233 ) -> io::Result<()> {
1234 let mut buffer = StyledBuffer::new();
1236 if !msp.has_primary_spans() && !msp.has_span_labels() && is_secondary && !self.short_message
1238 // This is a secondary message with no span info
1239 for _ in 0..max_line_num_len {
1240 buffer.prepend(0, " ", Style::NoStyle);
1242 draw_note_separator(&mut buffer, 0, max_line_num_len + 1);
1243 if *level != Level::FailureNote {
1244 buffer.append(0, level.to_str(), Style::MainHeaderMsg);
1245 buffer.append(0, ": ", Style::NoStyle);
1247 self.msg_to_buffer(&mut buffer, msg, max_line_num_len, "note", None);
1249 // The failure note level itself does not provide any useful diagnostic information
1250 if *level != Level::FailureNote {
1251 buffer.append(0, level.to_str(), Style::Level(*level));
1253 // only render error codes, not lint codes
1254 if let Some(DiagnosticId::Error(ref code)) = *code {
1255 buffer.append(0, "[", Style::Level(*level));
1256 buffer.append(0, &code, Style::Level(*level));
1257 buffer.append(0, "]", Style::Level(*level));
1259 let header_style = if is_secondary { Style::HeaderMsg } else { Style::MainHeaderMsg };
1260 if *level != Level::FailureNote {
1261 buffer.append(0, ": ", header_style);
1263 for &(ref text, _) in msg.iter() {
1264 buffer.append(0, &replace_tabs(text), header_style);
1268 let mut annotated_files = FileWithAnnotatedLines::collect_annotations(msp, &self.sm);
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())
1274 if !primary_span.is_dummy() {
1275 (sm.lookup_char_pos(primary_span.lo()), sm)
1277 emit_to_destination(&buffer.render(), level, &mut self.dst, self.short_message)?;
1281 // If we don't have span information, emit and exit
1282 emit_to_destination(&buffer.render(), level, &mut self.dst, self.short_message)?;
1286 annotated_files.binary_search_by(|x| x.file.name.cmp(&primary_lo.file.name))
1288 annotated_files.swap(0, pos);
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()) {
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;
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();
1307 buffer.prepend(buffer_msg_line_offset, "--> ", Style::LineNumber);
1309 buffer_msg_line_offset,
1312 loc.file.name.prefer_local(),
1313 sm.doctest_offset_line(&loc.file.name, loc.line),
1316 Style::LineAndColumn,
1318 for _ in 0..max_line_num_len {
1319 buffer.prepend(buffer_msg_line_offset, " ", Style::NoStyle);
1326 loc.file.name.prefer_local(),
1327 sm.doctest_offset_line(&loc.file.name, loc.line),
1330 Style::LineAndColumn,
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();
1338 draw_col_separator(&mut buffer, buffer_msg_line_offset, max_line_num_len + 1);
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)
1350 annotated_file.file.name.prefer_local(),
1351 sm.doctest_offset_line(&annotated_file.file.name, first_line.line_index),
1355 format!("{}", annotated_file.file.name.prefer_local())
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);
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(
1368 buffer_msg_line_offset,
1369 max_line_num_len + 1,
1372 // Contains the vertical lines' positions for active multiline annotations
1373 let mut multilines = FxHashMap::default();
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
1383 .take_while(|c| c.is_whitespace())
1386 // Tabs are displayed as 4 spaces
1392 if source_string.chars().any(|c| !c.is_whitespace()) {
1393 whitespace_margin = min(whitespace_margin, leading_whitespace);
1397 if whitespace_margin == usize::MAX {
1398 whitespace_margin = 0;
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);
1409 if span_left_margin == usize::MAX {
1410 span_left_margin = 0;
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 {
1420 annotated_file.file.get_line(line.line_index - 1).map_or(0, |s| s.len()),
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);
1431 let width_offset = 3 + max_line_num_len;
1432 let code_offset = if annotated_file.multiline_depth == 0 {
1435 width_offset + annotated_file.multiline_depth + 1
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
1443 termize::dimensions()
1444 .map(|(w, _)| w.saturating_sub(code_offset))
1445 .unwrap_or(DEFAULT_COLUMN_WIDTH)
1448 let margin = Margin::new(
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();
1461 let depths = self.render_source_line(
1463 annotated_file.file.clone(),
1464 &annotated_file.lines[line_idx],
1470 let mut to_add = FxHashMap::default();
1472 for (depth, style) in depths {
1473 if multilines.remove(&depth).is_none() {
1474 to_add.insert(depth, style);
1478 // Set the multiline annotation vertical lines to the left of
1479 // the code in this line.
1480 for (depth, style) in &multilines {
1481 for line in previous_buffer_line..buffer.num_lines() {
1482 draw_multiline_line(&mut buffer, line, width_offset, *depth, *style);
1485 // check to see if we need to print out or elide lines that come between
1486 // this annotated line and the next one.
1487 if line_idx < (annotated_file.lines.len() - 1) {
1488 let line_idx_delta = annotated_file.lines[line_idx + 1].line_index
1489 - annotated_file.lines[line_idx].line_index;
1490 if line_idx_delta > 2 {
1491 let last_buffer_line_num = buffer.num_lines();
1492 buffer.puts(last_buffer_line_num, 0, "...", Style::LineNumber);
1494 // Set the multiline annotation vertical lines on `...` bridging line.
1495 for (depth, style) in &multilines {
1496 draw_multiline_line(
1498 last_buffer_line_num,
1504 } else if line_idx_delta == 2 {
1505 let unannotated_line = annotated_file
1507 .get_line(annotated_file.lines[line_idx].line_index)
1508 .unwrap_or_else(|| Cow::from(""));
1510 let last_buffer_line_num = buffer.num_lines();
1514 &replace_tabs(&unannotated_line),
1515 annotated_file.lines[line_idx + 1].line_index - 1,
1516 last_buffer_line_num,
1522 for (depth, style) in &multilines {
1523 draw_multiline_line(
1525 last_buffer_line_num,
1534 multilines.extend(&to_add);
1539 // final step: take our styled buffer, render it, then output it
1540 emit_to_destination(&buffer.render(), level, &mut self.dst, self.short_message)?;
1545 fn emit_suggestion_default(
1547 suggestion: &CodeSuggestion,
1549 max_line_num_len: usize,
1550 ) -> io::Result<()> {
1551 let sm = match self.sm {
1553 None => return Ok(()),
1556 // Render the replacements for each suggestion
1557 let suggestions = suggestion.splice_lines(&**sm);
1558 debug!("emit_suggestion_default: suggestions={:?}", suggestions);
1560 if suggestions.is_empty() {
1561 // Suggestions coming from macros can have malformed spans. This is a heavy handed
1562 // approach to avoid ICEs by ignoring the suggestion outright.
1566 let mut buffer = StyledBuffer::new();
1568 // Render the suggestion message
1569 buffer.append(0, level.to_str(), Style::Level(*level));
1570 buffer.append(0, ": ", Style::HeaderMsg);
1574 &[(suggestion.msg.to_owned(), Style::NoStyle)],
1577 Some(Style::HeaderMsg),
1580 let mut row_num = 2;
1581 let mut notice_capitalization = false;
1582 for (complete, parts, only_capitalization) in suggestions.iter().take(MAX_SUGGESTIONS) {
1583 notice_capitalization |= only_capitalization;
1584 // Only show underline if the suggestion spans a single line and doesn't cover the
1585 // entirety of the code output. If you have multiple replacements in the same line
1586 // of code, show the underline.
1587 let show_underline = !(parts.len() == 1 && parts[0].snippet.trim() == complete.trim())
1588 && complete.lines().count() == 1;
1591 .span_to_lines(parts[0].span)
1592 .expect("span_to_lines failed when emitting suggestion");
1594 assert!(!lines.lines.is_empty() || parts[0].span.is_dummy());
1596 let line_start = sm.lookup_char_pos(parts[0].span.lo()).line;
1597 draw_col_separator_no_space(&mut buffer, 1, max_line_num_len + 1);
1598 let mut lines = complete.lines();
1599 for (line_pos, line) in lines.by_ref().take(MAX_SUGGESTION_HIGHLIGHT_LINES).enumerate()
1601 // Print the span column to avoid confusion
1605 &self.maybe_anonymized(line_start + line_pos),
1608 // print the suggestion
1609 draw_col_separator(&mut buffer, row_num, max_line_num_len + 1);
1610 buffer.append(row_num, &replace_tabs(line), Style::NoStyle);
1614 // This offset and the ones below need to be signed to account for replacement code
1615 // that is shorter than the original code.
1616 let mut offsets: Vec<(usize, isize)> = Vec::new();
1617 // Only show an underline in the suggestions if the suggestion is not the
1618 // entirety of the code being shown and the displayed code is not multiline.
1620 draw_col_separator(&mut buffer, row_num, max_line_num_len + 1);
1622 let span_start_pos = sm.lookup_char_pos(part.span.lo()).col_display;
1623 let span_end_pos = sm.lookup_char_pos(part.span.hi()).col_display;
1625 // Do not underline the leading...
1626 let start = part.snippet.len().saturating_sub(part.snippet.trim_start().len());
1627 // ...or trailing spaces. Account for substitutions containing unicode
1629 let sub_len: usize = part
1633 .map(|ch| unicode_width::UnicodeWidthChar::width(ch).unwrap_or(1))
1636 let offset: isize = offsets
1639 |(start, v)| if span_start_pos <= *start { None } else { Some(v) },
1642 let underline_start = (span_start_pos + start) as isize + offset;
1643 let underline_end = (span_start_pos + start + sub_len) as isize + offset;
1644 assert!(underline_start >= 0 && underline_end >= 0);
1645 for p in underline_start..underline_end {
1648 ((max_line_num_len + 3) as isize + p) as usize,
1650 Style::UnderlinePrimary,
1653 // underline removals too
1654 if underline_start == underline_end {
1655 for p in underline_start - 1..underline_start + 1 {
1658 ((max_line_num_len + 3) as isize + p) as usize,
1660 Style::UnderlineSecondary,
1665 // length of the code after substitution
1666 let full_sub_len = part
1669 .map(|ch| unicode_width::UnicodeWidthChar::width(ch).unwrap_or(1))
1670 .sum::<usize>() as isize;
1672 // length of the code to be substituted
1673 let snippet_len = span_end_pos as isize - span_start_pos as isize;
1674 // For multiple substitutions, use the position *after* the previous
1675 // substitutions have happened, only when further substitutions are
1676 // located strictly after.
1677 offsets.push((span_end_pos, full_sub_len - snippet_len));
1682 // if we elided some lines, add an ellipsis
1683 if lines.next().is_some() {
1684 buffer.puts(row_num, max_line_num_len - 1, "...", Style::LineNumber);
1685 } else if !show_underline {
1686 draw_col_separator_no_space(&mut buffer, row_num, max_line_num_len + 1);
1690 if suggestions.len() > MAX_SUGGESTIONS {
1691 let others = suggestions.len() - MAX_SUGGESTIONS;
1692 let msg = format!("and {} other candidate{}", others, pluralize!(others));
1693 buffer.puts(row_num, max_line_num_len + 3, &msg, Style::NoStyle);
1694 } else if notice_capitalization {
1695 let msg = "notice the capitalization difference";
1696 buffer.puts(row_num, max_line_num_len + 3, &msg, Style::NoStyle);
1698 emit_to_destination(&buffer.render(), level, &mut self.dst, self.short_message)?;
1702 fn emit_messages_default(
1705 message: &[(String, Style)],
1706 code: &Option<DiagnosticId>,
1708 children: &[SubDiagnostic],
1709 suggestions: &[CodeSuggestion],
1711 let max_line_num_len = if self.ui_testing {
1712 ANONYMIZED_LINE_NUM.len()
1714 let n = self.get_max_line_num(span, children);
1715 num_decimal_digits(n)
1718 match self.emit_message_default(span, message, code, level, max_line_num_len, false) {
1720 if !children.is_empty()
1721 || suggestions.iter().any(|s| s.style != SuggestionStyle::CompletelyHidden)
1723 let mut buffer = StyledBuffer::new();
1724 if !self.short_message {
1725 draw_col_separator_no_space(&mut buffer, 0, max_line_num_len + 1);
1727 if let Err(e) = emit_to_destination(
1733 panic!("failed to emit error: {}", e)
1736 if !self.short_message {
1737 for child in children {
1738 let span = child.render_span.as_ref().unwrap_or(&child.span);
1739 if let Err(err) = self.emit_message_default(
1741 &child.styled_message(),
1747 panic!("failed to emit error: {}", err);
1750 for sugg in suggestions {
1751 if sugg.style == SuggestionStyle::CompletelyHidden {
1752 // do not display this suggestion, it is meant only for tools
1753 } else if sugg.style == SuggestionStyle::HideCodeAlways {
1754 if let Err(e) = self.emit_message_default(
1756 &[(sugg.msg.to_owned(), Style::HeaderMsg)],
1762 panic!("failed to emit error: {}", e);
1764 } else if let Err(e) =
1765 self.emit_suggestion_default(sugg, &Level::Help, max_line_num_len)
1767 panic!("failed to emit error: {}", e);
1772 Err(e) => panic!("failed to emit error: {}", e),
1775 let mut dst = self.dst.writable();
1776 match writeln!(dst) {
1777 Err(e) => panic!("failed to emit error: {}", e),
1779 if let Err(e) = dst.flush() {
1780 panic!("failed to emit error: {}", e)
1787 impl FileWithAnnotatedLines {
1788 /// Preprocess all the annotations so that they are grouped by file and by line number
1789 /// This helps us quickly iterate over the whole message (including secondary file spans)
1790 pub fn collect_annotations(
1792 source_map: &Option<Lrc<SourceMap>>,
1793 ) -> Vec<FileWithAnnotatedLines> {
1794 fn add_annotation_to_file(
1795 file_vec: &mut Vec<FileWithAnnotatedLines>,
1796 file: Lrc<SourceFile>,
1800 for slot in file_vec.iter_mut() {
1801 // Look through each of our files for the one we're adding to
1802 if slot.file.name == file.name {
1803 // See if we already have a line for it
1804 for line_slot in &mut slot.lines {
1805 if line_slot.line_index == line_index {
1806 line_slot.annotations.push(ann);
1810 // We don't have a line yet, create one
1811 slot.lines.push(Line { line_index, annotations: vec![ann] });
1816 // This is the first time we're seeing the file
1817 file_vec.push(FileWithAnnotatedLines {
1819 lines: vec![Line { line_index, annotations: vec![ann] }],
1824 let mut output = vec![];
1825 let mut multiline_annotations = vec![];
1827 if let Some(ref sm) = source_map {
1828 for span_label in msp.span_labels() {
1829 if span_label.span.is_dummy() {
1833 let lo = sm.lookup_char_pos(span_label.span.lo());
1834 let mut hi = sm.lookup_char_pos(span_label.span.hi());
1836 // Watch out for "empty spans". If we get a span like 6..6, we
1837 // want to just display a `^` at 6, so convert that to
1838 // 6..7. This is degenerate input, but it's best to degrade
1839 // gracefully -- and the parser likes to supply a span like
1840 // that for EOF, in particular.
1842 if lo.col_display == hi.col_display && lo.line == hi.line {
1843 hi.col_display += 1;
1846 if lo.line != hi.line {
1847 let ml = MultilineAnnotation {
1849 line_start: lo.line,
1851 start_col: lo.col_display,
1852 end_col: hi.col_display,
1853 is_primary: span_label.is_primary,
1854 label: span_label.label,
1855 overlaps_exactly: false,
1857 multiline_annotations.push((lo.file, ml));
1859 let ann = Annotation {
1860 start_col: lo.col_display,
1861 end_col: hi.col_display,
1862 is_primary: span_label.is_primary,
1863 label: span_label.label,
1864 annotation_type: AnnotationType::Singleline,
1866 add_annotation_to_file(&mut output, lo.file, lo.line, ann);
1871 // Find overlapping multiline annotations, put them at different depths
1872 multiline_annotations.sort_by_key(|&(_, ref ml)| (ml.line_start, ml.line_end));
1873 for (_, ann) in multiline_annotations.clone() {
1874 for (_, a) in multiline_annotations.iter_mut() {
1875 // Move all other multiline annotations overlapping with this one
1876 // one level to the right.
1877 if !(ann.same_span(a))
1878 && num_overlap(ann.line_start, ann.line_end, a.line_start, a.line_end, true)
1881 } else if ann.same_span(a) && &ann != a {
1882 a.overlaps_exactly = true;
1889 let mut max_depth = 0; // max overlapping multiline spans
1890 for (file, ann) in multiline_annotations {
1891 max_depth = max(max_depth, ann.depth);
1892 let mut end_ann = ann.as_end();
1893 if !ann.overlaps_exactly {
1894 // avoid output like
1916 add_annotation_to_file(&mut output, file.clone(), ann.line_start, ann.as_start());
1917 // 4 is the minimum vertical length of a multiline span when presented: two lines
1918 // of code and two lines of underline. This is not true for the special case where
1919 // the beginning doesn't have an underline, but the current logic seems to be
1920 // working correctly.
1921 let middle = min(ann.line_start + 4, ann.line_end);
1922 for line in ann.line_start + 1..middle {
1923 // Every `|` that joins the beginning of the span (`___^`) to the end (`|__^`).
1924 add_annotation_to_file(&mut output, file.clone(), line, ann.as_line());
1926 let line_end = ann.line_end - 1;
1927 if middle < line_end {
1928 add_annotation_to_file(&mut output, file.clone(), line_end, ann.as_line());
1931 end_ann.annotation_type = AnnotationType::Singleline;
1933 add_annotation_to_file(&mut output, file, ann.line_end, end_ann);
1935 for file_vec in output.iter_mut() {
1936 file_vec.multiline_depth = max_depth;
1942 // instead of taking the String length or dividing by 10 while > 0, we multiply a limit by 10 until
1943 // we're higher. If the loop isn't exited by the `return`, the last multiplication will wrap, which
1944 // is OK, because while we cannot fit a higher power of 10 in a usize, the loop will end anyway.
1945 // This is also why we need the max number of decimal digits within a `usize`.
1946 fn num_decimal_digits(num: usize) -> usize {
1947 #[cfg(target_pointer_width = "64")]
1948 const MAX_DIGITS: usize = 20;
1950 #[cfg(target_pointer_width = "32")]
1951 const MAX_DIGITS: usize = 10;
1953 #[cfg(target_pointer_width = "16")]
1954 const MAX_DIGITS: usize = 5;
1957 for num_digits in 1..MAX_DIGITS {
1961 lim = lim.wrapping_mul(10);
1966 fn replace_tabs(str: &str) -> String {
1967 str.replace('\t', " ")
1970 fn draw_col_separator(buffer: &mut StyledBuffer, line: usize, col: usize) {
1971 buffer.puts(line, col, "| ", Style::LineNumber);
1974 fn draw_col_separator_no_space(buffer: &mut StyledBuffer, line: usize, col: usize) {
1975 draw_col_separator_no_space_with_style(buffer, line, col, Style::LineNumber);
1978 fn draw_col_separator_no_space_with_style(
1979 buffer: &mut StyledBuffer,
1984 buffer.putc(line, col, '|', style);
1988 buffer: &mut StyledBuffer,
1995 for col in col_from..col_to {
1996 buffer.putc(line, col, symbol, style);
2000 fn draw_note_separator(buffer: &mut StyledBuffer, line: usize, col: usize) {
2001 buffer.puts(line, col, "= ", Style::LineNumber);
2004 fn draw_multiline_line(
2005 buffer: &mut StyledBuffer,
2011 buffer.putc(line, offset + depth - 1, '|', style);
2021 let extra = if inclusive { 1 } else { 0 };
2022 (b_start..b_end + extra).contains(&a_start) || (a_start..a_end + extra).contains(&b_start)
2024 fn overlaps(a1: &Annotation, a2: &Annotation, padding: usize) -> bool {
2025 num_overlap(a1.start_col, a1.end_col + padding, a2.start_col, a2.end_col, false)
2028 fn emit_to_destination(
2029 rendered_buffer: &[Vec<StyledString>],
2031 dst: &mut Destination,
2032 short_message: bool,
2033 ) -> io::Result<()> {
2036 let mut dst = dst.writable();
2038 // In order to prevent error message interleaving, where multiple error lines get intermixed
2039 // when multiple compiler processes error simultaneously, we emit errors with additional
2042 // On Unix systems, we write into a buffered terminal rather than directly to a terminal. When
2043 // the .flush() is called we take the buffer created from the buffered writes and write it at
2044 // one shot. Because the Unix systems use ANSI for the colors, which is a text-based styling
2045 // scheme, this buffered approach works and maintains the styling.
2047 // On Windows, styling happens through calls to a terminal API. This prevents us from using the
2048 // same buffering approach. Instead, we use a global Windows mutex, which we acquire long
2049 // enough to output the full error message, then we release.
2050 let _buffer_lock = lock::acquire_global_lock("rustc_errors");
2051 for (pos, line) in rendered_buffer.iter().enumerate() {
2053 dst.apply_style(*lvl, part.style)?;
2054 write!(dst, "{}", part.text)?;
2057 if !short_message && (!lvl.is_failure_note() || pos != rendered_buffer.len() - 1) {
2065 pub enum Destination {
2066 Terminal(StandardStream),
2067 Buffered(BufferWriter),
2068 // The bool denotes whether we should be emitting ansi color codes or not
2069 Raw(Box<(dyn Write + Send)>, bool),
2072 pub enum WritableDst<'a> {
2073 Terminal(&'a mut StandardStream),
2074 Buffered(&'a mut BufferWriter, Buffer),
2075 Raw(&'a mut (dyn Write + Send)),
2076 ColoredRaw(Ansi<&'a mut (dyn Write + Send)>),
2080 fn from_stderr(color: ColorConfig) -> Destination {
2081 let choice = color.to_color_choice();
2082 // On Windows we'll be performing global synchronization on the entire
2083 // system for emitting rustc errors, so there's no need to buffer
2086 // On non-Windows we rely on the atomicity of `write` to ensure errors
2087 // don't get all jumbled up.
2089 Terminal(StandardStream::stderr(choice))
2091 Buffered(BufferWriter::stderr(choice))
2095 fn writable(&mut self) -> WritableDst<'_> {
2097 Destination::Terminal(ref mut t) => WritableDst::Terminal(t),
2098 Destination::Buffered(ref mut t) => {
2099 let buf = t.buffer();
2100 WritableDst::Buffered(t, buf)
2102 Destination::Raw(ref mut t, false) => WritableDst::Raw(t),
2103 Destination::Raw(ref mut t, true) => WritableDst::ColoredRaw(Ansi::new(t)),
2107 fn supports_color(&self) -> bool {
2109 Self::Terminal(ref stream) => stream.supports_color(),
2110 Self::Buffered(ref buffer) => buffer.buffer().supports_color(),
2111 Self::Raw(_, supports_color) => supports_color,
2116 impl<'a> WritableDst<'a> {
2117 fn apply_style(&mut self, lvl: Level, style: Style) -> io::Result<()> {
2118 let mut spec = ColorSpec::new();
2120 Style::LineAndColumn => {}
2121 Style::LineNumber => {
2122 spec.set_bold(true);
2123 spec.set_intense(true);
2125 spec.set_fg(Some(Color::Cyan));
2127 spec.set_fg(Some(Color::Blue));
2130 Style::Quotation => {}
2131 Style::MainHeaderMsg => {
2132 spec.set_bold(true);
2134 spec.set_intense(true).set_fg(Some(Color::White));
2137 Style::UnderlinePrimary | Style::LabelPrimary => {
2139 spec.set_bold(true);
2141 Style::UnderlineSecondary | Style::LabelSecondary => {
2142 spec.set_bold(true).set_intense(true);
2144 spec.set_fg(Some(Color::Cyan));
2146 spec.set_fg(Some(Color::Blue));
2149 Style::HeaderMsg | Style::NoStyle => {}
2150 Style::Level(lvl) => {
2152 spec.set_bold(true);
2154 Style::Highlight => {
2155 spec.set_bold(true);
2158 self.set_color(&spec)
2161 fn set_color(&mut self, color: &ColorSpec) -> io::Result<()> {
2163 WritableDst::Terminal(ref mut t) => t.set_color(color),
2164 WritableDst::Buffered(_, ref mut t) => t.set_color(color),
2165 WritableDst::ColoredRaw(ref mut t) => t.set_color(color),
2166 WritableDst::Raw(_) => Ok(()),
2170 fn reset(&mut self) -> io::Result<()> {
2172 WritableDst::Terminal(ref mut t) => t.reset(),
2173 WritableDst::Buffered(_, ref mut t) => t.reset(),
2174 WritableDst::ColoredRaw(ref mut t) => t.reset(),
2175 WritableDst::Raw(_) => Ok(()),
2180 impl<'a> Write for WritableDst<'a> {
2181 fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
2183 WritableDst::Terminal(ref mut t) => t.write(bytes),
2184 WritableDst::Buffered(_, ref mut buf) => buf.write(bytes),
2185 WritableDst::Raw(ref mut w) => w.write(bytes),
2186 WritableDst::ColoredRaw(ref mut t) => t.write(bytes),
2190 fn flush(&mut self) -> io::Result<()> {
2192 WritableDst::Terminal(ref mut t) => t.flush(),
2193 WritableDst::Buffered(_, ref mut buf) => buf.flush(),
2194 WritableDst::Raw(ref mut w) => w.flush(),
2195 WritableDst::ColoredRaw(ref mut w) => w.flush(),
2200 impl<'a> Drop for WritableDst<'a> {
2201 fn drop(&mut self) {
2202 if let WritableDst::Buffered(ref mut dst, ref mut buf) = self {
2203 drop(dst.print(buf));
2208 /// Whether the original and suggested code are visually similar enough to warrant extra wording.
2209 pub fn is_case_difference(sm: &SourceMap, suggested: &str, sp: Span) -> bool {
2210 // FIXME: this should probably be extended to also account for `FO0` → `FOO` and unicode.
2211 let found = match sm.span_to_snippet(sp) {
2212 Ok(snippet) => snippet,
2214 warn!("Invalid span {:?}. Err={:?}", sp, e);
2218 let ascii_confusables = &['c', 'f', 'i', 'k', 'o', 's', 'u', 'v', 'w', 'x', 'y', 'z'];
2219 // All the chars that differ in capitalization are confusable (above):
2220 let confusable = iter::zip(found.chars(), suggested.chars())
2221 .filter(|(f, s)| f != s)
2222 .all(|(f, s)| (ascii_confusables.contains(&f) || ascii_confusables.contains(&s)));
2223 confusable && found.to_lowercase() == suggested.to_lowercase()
2224 // FIXME: We sometimes suggest the same thing we already have, which is a
2225 // bug, but be defensive against that here.
2226 && found != suggested