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 trace.def_site_span.is_dummy() {
729 if always_backtrace {
730 new_labels.push((trace.def_site_span,
731 format!("in this expansion of `{}`{}",
732 trace.macro_decl_name,
733 if backtrace_len > 2 {
734 // if backtrace_len == 1 it'll be pointed
735 // at by "in this macro invocation"
736 format!(" (#{})", i + 1)
741 // Check to make sure we're not in any <*macros>
742 if !sm.span_to_filename(trace.def_site_span).is_macros() &&
743 !trace.macro_decl_name.starts_with("desugaring of ") &&
744 !trace.macro_decl_name.starts_with("#[") ||
746 new_labels.push((trace.call_site,
747 format!("in this macro invocation{}",
748 if backtrace_len > 2 && always_backtrace {
749 // only specify order when the macro
750 // backtrace is multiple levels deep
751 format!(" (#{})", i + 1)
755 if !always_backtrace {
761 for (label_span, label_text) in new_labels {
762 span.push_span_label(label_span, label_text);
764 for sp_label in span.span_labels() {
765 if sp_label.span.is_dummy() {
768 if sm.span_to_filename(sp_label.span.clone()).is_macros() &&
771 let v = sp_label.span.macro_backtrace();
772 if let Some(use_site) = v.last() {
773 before_after.push((sp_label.span.clone(), use_site.call_site.clone()));
777 // After we have them, make sure we replace these 'bad' def sites with their use sites
778 for (before, after) in before_after {
779 span.replace(before, after);
780 spans_updated = true;
787 // This does a small "fix" for multispans by looking to see if it can find any that
788 // point directly at <*macros>. Since these are often difficult to read, this
789 // will change the span to point at the use site.
790 fn fix_multispans_in_std_macros(&mut self,
791 span: &mut MultiSpan,
792 children: &mut Vec<SubDiagnostic>,
795 let mut spans_updated = self.fix_multispan_in_std_macros(span, backtrace);
796 for child in children.iter_mut() {
797 spans_updated |= self.fix_multispan_in_std_macros(&mut child.span, backtrace);
799 let msg = if level == &Error {
800 "this error originates in a macro outside of the current crate \
801 (in Nightly builds, run with -Z external-macro-backtrace \
802 for more info)".to_string()
804 "this warning originates in a macro outside of the current crate \
805 (in Nightly builds, run with -Z external-macro-backtrace \
806 for more info)".to_string()
810 children.push(SubDiagnostic {
816 span: MultiSpan::new(),
822 /// Adds a left margin to every line but the first, given a padding length and the label being
823 /// displayed, keeping the provided highlighting.
824 fn msg_to_buffer(&self,
825 buffer: &mut StyledBuffer,
826 msg: &[(String, Style)],
829 override_style: Option<Style>) {
831 // The extra 5 ` ` is padding that's always needed to align to the `note: `:
844 // | | length of label
846 // `max_line_num_len`
847 let padding = " ".repeat(padding + label.len() + 5);
849 /// Returns `true` if `style`, or the override if present and the style is `NoStyle`.
850 fn style_or_override(style: Style, override_style: Option<Style>) -> Style {
851 if let Some(o) = override_style {
852 if style == Style::NoStyle {
859 let mut line_number = 0;
861 // Provided the following diagnostic message:
865 // ("highlighted multiline\nstring to\nsee how it ", Style::NoStyle),
866 // ("looks", Style::Highlight),
867 // ("with\nvery ", Style::NoStyle),
868 // ("weird", Style::Highlight),
869 // (" formats\n", Style::NoStyle),
870 // ("see?", Style::Highlight),
873 // the expected output on a note is (* surround the highlighted text)
875 // = note: highlighted multiline
877 // see how it *looks* with
878 // very *weird* formats
880 for &(ref text, ref style) in msg.iter() {
881 let lines = text.split('\n').collect::<Vec<_>>();
883 for (i, line) in lines.iter().enumerate() {
886 buffer.append(line_number, &padding, Style::NoStyle);
888 buffer.append(line_number, line, style_or_override(*style, override_style));
891 buffer.append(line_number, text, style_or_override(*style, override_style));
896 fn emit_message_default(
899 msg: &[(String, Style)],
900 code: &Option<DiagnosticId>,
902 max_line_num_len: usize,
904 ) -> io::Result<()> {
905 let mut buffer = StyledBuffer::new();
906 let header_style = if is_secondary {
912 if !msp.has_primary_spans() && !msp.has_span_labels() && is_secondary
913 && !self.short_message {
914 // This is a secondary message with no span info
915 for _ in 0..max_line_num_len {
916 buffer.prepend(0, " ", Style::NoStyle);
918 draw_note_separator(&mut buffer, 0, max_line_num_len + 1);
919 let level_str = level.to_string();
920 if !level_str.is_empty() {
921 buffer.append(0, &level_str, Style::MainHeaderMsg);
922 buffer.append(0, ": ", Style::NoStyle);
924 self.msg_to_buffer(&mut buffer, msg, max_line_num_len, "note", None);
926 let level_str = level.to_string();
927 if !level_str.is_empty() {
928 buffer.append(0, &level_str, Style::Level(level.clone()));
930 // only render error codes, not lint codes
931 if let Some(DiagnosticId::Error(ref code)) = *code {
932 buffer.append(0, "[", Style::Level(level.clone()));
933 buffer.append(0, &code, Style::Level(level.clone()));
934 buffer.append(0, "]", Style::Level(level.clone()));
936 if !level_str.is_empty() {
937 buffer.append(0, ": ", header_style);
939 for &(ref text, _) in msg.iter() {
940 buffer.append(0, text, header_style);
944 let mut annotated_files = FileWithAnnotatedLines::collect_annotations(msp, &self.sm);
946 // Make sure our primary file comes first
947 let (primary_lo, sm) = if let (Some(sm), Some(ref primary_span)) =
948 (self.sm.as_ref(), msp.primary_span().as_ref()) {
949 if !primary_span.is_dummy() {
950 (sm.lookup_char_pos(primary_span.lo()), sm)
952 emit_to_destination(&buffer.render(), level, &mut self.dst, self.short_message)?;
956 // If we don't have span information, emit and exit
957 emit_to_destination(&buffer.render(), level, &mut self.dst, self.short_message)?;
961 annotated_files.binary_search_by(|x| x.file.name.cmp(&primary_lo.file.name)) {
962 annotated_files.swap(0, pos);
965 // Print out the annotate source lines that correspond with the error
966 for annotated_file in annotated_files {
967 // we can't annotate anything if the source is unavailable.
968 if !sm.ensure_source_file_source_present(annotated_file.file.clone()) {
972 // print out the span location and spacer before we print the annotated source
973 // to do this, we need to know if this span will be primary
974 let is_primary = primary_lo.file.name == annotated_file.file.name;
976 let loc = primary_lo.clone();
977 if !self.short_message {
978 // remember where we are in the output buffer for easy reference
979 let buffer_msg_line_offset = buffer.num_lines();
981 buffer.prepend(buffer_msg_line_offset, "--> ", Style::LineNumber);
982 buffer.append(buffer_msg_line_offset,
985 sm.doctest_offset_line(&loc.file.name, loc.line),
987 Style::LineAndColumn);
988 for _ in 0..max_line_num_len {
989 buffer.prepend(buffer_msg_line_offset, " ", Style::NoStyle);
993 &format!("{}:{}:{}: ",
995 sm.doctest_offset_line(&loc.file.name, loc.line),
997 Style::LineAndColumn);
999 } else if !self.short_message {
1000 // remember where we are in the output buffer for easy reference
1001 let buffer_msg_line_offset = buffer.num_lines();
1004 draw_col_separator(&mut buffer, buffer_msg_line_offset, max_line_num_len + 1);
1006 // Then, the secondary file indicator
1007 buffer.prepend(buffer_msg_line_offset + 1, "::: ", Style::LineNumber);
1008 let loc = if let Some(first_line) = annotated_file.lines.first() {
1009 let col = if let Some(first_annotation) = first_line.annotations.first() {
1010 format!(":{}", first_annotation.start_col + 1)
1015 annotated_file.file.name,
1016 sm.doctest_offset_line(
1017 &annotated_file.file.name, first_line.line_index),
1020 annotated_file.file.name.to_string()
1022 buffer.append(buffer_msg_line_offset + 1,
1024 Style::LineAndColumn);
1025 for _ in 0..max_line_num_len {
1026 buffer.prepend(buffer_msg_line_offset + 1, " ", Style::NoStyle);
1030 if !self.short_message {
1031 // Put in the spacer between the location and annotated source
1032 let buffer_msg_line_offset = buffer.num_lines();
1033 draw_col_separator_no_space(&mut buffer,
1034 buffer_msg_line_offset,
1035 max_line_num_len + 1);
1037 // Contains the vertical lines' positions for active multiline annotations
1038 let mut multilines = FxHashMap::default();
1040 // Next, output the annotate source for this file
1041 for line_idx in 0..annotated_file.lines.len() {
1042 let previous_buffer_line = buffer.num_lines();
1044 let width_offset = 3 + max_line_num_len;
1045 let code_offset = if annotated_file.multiline_depth == 0 {
1048 width_offset + annotated_file.multiline_depth + 1
1051 let depths = self.render_source_line(&mut buffer,
1052 annotated_file.file.clone(),
1053 &annotated_file.lines[line_idx],
1057 let mut to_add = FxHashMap::default();
1059 for (depth, style) in depths {
1060 if multilines.get(&depth).is_some() {
1061 multilines.remove(&depth);
1063 to_add.insert(depth, style);
1067 // Set the multiline annotation vertical lines to the left of
1068 // the code in this line.
1069 for (depth, style) in &multilines {
1070 for line in previous_buffer_line..buffer.num_lines() {
1071 draw_multiline_line(&mut buffer,
1078 // check to see if we need to print out or elide lines that come between
1079 // this annotated line and the next one.
1080 if line_idx < (annotated_file.lines.len() - 1) {
1081 let line_idx_delta = annotated_file.lines[line_idx + 1].line_index -
1082 annotated_file.lines[line_idx].line_index;
1083 if line_idx_delta > 2 {
1084 let last_buffer_line_num = buffer.num_lines();
1085 buffer.puts(last_buffer_line_num, 0, "...", Style::LineNumber);
1087 // Set the multiline annotation vertical lines on `...` bridging line.
1088 for (depth, style) in &multilines {
1089 draw_multiline_line(&mut buffer,
1090 last_buffer_line_num,
1095 } else if line_idx_delta == 2 {
1096 let unannotated_line = annotated_file.file
1097 .get_line(annotated_file.lines[line_idx].line_index)
1098 .unwrap_or_else(|| Cow::from(""));
1100 let last_buffer_line_num = buffer.num_lines();
1102 buffer.puts(last_buffer_line_num,
1104 &self.maybe_anonymized(annotated_file.lines[line_idx + 1]
1107 draw_col_separator(&mut buffer,
1108 last_buffer_line_num,
1109 1 + max_line_num_len);
1110 buffer.puts(last_buffer_line_num,
1115 for (depth, style) in &multilines {
1116 draw_multiline_line(&mut buffer,
1117 last_buffer_line_num,
1125 multilines.extend(&to_add);
1130 // final step: take our styled buffer, render it, then output it
1131 emit_to_destination(&buffer.render(), level, &mut self.dst, self.short_message)?;
1137 fn emit_suggestion_default(
1139 suggestion: &CodeSuggestion,
1141 max_line_num_len: usize,
1142 ) -> io::Result<()> {
1143 if let Some(ref sm) = self.sm {
1144 let mut buffer = StyledBuffer::new();
1146 // Render the suggestion message
1147 let level_str = level.to_string();
1148 if !level_str.is_empty() {
1149 buffer.append(0, &level_str, Style::Level(level.clone()));
1150 buffer.append(0, ": ", Style::HeaderMsg);
1154 &[(suggestion.msg.to_owned(), Style::NoStyle)],
1157 Some(Style::HeaderMsg),
1160 // Render the replacements for each suggestion
1161 let suggestions = suggestion.splice_lines(&**sm);
1163 let mut row_num = 2;
1164 for &(ref complete, ref parts) in suggestions.iter().take(MAX_SUGGESTIONS) {
1165 // Only show underline if the suggestion spans a single line and doesn't cover the
1166 // entirety of the code output. If you have multiple replacements in the same line
1167 // of code, show the underline.
1168 let show_underline = !(parts.len() == 1
1169 && parts[0].snippet.trim() == complete.trim())
1170 && complete.lines().count() == 1;
1172 let lines = sm.span_to_lines(parts[0].span).unwrap();
1174 assert!(!lines.lines.is_empty());
1176 let line_start = sm.lookup_char_pos(parts[0].span.lo()).line;
1177 draw_col_separator_no_space(&mut buffer, 1, max_line_num_len + 1);
1178 let mut line_pos = 0;
1179 let mut lines = complete.lines();
1180 for line in lines.by_ref().take(MAX_HIGHLIGHT_LINES) {
1181 // Print the span column to avoid confusion
1182 buffer.puts(row_num,
1184 &self.maybe_anonymized(line_start + line_pos),
1186 // print the suggestion
1187 draw_col_separator(&mut buffer, row_num, max_line_num_len + 1);
1188 buffer.append(row_num, line, Style::NoStyle);
1193 // This offset and the ones below need to be signed to account for replacement code
1194 // that is shorter than the original code.
1195 let mut offset: isize = 0;
1196 // Only show an underline in the suggestions if the suggestion is not the
1197 // entirety of the code being shown and the displayed code is not multiline.
1199 draw_col_separator(&mut buffer, row_num, max_line_num_len + 1);
1201 let span_start_pos = sm.lookup_char_pos(part.span.lo()).col_display;
1202 let span_end_pos = sm.lookup_char_pos(part.span.hi()).col_display;
1204 // Do not underline the leading...
1205 let start = part.snippet.len()
1206 .saturating_sub(part.snippet.trim_start().len());
1207 // ...or trailing spaces. Account for substitutions containing unicode
1209 let sub_len = part.snippet.trim().chars().fold(0, |acc, ch| {
1210 acc + unicode_width::UnicodeWidthChar::width(ch).unwrap_or(0)
1213 let underline_start = (span_start_pos + start) as isize + offset;
1214 let underline_end = (span_start_pos + start + sub_len) as isize + offset;
1215 for p in underline_start..underline_end {
1216 buffer.putc(row_num,
1217 max_line_num_len + 3 + p as usize,
1219 Style::UnderlinePrimary);
1221 // underline removals too
1222 if underline_start == underline_end {
1223 for p in underline_start-1..underline_start+1 {
1224 buffer.putc(row_num,
1225 max_line_num_len + 3 + p as usize,
1227 Style::UnderlineSecondary);
1231 // length of the code after substitution
1232 let full_sub_len = part.snippet.chars().fold(0, |acc, ch| {
1233 acc + unicode_width::UnicodeWidthChar::width(ch).unwrap_or(0) as isize
1236 // length of the code to be substituted
1237 let snippet_len = span_end_pos as isize - span_start_pos as isize;
1238 // For multiple substitutions, use the position *after* the previous
1239 // substitutions have happened.
1240 offset += full_sub_len - snippet_len;
1245 // if we elided some lines, add an ellipsis
1246 if lines.next().is_some() {
1247 buffer.puts(row_num, max_line_num_len - 1, "...", Style::LineNumber);
1248 } else if !show_underline {
1249 draw_col_separator_no_space(&mut buffer, row_num, max_line_num_len + 1);
1253 if suggestions.len() > MAX_SUGGESTIONS {
1254 let msg = format!("and {} other candidates", suggestions.len() - MAX_SUGGESTIONS);
1255 buffer.puts(row_num, 0, &msg, Style::NoStyle);
1257 emit_to_destination(&buffer.render(), level, &mut self.dst, self.short_message)?;
1262 fn emit_messages_default(&mut self,
1264 message: &[(String, Style)],
1265 code: &Option<DiagnosticId>,
1267 children: &[SubDiagnostic],
1268 suggestions: &[CodeSuggestion]) {
1269 let max_line_num_len = if self.ui_testing {
1270 ANONYMIZED_LINE_NUM.len()
1272 self.get_max_line_num(span, children).to_string().len()
1275 match self.emit_message_default(span,
1282 if !children.is_empty() {
1283 let mut buffer = StyledBuffer::new();
1284 if !self.short_message {
1285 draw_col_separator_no_space(&mut buffer, 0, max_line_num_len + 1);
1287 match emit_to_destination(&buffer.render(), level, &mut self.dst,
1288 self.short_message) {
1290 Err(e) => panic!("failed to emit error: {}", e)
1293 if !self.short_message {
1294 for child in children {
1295 let span = child.render_span.as_ref().unwrap_or(&child.span);
1296 match self.emit_message_default(
1298 &child.styled_message(),
1304 Err(e) => panic!("failed to emit error: {}", e),
1308 for sugg in suggestions {
1309 if sugg.style == SuggestionStyle::CompletelyHidden {
1310 // do not display this suggestion, it is meant only for tools
1311 } else if sugg.style == SuggestionStyle::HideCodeAlways {
1312 match self.emit_message_default(
1314 &[(sugg.msg.to_owned(), Style::HeaderMsg)],
1320 Err(e) => panic!("failed to emit error: {}", e),
1324 match self.emit_suggestion_default(
1329 Err(e) => panic!("failed to emit error: {}", e),
1336 Err(e) => panic!("failed to emit error: {}", e),
1339 let mut dst = self.dst.writable();
1340 match writeln!(dst) {
1341 Err(e) => panic!("failed to emit error: {}", e),
1344 Err(e) => panic!("failed to emit error: {}", e),
1352 impl FileWithAnnotatedLines {
1353 /// Preprocess all the annotations so that they are grouped by file and by line number
1354 /// This helps us quickly iterate over the whole message (including secondary file spans)
1355 pub fn collect_annotations(
1357 source_map: &Option<Lrc<SourceMapperDyn>>
1358 ) -> Vec<FileWithAnnotatedLines> {
1359 fn add_annotation_to_file(file_vec: &mut Vec<FileWithAnnotatedLines>,
1360 file: Lrc<SourceFile>,
1364 for slot in file_vec.iter_mut() {
1365 // Look through each of our files for the one we're adding to
1366 if slot.file.name == file.name {
1367 // See if we already have a line for it
1368 for line_slot in &mut slot.lines {
1369 if line_slot.line_index == line_index {
1370 line_slot.annotations.push(ann);
1374 // We don't have a line yet, create one
1375 slot.lines.push(Line {
1377 annotations: vec![ann],
1383 // This is the first time we're seeing the file
1384 file_vec.push(FileWithAnnotatedLines {
1388 annotations: vec![ann],
1394 let mut output = vec![];
1395 let mut multiline_annotations = vec![];
1397 if let Some(ref sm) = source_map {
1398 for span_label in msp.span_labels() {
1399 if span_label.span.is_dummy() {
1403 let lo = sm.lookup_char_pos(span_label.span.lo());
1404 let mut hi = sm.lookup_char_pos(span_label.span.hi());
1406 // Watch out for "empty spans". If we get a span like 6..6, we
1407 // want to just display a `^` at 6, so convert that to
1408 // 6..7. This is degenerate input, but it's best to degrade
1409 // gracefully -- and the parser likes to supply a span like
1410 // that for EOF, in particular.
1412 if lo.col_display == hi.col_display && lo.line == hi.line {
1413 hi.col_display += 1;
1416 let ann_type = if lo.line != hi.line {
1417 let ml = MultilineAnnotation {
1419 line_start: lo.line,
1421 start_col: lo.col_display,
1422 end_col: hi.col_display,
1423 is_primary: span_label.is_primary,
1424 label: span_label.label.clone(),
1425 overlaps_exactly: false,
1427 multiline_annotations.push((lo.file.clone(), ml.clone()));
1428 AnnotationType::Multiline(ml)
1430 AnnotationType::Singleline
1432 let ann = Annotation {
1433 start_col: lo.col_display,
1434 end_col: hi.col_display,
1435 is_primary: span_label.is_primary,
1436 label: span_label.label.clone(),
1437 annotation_type: ann_type,
1440 if !ann.is_multiline() {
1441 add_annotation_to_file(&mut output, lo.file, lo.line, ann);
1446 // Find overlapping multiline annotations, put them at different depths
1447 multiline_annotations.sort_by_key(|&(_, ref ml)| (ml.line_start, ml.line_end));
1448 for item in multiline_annotations.clone() {
1450 for item in multiline_annotations.iter_mut() {
1451 let ref mut a = item.1;
1452 // Move all other multiline annotations overlapping with this one
1453 // one level to the right.
1454 if !(ann.same_span(a)) &&
1455 num_overlap(ann.line_start, ann.line_end, a.line_start, a.line_end, true)
1458 } else if ann.same_span(a) && &ann != a {
1459 a.overlaps_exactly = true;
1466 let mut max_depth = 0; // max overlapping multiline spans
1467 for (file, ann) in multiline_annotations {
1468 if ann.depth > max_depth {
1469 max_depth = ann.depth;
1471 let mut end_ann = ann.as_end();
1472 if !ann.overlaps_exactly {
1473 // avoid output like
1495 add_annotation_to_file(&mut output, file.clone(), ann.line_start, ann.as_start());
1496 // 4 is the minimum vertical length of a multiline span when presented: two lines
1497 // of code and two lines of underline. This is not true for the special case where
1498 // the beginning doesn't have an underline, but the current logic seems to be
1499 // working correctly.
1500 let middle = min(ann.line_start + 4, ann.line_end);
1501 for line in ann.line_start + 1..middle {
1502 // Every `|` that joins the beginning of the span (`___^`) to the end (`|__^`).
1503 add_annotation_to_file(&mut output, file.clone(), line, ann.as_line());
1505 if middle < ann.line_end - 1 {
1506 for line in ann.line_end - 1..ann.line_end {
1507 add_annotation_to_file(&mut output, file.clone(), line, ann.as_line());
1511 end_ann.annotation_type = AnnotationType::Singleline;
1513 add_annotation_to_file(&mut output, file, ann.line_end, end_ann);
1515 for file_vec in output.iter_mut() {
1516 file_vec.multiline_depth = max_depth;
1522 fn draw_col_separator(buffer: &mut StyledBuffer, line: usize, col: usize) {
1523 buffer.puts(line, col, "| ", Style::LineNumber);
1526 fn draw_col_separator_no_space(buffer: &mut StyledBuffer, line: usize, col: usize) {
1527 draw_col_separator_no_space_with_style(buffer, line, col, Style::LineNumber);
1530 fn draw_col_separator_no_space_with_style(buffer: &mut StyledBuffer,
1534 buffer.putc(line, col, '|', style);
1537 fn draw_range(buffer: &mut StyledBuffer, symbol: char, line: usize,
1538 col_from: usize, col_to: usize, style: Style) {
1539 for col in col_from..col_to {
1540 buffer.putc(line, col, symbol, style);
1544 fn draw_note_separator(buffer: &mut StyledBuffer, line: usize, col: usize) {
1545 buffer.puts(line, col, "= ", Style::LineNumber);
1548 fn draw_multiline_line(buffer: &mut StyledBuffer,
1554 buffer.putc(line, offset + depth - 1, '|', style);
1557 fn num_overlap(a_start: usize, a_end: usize, b_start: usize, b_end:usize, inclusive: bool) -> bool {
1558 let extra = if inclusive {
1563 (b_start..b_end + extra).contains(&a_start) ||
1564 (a_start..a_end + extra).contains(&b_start)
1566 fn overlaps(a1: &Annotation, a2: &Annotation, padding: usize) -> bool {
1567 num_overlap(a1.start_col, a1.end_col + padding, a2.start_col, a2.end_col, false)
1570 fn emit_to_destination(rendered_buffer: &[Vec<StyledString>],
1572 dst: &mut Destination,
1573 short_message: bool)
1577 let mut dst = dst.writable();
1579 // In order to prevent error message interleaving, where multiple error lines get intermixed
1580 // when multiple compiler processes error simultaneously, we emit errors with additional
1583 // On Unix systems, we write into a buffered terminal rather than directly to a terminal. When
1584 // the .flush() is called we take the buffer created from the buffered writes and write it at
1585 // one shot. Because the Unix systems use ANSI for the colors, which is a text-based styling
1586 // scheme, this buffered approach works and maintains the styling.
1588 // On Windows, styling happens through calls to a terminal API. This prevents us from using the
1589 // same buffering approach. Instead, we use a global Windows mutex, which we acquire long
1590 // enough to output the full error message, then we release.
1591 let _buffer_lock = lock::acquire_global_lock("rustc_errors");
1592 for (pos, line) in rendered_buffer.iter().enumerate() {
1594 dst.apply_style(lvl.clone(), part.style)?;
1595 write!(dst, "{}", part.text)?;
1598 if !short_message && (!lvl.is_failure_note() || pos != rendered_buffer.len() - 1) {
1606 pub enum Destination {
1607 Terminal(StandardStream),
1608 Buffered(BufferWriter),
1609 // The bool denotes whether we should be emitting ansi color codes or not
1610 Raw(Box<(dyn Write + Send)>, bool),
1613 pub enum WritableDst<'a> {
1614 Terminal(&'a mut StandardStream),
1615 Buffered(&'a mut BufferWriter, Buffer),
1616 Raw(&'a mut (dyn Write + Send)),
1617 ColoredRaw(Ansi<&'a mut (dyn Write + Send)>),
1621 fn from_stderr(color: ColorConfig) -> Destination {
1622 let choice = color.to_color_choice();
1623 // On Windows we'll be performing global synchronization on the entire
1624 // system for emitting rustc errors, so there's no need to buffer
1627 // On non-Windows we rely on the atomicity of `write` to ensure errors
1628 // don't get all jumbled up.
1630 Terminal(StandardStream::stderr(choice))
1632 Buffered(BufferWriter::stderr(choice))
1636 fn writable(&mut self) -> WritableDst<'_> {
1638 Destination::Terminal(ref mut t) => WritableDst::Terminal(t),
1639 Destination::Buffered(ref mut t) => {
1640 let buf = t.buffer();
1641 WritableDst::Buffered(t, buf)
1643 Destination::Raw(ref mut t, false) => WritableDst::Raw(t),
1644 Destination::Raw(ref mut t, true) => WritableDst::ColoredRaw(Ansi::new(t)),
1649 impl<'a> WritableDst<'a> {
1650 fn apply_style(&mut self, lvl: Level, style: Style) -> io::Result<()> {
1651 let mut spec = ColorSpec::new();
1653 Style::LineAndColumn => {}
1654 Style::LineNumber => {
1655 spec.set_bold(true);
1656 spec.set_intense(true);
1658 spec.set_fg(Some(Color::Cyan));
1660 spec.set_fg(Some(Color::Blue));
1663 Style::Quotation => {}
1664 Style::MainHeaderMsg => {
1665 spec.set_bold(true);
1667 spec.set_intense(true)
1668 .set_fg(Some(Color::White));
1671 Style::UnderlinePrimary | Style::LabelPrimary => {
1673 spec.set_bold(true);
1675 Style::UnderlineSecondary |
1676 Style::LabelSecondary => {
1680 spec.set_fg(Some(Color::Cyan));
1682 spec.set_fg(Some(Color::Blue));
1686 Style::NoStyle => {}
1687 Style::Level(lvl) => {
1689 spec.set_bold(true);
1691 Style::Highlight => {
1692 spec.set_bold(true);
1695 self.set_color(&spec)
1698 fn set_color(&mut self, color: &ColorSpec) -> io::Result<()> {
1700 WritableDst::Terminal(ref mut t) => t.set_color(color),
1701 WritableDst::Buffered(_, ref mut t) => t.set_color(color),
1702 WritableDst::ColoredRaw(ref mut t) => t.set_color(color),
1703 WritableDst::Raw(_) => Ok(())
1707 fn reset(&mut self) -> io::Result<()> {
1709 WritableDst::Terminal(ref mut t) => t.reset(),
1710 WritableDst::Buffered(_, ref mut t) => t.reset(),
1711 WritableDst::ColoredRaw(ref mut t) => t.reset(),
1712 WritableDst::Raw(_) => Ok(()),
1717 impl<'a> Write for WritableDst<'a> {
1718 fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
1720 WritableDst::Terminal(ref mut t) => t.write(bytes),
1721 WritableDst::Buffered(_, ref mut buf) => buf.write(bytes),
1722 WritableDst::Raw(ref mut w) => w.write(bytes),
1723 WritableDst::ColoredRaw(ref mut t) => t.write(bytes),
1727 fn flush(&mut self) -> io::Result<()> {
1729 WritableDst::Terminal(ref mut t) => t.flush(),
1730 WritableDst::Buffered(_, ref mut buf) => buf.flush(),
1731 WritableDst::Raw(ref mut w) => w.flush(),
1732 WritableDst::ColoredRaw(ref mut w) => w.flush(),
1737 impl<'a> Drop for WritableDst<'a> {
1738 fn drop(&mut self) {
1740 WritableDst::Buffered(ref mut dst, ref mut buf) => {
1741 drop(dst.print(buf));