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};
19 use termcolor::{StandardStream, ColorChoice, ColorSpec, BufferWriter, Ansi};
20 use termcolor::{WriteColor, Color, Buffer};
22 /// Describes the way the content of the `rendered` field of the json output is generated
23 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
24 pub enum HumanReadableErrorType {
29 impl HumanReadableErrorType {
30 /// Returns a (`short`, `color`) tuple
31 pub fn unzip(self) -> (bool, ColorConfig) {
33 HumanReadableErrorType::Default(cc) => (false, cc),
34 HumanReadableErrorType::Short(cc) => (true, cc),
39 dst: Box<dyn Write + Send>,
40 source_map: Option<Lrc<SourceMapperDyn>>,
43 let (short, color_config) = self.unzip();
44 EmitterWriter::new(dst, source_map, short, teach, color_config.suggests_using_colors())
48 const ANONYMIZED_LINE_NUM: &str = "LL";
50 /// Emitter trait for emitting errors.
52 /// Emit a structured diagnostic.
53 fn emit_diagnostic(&mut self, db: &DiagnosticBuilder<'_>);
55 /// Emit a JSON directive. The default is to do nothing; this should only
56 /// be emitted with --error-format=json.
57 fn maybe_emit_json_directive(&mut self, _directive: String) {}
59 /// Checks if should show explanations about "rustc --explain"
60 fn should_show_explain(&self) -> bool {
65 impl Emitter for EmitterWriter {
66 fn emit_diagnostic(&mut self, db: &DiagnosticBuilder<'_>) {
67 let mut primary_span = db.span.clone();
68 let mut children = db.children.clone();
69 let mut suggestions: &[_] = &[];
71 if let Some((sugg, rest)) = db.suggestions.split_first() {
73 // don't display multi-suggestions as labels
74 sugg.substitutions.len() == 1 &&
75 // don't display multipart suggestions as labels
76 sugg.substitutions[0].parts.len() == 1 &&
77 // don't display long messages as labels
78 sugg.msg.split_whitespace().count() < 10 &&
79 // don't display multiline suggestions as labels
80 !sugg.substitutions[0].parts[0].snippet.contains('\n') &&
81 // when this style is set we want the suggestion to be a message, not inline
82 sugg.style != SuggestionStyle::HideCodeAlways &&
83 // trivial suggestion for tooling's sake, never shown
84 sugg.style != SuggestionStyle::CompletelyHidden
86 let substitution = &sugg.substitutions[0].parts[0].snippet.trim();
87 let msg = if substitution.len() == 0 || sugg.style.hide_inline() {
88 // This substitution is only removal or we explicitly don't want to show the
89 // code inline, don't show it
90 format!("help: {}", sugg.msg)
92 format!("help: {}: `{}`", sugg.msg, substitution)
94 primary_span.push_span_label(sugg.substitutions[0].parts[0].span, msg);
96 // if there are multiple suggestions, print them all in full
97 // to be consistent. We could try to figure out if we can
98 // make one (or the first one) inline, but that would give
99 // undue importance to a semi-random suggestion
100 suggestions = &db.suggestions;
104 self.fix_multispans_in_std_macros(&mut primary_span,
107 db.handler.flags.external_macro_backtrace);
109 self.emit_messages_default(&db.level,
110 &db.styled_message(),
117 fn should_show_explain(&self) -> bool {
122 /// maximum number of lines we will print for each error; arbitrary.
123 pub const MAX_HIGHLIGHT_LINES: usize = 6;
124 /// maximum number of suggestions to be shown
126 /// Arbitrary, but taken from trait import suggestion limit
127 pub const MAX_SUGGESTIONS: usize = 4;
129 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
130 pub enum ColorConfig {
137 fn to_color_choice(self) -> ColorChoice {
139 ColorConfig::Always => {
140 if atty::is(atty::Stream::Stderr) {
143 ColorChoice::AlwaysAnsi
146 ColorConfig::Never => ColorChoice::Never,
147 ColorConfig::Auto if atty::is(atty::Stream::Stderr) => {
150 ColorConfig::Auto => ColorChoice::Never,
153 fn suggests_using_colors(self) -> bool {
155 | ColorConfig::Always
158 ColorConfig::Never => false,
163 pub struct EmitterWriter {
165 sm: Option<Lrc<SourceMapperDyn>>,
171 struct FileWithAnnotatedLines {
172 file: Lrc<SourceFile>,
174 multiline_depth: usize,
178 pub fn stderr(color_config: ColorConfig,
179 source_map: Option<Lrc<SourceMapperDyn>>,
183 let dst = Destination::from_stderr(color_config);
194 dst: Box<dyn Write + Send>,
195 source_map: Option<Lrc<SourceMapperDyn>>,
201 dst: Raw(dst, colored),
209 pub fn ui_testing(mut self, ui_testing: bool) -> Self {
210 self.ui_testing = ui_testing;
214 fn maybe_anonymized(&self, line_num: usize) -> String {
216 ANONYMIZED_LINE_NUM.to_string()
222 fn preprocess_annotations(&mut self, msp: &MultiSpan) -> Vec<FileWithAnnotatedLines> {
223 fn add_annotation_to_file(file_vec: &mut Vec<FileWithAnnotatedLines>,
224 file: Lrc<SourceFile>,
228 for slot in file_vec.iter_mut() {
229 // Look through each of our files for the one we're adding to
230 if slot.file.name == file.name {
231 // See if we already have a line for it
232 for line_slot in &mut slot.lines {
233 if line_slot.line_index == line_index {
234 line_slot.annotations.push(ann);
238 // We don't have a line yet, create one
239 slot.lines.push(Line {
241 annotations: vec![ann],
247 // This is the first time we're seeing the file
248 file_vec.push(FileWithAnnotatedLines {
252 annotations: vec![ann],
258 let mut output = vec![];
259 let mut multiline_annotations = vec![];
261 if let Some(ref sm) = self.sm {
262 for span_label in msp.span_labels() {
263 if span_label.span.is_dummy() {
267 let lo = sm.lookup_char_pos(span_label.span.lo());
268 let mut hi = sm.lookup_char_pos(span_label.span.hi());
270 // Watch out for "empty spans". If we get a span like 6..6, we
271 // want to just display a `^` at 6, so convert that to
272 // 6..7. This is degenerate input, but it's best to degrade
273 // gracefully -- and the parser likes to supply a span like
274 // that for EOF, in particular.
276 if lo.col_display == hi.col_display && lo.line == hi.line {
280 let ann_type = if lo.line != hi.line {
281 let ml = MultilineAnnotation {
285 start_col: lo.col_display,
286 end_col: hi.col_display,
287 is_primary: span_label.is_primary,
288 label: span_label.label.clone(),
289 overlaps_exactly: false,
291 multiline_annotations.push((lo.file.clone(), ml.clone()));
292 AnnotationType::Multiline(ml)
294 AnnotationType::Singleline
296 let ann = Annotation {
297 start_col: lo.col_display,
298 end_col: hi.col_display,
299 is_primary: span_label.is_primary,
300 label: span_label.label.clone(),
301 annotation_type: ann_type,
304 if !ann.is_multiline() {
305 add_annotation_to_file(&mut output, lo.file, lo.line, ann);
310 // Find overlapping multiline annotations, put them at different depths
311 multiline_annotations.sort_by_key(|&(_, ref ml)| (ml.line_start, ml.line_end));
312 for item in multiline_annotations.clone() {
314 for item in multiline_annotations.iter_mut() {
315 let ref mut a = item.1;
316 // Move all other multiline annotations overlapping with this one
317 // one level to the right.
318 if !(ann.same_span(a)) &&
319 num_overlap(ann.line_start, ann.line_end, a.line_start, a.line_end, true)
322 } else if ann.same_span(a) && &ann != a {
323 a.overlaps_exactly = true;
330 let mut max_depth = 0; // max overlapping multiline spans
331 for (file, ann) in multiline_annotations {
332 if ann.depth > max_depth {
333 max_depth = ann.depth;
335 let mut end_ann = ann.as_end();
336 if !ann.overlaps_exactly {
359 add_annotation_to_file(&mut output, file.clone(), ann.line_start, ann.as_start());
360 // 4 is the minimum vertical length of a multiline span when presented: two lines
361 // of code and two lines of underline. This is not true for the special case where
362 // the beginning doesn't have an underline, but the current logic seems to be
363 // working correctly.
364 let middle = min(ann.line_start + 4, ann.line_end);
365 for line in ann.line_start + 1..middle {
366 // Every `|` that joins the beginning of the span (`___^`) to the end (`|__^`).
367 add_annotation_to_file(&mut output, file.clone(), line, ann.as_line());
369 if middle < ann.line_end - 1 {
370 for line in ann.line_end - 1..ann.line_end {
371 add_annotation_to_file(&mut output, file.clone(), line, ann.as_line());
375 end_ann.annotation_type = AnnotationType::Singleline;
377 add_annotation_to_file(&mut output, file, ann.line_end, end_ann);
379 for file_vec in output.iter_mut() {
380 file_vec.multiline_depth = max_depth;
385 fn render_source_line(&self,
386 buffer: &mut StyledBuffer,
387 file: Lrc<SourceFile>,
390 code_offset: usize) -> Vec<(usize, Style)> {
391 if line.line_index == 0 {
395 let source_string = match file.get_line(line.line_index - 1) {
397 None => return Vec::new(),
400 let line_offset = buffer.num_lines();
402 // First create the source line we will highlight.
403 buffer.puts(line_offset, code_offset, &source_string, Style::Quotation);
404 buffer.puts(line_offset,
406 &self.maybe_anonymized(line.line_index),
409 draw_col_separator(buffer, line_offset, width_offset - 2);
411 // Special case when there's only one annotation involved, it is the start of a multiline
412 // span and there's no text at the beginning of the code line. Instead of doing the whole
421 // we simplify the output to:
427 if line.annotations.len() == 1 {
428 if let Some(ref ann) = line.annotations.get(0) {
429 if let AnnotationType::MultilineStart(depth) = ann.annotation_type {
430 if source_string.chars()
432 .all(|c| c.is_whitespace()) {
433 let style = if ann.is_primary {
434 Style::UnderlinePrimary
436 Style::UnderlineSecondary
438 buffer.putc(line_offset,
439 width_offset + depth - 1,
442 return vec![(depth, style)];
448 // We want to display like this:
450 // vec.push(vec.pop().unwrap());
451 // --- ^^^ - previous borrow ends here
453 // | error occurs here
454 // previous borrow of `vec` occurs here
456 // But there are some weird edge cases to be aware of:
458 // vec.push(vec.pop().unwrap());
459 // -------- - previous borrow ends here
461 // |this makes no sense
462 // previous borrow of `vec` occurs here
464 // For this reason, we group the lines into "highlight lines"
465 // and "annotations lines", where the highlight lines have the `^`.
467 // Sort the annotations by (start, end col)
468 // The labels are reversed, sort and then reversed again.
469 // Consider a list of annotations (A1, A2, C1, C2, B1, B2) where
470 // the letter signifies the span. Here we are only sorting by the
471 // span and hence, the order of the elements with the same span will
472 // not change. On reversing the ordering (|a, b| but b.cmp(a)), you get
473 // (C1, C2, B1, B2, A1, A2). All the elements with the same span are
474 // still ordered first to last, but all the elements with different
475 // spans are ordered by their spans in last to first order. Last to
476 // first order is important, because the jiggly lines and | are on
477 // the left, so the rightmost span needs to be rendered first,
478 // otherwise the lines would end up needing to go over a message.
480 let mut annotations = line.annotations.clone();
481 annotations.sort_by_key(|a| Reverse(a.start_col));
483 // First, figure out where each label will be positioned.
485 // In the case where you have the following annotations:
487 // vec.push(vec.pop().unwrap());
488 // -------- - previous borrow ends here [C]
490 // |this makes no sense [B]
491 // previous borrow of `vec` occurs here [A]
493 // `annotations_position` will hold [(2, A), (1, B), (0, C)].
495 // We try, when possible, to stick the rightmost annotation at the end
496 // of the highlight line:
498 // vec.push(vec.pop().unwrap());
499 // --- --- - previous borrow ends here
501 // But sometimes that's not possible because one of the other
502 // annotations overlaps it. For example, from the test
503 // `span_overlap_label`, we have the following annotations
504 // (written on distinct lines for clarity):
510 // In this case, we can't stick the rightmost-most label on
511 // the highlight line, or we would get:
518 // which is totally weird. Instead we want:
526 // which is...less weird, at least. In fact, in general, if
527 // the rightmost span overlaps with any other span, we should
528 // use the "hang below" version, so we can at least make it
529 // clear where the span *starts*. There's an exception for this
530 // logic, when the labels do not have a message:
545 let mut annotations_position = vec![];
546 let mut line_len = 0;
548 for (i, annotation) in annotations.iter().enumerate() {
549 for (j, next) in annotations.iter().enumerate() {
550 if overlaps(next, annotation, 0) // This label overlaps with another one and both
551 && annotation.has_label() // take space (they have text and are not
552 && j > i // multiline lines).
553 && p == 0 // We're currently on the first line, move the label one line down
555 // If we're overlapping with an un-labelled annotation with the same span
556 // we can just merge them in the output
557 if next.start_col == annotation.start_col
558 && next.end_col == annotation.end_col
564 // This annotation needs a new line in the output.
569 annotations_position.push((p, annotation));
570 for (j, next) in annotations.iter().enumerate() {
572 let l = if let Some(ref label) = next.label {
577 if (overlaps(next, annotation, l) // Do not allow two labels to be in the same
578 // line if they overlap including padding, to
579 // avoid situations like:
586 && annotation.has_label() // Both labels must have some text, otherwise
587 && next.has_label()) // they are not overlapping.
588 // Do not add a new line if this annotation
589 // or the next are vertical line placeholders.
590 || (annotation.takes_space() // If either this or the next annotation is
591 && next.has_label()) // multiline start/end, move it to a new line
592 || (annotation.has_label() // so as not to overlap the orizontal lines.
593 && next.takes_space())
594 || (annotation.takes_space() && next.takes_space())
595 || (overlaps(next, annotation, l)
596 && next.end_col <= annotation.end_col
598 && p == 0) // Avoid #42595.
600 // This annotation needs a new line in the output.
615 // If there are no annotations or the only annotations on this line are
616 // MultilineLine, then there's only code being shown, stop processing.
617 if line.annotations.iter().all(|a| a.is_line()) {
621 // Write the colunmn separator.
623 // After this we will have:
632 for pos in 0..=line_len {
633 draw_col_separator(buffer, line_offset + pos + 1, width_offset - 2);
634 buffer.putc(line_offset + pos + 1,
640 // Write the horizontal lines for multiline annotations
641 // (only the first and last lines need this).
643 // After this we will have:
652 for &(pos, annotation) in &annotations_position {
653 let style = if annotation.is_primary {
654 Style::UnderlinePrimary
656 Style::UnderlineSecondary
659 match annotation.annotation_type {
660 AnnotationType::MultilineStart(depth) |
661 AnnotationType::MultilineEnd(depth) => {
665 width_offset + depth,
666 code_offset + annotation.start_col,
670 buffer.set_style_range(line_offset,
671 code_offset + annotation.start_col,
672 code_offset + annotation.end_col,
674 annotation.is_primary);
680 // Write the vertical lines for labels that are on a different line as the underline.
682 // After this we will have:
691 for &(pos, annotation) in &annotations_position {
692 let style = if annotation.is_primary {
693 Style::UnderlinePrimary
695 Style::UnderlineSecondary
699 if pos > 1 && (annotation.has_label() || annotation.takes_space()) {
700 for p in line_offset + 1..=line_offset + pos {
702 code_offset + annotation.start_col,
707 match annotation.annotation_type {
708 AnnotationType::MultilineStart(depth) => {
709 for p in line_offset + pos + 1..line_offset + line_len + 2 {
711 width_offset + depth - 1,
716 AnnotationType::MultilineEnd(depth) => {
717 for p in line_offset..=line_offset + pos {
719 width_offset + depth - 1,
728 // Write the labels on the annotations that actually have a label.
730 // After this we will have:
735 // | something about `foo`
739 for &(pos, annotation) in &annotations_position {
740 let style = if annotation.is_primary {
743 Style::LabelSecondary
745 let (pos, col) = if pos == 0 {
746 (pos + 1, annotation.end_col + 1)
748 (pos + 2, annotation.start_col)
750 if let Some(ref label) = annotation.label {
751 buffer.puts(line_offset + pos,
758 // Sort from biggest span to smallest span so that smaller spans are
759 // represented in the output:
764 // | | something about `foo`
765 // | something about `fn foo()`
766 annotations_position.sort_by(|a, b| {
767 // Decreasing order. When `a` and `b` are the same length, prefer `Primary`.
768 (a.1.len(), !a.1.is_primary).cmp(&(b.1.len(), !b.1.is_primary)).reverse()
771 // Write the underlines.
773 // After this we will have:
778 // | something about `foo`
782 for &(_, annotation) in &annotations_position {
783 let (underline, style) = if annotation.is_primary {
784 ('^', Style::UnderlinePrimary)
786 ('-', Style::UnderlineSecondary)
788 for p in annotation.start_col..annotation.end_col {
789 buffer.putc(line_offset + 1,
795 annotations_position.iter().filter_map(|&(_, annotation)| {
796 match annotation.annotation_type {
797 AnnotationType::MultilineStart(p) | AnnotationType::MultilineEnd(p) => {
798 let style = if annotation.is_primary {
801 Style::LabelSecondary
808 }).collect::<Vec<_>>()
811 fn get_multispan_max_line_num(&mut self, msp: &MultiSpan) -> usize {
813 if let Some(ref sm) = self.sm {
814 for primary_span in msp.primary_spans() {
815 if !primary_span.is_dummy() {
816 let hi = sm.lookup_char_pos(primary_span.hi());
822 if !self.short_message {
823 for span_label in msp.span_labels() {
824 if !span_label.span.is_dummy() {
825 let hi = sm.lookup_char_pos(span_label.span.hi());
836 fn get_max_line_num(&mut self, span: &MultiSpan, children: &[SubDiagnostic]) -> usize {
839 let primary = self.get_multispan_max_line_num(span);
840 max = if primary > max { primary } else { max };
842 for sub in children {
843 let sub_result = self.get_multispan_max_line_num(&sub.span);
844 max = if sub_result > max { primary } else { max };
849 // This "fixes" MultiSpans that contain Spans that are pointing to locations inside of
850 // <*macros>. Since these locations are often difficult to read, we move these Spans from
851 // <*macros> to their corresponding use site.
852 fn fix_multispan_in_std_macros(&mut self,
853 span: &mut MultiSpan,
854 always_backtrace: bool) -> bool {
855 let mut spans_updated = false;
857 if let Some(ref sm) = self.sm {
858 let mut before_after: Vec<(Span, Span)> = vec![];
859 let mut new_labels: Vec<(Span, String)> = vec![];
861 // First, find all the spans in <*macros> and point instead at their use site
862 for sp in span.primary_spans() {
866 let call_sp = sm.call_span_if_macro(*sp);
867 if call_sp != *sp && !always_backtrace {
868 before_after.push((*sp, call_sp));
870 let backtrace_len = sp.macro_backtrace().len();
871 for (i, trace) in sp.macro_backtrace().iter().rev().enumerate() {
872 // Only show macro locations that are local
873 // and display them like a span_note
874 if let Some(def_site) = trace.def_site_span {
875 if def_site.is_dummy() {
878 if always_backtrace {
879 new_labels.push((def_site,
880 format!("in this expansion of `{}`{}",
881 trace.macro_decl_name,
882 if backtrace_len > 2 {
883 // if backtrace_len == 1 it'll be pointed
884 // at by "in this macro invocation"
885 format!(" (#{})", i + 1)
890 // Check to make sure we're not in any <*macros>
891 if !sm.span_to_filename(def_site).is_macros() &&
892 !trace.macro_decl_name.starts_with("desugaring of ") &&
893 !trace.macro_decl_name.starts_with("#[") ||
895 new_labels.push((trace.call_site,
896 format!("in this macro invocation{}",
897 if backtrace_len > 2 && always_backtrace {
898 // only specify order when the macro
899 // backtrace is multiple levels deep
900 format!(" (#{})", i + 1)
904 if !always_backtrace {
911 for (label_span, label_text) in new_labels {
912 span.push_span_label(label_span, label_text);
914 for sp_label in span.span_labels() {
915 if sp_label.span.is_dummy() {
918 if sm.span_to_filename(sp_label.span.clone()).is_macros() &&
921 let v = sp_label.span.macro_backtrace();
922 if let Some(use_site) = v.last() {
923 before_after.push((sp_label.span.clone(), use_site.call_site.clone()));
927 // After we have them, make sure we replace these 'bad' def sites with their use sites
928 for (before, after) in before_after {
929 span.replace(before, after);
930 spans_updated = true;
937 // This does a small "fix" for multispans by looking to see if it can find any that
938 // point directly at <*macros>. Since these are often difficult to read, this
939 // will change the span to point at the use site.
940 fn fix_multispans_in_std_macros(&mut self,
941 span: &mut MultiSpan,
942 children: &mut Vec<SubDiagnostic>,
945 let mut spans_updated = self.fix_multispan_in_std_macros(span, backtrace);
946 for child in children.iter_mut() {
947 spans_updated |= self.fix_multispan_in_std_macros(&mut child.span, backtrace);
949 let msg = if level == &Error {
950 "this error originates in a macro outside of the current crate \
951 (in Nightly builds, run with -Z external-macro-backtrace \
952 for more info)".to_string()
954 "this warning originates in a macro outside of the current crate \
955 (in Nightly builds, run with -Z external-macro-backtrace \
956 for more info)".to_string()
960 children.push(SubDiagnostic {
966 span: MultiSpan::new(),
972 /// Adds a left margin to every line but the first, given a padding length and the label being
973 /// displayed, keeping the provided highlighting.
974 fn msg_to_buffer(&self,
975 buffer: &mut StyledBuffer,
976 msg: &[(String, Style)],
979 override_style: Option<Style>) {
981 // The extra 5 ` ` is padding that's always needed to align to the `note: `:
994 // | | length of label
996 // `max_line_num_len`
997 let padding = " ".repeat(padding + label.len() + 5);
999 /// Returns `true` if `style`, or the override if present and the style is `NoStyle`.
1000 fn style_or_override(style: Style, override_style: Option<Style>) -> Style {
1001 if let Some(o) = override_style {
1002 if style == Style::NoStyle {
1009 let mut line_number = 0;
1011 // Provided the following diagnostic message:
1015 // ("highlighted multiline\nstring to\nsee how it ", Style::NoStyle),
1016 // ("looks", Style::Highlight),
1017 // ("with\nvery ", Style::NoStyle),
1018 // ("weird", Style::Highlight),
1019 // (" formats\n", Style::NoStyle),
1020 // ("see?", Style::Highlight),
1023 // the expected output on a note is (* surround the highlighted text)
1025 // = note: highlighted multiline
1027 // see how it *looks* with
1028 // very *weird* formats
1030 for &(ref text, ref style) in msg.iter() {
1031 let lines = text.split('\n').collect::<Vec<_>>();
1032 if lines.len() > 1 {
1033 for (i, line) in lines.iter().enumerate() {
1036 buffer.append(line_number, &padding, Style::NoStyle);
1038 buffer.append(line_number, line, style_or_override(*style, override_style));
1041 buffer.append(line_number, text, style_or_override(*style, override_style));
1046 fn emit_message_default(
1049 msg: &[(String, Style)],
1050 code: &Option<DiagnosticId>,
1052 max_line_num_len: usize,
1054 ) -> io::Result<()> {
1055 let mut buffer = StyledBuffer::new();
1056 let header_style = if is_secondary {
1059 Style::MainHeaderMsg
1062 if !msp.has_primary_spans() && !msp.has_span_labels() && is_secondary
1063 && !self.short_message {
1064 // This is a secondary message with no span info
1065 for _ in 0..max_line_num_len {
1066 buffer.prepend(0, " ", Style::NoStyle);
1068 draw_note_separator(&mut buffer, 0, max_line_num_len + 1);
1069 let level_str = level.to_string();
1070 if !level_str.is_empty() {
1071 buffer.append(0, &level_str, Style::MainHeaderMsg);
1072 buffer.append(0, ": ", Style::NoStyle);
1074 self.msg_to_buffer(&mut buffer, msg, max_line_num_len, "note", None);
1076 let level_str = level.to_string();
1077 if !level_str.is_empty() {
1078 buffer.append(0, &level_str, Style::Level(level.clone()));
1080 // only render error codes, not lint codes
1081 if let Some(DiagnosticId::Error(ref code)) = *code {
1082 buffer.append(0, "[", Style::Level(level.clone()));
1083 buffer.append(0, &code, Style::Level(level.clone()));
1084 buffer.append(0, "]", Style::Level(level.clone()));
1086 if !level_str.is_empty() {
1087 buffer.append(0, ": ", header_style);
1089 for &(ref text, _) in msg.iter() {
1090 buffer.append(0, text, header_style);
1094 // Preprocess all the annotations so that they are grouped by file and by line number
1095 // This helps us quickly iterate over the whole message (including secondary file spans)
1096 let mut annotated_files = self.preprocess_annotations(msp);
1098 // Make sure our primary file comes first
1099 let (primary_lo, sm) = if let (Some(sm), Some(ref primary_span)) =
1100 (self.sm.as_ref(), msp.primary_span().as_ref()) {
1101 if !primary_span.is_dummy() {
1102 (sm.lookup_char_pos(primary_span.lo()), sm)
1104 emit_to_destination(&buffer.render(), level, &mut self.dst, self.short_message)?;
1108 // If we don't have span information, emit and exit
1109 emit_to_destination(&buffer.render(), level, &mut self.dst, self.short_message)?;
1113 annotated_files.binary_search_by(|x| x.file.name.cmp(&primary_lo.file.name)) {
1114 annotated_files.swap(0, pos);
1117 // Print out the annotate source lines that correspond with the error
1118 for annotated_file in annotated_files {
1119 // we can't annotate anything if the source is unavailable.
1120 if !sm.ensure_source_file_source_present(annotated_file.file.clone()) {
1124 // print out the span location and spacer before we print the annotated source
1125 // to do this, we need to know if this span will be primary
1126 let is_primary = primary_lo.file.name == annotated_file.file.name;
1128 let loc = primary_lo.clone();
1129 if !self.short_message {
1130 // remember where we are in the output buffer for easy reference
1131 let buffer_msg_line_offset = buffer.num_lines();
1133 buffer.prepend(buffer_msg_line_offset, "--> ", Style::LineNumber);
1134 buffer.append(buffer_msg_line_offset,
1135 &format!("{}:{}:{}",
1137 sm.doctest_offset_line(&loc.file.name, loc.line),
1139 Style::LineAndColumn);
1140 for _ in 0..max_line_num_len {
1141 buffer.prepend(buffer_msg_line_offset, " ", Style::NoStyle);
1145 &format!("{}:{}:{}: ",
1147 sm.doctest_offset_line(&loc.file.name, loc.line),
1149 Style::LineAndColumn);
1151 } else if !self.short_message {
1152 // remember where we are in the output buffer for easy reference
1153 let buffer_msg_line_offset = buffer.num_lines();
1156 draw_col_separator(&mut buffer, buffer_msg_line_offset, max_line_num_len + 1);
1158 // Then, the secondary file indicator
1159 buffer.prepend(buffer_msg_line_offset + 1, "::: ", Style::LineNumber);
1160 let loc = if let Some(first_line) = annotated_file.lines.first() {
1161 let col = if let Some(first_annotation) = first_line.annotations.first() {
1162 format!(":{}", first_annotation.start_col + 1)
1167 annotated_file.file.name,
1168 sm.doctest_offset_line(
1169 &annotated_file.file.name, first_line.line_index),
1172 annotated_file.file.name.to_string()
1174 buffer.append(buffer_msg_line_offset + 1,
1176 Style::LineAndColumn);
1177 for _ in 0..max_line_num_len {
1178 buffer.prepend(buffer_msg_line_offset + 1, " ", Style::NoStyle);
1182 if !self.short_message {
1183 // Put in the spacer between the location and annotated source
1184 let buffer_msg_line_offset = buffer.num_lines();
1185 draw_col_separator_no_space(&mut buffer,
1186 buffer_msg_line_offset,
1187 max_line_num_len + 1);
1189 // Contains the vertical lines' positions for active multiline annotations
1190 let mut multilines = FxHashMap::default();
1192 // Next, output the annotate source for this file
1193 for line_idx in 0..annotated_file.lines.len() {
1194 let previous_buffer_line = buffer.num_lines();
1196 let width_offset = 3 + max_line_num_len;
1197 let code_offset = if annotated_file.multiline_depth == 0 {
1200 width_offset + annotated_file.multiline_depth + 1
1203 let depths = self.render_source_line(&mut buffer,
1204 annotated_file.file.clone(),
1205 &annotated_file.lines[line_idx],
1209 let mut to_add = FxHashMap::default();
1211 for (depth, style) in depths {
1212 if multilines.get(&depth).is_some() {
1213 multilines.remove(&depth);
1215 to_add.insert(depth, style);
1219 // Set the multiline annotation vertical lines to the left of
1220 // the code in this line.
1221 for (depth, style) in &multilines {
1222 for line in previous_buffer_line..buffer.num_lines() {
1223 draw_multiline_line(&mut buffer,
1230 // check to see if we need to print out or elide lines that come between
1231 // this annotated line and the next one.
1232 if line_idx < (annotated_file.lines.len() - 1) {
1233 let line_idx_delta = annotated_file.lines[line_idx + 1].line_index -
1234 annotated_file.lines[line_idx].line_index;
1235 if line_idx_delta > 2 {
1236 let last_buffer_line_num = buffer.num_lines();
1237 buffer.puts(last_buffer_line_num, 0, "...", Style::LineNumber);
1239 // Set the multiline annotation vertical lines on `...` bridging line.
1240 for (depth, style) in &multilines {
1241 draw_multiline_line(&mut buffer,
1242 last_buffer_line_num,
1247 } else if line_idx_delta == 2 {
1248 let unannotated_line = annotated_file.file
1249 .get_line(annotated_file.lines[line_idx].line_index)
1250 .unwrap_or_else(|| Cow::from(""));
1252 let last_buffer_line_num = buffer.num_lines();
1254 buffer.puts(last_buffer_line_num,
1256 &self.maybe_anonymized(annotated_file.lines[line_idx + 1]
1259 draw_col_separator(&mut buffer,
1260 last_buffer_line_num,
1261 1 + max_line_num_len);
1262 buffer.puts(last_buffer_line_num,
1267 for (depth, style) in &multilines {
1268 draw_multiline_line(&mut buffer,
1269 last_buffer_line_num,
1277 multilines.extend(&to_add);
1282 // final step: take our styled buffer, render it, then output it
1283 emit_to_destination(&buffer.render(), level, &mut self.dst, self.short_message)?;
1289 fn emit_suggestion_default(
1291 suggestion: &CodeSuggestion,
1293 max_line_num_len: usize,
1294 ) -> io::Result<()> {
1295 if let Some(ref sm) = self.sm {
1296 let mut buffer = StyledBuffer::new();
1298 // Render the suggestion message
1299 let level_str = level.to_string();
1300 if !level_str.is_empty() {
1301 buffer.append(0, &level_str, Style::Level(level.clone()));
1302 buffer.append(0, ": ", Style::HeaderMsg);
1306 &[(suggestion.msg.to_owned(), Style::NoStyle)],
1309 Some(Style::HeaderMsg),
1312 // Render the replacements for each suggestion
1313 let suggestions = suggestion.splice_lines(&**sm);
1315 let mut row_num = 2;
1316 for &(ref complete, ref parts) in suggestions.iter().take(MAX_SUGGESTIONS) {
1317 // Only show underline if the suggestion spans a single line and doesn't cover the
1318 // entirety of the code output. If you have multiple replacements in the same line
1319 // of code, show the underline.
1320 let show_underline = !(parts.len() == 1
1321 && parts[0].snippet.trim() == complete.trim())
1322 && complete.lines().count() == 1;
1324 let lines = sm.span_to_lines(parts[0].span).unwrap();
1326 assert!(!lines.lines.is_empty());
1328 let line_start = sm.lookup_char_pos(parts[0].span.lo()).line;
1329 draw_col_separator_no_space(&mut buffer, 1, max_line_num_len + 1);
1330 let mut line_pos = 0;
1331 let mut lines = complete.lines();
1332 for line in lines.by_ref().take(MAX_HIGHLIGHT_LINES) {
1333 // Print the span column to avoid confusion
1334 buffer.puts(row_num,
1336 &self.maybe_anonymized(line_start + line_pos),
1338 // print the suggestion
1339 draw_col_separator(&mut buffer, row_num, max_line_num_len + 1);
1340 buffer.append(row_num, line, Style::NoStyle);
1345 // This offset and the ones below need to be signed to account for replacement code
1346 // that is shorter than the original code.
1347 let mut offset: isize = 0;
1348 // Only show an underline in the suggestions if the suggestion is not the
1349 // entirety of the code being shown and the displayed code is not multiline.
1351 draw_col_separator(&mut buffer, row_num, max_line_num_len + 1);
1353 let span_start_pos = sm.lookup_char_pos(part.span.lo()).col_display;
1354 let span_end_pos = sm.lookup_char_pos(part.span.hi()).col_display;
1356 // Do not underline the leading...
1357 let start = part.snippet.len()
1358 .saturating_sub(part.snippet.trim_start().len());
1359 // ...or trailing spaces. Account for substitutions containing unicode
1361 let sub_len = part.snippet.trim().chars().fold(0, |acc, ch| {
1362 acc + unicode_width::UnicodeWidthChar::width(ch).unwrap_or(0)
1365 let underline_start = (span_start_pos + start) as isize + offset;
1366 let underline_end = (span_start_pos + start + sub_len) as isize + offset;
1367 for p in underline_start..underline_end {
1368 buffer.putc(row_num,
1369 max_line_num_len + 3 + p as usize,
1371 Style::UnderlinePrimary);
1373 // underline removals too
1374 if underline_start == underline_end {
1375 for p in underline_start-1..underline_start+1 {
1376 buffer.putc(row_num,
1377 max_line_num_len + 3 + p as usize,
1379 Style::UnderlineSecondary);
1383 // length of the code after substitution
1384 let full_sub_len = part.snippet.chars().fold(0, |acc, ch| {
1385 acc + unicode_width::UnicodeWidthChar::width(ch).unwrap_or(0) as isize
1388 // length of the code to be substituted
1389 let snippet_len = span_end_pos as isize - span_start_pos as isize;
1390 // For multiple substitutions, use the position *after* the previous
1391 // substitutions have happened.
1392 offset += full_sub_len - snippet_len;
1397 // if we elided some lines, add an ellipsis
1398 if lines.next().is_some() {
1399 buffer.puts(row_num, max_line_num_len - 1, "...", Style::LineNumber);
1400 } else if !show_underline {
1401 draw_col_separator_no_space(&mut buffer, row_num, max_line_num_len + 1);
1405 if suggestions.len() > MAX_SUGGESTIONS {
1406 let msg = format!("and {} other candidates", suggestions.len() - MAX_SUGGESTIONS);
1407 buffer.puts(row_num, 0, &msg, Style::NoStyle);
1409 emit_to_destination(&buffer.render(), level, &mut self.dst, self.short_message)?;
1414 fn emit_messages_default(&mut self,
1416 message: &[(String, Style)],
1417 code: &Option<DiagnosticId>,
1419 children: &[SubDiagnostic],
1420 suggestions: &[CodeSuggestion]) {
1421 let max_line_num_len = if self.ui_testing {
1422 ANONYMIZED_LINE_NUM.len()
1424 self.get_max_line_num(span, children).to_string().len()
1427 match self.emit_message_default(span,
1434 if !children.is_empty() {
1435 let mut buffer = StyledBuffer::new();
1436 if !self.short_message {
1437 draw_col_separator_no_space(&mut buffer, 0, max_line_num_len + 1);
1439 match emit_to_destination(&buffer.render(), level, &mut self.dst,
1440 self.short_message) {
1442 Err(e) => panic!("failed to emit error: {}", e)
1445 if !self.short_message {
1446 for child in children {
1447 let span = child.render_span.as_ref().unwrap_or(&child.span);
1448 match self.emit_message_default(
1450 &child.styled_message(),
1456 Err(e) => panic!("failed to emit error: {}", e),
1460 for sugg in suggestions {
1461 if sugg.style == SuggestionStyle::CompletelyHidden {
1462 // do not display this suggestion, it is meant only for tools
1463 } else if sugg.style == SuggestionStyle::HideCodeAlways {
1464 match self.emit_message_default(
1466 &[(sugg.msg.to_owned(), Style::HeaderMsg)],
1472 Err(e) => panic!("failed to emit error: {}", e),
1476 match self.emit_suggestion_default(
1481 Err(e) => panic!("failed to emit error: {}", e),
1488 Err(e) => panic!("failed to emit error: {}", e),
1491 let mut dst = self.dst.writable();
1492 match write!(dst, "\n") {
1493 Err(e) => panic!("failed to emit error: {}", e),
1496 Err(e) => panic!("failed to emit error: {}", e),
1504 fn draw_col_separator(buffer: &mut StyledBuffer, line: usize, col: usize) {
1505 buffer.puts(line, col, "| ", Style::LineNumber);
1508 fn draw_col_separator_no_space(buffer: &mut StyledBuffer, line: usize, col: usize) {
1509 draw_col_separator_no_space_with_style(buffer, line, col, Style::LineNumber);
1512 fn draw_col_separator_no_space_with_style(buffer: &mut StyledBuffer,
1516 buffer.putc(line, col, '|', style);
1519 fn draw_range(buffer: &mut StyledBuffer, symbol: char, line: usize,
1520 col_from: usize, col_to: usize, style: Style) {
1521 for col in col_from..col_to {
1522 buffer.putc(line, col, symbol, style);
1526 fn draw_note_separator(buffer: &mut StyledBuffer, line: usize, col: usize) {
1527 buffer.puts(line, col, "= ", Style::LineNumber);
1530 fn draw_multiline_line(buffer: &mut StyledBuffer,
1536 buffer.putc(line, offset + depth - 1, '|', style);
1539 fn num_overlap(a_start: usize, a_end: usize, b_start: usize, b_end:usize, inclusive: bool) -> bool {
1540 let extra = if inclusive {
1545 (b_start..b_end + extra).contains(&a_start) ||
1546 (a_start..a_end + extra).contains(&b_start)
1548 fn overlaps(a1: &Annotation, a2: &Annotation, padding: usize) -> bool {
1549 num_overlap(a1.start_col, a1.end_col + padding, a2.start_col, a2.end_col, false)
1552 fn emit_to_destination(rendered_buffer: &[Vec<StyledString>],
1554 dst: &mut Destination,
1555 short_message: bool)
1559 let mut dst = dst.writable();
1561 // In order to prevent error message interleaving, where multiple error lines get intermixed
1562 // when multiple compiler processes error simultaneously, we emit errors with additional
1565 // On Unix systems, we write into a buffered terminal rather than directly to a terminal. When
1566 // the .flush() is called we take the buffer created from the buffered writes and write it at
1567 // one shot. Because the Unix systems use ANSI for the colors, which is a text-based styling
1568 // scheme, this buffered approach works and maintains the styling.
1570 // On Windows, styling happens through calls to a terminal API. This prevents us from using the
1571 // same buffering approach. Instead, we use a global Windows mutex, which we acquire long
1572 // enough to output the full error message, then we release.
1573 let _buffer_lock = lock::acquire_global_lock("rustc_errors");
1574 for (pos, line) in rendered_buffer.iter().enumerate() {
1576 dst.apply_style(lvl.clone(), part.style)?;
1577 write!(dst, "{}", part.text)?;
1580 if !short_message && (!lvl.is_failure_note() || pos != rendered_buffer.len() - 1) {
1588 pub enum Destination {
1589 Terminal(StandardStream),
1590 Buffered(BufferWriter),
1591 // The bool denotes whether we should be emitting ansi color codes or not
1592 Raw(Box<(dyn Write + Send)>, bool),
1595 pub enum WritableDst<'a> {
1596 Terminal(&'a mut StandardStream),
1597 Buffered(&'a mut BufferWriter, Buffer),
1598 Raw(&'a mut (dyn Write + Send)),
1599 ColoredRaw(Ansi<&'a mut (dyn Write + Send)>),
1603 fn from_stderr(color: ColorConfig) -> Destination {
1604 let choice = color.to_color_choice();
1605 // On Windows we'll be performing global synchronization on the entire
1606 // system for emitting rustc errors, so there's no need to buffer
1609 // On non-Windows we rely on the atomicity of `write` to ensure errors
1610 // don't get all jumbled up.
1612 Terminal(StandardStream::stderr(choice))
1614 Buffered(BufferWriter::stderr(choice))
1618 fn writable<'a>(&'a mut self) -> WritableDst<'a> {
1620 Destination::Terminal(ref mut t) => WritableDst::Terminal(t),
1621 Destination::Buffered(ref mut t) => {
1622 let buf = t.buffer();
1623 WritableDst::Buffered(t, buf)
1625 Destination::Raw(ref mut t, false) => WritableDst::Raw(t),
1626 Destination::Raw(ref mut t, true) => WritableDst::ColoredRaw(Ansi::new(t)),
1631 impl<'a> WritableDst<'a> {
1632 fn apply_style(&mut self, lvl: Level, style: Style) -> io::Result<()> {
1633 let mut spec = ColorSpec::new();
1635 Style::LineAndColumn => {}
1636 Style::LineNumber => {
1637 spec.set_bold(true);
1638 spec.set_intense(true);
1640 spec.set_fg(Some(Color::Cyan));
1642 spec.set_fg(Some(Color::Blue));
1645 Style::Quotation => {}
1646 Style::OldSchoolNoteText | Style::MainHeaderMsg => {
1647 spec.set_bold(true);
1649 spec.set_intense(true)
1650 .set_fg(Some(Color::White));
1653 Style::UnderlinePrimary | Style::LabelPrimary => {
1655 spec.set_bold(true);
1657 Style::UnderlineSecondary |
1658 Style::LabelSecondary => {
1662 spec.set_fg(Some(Color::Cyan));
1664 spec.set_fg(Some(Color::Blue));
1668 Style::NoStyle => {}
1669 Style::Level(lvl) => {
1671 spec.set_bold(true);
1673 Style::Highlight => {
1674 spec.set_bold(true);
1677 self.set_color(&spec)
1680 fn set_color(&mut self, color: &ColorSpec) -> io::Result<()> {
1682 WritableDst::Terminal(ref mut t) => t.set_color(color),
1683 WritableDst::Buffered(_, ref mut t) => t.set_color(color),
1684 WritableDst::ColoredRaw(ref mut t) => t.set_color(color),
1685 WritableDst::Raw(_) => Ok(())
1689 fn reset(&mut self) -> io::Result<()> {
1691 WritableDst::Terminal(ref mut t) => t.reset(),
1692 WritableDst::Buffered(_, ref mut t) => t.reset(),
1693 WritableDst::ColoredRaw(ref mut t) => t.reset(),
1694 WritableDst::Raw(_) => Ok(()),
1699 impl<'a> Write for WritableDst<'a> {
1700 fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
1702 WritableDst::Terminal(ref mut t) => t.write(bytes),
1703 WritableDst::Buffered(_, ref mut buf) => buf.write(bytes),
1704 WritableDst::Raw(ref mut w) => w.write(bytes),
1705 WritableDst::ColoredRaw(ref mut t) => t.write(bytes),
1709 fn flush(&mut self) -> io::Result<()> {
1711 WritableDst::Terminal(ref mut t) => t.flush(),
1712 WritableDst::Buffered(_, ref mut buf) => buf.flush(),
1713 WritableDst::Raw(ref mut w) => w.flush(),
1714 WritableDst::ColoredRaw(ref mut w) => w.flush(),
1719 impl<'a> Drop for WritableDst<'a> {
1720 fn drop(&mut self) {
1722 WritableDst::Buffered(ref mut dst, ref mut buf) => {
1723 drop(dst.print(buf));