1 //! The current rustc diagnostics emitter.
3 //! An `Emitter` takes care of generating the output from a `DiagnosticBuilder` struct.
5 //! There are various `Emitter` implementations that generate different output formats such as
6 //! JSON and human readable output.
8 //! The output types are defined in `librustc::session::config::ErrorOutputType`.
12 use syntax_pos::{SourceFile, Span, MultiSpan};
15 Level, CodeSuggestion, DiagnosticBuilder, SubDiagnostic,
16 SuggestionStyle, SourceMapperDyn, DiagnosticId,
18 use crate::Level::Error;
19 use crate::snippet::{Annotation, AnnotationType, Line, MultilineAnnotation, StyledString, Style};
20 use crate::styled_buffer::StyledBuffer;
22 use rustc_data_structures::fx::FxHashMap;
23 use rustc_data_structures::sync::Lrc;
25 use std::io::prelude::*;
27 use std::cmp::{min, Reverse};
29 use termcolor::{StandardStream, ColorChoice, ColorSpec, BufferWriter, Ansi};
30 use termcolor::{WriteColor, Color, Buffer};
32 /// Describes the way the content of the `rendered` field of the json output is generated
33 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
34 pub enum HumanReadableErrorType {
36 AnnotateSnippet(ColorConfig),
40 impl HumanReadableErrorType {
41 /// Returns a (`short`, `color`) tuple
42 pub fn unzip(self) -> (bool, ColorConfig) {
44 HumanReadableErrorType::Default(cc) => (false, cc),
45 HumanReadableErrorType::Short(cc) => (true, cc),
46 HumanReadableErrorType::AnnotateSnippet(cc) => (false, cc),
51 dst: Box<dyn Write + Send>,
52 source_map: Option<Lrc<SourceMapperDyn>>,
55 let (short, color_config) = self.unzip();
56 EmitterWriter::new(dst, source_map, short, teach, color_config.suggests_using_colors())
60 const ANONYMIZED_LINE_NUM: &str = "LL";
62 /// Emitter trait for emitting errors.
64 /// Emit a structured diagnostic.
65 fn emit_diagnostic(&mut self, db: &DiagnosticBuilder<'_>);
67 /// Emit a notification that an artifact has been output.
68 /// This is currently only supported for the JSON format,
69 /// other formats can, and will, simply ignore it.
70 fn emit_artifact_notification(&mut self, _path: &Path, _artifact_type: &str) {}
72 /// Checks if should show explanations about "rustc --explain"
73 fn should_show_explain(&self) -> bool {
78 impl Emitter for EmitterWriter {
79 fn emit_diagnostic(&mut self, db: &DiagnosticBuilder<'_>) {
80 let mut primary_span = db.span.clone();
81 let mut children = db.children.clone();
82 let mut suggestions: &[_] = &[];
84 if let Some((sugg, rest)) = db.suggestions.split_first() {
86 // don't display multi-suggestions as labels
87 sugg.substitutions.len() == 1 &&
88 // don't display multipart suggestions as labels
89 sugg.substitutions[0].parts.len() == 1 &&
90 // don't display long messages as labels
91 sugg.msg.split_whitespace().count() < 10 &&
92 // don't display multiline suggestions as labels
93 !sugg.substitutions[0].parts[0].snippet.contains('\n') &&
94 // when this style is set we want the suggestion to be a message, not inline
95 sugg.style != SuggestionStyle::HideCodeAlways &&
96 // trivial suggestion for tooling's sake, never shown
97 sugg.style != SuggestionStyle::CompletelyHidden
99 let substitution = &sugg.substitutions[0].parts[0].snippet.trim();
100 let msg = if substitution.len() == 0 || sugg.style.hide_inline() {
101 // This substitution is only removal or we explicitly don't want to show the
102 // code inline, don't show it
103 format!("help: {}", sugg.msg)
105 format!("help: {}: `{}`", sugg.msg, substitution)
107 primary_span.push_span_label(sugg.substitutions[0].parts[0].span, msg);
109 // if there are multiple suggestions, print them all in full
110 // to be consistent. We could try to figure out if we can
111 // make one (or the first one) inline, but that would give
112 // undue importance to a semi-random suggestion
113 suggestions = &db.suggestions;
117 self.fix_multispans_in_std_macros(&mut primary_span,
120 db.handler.flags.external_macro_backtrace);
122 self.emit_messages_default(&db.level,
123 &db.styled_message(),
130 fn should_show_explain(&self) -> bool {
135 /// maximum number of lines we will print for each error; arbitrary.
136 pub const MAX_HIGHLIGHT_LINES: usize = 6;
137 /// maximum number of suggestions to be shown
139 /// Arbitrary, but taken from trait import suggestion limit
140 pub const MAX_SUGGESTIONS: usize = 4;
142 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
143 pub enum ColorConfig {
150 fn to_color_choice(self) -> ColorChoice {
152 ColorConfig::Always => {
153 if atty::is(atty::Stream::Stderr) {
156 ColorChoice::AlwaysAnsi
159 ColorConfig::Never => ColorChoice::Never,
160 ColorConfig::Auto if atty::is(atty::Stream::Stderr) => {
163 ColorConfig::Auto => ColorChoice::Never,
166 fn suggests_using_colors(self) -> bool {
168 | ColorConfig::Always
171 ColorConfig::Never => false,
176 /// Handles the writing of `HumanReadableErrorType::Default` and `HumanReadableErrorType::Short`
177 pub struct EmitterWriter {
179 sm: Option<Lrc<SourceMapperDyn>>,
186 pub struct FileWithAnnotatedLines {
187 pub file: Lrc<SourceFile>,
188 pub lines: Vec<Line>,
189 multiline_depth: usize,
193 pub fn stderr(color_config: ColorConfig,
194 source_map: Option<Lrc<SourceMapperDyn>>,
198 let dst = Destination::from_stderr(color_config);
209 dst: Box<dyn Write + Send>,
210 source_map: Option<Lrc<SourceMapperDyn>>,
216 dst: Raw(dst, colored),
224 pub fn ui_testing(mut self, ui_testing: bool) -> Self {
225 self.ui_testing = ui_testing;
229 fn maybe_anonymized(&self, line_num: usize) -> String {
231 ANONYMIZED_LINE_NUM.to_string()
237 fn render_source_line(&self,
238 buffer: &mut StyledBuffer,
239 file: Lrc<SourceFile>,
242 code_offset: usize) -> Vec<(usize, Style)> {
243 if line.line_index == 0 {
247 let source_string = match file.get_line(line.line_index - 1) {
249 None => return Vec::new(),
252 let line_offset = buffer.num_lines();
254 // First create the source line we will highlight.
255 buffer.puts(line_offset, code_offset, &source_string, Style::Quotation);
256 buffer.puts(line_offset,
258 &self.maybe_anonymized(line.line_index),
261 draw_col_separator(buffer, line_offset, width_offset - 2);
263 // Special case when there's only one annotation involved, it is the start of a multiline
264 // span and there's no text at the beginning of the code line. Instead of doing the whole
273 // we simplify the output to:
279 if line.annotations.len() == 1 {
280 if let Some(ref ann) = line.annotations.get(0) {
281 if let AnnotationType::MultilineStart(depth) = ann.annotation_type {
282 if source_string.chars()
284 .all(|c| c.is_whitespace()) {
285 let style = if ann.is_primary {
286 Style::UnderlinePrimary
288 Style::UnderlineSecondary
290 buffer.putc(line_offset,
291 width_offset + depth - 1,
294 return vec![(depth, style)];
300 // We want to display like this:
302 // vec.push(vec.pop().unwrap());
303 // --- ^^^ - previous borrow ends here
305 // | error occurs here
306 // previous borrow of `vec` occurs here
308 // But there are some weird edge cases to be aware of:
310 // vec.push(vec.pop().unwrap());
311 // -------- - previous borrow ends here
313 // |this makes no sense
314 // previous borrow of `vec` occurs here
316 // For this reason, we group the lines into "highlight lines"
317 // and "annotations lines", where the highlight lines have the `^`.
319 // Sort the annotations by (start, end col)
320 // The labels are reversed, sort and then reversed again.
321 // Consider a list of annotations (A1, A2, C1, C2, B1, B2) where
322 // the letter signifies the span. Here we are only sorting by the
323 // span and hence, the order of the elements with the same span will
324 // not change. On reversing the ordering (|a, b| but b.cmp(a)), you get
325 // (C1, C2, B1, B2, A1, A2). All the elements with the same span are
326 // still ordered first to last, but all the elements with different
327 // spans are ordered by their spans in last to first order. Last to
328 // first order is important, because the jiggly lines and | are on
329 // the left, so the rightmost span needs to be rendered first,
330 // otherwise the lines would end up needing to go over a message.
332 let mut annotations = line.annotations.clone();
333 annotations.sort_by_key(|a| Reverse(a.start_col));
335 // First, figure out where each label will be positioned.
337 // In the case where you have the following annotations:
339 // vec.push(vec.pop().unwrap());
340 // -------- - previous borrow ends here [C]
342 // |this makes no sense [B]
343 // previous borrow of `vec` occurs here [A]
345 // `annotations_position` will hold [(2, A), (1, B), (0, C)].
347 // We try, when possible, to stick the rightmost annotation at the end
348 // of the highlight line:
350 // vec.push(vec.pop().unwrap());
351 // --- --- - previous borrow ends here
353 // But sometimes that's not possible because one of the other
354 // annotations overlaps it. For example, from the test
355 // `span_overlap_label`, we have the following annotations
356 // (written on distinct lines for clarity):
362 // In this case, we can't stick the rightmost-most label on
363 // the highlight line, or we would get:
370 // which is totally weird. Instead we want:
378 // which is...less weird, at least. In fact, in general, if
379 // the rightmost span overlaps with any other span, we should
380 // use the "hang below" version, so we can at least make it
381 // clear where the span *starts*. There's an exception for this
382 // logic, when the labels do not have a message:
397 let mut annotations_position = vec![];
398 let mut line_len = 0;
400 for (i, annotation) in annotations.iter().enumerate() {
401 for (j, next) in annotations.iter().enumerate() {
402 if overlaps(next, annotation, 0) // This label overlaps with another one and both
403 && annotation.has_label() // take space (they have text and are not
404 && j > i // multiline lines).
405 && p == 0 // We're currently on the first line, move the label one line down
407 // If we're overlapping with an un-labelled annotation with the same span
408 // we can just merge them in the output
409 if next.start_col == annotation.start_col
410 && next.end_col == annotation.end_col
416 // This annotation needs a new line in the output.
421 annotations_position.push((p, annotation));
422 for (j, next) in annotations.iter().enumerate() {
424 let l = if let Some(ref label) = next.label {
429 if (overlaps(next, annotation, l) // Do not allow two labels to be in the same
430 // line if they overlap including padding, to
431 // avoid situations like:
438 && annotation.has_label() // Both labels must have some text, otherwise
439 && next.has_label()) // they are not overlapping.
440 // Do not add a new line if this annotation
441 // or the next are vertical line placeholders.
442 || (annotation.takes_space() // If either this or the next annotation is
443 && next.has_label()) // multiline start/end, move it to a new line
444 || (annotation.has_label() // so as not to overlap the orizontal lines.
445 && next.takes_space())
446 || (annotation.takes_space() && next.takes_space())
447 || (overlaps(next, annotation, l)
448 && next.end_col <= annotation.end_col
450 && p == 0) // Avoid #42595.
452 // This annotation needs a new line in the output.
467 // If there are no annotations or the only annotations on this line are
468 // MultilineLine, then there's only code being shown, stop processing.
469 if line.annotations.iter().all(|a| a.is_line()) {
473 // Write the colunmn separator.
475 // After this we will have:
484 for pos in 0..=line_len {
485 draw_col_separator(buffer, line_offset + pos + 1, width_offset - 2);
486 buffer.putc(line_offset + pos + 1,
492 // Write the horizontal lines for multiline annotations
493 // (only the first and last lines need this).
495 // After this we will have:
504 for &(pos, annotation) in &annotations_position {
505 let style = if annotation.is_primary {
506 Style::UnderlinePrimary
508 Style::UnderlineSecondary
511 match annotation.annotation_type {
512 AnnotationType::MultilineStart(depth) |
513 AnnotationType::MultilineEnd(depth) => {
517 width_offset + depth,
518 code_offset + annotation.start_col,
522 buffer.set_style_range(line_offset,
523 code_offset + annotation.start_col,
524 code_offset + annotation.end_col,
526 annotation.is_primary);
532 // Write the vertical lines for labels that are on a different line as the underline.
534 // After this we will have:
543 for &(pos, annotation) in &annotations_position {
544 let style = if annotation.is_primary {
545 Style::UnderlinePrimary
547 Style::UnderlineSecondary
551 if pos > 1 && (annotation.has_label() || annotation.takes_space()) {
552 for p in line_offset + 1..=line_offset + pos {
554 code_offset + annotation.start_col,
559 match annotation.annotation_type {
560 AnnotationType::MultilineStart(depth) => {
561 for p in line_offset + pos + 1..line_offset + line_len + 2 {
563 width_offset + depth - 1,
568 AnnotationType::MultilineEnd(depth) => {
569 for p in line_offset..=line_offset + pos {
571 width_offset + depth - 1,
580 // Write the labels on the annotations that actually have a label.
582 // After this we will have:
587 // | something about `foo`
591 for &(pos, annotation) in &annotations_position {
592 let style = if annotation.is_primary {
595 Style::LabelSecondary
597 let (pos, col) = if pos == 0 {
598 (pos + 1, annotation.end_col + 1)
600 (pos + 2, annotation.start_col)
602 if let Some(ref label) = annotation.label {
603 buffer.puts(line_offset + pos,
610 // Sort from biggest span to smallest span so that smaller spans are
611 // represented in the output:
616 // | | something about `foo`
617 // | something about `fn foo()`
618 annotations_position.sort_by(|a, b| {
619 // Decreasing order. When `a` and `b` are the same length, prefer `Primary`.
620 (a.1.len(), !a.1.is_primary).cmp(&(b.1.len(), !b.1.is_primary)).reverse()
623 // Write the underlines.
625 // After this we will have:
630 // | something about `foo`
634 for &(_, annotation) in &annotations_position {
635 let (underline, style) = if annotation.is_primary {
636 ('^', Style::UnderlinePrimary)
638 ('-', Style::UnderlineSecondary)
640 for p in annotation.start_col..annotation.end_col {
641 buffer.putc(line_offset + 1,
647 annotations_position.iter().filter_map(|&(_, annotation)| {
648 match annotation.annotation_type {
649 AnnotationType::MultilineStart(p) | AnnotationType::MultilineEnd(p) => {
650 let style = if annotation.is_primary {
653 Style::LabelSecondary
660 }).collect::<Vec<_>>()
663 fn get_multispan_max_line_num(&mut self, msp: &MultiSpan) -> usize {
665 if let Some(ref sm) = self.sm {
666 for primary_span in msp.primary_spans() {
667 if !primary_span.is_dummy() {
668 let hi = sm.lookup_char_pos(primary_span.hi());
674 if !self.short_message {
675 for span_label in msp.span_labels() {
676 if !span_label.span.is_dummy() {
677 let hi = sm.lookup_char_pos(span_label.span.hi());
688 fn get_max_line_num(&mut self, span: &MultiSpan, children: &[SubDiagnostic]) -> usize {
691 let primary = self.get_multispan_max_line_num(span);
692 max = if primary > max { primary } else { max };
694 for sub in children {
695 let sub_result = self.get_multispan_max_line_num(&sub.span);
696 max = if sub_result > max { primary } else { max };
701 // This "fixes" MultiSpans that contain Spans that are pointing to locations inside of
702 // <*macros>. Since these locations are often difficult to read, we move these Spans from
703 // <*macros> to their corresponding use site.
704 fn fix_multispan_in_std_macros(&mut self,
705 span: &mut MultiSpan,
706 always_backtrace: bool) -> bool {
707 let mut spans_updated = false;
709 if let Some(ref sm) = self.sm {
710 let mut before_after: Vec<(Span, Span)> = vec![];
711 let mut new_labels: Vec<(Span, String)> = vec![];
713 // First, find all the spans in <*macros> and point instead at their use site
714 for sp in span.primary_spans() {
718 let call_sp = sm.call_span_if_macro(*sp);
719 if call_sp != *sp && !always_backtrace {
720 before_after.push((*sp, call_sp));
722 let backtrace_len = sp.macro_backtrace().len();
723 for (i, trace) in sp.macro_backtrace().iter().rev().enumerate() {
724 // Only show macro locations that are local
725 // and display them like a span_note
726 if let Some(def_site) = trace.def_site_span {
727 if def_site.is_dummy() {
730 if always_backtrace {
731 new_labels.push((def_site,
732 format!("in this expansion of `{}`{}",
733 trace.macro_decl_name,
734 if backtrace_len > 2 {
735 // if backtrace_len == 1 it'll be pointed
736 // at by "in this macro invocation"
737 format!(" (#{})", i + 1)
742 // Check to make sure we're not in any <*macros>
743 if !sm.span_to_filename(def_site).is_macros() &&
744 !trace.macro_decl_name.starts_with("desugaring of ") &&
745 !trace.macro_decl_name.starts_with("#[") ||
747 new_labels.push((trace.call_site,
748 format!("in this macro invocation{}",
749 if backtrace_len > 2 && always_backtrace {
750 // only specify order when the macro
751 // backtrace is multiple levels deep
752 format!(" (#{})", i + 1)
756 if !always_backtrace {
763 for (label_span, label_text) in new_labels {
764 span.push_span_label(label_span, label_text);
766 for sp_label in span.span_labels() {
767 if sp_label.span.is_dummy() {
770 if sm.span_to_filename(sp_label.span.clone()).is_macros() &&
773 let v = sp_label.span.macro_backtrace();
774 if let Some(use_site) = v.last() {
775 before_after.push((sp_label.span.clone(), use_site.call_site.clone()));
779 // After we have them, make sure we replace these 'bad' def sites with their use sites
780 for (before, after) in before_after {
781 span.replace(before, after);
782 spans_updated = true;
789 // This does a small "fix" for multispans by looking to see if it can find any that
790 // point directly at <*macros>. Since these are often difficult to read, this
791 // will change the span to point at the use site.
792 fn fix_multispans_in_std_macros(&mut self,
793 span: &mut MultiSpan,
794 children: &mut Vec<SubDiagnostic>,
797 let mut spans_updated = self.fix_multispan_in_std_macros(span, backtrace);
798 for child in children.iter_mut() {
799 spans_updated |= self.fix_multispan_in_std_macros(&mut child.span, backtrace);
801 let msg = if level == &Error {
802 "this error originates in a macro outside of the current crate \
803 (in Nightly builds, run with -Z external-macro-backtrace \
804 for more info)".to_string()
806 "this warning originates in a macro outside of the current crate \
807 (in Nightly builds, run with -Z external-macro-backtrace \
808 for more info)".to_string()
812 children.push(SubDiagnostic {
818 span: MultiSpan::new(),
824 /// Adds a left margin to every line but the first, given a padding length and the label being
825 /// displayed, keeping the provided highlighting.
826 fn msg_to_buffer(&self,
827 buffer: &mut StyledBuffer,
828 msg: &[(String, Style)],
831 override_style: Option<Style>) {
833 // The extra 5 ` ` is padding that's always needed to align to the `note: `:
846 // | | length of label
848 // `max_line_num_len`
849 let padding = " ".repeat(padding + label.len() + 5);
851 /// Returns `true` if `style`, or the override if present and the style is `NoStyle`.
852 fn style_or_override(style: Style, override_style: Option<Style>) -> Style {
853 if let Some(o) = override_style {
854 if style == Style::NoStyle {
861 let mut line_number = 0;
863 // Provided the following diagnostic message:
867 // ("highlighted multiline\nstring to\nsee how it ", Style::NoStyle),
868 // ("looks", Style::Highlight),
869 // ("with\nvery ", Style::NoStyle),
870 // ("weird", Style::Highlight),
871 // (" formats\n", Style::NoStyle),
872 // ("see?", Style::Highlight),
875 // the expected output on a note is (* surround the highlighted text)
877 // = note: highlighted multiline
879 // see how it *looks* with
880 // very *weird* formats
882 for &(ref text, ref style) in msg.iter() {
883 let lines = text.split('\n').collect::<Vec<_>>();
885 for (i, line) in lines.iter().enumerate() {
888 buffer.append(line_number, &padding, Style::NoStyle);
890 buffer.append(line_number, line, style_or_override(*style, override_style));
893 buffer.append(line_number, text, style_or_override(*style, override_style));
898 fn emit_message_default(
901 msg: &[(String, Style)],
902 code: &Option<DiagnosticId>,
904 max_line_num_len: usize,
906 ) -> io::Result<()> {
907 let mut buffer = StyledBuffer::new();
908 let header_style = if is_secondary {
914 if !msp.has_primary_spans() && !msp.has_span_labels() && is_secondary
915 && !self.short_message {
916 // This is a secondary message with no span info
917 for _ in 0..max_line_num_len {
918 buffer.prepend(0, " ", Style::NoStyle);
920 draw_note_separator(&mut buffer, 0, max_line_num_len + 1);
921 let level_str = level.to_string();
922 if !level_str.is_empty() {
923 buffer.append(0, &level_str, Style::MainHeaderMsg);
924 buffer.append(0, ": ", Style::NoStyle);
926 self.msg_to_buffer(&mut buffer, msg, max_line_num_len, "note", None);
928 let level_str = level.to_string();
929 if !level_str.is_empty() {
930 buffer.append(0, &level_str, Style::Level(level.clone()));
932 // only render error codes, not lint codes
933 if let Some(DiagnosticId::Error(ref code)) = *code {
934 buffer.append(0, "[", Style::Level(level.clone()));
935 buffer.append(0, &code, Style::Level(level.clone()));
936 buffer.append(0, "]", Style::Level(level.clone()));
938 if !level_str.is_empty() {
939 buffer.append(0, ": ", header_style);
941 for &(ref text, _) in msg.iter() {
942 buffer.append(0, text, header_style);
946 let mut annotated_files = FileWithAnnotatedLines::collect_annotations(msp, &self.sm);
948 // Make sure our primary file comes first
949 let (primary_lo, sm) = if let (Some(sm), Some(ref primary_span)) =
950 (self.sm.as_ref(), msp.primary_span().as_ref()) {
951 if !primary_span.is_dummy() {
952 (sm.lookup_char_pos(primary_span.lo()), sm)
954 emit_to_destination(&buffer.render(), level, &mut self.dst, self.short_message)?;
958 // If we don't have span information, emit and exit
959 emit_to_destination(&buffer.render(), level, &mut self.dst, self.short_message)?;
963 annotated_files.binary_search_by(|x| x.file.name.cmp(&primary_lo.file.name)) {
964 annotated_files.swap(0, pos);
967 // Print out the annotate source lines that correspond with the error
968 for annotated_file in annotated_files {
969 // we can't annotate anything if the source is unavailable.
970 if !sm.ensure_source_file_source_present(annotated_file.file.clone()) {
974 // print out the span location and spacer before we print the annotated source
975 // to do this, we need to know if this span will be primary
976 let is_primary = primary_lo.file.name == annotated_file.file.name;
978 let loc = primary_lo.clone();
979 if !self.short_message {
980 // remember where we are in the output buffer for easy reference
981 let buffer_msg_line_offset = buffer.num_lines();
983 buffer.prepend(buffer_msg_line_offset, "--> ", Style::LineNumber);
984 buffer.append(buffer_msg_line_offset,
987 sm.doctest_offset_line(&loc.file.name, loc.line),
989 Style::LineAndColumn);
990 for _ in 0..max_line_num_len {
991 buffer.prepend(buffer_msg_line_offset, " ", Style::NoStyle);
995 &format!("{}:{}:{}: ",
997 sm.doctest_offset_line(&loc.file.name, loc.line),
999 Style::LineAndColumn);
1001 } else if !self.short_message {
1002 // remember where we are in the output buffer for easy reference
1003 let buffer_msg_line_offset = buffer.num_lines();
1006 draw_col_separator(&mut buffer, buffer_msg_line_offset, max_line_num_len + 1);
1008 // Then, the secondary file indicator
1009 buffer.prepend(buffer_msg_line_offset + 1, "::: ", Style::LineNumber);
1010 let loc = if let Some(first_line) = annotated_file.lines.first() {
1011 let col = if let Some(first_annotation) = first_line.annotations.first() {
1012 format!(":{}", first_annotation.start_col + 1)
1017 annotated_file.file.name,
1018 sm.doctest_offset_line(
1019 &annotated_file.file.name, first_line.line_index),
1022 annotated_file.file.name.to_string()
1024 buffer.append(buffer_msg_line_offset + 1,
1026 Style::LineAndColumn);
1027 for _ in 0..max_line_num_len {
1028 buffer.prepend(buffer_msg_line_offset + 1, " ", Style::NoStyle);
1032 if !self.short_message {
1033 // Put in the spacer between the location and annotated source
1034 let buffer_msg_line_offset = buffer.num_lines();
1035 draw_col_separator_no_space(&mut buffer,
1036 buffer_msg_line_offset,
1037 max_line_num_len + 1);
1039 // Contains the vertical lines' positions for active multiline annotations
1040 let mut multilines = FxHashMap::default();
1042 // Next, output the annotate source for this file
1043 for line_idx in 0..annotated_file.lines.len() {
1044 let previous_buffer_line = buffer.num_lines();
1046 let width_offset = 3 + max_line_num_len;
1047 let code_offset = if annotated_file.multiline_depth == 0 {
1050 width_offset + annotated_file.multiline_depth + 1
1053 let depths = self.render_source_line(&mut buffer,
1054 annotated_file.file.clone(),
1055 &annotated_file.lines[line_idx],
1059 let mut to_add = FxHashMap::default();
1061 for (depth, style) in depths {
1062 if multilines.get(&depth).is_some() {
1063 multilines.remove(&depth);
1065 to_add.insert(depth, style);
1069 // Set the multiline annotation vertical lines to the left of
1070 // the code in this line.
1071 for (depth, style) in &multilines {
1072 for line in previous_buffer_line..buffer.num_lines() {
1073 draw_multiline_line(&mut buffer,
1080 // check to see if we need to print out or elide lines that come between
1081 // this annotated line and the next one.
1082 if line_idx < (annotated_file.lines.len() - 1) {
1083 let line_idx_delta = annotated_file.lines[line_idx + 1].line_index -
1084 annotated_file.lines[line_idx].line_index;
1085 if line_idx_delta > 2 {
1086 let last_buffer_line_num = buffer.num_lines();
1087 buffer.puts(last_buffer_line_num, 0, "...", Style::LineNumber);
1089 // Set the multiline annotation vertical lines on `...` bridging line.
1090 for (depth, style) in &multilines {
1091 draw_multiline_line(&mut buffer,
1092 last_buffer_line_num,
1097 } else if line_idx_delta == 2 {
1098 let unannotated_line = annotated_file.file
1099 .get_line(annotated_file.lines[line_idx].line_index)
1100 .unwrap_or_else(|| Cow::from(""));
1102 let last_buffer_line_num = buffer.num_lines();
1104 buffer.puts(last_buffer_line_num,
1106 &self.maybe_anonymized(annotated_file.lines[line_idx + 1]
1109 draw_col_separator(&mut buffer,
1110 last_buffer_line_num,
1111 1 + max_line_num_len);
1112 buffer.puts(last_buffer_line_num,
1117 for (depth, style) in &multilines {
1118 draw_multiline_line(&mut buffer,
1119 last_buffer_line_num,
1127 multilines.extend(&to_add);
1132 // final step: take our styled buffer, render it, then output it
1133 emit_to_destination(&buffer.render(), level, &mut self.dst, self.short_message)?;
1139 fn emit_suggestion_default(
1141 suggestion: &CodeSuggestion,
1143 max_line_num_len: usize,
1144 ) -> io::Result<()> {
1145 if let Some(ref sm) = self.sm {
1146 let mut buffer = StyledBuffer::new();
1148 // Render the suggestion message
1149 let level_str = level.to_string();
1150 if !level_str.is_empty() {
1151 buffer.append(0, &level_str, Style::Level(level.clone()));
1152 buffer.append(0, ": ", Style::HeaderMsg);
1156 &[(suggestion.msg.to_owned(), Style::NoStyle)],
1159 Some(Style::HeaderMsg),
1162 // Render the replacements for each suggestion
1163 let suggestions = suggestion.splice_lines(&**sm);
1165 let mut row_num = 2;
1166 for &(ref complete, ref parts) in suggestions.iter().take(MAX_SUGGESTIONS) {
1167 // Only show underline if the suggestion spans a single line and doesn't cover the
1168 // entirety of the code output. If you have multiple replacements in the same line
1169 // of code, show the underline.
1170 let show_underline = !(parts.len() == 1
1171 && parts[0].snippet.trim() == complete.trim())
1172 && complete.lines().count() == 1;
1174 let lines = sm.span_to_lines(parts[0].span).unwrap();
1176 assert!(!lines.lines.is_empty());
1178 let line_start = sm.lookup_char_pos(parts[0].span.lo()).line;
1179 draw_col_separator_no_space(&mut buffer, 1, max_line_num_len + 1);
1180 let mut line_pos = 0;
1181 let mut lines = complete.lines();
1182 for line in lines.by_ref().take(MAX_HIGHLIGHT_LINES) {
1183 // Print the span column to avoid confusion
1184 buffer.puts(row_num,
1186 &self.maybe_anonymized(line_start + line_pos),
1188 // print the suggestion
1189 draw_col_separator(&mut buffer, row_num, max_line_num_len + 1);
1190 buffer.append(row_num, line, Style::NoStyle);
1195 // This offset and the ones below need to be signed to account for replacement code
1196 // that is shorter than the original code.
1197 let mut offset: isize = 0;
1198 // Only show an underline in the suggestions if the suggestion is not the
1199 // entirety of the code being shown and the displayed code is not multiline.
1201 draw_col_separator(&mut buffer, row_num, max_line_num_len + 1);
1203 let span_start_pos = sm.lookup_char_pos(part.span.lo()).col_display;
1204 let span_end_pos = sm.lookup_char_pos(part.span.hi()).col_display;
1206 // Do not underline the leading...
1207 let start = part.snippet.len()
1208 .saturating_sub(part.snippet.trim_start().len());
1209 // ...or trailing spaces. Account for substitutions containing unicode
1211 let sub_len = part.snippet.trim().chars().fold(0, |acc, ch| {
1212 acc + unicode_width::UnicodeWidthChar::width(ch).unwrap_or(0)
1215 let underline_start = (span_start_pos + start) as isize + offset;
1216 let underline_end = (span_start_pos + start + sub_len) as isize + offset;
1217 for p in underline_start..underline_end {
1218 buffer.putc(row_num,
1219 max_line_num_len + 3 + p as usize,
1221 Style::UnderlinePrimary);
1223 // underline removals too
1224 if underline_start == underline_end {
1225 for p in underline_start-1..underline_start+1 {
1226 buffer.putc(row_num,
1227 max_line_num_len + 3 + p as usize,
1229 Style::UnderlineSecondary);
1233 // length of the code after substitution
1234 let full_sub_len = part.snippet.chars().fold(0, |acc, ch| {
1235 acc + unicode_width::UnicodeWidthChar::width(ch).unwrap_or(0) as isize
1238 // length of the code to be substituted
1239 let snippet_len = span_end_pos as isize - span_start_pos as isize;
1240 // For multiple substitutions, use the position *after* the previous
1241 // substitutions have happened.
1242 offset += full_sub_len - snippet_len;
1247 // if we elided some lines, add an ellipsis
1248 if lines.next().is_some() {
1249 buffer.puts(row_num, max_line_num_len - 1, "...", Style::LineNumber);
1250 } else if !show_underline {
1251 draw_col_separator_no_space(&mut buffer, row_num, max_line_num_len + 1);
1255 if suggestions.len() > MAX_SUGGESTIONS {
1256 let msg = format!("and {} other candidates", suggestions.len() - MAX_SUGGESTIONS);
1257 buffer.puts(row_num, 0, &msg, Style::NoStyle);
1259 emit_to_destination(&buffer.render(), level, &mut self.dst, self.short_message)?;
1264 fn emit_messages_default(&mut self,
1266 message: &[(String, Style)],
1267 code: &Option<DiagnosticId>,
1269 children: &[SubDiagnostic],
1270 suggestions: &[CodeSuggestion]) {
1271 let max_line_num_len = if self.ui_testing {
1272 ANONYMIZED_LINE_NUM.len()
1274 self.get_max_line_num(span, children).to_string().len()
1277 match self.emit_message_default(span,
1284 if !children.is_empty() {
1285 let mut buffer = StyledBuffer::new();
1286 if !self.short_message {
1287 draw_col_separator_no_space(&mut buffer, 0, max_line_num_len + 1);
1289 match emit_to_destination(&buffer.render(), level, &mut self.dst,
1290 self.short_message) {
1292 Err(e) => panic!("failed to emit error: {}", e)
1295 if !self.short_message {
1296 for child in children {
1297 let span = child.render_span.as_ref().unwrap_or(&child.span);
1298 match self.emit_message_default(
1300 &child.styled_message(),
1306 Err(e) => panic!("failed to emit error: {}", e),
1310 for sugg in suggestions {
1311 if sugg.style == SuggestionStyle::CompletelyHidden {
1312 // do not display this suggestion, it is meant only for tools
1313 } else if sugg.style == SuggestionStyle::HideCodeAlways {
1314 match self.emit_message_default(
1316 &[(sugg.msg.to_owned(), Style::HeaderMsg)],
1322 Err(e) => panic!("failed to emit error: {}", e),
1326 match self.emit_suggestion_default(
1331 Err(e) => panic!("failed to emit error: {}", e),
1338 Err(e) => panic!("failed to emit error: {}", e),
1341 let mut dst = self.dst.writable();
1342 match write!(dst, "\n") {
1343 Err(e) => panic!("failed to emit error: {}", e),
1346 Err(e) => panic!("failed to emit error: {}", e),
1354 impl FileWithAnnotatedLines {
1355 /// Preprocess all the annotations so that they are grouped by file and by line number
1356 /// This helps us quickly iterate over the whole message (including secondary file spans)
1357 pub fn collect_annotations(
1359 source_map: &Option<Lrc<SourceMapperDyn>>
1360 ) -> Vec<FileWithAnnotatedLines> {
1361 fn add_annotation_to_file(file_vec: &mut Vec<FileWithAnnotatedLines>,
1362 file: Lrc<SourceFile>,
1366 for slot in file_vec.iter_mut() {
1367 // Look through each of our files for the one we're adding to
1368 if slot.file.name == file.name {
1369 // See if we already have a line for it
1370 for line_slot in &mut slot.lines {
1371 if line_slot.line_index == line_index {
1372 line_slot.annotations.push(ann);
1376 // We don't have a line yet, create one
1377 slot.lines.push(Line {
1379 annotations: vec![ann],
1385 // This is the first time we're seeing the file
1386 file_vec.push(FileWithAnnotatedLines {
1390 annotations: vec![ann],
1396 let mut output = vec![];
1397 let mut multiline_annotations = vec![];
1399 if let Some(ref sm) = source_map {
1400 for span_label in msp.span_labels() {
1401 if span_label.span.is_dummy() {
1405 let lo = sm.lookup_char_pos(span_label.span.lo());
1406 let mut hi = sm.lookup_char_pos(span_label.span.hi());
1408 // Watch out for "empty spans". If we get a span like 6..6, we
1409 // want to just display a `^` at 6, so convert that to
1410 // 6..7. This is degenerate input, but it's best to degrade
1411 // gracefully -- and the parser likes to supply a span like
1412 // that for EOF, in particular.
1414 if lo.col_display == hi.col_display && lo.line == hi.line {
1415 hi.col_display += 1;
1418 let ann_type = if lo.line != hi.line {
1419 let ml = MultilineAnnotation {
1421 line_start: lo.line,
1423 start_col: lo.col_display,
1424 end_col: hi.col_display,
1425 is_primary: span_label.is_primary,
1426 label: span_label.label.clone(),
1427 overlaps_exactly: false,
1429 multiline_annotations.push((lo.file.clone(), ml.clone()));
1430 AnnotationType::Multiline(ml)
1432 AnnotationType::Singleline
1434 let ann = Annotation {
1435 start_col: lo.col_display,
1436 end_col: hi.col_display,
1437 is_primary: span_label.is_primary,
1438 label: span_label.label.clone(),
1439 annotation_type: ann_type,
1442 if !ann.is_multiline() {
1443 add_annotation_to_file(&mut output, lo.file, lo.line, ann);
1448 // Find overlapping multiline annotations, put them at different depths
1449 multiline_annotations.sort_by_key(|&(_, ref ml)| (ml.line_start, ml.line_end));
1450 for item in multiline_annotations.clone() {
1452 for item in multiline_annotations.iter_mut() {
1453 let ref mut a = item.1;
1454 // Move all other multiline annotations overlapping with this one
1455 // one level to the right.
1456 if !(ann.same_span(a)) &&
1457 num_overlap(ann.line_start, ann.line_end, a.line_start, a.line_end, true)
1460 } else if ann.same_span(a) && &ann != a {
1461 a.overlaps_exactly = true;
1468 let mut max_depth = 0; // max overlapping multiline spans
1469 for (file, ann) in multiline_annotations {
1470 if ann.depth > max_depth {
1471 max_depth = ann.depth;
1473 let mut end_ann = ann.as_end();
1474 if !ann.overlaps_exactly {
1475 // avoid output like
1497 add_annotation_to_file(&mut output, file.clone(), ann.line_start, ann.as_start());
1498 // 4 is the minimum vertical length of a multiline span when presented: two lines
1499 // of code and two lines of underline. This is not true for the special case where
1500 // the beginning doesn't have an underline, but the current logic seems to be
1501 // working correctly.
1502 let middle = min(ann.line_start + 4, ann.line_end);
1503 for line in ann.line_start + 1..middle {
1504 // Every `|` that joins the beginning of the span (`___^`) to the end (`|__^`).
1505 add_annotation_to_file(&mut output, file.clone(), line, ann.as_line());
1507 if middle < ann.line_end - 1 {
1508 for line in ann.line_end - 1..ann.line_end {
1509 add_annotation_to_file(&mut output, file.clone(), line, ann.as_line());
1513 end_ann.annotation_type = AnnotationType::Singleline;
1515 add_annotation_to_file(&mut output, file, ann.line_end, end_ann);
1517 for file_vec in output.iter_mut() {
1518 file_vec.multiline_depth = max_depth;
1524 fn draw_col_separator(buffer: &mut StyledBuffer, line: usize, col: usize) {
1525 buffer.puts(line, col, "| ", Style::LineNumber);
1528 fn draw_col_separator_no_space(buffer: &mut StyledBuffer, line: usize, col: usize) {
1529 draw_col_separator_no_space_with_style(buffer, line, col, Style::LineNumber);
1532 fn draw_col_separator_no_space_with_style(buffer: &mut StyledBuffer,
1536 buffer.putc(line, col, '|', style);
1539 fn draw_range(buffer: &mut StyledBuffer, symbol: char, line: usize,
1540 col_from: usize, col_to: usize, style: Style) {
1541 for col in col_from..col_to {
1542 buffer.putc(line, col, symbol, style);
1546 fn draw_note_separator(buffer: &mut StyledBuffer, line: usize, col: usize) {
1547 buffer.puts(line, col, "= ", Style::LineNumber);
1550 fn draw_multiline_line(buffer: &mut StyledBuffer,
1556 buffer.putc(line, offset + depth - 1, '|', style);
1559 fn num_overlap(a_start: usize, a_end: usize, b_start: usize, b_end:usize, inclusive: bool) -> bool {
1560 let extra = if inclusive {
1565 (b_start..b_end + extra).contains(&a_start) ||
1566 (a_start..a_end + extra).contains(&b_start)
1568 fn overlaps(a1: &Annotation, a2: &Annotation, padding: usize) -> bool {
1569 num_overlap(a1.start_col, a1.end_col + padding, a2.start_col, a2.end_col, false)
1572 fn emit_to_destination(rendered_buffer: &[Vec<StyledString>],
1574 dst: &mut Destination,
1575 short_message: bool)
1579 let mut dst = dst.writable();
1581 // In order to prevent error message interleaving, where multiple error lines get intermixed
1582 // when multiple compiler processes error simultaneously, we emit errors with additional
1585 // On Unix systems, we write into a buffered terminal rather than directly to a terminal. When
1586 // the .flush() is called we take the buffer created from the buffered writes and write it at
1587 // one shot. Because the Unix systems use ANSI for the colors, which is a text-based styling
1588 // scheme, this buffered approach works and maintains the styling.
1590 // On Windows, styling happens through calls to a terminal API. This prevents us from using the
1591 // same buffering approach. Instead, we use a global Windows mutex, which we acquire long
1592 // enough to output the full error message, then we release.
1593 let _buffer_lock = lock::acquire_global_lock("rustc_errors");
1594 for (pos, line) in rendered_buffer.iter().enumerate() {
1596 dst.apply_style(lvl.clone(), part.style)?;
1597 write!(dst, "{}", part.text)?;
1600 if !short_message && (!lvl.is_failure_note() || pos != rendered_buffer.len() - 1) {
1608 pub enum Destination {
1609 Terminal(StandardStream),
1610 Buffered(BufferWriter),
1611 // The bool denotes whether we should be emitting ansi color codes or not
1612 Raw(Box<(dyn Write + Send)>, bool),
1615 pub enum WritableDst<'a> {
1616 Terminal(&'a mut StandardStream),
1617 Buffered(&'a mut BufferWriter, Buffer),
1618 Raw(&'a mut (dyn Write + Send)),
1619 ColoredRaw(Ansi<&'a mut (dyn Write + Send)>),
1623 fn from_stderr(color: ColorConfig) -> Destination {
1624 let choice = color.to_color_choice();
1625 // On Windows we'll be performing global synchronization on the entire
1626 // system for emitting rustc errors, so there's no need to buffer
1629 // On non-Windows we rely on the atomicity of `write` to ensure errors
1630 // don't get all jumbled up.
1632 Terminal(StandardStream::stderr(choice))
1634 Buffered(BufferWriter::stderr(choice))
1638 fn writable<'a>(&'a mut self) -> WritableDst<'a> {
1640 Destination::Terminal(ref mut t) => WritableDst::Terminal(t),
1641 Destination::Buffered(ref mut t) => {
1642 let buf = t.buffer();
1643 WritableDst::Buffered(t, buf)
1645 Destination::Raw(ref mut t, false) => WritableDst::Raw(t),
1646 Destination::Raw(ref mut t, true) => WritableDst::ColoredRaw(Ansi::new(t)),
1651 impl<'a> WritableDst<'a> {
1652 fn apply_style(&mut self, lvl: Level, style: Style) -> io::Result<()> {
1653 let mut spec = ColorSpec::new();
1655 Style::LineAndColumn => {}
1656 Style::LineNumber => {
1657 spec.set_bold(true);
1658 spec.set_intense(true);
1660 spec.set_fg(Some(Color::Cyan));
1662 spec.set_fg(Some(Color::Blue));
1665 Style::Quotation => {}
1666 Style::MainHeaderMsg => {
1667 spec.set_bold(true);
1669 spec.set_intense(true)
1670 .set_fg(Some(Color::White));
1673 Style::UnderlinePrimary | Style::LabelPrimary => {
1675 spec.set_bold(true);
1677 Style::UnderlineSecondary |
1678 Style::LabelSecondary => {
1682 spec.set_fg(Some(Color::Cyan));
1684 spec.set_fg(Some(Color::Blue));
1688 Style::NoStyle => {}
1689 Style::Level(lvl) => {
1691 spec.set_bold(true);
1693 Style::Highlight => {
1694 spec.set_bold(true);
1697 self.set_color(&spec)
1700 fn set_color(&mut self, color: &ColorSpec) -> io::Result<()> {
1702 WritableDst::Terminal(ref mut t) => t.set_color(color),
1703 WritableDst::Buffered(_, ref mut t) => t.set_color(color),
1704 WritableDst::ColoredRaw(ref mut t) => t.set_color(color),
1705 WritableDst::Raw(_) => Ok(())
1709 fn reset(&mut self) -> io::Result<()> {
1711 WritableDst::Terminal(ref mut t) => t.reset(),
1712 WritableDst::Buffered(_, ref mut t) => t.reset(),
1713 WritableDst::ColoredRaw(ref mut t) => t.reset(),
1714 WritableDst::Raw(_) => Ok(()),
1719 impl<'a> Write for WritableDst<'a> {
1720 fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
1722 WritableDst::Terminal(ref mut t) => t.write(bytes),
1723 WritableDst::Buffered(_, ref mut buf) => buf.write(bytes),
1724 WritableDst::Raw(ref mut w) => w.write(bytes),
1725 WritableDst::ColoredRaw(ref mut t) => t.write(bytes),
1729 fn flush(&mut self) -> io::Result<()> {
1731 WritableDst::Terminal(ref mut t) => t.flush(),
1732 WritableDst::Buffered(_, ref mut buf) => buf.flush(),
1733 WritableDst::Raw(ref mut w) => w.flush(),
1734 WritableDst::ColoredRaw(ref mut w) => w.flush(),
1739 impl<'a> Drop for WritableDst<'a> {
1740 fn drop(&mut self) {
1742 WritableDst::Buffered(ref mut dst, ref mut buf) => {
1743 drop(dst.print(buf));