3 use syntax_pos::{SourceFile, Span, MultiSpan};
6 Level, CodeSuggestion, DiagnosticBuilder, SubDiagnostic,
7 SuggestionStyle, SourceMapperDyn, DiagnosticId,
9 use crate::Level::Error;
10 use crate::snippet::{Annotation, AnnotationType, Line, MultilineAnnotation, StyledString, Style};
11 use crate::styled_buffer::StyledBuffer;
13 use rustc_data_structures::fx::FxHashMap;
14 use rustc_data_structures::sync::Lrc;
16 use std::io::prelude::*;
18 use std::cmp::{min, Reverse};
20 use termcolor::{StandardStream, ColorChoice, ColorSpec, BufferWriter, Ansi};
21 use termcolor::{WriteColor, Color, Buffer};
23 /// Describes the way the content of the `rendered` field of the json output is generated
24 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
25 pub enum HumanReadableErrorType {
30 impl HumanReadableErrorType {
31 /// Returns a (`short`, `color`) tuple
32 pub fn unzip(self) -> (bool, ColorConfig) {
34 HumanReadableErrorType::Default(cc) => (false, cc),
35 HumanReadableErrorType::Short(cc) => (true, cc),
40 dst: Box<dyn Write + Send>,
41 source_map: Option<Lrc<SourceMapperDyn>>,
44 let (short, color_config) = self.unzip();
45 EmitterWriter::new(dst, source_map, short, teach, color_config.suggests_using_colors())
49 const ANONYMIZED_LINE_NUM: &str = "LL";
51 /// Emitter trait for emitting errors.
53 /// Emit a structured diagnostic.
54 fn emit_diagnostic(&mut self, db: &DiagnosticBuilder<'_>);
56 /// Emit a notification that an artifact has been output.
57 /// This is currently only supported for the JSON format,
58 /// other formats can, and will, simply ignore it.
59 fn emit_artifact_notification(&mut self, _path: &Path) {}
61 /// Checks if should show explanations about "rustc --explain"
62 fn should_show_explain(&self) -> bool {
67 impl Emitter for EmitterWriter {
68 fn emit_diagnostic(&mut self, db: &DiagnosticBuilder<'_>) {
69 let mut primary_span = db.span.clone();
70 let mut children = db.children.clone();
71 let mut suggestions: &[_] = &[];
73 if let Some((sugg, rest)) = db.suggestions.split_first() {
75 // don't display multi-suggestions as labels
76 sugg.substitutions.len() == 1 &&
77 // don't display multipart suggestions as labels
78 sugg.substitutions[0].parts.len() == 1 &&
79 // don't display long messages as labels
80 sugg.msg.split_whitespace().count() < 10 &&
81 // don't display multiline suggestions as labels
82 !sugg.substitutions[0].parts[0].snippet.contains('\n') &&
83 // when this style is set we want the suggestion to be a message, not inline
84 sugg.style != SuggestionStyle::HideCodeAlways &&
85 // trivial suggestion for tooling's sake, never shown
86 sugg.style != SuggestionStyle::CompletelyHidden
88 let substitution = &sugg.substitutions[0].parts[0].snippet.trim();
89 let msg = if substitution.len() == 0 || sugg.style.hide_inline() {
90 // This substitution is only removal or we explicitly don't want to show the
91 // code inline, don't show it
92 format!("help: {}", sugg.msg)
94 format!("help: {}: `{}`", sugg.msg, substitution)
96 primary_span.push_span_label(sugg.substitutions[0].parts[0].span, msg);
98 // if there are multiple suggestions, print them all in full
99 // to be consistent. We could try to figure out if we can
100 // make one (or the first one) inline, but that would give
101 // undue importance to a semi-random suggestion
102 suggestions = &db.suggestions;
106 self.fix_multispans_in_std_macros(&mut primary_span,
109 db.handler.flags.external_macro_backtrace);
111 self.emit_messages_default(&db.level,
112 &db.styled_message(),
119 fn should_show_explain(&self) -> bool {
124 /// maximum number of lines we will print for each error; arbitrary.
125 pub const MAX_HIGHLIGHT_LINES: usize = 6;
126 /// maximum number of suggestions to be shown
128 /// Arbitrary, but taken from trait import suggestion limit
129 pub const MAX_SUGGESTIONS: usize = 4;
131 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
132 pub enum ColorConfig {
139 fn to_color_choice(self) -> ColorChoice {
141 ColorConfig::Always => {
142 if atty::is(atty::Stream::Stderr) {
145 ColorChoice::AlwaysAnsi
148 ColorConfig::Never => ColorChoice::Never,
149 ColorConfig::Auto if atty::is(atty::Stream::Stderr) => {
152 ColorConfig::Auto => ColorChoice::Never,
155 fn suggests_using_colors(self) -> bool {
157 | ColorConfig::Always
160 ColorConfig::Never => false,
165 pub struct EmitterWriter {
167 sm: Option<Lrc<SourceMapperDyn>>,
173 struct FileWithAnnotatedLines {
174 file: Lrc<SourceFile>,
176 multiline_depth: usize,
180 pub fn stderr(color_config: ColorConfig,
181 source_map: Option<Lrc<SourceMapperDyn>>,
185 let dst = Destination::from_stderr(color_config);
196 dst: Box<dyn Write + Send>,
197 source_map: Option<Lrc<SourceMapperDyn>>,
203 dst: Raw(dst, colored),
211 pub fn ui_testing(mut self, ui_testing: bool) -> Self {
212 self.ui_testing = ui_testing;
216 fn maybe_anonymized(&self, line_num: usize) -> String {
218 ANONYMIZED_LINE_NUM.to_string()
224 fn preprocess_annotations(&mut self, msp: &MultiSpan) -> Vec<FileWithAnnotatedLines> {
225 fn add_annotation_to_file(file_vec: &mut Vec<FileWithAnnotatedLines>,
226 file: Lrc<SourceFile>,
230 for slot in file_vec.iter_mut() {
231 // Look through each of our files for the one we're adding to
232 if slot.file.name == file.name {
233 // See if we already have a line for it
234 for line_slot in &mut slot.lines {
235 if line_slot.line_index == line_index {
236 line_slot.annotations.push(ann);
240 // We don't have a line yet, create one
241 slot.lines.push(Line {
243 annotations: vec![ann],
249 // This is the first time we're seeing the file
250 file_vec.push(FileWithAnnotatedLines {
254 annotations: vec![ann],
260 let mut output = vec![];
261 let mut multiline_annotations = vec![];
263 if let Some(ref sm) = self.sm {
264 for span_label in msp.span_labels() {
265 if span_label.span.is_dummy() {
269 let lo = sm.lookup_char_pos(span_label.span.lo());
270 let mut hi = sm.lookup_char_pos(span_label.span.hi());
272 // Watch out for "empty spans". If we get a span like 6..6, we
273 // want to just display a `^` at 6, so convert that to
274 // 6..7. This is degenerate input, but it's best to degrade
275 // gracefully -- and the parser likes to supply a span like
276 // that for EOF, in particular.
278 if lo.col_display == hi.col_display && lo.line == hi.line {
282 let ann_type = if lo.line != hi.line {
283 let ml = MultilineAnnotation {
287 start_col: lo.col_display,
288 end_col: hi.col_display,
289 is_primary: span_label.is_primary,
290 label: span_label.label.clone(),
291 overlaps_exactly: false,
293 multiline_annotations.push((lo.file.clone(), ml.clone()));
294 AnnotationType::Multiline(ml)
296 AnnotationType::Singleline
298 let ann = Annotation {
299 start_col: lo.col_display,
300 end_col: hi.col_display,
301 is_primary: span_label.is_primary,
302 label: span_label.label.clone(),
303 annotation_type: ann_type,
306 if !ann.is_multiline() {
307 add_annotation_to_file(&mut output, lo.file, lo.line, ann);
312 // Find overlapping multiline annotations, put them at different depths
313 multiline_annotations.sort_by_key(|&(_, ref ml)| (ml.line_start, ml.line_end));
314 for item in multiline_annotations.clone() {
316 for item in multiline_annotations.iter_mut() {
317 let ref mut a = item.1;
318 // Move all other multiline annotations overlapping with this one
319 // one level to the right.
320 if !(ann.same_span(a)) &&
321 num_overlap(ann.line_start, ann.line_end, a.line_start, a.line_end, true)
324 } else if ann.same_span(a) && &ann != a {
325 a.overlaps_exactly = true;
332 let mut max_depth = 0; // max overlapping multiline spans
333 for (file, ann) in multiline_annotations {
334 if ann.depth > max_depth {
335 max_depth = ann.depth;
337 let mut end_ann = ann.as_end();
338 if !ann.overlaps_exactly {
361 add_annotation_to_file(&mut output, file.clone(), ann.line_start, ann.as_start());
362 // 4 is the minimum vertical length of a multiline span when presented: two lines
363 // of code and two lines of underline. This is not true for the special case where
364 // the beginning doesn't have an underline, but the current logic seems to be
365 // working correctly.
366 let middle = min(ann.line_start + 4, ann.line_end);
367 for line in ann.line_start + 1..middle {
368 // Every `|` that joins the beginning of the span (`___^`) to the end (`|__^`).
369 add_annotation_to_file(&mut output, file.clone(), line, ann.as_line());
371 if middle < ann.line_end - 1 {
372 for line in ann.line_end - 1..ann.line_end {
373 add_annotation_to_file(&mut output, file.clone(), line, ann.as_line());
377 end_ann.annotation_type = AnnotationType::Singleline;
379 add_annotation_to_file(&mut output, file, ann.line_end, end_ann);
381 for file_vec in output.iter_mut() {
382 file_vec.multiline_depth = max_depth;
387 fn render_source_line(&self,
388 buffer: &mut StyledBuffer,
389 file: Lrc<SourceFile>,
392 code_offset: usize) -> Vec<(usize, Style)> {
393 if line.line_index == 0 {
397 let source_string = match file.get_line(line.line_index - 1) {
399 None => return Vec::new(),
402 let line_offset = buffer.num_lines();
404 // First create the source line we will highlight.
405 buffer.puts(line_offset, code_offset, &source_string, Style::Quotation);
406 buffer.puts(line_offset,
408 &self.maybe_anonymized(line.line_index),
411 draw_col_separator(buffer, line_offset, width_offset - 2);
413 // Special case when there's only one annotation involved, it is the start of a multiline
414 // span and there's no text at the beginning of the code line. Instead of doing the whole
423 // we simplify the output to:
429 if line.annotations.len() == 1 {
430 if let Some(ref ann) = line.annotations.get(0) {
431 if let AnnotationType::MultilineStart(depth) = ann.annotation_type {
432 if source_string.chars()
434 .all(|c| c.is_whitespace()) {
435 let style = if ann.is_primary {
436 Style::UnderlinePrimary
438 Style::UnderlineSecondary
440 buffer.putc(line_offset,
441 width_offset + depth - 1,
444 return vec![(depth, style)];
450 // We want to display like this:
452 // vec.push(vec.pop().unwrap());
453 // --- ^^^ - previous borrow ends here
455 // | error occurs here
456 // previous borrow of `vec` occurs here
458 // But there are some weird edge cases to be aware of:
460 // vec.push(vec.pop().unwrap());
461 // -------- - previous borrow ends here
463 // |this makes no sense
464 // previous borrow of `vec` occurs here
466 // For this reason, we group the lines into "highlight lines"
467 // and "annotations lines", where the highlight lines have the `^`.
469 // Sort the annotations by (start, end col)
470 // The labels are reversed, sort and then reversed again.
471 // Consider a list of annotations (A1, A2, C1, C2, B1, B2) where
472 // the letter signifies the span. Here we are only sorting by the
473 // span and hence, the order of the elements with the same span will
474 // not change. On reversing the ordering (|a, b| but b.cmp(a)), you get
475 // (C1, C2, B1, B2, A1, A2). All the elements with the same span are
476 // still ordered first to last, but all the elements with different
477 // spans are ordered by their spans in last to first order. Last to
478 // first order is important, because the jiggly lines and | are on
479 // the left, so the rightmost span needs to be rendered first,
480 // otherwise the lines would end up needing to go over a message.
482 let mut annotations = line.annotations.clone();
483 annotations.sort_by_key(|a| Reverse(a.start_col));
485 // First, figure out where each label will be positioned.
487 // In the case where you have the following annotations:
489 // vec.push(vec.pop().unwrap());
490 // -------- - previous borrow ends here [C]
492 // |this makes no sense [B]
493 // previous borrow of `vec` occurs here [A]
495 // `annotations_position` will hold [(2, A), (1, B), (0, C)].
497 // We try, when possible, to stick the rightmost annotation at the end
498 // of the highlight line:
500 // vec.push(vec.pop().unwrap());
501 // --- --- - previous borrow ends here
503 // But sometimes that's not possible because one of the other
504 // annotations overlaps it. For example, from the test
505 // `span_overlap_label`, we have the following annotations
506 // (written on distinct lines for clarity):
512 // In this case, we can't stick the rightmost-most label on
513 // the highlight line, or we would get:
520 // which is totally weird. Instead we want:
528 // which is...less weird, at least. In fact, in general, if
529 // the rightmost span overlaps with any other span, we should
530 // use the "hang below" version, so we can at least make it
531 // clear where the span *starts*. There's an exception for this
532 // logic, when the labels do not have a message:
547 let mut annotations_position = vec![];
548 let mut line_len = 0;
550 for (i, annotation) in annotations.iter().enumerate() {
551 for (j, next) in annotations.iter().enumerate() {
552 if overlaps(next, annotation, 0) // This label overlaps with another one and both
553 && annotation.has_label() // take space (they have text and are not
554 && j > i // multiline lines).
555 && p == 0 // We're currently on the first line, move the label one line down
557 // If we're overlapping with an un-labelled annotation with the same span
558 // we can just merge them in the output
559 if next.start_col == annotation.start_col
560 && next.end_col == annotation.end_col
566 // This annotation needs a new line in the output.
571 annotations_position.push((p, annotation));
572 for (j, next) in annotations.iter().enumerate() {
574 let l = if let Some(ref label) = next.label {
579 if (overlaps(next, annotation, l) // Do not allow two labels to be in the same
580 // line if they overlap including padding, to
581 // avoid situations like:
588 && annotation.has_label() // Both labels must have some text, otherwise
589 && next.has_label()) // they are not overlapping.
590 // Do not add a new line if this annotation
591 // or the next are vertical line placeholders.
592 || (annotation.takes_space() // If either this or the next annotation is
593 && next.has_label()) // multiline start/end, move it to a new line
594 || (annotation.has_label() // so as not to overlap the orizontal lines.
595 && next.takes_space())
596 || (annotation.takes_space() && next.takes_space())
597 || (overlaps(next, annotation, l)
598 && next.end_col <= annotation.end_col
600 && p == 0) // Avoid #42595.
602 // This annotation needs a new line in the output.
617 // If there are no annotations or the only annotations on this line are
618 // MultilineLine, then there's only code being shown, stop processing.
619 if line.annotations.iter().all(|a| a.is_line()) {
623 // Write the colunmn separator.
625 // After this we will have:
634 for pos in 0..=line_len {
635 draw_col_separator(buffer, line_offset + pos + 1, width_offset - 2);
636 buffer.putc(line_offset + pos + 1,
642 // Write the horizontal lines for multiline annotations
643 // (only the first and last lines need this).
645 // After this we will have:
654 for &(pos, annotation) in &annotations_position {
655 let style = if annotation.is_primary {
656 Style::UnderlinePrimary
658 Style::UnderlineSecondary
661 match annotation.annotation_type {
662 AnnotationType::MultilineStart(depth) |
663 AnnotationType::MultilineEnd(depth) => {
667 width_offset + depth,
668 code_offset + annotation.start_col,
672 buffer.set_style_range(line_offset,
673 code_offset + annotation.start_col,
674 code_offset + annotation.end_col,
676 annotation.is_primary);
682 // Write the vertical lines for labels that are on a different line as the underline.
684 // After this we will have:
693 for &(pos, annotation) in &annotations_position {
694 let style = if annotation.is_primary {
695 Style::UnderlinePrimary
697 Style::UnderlineSecondary
701 if pos > 1 && (annotation.has_label() || annotation.takes_space()) {
702 for p in line_offset + 1..=line_offset + pos {
704 code_offset + annotation.start_col,
709 match annotation.annotation_type {
710 AnnotationType::MultilineStart(depth) => {
711 for p in line_offset + pos + 1..line_offset + line_len + 2 {
713 width_offset + depth - 1,
718 AnnotationType::MultilineEnd(depth) => {
719 for p in line_offset..=line_offset + pos {
721 width_offset + depth - 1,
730 // Write the labels on the annotations that actually have a label.
732 // After this we will have:
737 // | something about `foo`
741 for &(pos, annotation) in &annotations_position {
742 let style = if annotation.is_primary {
745 Style::LabelSecondary
747 let (pos, col) = if pos == 0 {
748 (pos + 1, annotation.end_col + 1)
750 (pos + 2, annotation.start_col)
752 if let Some(ref label) = annotation.label {
753 buffer.puts(line_offset + pos,
760 // Sort from biggest span to smallest span so that smaller spans are
761 // represented in the output:
766 // | | something about `foo`
767 // | something about `fn foo()`
768 annotations_position.sort_by(|a, b| {
769 // Decreasing order. When `a` and `b` are the same length, prefer `Primary`.
770 (a.1.len(), !a.1.is_primary).cmp(&(b.1.len(), !b.1.is_primary)).reverse()
773 // Write the underlines.
775 // After this we will have:
780 // | something about `foo`
784 for &(_, annotation) in &annotations_position {
785 let (underline, style) = if annotation.is_primary {
786 ('^', Style::UnderlinePrimary)
788 ('-', Style::UnderlineSecondary)
790 for p in annotation.start_col..annotation.end_col {
791 buffer.putc(line_offset + 1,
797 annotations_position.iter().filter_map(|&(_, annotation)| {
798 match annotation.annotation_type {
799 AnnotationType::MultilineStart(p) | AnnotationType::MultilineEnd(p) => {
800 let style = if annotation.is_primary {
803 Style::LabelSecondary
810 }).collect::<Vec<_>>()
813 fn get_multispan_max_line_num(&mut self, msp: &MultiSpan) -> usize {
815 if let Some(ref sm) = self.sm {
816 for primary_span in msp.primary_spans() {
817 if !primary_span.is_dummy() {
818 let hi = sm.lookup_char_pos(primary_span.hi());
824 if !self.short_message {
825 for span_label in msp.span_labels() {
826 if !span_label.span.is_dummy() {
827 let hi = sm.lookup_char_pos(span_label.span.hi());
838 fn get_max_line_num(&mut self, span: &MultiSpan, children: &[SubDiagnostic]) -> usize {
841 let primary = self.get_multispan_max_line_num(span);
842 max = if primary > max { primary } else { max };
844 for sub in children {
845 let sub_result = self.get_multispan_max_line_num(&sub.span);
846 max = if sub_result > max { primary } else { max };
851 // This "fixes" MultiSpans that contain Spans that are pointing to locations inside of
852 // <*macros>. Since these locations are often difficult to read, we move these Spans from
853 // <*macros> to their corresponding use site.
854 fn fix_multispan_in_std_macros(&mut self,
855 span: &mut MultiSpan,
856 always_backtrace: bool) -> bool {
857 let mut spans_updated = false;
859 if let Some(ref sm) = self.sm {
860 let mut before_after: Vec<(Span, Span)> = vec![];
861 let mut new_labels: Vec<(Span, String)> = vec![];
863 // First, find all the spans in <*macros> and point instead at their use site
864 for sp in span.primary_spans() {
868 let call_sp = sm.call_span_if_macro(*sp);
869 if call_sp != *sp && !always_backtrace {
870 before_after.push((*sp, call_sp));
872 let backtrace_len = sp.macro_backtrace().len();
873 for (i, trace) in sp.macro_backtrace().iter().rev().enumerate() {
874 // Only show macro locations that are local
875 // and display them like a span_note
876 if let Some(def_site) = trace.def_site_span {
877 if def_site.is_dummy() {
880 if always_backtrace {
881 new_labels.push((def_site,
882 format!("in this expansion of `{}`{}",
883 trace.macro_decl_name,
884 if backtrace_len > 2 {
885 // if backtrace_len == 1 it'll be pointed
886 // at by "in this macro invocation"
887 format!(" (#{})", i + 1)
892 // Check to make sure we're not in any <*macros>
893 if !sm.span_to_filename(def_site).is_macros() &&
894 !trace.macro_decl_name.starts_with("desugaring of ") &&
895 !trace.macro_decl_name.starts_with("#[") ||
897 new_labels.push((trace.call_site,
898 format!("in this macro invocation{}",
899 if backtrace_len > 2 && always_backtrace {
900 // only specify order when the macro
901 // backtrace is multiple levels deep
902 format!(" (#{})", i + 1)
906 if !always_backtrace {
913 for (label_span, label_text) in new_labels {
914 span.push_span_label(label_span, label_text);
916 for sp_label in span.span_labels() {
917 if sp_label.span.is_dummy() {
920 if sm.span_to_filename(sp_label.span.clone()).is_macros() &&
923 let v = sp_label.span.macro_backtrace();
924 if let Some(use_site) = v.last() {
925 before_after.push((sp_label.span.clone(), use_site.call_site.clone()));
929 // After we have them, make sure we replace these 'bad' def sites with their use sites
930 for (before, after) in before_after {
931 span.replace(before, after);
932 spans_updated = true;
939 // This does a small "fix" for multispans by looking to see if it can find any that
940 // point directly at <*macros>. Since these are often difficult to read, this
941 // will change the span to point at the use site.
942 fn fix_multispans_in_std_macros(&mut self,
943 span: &mut MultiSpan,
944 children: &mut Vec<SubDiagnostic>,
947 let mut spans_updated = self.fix_multispan_in_std_macros(span, backtrace);
948 for child in children.iter_mut() {
949 spans_updated |= self.fix_multispan_in_std_macros(&mut child.span, backtrace);
951 let msg = if level == &Error {
952 "this error originates in a macro outside of the current crate \
953 (in Nightly builds, run with -Z external-macro-backtrace \
954 for more info)".to_string()
956 "this warning originates in a macro outside of the current crate \
957 (in Nightly builds, run with -Z external-macro-backtrace \
958 for more info)".to_string()
962 children.push(SubDiagnostic {
968 span: MultiSpan::new(),
974 /// Adds a left margin to every line but the first, given a padding length and the label being
975 /// displayed, keeping the provided highlighting.
976 fn msg_to_buffer(&self,
977 buffer: &mut StyledBuffer,
978 msg: &[(String, Style)],
981 override_style: Option<Style>) {
983 // The extra 5 ` ` is padding that's always needed to align to the `note: `:
996 // | | length of label
998 // `max_line_num_len`
999 let padding = " ".repeat(padding + label.len() + 5);
1001 /// Returns `true` if `style`, or the override if present and the style is `NoStyle`.
1002 fn style_or_override(style: Style, override_style: Option<Style>) -> Style {
1003 if let Some(o) = override_style {
1004 if style == Style::NoStyle {
1011 let mut line_number = 0;
1013 // Provided the following diagnostic message:
1017 // ("highlighted multiline\nstring to\nsee how it ", Style::NoStyle),
1018 // ("looks", Style::Highlight),
1019 // ("with\nvery ", Style::NoStyle),
1020 // ("weird", Style::Highlight),
1021 // (" formats\n", Style::NoStyle),
1022 // ("see?", Style::Highlight),
1025 // the expected output on a note is (* surround the highlighted text)
1027 // = note: highlighted multiline
1029 // see how it *looks* with
1030 // very *weird* formats
1032 for &(ref text, ref style) in msg.iter() {
1033 let lines = text.split('\n').collect::<Vec<_>>();
1034 if lines.len() > 1 {
1035 for (i, line) in lines.iter().enumerate() {
1038 buffer.append(line_number, &padding, Style::NoStyle);
1040 buffer.append(line_number, line, style_or_override(*style, override_style));
1043 buffer.append(line_number, text, style_or_override(*style, override_style));
1048 fn emit_message_default(
1051 msg: &[(String, Style)],
1052 code: &Option<DiagnosticId>,
1054 max_line_num_len: usize,
1056 ) -> io::Result<()> {
1057 let mut buffer = StyledBuffer::new();
1058 let header_style = if is_secondary {
1061 Style::MainHeaderMsg
1064 if !msp.has_primary_spans() && !msp.has_span_labels() && is_secondary
1065 && !self.short_message {
1066 // This is a secondary message with no span info
1067 for _ in 0..max_line_num_len {
1068 buffer.prepend(0, " ", Style::NoStyle);
1070 draw_note_separator(&mut buffer, 0, max_line_num_len + 1);
1071 let level_str = level.to_string();
1072 if !level_str.is_empty() {
1073 buffer.append(0, &level_str, Style::MainHeaderMsg);
1074 buffer.append(0, ": ", Style::NoStyle);
1076 self.msg_to_buffer(&mut buffer, msg, max_line_num_len, "note", None);
1078 let level_str = level.to_string();
1079 if !level_str.is_empty() {
1080 buffer.append(0, &level_str, Style::Level(level.clone()));
1082 // only render error codes, not lint codes
1083 if let Some(DiagnosticId::Error(ref code)) = *code {
1084 buffer.append(0, "[", Style::Level(level.clone()));
1085 buffer.append(0, &code, Style::Level(level.clone()));
1086 buffer.append(0, "]", Style::Level(level.clone()));
1088 if !level_str.is_empty() {
1089 buffer.append(0, ": ", header_style);
1091 for &(ref text, _) in msg.iter() {
1092 buffer.append(0, text, header_style);
1096 // Preprocess all the annotations so that they are grouped by file and by line number
1097 // This helps us quickly iterate over the whole message (including secondary file spans)
1098 let mut annotated_files = self.preprocess_annotations(msp);
1100 // Make sure our primary file comes first
1101 let (primary_lo, sm) = if let (Some(sm), Some(ref primary_span)) =
1102 (self.sm.as_ref(), msp.primary_span().as_ref()) {
1103 if !primary_span.is_dummy() {
1104 (sm.lookup_char_pos(primary_span.lo()), sm)
1106 emit_to_destination(&buffer.render(), level, &mut self.dst, self.short_message)?;
1110 // If we don't have span information, emit and exit
1111 emit_to_destination(&buffer.render(), level, &mut self.dst, self.short_message)?;
1115 annotated_files.binary_search_by(|x| x.file.name.cmp(&primary_lo.file.name)) {
1116 annotated_files.swap(0, pos);
1119 // Print out the annotate source lines that correspond with the error
1120 for annotated_file in annotated_files {
1121 // we can't annotate anything if the source is unavailable.
1122 if !sm.ensure_source_file_source_present(annotated_file.file.clone()) {
1126 // print out the span location and spacer before we print the annotated source
1127 // to do this, we need to know if this span will be primary
1128 let is_primary = primary_lo.file.name == annotated_file.file.name;
1130 let loc = primary_lo.clone();
1131 if !self.short_message {
1132 // remember where we are in the output buffer for easy reference
1133 let buffer_msg_line_offset = buffer.num_lines();
1135 buffer.prepend(buffer_msg_line_offset, "--> ", Style::LineNumber);
1136 buffer.append(buffer_msg_line_offset,
1137 &format!("{}:{}:{}",
1139 sm.doctest_offset_line(&loc.file.name, loc.line),
1141 Style::LineAndColumn);
1142 for _ in 0..max_line_num_len {
1143 buffer.prepend(buffer_msg_line_offset, " ", Style::NoStyle);
1147 &format!("{}:{}:{}: ",
1149 sm.doctest_offset_line(&loc.file.name, loc.line),
1151 Style::LineAndColumn);
1153 } else if !self.short_message {
1154 // remember where we are in the output buffer for easy reference
1155 let buffer_msg_line_offset = buffer.num_lines();
1158 draw_col_separator(&mut buffer, buffer_msg_line_offset, max_line_num_len + 1);
1160 // Then, the secondary file indicator
1161 buffer.prepend(buffer_msg_line_offset + 1, "::: ", Style::LineNumber);
1162 let loc = if let Some(first_line) = annotated_file.lines.first() {
1163 let col = if let Some(first_annotation) = first_line.annotations.first() {
1164 format!(":{}", first_annotation.start_col + 1)
1169 annotated_file.file.name,
1170 sm.doctest_offset_line(
1171 &annotated_file.file.name, first_line.line_index),
1174 annotated_file.file.name.to_string()
1176 buffer.append(buffer_msg_line_offset + 1,
1178 Style::LineAndColumn);
1179 for _ in 0..max_line_num_len {
1180 buffer.prepend(buffer_msg_line_offset + 1, " ", Style::NoStyle);
1184 if !self.short_message {
1185 // Put in the spacer between the location and annotated source
1186 let buffer_msg_line_offset = buffer.num_lines();
1187 draw_col_separator_no_space(&mut buffer,
1188 buffer_msg_line_offset,
1189 max_line_num_len + 1);
1191 // Contains the vertical lines' positions for active multiline annotations
1192 let mut multilines = FxHashMap::default();
1194 // Next, output the annotate source for this file
1195 for line_idx in 0..annotated_file.lines.len() {
1196 let previous_buffer_line = buffer.num_lines();
1198 let width_offset = 3 + max_line_num_len;
1199 let code_offset = if annotated_file.multiline_depth == 0 {
1202 width_offset + annotated_file.multiline_depth + 1
1205 let depths = self.render_source_line(&mut buffer,
1206 annotated_file.file.clone(),
1207 &annotated_file.lines[line_idx],
1211 let mut to_add = FxHashMap::default();
1213 for (depth, style) in depths {
1214 if multilines.get(&depth).is_some() {
1215 multilines.remove(&depth);
1217 to_add.insert(depth, style);
1221 // Set the multiline annotation vertical lines to the left of
1222 // the code in this line.
1223 for (depth, style) in &multilines {
1224 for line in previous_buffer_line..buffer.num_lines() {
1225 draw_multiline_line(&mut buffer,
1232 // check to see if we need to print out or elide lines that come between
1233 // this annotated line and the next one.
1234 if line_idx < (annotated_file.lines.len() - 1) {
1235 let line_idx_delta = annotated_file.lines[line_idx + 1].line_index -
1236 annotated_file.lines[line_idx].line_index;
1237 if line_idx_delta > 2 {
1238 let last_buffer_line_num = buffer.num_lines();
1239 buffer.puts(last_buffer_line_num, 0, "...", Style::LineNumber);
1241 // Set the multiline annotation vertical lines on `...` bridging line.
1242 for (depth, style) in &multilines {
1243 draw_multiline_line(&mut buffer,
1244 last_buffer_line_num,
1249 } else if line_idx_delta == 2 {
1250 let unannotated_line = annotated_file.file
1251 .get_line(annotated_file.lines[line_idx].line_index)
1252 .unwrap_or_else(|| Cow::from(""));
1254 let last_buffer_line_num = buffer.num_lines();
1256 buffer.puts(last_buffer_line_num,
1258 &self.maybe_anonymized(annotated_file.lines[line_idx + 1]
1261 draw_col_separator(&mut buffer,
1262 last_buffer_line_num,
1263 1 + max_line_num_len);
1264 buffer.puts(last_buffer_line_num,
1269 for (depth, style) in &multilines {
1270 draw_multiline_line(&mut buffer,
1271 last_buffer_line_num,
1279 multilines.extend(&to_add);
1284 // final step: take our styled buffer, render it, then output it
1285 emit_to_destination(&buffer.render(), level, &mut self.dst, self.short_message)?;
1291 fn emit_suggestion_default(
1293 suggestion: &CodeSuggestion,
1295 max_line_num_len: usize,
1296 ) -> io::Result<()> {
1297 if let Some(ref sm) = self.sm {
1298 let mut buffer = StyledBuffer::new();
1300 // Render the suggestion message
1301 let level_str = level.to_string();
1302 if !level_str.is_empty() {
1303 buffer.append(0, &level_str, Style::Level(level.clone()));
1304 buffer.append(0, ": ", Style::HeaderMsg);
1308 &[(suggestion.msg.to_owned(), Style::NoStyle)],
1311 Some(Style::HeaderMsg),
1314 // Render the replacements for each suggestion
1315 let suggestions = suggestion.splice_lines(&**sm);
1317 let mut row_num = 2;
1318 for &(ref complete, ref parts) in suggestions.iter().take(MAX_SUGGESTIONS) {
1319 // Only show underline if the suggestion spans a single line and doesn't cover the
1320 // entirety of the code output. If you have multiple replacements in the same line
1321 // of code, show the underline.
1322 let show_underline = !(parts.len() == 1
1323 && parts[0].snippet.trim() == complete.trim())
1324 && complete.lines().count() == 1;
1326 let lines = sm.span_to_lines(parts[0].span).unwrap();
1328 assert!(!lines.lines.is_empty());
1330 let line_start = sm.lookup_char_pos(parts[0].span.lo()).line;
1331 draw_col_separator_no_space(&mut buffer, 1, max_line_num_len + 1);
1332 let mut line_pos = 0;
1333 let mut lines = complete.lines();
1334 for line in lines.by_ref().take(MAX_HIGHLIGHT_LINES) {
1335 // Print the span column to avoid confusion
1336 buffer.puts(row_num,
1338 &self.maybe_anonymized(line_start + line_pos),
1340 // print the suggestion
1341 draw_col_separator(&mut buffer, row_num, max_line_num_len + 1);
1342 buffer.append(row_num, line, Style::NoStyle);
1347 // This offset and the ones below need to be signed to account for replacement code
1348 // that is shorter than the original code.
1349 let mut offset: isize = 0;
1350 // Only show an underline in the suggestions if the suggestion is not the
1351 // entirety of the code being shown and the displayed code is not multiline.
1353 draw_col_separator(&mut buffer, row_num, max_line_num_len + 1);
1355 let span_start_pos = sm.lookup_char_pos(part.span.lo()).col_display;
1356 let span_end_pos = sm.lookup_char_pos(part.span.hi()).col_display;
1358 // Do not underline the leading...
1359 let start = part.snippet.len()
1360 .saturating_sub(part.snippet.trim_start().len());
1361 // ...or trailing spaces. Account for substitutions containing unicode
1363 let sub_len = part.snippet.trim().chars().fold(0, |acc, ch| {
1364 acc + unicode_width::UnicodeWidthChar::width(ch).unwrap_or(0)
1367 let underline_start = (span_start_pos + start) as isize + offset;
1368 let underline_end = (span_start_pos + start + sub_len) as isize + offset;
1369 for p in underline_start..underline_end {
1370 buffer.putc(row_num,
1371 max_line_num_len + 3 + p as usize,
1373 Style::UnderlinePrimary);
1375 // underline removals too
1376 if underline_start == underline_end {
1377 for p in underline_start-1..underline_start+1 {
1378 buffer.putc(row_num,
1379 max_line_num_len + 3 + p as usize,
1381 Style::UnderlineSecondary);
1385 // length of the code after substitution
1386 let full_sub_len = part.snippet.chars().fold(0, |acc, ch| {
1387 acc + unicode_width::UnicodeWidthChar::width(ch).unwrap_or(0) as isize
1390 // length of the code to be substituted
1391 let snippet_len = span_end_pos as isize - span_start_pos as isize;
1392 // For multiple substitutions, use the position *after* the previous
1393 // substitutions have happened.
1394 offset += full_sub_len - snippet_len;
1399 // if we elided some lines, add an ellipsis
1400 if lines.next().is_some() {
1401 buffer.puts(row_num, max_line_num_len - 1, "...", Style::LineNumber);
1402 } else if !show_underline {
1403 draw_col_separator_no_space(&mut buffer, row_num, max_line_num_len + 1);
1407 if suggestions.len() > MAX_SUGGESTIONS {
1408 let msg = format!("and {} other candidates", suggestions.len() - MAX_SUGGESTIONS);
1409 buffer.puts(row_num, 0, &msg, Style::NoStyle);
1411 emit_to_destination(&buffer.render(), level, &mut self.dst, self.short_message)?;
1416 fn emit_messages_default(&mut self,
1418 message: &[(String, Style)],
1419 code: &Option<DiagnosticId>,
1421 children: &[SubDiagnostic],
1422 suggestions: &[CodeSuggestion]) {
1423 let max_line_num_len = if self.ui_testing {
1424 ANONYMIZED_LINE_NUM.len()
1426 self.get_max_line_num(span, children).to_string().len()
1429 match self.emit_message_default(span,
1436 if !children.is_empty() {
1437 let mut buffer = StyledBuffer::new();
1438 if !self.short_message {
1439 draw_col_separator_no_space(&mut buffer, 0, max_line_num_len + 1);
1441 match emit_to_destination(&buffer.render(), level, &mut self.dst,
1442 self.short_message) {
1444 Err(e) => panic!("failed to emit error: {}", e)
1447 if !self.short_message {
1448 for child in children {
1449 let span = child.render_span.as_ref().unwrap_or(&child.span);
1450 match self.emit_message_default(
1452 &child.styled_message(),
1458 Err(e) => panic!("failed to emit error: {}", e),
1462 for sugg in suggestions {
1463 if sugg.style == SuggestionStyle::CompletelyHidden {
1464 // do not display this suggestion, it is meant only for tools
1465 } else if sugg.style == SuggestionStyle::HideCodeAlways {
1466 match self.emit_message_default(
1468 &[(sugg.msg.to_owned(), Style::HeaderMsg)],
1474 Err(e) => panic!("failed to emit error: {}", e),
1478 match self.emit_suggestion_default(
1483 Err(e) => panic!("failed to emit error: {}", e),
1490 Err(e) => panic!("failed to emit error: {}", e),
1493 let mut dst = self.dst.writable();
1494 match write!(dst, "\n") {
1495 Err(e) => panic!("failed to emit error: {}", e),
1498 Err(e) => panic!("failed to emit error: {}", e),
1506 fn draw_col_separator(buffer: &mut StyledBuffer, line: usize, col: usize) {
1507 buffer.puts(line, col, "| ", Style::LineNumber);
1510 fn draw_col_separator_no_space(buffer: &mut StyledBuffer, line: usize, col: usize) {
1511 draw_col_separator_no_space_with_style(buffer, line, col, Style::LineNumber);
1514 fn draw_col_separator_no_space_with_style(buffer: &mut StyledBuffer,
1518 buffer.putc(line, col, '|', style);
1521 fn draw_range(buffer: &mut StyledBuffer, symbol: char, line: usize,
1522 col_from: usize, col_to: usize, style: Style) {
1523 for col in col_from..col_to {
1524 buffer.putc(line, col, symbol, style);
1528 fn draw_note_separator(buffer: &mut StyledBuffer, line: usize, col: usize) {
1529 buffer.puts(line, col, "= ", Style::LineNumber);
1532 fn draw_multiline_line(buffer: &mut StyledBuffer,
1538 buffer.putc(line, offset + depth - 1, '|', style);
1541 fn num_overlap(a_start: usize, a_end: usize, b_start: usize, b_end:usize, inclusive: bool) -> bool {
1542 let extra = if inclusive {
1547 (b_start..b_end + extra).contains(&a_start) ||
1548 (a_start..a_end + extra).contains(&b_start)
1550 fn overlaps(a1: &Annotation, a2: &Annotation, padding: usize) -> bool {
1551 num_overlap(a1.start_col, a1.end_col + padding, a2.start_col, a2.end_col, false)
1554 fn emit_to_destination(rendered_buffer: &[Vec<StyledString>],
1556 dst: &mut Destination,
1557 short_message: bool)
1561 let mut dst = dst.writable();
1563 // In order to prevent error message interleaving, where multiple error lines get intermixed
1564 // when multiple compiler processes error simultaneously, we emit errors with additional
1567 // On Unix systems, we write into a buffered terminal rather than directly to a terminal. When
1568 // the .flush() is called we take the buffer created from the buffered writes and write it at
1569 // one shot. Because the Unix systems use ANSI for the colors, which is a text-based styling
1570 // scheme, this buffered approach works and maintains the styling.
1572 // On Windows, styling happens through calls to a terminal API. This prevents us from using the
1573 // same buffering approach. Instead, we use a global Windows mutex, which we acquire long
1574 // enough to output the full error message, then we release.
1575 let _buffer_lock = lock::acquire_global_lock("rustc_errors");
1576 for (pos, line) in rendered_buffer.iter().enumerate() {
1578 dst.apply_style(lvl.clone(), part.style)?;
1579 write!(dst, "{}", part.text)?;
1582 if !short_message && (!lvl.is_failure_note() || pos != rendered_buffer.len() - 1) {
1590 pub enum Destination {
1591 Terminal(StandardStream),
1592 Buffered(BufferWriter),
1593 // The bool denotes whether we should be emitting ansi color codes or not
1594 Raw(Box<(dyn Write + Send)>, bool),
1597 pub enum WritableDst<'a> {
1598 Terminal(&'a mut StandardStream),
1599 Buffered(&'a mut BufferWriter, Buffer),
1600 Raw(&'a mut (dyn Write + Send)),
1601 ColoredRaw(Ansi<&'a mut (dyn Write + Send)>),
1605 fn from_stderr(color: ColorConfig) -> Destination {
1606 let choice = color.to_color_choice();
1607 // On Windows we'll be performing global synchronization on the entire
1608 // system for emitting rustc errors, so there's no need to buffer
1611 // On non-Windows we rely on the atomicity of `write` to ensure errors
1612 // don't get all jumbled up.
1614 Terminal(StandardStream::stderr(choice))
1616 Buffered(BufferWriter::stderr(choice))
1620 fn writable<'a>(&'a mut self) -> WritableDst<'a> {
1622 Destination::Terminal(ref mut t) => WritableDst::Terminal(t),
1623 Destination::Buffered(ref mut t) => {
1624 let buf = t.buffer();
1625 WritableDst::Buffered(t, buf)
1627 Destination::Raw(ref mut t, false) => WritableDst::Raw(t),
1628 Destination::Raw(ref mut t, true) => WritableDst::ColoredRaw(Ansi::new(t)),
1633 impl<'a> WritableDst<'a> {
1634 fn apply_style(&mut self, lvl: Level, style: Style) -> io::Result<()> {
1635 let mut spec = ColorSpec::new();
1637 Style::LineAndColumn => {}
1638 Style::LineNumber => {
1639 spec.set_bold(true);
1640 spec.set_intense(true);
1642 spec.set_fg(Some(Color::Cyan));
1644 spec.set_fg(Some(Color::Blue));
1647 Style::Quotation => {}
1648 Style::OldSchoolNoteText | Style::MainHeaderMsg => {
1649 spec.set_bold(true);
1651 spec.set_intense(true)
1652 .set_fg(Some(Color::White));
1655 Style::UnderlinePrimary | Style::LabelPrimary => {
1657 spec.set_bold(true);
1659 Style::UnderlineSecondary |
1660 Style::LabelSecondary => {
1664 spec.set_fg(Some(Color::Cyan));
1666 spec.set_fg(Some(Color::Blue));
1670 Style::NoStyle => {}
1671 Style::Level(lvl) => {
1673 spec.set_bold(true);
1675 Style::Highlight => {
1676 spec.set_bold(true);
1679 self.set_color(&spec)
1682 fn set_color(&mut self, color: &ColorSpec) -> io::Result<()> {
1684 WritableDst::Terminal(ref mut t) => t.set_color(color),
1685 WritableDst::Buffered(_, ref mut t) => t.set_color(color),
1686 WritableDst::ColoredRaw(ref mut t) => t.set_color(color),
1687 WritableDst::Raw(_) => Ok(())
1691 fn reset(&mut self) -> io::Result<()> {
1693 WritableDst::Terminal(ref mut t) => t.reset(),
1694 WritableDst::Buffered(_, ref mut t) => t.reset(),
1695 WritableDst::ColoredRaw(ref mut t) => t.reset(),
1696 WritableDst::Raw(_) => Ok(()),
1701 impl<'a> Write for WritableDst<'a> {
1702 fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
1704 WritableDst::Terminal(ref mut t) => t.write(bytes),
1705 WritableDst::Buffered(_, ref mut buf) => buf.write(bytes),
1706 WritableDst::Raw(ref mut w) => w.write(bytes),
1707 WritableDst::ColoredRaw(ref mut t) => t.write(bytes),
1711 fn flush(&mut self) -> io::Result<()> {
1713 WritableDst::Terminal(ref mut t) => t.flush(),
1714 WritableDst::Buffered(_, ref mut buf) => buf.flush(),
1715 WritableDst::Raw(ref mut w) => w.flush(),
1716 WritableDst::ColoredRaw(ref mut w) => w.flush(),
1721 impl<'a> Drop for WritableDst<'a> {
1722 fn drop(&mut self) {
1724 WritableDst::Buffered(ref mut dst, ref mut buf) => {
1725 drop(dst.print(buf));