1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use self::Destination::*;
13 use syntax_pos::{FileMap, Span, MultiSpan};
15 use {Level, CodeSuggestion, DiagnosticBuilder, SubDiagnostic, CodeMapperDyn, DiagnosticId};
16 use snippet::{Annotation, AnnotationType, Line, MultilineAnnotation, StyledString, Style};
17 use styled_buffer::StyledBuffer;
19 use rustc_data_structures::sync::Lrc;
22 use std::io::prelude::*;
24 use std::collections::HashMap;
25 use std::cmp::{min, Reverse};
26 use termcolor::{StandardStream, ColorChoice, ColorSpec, BufferWriter};
27 use termcolor::{WriteColor, Color, Buffer};
30 const ANONYMIZED_LINE_NUM: &str = "LL";
32 /// Emitter trait for emitting errors.
34 /// Emit a structured diagnostic.
35 fn emit(&mut self, db: &DiagnosticBuilder);
37 /// Check if should show explanations about "rustc --explain"
38 fn should_show_explain(&self) -> bool {
43 impl Emitter for EmitterWriter {
44 fn emit(&mut self, db: &DiagnosticBuilder) {
45 let mut primary_span = db.span.clone();
46 let mut children = db.children.clone();
47 let mut suggestions: &[_] = &[];
49 if let Some((sugg, rest)) = db.suggestions.split_first() {
51 // don't display multi-suggestions as labels
52 sugg.substitutions.len() == 1 &&
53 // don't display multipart suggestions as labels
54 sugg.substitutions[0].parts.len() == 1 &&
55 // don't display long messages as labels
56 sugg.msg.split_whitespace().count() < 10 &&
57 // don't display multiline suggestions as labels
58 !sugg.substitutions[0].parts[0].snippet.contains('\n') {
59 let substitution = &sugg.substitutions[0].parts[0].snippet.trim();
60 let msg = if substitution.len() == 0 || !sugg.show_code_when_inline {
61 // This substitution is only removal or we explicitly don't want to show the
62 // code inline, don't show it
63 format!("help: {}", sugg.msg)
65 format!("help: {}: `{}`", sugg.msg, substitution)
67 primary_span.push_span_label(sugg.substitutions[0].parts[0].span, msg);
69 // if there are multiple suggestions, print them all in full
70 // to be consistent. We could try to figure out if we can
71 // make one (or the first one) inline, but that would give
72 // undue importance to a semi-random suggestion
73 suggestions = &db.suggestions;
77 self.fix_multispans_in_std_macros(&mut primary_span,
79 db.handler.flags.external_macro_backtrace);
81 self.emit_messages_default(&db.level,
89 fn should_show_explain(&self) -> bool {
94 /// maximum number of lines we will print for each error; arbitrary.
95 pub const MAX_HIGHLIGHT_LINES: usize = 6;
96 /// maximum number of suggestions to be shown
98 /// Arbitrary, but taken from trait import suggestion limit
99 pub const MAX_SUGGESTIONS: usize = 4;
101 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
102 pub enum ColorConfig {
109 fn to_color_choice(&self) -> ColorChoice {
111 ColorConfig::Always => ColorChoice::Always,
112 ColorConfig::Never => ColorChoice::Never,
113 ColorConfig::Auto if atty::is(atty::Stream::Stderr) => {
116 ColorConfig::Auto => ColorChoice::Never,
121 pub struct EmitterWriter {
123 cm: Option<Lrc<CodeMapperDyn>>,
129 struct FileWithAnnotatedLines {
132 multiline_depth: usize,
136 pub fn stderr(color_config: ColorConfig,
137 code_map: Option<Lrc<CodeMapperDyn>>,
141 let dst = Destination::from_stderr(color_config);
151 pub fn new(dst: Box<dyn Write + Send>,
152 code_map: Option<Lrc<CodeMapperDyn>>,
165 pub fn ui_testing(mut self, ui_testing: bool) -> Self {
166 self.ui_testing = ui_testing;
170 fn maybe_anonymized(&self, line_num: usize) -> String {
172 ANONYMIZED_LINE_NUM.to_string()
178 fn preprocess_annotations(&mut self, msp: &MultiSpan) -> Vec<FileWithAnnotatedLines> {
179 fn add_annotation_to_file(file_vec: &mut Vec<FileWithAnnotatedLines>,
184 for slot in file_vec.iter_mut() {
185 // Look through each of our files for the one we're adding to
186 if slot.file.name == file.name {
187 // See if we already have a line for it
188 for line_slot in &mut slot.lines {
189 if line_slot.line_index == line_index {
190 line_slot.annotations.push(ann);
194 // We don't have a line yet, create one
195 slot.lines.push(Line {
197 annotations: vec![ann],
203 // This is the first time we're seeing the file
204 file_vec.push(FileWithAnnotatedLines {
208 annotations: vec![ann],
214 let mut output = vec![];
215 let mut multiline_annotations = vec![];
217 if let Some(ref cm) = self.cm {
218 for span_label in msp.span_labels() {
219 if span_label.span.is_dummy() {
223 let lo = cm.lookup_char_pos(span_label.span.lo());
224 let mut hi = cm.lookup_char_pos(span_label.span.hi());
226 // Watch out for "empty spans". If we get a span like 6..6, we
227 // want to just display a `^` at 6, so convert that to
228 // 6..7. This is degenerate input, but it's best to degrade
229 // gracefully -- and the parser likes to supply a span like
230 // that for EOF, in particular.
231 if lo.col_display == hi.col_display && lo.line == hi.line {
235 let ann_type = if lo.line != hi.line {
236 let ml = MultilineAnnotation {
240 start_col: lo.col_display,
241 end_col: hi.col_display,
242 is_primary: span_label.is_primary,
243 label: span_label.label.clone(),
245 multiline_annotations.push((lo.file.clone(), ml.clone()));
246 AnnotationType::Multiline(ml)
248 AnnotationType::Singleline
250 let ann = Annotation {
251 start_col: lo.col_display,
252 end_col: hi.col_display,
253 is_primary: span_label.is_primary,
254 label: span_label.label.clone(),
255 annotation_type: ann_type,
258 if !ann.is_multiline() {
259 add_annotation_to_file(&mut output,
267 // Find overlapping multiline annotations, put them at different depths
268 multiline_annotations.sort_by_key(|&(_, ref ml)| (ml.line_start, ml.line_end));
269 for item in multiline_annotations.clone() {
271 for item in multiline_annotations.iter_mut() {
272 let ref mut a = item.1;
273 // Move all other multiline annotations overlapping with this one
274 // one level to the right.
276 num_overlap(ann.line_start, ann.line_end, a.line_start, a.line_end, true)
285 let mut max_depth = 0; // max overlapping multiline spans
286 for (file, ann) in multiline_annotations {
287 if ann.depth > max_depth {
288 max_depth = ann.depth;
290 add_annotation_to_file(&mut output, file.clone(), ann.line_start, ann.as_start());
291 let middle = min(ann.line_start + 4, ann.line_end);
292 for line in ann.line_start + 1..middle {
293 add_annotation_to_file(&mut output, file.clone(), line, ann.as_line());
295 if middle < ann.line_end - 1 {
296 for line in ann.line_end - 1..ann.line_end {
297 add_annotation_to_file(&mut output, file.clone(), line, ann.as_line());
300 add_annotation_to_file(&mut output, file, ann.line_end, ann.as_end());
302 for file_vec in output.iter_mut() {
303 file_vec.multiline_depth = max_depth;
308 fn render_source_line(&self,
309 buffer: &mut StyledBuffer,
313 code_offset: usize) -> Vec<(usize, Style)> {
314 if line.line_index == 0 {
318 let source_string = match file.get_line(line.line_index - 1) {
320 None => return Vec::new(),
323 let line_offset = buffer.num_lines();
325 // First create the source line we will highlight.
326 buffer.puts(line_offset, code_offset, &source_string, Style::Quotation);
327 buffer.puts(line_offset,
329 &self.maybe_anonymized(line.line_index),
332 draw_col_separator(buffer, line_offset, width_offset - 2);
334 // Special case when there's only one annotation involved, it is the start of a multiline
335 // span and there's no text at the beginning of the code line. Instead of doing the whole
344 // we simplify the output to:
350 if line.annotations.len() == 1 {
351 if let Some(ref ann) = line.annotations.get(0) {
352 if let AnnotationType::MultilineStart(depth) = ann.annotation_type {
353 if source_string.chars()
355 .all(|c| c.is_whitespace()) {
356 let style = if ann.is_primary {
357 Style::UnderlinePrimary
359 Style::UnderlineSecondary
361 buffer.putc(line_offset,
362 width_offset + depth - 1,
365 return vec![(depth, style)];
371 // We want to display like this:
373 // vec.push(vec.pop().unwrap());
374 // --- ^^^ - previous borrow ends here
376 // | error occurs here
377 // previous borrow of `vec` occurs here
379 // But there are some weird edge cases to be aware of:
381 // vec.push(vec.pop().unwrap());
382 // -------- - previous borrow ends here
384 // |this makes no sense
385 // previous borrow of `vec` occurs here
387 // For this reason, we group the lines into "highlight lines"
388 // and "annotations lines", where the highlight lines have the `^`.
390 // Sort the annotations by (start, end col)
391 // The labels are reversed, sort and then reversed again.
392 // Consider a list of annotations (A1, A2, C1, C2, B1, B2) where
393 // the letter signifies the span. Here we are only sorting by the
394 // span and hence, the order of the elements with the same span will
395 // not change. On reversing the ordering (|a, b| but b.cmp(a)), you get
396 // (C1, C2, B1, B2, A1, A2). All the elements with the same span are
397 // still ordered first to last, but all the elements with different
398 // spans are ordered by their spans in last to first order. Last to
399 // first order is important, because the jiggly lines and | are on
400 // the left, so the rightmost span needs to be rendered first,
401 // otherwise the lines would end up needing to go over a message.
403 let mut annotations = line.annotations.clone();
404 annotations.sort_by_key(|a| Reverse(a.start_col));
406 // First, figure out where each label will be positioned.
408 // In the case where you have the following annotations:
410 // vec.push(vec.pop().unwrap());
411 // -------- - previous borrow ends here [C]
413 // |this makes no sense [B]
414 // previous borrow of `vec` occurs here [A]
416 // `annotations_position` will hold [(2, A), (1, B), (0, C)].
418 // We try, when possible, to stick the rightmost annotation at the end
419 // of the highlight line:
421 // vec.push(vec.pop().unwrap());
422 // --- --- - previous borrow ends here
424 // But sometimes that's not possible because one of the other
425 // annotations overlaps it. For example, from the test
426 // `span_overlap_label`, we have the following annotations
427 // (written on distinct lines for clarity):
433 // In this case, we can't stick the rightmost-most label on
434 // the highlight line, or we would get:
441 // which is totally weird. Instead we want:
449 // which is...less weird, at least. In fact, in general, if
450 // the rightmost span overlaps with any other span, we should
451 // use the "hang below" version, so we can at least make it
452 // clear where the span *starts*. There's an exception for this
453 // logic, when the labels do not have a message:
468 let mut annotations_position = vec![];
469 let mut line_len = 0;
471 for (i, annotation) in annotations.iter().enumerate() {
472 for (j, next) in annotations.iter().enumerate() {
473 if overlaps(next, annotation, 0) // This label overlaps with another one and both
474 && annotation.has_label() // take space (they have text and are not
475 && j > i // multiline lines).
476 && p == 0 // We're currently on the first line, move the label one line down
478 // This annotation needs a new line in the output.
483 annotations_position.push((p, annotation));
484 for (j, next) in annotations.iter().enumerate() {
486 let l = if let Some(ref label) = next.label {
491 if (overlaps(next, annotation, l) // Do not allow two labels to be in the same
492 // line if they overlap including padding, to
493 // avoid situations like:
500 && annotation.has_label() // Both labels must have some text, otherwise
501 && next.has_label()) // they are not overlapping.
502 // Do not add a new line if this annotation
503 // or the next are vertical line placeholders.
504 || (annotation.takes_space() // If either this or the next annotation is
505 && next.has_label()) // multiline start/end, move it to a new line
506 || (annotation.has_label() // so as not to overlap the orizontal lines.
507 && next.takes_space())
508 || (annotation.takes_space() && next.takes_space())
509 || (overlaps(next, annotation, l)
510 && next.end_col <= annotation.end_col
512 && p == 0) // Avoid #42595.
514 // This annotation needs a new line in the output.
529 // If there are no annotations or the only annotations on this line are
530 // MultilineLine, then there's only code being shown, stop processing.
531 if line.annotations.is_empty() || line.annotations.iter()
532 .filter(|a| !a.is_line()).collect::<Vec<_>>().len() == 0
537 // Write the colunmn separator.
539 // After this we will have:
548 for pos in 0..line_len + 1 {
549 draw_col_separator(buffer, line_offset + pos + 1, width_offset - 2);
550 buffer.putc(line_offset + pos + 1,
556 // Write the horizontal lines for multiline annotations
557 // (only the first and last lines need this).
559 // After this we will have:
568 for &(pos, annotation) in &annotations_position {
569 let style = if annotation.is_primary {
570 Style::UnderlinePrimary
572 Style::UnderlineSecondary
575 match annotation.annotation_type {
576 AnnotationType::MultilineStart(depth) |
577 AnnotationType::MultilineEnd(depth) => {
581 width_offset + depth,
582 code_offset + annotation.start_col,
586 buffer.set_style_range(line_offset,
587 code_offset + annotation.start_col,
588 code_offset + annotation.end_col,
590 annotation.is_primary);
596 // Write the vertical lines for labels that are on a different line as the underline.
598 // After this we will have:
607 for &(pos, annotation) in &annotations_position {
608 let style = if annotation.is_primary {
609 Style::UnderlinePrimary
611 Style::UnderlineSecondary
615 if pos > 1 && (annotation.has_label() || annotation.takes_space()) {
616 for p in line_offset + 1..line_offset + pos + 1 {
618 code_offset + annotation.start_col,
623 match annotation.annotation_type {
624 AnnotationType::MultilineStart(depth) => {
625 for p in line_offset + pos + 1..line_offset + line_len + 2 {
627 width_offset + depth - 1,
632 AnnotationType::MultilineEnd(depth) => {
633 for p in line_offset..line_offset + pos + 1 {
635 width_offset + depth - 1,
644 // Write the labels on the annotations that actually have a label.
646 // After this we will have:
651 // | something about `foo`
655 for &(pos, annotation) in &annotations_position {
656 let style = if annotation.is_primary {
659 Style::LabelSecondary
661 let (pos, col) = if pos == 0 {
662 (pos + 1, annotation.end_col + 1)
664 (pos + 2, annotation.start_col)
666 if let Some(ref label) = annotation.label {
667 buffer.puts(line_offset + pos,
674 // Sort from biggest span to smallest span so that smaller spans are
675 // represented in the output:
680 // | | something about `foo`
681 // | something about `fn foo()`
682 annotations_position.sort_by(|a, b| {
684 a.1.len().cmp(&b.1.len()).reverse()
687 // Write the underlines.
689 // After this we will have:
694 // | something about `foo`
698 for &(_, annotation) in &annotations_position {
699 let (underline, style) = if annotation.is_primary {
700 ('^', Style::UnderlinePrimary)
702 ('-', Style::UnderlineSecondary)
704 for p in annotation.start_col..annotation.end_col {
705 buffer.putc(line_offset + 1,
711 annotations_position.iter().filter_map(|&(_, annotation)| {
712 match annotation.annotation_type {
713 AnnotationType::MultilineStart(p) | AnnotationType::MultilineEnd(p) => {
714 let style = if annotation.is_primary {
717 Style::LabelSecondary
724 }).collect::<Vec<_>>()
727 fn get_multispan_max_line_num(&mut self, msp: &MultiSpan) -> usize {
729 if let Some(ref cm) = self.cm {
730 for primary_span in msp.primary_spans() {
731 if !primary_span.is_dummy() {
732 let hi = cm.lookup_char_pos(primary_span.hi());
738 if !self.short_message {
739 for span_label in msp.span_labels() {
740 if !span_label.span.is_dummy() {
741 let hi = cm.lookup_char_pos(span_label.span.hi());
752 fn get_max_line_num(&mut self, span: &MultiSpan, children: &Vec<SubDiagnostic>) -> usize {
755 let primary = self.get_multispan_max_line_num(span);
756 max = if primary > max { primary } else { max };
758 for sub in children {
759 let sub_result = self.get_multispan_max_line_num(&sub.span);
760 max = if sub_result > max { primary } else { max };
765 // This "fixes" MultiSpans that contain Spans that are pointing to locations inside of
766 // <*macros>. Since these locations are often difficult to read, we move these Spans from
767 // <*macros> to their corresponding use site.
768 fn fix_multispan_in_std_macros(&mut self,
769 span: &mut MultiSpan,
770 always_backtrace: bool) -> bool {
771 let mut spans_updated = false;
773 if let Some(ref cm) = self.cm {
774 let mut before_after: Vec<(Span, Span)> = vec![];
775 let mut new_labels: Vec<(Span, String)> = vec![];
777 // First, find all the spans in <*macros> and point instead at their use site
778 for sp in span.primary_spans() {
782 let call_sp = cm.call_span_if_macro(*sp);
783 if call_sp != *sp && !always_backtrace {
784 before_after.push((*sp, call_sp));
786 let backtrace_len = sp.macro_backtrace().len();
787 for (i, trace) in sp.macro_backtrace().iter().rev().enumerate() {
788 // Only show macro locations that are local
789 // and display them like a span_note
790 if let Some(def_site) = trace.def_site_span {
791 if def_site.is_dummy() {
794 if always_backtrace {
795 new_labels.push((def_site,
796 format!("in this expansion of `{}`{}",
797 trace.macro_decl_name,
798 if backtrace_len > 2 {
799 // if backtrace_len == 1 it'll be pointed
800 // at by "in this macro invocation"
801 format!(" (#{})", i + 1)
806 // Check to make sure we're not in any <*macros>
807 if !cm.span_to_filename(def_site).is_macros() &&
808 !trace.macro_decl_name.starts_with("desugaring of ") &&
809 !trace.macro_decl_name.starts_with("#[") ||
811 new_labels.push((trace.call_site,
812 format!("in this macro invocation{}",
813 if backtrace_len > 2 && always_backtrace {
814 // only specify order when the macro
815 // backtrace is multiple levels deep
816 format!(" (#{})", i + 1)
820 if !always_backtrace {
827 for (label_span, label_text) in new_labels {
828 span.push_span_label(label_span, label_text);
830 for sp_label in span.span_labels() {
831 if sp_label.span.is_dummy() {
834 if cm.span_to_filename(sp_label.span.clone()).is_macros() &&
837 let v = sp_label.span.macro_backtrace();
838 if let Some(use_site) = v.last() {
839 before_after.push((sp_label.span.clone(), use_site.call_site.clone()));
843 // After we have them, make sure we replace these 'bad' def sites with their use sites
844 for (before, after) in before_after {
845 span.replace(before, after);
846 spans_updated = true;
853 // This does a small "fix" for multispans by looking to see if it can find any that
854 // point directly at <*macros>. Since these are often difficult to read, this
855 // will change the span to point at the use site.
856 fn fix_multispans_in_std_macros(&mut self,
857 span: &mut MultiSpan,
858 children: &mut Vec<SubDiagnostic>,
860 let mut spans_updated = self.fix_multispan_in_std_macros(span, backtrace);
861 for child in children.iter_mut() {
862 spans_updated |= self.fix_multispan_in_std_macros(&mut child.span, backtrace);
865 children.push(SubDiagnostic {
868 ("this error originates in a macro outside of the current crate \
869 (in Nightly builds, run with -Z external-macro-backtrace \
870 for more info)".to_string(),
873 span: MultiSpan::new(),
879 /// Add a left margin to every line but the first, given a padding length and the label being
880 /// displayed, keeping the provided highlighting.
881 fn msg_to_buffer(&self,
882 buffer: &mut StyledBuffer,
883 msg: &[(String, Style)],
886 override_style: Option<Style>) {
888 // The extra 5 ` ` is padding that's always needed to align to the `note: `:
901 // | | length of label
903 // `max_line_num_len`
904 let padding = (0..padding + label.len() + 5)
906 .collect::<String>();
908 /// Return whether `style`, or the override if present and the style is `NoStyle`.
909 fn style_or_override(style: Style, override_style: Option<Style>) -> Style {
910 if let Some(o) = override_style {
911 if style == Style::NoStyle {
918 let mut line_number = 0;
920 // Provided the following diagnostic message:
924 // ("highlighted multiline\nstring to\nsee how it ", Style::NoStyle),
925 // ("looks", Style::Highlight),
926 // ("with\nvery ", Style::NoStyle),
927 // ("weird", Style::Highlight),
928 // (" formats\n", Style::NoStyle),
929 // ("see?", Style::Highlight),
932 // the expected output on a note is (* surround the highlighted text)
934 // = note: highlighted multiline
936 // see how it *looks* with
937 // very *weird* formats
939 for &(ref text, ref style) in msg.iter() {
940 let lines = text.split('\n').collect::<Vec<_>>();
942 for (i, line) in lines.iter().enumerate() {
945 buffer.append(line_number, &padding, Style::NoStyle);
947 buffer.append(line_number, line, style_or_override(*style, override_style));
950 buffer.append(line_number, text, style_or_override(*style, override_style));
955 fn emit_message_default(&mut self,
957 msg: &Vec<(String, Style)>,
958 code: &Option<DiagnosticId>,
960 max_line_num_len: usize,
963 let mut buffer = StyledBuffer::new();
964 let header_style = if is_secondary {
970 if msp.primary_spans().is_empty() && msp.span_labels().is_empty() && is_secondary
971 && !self.short_message {
972 // This is a secondary message with no span info
973 for _ in 0..max_line_num_len {
974 buffer.prepend(0, " ", Style::NoStyle);
976 draw_note_separator(&mut buffer, 0, max_line_num_len + 1);
977 let level_str = level.to_string();
978 if !level_str.is_empty() {
979 buffer.append(0, &level_str, Style::MainHeaderMsg);
980 buffer.append(0, ": ", Style::NoStyle);
982 self.msg_to_buffer(&mut buffer, msg, max_line_num_len, "note", None);
984 let level_str = level.to_string();
985 if !level_str.is_empty() {
986 buffer.append(0, &level_str, Style::Level(level.clone()));
988 // only render error codes, not lint codes
989 if let Some(DiagnosticId::Error(ref code)) = *code {
990 buffer.append(0, "[", Style::Level(level.clone()));
991 buffer.append(0, &code, Style::Level(level.clone()));
992 buffer.append(0, "]", Style::Level(level.clone()));
994 if !level_str.is_empty() {
995 buffer.append(0, ": ", header_style);
997 for &(ref text, _) in msg.iter() {
998 buffer.append(0, text, header_style);
1002 // Preprocess all the annotations so that they are grouped by file and by line number
1003 // This helps us quickly iterate over the whole message (including secondary file spans)
1004 let mut annotated_files = self.preprocess_annotations(msp);
1006 // Make sure our primary file comes first
1007 let (primary_lo, cm) = if let (Some(cm), Some(ref primary_span)) =
1008 (self.cm.as_ref(), msp.primary_span().as_ref()) {
1009 if !primary_span.is_dummy() {
1010 (cm.lookup_char_pos(primary_span.lo()), cm)
1012 emit_to_destination(&buffer.render(), level, &mut self.dst, self.short_message)?;
1016 // If we don't have span information, emit and exit
1017 emit_to_destination(&buffer.render(), level, &mut self.dst, self.short_message)?;
1021 annotated_files.binary_search_by(|x| x.file.name.cmp(&primary_lo.file.name)) {
1022 annotated_files.swap(0, pos);
1025 // Print out the annotate source lines that correspond with the error
1026 for annotated_file in annotated_files {
1027 // we can't annotate anything if the source is unavailable.
1028 if !cm.ensure_filemap_source_present(annotated_file.file.clone()) {
1032 // print out the span location and spacer before we print the annotated source
1033 // to do this, we need to know if this span will be primary
1034 let is_primary = primary_lo.file.name == annotated_file.file.name;
1036 let loc = primary_lo.clone();
1037 if !self.short_message {
1038 // remember where we are in the output buffer for easy reference
1039 let buffer_msg_line_offset = buffer.num_lines();
1041 buffer.prepend(buffer_msg_line_offset, "--> ", Style::LineNumber);
1042 buffer.append(buffer_msg_line_offset,
1043 &format!("{}:{}:{}",
1045 cm.doctest_offset_line(loc.line),
1047 Style::LineAndColumn);
1048 for _ in 0..max_line_num_len {
1049 buffer.prepend(buffer_msg_line_offset, " ", Style::NoStyle);
1053 &format!("{}:{}:{}: ",
1055 cm.doctest_offset_line(loc.line),
1057 Style::LineAndColumn);
1059 } else if !self.short_message {
1060 // remember where we are in the output buffer for easy reference
1061 let buffer_msg_line_offset = buffer.num_lines();
1064 draw_col_separator(&mut buffer, buffer_msg_line_offset, max_line_num_len + 1);
1066 // Then, the secondary file indicator
1067 buffer.prepend(buffer_msg_line_offset + 1, "::: ", Style::LineNumber);
1068 let loc = if let Some(first_line) = annotated_file.lines.first() {
1069 let col = if let Some(first_annotation) = first_line.annotations.first() {
1070 format!(":{}", first_annotation.start_col + 1)
1075 annotated_file.file.name,
1076 cm.doctest_offset_line(first_line.line_index),
1079 annotated_file.file.name.to_string()
1081 buffer.append(buffer_msg_line_offset + 1,
1083 Style::LineAndColumn);
1084 for _ in 0..max_line_num_len {
1085 buffer.prepend(buffer_msg_line_offset + 1, " ", Style::NoStyle);
1089 if !self.short_message {
1090 // Put in the spacer between the location and annotated source
1091 let buffer_msg_line_offset = buffer.num_lines();
1092 draw_col_separator_no_space(&mut buffer,
1093 buffer_msg_line_offset,
1094 max_line_num_len + 1);
1096 // Contains the vertical lines' positions for active multiline annotations
1097 let mut multilines = HashMap::new();
1099 // Next, output the annotate source for this file
1100 for line_idx in 0..annotated_file.lines.len() {
1101 let previous_buffer_line = buffer.num_lines();
1103 let width_offset = 3 + max_line_num_len;
1104 let code_offset = if annotated_file.multiline_depth == 0 {
1107 width_offset + annotated_file.multiline_depth + 1
1110 let depths = self.render_source_line(&mut buffer,
1111 annotated_file.file.clone(),
1112 &annotated_file.lines[line_idx],
1116 let mut to_add = HashMap::new();
1118 for (depth, style) in depths {
1119 if multilines.get(&depth).is_some() {
1120 multilines.remove(&depth);
1122 to_add.insert(depth, style);
1126 // Set the multiline annotation vertical lines to the left of
1127 // the code in this line.
1128 for (depth, style) in &multilines {
1129 for line in previous_buffer_line..buffer.num_lines() {
1130 draw_multiline_line(&mut buffer,
1137 // check to see if we need to print out or elide lines that come between
1138 // this annotated line and the next one.
1139 if line_idx < (annotated_file.lines.len() - 1) {
1140 let line_idx_delta = annotated_file.lines[line_idx + 1].line_index -
1141 annotated_file.lines[line_idx].line_index;
1142 if line_idx_delta > 2 {
1143 let last_buffer_line_num = buffer.num_lines();
1144 buffer.puts(last_buffer_line_num, 0, "...", Style::LineNumber);
1146 // Set the multiline annotation vertical lines on `...` bridging line.
1147 for (depth, style) in &multilines {
1148 draw_multiline_line(&mut buffer,
1149 last_buffer_line_num,
1154 } else if line_idx_delta == 2 {
1155 let unannotated_line = annotated_file.file
1156 .get_line(annotated_file.lines[line_idx].line_index)
1157 .unwrap_or_else(|| Cow::from(""));
1159 let last_buffer_line_num = buffer.num_lines();
1161 buffer.puts(last_buffer_line_num,
1163 &self.maybe_anonymized(annotated_file.lines[line_idx + 1]
1166 draw_col_separator(&mut buffer,
1167 last_buffer_line_num,
1168 1 + max_line_num_len);
1169 buffer.puts(last_buffer_line_num,
1174 for (depth, style) in &multilines {
1175 draw_multiline_line(&mut buffer,
1176 last_buffer_line_num,
1184 multilines.extend(&to_add);
1189 // final step: take our styled buffer, render it, then output it
1190 emit_to_destination(&buffer.render(), level, &mut self.dst, self.short_message)?;
1196 fn emit_suggestion_default(&mut self,
1197 suggestion: &CodeSuggestion,
1199 max_line_num_len: usize)
1201 if let Some(ref cm) = self.cm {
1202 let mut buffer = StyledBuffer::new();
1204 // Render the suggestion message
1205 let level_str = level.to_string();
1206 if !level_str.is_empty() {
1207 buffer.append(0, &level_str, Style::Level(level.clone()));
1208 buffer.append(0, ": ", Style::HeaderMsg);
1210 self.msg_to_buffer(&mut buffer,
1211 &[(suggestion.msg.to_owned(), Style::NoStyle)],
1214 Some(Style::HeaderMsg));
1216 // Render the replacements for each suggestion
1217 let suggestions = suggestion.splice_lines(&**cm);
1219 let mut row_num = 2;
1220 for &(ref complete, ref parts) in suggestions.iter().take(MAX_SUGGESTIONS) {
1221 // Only show underline if the suggestion spans a single line and doesn't cover the
1222 // entirety of the code output. If you have multiple replacements in the same line
1223 // of code, show the underline.
1224 let show_underline = !(parts.len() == 1
1225 && parts[0].snippet.trim() == complete.trim())
1226 && complete.lines().count() == 1;
1228 let lines = cm.span_to_lines(parts[0].span).unwrap();
1230 assert!(!lines.lines.is_empty());
1232 let line_start = cm.lookup_char_pos(parts[0].span.lo()).line;
1233 draw_col_separator_no_space(&mut buffer, 1, max_line_num_len + 1);
1234 let mut line_pos = 0;
1235 let mut lines = complete.lines();
1236 for line in lines.by_ref().take(MAX_HIGHLIGHT_LINES) {
1237 // Print the span column to avoid confusion
1238 buffer.puts(row_num,
1240 &self.maybe_anonymized(line_start + line_pos),
1242 // print the suggestion
1243 draw_col_separator(&mut buffer, row_num, max_line_num_len + 1);
1244 buffer.append(row_num, line, Style::NoStyle);
1249 // This offset and the ones below need to be signed to account for replacement code
1250 // that is shorter than the original code.
1251 let mut offset: isize = 0;
1252 // Only show an underline in the suggestions if the suggestion is not the
1253 // entirety of the code being shown and the displayed code is not multiline.
1255 draw_col_separator(&mut buffer, row_num, max_line_num_len + 1);
1257 let span_start_pos = cm.lookup_char_pos(part.span.lo()).col_display;
1258 let span_end_pos = cm.lookup_char_pos(part.span.hi()).col_display;
1260 // Do not underline the leading...
1261 let start = part.snippet.len()
1262 .saturating_sub(part.snippet.trim_left().len());
1263 // ...or trailing spaces. Account for substitutions containing unicode
1265 let sub_len = part.snippet.trim().chars().fold(0, |acc, ch| {
1266 acc + unicode_width::UnicodeWidthChar::width(ch).unwrap_or(0)
1269 let underline_start = (span_start_pos + start) as isize + offset;
1270 let underline_end = (span_start_pos + start + sub_len) as isize + offset;
1271 for p in underline_start..underline_end {
1272 buffer.putc(row_num,
1273 max_line_num_len + 3 + p as usize,
1275 Style::UnderlinePrimary);
1277 // underline removals too
1278 if underline_start == underline_end {
1279 for p in underline_start-1..underline_start+1 {
1280 buffer.putc(row_num,
1281 max_line_num_len + 3 + p as usize,
1283 Style::UnderlineSecondary);
1287 // length of the code after substitution
1288 let full_sub_len = part.snippet.chars().fold(0, |acc, ch| {
1289 acc + unicode_width::UnicodeWidthChar::width(ch).unwrap_or(0) as isize
1292 // length of the code to be substituted
1293 let snippet_len = span_end_pos as isize - span_start_pos as isize;
1294 // For multiple substitutions, use the position *after* the previous
1295 // substitutions have happened.
1296 offset += full_sub_len - snippet_len;
1301 // if we elided some lines, add an ellipsis
1302 if let Some(_) = lines.next() {
1303 buffer.puts(row_num, max_line_num_len - 1, "...", Style::LineNumber);
1304 } else if !show_underline {
1305 draw_col_separator_no_space(&mut buffer, row_num, max_line_num_len + 1);
1309 if suggestions.len() > MAX_SUGGESTIONS {
1310 let msg = format!("and {} other candidates", suggestions.len() - MAX_SUGGESTIONS);
1311 buffer.puts(row_num, 0, &msg, Style::NoStyle);
1313 emit_to_destination(&buffer.render(), level, &mut self.dst, self.short_message)?;
1318 fn emit_messages_default(&mut self,
1320 message: &Vec<(String, Style)>,
1321 code: &Option<DiagnosticId>,
1323 children: &Vec<SubDiagnostic>,
1324 suggestions: &[CodeSuggestion]) {
1325 let max_line_num_len = if self.ui_testing {
1326 ANONYMIZED_LINE_NUM.len()
1328 self.get_max_line_num(span, children).to_string().len()
1331 match self.emit_message_default(span,
1338 if !children.is_empty() {
1339 let mut buffer = StyledBuffer::new();
1340 if !self.short_message {
1341 draw_col_separator_no_space(&mut buffer, 0, max_line_num_len + 1);
1343 match emit_to_destination(&buffer.render(), level, &mut self.dst,
1344 self.short_message) {
1346 Err(e) => panic!("failed to emit error: {}", e)
1349 if !self.short_message {
1350 for child in children {
1351 let span = child.render_span.as_ref().unwrap_or(&child.span);
1352 match self.emit_message_default(&span,
1353 &child.styled_message(),
1358 Err(e) => panic!("failed to emit error: {}", e),
1362 for sugg in suggestions {
1363 match self.emit_suggestion_default(sugg,
1366 Err(e) => panic!("failed to emit error: {}", e),
1372 Err(e) => panic!("failed to emit error: {}", e),
1375 let mut dst = self.dst.writable();
1376 match write!(dst, "\n") {
1377 Err(e) => panic!("failed to emit error: {}", e),
1380 Err(e) => panic!("failed to emit error: {}", e),
1388 fn draw_col_separator(buffer: &mut StyledBuffer, line: usize, col: usize) {
1389 buffer.puts(line, col, "| ", Style::LineNumber);
1392 fn draw_col_separator_no_space(buffer: &mut StyledBuffer, line: usize, col: usize) {
1393 draw_col_separator_no_space_with_style(buffer, line, col, Style::LineNumber);
1396 fn draw_col_separator_no_space_with_style(buffer: &mut StyledBuffer,
1400 buffer.putc(line, col, '|', style);
1403 fn draw_range(buffer: &mut StyledBuffer, symbol: char, line: usize,
1404 col_from: usize, col_to: usize, style: Style) {
1405 for col in col_from..col_to {
1406 buffer.putc(line, col, symbol, style);
1410 fn draw_note_separator(buffer: &mut StyledBuffer, line: usize, col: usize) {
1411 buffer.puts(line, col, "= ", Style::LineNumber);
1414 fn draw_multiline_line(buffer: &mut StyledBuffer,
1420 buffer.putc(line, offset + depth - 1, '|', style);
1423 fn num_overlap(a_start: usize, a_end: usize, b_start: usize, b_end:usize, inclusive: bool) -> bool {
1424 let extra = if inclusive {
1429 (b_start..b_end + extra).contains(&a_start) ||
1430 (a_start..a_end + extra).contains(&b_start)
1432 fn overlaps(a1: &Annotation, a2: &Annotation, padding: usize) -> bool {
1433 num_overlap(a1.start_col, a1.end_col + padding, a2.start_col, a2.end_col, false)
1436 fn emit_to_destination(rendered_buffer: &Vec<Vec<StyledString>>,
1438 dst: &mut Destination,
1439 short_message: bool)
1443 let mut dst = dst.writable();
1445 // In order to prevent error message interleaving, where multiple error lines get intermixed
1446 // when multiple compiler processes error simultaneously, we emit errors with additional
1449 // On Unix systems, we write into a buffered terminal rather than directly to a terminal. When
1450 // the .flush() is called we take the buffer created from the buffered writes and write it at
1451 // one shot. Because the Unix systems use ANSI for the colors, which is a text-based styling
1452 // scheme, this buffered approach works and maintains the styling.
1454 // On Windows, styling happens through calls to a terminal API. This prevents us from using the
1455 // same buffering approach. Instead, we use a global Windows mutex, which we acquire long
1456 // enough to output the full error message, then we release.
1457 let _buffer_lock = lock::acquire_global_lock("rustc_errors");
1458 for (pos, line) in rendered_buffer.iter().enumerate() {
1460 dst.apply_style(lvl.clone(), part.style)?;
1461 write!(dst, "{}", part.text)?;
1464 if !short_message && (!lvl.is_failure_note() || pos != rendered_buffer.len() - 1) {
1472 pub enum Destination {
1473 Terminal(StandardStream),
1474 Buffered(BufferWriter),
1475 Raw(Box<dyn Write + Send>),
1478 pub enum WritableDst<'a> {
1479 Terminal(&'a mut StandardStream),
1480 Buffered(&'a mut BufferWriter, Buffer),
1481 Raw(&'a mut Box<dyn Write + Send>),
1485 fn from_stderr(color: ColorConfig) -> Destination {
1486 let choice = color.to_color_choice();
1487 // On Windows we'll be performing global synchronization on the entire
1488 // system for emitting rustc errors, so there's no need to buffer
1491 // On non-Windows we rely on the atomicity of `write` to ensure errors
1492 // don't get all jumbled up.
1494 Terminal(StandardStream::stderr(choice))
1496 Buffered(BufferWriter::stderr(choice))
1500 fn writable<'a>(&'a mut self) -> WritableDst<'a> {
1502 Destination::Terminal(ref mut t) => WritableDst::Terminal(t),
1503 Destination::Buffered(ref mut t) => {
1504 let buf = t.buffer();
1505 WritableDst::Buffered(t, buf)
1507 Destination::Raw(ref mut t) => WritableDst::Raw(t),
1512 impl<'a> WritableDst<'a> {
1513 fn apply_style(&mut self, lvl: Level, style: Style) -> io::Result<()> {
1514 let mut spec = ColorSpec::new();
1516 Style::LineAndColumn => {}
1517 Style::LineNumber => {
1518 spec.set_bold(true);
1519 spec.set_intense(true);
1521 spec.set_fg(Some(Color::Cyan));
1523 spec.set_fg(Some(Color::Blue));
1526 Style::Quotation => {}
1527 Style::OldSchoolNoteText | Style::MainHeaderMsg => {
1528 spec.set_bold(true);
1530 spec.set_intense(true)
1531 .set_fg(Some(Color::White));
1534 Style::UnderlinePrimary | Style::LabelPrimary => {
1536 spec.set_bold(true);
1538 Style::UnderlineSecondary |
1539 Style::LabelSecondary => {
1543 spec.set_fg(Some(Color::Cyan));
1545 spec.set_fg(Some(Color::Blue));
1549 Style::NoStyle => {}
1550 Style::Level(lvl) => {
1552 spec.set_bold(true);
1554 Style::Highlight => {
1555 spec.set_bold(true);
1558 self.set_color(&spec)
1561 fn set_color(&mut self, color: &ColorSpec) -> io::Result<()> {
1563 WritableDst::Terminal(ref mut t) => t.set_color(color),
1564 WritableDst::Buffered(_, ref mut t) => t.set_color(color),
1565 WritableDst::Raw(_) => Ok(())
1569 fn reset(&mut self) -> io::Result<()> {
1571 WritableDst::Terminal(ref mut t) => t.reset(),
1572 WritableDst::Buffered(_, ref mut t) => t.reset(),
1573 WritableDst::Raw(_) => Ok(()),
1578 impl<'a> Write for WritableDst<'a> {
1579 fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
1581 WritableDst::Terminal(ref mut t) => t.write(bytes),
1582 WritableDst::Buffered(_, ref mut buf) => buf.write(bytes),
1583 WritableDst::Raw(ref mut w) => w.write(bytes),
1587 fn flush(&mut self) -> io::Result<()> {
1589 WritableDst::Terminal(ref mut t) => t.flush(),
1590 WritableDst::Buffered(_, ref mut buf) => buf.flush(),
1591 WritableDst::Raw(ref mut w) => w.flush(),
1596 impl<'a> Drop for WritableDst<'a> {
1597 fn drop(&mut self) {
1599 WritableDst::Buffered(ref mut dst, ref mut buf) => {
1600 drop(dst.print(buf));