1 use self::Destination::*;
3 use syntax_pos::{SourceFile, Span, MultiSpan};
5 use {Level, CodeSuggestion, DiagnosticBuilder, SubDiagnostic, SourceMapperDyn, DiagnosticId};
6 use snippet::{Annotation, AnnotationType, Line, MultilineAnnotation, StyledString, Style};
7 use styled_buffer::StyledBuffer;
9 use rustc_data_structures::fx::FxHashMap;
10 use rustc_data_structures::sync::Lrc;
13 use std::io::prelude::*;
15 use std::cmp::{min, Reverse};
16 use termcolor::{StandardStream, ColorChoice, ColorSpec, BufferWriter};
17 use termcolor::{WriteColor, Color, Buffer};
20 const ANONYMIZED_LINE_NUM: &str = "LL";
22 /// Emitter trait for emitting errors.
24 /// Emit a structured diagnostic.
25 fn emit(&mut self, db: &DiagnosticBuilder);
27 /// Check if should show explanations about "rustc --explain"
28 fn should_show_explain(&self) -> bool {
33 impl Emitter for EmitterWriter {
34 fn emit(&mut self, db: &DiagnosticBuilder) {
35 let mut primary_span = db.span.clone();
36 let mut children = db.children.clone();
37 let mut suggestions: &[_] = &[];
39 if let Some((sugg, rest)) = db.suggestions.split_first() {
41 // don't display multi-suggestions as labels
42 sugg.substitutions.len() == 1 &&
43 // don't display multipart suggestions as labels
44 sugg.substitutions[0].parts.len() == 1 &&
45 // don't display long messages as labels
46 sugg.msg.split_whitespace().count() < 10 &&
47 // don't display multiline suggestions as labels
48 !sugg.substitutions[0].parts[0].snippet.contains('\n') {
49 let substitution = &sugg.substitutions[0].parts[0].snippet.trim();
50 let msg = if substitution.len() == 0 || !sugg.show_code_when_inline {
51 // This substitution is only removal or we explicitly don't want to show the
52 // code inline, don't show it
53 format!("help: {}", sugg.msg)
55 format!("help: {}: `{}`", sugg.msg, substitution)
57 primary_span.push_span_label(sugg.substitutions[0].parts[0].span, msg);
59 // if there are multiple suggestions, print them all in full
60 // to be consistent. We could try to figure out if we can
61 // make one (or the first one) inline, but that would give
62 // undue importance to a semi-random suggestion
63 suggestions = &db.suggestions;
67 self.fix_multispans_in_std_macros(&mut primary_span,
69 db.handler.flags.external_macro_backtrace);
71 self.emit_messages_default(&db.level,
79 fn should_show_explain(&self) -> bool {
84 /// maximum number of lines we will print for each error; arbitrary.
85 pub const MAX_HIGHLIGHT_LINES: usize = 6;
86 /// maximum number of suggestions to be shown
88 /// Arbitrary, but taken from trait import suggestion limit
89 pub const MAX_SUGGESTIONS: usize = 4;
91 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
92 pub enum ColorConfig {
99 fn to_color_choice(&self) -> ColorChoice {
101 ColorConfig::Always => {
102 if atty::is(atty::Stream::Stderr) {
105 ColorChoice::AlwaysAnsi
108 ColorConfig::Never => ColorChoice::Never,
109 ColorConfig::Auto if atty::is(atty::Stream::Stderr) => {
112 ColorConfig::Auto => ColorChoice::Never,
117 pub struct EmitterWriter {
119 sm: Option<Lrc<SourceMapperDyn>>,
125 struct FileWithAnnotatedLines {
126 file: Lrc<SourceFile>,
128 multiline_depth: usize,
132 pub fn stderr(color_config: ColorConfig,
133 source_map: Option<Lrc<SourceMapperDyn>>,
137 let dst = Destination::from_stderr(color_config);
147 pub fn new(dst: Box<dyn Write + Send>,
148 source_map: Option<Lrc<SourceMapperDyn>>,
161 pub fn ui_testing(mut self, ui_testing: bool) -> Self {
162 self.ui_testing = ui_testing;
166 fn maybe_anonymized(&self, line_num: usize) -> String {
168 ANONYMIZED_LINE_NUM.to_string()
174 fn preprocess_annotations(&mut self, msp: &MultiSpan) -> Vec<FileWithAnnotatedLines> {
175 fn add_annotation_to_file(file_vec: &mut Vec<FileWithAnnotatedLines>,
176 file: Lrc<SourceFile>,
180 for slot in file_vec.iter_mut() {
181 // Look through each of our files for the one we're adding to
182 if slot.file.name == file.name {
183 // See if we already have a line for it
184 for line_slot in &mut slot.lines {
185 if line_slot.line_index == line_index {
186 line_slot.annotations.push(ann);
190 // We don't have a line yet, create one
191 slot.lines.push(Line {
193 annotations: vec![ann],
199 // This is the first time we're seeing the file
200 file_vec.push(FileWithAnnotatedLines {
204 annotations: vec![ann],
210 let mut output = vec![];
211 let mut multiline_annotations = vec![];
213 if let Some(ref sm) = self.sm {
214 for span_label in msp.span_labels() {
215 if span_label.span.is_dummy() {
219 let lo = sm.lookup_char_pos(span_label.span.lo());
220 let mut hi = sm.lookup_char_pos(span_label.span.hi());
222 // Watch out for "empty spans". If we get a span like 6..6, we
223 // want to just display a `^` at 6, so convert that to
224 // 6..7. This is degenerate input, but it's best to degrade
225 // gracefully -- and the parser likes to supply a span like
226 // that for EOF, in particular.
227 if lo.col_display == hi.col_display && lo.line == hi.line {
231 let ann_type = if lo.line != hi.line {
232 let ml = MultilineAnnotation {
236 start_col: lo.col_display,
237 end_col: hi.col_display,
238 is_primary: span_label.is_primary,
239 label: span_label.label.clone(),
241 multiline_annotations.push((lo.file.clone(), ml.clone()));
242 AnnotationType::Multiline(ml)
244 AnnotationType::Singleline
246 let ann = Annotation {
247 start_col: lo.col_display,
248 end_col: hi.col_display,
249 is_primary: span_label.is_primary,
250 label: span_label.label.clone(),
251 annotation_type: ann_type,
254 if !ann.is_multiline() {
255 add_annotation_to_file(&mut output,
263 // Find overlapping multiline annotations, put them at different depths
264 multiline_annotations.sort_by_key(|&(_, ref ml)| (ml.line_start, ml.line_end));
265 for item in multiline_annotations.clone() {
267 for item in multiline_annotations.iter_mut() {
268 let ref mut a = item.1;
269 // Move all other multiline annotations overlapping with this one
270 // one level to the right.
272 num_overlap(ann.line_start, ann.line_end, a.line_start, a.line_end, true)
281 let mut max_depth = 0; // max overlapping multiline spans
282 for (file, ann) in multiline_annotations {
283 if ann.depth > max_depth {
284 max_depth = ann.depth;
286 add_annotation_to_file(&mut output, file.clone(), ann.line_start, ann.as_start());
287 let middle = min(ann.line_start + 4, ann.line_end);
288 for line in ann.line_start + 1..middle {
289 add_annotation_to_file(&mut output, file.clone(), line, ann.as_line());
291 if middle < ann.line_end - 1 {
292 for line in ann.line_end - 1..ann.line_end {
293 add_annotation_to_file(&mut output, file.clone(), line, ann.as_line());
296 add_annotation_to_file(&mut output, file, ann.line_end, ann.as_end());
298 for file_vec in output.iter_mut() {
299 file_vec.multiline_depth = max_depth;
304 fn render_source_line(&self,
305 buffer: &mut StyledBuffer,
306 file: Lrc<SourceFile>,
309 code_offset: usize) -> Vec<(usize, Style)> {
310 if line.line_index == 0 {
314 let source_string = match file.get_line(line.line_index - 1) {
316 None => return Vec::new(),
319 let line_offset = buffer.num_lines();
321 // First create the source line we will highlight.
322 buffer.puts(line_offset, code_offset, &source_string, Style::Quotation);
323 buffer.puts(line_offset,
325 &self.maybe_anonymized(line.line_index),
328 draw_col_separator(buffer, line_offset, width_offset - 2);
330 // Special case when there's only one annotation involved, it is the start of a multiline
331 // span and there's no text at the beginning of the code line. Instead of doing the whole
340 // we simplify the output to:
346 if line.annotations.len() == 1 {
347 if let Some(ref ann) = line.annotations.get(0) {
348 if let AnnotationType::MultilineStart(depth) = ann.annotation_type {
349 if source_string.chars()
351 .all(|c| c.is_whitespace()) {
352 let style = if ann.is_primary {
353 Style::UnderlinePrimary
355 Style::UnderlineSecondary
357 buffer.putc(line_offset,
358 width_offset + depth - 1,
361 return vec![(depth, style)];
367 // We want to display like this:
369 // vec.push(vec.pop().unwrap());
370 // --- ^^^ - previous borrow ends here
372 // | error occurs here
373 // previous borrow of `vec` occurs here
375 // But there are some weird edge cases to be aware of:
377 // vec.push(vec.pop().unwrap());
378 // -------- - previous borrow ends here
380 // |this makes no sense
381 // previous borrow of `vec` occurs here
383 // For this reason, we group the lines into "highlight lines"
384 // and "annotations lines", where the highlight lines have the `^`.
386 // Sort the annotations by (start, end col)
387 // The labels are reversed, sort and then reversed again.
388 // Consider a list of annotations (A1, A2, C1, C2, B1, B2) where
389 // the letter signifies the span. Here we are only sorting by the
390 // span and hence, the order of the elements with the same span will
391 // not change. On reversing the ordering (|a, b| but b.cmp(a)), you get
392 // (C1, C2, B1, B2, A1, A2). All the elements with the same span are
393 // still ordered first to last, but all the elements with different
394 // spans are ordered by their spans in last to first order. Last to
395 // first order is important, because the jiggly lines and | are on
396 // the left, so the rightmost span needs to be rendered first,
397 // otherwise the lines would end up needing to go over a message.
399 let mut annotations = line.annotations.clone();
400 annotations.sort_by_key(|a| Reverse(a.start_col));
402 // First, figure out where each label will be positioned.
404 // In the case where you have the following annotations:
406 // vec.push(vec.pop().unwrap());
407 // -------- - previous borrow ends here [C]
409 // |this makes no sense [B]
410 // previous borrow of `vec` occurs here [A]
412 // `annotations_position` will hold [(2, A), (1, B), (0, C)].
414 // We try, when possible, to stick the rightmost annotation at the end
415 // of the highlight line:
417 // vec.push(vec.pop().unwrap());
418 // --- --- - previous borrow ends here
420 // But sometimes that's not possible because one of the other
421 // annotations overlaps it. For example, from the test
422 // `span_overlap_label`, we have the following annotations
423 // (written on distinct lines for clarity):
429 // In this case, we can't stick the rightmost-most label on
430 // the highlight line, or we would get:
437 // which is totally weird. Instead we want:
445 // which is...less weird, at least. In fact, in general, if
446 // the rightmost span overlaps with any other span, we should
447 // use the "hang below" version, so we can at least make it
448 // clear where the span *starts*. There's an exception for this
449 // logic, when the labels do not have a message:
464 let mut annotations_position = vec![];
465 let mut line_len = 0;
467 for (i, annotation) in annotations.iter().enumerate() {
468 for (j, next) in annotations.iter().enumerate() {
469 if overlaps(next, annotation, 0) // This label overlaps with another one and both
470 && annotation.has_label() // take space (they have text and are not
471 && j > i // multiline lines).
472 && p == 0 // We're currently on the first line, move the label one line down
474 // This annotation needs a new line in the output.
479 annotations_position.push((p, annotation));
480 for (j, next) in annotations.iter().enumerate() {
482 let l = if let Some(ref label) = next.label {
487 if (overlaps(next, annotation, l) // Do not allow two labels to be in the same
488 // line if they overlap including padding, to
489 // avoid situations like:
496 && annotation.has_label() // Both labels must have some text, otherwise
497 && next.has_label()) // they are not overlapping.
498 // Do not add a new line if this annotation
499 // or the next are vertical line placeholders.
500 || (annotation.takes_space() // If either this or the next annotation is
501 && next.has_label()) // multiline start/end, move it to a new line
502 || (annotation.has_label() // so as not to overlap the orizontal lines.
503 && next.takes_space())
504 || (annotation.takes_space() && next.takes_space())
505 || (overlaps(next, annotation, l)
506 && next.end_col <= annotation.end_col
508 && p == 0) // Avoid #42595.
510 // This annotation needs a new line in the output.
525 // If there are no annotations or the only annotations on this line are
526 // MultilineLine, then there's only code being shown, stop processing.
527 if line.annotations.iter().all(|a| a.is_line()) {
531 // Write the colunmn separator.
533 // After this we will have:
542 for pos in 0..=line_len {
543 draw_col_separator(buffer, line_offset + pos + 1, width_offset - 2);
544 buffer.putc(line_offset + pos + 1,
550 // Write the horizontal lines for multiline annotations
551 // (only the first and last lines need this).
553 // After this we will have:
562 for &(pos, annotation) in &annotations_position {
563 let style = if annotation.is_primary {
564 Style::UnderlinePrimary
566 Style::UnderlineSecondary
569 match annotation.annotation_type {
570 AnnotationType::MultilineStart(depth) |
571 AnnotationType::MultilineEnd(depth) => {
575 width_offset + depth,
576 code_offset + annotation.start_col,
580 buffer.set_style_range(line_offset,
581 code_offset + annotation.start_col,
582 code_offset + annotation.end_col,
584 annotation.is_primary);
590 // Write the vertical lines for labels that are on a different line as the underline.
592 // After this we will have:
601 for &(pos, annotation) in &annotations_position {
602 let style = if annotation.is_primary {
603 Style::UnderlinePrimary
605 Style::UnderlineSecondary
609 if pos > 1 && (annotation.has_label() || annotation.takes_space()) {
610 for p in line_offset + 1..=line_offset + pos {
612 code_offset + annotation.start_col,
617 match annotation.annotation_type {
618 AnnotationType::MultilineStart(depth) => {
619 for p in line_offset + pos + 1..line_offset + line_len + 2 {
621 width_offset + depth - 1,
626 AnnotationType::MultilineEnd(depth) => {
627 for p in line_offset..=line_offset + pos {
629 width_offset + depth - 1,
638 // Write the labels on the annotations that actually have a label.
640 // After this we will have:
645 // | something about `foo`
649 for &(pos, annotation) in &annotations_position {
650 let style = if annotation.is_primary {
653 Style::LabelSecondary
655 let (pos, col) = if pos == 0 {
656 (pos + 1, annotation.end_col + 1)
658 (pos + 2, annotation.start_col)
660 if let Some(ref label) = annotation.label {
661 buffer.puts(line_offset + pos,
668 // Sort from biggest span to smallest span so that smaller spans are
669 // represented in the output:
674 // | | something about `foo`
675 // | something about `fn foo()`
676 annotations_position.sort_by(|a, b| {
678 a.1.len().cmp(&b.1.len()).reverse()
681 // Write the underlines.
683 // After this we will have:
688 // | something about `foo`
692 for &(_, annotation) in &annotations_position {
693 let (underline, style) = if annotation.is_primary {
694 ('^', Style::UnderlinePrimary)
696 ('-', Style::UnderlineSecondary)
698 for p in annotation.start_col..annotation.end_col {
699 buffer.putc(line_offset + 1,
705 annotations_position.iter().filter_map(|&(_, annotation)| {
706 match annotation.annotation_type {
707 AnnotationType::MultilineStart(p) | AnnotationType::MultilineEnd(p) => {
708 let style = if annotation.is_primary {
711 Style::LabelSecondary
718 }).collect::<Vec<_>>()
721 fn get_multispan_max_line_num(&mut self, msp: &MultiSpan) -> usize {
723 if let Some(ref sm) = self.sm {
724 for primary_span in msp.primary_spans() {
725 if !primary_span.is_dummy() {
726 let hi = sm.lookup_char_pos(primary_span.hi());
732 if !self.short_message {
733 for span_label in msp.span_labels() {
734 if !span_label.span.is_dummy() {
735 let hi = sm.lookup_char_pos(span_label.span.hi());
746 fn get_max_line_num(&mut self, span: &MultiSpan, children: &[SubDiagnostic]) -> usize {
749 let primary = self.get_multispan_max_line_num(span);
750 max = if primary > max { primary } else { max };
752 for sub in children {
753 let sub_result = self.get_multispan_max_line_num(&sub.span);
754 max = if sub_result > max { primary } else { max };
759 // This "fixes" MultiSpans that contain Spans that are pointing to locations inside of
760 // <*macros>. Since these locations are often difficult to read, we move these Spans from
761 // <*macros> to their corresponding use site.
762 fn fix_multispan_in_std_macros(&mut self,
763 span: &mut MultiSpan,
764 always_backtrace: bool) -> bool {
765 let mut spans_updated = false;
767 if let Some(ref sm) = self.sm {
768 let mut before_after: Vec<(Span, Span)> = vec![];
769 let mut new_labels: Vec<(Span, String)> = vec![];
771 // First, find all the spans in <*macros> and point instead at their use site
772 for sp in span.primary_spans() {
776 let call_sp = sm.call_span_if_macro(*sp);
777 if call_sp != *sp && !always_backtrace {
778 before_after.push((*sp, call_sp));
780 let backtrace_len = sp.macro_backtrace().len();
781 for (i, trace) in sp.macro_backtrace().iter().rev().enumerate() {
782 // Only show macro locations that are local
783 // and display them like a span_note
784 if let Some(def_site) = trace.def_site_span {
785 if def_site.is_dummy() {
788 if always_backtrace {
789 new_labels.push((def_site,
790 format!("in this expansion of `{}`{}",
791 trace.macro_decl_name,
792 if backtrace_len > 2 {
793 // if backtrace_len == 1 it'll be pointed
794 // at by "in this macro invocation"
795 format!(" (#{})", i + 1)
800 // Check to make sure we're not in any <*macros>
801 if !sm.span_to_filename(def_site).is_macros() &&
802 !trace.macro_decl_name.starts_with("desugaring of ") &&
803 !trace.macro_decl_name.starts_with("#[") ||
805 new_labels.push((trace.call_site,
806 format!("in this macro invocation{}",
807 if backtrace_len > 2 && always_backtrace {
808 // only specify order when the macro
809 // backtrace is multiple levels deep
810 format!(" (#{})", i + 1)
814 if !always_backtrace {
821 for (label_span, label_text) in new_labels {
822 span.push_span_label(label_span, label_text);
824 for sp_label in span.span_labels() {
825 if sp_label.span.is_dummy() {
828 if sm.span_to_filename(sp_label.span.clone()).is_macros() &&
831 let v = sp_label.span.macro_backtrace();
832 if let Some(use_site) = v.last() {
833 before_after.push((sp_label.span.clone(), use_site.call_site.clone()));
837 // After we have them, make sure we replace these 'bad' def sites with their use sites
838 for (before, after) in before_after {
839 span.replace(before, after);
840 spans_updated = true;
847 // This does a small "fix" for multispans by looking to see if it can find any that
848 // point directly at <*macros>. Since these are often difficult to read, this
849 // will change the span to point at the use site.
850 fn fix_multispans_in_std_macros(&mut self,
851 span: &mut MultiSpan,
852 children: &mut Vec<SubDiagnostic>,
854 let mut spans_updated = self.fix_multispan_in_std_macros(span, backtrace);
855 for child in children.iter_mut() {
856 spans_updated |= self.fix_multispan_in_std_macros(&mut child.span, backtrace);
859 children.push(SubDiagnostic {
862 ("this error originates in a macro outside of the current crate \
863 (in Nightly builds, run with -Z external-macro-backtrace \
864 for more info)".to_string(),
867 span: MultiSpan::new(),
873 /// Add a left margin to every line but the first, given a padding length and the label being
874 /// displayed, keeping the provided highlighting.
875 fn msg_to_buffer(&self,
876 buffer: &mut StyledBuffer,
877 msg: &[(String, Style)],
880 override_style: Option<Style>) {
882 // The extra 5 ` ` is padding that's always needed to align to the `note: `:
895 // | | length of label
897 // `max_line_num_len`
898 let padding = " ".repeat(padding + label.len() + 5);
900 /// Return whether `style`, or the override if present and the style is `NoStyle`.
901 fn style_or_override(style: Style, override_style: Option<Style>) -> Style {
902 if let Some(o) = override_style {
903 if style == Style::NoStyle {
910 let mut line_number = 0;
912 // Provided the following diagnostic message:
916 // ("highlighted multiline\nstring to\nsee how it ", Style::NoStyle),
917 // ("looks", Style::Highlight),
918 // ("with\nvery ", Style::NoStyle),
919 // ("weird", Style::Highlight),
920 // (" formats\n", Style::NoStyle),
921 // ("see?", Style::Highlight),
924 // the expected output on a note is (* surround the highlighted text)
926 // = note: highlighted multiline
928 // see how it *looks* with
929 // very *weird* formats
931 for &(ref text, ref style) in msg.iter() {
932 let lines = text.split('\n').collect::<Vec<_>>();
934 for (i, line) in lines.iter().enumerate() {
937 buffer.append(line_number, &padding, Style::NoStyle);
939 buffer.append(line_number, line, style_or_override(*style, override_style));
942 buffer.append(line_number, text, style_or_override(*style, override_style));
947 fn emit_message_default(&mut self,
949 msg: &[(String, Style)],
950 code: &Option<DiagnosticId>,
952 max_line_num_len: usize,
955 let mut buffer = StyledBuffer::new();
956 let header_style = if is_secondary {
962 if !msp.has_primary_spans() && !msp.has_span_labels() && is_secondary
963 && !self.short_message {
964 // This is a secondary message with no span info
965 for _ in 0..max_line_num_len {
966 buffer.prepend(0, " ", Style::NoStyle);
968 draw_note_separator(&mut buffer, 0, max_line_num_len + 1);
969 let level_str = level.to_string();
970 if !level_str.is_empty() {
971 buffer.append(0, &level_str, Style::MainHeaderMsg);
972 buffer.append(0, ": ", Style::NoStyle);
974 self.msg_to_buffer(&mut buffer, msg, max_line_num_len, "note", None);
976 let level_str = level.to_string();
977 if !level_str.is_empty() {
978 buffer.append(0, &level_str, Style::Level(level.clone()));
980 // only render error codes, not lint codes
981 if let Some(DiagnosticId::Error(ref code)) = *code {
982 buffer.append(0, "[", Style::Level(level.clone()));
983 buffer.append(0, &code, Style::Level(level.clone()));
984 buffer.append(0, "]", Style::Level(level.clone()));
986 if !level_str.is_empty() {
987 buffer.append(0, ": ", header_style);
989 for &(ref text, _) in msg.iter() {
990 buffer.append(0, text, header_style);
994 // Preprocess all the annotations so that they are grouped by file and by line number
995 // This helps us quickly iterate over the whole message (including secondary file spans)
996 let mut annotated_files = self.preprocess_annotations(msp);
998 // Make sure our primary file comes first
999 let (primary_lo, sm) = if let (Some(sm), Some(ref primary_span)) =
1000 (self.sm.as_ref(), msp.primary_span().as_ref()) {
1001 if !primary_span.is_dummy() {
1002 (sm.lookup_char_pos(primary_span.lo()), sm)
1004 emit_to_destination(&buffer.render(), level, &mut self.dst, self.short_message)?;
1008 // If we don't have span information, emit and exit
1009 emit_to_destination(&buffer.render(), level, &mut self.dst, self.short_message)?;
1013 annotated_files.binary_search_by(|x| x.file.name.cmp(&primary_lo.file.name)) {
1014 annotated_files.swap(0, pos);
1017 // Print out the annotate source lines that correspond with the error
1018 for annotated_file in annotated_files {
1019 // we can't annotate anything if the source is unavailable.
1020 if !sm.ensure_source_file_source_present(annotated_file.file.clone()) {
1024 // print out the span location and spacer before we print the annotated source
1025 // to do this, we need to know if this span will be primary
1026 let is_primary = primary_lo.file.name == annotated_file.file.name;
1028 let loc = primary_lo.clone();
1029 if !self.short_message {
1030 // remember where we are in the output buffer for easy reference
1031 let buffer_msg_line_offset = buffer.num_lines();
1033 buffer.prepend(buffer_msg_line_offset, "--> ", Style::LineNumber);
1034 buffer.append(buffer_msg_line_offset,
1035 &format!("{}:{}:{}",
1037 sm.doctest_offset_line(&loc.file.name, loc.line),
1039 Style::LineAndColumn);
1040 for _ in 0..max_line_num_len {
1041 buffer.prepend(buffer_msg_line_offset, " ", Style::NoStyle);
1045 &format!("{}:{}:{}: ",
1047 sm.doctest_offset_line(&loc.file.name, loc.line),
1049 Style::LineAndColumn);
1051 } else if !self.short_message {
1052 // remember where we are in the output buffer for easy reference
1053 let buffer_msg_line_offset = buffer.num_lines();
1056 draw_col_separator(&mut buffer, buffer_msg_line_offset, max_line_num_len + 1);
1058 // Then, the secondary file indicator
1059 buffer.prepend(buffer_msg_line_offset + 1, "::: ", Style::LineNumber);
1060 let loc = if let Some(first_line) = annotated_file.lines.first() {
1061 let col = if let Some(first_annotation) = first_line.annotations.first() {
1062 format!(":{}", first_annotation.start_col + 1)
1067 annotated_file.file.name,
1068 sm.doctest_offset_line(
1069 &annotated_file.file.name, first_line.line_index),
1072 annotated_file.file.name.to_string()
1074 buffer.append(buffer_msg_line_offset + 1,
1076 Style::LineAndColumn);
1077 for _ in 0..max_line_num_len {
1078 buffer.prepend(buffer_msg_line_offset + 1, " ", Style::NoStyle);
1082 if !self.short_message {
1083 // Put in the spacer between the location and annotated source
1084 let buffer_msg_line_offset = buffer.num_lines();
1085 draw_col_separator_no_space(&mut buffer,
1086 buffer_msg_line_offset,
1087 max_line_num_len + 1);
1089 // Contains the vertical lines' positions for active multiline annotations
1090 let mut multilines = FxHashMap::default();
1092 // Next, output the annotate source for this file
1093 for line_idx in 0..annotated_file.lines.len() {
1094 let previous_buffer_line = buffer.num_lines();
1096 let width_offset = 3 + max_line_num_len;
1097 let code_offset = if annotated_file.multiline_depth == 0 {
1100 width_offset + annotated_file.multiline_depth + 1
1103 let depths = self.render_source_line(&mut buffer,
1104 annotated_file.file.clone(),
1105 &annotated_file.lines[line_idx],
1109 let mut to_add = FxHashMap::default();
1111 for (depth, style) in depths {
1112 if multilines.get(&depth).is_some() {
1113 multilines.remove(&depth);
1115 to_add.insert(depth, style);
1119 // Set the multiline annotation vertical lines to the left of
1120 // the code in this line.
1121 for (depth, style) in &multilines {
1122 for line in previous_buffer_line..buffer.num_lines() {
1123 draw_multiline_line(&mut buffer,
1130 // check to see if we need to print out or elide lines that come between
1131 // this annotated line and the next one.
1132 if line_idx < (annotated_file.lines.len() - 1) {
1133 let line_idx_delta = annotated_file.lines[line_idx + 1].line_index -
1134 annotated_file.lines[line_idx].line_index;
1135 if line_idx_delta > 2 {
1136 let last_buffer_line_num = buffer.num_lines();
1137 buffer.puts(last_buffer_line_num, 0, "...", Style::LineNumber);
1139 // Set the multiline annotation vertical lines on `...` bridging line.
1140 for (depth, style) in &multilines {
1141 draw_multiline_line(&mut buffer,
1142 last_buffer_line_num,
1147 } else if line_idx_delta == 2 {
1148 let unannotated_line = annotated_file.file
1149 .get_line(annotated_file.lines[line_idx].line_index)
1150 .unwrap_or_else(|| Cow::from(""));
1152 let last_buffer_line_num = buffer.num_lines();
1154 buffer.puts(last_buffer_line_num,
1156 &self.maybe_anonymized(annotated_file.lines[line_idx + 1]
1159 draw_col_separator(&mut buffer,
1160 last_buffer_line_num,
1161 1 + max_line_num_len);
1162 buffer.puts(last_buffer_line_num,
1167 for (depth, style) in &multilines {
1168 draw_multiline_line(&mut buffer,
1169 last_buffer_line_num,
1177 multilines.extend(&to_add);
1182 // final step: take our styled buffer, render it, then output it
1183 emit_to_destination(&buffer.render(), level, &mut self.dst, self.short_message)?;
1189 fn emit_suggestion_default(&mut self,
1190 suggestion: &CodeSuggestion,
1192 max_line_num_len: usize)
1194 if let Some(ref sm) = self.sm {
1195 let mut buffer = StyledBuffer::new();
1197 // Render the suggestion message
1198 let level_str = level.to_string();
1199 if !level_str.is_empty() {
1200 buffer.append(0, &level_str, Style::Level(level.clone()));
1201 buffer.append(0, ": ", Style::HeaderMsg);
1203 self.msg_to_buffer(&mut buffer,
1204 &[(suggestion.msg.to_owned(), Style::NoStyle)],
1207 Some(Style::HeaderMsg));
1209 // Render the replacements for each suggestion
1210 let suggestions = suggestion.splice_lines(&**sm);
1212 let mut row_num = 2;
1213 for &(ref complete, ref parts) in suggestions.iter().take(MAX_SUGGESTIONS) {
1214 // Only show underline if the suggestion spans a single line and doesn't cover the
1215 // entirety of the code output. If you have multiple replacements in the same line
1216 // of code, show the underline.
1217 let show_underline = !(parts.len() == 1
1218 && parts[0].snippet.trim() == complete.trim())
1219 && complete.lines().count() == 1;
1221 let lines = sm.span_to_lines(parts[0].span).unwrap();
1223 assert!(!lines.lines.is_empty());
1225 let line_start = sm.lookup_char_pos(parts[0].span.lo()).line;
1226 draw_col_separator_no_space(&mut buffer, 1, max_line_num_len + 1);
1227 let mut line_pos = 0;
1228 let mut lines = complete.lines();
1229 for line in lines.by_ref().take(MAX_HIGHLIGHT_LINES) {
1230 // Print the span column to avoid confusion
1231 buffer.puts(row_num,
1233 &self.maybe_anonymized(line_start + line_pos),
1235 // print the suggestion
1236 draw_col_separator(&mut buffer, row_num, max_line_num_len + 1);
1237 buffer.append(row_num, line, Style::NoStyle);
1242 // This offset and the ones below need to be signed to account for replacement code
1243 // that is shorter than the original code.
1244 let mut offset: isize = 0;
1245 // Only show an underline in the suggestions if the suggestion is not the
1246 // entirety of the code being shown and the displayed code is not multiline.
1248 draw_col_separator(&mut buffer, row_num, max_line_num_len + 1);
1250 let span_start_pos = sm.lookup_char_pos(part.span.lo()).col_display;
1251 let span_end_pos = sm.lookup_char_pos(part.span.hi()).col_display;
1253 // Do not underline the leading...
1254 let start = part.snippet.len()
1255 .saturating_sub(part.snippet.trim_start().len());
1256 // ...or trailing spaces. Account for substitutions containing unicode
1258 let sub_len = part.snippet.trim().chars().fold(0, |acc, ch| {
1259 acc + unicode_width::UnicodeWidthChar::width(ch).unwrap_or(0)
1262 let underline_start = (span_start_pos + start) as isize + offset;
1263 let underline_end = (span_start_pos + start + sub_len) as isize + offset;
1264 for p in underline_start..underline_end {
1265 buffer.putc(row_num,
1266 max_line_num_len + 3 + p as usize,
1268 Style::UnderlinePrimary);
1270 // underline removals too
1271 if underline_start == underline_end {
1272 for p in underline_start-1..underline_start+1 {
1273 buffer.putc(row_num,
1274 max_line_num_len + 3 + p as usize,
1276 Style::UnderlineSecondary);
1280 // length of the code after substitution
1281 let full_sub_len = part.snippet.chars().fold(0, |acc, ch| {
1282 acc + unicode_width::UnicodeWidthChar::width(ch).unwrap_or(0) as isize
1285 // length of the code to be substituted
1286 let snippet_len = span_end_pos as isize - span_start_pos as isize;
1287 // For multiple substitutions, use the position *after* the previous
1288 // substitutions have happened.
1289 offset += full_sub_len - snippet_len;
1294 // if we elided some lines, add an ellipsis
1295 if lines.next().is_some() {
1296 buffer.puts(row_num, max_line_num_len - 1, "...", Style::LineNumber);
1297 } else if !show_underline {
1298 draw_col_separator_no_space(&mut buffer, row_num, max_line_num_len + 1);
1302 if suggestions.len() > MAX_SUGGESTIONS {
1303 let msg = format!("and {} other candidates", suggestions.len() - MAX_SUGGESTIONS);
1304 buffer.puts(row_num, 0, &msg, Style::NoStyle);
1306 emit_to_destination(&buffer.render(), level, &mut self.dst, self.short_message)?;
1311 fn emit_messages_default(&mut self,
1313 message: &[(String, Style)],
1314 code: &Option<DiagnosticId>,
1316 children: &[SubDiagnostic],
1317 suggestions: &[CodeSuggestion]) {
1318 let max_line_num_len = if self.ui_testing {
1319 ANONYMIZED_LINE_NUM.len()
1321 self.get_max_line_num(span, children).to_string().len()
1324 match self.emit_message_default(span,
1331 if !children.is_empty() {
1332 let mut buffer = StyledBuffer::new();
1333 if !self.short_message {
1334 draw_col_separator_no_space(&mut buffer, 0, max_line_num_len + 1);
1336 match emit_to_destination(&buffer.render(), level, &mut self.dst,
1337 self.short_message) {
1339 Err(e) => panic!("failed to emit error: {}", e)
1342 if !self.short_message {
1343 for child in children {
1344 let span = child.render_span.as_ref().unwrap_or(&child.span);
1345 match self.emit_message_default(&span,
1346 &child.styled_message(),
1351 Err(e) => panic!("failed to emit error: {}", e),
1355 for sugg in suggestions {
1356 match self.emit_suggestion_default(sugg,
1359 Err(e) => panic!("failed to emit error: {}", e),
1365 Err(e) => panic!("failed to emit error: {}", e),
1368 let mut dst = self.dst.writable();
1369 match write!(dst, "\n") {
1370 Err(e) => panic!("failed to emit error: {}", e),
1373 Err(e) => panic!("failed to emit error: {}", e),
1381 fn draw_col_separator(buffer: &mut StyledBuffer, line: usize, col: usize) {
1382 buffer.puts(line, col, "| ", Style::LineNumber);
1385 fn draw_col_separator_no_space(buffer: &mut StyledBuffer, line: usize, col: usize) {
1386 draw_col_separator_no_space_with_style(buffer, line, col, Style::LineNumber);
1389 fn draw_col_separator_no_space_with_style(buffer: &mut StyledBuffer,
1393 buffer.putc(line, col, '|', style);
1396 fn draw_range(buffer: &mut StyledBuffer, symbol: char, line: usize,
1397 col_from: usize, col_to: usize, style: Style) {
1398 for col in col_from..col_to {
1399 buffer.putc(line, col, symbol, style);
1403 fn draw_note_separator(buffer: &mut StyledBuffer, line: usize, col: usize) {
1404 buffer.puts(line, col, "= ", Style::LineNumber);
1407 fn draw_multiline_line(buffer: &mut StyledBuffer,
1413 buffer.putc(line, offset + depth - 1, '|', style);
1416 fn num_overlap(a_start: usize, a_end: usize, b_start: usize, b_end:usize, inclusive: bool) -> bool {
1417 let extra = if inclusive {
1422 (b_start..b_end + extra).contains(&a_start) ||
1423 (a_start..a_end + extra).contains(&b_start)
1425 fn overlaps(a1: &Annotation, a2: &Annotation, padding: usize) -> bool {
1426 num_overlap(a1.start_col, a1.end_col + padding, a2.start_col, a2.end_col, false)
1429 fn emit_to_destination(rendered_buffer: &[Vec<StyledString>],
1431 dst: &mut Destination,
1432 short_message: bool)
1436 let mut dst = dst.writable();
1438 // In order to prevent error message interleaving, where multiple error lines get intermixed
1439 // when multiple compiler processes error simultaneously, we emit errors with additional
1442 // On Unix systems, we write into a buffered terminal rather than directly to a terminal. When
1443 // the .flush() is called we take the buffer created from the buffered writes and write it at
1444 // one shot. Because the Unix systems use ANSI for the colors, which is a text-based styling
1445 // scheme, this buffered approach works and maintains the styling.
1447 // On Windows, styling happens through calls to a terminal API. This prevents us from using the
1448 // same buffering approach. Instead, we use a global Windows mutex, which we acquire long
1449 // enough to output the full error message, then we release.
1450 let _buffer_lock = lock::acquire_global_lock("rustc_errors");
1451 for (pos, line) in rendered_buffer.iter().enumerate() {
1453 dst.apply_style(lvl.clone(), part.style)?;
1454 write!(dst, "{}", part.text)?;
1457 if !short_message && (!lvl.is_failure_note() || pos != rendered_buffer.len() - 1) {
1465 pub enum Destination {
1466 Terminal(StandardStream),
1467 Buffered(BufferWriter),
1468 Raw(Box<dyn Write + Send>),
1471 pub enum WritableDst<'a> {
1472 Terminal(&'a mut StandardStream),
1473 Buffered(&'a mut BufferWriter, Buffer),
1474 Raw(&'a mut Box<dyn Write + Send>),
1478 fn from_stderr(color: ColorConfig) -> Destination {
1479 let choice = color.to_color_choice();
1480 // On Windows we'll be performing global synchronization on the entire
1481 // system for emitting rustc errors, so there's no need to buffer
1484 // On non-Windows we rely on the atomicity of `write` to ensure errors
1485 // don't get all jumbled up.
1487 Terminal(StandardStream::stderr(choice))
1489 Buffered(BufferWriter::stderr(choice))
1493 fn writable<'a>(&'a mut self) -> WritableDst<'a> {
1495 Destination::Terminal(ref mut t) => WritableDst::Terminal(t),
1496 Destination::Buffered(ref mut t) => {
1497 let buf = t.buffer();
1498 WritableDst::Buffered(t, buf)
1500 Destination::Raw(ref mut t) => WritableDst::Raw(t),
1505 impl<'a> WritableDst<'a> {
1506 fn apply_style(&mut self, lvl: Level, style: Style) -> io::Result<()> {
1507 let mut spec = ColorSpec::new();
1509 Style::LineAndColumn => {}
1510 Style::LineNumber => {
1511 spec.set_bold(true);
1512 spec.set_intense(true);
1514 spec.set_fg(Some(Color::Cyan));
1516 spec.set_fg(Some(Color::Blue));
1519 Style::Quotation => {}
1520 Style::OldSchoolNoteText | Style::MainHeaderMsg => {
1521 spec.set_bold(true);
1523 spec.set_intense(true)
1524 .set_fg(Some(Color::White));
1527 Style::UnderlinePrimary | Style::LabelPrimary => {
1529 spec.set_bold(true);
1531 Style::UnderlineSecondary |
1532 Style::LabelSecondary => {
1536 spec.set_fg(Some(Color::Cyan));
1538 spec.set_fg(Some(Color::Blue));
1542 Style::NoStyle => {}
1543 Style::Level(lvl) => {
1545 spec.set_bold(true);
1547 Style::Highlight => {
1548 spec.set_bold(true);
1551 self.set_color(&spec)
1554 fn set_color(&mut self, color: &ColorSpec) -> io::Result<()> {
1556 WritableDst::Terminal(ref mut t) => t.set_color(color),
1557 WritableDst::Buffered(_, ref mut t) => t.set_color(color),
1558 WritableDst::Raw(_) => Ok(())
1562 fn reset(&mut self) -> io::Result<()> {
1564 WritableDst::Terminal(ref mut t) => t.reset(),
1565 WritableDst::Buffered(_, ref mut t) => t.reset(),
1566 WritableDst::Raw(_) => Ok(()),
1571 impl<'a> Write for WritableDst<'a> {
1572 fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
1574 WritableDst::Terminal(ref mut t) => t.write(bytes),
1575 WritableDst::Buffered(_, ref mut buf) => buf.write(bytes),
1576 WritableDst::Raw(ref mut w) => w.write(bytes),
1580 fn flush(&mut self) -> io::Result<()> {
1582 WritableDst::Terminal(ref mut t) => t.flush(),
1583 WritableDst::Buffered(_, ref mut buf) => buf.flush(),
1584 WritableDst::Raw(ref mut w) => w.flush(),
1589 impl<'a> Drop for WritableDst<'a> {
1590 fn drop(&mut self) {
1592 WritableDst::Buffered(ref mut dst, ref mut buf) => {
1593 drop(dst.print(buf));