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::{DUMMY_SP, FileMap, Span, MultiSpan};
15 use {Level, CodeSuggestion, DiagnosticBuilder, SubDiagnostic, CodeMapper, DiagnosticId};
17 use snippet::{Annotation, AnnotationType, Line, MultilineAnnotation, StyledString, Style};
18 use styled_buffer::StyledBuffer;
21 use std::io::prelude::*;
25 use std::collections::HashMap;
28 /// Emitter trait for emitting errors.
30 /// Emit a structured diagnostic.
31 fn emit(&mut self, db: &DiagnosticBuilder);
34 impl Emitter for EmitterWriter {
35 fn emit(&mut self, db: &DiagnosticBuilder) {
36 let mut primary_span = db.span.clone();
37 let mut children = db.children.clone();
39 if let Some((sugg, rest)) = db.suggestions.split_first() {
41 // don't display multi-suggestions as labels
42 sugg.substitutions.len() == 1 &&
43 // don't display multipart suggestions as labels
44 sugg.substitutions[0].parts.len() == 1 &&
45 // don't display long messages as labels
46 sugg.msg.split_whitespace().count() < 10 &&
47 // don't display multiline suggestions as labels
48 !sugg.substitutions[0].parts[0].snippet.contains('\n') {
49 let substitution = &sugg.substitutions[0].parts[0].snippet;
50 let msg = if substitution.len() == 0 || !sugg.show_code_when_inline {
51 // This substitution is only removal or we explicitly don't want to show the
52 // code inline, don't show it
53 format!("help: {}", sugg.msg)
55 format!("help: {}: `{}`", sugg.msg, substitution)
57 primary_span.push_span_label(sugg.substitutions[0].parts[0].span, msg);
59 // if there are multiple suggestions, print them all in full
60 // to be consistent. We could try to figure out if we can
61 // make one (or the first one) inline, but that would give
62 // undue importance to a semi-random suggestion
63 for sugg in &db.suggestions {
64 children.push(SubDiagnostic {
67 span: MultiSpan::new(),
68 render_span: Some(Suggestion(sugg.clone())),
74 self.fix_multispans_in_std_macros(&mut primary_span, &mut children);
75 self.emit_messages_default(&db.level,
83 /// maximum number of lines we will print for each error; arbitrary.
84 pub const MAX_HIGHLIGHT_LINES: usize = 6;
85 /// maximum number of suggestions to be shown
87 /// Arbitrary, but taken from trait import suggestion limit
88 pub const MAX_SUGGESTIONS: usize = 4;
90 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
91 pub enum ColorConfig {
98 fn use_color(&self) -> bool {
100 ColorConfig::Always => true,
101 ColorConfig::Never => false,
102 ColorConfig::Auto => stderr_isatty(),
107 pub struct EmitterWriter {
109 cm: Option<Rc<CodeMapper>>,
113 struct FileWithAnnotatedLines {
116 multiline_depth: usize,
120 pub fn stderr(color_config: ColorConfig,
121 code_map: Option<Rc<CodeMapper>>,
124 if color_config.use_color() {
125 let dst = Destination::from_stderr();
129 short_message: short_message,
133 dst: Raw(Box::new(io::stderr())),
135 short_message: short_message,
140 pub fn new(dst: Box<Write + Send>,
141 code_map: Option<Rc<CodeMapper>>,
147 short_message: short_message,
151 fn preprocess_annotations(&mut self, msp: &MultiSpan) -> Vec<FileWithAnnotatedLines> {
152 fn add_annotation_to_file(file_vec: &mut Vec<FileWithAnnotatedLines>,
157 for slot in file_vec.iter_mut() {
158 // Look through each of our files for the one we're adding to
159 if slot.file.name == file.name {
160 // See if we already have a line for it
161 for line_slot in &mut slot.lines {
162 if line_slot.line_index == line_index {
163 line_slot.annotations.push(ann);
167 // We don't have a line yet, create one
168 slot.lines.push(Line {
170 annotations: vec![ann],
176 // This is the first time we're seeing the file
177 file_vec.push(FileWithAnnotatedLines {
181 annotations: vec![ann],
187 let mut output = vec![];
188 let mut multiline_annotations = vec![];
190 if let Some(ref cm) = self.cm {
191 for span_label in msp.span_labels() {
192 if span_label.span == DUMMY_SP {
196 let lo = cm.lookup_char_pos(span_label.span.lo());
197 let mut hi = cm.lookup_char_pos(span_label.span.hi());
199 // Watch out for "empty spans". If we get a span like 6..6, we
200 // want to just display a `^` at 6, so convert that to
201 // 6..7. This is degenerate input, but it's best to degrade
202 // gracefully -- and the parser likes to supply a span like
203 // that for EOF, in particular.
204 if lo.col_display == hi.col_display && lo.line == hi.line {
208 let ann_type = if lo.line != hi.line {
209 let ml = MultilineAnnotation {
213 start_col: lo.col_display,
214 end_col: hi.col_display,
215 is_primary: span_label.is_primary,
216 label: span_label.label.clone(),
218 multiline_annotations.push((lo.file.clone(), ml.clone()));
219 AnnotationType::Multiline(ml)
221 AnnotationType::Singleline
223 let ann = Annotation {
224 start_col: lo.col_display,
225 end_col: hi.col_display,
226 is_primary: span_label.is_primary,
227 label: span_label.label.clone(),
228 annotation_type: ann_type,
231 if !ann.is_multiline() {
232 add_annotation_to_file(&mut output,
240 // Find overlapping multiline annotations, put them at different depths
241 multiline_annotations.sort_by(|a, b| {
242 (a.1.line_start, a.1.line_end).cmp(&(b.1.line_start, b.1.line_end))
244 for item in multiline_annotations.clone() {
246 for item in multiline_annotations.iter_mut() {
247 let ref mut a = item.1;
248 // Move all other multiline annotations overlapping with this one
249 // one level to the right.
251 num_overlap(ann.line_start, ann.line_end, a.line_start, a.line_end, true)
260 let mut max_depth = 0; // max overlapping multiline spans
261 for (file, ann) in multiline_annotations {
262 if ann.depth > max_depth {
263 max_depth = ann.depth;
265 add_annotation_to_file(&mut output, file.clone(), ann.line_start, ann.as_start());
266 let middle = min(ann.line_start + 4, ann.line_end);
267 for line in ann.line_start + 1..middle {
268 add_annotation_to_file(&mut output, file.clone(), line, ann.as_line());
270 if middle < ann.line_end - 1 {
271 for line in ann.line_end - 1..ann.line_end {
272 add_annotation_to_file(&mut output, file.clone(), line, ann.as_line());
275 add_annotation_to_file(&mut output, file, ann.line_end, ann.as_end());
277 for file_vec in output.iter_mut() {
278 file_vec.multiline_depth = max_depth;
283 fn render_source_line(&self,
284 buffer: &mut StyledBuffer,
288 code_offset: usize) -> Vec<(usize, Style)> {
289 let source_string = match file.get_line(line.line_index - 1) {
291 None => return Vec::new(),
294 let line_offset = buffer.num_lines();
296 // First create the source line we will highlight.
297 buffer.puts(line_offset, code_offset, &source_string, Style::Quotation);
298 buffer.puts(line_offset,
300 &(line.line_index.to_string()),
303 draw_col_separator(buffer, line_offset, width_offset - 2);
305 // Special case when there's only one annotation involved, it is the start of a multiline
306 // span and there's no text at the beginning of the code line. Instead of doing the whole
315 // we simplify the output to:
321 if line.annotations.len() == 1 {
322 if let Some(ref ann) = line.annotations.get(0) {
323 if let AnnotationType::MultilineStart(depth) = ann.annotation_type {
324 if source_string.chars()
326 .all(|c| c.is_whitespace()) {
327 let style = if ann.is_primary {
328 Style::UnderlinePrimary
330 Style::UnderlineSecondary
332 buffer.putc(line_offset,
333 width_offset + depth - 1,
336 return vec![(depth, style)];
342 // We want to display like this:
344 // vec.push(vec.pop().unwrap());
345 // --- ^^^ - previous borrow ends here
347 // | error occurs here
348 // previous borrow of `vec` occurs here
350 // But there are some weird edge cases to be aware of:
352 // vec.push(vec.pop().unwrap());
353 // -------- - previous borrow ends here
355 // |this makes no sense
356 // previous borrow of `vec` occurs here
358 // For this reason, we group the lines into "highlight lines"
359 // and "annotations lines", where the highlight lines have the `^`.
361 // Sort the annotations by (start, end col)
362 // The labels are reversed, sort and then reversed again.
363 // Consider a list of annotations (A1, A2, C1, C2, B1, B2) where
364 // the letter signifies the span. Here we are only sorting by the
365 // span and hence, the order of the elements with the same span will
366 // not change. On reversing the ordering (|a, b| but b.cmp(a)), you get
367 // (C1, C2, B1, B2, A1, A2). All the elements with the same span are
368 // still ordered first to last, but all the elements with different
369 // spans are ordered by their spans in last to first order. Last to
370 // first order is important, because the jiggly lines and | are on
371 // the left, so the rightmost span needs to be rendered first,
372 // otherwise the lines would end up needing to go over a message.
374 let mut annotations = line.annotations.clone();
375 annotations.sort_by(|a,b| b.start_col.cmp(&a.start_col));
377 // First, figure out where each label will be positioned.
379 // In the case where you have the following annotations:
381 // vec.push(vec.pop().unwrap());
382 // -------- - previous borrow ends here [C]
384 // |this makes no sense [B]
385 // previous borrow of `vec` occurs here [A]
387 // `annotations_position` will hold [(2, A), (1, B), (0, C)].
389 // We try, when possible, to stick the rightmost annotation at the end
390 // of the highlight line:
392 // vec.push(vec.pop().unwrap());
393 // --- --- - previous borrow ends here
395 // But sometimes that's not possible because one of the other
396 // annotations overlaps it. For example, from the test
397 // `span_overlap_label`, we have the following annotations
398 // (written on distinct lines for clarity):
404 // In this case, we can't stick the rightmost-most label on
405 // the highlight line, or we would get:
412 // which is totally weird. Instead we want:
420 // which is...less weird, at least. In fact, in general, if
421 // the rightmost span overlaps with any other span, we should
422 // use the "hang below" version, so we can at least make it
423 // clear where the span *starts*. There's an exception for this
424 // logic, when the labels do not have a message:
439 let mut annotations_position = vec![];
440 let mut line_len = 0;
442 for (i, annotation) in annotations.iter().enumerate() {
443 for (j, next) in annotations.iter().enumerate() {
444 if overlaps(next, annotation, 0) // This label overlaps with another one and both
445 && annotation.has_label() // take space (they have text and are not
446 && j > i // multiline lines).
447 && p == 0 // We're currently on the first line, move the label one line down
449 // This annotation needs a new line in the output.
454 annotations_position.push((p, annotation));
455 for (j, next) in annotations.iter().enumerate() {
457 let l = if let Some(ref label) = next.label {
462 if (overlaps(next, annotation, l) // Do not allow two labels to be in the same
463 // line if they overlap including padding, to
464 // avoid situations like:
471 && annotation.has_label() // Both labels must have some text, otherwise
472 && next.has_label()) // they are not overlapping.
473 // Do not add a new line if this annotation
474 // or the next are vertical line placeholders.
475 || (annotation.takes_space() // If either this or the next annotation is
476 && next.has_label()) // multiline start/end, move it to a new line
477 || (annotation.has_label() // so as not to overlap the orizontal lines.
478 && next.takes_space())
479 || (annotation.takes_space() && next.takes_space())
480 || (overlaps(next, annotation, l)
481 && next.end_col <= annotation.end_col
483 && p == 0) // Avoid #42595.
485 // This annotation needs a new line in the output.
500 // If there are no annotations or the only annotations on this line are
501 // MultilineLine, then there's only code being shown, stop processing.
502 if line.annotations.is_empty() || line.annotations.iter()
503 .filter(|a| !a.is_line()).collect::<Vec<_>>().len() == 0
508 // Write the colunmn separator.
510 // After this we will have:
519 for pos in 0..line_len + 1 {
520 draw_col_separator(buffer, line_offset + pos + 1, width_offset - 2);
521 buffer.putc(line_offset + pos + 1,
527 // Write the horizontal lines for multiline annotations
528 // (only the first and last lines need this).
530 // After this we will have:
539 for &(pos, annotation) in &annotations_position {
540 let style = if annotation.is_primary {
541 Style::UnderlinePrimary
543 Style::UnderlineSecondary
546 match annotation.annotation_type {
547 AnnotationType::MultilineStart(depth) |
548 AnnotationType::MultilineEnd(depth) => {
552 width_offset + depth,
553 code_offset + annotation.start_col,
560 // Write the vertical lines for labels that are on a different line as the underline.
562 // After this we will have:
571 for &(pos, annotation) in &annotations_position {
572 let style = if annotation.is_primary {
573 Style::UnderlinePrimary
575 Style::UnderlineSecondary
579 if pos > 1 && (annotation.has_label() || annotation.takes_space()) {
580 for p in line_offset + 1..line_offset + pos + 1 {
582 code_offset + annotation.start_col,
587 match annotation.annotation_type {
588 AnnotationType::MultilineStart(depth) => {
589 for p in line_offset + pos + 1..line_offset + line_len + 2 {
591 width_offset + depth - 1,
596 AnnotationType::MultilineEnd(depth) => {
597 for p in line_offset..line_offset + pos + 1 {
599 width_offset + depth - 1,
608 // Write the labels on the annotations that actually have a label.
610 // After this we will have:
615 // | something about `foo`
619 for &(pos, annotation) in &annotations_position {
620 let style = if annotation.is_primary {
623 Style::LabelSecondary
625 let (pos, col) = if pos == 0 {
626 (pos + 1, annotation.end_col + 1)
628 (pos + 2, annotation.start_col)
630 if let Some(ref label) = annotation.label {
631 buffer.puts(line_offset + pos,
638 // Sort from biggest span to smallest span so that smaller spans are
639 // represented in the output:
644 // | | something about `foo`
645 // | something about `fn foo()`
646 annotations_position.sort_by(|a, b| {
648 a.1.len().cmp(&b.1.len()).reverse()
651 // Write the underlines.
653 // After this we will have:
658 // | something about `foo`
662 for &(_, annotation) in &annotations_position {
663 let (underline, style) = if annotation.is_primary {
664 ('^', Style::UnderlinePrimary)
666 ('-', Style::UnderlineSecondary)
668 for p in annotation.start_col..annotation.end_col {
669 buffer.putc(line_offset + 1,
675 annotations_position.iter().filter_map(|&(_, annotation)| {
676 match annotation.annotation_type {
677 AnnotationType::MultilineStart(p) | AnnotationType::MultilineEnd(p) => {
678 let style = if annotation.is_primary {
681 Style::LabelSecondary
688 }).collect::<Vec<_>>()
691 fn get_multispan_max_line_num(&mut self, msp: &MultiSpan) -> usize {
693 if let Some(ref cm) = self.cm {
694 for primary_span in msp.primary_spans() {
695 if primary_span != &DUMMY_SP {
696 let hi = cm.lookup_char_pos(primary_span.hi());
702 if !self.short_message {
703 for span_label in msp.span_labels() {
704 if span_label.span != DUMMY_SP {
705 let hi = cm.lookup_char_pos(span_label.span.hi());
716 fn get_max_line_num(&mut self, span: &MultiSpan, children: &Vec<SubDiagnostic>) -> usize {
719 let primary = self.get_multispan_max_line_num(span);
720 max = if primary > max { primary } else { max };
722 for sub in children {
723 let sub_result = self.get_multispan_max_line_num(&sub.span);
724 max = if sub_result > max { primary } else { max };
729 // This "fixes" MultiSpans that contain Spans that are pointing to locations inside of
730 // <*macros>. Since these locations are often difficult to read, we move these Spans from
731 // <*macros> to their corresponding use site.
732 fn fix_multispan_in_std_macros(&mut self, span: &mut MultiSpan) -> bool {
733 let mut spans_updated = false;
735 if let Some(ref cm) = self.cm {
736 let mut before_after: Vec<(Span, Span)> = vec![];
737 let mut new_labels: Vec<(Span, String)> = vec![];
739 // First, find all the spans in <*macros> and point instead at their use site
740 for sp in span.primary_spans() {
744 let call_sp = cm.call_span_if_macro(*sp);
746 before_after.push((sp.clone(), call_sp));
748 for trace in sp.macro_backtrace().iter().rev() {
749 // Only show macro locations that are local
750 // and display them like a span_note
751 if let Some(def_site) = trace.def_site_span {
752 if def_site == DUMMY_SP {
755 // Check to make sure we're not in any <*macros>
756 if !cm.span_to_filename(def_site).contains("macros>") &&
757 !trace.macro_decl_name.starts_with("#[") {
758 new_labels.push((trace.call_site,
759 "in this macro invocation".to_string()));
765 for (label_span, label_text) in new_labels {
766 span.push_span_label(label_span, label_text);
768 for sp_label in span.span_labels() {
769 if sp_label.span == DUMMY_SP {
772 if cm.span_to_filename(sp_label.span.clone()).contains("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>) {
795 let mut spans_updated = self.fix_multispan_in_std_macros(span);
796 for child in children.iter_mut() {
797 spans_updated |= self.fix_multispan_in_std_macros(&mut child.span);
800 children.push(SubDiagnostic {
802 message: vec![("this error originates in a macro outside of the current crate"
803 .to_string(), Style::NoStyle)],
804 span: MultiSpan::new(),
810 /// Add a left margin to every line but the first, given a padding length and the label being
811 /// displayed, keeping the provided highlighting.
812 fn msg_to_buffer(&self,
813 buffer: &mut StyledBuffer,
814 msg: &[(String, Style)],
817 override_style: Option<Style>) {
819 // The extra 5 ` ` is padding that's always needed to align to the `note: `:
832 // | | length of label
834 // `max_line_num_len`
835 let padding = (0..padding + label.len() + 5)
837 .collect::<String>();
839 /// Return whether `style`, or the override if present and the style is `NoStyle`.
840 fn style_or_override(style: Style, override_style: Option<Style>) -> Style {
841 if let Some(o) = override_style {
842 if style == Style::NoStyle {
849 let mut line_number = 0;
851 // Provided the following diagnostic message:
855 // ("highlighted multiline\nstring to\nsee how it ", Style::NoStyle),
856 // ("looks", Style::Highlight),
857 // ("with\nvery ", Style::NoStyle),
858 // ("weird", Style::Highlight),
859 // (" formats\n", Style::NoStyle),
860 // ("see?", Style::Highlight),
863 // the expected output on a note is (* surround the highlighted text)
865 // = note: highlighted multiline
867 // see how it *looks* with
868 // very *weird* formats
870 for &(ref text, ref style) in msg.iter() {
871 let lines = text.split('\n').collect::<Vec<_>>();
873 for (i, line) in lines.iter().enumerate() {
876 buffer.append(line_number, &padding, Style::NoStyle);
878 buffer.append(line_number, line, style_or_override(*style, override_style));
881 buffer.append(line_number, text, style_or_override(*style, override_style));
886 fn emit_message_default(&mut self,
888 msg: &Vec<(String, Style)>,
889 code: &Option<DiagnosticId>,
891 max_line_num_len: usize,
894 let mut buffer = StyledBuffer::new();
896 if msp.primary_spans().is_empty() && msp.span_labels().is_empty() && is_secondary
897 && !self.short_message {
898 // This is a secondary message with no span info
899 for _ in 0..max_line_num_len {
900 buffer.prepend(0, " ", Style::NoStyle);
902 draw_note_separator(&mut buffer, 0, max_line_num_len + 1);
903 buffer.append(0, &level.to_string(), Style::HeaderMsg);
904 buffer.append(0, ": ", Style::NoStyle);
905 self.msg_to_buffer(&mut buffer, msg, max_line_num_len, "note", None);
907 buffer.append(0, &level.to_string(), Style::Level(level.clone()));
908 // only render error codes, not lint codes
909 if let Some(DiagnosticId::Error(ref code)) = *code {
910 buffer.append(0, "[", Style::Level(level.clone()));
911 buffer.append(0, &code, Style::Level(level.clone()));
912 buffer.append(0, "]", Style::Level(level.clone()));
914 buffer.append(0, ": ", Style::HeaderMsg);
915 for &(ref text, _) in msg.iter() {
916 buffer.append(0, text, Style::HeaderMsg);
920 // Preprocess all the annotations so that they are grouped by file and by line number
921 // This helps us quickly iterate over the whole message (including secondary file spans)
922 let mut annotated_files = self.preprocess_annotations(msp);
924 // Make sure our primary file comes first
925 let (primary_lo, cm) = if let (Some(cm), Some(ref primary_span)) =
926 (self.cm.as_ref(), msp.primary_span().as_ref()) {
927 if primary_span != &&DUMMY_SP {
928 (cm.lookup_char_pos(primary_span.lo()), cm)
930 emit_to_destination(&buffer.render(), level, &mut self.dst, self.short_message)?;
934 // If we don't have span information, emit and exit
935 emit_to_destination(&buffer.render(), level, &mut self.dst, self.short_message)?;
939 annotated_files.binary_search_by(|x| x.file.name.cmp(&primary_lo.file.name)) {
940 annotated_files.swap(0, pos);
943 // Print out the annotate source lines that correspond with the error
944 for annotated_file in annotated_files {
945 // we can't annotate anything if the source is unavailable.
946 if !cm.ensure_filemap_source_present(annotated_file.file.clone()) {
950 // print out the span location and spacer before we print the annotated source
951 // to do this, we need to know if this span will be primary
952 let is_primary = primary_lo.file.name == annotated_file.file.name;
954 let loc = primary_lo.clone();
955 if !self.short_message {
956 // remember where we are in the output buffer for easy reference
957 let buffer_msg_line_offset = buffer.num_lines();
959 buffer.prepend(buffer_msg_line_offset, "--> ", Style::LineNumber);
960 buffer.append(buffer_msg_line_offset,
961 &format!("{}:{}:{}", loc.file.name, loc.line, loc.col.0 + 1),
962 Style::LineAndColumn);
963 for _ in 0..max_line_num_len {
964 buffer.prepend(buffer_msg_line_offset, " ", Style::NoStyle);
968 &format!("{}:{}:{} - ", loc.file.name, loc.line, loc.col.0 + 1),
969 Style::LineAndColumn);
971 } else if !self.short_message {
972 // remember where we are in the output buffer for easy reference
973 let buffer_msg_line_offset = buffer.num_lines();
976 draw_col_separator(&mut buffer, buffer_msg_line_offset, max_line_num_len + 1);
978 // Then, the secondary file indicator
979 buffer.prepend(buffer_msg_line_offset + 1, "::: ", Style::LineNumber);
980 buffer.append(buffer_msg_line_offset + 1,
981 &annotated_file.file.name,
982 Style::LineAndColumn);
983 for _ in 0..max_line_num_len {
984 buffer.prepend(buffer_msg_line_offset + 1, " ", Style::NoStyle);
988 if !self.short_message {
989 // Put in the spacer between the location and annotated source
990 let buffer_msg_line_offset = buffer.num_lines();
991 draw_col_separator_no_space(&mut buffer,
992 buffer_msg_line_offset,
993 max_line_num_len + 1);
995 // Contains the vertical lines' positions for active multiline annotations
996 let mut multilines = HashMap::new();
998 // Next, output the annotate source for this file
999 for line_idx in 0..annotated_file.lines.len() {
1000 let previous_buffer_line = buffer.num_lines();
1002 let width_offset = 3 + max_line_num_len;
1003 let code_offset = if annotated_file.multiline_depth == 0 {
1006 width_offset + annotated_file.multiline_depth + 1
1009 let depths = self.render_source_line(&mut buffer,
1010 annotated_file.file.clone(),
1011 &annotated_file.lines[line_idx],
1015 let mut to_add = HashMap::new();
1017 for (depth, style) in depths {
1018 if multilines.get(&depth).is_some() {
1019 multilines.remove(&depth);
1021 to_add.insert(depth, style);
1025 // Set the multiline annotation vertical lines to the left of
1026 // the code in this line.
1027 for (depth, style) in &multilines {
1028 for line in previous_buffer_line..buffer.num_lines() {
1029 draw_multiline_line(&mut buffer,
1036 // check to see if we need to print out or elide lines that come between
1037 // this annotated line and the next one.
1038 if line_idx < (annotated_file.lines.len() - 1) {
1039 let line_idx_delta = annotated_file.lines[line_idx + 1].line_index -
1040 annotated_file.lines[line_idx].line_index;
1041 if line_idx_delta > 2 {
1042 let last_buffer_line_num = buffer.num_lines();
1043 buffer.puts(last_buffer_line_num, 0, "...", Style::LineNumber);
1045 // Set the multiline annotation vertical lines on `...` bridging line.
1046 for (depth, style) in &multilines {
1047 draw_multiline_line(&mut buffer,
1048 last_buffer_line_num,
1053 } else if line_idx_delta == 2 {
1054 let unannotated_line = annotated_file.file
1055 .get_line(annotated_file.lines[line_idx].line_index)
1056 .unwrap_or_else(|| Cow::from(""));
1058 let last_buffer_line_num = buffer.num_lines();
1060 buffer.puts(last_buffer_line_num,
1062 &(annotated_file.lines[line_idx + 1].line_index - 1)
1065 draw_col_separator(&mut buffer,
1066 last_buffer_line_num,
1067 1 + max_line_num_len);
1068 buffer.puts(last_buffer_line_num,
1073 for (depth, style) in &multilines {
1074 draw_multiline_line(&mut buffer,
1075 last_buffer_line_num,
1083 multilines.extend(&to_add);
1088 // final step: take our styled buffer, render it, then output it
1089 emit_to_destination(&buffer.render(), level, &mut self.dst, self.short_message)?;
1094 fn emit_suggestion_default(&mut self,
1095 suggestion: &CodeSuggestion,
1097 max_line_num_len: usize)
1099 use std::borrow::Borrow;
1101 if let Some(ref cm) = self.cm {
1102 let mut buffer = StyledBuffer::new();
1104 // Render the suggestion message
1105 buffer.append(0, &level.to_string(), Style::Level(level.clone()));
1106 buffer.append(0, ": ", Style::HeaderMsg);
1107 self.msg_to_buffer(&mut buffer,
1108 &[(suggestion.msg.to_owned(), Style::NoStyle)],
1111 Some(Style::HeaderMsg));
1113 // Render the replacements for each suggestion
1114 let suggestions = suggestion.splice_lines(cm.borrow());
1116 let mut row_num = 2;
1117 for &(ref complete, ref parts) in suggestions.iter().take(MAX_SUGGESTIONS) {
1118 let show_underline = parts.len() == 1
1119 && complete.lines().count() == 1
1120 && parts[0].snippet.trim() != complete.trim();
1122 let lines = cm.span_to_lines(parts[0].span).unwrap();
1124 assert!(!lines.lines.is_empty());
1126 let span_start_pos = cm.lookup_char_pos(parts[0].span.lo());
1127 let line_start = span_start_pos.line;
1128 draw_col_separator_no_space(&mut buffer, 1, max_line_num_len + 1);
1129 let mut line_pos = 0;
1130 // Only show underline if there's a single suggestion and it is a single line
1131 let mut lines = complete.lines();
1132 for line in lines.by_ref().take(MAX_HIGHLIGHT_LINES) {
1133 // Print the span column to avoid confusion
1134 buffer.puts(row_num,
1136 &((line_start + line_pos).to_string()),
1138 // print the suggestion
1139 draw_col_separator(&mut buffer, row_num, max_line_num_len + 1);
1140 buffer.append(row_num, line, Style::NoStyle);
1144 // Only show an underline in the suggestions if the suggestion is not the
1145 // entirety of the code being shown and the displayed code is not multiline.
1147 draw_col_separator(&mut buffer, row_num, max_line_num_len + 1);
1148 let start = parts[0].snippet.len() - parts[0].snippet.trim_left().len();
1149 let sub_len = parts[0].snippet.trim().len();
1150 let underline_start = span_start_pos.col.0 + start;
1151 let underline_end = span_start_pos.col.0 + sub_len;
1152 for p in underline_start..underline_end {
1153 buffer.putc(row_num,
1154 max_line_num_len + 3 + p,
1156 Style::UnderlinePrimary);
1161 // if we elided some lines, add an ellipsis
1162 if let Some(_) = lines.next() {
1163 buffer.puts(row_num, max_line_num_len - 1, "...", Style::LineNumber);
1164 } else if !show_underline {
1165 draw_col_separator_no_space(&mut buffer, row_num, max_line_num_len + 1);
1169 if suggestions.len() > MAX_SUGGESTIONS {
1170 let msg = format!("and {} other candidates", suggestions.len() - MAX_SUGGESTIONS);
1171 buffer.puts(row_num, 0, &msg, Style::NoStyle);
1173 emit_to_destination(&buffer.render(), level, &mut self.dst, self.short_message)?;
1177 fn emit_messages_default(&mut self,
1179 message: &Vec<(String, Style)>,
1180 code: &Option<DiagnosticId>,
1182 children: &Vec<SubDiagnostic>) {
1183 let max_line_num = self.get_max_line_num(span, children);
1184 let max_line_num_len = max_line_num.to_string().len();
1186 match self.emit_message_default(span, message, code, level, max_line_num_len, false) {
1188 if !children.is_empty() {
1189 let mut buffer = StyledBuffer::new();
1190 if !self.short_message {
1191 draw_col_separator_no_space(&mut buffer, 0, max_line_num_len + 1);
1193 match emit_to_destination(&buffer.render(), level, &mut self.dst,
1194 self.short_message) {
1196 Err(e) => panic!("failed to emit error: {}", e)
1199 if !self.short_message {
1200 for child in children {
1201 match child.render_span {
1202 Some(FullSpan(ref msp)) => {
1203 match self.emit_message_default(msp,
1204 &child.styled_message(),
1209 Err(e) => panic!("failed to emit error: {}", e),
1213 Some(Suggestion(ref cs)) => {
1214 match self.emit_suggestion_default(cs,
1217 Err(e) => panic!("failed to emit error: {}", e),
1222 match self.emit_message_default(&child.span,
1223 &child.styled_message(),
1228 Err(e) => panic!("failed to emit error: {}", e),
1236 Err(e) => panic!("failed to emit error: {}", e),
1238 match write!(&mut self.dst, "\n") {
1239 Err(e) => panic!("failed to emit error: {}", e),
1241 match self.dst.flush() {
1242 Err(e) => panic!("failed to emit error: {}", e),
1250 fn draw_col_separator(buffer: &mut StyledBuffer, line: usize, col: usize) {
1251 buffer.puts(line, col, "| ", Style::LineNumber);
1254 fn draw_col_separator_no_space(buffer: &mut StyledBuffer, line: usize, col: usize) {
1255 draw_col_separator_no_space_with_style(buffer, line, col, Style::LineNumber);
1258 fn draw_col_separator_no_space_with_style(buffer: &mut StyledBuffer,
1262 buffer.putc(line, col, '|', style);
1265 fn draw_range(buffer: &mut StyledBuffer, symbol: char, line: usize,
1266 col_from: usize, col_to: usize, style: Style) {
1267 for col in col_from..col_to {
1268 buffer.putc(line, col, symbol, style);
1272 fn draw_note_separator(buffer: &mut StyledBuffer, line: usize, col: usize) {
1273 buffer.puts(line, col, "= ", Style::LineNumber);
1276 fn draw_multiline_line(buffer: &mut StyledBuffer,
1282 buffer.putc(line, offset + depth - 1, '|', style);
1285 fn num_overlap(a_start: usize, a_end: usize, b_start: usize, b_end:usize, inclusive: bool) -> bool {
1286 let extra = if inclusive {
1291 (b_start..b_end + extra).contains(a_start) ||
1292 (a_start..a_end + extra).contains(b_start)
1294 fn overlaps(a1: &Annotation, a2: &Annotation, padding: usize) -> bool {
1295 num_overlap(a1.start_col, a1.end_col + padding, a2.start_col, a2.end_col, false)
1298 fn emit_to_destination(rendered_buffer: &Vec<Vec<StyledString>>,
1300 dst: &mut Destination,
1301 short_message: bool)
1305 // In order to prevent error message interleaving, where multiple error lines get intermixed
1306 // when multiple compiler processes error simultaneously, we emit errors with additional
1309 // On Unix systems, we write into a buffered terminal rather than directly to a terminal. When
1310 // the .flush() is called we take the buffer created from the buffered writes and write it at
1311 // one shot. Because the Unix systems use ANSI for the colors, which is a text-based styling
1312 // scheme, this buffered approach works and maintains the styling.
1314 // On Windows, styling happens through calls to a terminal API. This prevents us from using the
1315 // same buffering approach. Instead, we use a global Windows mutex, which we acquire long
1316 // enough to output the full error message, then we release.
1317 let _buffer_lock = lock::acquire_global_lock("rustc_errors");
1318 for line in rendered_buffer {
1320 dst.apply_style(lvl.clone(), part.style)?;
1321 write!(dst, "{}", part.text)?;
1333 fn stderr_isatty() -> bool {
1335 unsafe { libc::isatty(libc::STDERR_FILENO) != 0 }
1338 fn stderr_isatty() -> bool {
1341 type HANDLE = *mut u8;
1342 const STD_ERROR_HANDLE: DWORD = -12i32 as DWORD;
1344 fn GetStdHandle(which: DWORD) -> HANDLE;
1345 fn GetConsoleMode(hConsoleHandle: HANDLE, lpMode: *mut DWORD) -> BOOL;
1348 let handle = GetStdHandle(STD_ERROR_HANDLE);
1350 GetConsoleMode(handle, &mut out) != 0
1354 pub type BufferedStderr = term::Terminal<Output = BufferedWriter> + Send;
1356 pub enum Destination {
1357 Terminal(Box<term::StderrTerminal>),
1358 BufferedTerminal(Box<BufferedStderr>),
1359 Raw(Box<Write + Send>),
1362 /// Buffered writer gives us a way on Unix to buffer up an entire error message before we output
1363 /// it. This helps to prevent interleaving of multiple error messages when multiple compiler
1364 /// processes error simultaneously
1365 pub struct BufferedWriter {
1369 impl BufferedWriter {
1370 // note: we use _new because the conditional compilation at its use site may make this
1371 // this function unused on some platforms
1372 fn _new() -> BufferedWriter {
1373 BufferedWriter { buffer: vec![] }
1377 impl Write for BufferedWriter {
1378 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
1380 self.buffer.push(*b);
1384 fn flush(&mut self) -> io::Result<()> {
1385 let mut stderr = io::stderr();
1386 let result = stderr.write_all(&self.buffer)
1387 .and_then(|_| stderr.flush());
1388 self.buffer.clear();
1394 #[cfg(not(windows))]
1395 /// When not on Windows, prefer the buffered terminal so that we can buffer an entire error
1396 /// to be emitted at one time.
1397 fn from_stderr() -> Destination {
1398 let stderr: Option<Box<BufferedStderr>> =
1399 term::TerminfoTerminal::new(BufferedWriter::_new())
1400 .map(|t| Box::new(t) as Box<BufferedStderr>);
1403 Some(t) => BufferedTerminal(t),
1404 None => Raw(Box::new(io::stderr())),
1409 /// Return a normal, unbuffered terminal when on Windows.
1410 fn from_stderr() -> Destination {
1411 let stderr: Option<Box<term::StderrTerminal>> = term::TerminfoTerminal::new(io::stderr())
1412 .map(|t| Box::new(t) as Box<term::StderrTerminal>)
1414 term::WinConsole::new(io::stderr())
1416 .map(|t| Box::new(t) as Box<term::StderrTerminal>)
1420 Some(t) => Terminal(t),
1421 None => Raw(Box::new(io::stderr())),
1425 fn apply_style(&mut self, lvl: Level, style: Style) -> io::Result<()> {
1427 Style::LineAndColumn => {}
1428 Style::LineNumber => {
1429 self.start_attr(term::Attr::Bold)?;
1431 self.start_attr(term::Attr::ForegroundColor(term::color::BRIGHT_CYAN))?;
1433 self.start_attr(term::Attr::ForegroundColor(term::color::BRIGHT_BLUE))?;
1436 Style::Quotation => {}
1437 Style::HeaderMsg => {
1438 self.start_attr(term::Attr::Bold)?;
1440 self.start_attr(term::Attr::ForegroundColor(term::color::BRIGHT_WHITE))?;
1443 Style::UnderlinePrimary | Style::LabelPrimary => {
1444 self.start_attr(term::Attr::Bold)?;
1445 self.start_attr(term::Attr::ForegroundColor(lvl.color()))?;
1447 Style::UnderlineSecondary |
1448 Style::LabelSecondary => {
1449 self.start_attr(term::Attr::Bold)?;
1451 self.start_attr(term::Attr::ForegroundColor(term::color::BRIGHT_CYAN))?;
1453 self.start_attr(term::Attr::ForegroundColor(term::color::BRIGHT_BLUE))?;
1456 Style::NoStyle => {}
1457 Style::Level(l) => {
1458 self.start_attr(term::Attr::Bold)?;
1459 self.start_attr(term::Attr::ForegroundColor(l.color()))?;
1461 Style::Highlight => self.start_attr(term::Attr::Bold)?,
1466 fn start_attr(&mut self, attr: term::Attr) -> io::Result<()> {
1468 Terminal(ref mut t) => {
1471 BufferedTerminal(ref mut t) => {
1479 fn reset_attrs(&mut self) -> io::Result<()> {
1481 Terminal(ref mut t) => {
1484 BufferedTerminal(ref mut t) => {
1493 impl Write for Destination {
1494 fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
1496 Terminal(ref mut t) => t.write(bytes),
1497 BufferedTerminal(ref mut t) => t.write(bytes),
1498 Raw(ref mut w) => w.write(bytes),
1501 fn flush(&mut self) -> io::Result<()> {
1503 Terminal(ref mut t) => t.flush(),
1504 BufferedTerminal(ref mut t) => t.flush(),
1505 Raw(ref mut w) => w.flush(),