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 /// Checks if should show explanations about "rustc --explain"
199 fn should_show_explain(&self) -> bool {
203 /// Checks if we can use colors in the current output stream.
204 fn supports_color(&self) -> bool {
208 fn source_map(&self) -> Option<&Lrc<SourceMap>>;
210 /// Formats the substitutions of the primary_span
212 /// The are a lot of conditions to this method, but in short:
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.
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>(
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') &&
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)
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)
251 // Show the default suggestion text with the substitution
257 .map(|sm| is_case_difference(
260 sugg.substitutions[0].parts[0].span,
264 " (notice the capitalization)"
271 primary_span.push_span_label(sugg.substitutions[0].parts[0].span, msg);
273 // We return only the modified primary_span
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)
283 (primary_span, &diag.suggestions)
287 fn fix_multispans_in_extern_macros_and_render_macro_backtrace(
289 source_map: &Option<Lrc<SourceMap>>,
290 span: &mut MultiSpan,
291 children: &mut Vec<SubDiagnostic>,
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,
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,
309 ExpnKind::Macro(macro_kind, _) => Some(macro_kind),
314 self.fix_multispans_in_extern_macros(source_map, span, children);
317 self.render_multispans_macro_backtrace(span, children, backtrace);
320 if let Some(macro_kind) = has_macro_spans {
322 "this {} originates in {} {} \
323 (in Nightly builds, run with -Z macro-backtrace for more info)",
325 macro_kind.article(),
329 children.push(SubDiagnostic {
331 message: vec![(msg, Style::NoStyle)],
332 span: MultiSpan::new(),
339 fn render_multispans_macro_backtrace(
341 span: &mut MultiSpan,
342 children: &mut Vec<SubDiagnostic>,
345 for span in iter::once(span).chain(children.iter_mut().map(|child| &mut child.span)) {
346 self.render_multispan_macro_backtrace(span, backtrace);
350 fn render_multispan_macro_backtrace(&self, span: &mut MultiSpan, always_backtrace: bool) {
351 let mut new_labels: Vec<(Span, String)> = vec![];
353 for &sp in span.primary_spans() {
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() {
367 if matches!(trace.kind, ExpnKind::Inlined) {
369 .push((trace.call_site, "in the inlined copy of this code".to_string()));
370 } else if always_backtrace {
374 "in this expansion of `{}`{}",
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)
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.
392 // This also handles the case where an external span got replaced
393 // with the call site span by `fix_multispans_in_extern_macros`.
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);
400 if !redundant_span && matches!(trace.kind, ExpnKind::Macro(MacroKind::Bang, _))
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)
417 if !always_backtrace {
423 for (label_span, label_text) in new_labels {
424 span.push_span_label(label_span, label_text);
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(
433 source_map: &Option<Lrc<SourceMap>>,
434 span: &mut MultiSpan,
435 children: &mut Vec<SubDiagnostic>,
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);
441 debug!("fix_multispans_in_extern_macros: after: span={:?} children={:?}", span, children);
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(
449 source_map: &Option<Lrc<SourceMap>>,
450 span: &mut MultiSpan,
452 let sm = match source_map {
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() && sm.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();
1235 let header_style = if is_secondary { Style::HeaderMsg } else { Style::MainHeaderMsg };
1237 if !msp.has_primary_spans() && !msp.has_span_labels() && is_secondary && !self.short_message
1239 // This is a secondary message with no span info
1240 for _ in 0..max_line_num_len {
1241 buffer.prepend(0, " ", Style::NoStyle);
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);
1248 self.msg_to_buffer(&mut buffer, msg, max_line_num_len, "note", None);
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));
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));
1260 if *level != Level::FailureNote {
1261 buffer.append(0, ": ", header_style);
1263 for &(ref text, _) in msg.iter() {
1264 buffer.append(0, 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,
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);
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,
1351 sm.doctest_offset_line(&annotated_file.file.name, first_line.line_index),
1355 annotated_file.file.name.to_string()
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.get(&depth).is_some() {
1474 multilines.remove(&depth);
1476 to_add.insert(depth, style);
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);
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);
1496 // Set the multiline annotation vertical lines on `...` bridging line.
1497 for (depth, style) in &multilines {
1498 draw_multiline_line(
1500 last_buffer_line_num,
1506 } else if line_idx_delta == 2 {
1507 let unannotated_line = annotated_file
1509 .get_line(annotated_file.lines[line_idx].line_index)
1510 .unwrap_or_else(|| Cow::from(""));
1512 let last_buffer_line_num = buffer.num_lines();
1516 &replace_tabs(&unannotated_line),
1517 annotated_file.lines[line_idx + 1].line_index - 1,
1518 last_buffer_line_num,
1524 for (depth, style) in &multilines {
1525 draw_multiline_line(
1527 last_buffer_line_num,
1536 multilines.extend(&to_add);
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)?;
1547 fn emit_suggestion_default(
1549 suggestion: &CodeSuggestion,
1551 max_line_num_len: usize,
1552 ) -> io::Result<()> {
1553 let sm = match self.sm {
1555 None => return Ok(()),
1558 // Render the replacements for each suggestion
1559 let suggestions = suggestion.splice_lines(&**sm);
1560 debug!("emit_suggestion_default: suggestions={:?}", suggestions);
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.
1568 let mut buffer = StyledBuffer::new();
1570 // Render the suggestion message
1571 buffer.append(0, level.to_str(), Style::Level(*level));
1572 buffer.append(0, ": ", Style::HeaderMsg);
1576 &[(suggestion.msg.to_owned(), Style::NoStyle)],
1579 Some(Style::HeaderMsg),
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;
1593 .span_to_lines(parts[0].span)
1594 .expect("span_to_lines failed when emitting suggestion");
1596 assert!(!lines.lines.is_empty() || parts[0].span.is_dummy());
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()
1603 // Print the span column to avoid confusion
1607 &self.maybe_anonymized(line_start + line_pos),
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);
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.
1622 draw_col_separator(&mut buffer, row_num, max_line_num_len + 1);
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;
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
1631 let sub_len: usize = part
1635 .map(|ch| unicode_width::UnicodeWidthChar::width(ch).unwrap_or(1))
1638 let offset: isize = offsets
1641 |(start, v)| if span_start_pos <= *start { None } else { Some(v) },
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 {
1650 ((max_line_num_len + 3) as isize + p) as usize,
1652 Style::UnderlinePrimary,
1655 // underline removals too
1656 if underline_start == underline_end {
1657 for p in underline_start - 1..underline_start + 1 {
1660 ((max_line_num_len + 3) as isize + p) as usize,
1662 Style::UnderlineSecondary,
1667 // length of the code after substitution
1668 let full_sub_len = part
1671 .map(|ch| unicode_width::UnicodeWidthChar::width(ch).unwrap_or(1))
1672 .sum::<usize>() as isize;
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));
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);
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);
1700 emit_to_destination(&buffer.render(), level, &mut self.dst, self.short_message)?;
1704 fn emit_messages_default(
1707 message: &[(String, Style)],
1708 code: &Option<DiagnosticId>,
1710 children: &[SubDiagnostic],
1711 suggestions: &[CodeSuggestion],
1713 let max_line_num_len = if self.ui_testing {
1714 ANONYMIZED_LINE_NUM.len()
1716 self.get_max_line_num(span, children).to_string().len()
1719 match self.emit_message_default(span, message, code, level, max_line_num_len, false) {
1721 if !children.is_empty()
1722 || suggestions.iter().any(|s| s.style != SuggestionStyle::CompletelyHidden)
1724 let mut buffer = StyledBuffer::new();
1725 if !self.short_message {
1726 draw_col_separator_no_space(&mut buffer, 0, max_line_num_len + 1);
1728 match emit_to_destination(
1735 Err(e) => panic!("failed to emit error: {}", e),
1738 if !self.short_message {
1739 for child in children {
1740 let span = child.render_span.as_ref().unwrap_or(&child.span);
1741 if let Err(err) = self.emit_message_default(
1743 &child.styled_message(),
1749 panic!("failed to emit error: {}", err);
1752 for sugg in suggestions {
1753 if sugg.style == SuggestionStyle::CompletelyHidden {
1754 // do not display this suggestion, it is meant only for tools
1755 } else if sugg.style == SuggestionStyle::HideCodeAlways {
1756 if let Err(e) = self.emit_message_default(
1758 &[(sugg.msg.to_owned(), Style::HeaderMsg)],
1764 panic!("failed to emit error: {}", e);
1766 } else if let Err(e) =
1767 self.emit_suggestion_default(sugg, &Level::Help, max_line_num_len)
1769 panic!("failed to emit error: {}", e);
1774 Err(e) => panic!("failed to emit error: {}", e),
1777 let mut dst = self.dst.writable();
1778 match writeln!(dst) {
1779 Err(e) => panic!("failed to emit error: {}", e),
1781 if let Err(e) = dst.flush() {
1782 panic!("failed to emit error: {}", e)
1789 impl FileWithAnnotatedLines {
1790 /// Preprocess all the annotations so that they are grouped by file and by line number
1791 /// This helps us quickly iterate over the whole message (including secondary file spans)
1792 pub fn collect_annotations(
1794 source_map: &Option<Lrc<SourceMap>>,
1795 ) -> Vec<FileWithAnnotatedLines> {
1796 fn add_annotation_to_file(
1797 file_vec: &mut Vec<FileWithAnnotatedLines>,
1798 file: Lrc<SourceFile>,
1802 for slot in file_vec.iter_mut() {
1803 // Look through each of our files for the one we're adding to
1804 if slot.file.name == file.name {
1805 // See if we already have a line for it
1806 for line_slot in &mut slot.lines {
1807 if line_slot.line_index == line_index {
1808 line_slot.annotations.push(ann);
1812 // We don't have a line yet, create one
1813 slot.lines.push(Line { line_index, annotations: vec![ann] });
1818 // This is the first time we're seeing the file
1819 file_vec.push(FileWithAnnotatedLines {
1821 lines: vec![Line { line_index, annotations: vec![ann] }],
1826 let mut output = vec![];
1827 let mut multiline_annotations = vec![];
1829 if let Some(ref sm) = source_map {
1830 for span_label in msp.span_labels() {
1831 if span_label.span.is_dummy() {
1835 let lo = sm.lookup_char_pos(span_label.span.lo());
1836 let mut hi = sm.lookup_char_pos(span_label.span.hi());
1838 // Watch out for "empty spans". If we get a span like 6..6, we
1839 // want to just display a `^` at 6, so convert that to
1840 // 6..7. This is degenerate input, but it's best to degrade
1841 // gracefully -- and the parser likes to supply a span like
1842 // that for EOF, in particular.
1844 if lo.col_display == hi.col_display && lo.line == hi.line {
1845 hi.col_display += 1;
1848 if lo.line != hi.line {
1849 let ml = MultilineAnnotation {
1851 line_start: lo.line,
1853 start_col: lo.col_display,
1854 end_col: hi.col_display,
1855 is_primary: span_label.is_primary,
1856 label: span_label.label,
1857 overlaps_exactly: false,
1859 multiline_annotations.push((lo.file, ml));
1861 let ann = Annotation {
1862 start_col: lo.col_display,
1863 end_col: hi.col_display,
1864 is_primary: span_label.is_primary,
1865 label: span_label.label,
1866 annotation_type: AnnotationType::Singleline,
1868 add_annotation_to_file(&mut output, lo.file, lo.line, ann);
1873 // Find overlapping multiline annotations, put them at different depths
1874 multiline_annotations.sort_by_key(|&(_, ref ml)| (ml.line_start, ml.line_end));
1875 for (_, ann) in multiline_annotations.clone() {
1876 for (_, a) in multiline_annotations.iter_mut() {
1877 // Move all other multiline annotations overlapping with this one
1878 // one level to the right.
1879 if !(ann.same_span(a))
1880 && num_overlap(ann.line_start, ann.line_end, a.line_start, a.line_end, true)
1883 } else if ann.same_span(a) && &ann != a {
1884 a.overlaps_exactly = true;
1891 let mut max_depth = 0; // max overlapping multiline spans
1892 for (file, ann) in multiline_annotations {
1893 max_depth = max(max_depth, ann.depth);
1894 let mut end_ann = ann.as_end();
1895 if !ann.overlaps_exactly {
1896 // avoid output like
1918 add_annotation_to_file(&mut output, file.clone(), ann.line_start, ann.as_start());
1919 // 4 is the minimum vertical length of a multiline span when presented: two lines
1920 // of code and two lines of underline. This is not true for the special case where
1921 // the beginning doesn't have an underline, but the current logic seems to be
1922 // working correctly.
1923 let middle = min(ann.line_start + 4, ann.line_end);
1924 for line in ann.line_start + 1..middle {
1925 // Every `|` that joins the beginning of the span (`___^`) to the end (`|__^`).
1926 add_annotation_to_file(&mut output, file.clone(), line, ann.as_line());
1928 let line_end = ann.line_end - 1;
1929 if middle < line_end {
1930 add_annotation_to_file(&mut output, file.clone(), line_end, ann.as_line());
1933 end_ann.annotation_type = AnnotationType::Singleline;
1935 add_annotation_to_file(&mut output, file, ann.line_end, end_ann);
1937 for file_vec in output.iter_mut() {
1938 file_vec.multiline_depth = max_depth;
1944 fn replace_tabs(str: &str) -> String {
1945 str.replace('\t', " ")
1948 fn draw_col_separator(buffer: &mut StyledBuffer, line: usize, col: usize) {
1949 buffer.puts(line, col, "| ", Style::LineNumber);
1952 fn draw_col_separator_no_space(buffer: &mut StyledBuffer, line: usize, col: usize) {
1953 draw_col_separator_no_space_with_style(buffer, line, col, Style::LineNumber);
1956 fn draw_col_separator_no_space_with_style(
1957 buffer: &mut StyledBuffer,
1962 buffer.putc(line, col, '|', style);
1966 buffer: &mut StyledBuffer,
1973 for col in col_from..col_to {
1974 buffer.putc(line, col, symbol, style);
1978 fn draw_note_separator(buffer: &mut StyledBuffer, line: usize, col: usize) {
1979 buffer.puts(line, col, "= ", Style::LineNumber);
1982 fn draw_multiline_line(
1983 buffer: &mut StyledBuffer,
1989 buffer.putc(line, offset + depth - 1, '|', style);
1999 let extra = if inclusive { 1 } else { 0 };
2000 (b_start..b_end + extra).contains(&a_start) || (a_start..a_end + extra).contains(&b_start)
2002 fn overlaps(a1: &Annotation, a2: &Annotation, padding: usize) -> bool {
2003 num_overlap(a1.start_col, a1.end_col + padding, a2.start_col, a2.end_col, false)
2006 fn emit_to_destination(
2007 rendered_buffer: &[Vec<StyledString>],
2009 dst: &mut Destination,
2010 short_message: bool,
2011 ) -> io::Result<()> {
2014 let mut dst = dst.writable();
2016 // In order to prevent error message interleaving, where multiple error lines get intermixed
2017 // when multiple compiler processes error simultaneously, we emit errors with additional
2020 // On Unix systems, we write into a buffered terminal rather than directly to a terminal. When
2021 // the .flush() is called we take the buffer created from the buffered writes and write it at
2022 // one shot. Because the Unix systems use ANSI for the colors, which is a text-based styling
2023 // scheme, this buffered approach works and maintains the styling.
2025 // On Windows, styling happens through calls to a terminal API. This prevents us from using the
2026 // same buffering approach. Instead, we use a global Windows mutex, which we acquire long
2027 // enough to output the full error message, then we release.
2028 let _buffer_lock = lock::acquire_global_lock("rustc_errors");
2029 for (pos, line) in rendered_buffer.iter().enumerate() {
2031 dst.apply_style(*lvl, part.style)?;
2032 write!(dst, "{}", part.text)?;
2035 if !short_message && (!lvl.is_failure_note() || pos != rendered_buffer.len() - 1) {
2043 pub enum Destination {
2044 Terminal(StandardStream),
2045 Buffered(BufferWriter),
2046 // The bool denotes whether we should be emitting ansi color codes or not
2047 Raw(Box<(dyn Write + Send)>, bool),
2050 pub enum WritableDst<'a> {
2051 Terminal(&'a mut StandardStream),
2052 Buffered(&'a mut BufferWriter, Buffer),
2053 Raw(&'a mut (dyn Write + Send)),
2054 ColoredRaw(Ansi<&'a mut (dyn Write + Send)>),
2058 fn from_stderr(color: ColorConfig) -> Destination {
2059 let choice = color.to_color_choice();
2060 // On Windows we'll be performing global synchronization on the entire
2061 // system for emitting rustc errors, so there's no need to buffer
2064 // On non-Windows we rely on the atomicity of `write` to ensure errors
2065 // don't get all jumbled up.
2067 Terminal(StandardStream::stderr(choice))
2069 Buffered(BufferWriter::stderr(choice))
2073 fn writable(&mut self) -> WritableDst<'_> {
2075 Destination::Terminal(ref mut t) => WritableDst::Terminal(t),
2076 Destination::Buffered(ref mut t) => {
2077 let buf = t.buffer();
2078 WritableDst::Buffered(t, buf)
2080 Destination::Raw(ref mut t, false) => WritableDst::Raw(t),
2081 Destination::Raw(ref mut t, true) => WritableDst::ColoredRaw(Ansi::new(t)),
2085 fn supports_color(&self) -> bool {
2087 Self::Terminal(ref stream) => stream.supports_color(),
2088 Self::Buffered(ref buffer) => buffer.buffer().supports_color(),
2089 Self::Raw(_, supports_color) => supports_color,
2094 impl<'a> WritableDst<'a> {
2095 fn apply_style(&mut self, lvl: Level, style: Style) -> io::Result<()> {
2096 let mut spec = ColorSpec::new();
2098 Style::LineAndColumn => {}
2099 Style::LineNumber => {
2100 spec.set_bold(true);
2101 spec.set_intense(true);
2103 spec.set_fg(Some(Color::Cyan));
2105 spec.set_fg(Some(Color::Blue));
2108 Style::Quotation => {}
2109 Style::MainHeaderMsg => {
2110 spec.set_bold(true);
2112 spec.set_intense(true).set_fg(Some(Color::White));
2115 Style::UnderlinePrimary | Style::LabelPrimary => {
2117 spec.set_bold(true);
2119 Style::UnderlineSecondary | Style::LabelSecondary => {
2120 spec.set_bold(true).set_intense(true);
2122 spec.set_fg(Some(Color::Cyan));
2124 spec.set_fg(Some(Color::Blue));
2127 Style::HeaderMsg | Style::NoStyle => {}
2128 Style::Level(lvl) => {
2130 spec.set_bold(true);
2132 Style::Highlight => {
2133 spec.set_bold(true);
2136 self.set_color(&spec)
2139 fn set_color(&mut self, color: &ColorSpec) -> io::Result<()> {
2141 WritableDst::Terminal(ref mut t) => t.set_color(color),
2142 WritableDst::Buffered(_, ref mut t) => t.set_color(color),
2143 WritableDst::ColoredRaw(ref mut t) => t.set_color(color),
2144 WritableDst::Raw(_) => Ok(()),
2148 fn reset(&mut self) -> io::Result<()> {
2150 WritableDst::Terminal(ref mut t) => t.reset(),
2151 WritableDst::Buffered(_, ref mut t) => t.reset(),
2152 WritableDst::ColoredRaw(ref mut t) => t.reset(),
2153 WritableDst::Raw(_) => Ok(()),
2158 impl<'a> Write for WritableDst<'a> {
2159 fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
2161 WritableDst::Terminal(ref mut t) => t.write(bytes),
2162 WritableDst::Buffered(_, ref mut buf) => buf.write(bytes),
2163 WritableDst::Raw(ref mut w) => w.write(bytes),
2164 WritableDst::ColoredRaw(ref mut t) => t.write(bytes),
2168 fn flush(&mut self) -> io::Result<()> {
2170 WritableDst::Terminal(ref mut t) => t.flush(),
2171 WritableDst::Buffered(_, ref mut buf) => buf.flush(),
2172 WritableDst::Raw(ref mut w) => w.flush(),
2173 WritableDst::ColoredRaw(ref mut w) => w.flush(),
2178 impl<'a> Drop for WritableDst<'a> {
2179 fn drop(&mut self) {
2180 if let WritableDst::Buffered(ref mut dst, ref mut buf) = self {
2181 drop(dst.print(buf));
2186 /// Whether the original and suggested code are visually similar enough to warrant extra wording.
2187 pub fn is_case_difference(sm: &SourceMap, suggested: &str, sp: Span) -> bool {
2188 // FIXME: this should probably be extended to also account for `FO0` → `FOO` and unicode.
2189 let found = match sm.span_to_snippet(sp) {
2190 Ok(snippet) => snippet,
2192 warn!("Invalid span {:?}. Err={:?}", sp, e);
2196 let ascii_confusables = &['c', 'f', 'i', 'k', 'o', 's', 'u', 'v', 'w', 'x', 'y', 'z'];
2197 // All the chars that differ in capitalization are confusable (above):
2198 let confusable = found
2200 .zip(suggested.chars())
2201 .filter(|(f, s)| f != s)
2202 .all(|(f, s)| (ascii_confusables.contains(&f) || ascii_confusables.contains(&s)));
2203 confusable && found.to_lowercase() == suggested.to_lowercase()
2204 // FIXME: We sometimes suggest the same thing we already have, which is a
2205 // bug, but be defensive against that here.
2206 && found != suggested