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, CharPos};
15 use {Level, CodeSuggestion, DiagnosticBuilder, SubDiagnostic, CodeMapper};
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 multipart suggestions as labels
42 sugg.substitution_parts.len() == 1 &&
43 // don't display multi-suggestions as labels
44 sugg.substitutions() == 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.substitution_parts[0].substitutions[0].find('\n').is_none() {
49 let substitution = &sugg.substitution_parts[0].substitutions[0];
50 let msg = format!("help: {} `{}`", sugg.msg, substitution);
51 primary_span.push_span_label(sugg.substitution_spans().next().unwrap(), msg);
53 // if there are multiple suggestions, print them all in full
54 // to be consistent. We could try to figure out if we can
55 // make one (or the first one) inline, but that would give
56 // undue importance to a semi-random suggestion
57 for sugg in &db.suggestions {
58 children.push(SubDiagnostic {
61 span: MultiSpan::new(),
62 render_span: Some(Suggestion(sugg.clone())),
68 self.fix_multispans_in_std_macros(&mut primary_span, &mut children);
69 self.emit_messages_default(&db.level,
77 /// maximum number of lines we will print for each error; arbitrary.
78 pub const MAX_HIGHLIGHT_LINES: usize = 6;
79 /// maximum number of suggestions to be shown
81 /// Arbitrary, but taken from trait import suggestion limit
82 pub const MAX_SUGGESTIONS: usize = 4;
84 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
85 pub enum ColorConfig {
92 fn use_color(&self) -> bool {
94 ColorConfig::Always => true,
95 ColorConfig::Never => false,
96 ColorConfig::Auto => stderr_isatty(),
101 pub struct EmitterWriter {
103 cm: Option<Rc<CodeMapper>>,
106 struct FileWithAnnotatedLines {
109 multiline_depth: usize,
113 pub fn stderr(color_config: ColorConfig, code_map: Option<Rc<CodeMapper>>) -> EmitterWriter {
114 if color_config.use_color() {
115 let dst = Destination::from_stderr();
122 dst: Raw(Box::new(io::stderr())),
128 pub fn new(dst: Box<Write + Send>, code_map: Option<Rc<CodeMapper>>) -> EmitterWriter {
135 fn preprocess_annotations(&mut self, msp: &MultiSpan) -> Vec<FileWithAnnotatedLines> {
136 fn add_annotation_to_file(file_vec: &mut Vec<FileWithAnnotatedLines>,
141 for slot in file_vec.iter_mut() {
142 // Look through each of our files for the one we're adding to
143 if slot.file.name == file.name {
144 // See if we already have a line for it
145 for line_slot in &mut slot.lines {
146 if line_slot.line_index == line_index {
147 line_slot.annotations.push(ann);
151 // We don't have a line yet, create one
152 slot.lines.push(Line {
153 line_index: line_index,
154 annotations: vec![ann],
160 // This is the first time we're seeing the file
161 file_vec.push(FileWithAnnotatedLines {
164 line_index: line_index,
165 annotations: vec![ann],
171 let mut output = vec![];
172 let mut multiline_annotations = vec![];
174 if let Some(ref cm) = self.cm {
175 for span_label in msp.span_labels() {
176 if span_label.span == DUMMY_SP {
180 let lo = cm.lookup_char_pos(span_label.span.lo);
181 let mut hi = cm.lookup_char_pos(span_label.span.hi);
183 // Watch out for "empty spans". If we get a span like 6..6, we
184 // want to just display a `^` at 6, so convert that to
185 // 6..7. This is degenerate input, but it's best to degrade
186 // gracefully -- and the parser likes to supply a span like
187 // that for EOF, in particular.
188 if lo.col == hi.col && lo.line == hi.line {
189 hi.col = CharPos(lo.col.0 + 1);
192 let ann_type = if lo.line != hi.line {
193 let ml = MultilineAnnotation {
199 is_primary: span_label.is_primary,
200 label: span_label.label.clone(),
202 multiline_annotations.push((lo.file.clone(), ml.clone()));
203 AnnotationType::Multiline(ml)
205 AnnotationType::Singleline
207 let ann = Annotation {
210 is_primary: span_label.is_primary,
211 label: span_label.label.clone(),
212 annotation_type: ann_type,
215 if !ann.is_multiline() {
216 add_annotation_to_file(&mut output,
224 // Find overlapping multiline annotations, put them at different depths
225 multiline_annotations.sort_by(|a, b| {
226 (a.1.line_start, a.1.line_end).cmp(&(b.1.line_start, b.1.line_end))
228 for item in multiline_annotations.clone() {
230 for item in multiline_annotations.iter_mut() {
231 let ref mut a = item.1;
232 // Move all other multiline annotations overlapping with this one
233 // one level to the right.
235 num_overlap(ann.line_start, ann.line_end, a.line_start, a.line_end, true)
244 let mut max_depth = 0; // max overlapping multiline spans
245 for (file, ann) in multiline_annotations {
246 if ann.depth > max_depth {
247 max_depth = ann.depth;
249 add_annotation_to_file(&mut output, file.clone(), ann.line_start, ann.as_start());
250 let middle = min(ann.line_start + 4, ann.line_end);
251 for line in ann.line_start + 1..middle {
252 add_annotation_to_file(&mut output, file.clone(), line, ann.as_line());
254 if middle < ann.line_end - 1 {
255 for line in ann.line_end - 1..ann.line_end {
256 add_annotation_to_file(&mut output, file.clone(), line, ann.as_line());
259 add_annotation_to_file(&mut output, file, ann.line_end, ann.as_end());
261 for file_vec in output.iter_mut() {
262 file_vec.multiline_depth = max_depth;
267 fn render_source_line(&self,
268 buffer: &mut StyledBuffer,
272 code_offset: usize) -> Vec<(usize, Style)> {
273 let source_string = match file.get_line(line.line_index - 1) {
275 None => return Vec::new(),
278 let line_offset = buffer.num_lines();
280 // First create the source line we will highlight.
281 buffer.puts(line_offset, code_offset, &source_string, Style::Quotation);
282 buffer.puts(line_offset,
284 &(line.line_index.to_string()),
287 draw_col_separator(buffer, line_offset, width_offset - 2);
289 // Special case when there's only one annotation involved, it is the start of a multiline
290 // span and there's no text at the beginning of the code line. Instead of doing the whole
299 // we simplify the output to:
305 if line.annotations.len() == 1 {
306 if let Some(ref ann) = line.annotations.get(0) {
307 if let AnnotationType::MultilineStart(depth) = ann.annotation_type {
308 if source_string[0..ann.start_col].trim() == "" {
309 let style = if ann.is_primary {
310 Style::UnderlinePrimary
312 Style::UnderlineSecondary
314 buffer.putc(line_offset,
315 width_offset + depth - 1,
318 return vec![(depth, style)];
324 // We want to display like this:
326 // vec.push(vec.pop().unwrap());
327 // --- ^^^ - previous borrow ends here
329 // | error occurs here
330 // previous borrow of `vec` occurs here
332 // But there are some weird edge cases to be aware of:
334 // vec.push(vec.pop().unwrap());
335 // -------- - previous borrow ends here
337 // |this makes no sense
338 // previous borrow of `vec` occurs here
340 // For this reason, we group the lines into "highlight lines"
341 // and "annotations lines", where the highlight lines have the `^`.
343 // Sort the annotations by (start, end col)
344 let mut annotations = line.annotations.clone();
346 annotations.reverse();
348 // First, figure out where each label will be positioned.
350 // In the case where you have the following annotations:
352 // vec.push(vec.pop().unwrap());
353 // -------- - previous borrow ends here [C]
355 // |this makes no sense [B]
356 // previous borrow of `vec` occurs here [A]
358 // `annotations_position` will hold [(2, A), (1, B), (0, C)].
360 // We try, when possible, to stick the rightmost annotation at the end
361 // of the highlight line:
363 // vec.push(vec.pop().unwrap());
364 // --- --- - previous borrow ends here
366 // But sometimes that's not possible because one of the other
367 // annotations overlaps it. For example, from the test
368 // `span_overlap_label`, we have the following annotations
369 // (written on distinct lines for clarity):
375 // In this case, we can't stick the rightmost-most label on
376 // the highlight line, or we would get:
383 // which is totally weird. Instead we want:
391 // which is...less weird, at least. In fact, in general, if
392 // the rightmost span overlaps with any other span, we should
393 // use the "hang below" version, so we can at least make it
394 // clear where the span *starts*. There's an exception for this
395 // logic, when the labels do not have a message:
410 let mut annotations_position = vec![];
411 let mut line_len = 0;
413 for (i, annotation) in annotations.iter().enumerate() {
414 for (j, next) in annotations.iter().enumerate() {
415 if overlaps(next, annotation, 0) // This label overlaps with another one and both
416 && annotation.has_label() // take space (they have text and are not
417 && j > i // multiline lines).
418 && p == 0 // We're currently on the first line, move the label one line down
420 // This annotation needs a new line in the output.
425 annotations_position.push((p, annotation));
426 for (j, next) in annotations.iter().enumerate() {
428 let l = if let Some(ref label) = next.label {
433 if (overlaps(next, annotation, l) // Do not allow two labels to be in the same
434 // line if they overlap including padding, to
435 // avoid situations like:
442 && annotation.has_label() // Both labels must have some text, otherwise
443 && next.has_label()) // they are not overlapping.
444 // Do not add a new line if this annotation
445 // or the next are vertical line placeholders.
446 || (annotation.takes_space() // If either this or the next annotation is
447 && next.has_label()) // multiline start/end, move it to a new line
448 || (annotation.has_label() // so as not to overlap the orizontal lines.
449 && next.takes_space())
450 || (annotation.takes_space() && next.takes_space())
451 || (overlaps(next, annotation, l)
452 && next.end_col <= annotation.end_col
454 && p == 0) // Avoid #42595.
456 // This annotation needs a new line in the output.
471 // If there are no annotations or the only annotations on this line are
472 // MultilineLine, then there's only code being shown, stop processing.
473 if line.annotations.is_empty() || line.annotations.iter()
474 .filter(|a| !a.is_line()).collect::<Vec<_>>().len() == 0
479 // Write the colunmn separator.
481 // After this we will have:
490 for pos in 0..line_len + 1 {
491 draw_col_separator(buffer, line_offset + pos + 1, width_offset - 2);
492 buffer.putc(line_offset + pos + 1,
498 // Write the horizontal lines for multiline annotations
499 // (only the first and last lines need this).
501 // After this we will have:
510 for &(pos, annotation) in &annotations_position {
511 let style = if annotation.is_primary {
512 Style::UnderlinePrimary
514 Style::UnderlineSecondary
517 match annotation.annotation_type {
518 AnnotationType::MultilineStart(depth) |
519 AnnotationType::MultilineEnd(depth) => {
523 width_offset + depth,
524 code_offset + annotation.start_col,
531 // Write the vertical lines for labels that are on a different line as the underline.
533 // After this we will have:
542 for &(pos, annotation) in &annotations_position {
543 let style = if annotation.is_primary {
544 Style::UnderlinePrimary
546 Style::UnderlineSecondary
550 if pos > 1 && (annotation.has_label() || annotation.takes_space()) {
551 for p in line_offset + 1..line_offset + pos + 1 {
553 code_offset + annotation.start_col,
558 match annotation.annotation_type {
559 AnnotationType::MultilineStart(depth) => {
560 for p in line_offset + pos + 1..line_offset + line_len + 2 {
562 width_offset + depth - 1,
567 AnnotationType::MultilineEnd(depth) => {
568 for p in line_offset..line_offset + pos + 1 {
570 width_offset + depth - 1,
579 // Write the labels on the annotations that actually have a label.
581 // After this we will have:
586 // | something about `foo`
590 for &(pos, annotation) in &annotations_position {
591 let style = if annotation.is_primary {
594 Style::LabelSecondary
596 let (pos, col) = if pos == 0 {
597 (pos + 1, annotation.end_col + 1)
599 (pos + 2, annotation.start_col)
601 if let Some(ref label) = annotation.label {
602 buffer.puts(line_offset + pos,
609 // Sort from biggest span to smallest span so that smaller spans are
610 // represented in the output:
615 // | | something about `foo`
616 // | something about `fn foo()`
617 annotations_position.sort_by(|a, b| {
619 a.1.len().cmp(&b.1.len()).reverse()
622 // Write the underlines.
624 // After this we will have:
629 // | something about `foo`
633 for &(_, annotation) in &annotations_position {
634 let (underline, style) = if annotation.is_primary {
635 ('^', Style::UnderlinePrimary)
637 ('-', Style::UnderlineSecondary)
639 for p in annotation.start_col..annotation.end_col {
640 buffer.putc(line_offset + 1,
646 annotations_position.iter().filter_map(|&(_, annotation)| {
647 match annotation.annotation_type {
648 AnnotationType::MultilineStart(p) | AnnotationType::MultilineEnd(p) => {
649 let style = if annotation.is_primary {
652 Style::LabelSecondary
659 }).collect::<Vec<_>>()
662 fn get_multispan_max_line_num(&mut self, msp: &MultiSpan) -> usize {
664 if let Some(ref cm) = self.cm {
665 for primary_span in msp.primary_spans() {
666 if primary_span != &DUMMY_SP {
667 let hi = cm.lookup_char_pos(primary_span.hi);
673 for span_label in msp.span_labels() {
674 if span_label.span != DUMMY_SP {
675 let hi = cm.lookup_char_pos(span_label.span.hi);
685 fn get_max_line_num(&mut self, span: &MultiSpan, children: &Vec<SubDiagnostic>) -> usize {
688 let primary = self.get_multispan_max_line_num(span);
689 max = if primary > max { primary } else { max };
691 for sub in children {
692 let sub_result = self.get_multispan_max_line_num(&sub.span);
693 max = if sub_result > max { primary } else { max };
698 // This "fixes" MultiSpans that contain Spans that are pointing to locations inside of
699 // <*macros>. Since these locations are often difficult to read, we move these Spans from
700 // <*macros> to their corresponding use site.
701 fn fix_multispan_in_std_macros(&mut self, span: &mut MultiSpan) -> bool {
702 let mut spans_updated = false;
704 if let Some(ref cm) = self.cm {
705 let mut before_after: Vec<(Span, Span)> = vec![];
706 let mut new_labels: Vec<(Span, String)> = vec![];
708 // First, find all the spans in <*macros> and point instead at their use site
709 for sp in span.primary_spans() {
713 let call_sp = cm.call_span_if_macro(*sp);
715 before_after.push((sp.clone(), call_sp));
717 for trace in sp.macro_backtrace().iter().rev() {
718 // Only show macro locations that are local
719 // and display them like a span_note
720 if let Some(def_site) = trace.def_site_span {
721 if def_site == DUMMY_SP {
724 // Check to make sure we're not in any <*macros>
725 if !cm.span_to_filename(def_site).contains("macros>") &&
726 !trace.macro_decl_name.starts_with("#[") {
727 new_labels.push((trace.call_site,
728 "in this macro invocation".to_string()));
734 for (label_span, label_text) in new_labels {
735 span.push_span_label(label_span, label_text);
737 for sp_label in span.span_labels() {
738 if sp_label.span == DUMMY_SP {
741 if cm.span_to_filename(sp_label.span.clone()).contains("macros>") {
742 let v = sp_label.span.macro_backtrace();
743 if let Some(use_site) = v.last() {
744 before_after.push((sp_label.span.clone(), use_site.call_site.clone()));
748 // After we have them, make sure we replace these 'bad' def sites with their use sites
749 for (before, after) in before_after {
750 span.replace(before, after);
751 spans_updated = true;
758 // This does a small "fix" for multispans by looking to see if it can find any that
759 // point directly at <*macros>. Since these are often difficult to read, this
760 // will change the span to point at the use site.
761 fn fix_multispans_in_std_macros(&mut self,
762 span: &mut MultiSpan,
763 children: &mut Vec<SubDiagnostic>) {
764 let mut spans_updated = self.fix_multispan_in_std_macros(span);
765 for child in children.iter_mut() {
766 spans_updated |= self.fix_multispan_in_std_macros(&mut child.span);
769 children.push(SubDiagnostic {
771 message: vec![("this error originates in a macro outside of the current crate"
772 .to_string(), Style::NoStyle)],
773 span: MultiSpan::new(),
779 /// Add a left margin to every line but the first, given a padding length and the label being
780 /// displayed, keeping the provided highlighting.
781 fn msg_to_buffer(&self,
782 buffer: &mut StyledBuffer,
783 msg: &[(String, Style)],
786 override_style: Option<Style>) {
788 // The extra 5 ` ` is padding that's always needed to align to the `note: `:
801 // | | length of label
803 // `max_line_num_len`
804 let padding = (0..padding + label.len() + 5)
806 .collect::<String>();
808 /// Return wether `style`, or the override if present and the style is `NoStyle`.
809 fn style_or_override(style: Style, override_style: Option<Style>) -> Style {
810 if let Some(o) = override_style {
811 if style == Style::NoStyle {
818 let mut line_number = 0;
820 // Provided the following diagnostic message:
824 // ("highlighted multiline\nstring to\nsee how it ", Style::NoStyle),
825 // ("looks", Style::Highlight),
826 // ("with\nvery ", Style::NoStyle),
827 // ("weird", Style::Highlight),
828 // (" formats\n", Style::NoStyle),
829 // ("see?", Style::Highlight),
832 // the expected output on a note is (* surround the highlighted text)
834 // = note: highlighted multiline
836 // see how it *looks* with
837 // very *weird* formats
839 for &(ref text, ref style) in msg.iter() {
840 let lines = text.split('\n').collect::<Vec<_>>();
842 for (i, line) in lines.iter().enumerate() {
845 buffer.append(line_number, &padding, Style::NoStyle);
847 buffer.append(line_number, line, style_or_override(*style, override_style));
850 buffer.append(line_number, text, style_or_override(*style, override_style));
855 fn emit_message_default(&mut self,
857 msg: &Vec<(String, Style)>,
858 code: &Option<String>,
860 max_line_num_len: usize,
863 let mut buffer = StyledBuffer::new();
865 if msp.primary_spans().is_empty() && msp.span_labels().is_empty() && is_secondary {
866 // This is a secondary message with no span info
867 for _ in 0..max_line_num_len {
868 buffer.prepend(0, " ", Style::NoStyle);
870 draw_note_separator(&mut buffer, 0, max_line_num_len + 1);
871 buffer.append(0, &level.to_string(), Style::HeaderMsg);
872 buffer.append(0, ": ", Style::NoStyle);
873 self.msg_to_buffer(&mut buffer, msg, max_line_num_len, "note", None);
875 buffer.append(0, &level.to_string(), Style::Level(level.clone()));
878 buffer.append(0, "[", Style::Level(level.clone()));
879 buffer.append(0, &code, Style::Level(level.clone()));
880 buffer.append(0, "]", Style::Level(level.clone()));
884 buffer.append(0, ": ", Style::HeaderMsg);
885 for &(ref text, _) in msg.iter() {
886 buffer.append(0, text, Style::HeaderMsg);
890 // Preprocess all the annotations so that they are grouped by file and by line number
891 // This helps us quickly iterate over the whole message (including secondary file spans)
892 let mut annotated_files = self.preprocess_annotations(msp);
894 // Make sure our primary file comes first
895 let (primary_lo, cm) = if let (Some(cm), Some(ref primary_span)) =
896 (self.cm.as_ref(), msp.primary_span().as_ref()) {
897 if primary_span != &&DUMMY_SP {
898 (cm.lookup_char_pos(primary_span.lo), cm)
900 emit_to_destination(&buffer.render(), level, &mut self.dst)?;
904 // If we don't have span information, emit and exit
905 emit_to_destination(&buffer.render(), level, &mut self.dst)?;
909 annotated_files.binary_search_by(|x| x.file.name.cmp(&primary_lo.file.name)) {
910 annotated_files.swap(0, pos);
913 // Print out the annotate source lines that correspond with the error
914 for annotated_file in annotated_files {
915 // we can't annotate anything if the source is unavailable.
916 if !cm.ensure_filemap_source_present(annotated_file.file.clone()) {
920 // print out the span location and spacer before we print the annotated source
921 // to do this, we need to know if this span will be primary
922 let is_primary = primary_lo.file.name == annotated_file.file.name;
924 // remember where we are in the output buffer for easy reference
925 let buffer_msg_line_offset = buffer.num_lines();
927 buffer.prepend(buffer_msg_line_offset, "--> ", Style::LineNumber);
928 let loc = primary_lo.clone();
929 buffer.append(buffer_msg_line_offset,
930 &format!("{}:{}:{}", loc.file.name, loc.line, loc.col.0 + 1),
931 Style::LineAndColumn);
932 for _ in 0..max_line_num_len {
933 buffer.prepend(buffer_msg_line_offset, " ", Style::NoStyle);
936 // remember where we are in the output buffer for easy reference
937 let buffer_msg_line_offset = buffer.num_lines();
940 draw_col_separator(&mut buffer, buffer_msg_line_offset, max_line_num_len + 1);
942 // Then, the secondary file indicator
943 buffer.prepend(buffer_msg_line_offset + 1, "::: ", Style::LineNumber);
944 buffer.append(buffer_msg_line_offset + 1,
945 &annotated_file.file.name,
946 Style::LineAndColumn);
947 for _ in 0..max_line_num_len {
948 buffer.prepend(buffer_msg_line_offset + 1, " ", Style::NoStyle);
952 // Put in the spacer between the location and annotated source
953 let buffer_msg_line_offset = buffer.num_lines();
954 draw_col_separator_no_space(&mut buffer, buffer_msg_line_offset, max_line_num_len + 1);
956 // Contains the vertical lines' positions for active multiline annotations
957 let mut multilines = HashMap::new();
959 // Next, output the annotate source for this file
960 for line_idx in 0..annotated_file.lines.len() {
961 let previous_buffer_line = buffer.num_lines();
963 let width_offset = 3 + max_line_num_len;
964 let code_offset = if annotated_file.multiline_depth == 0 {
967 width_offset + annotated_file.multiline_depth + 1
970 let depths = self.render_source_line(&mut buffer,
971 annotated_file.file.clone(),
972 &annotated_file.lines[line_idx],
976 let mut to_add = HashMap::new();
978 for (depth, style) in depths {
979 if multilines.get(&depth).is_some() {
980 multilines.remove(&depth);
982 to_add.insert(depth, style);
986 // Set the multiline annotation vertical lines to the left of
987 // the code in this line.
988 for (depth, style) in &multilines {
989 for line in previous_buffer_line..buffer.num_lines() {
990 draw_multiline_line(&mut buffer,
997 // check to see if we need to print out or elide lines that come between
998 // this annotated line and the next one.
999 if line_idx < (annotated_file.lines.len() - 1) {
1000 let line_idx_delta = annotated_file.lines[line_idx + 1].line_index -
1001 annotated_file.lines[line_idx].line_index;
1002 if line_idx_delta > 2 {
1003 let last_buffer_line_num = buffer.num_lines();
1004 buffer.puts(last_buffer_line_num, 0, "...", Style::LineNumber);
1006 // Set the multiline annotation vertical lines on `...` bridging line.
1007 for (depth, style) in &multilines {
1008 draw_multiline_line(&mut buffer,
1009 last_buffer_line_num,
1014 } else if line_idx_delta == 2 {
1015 let unannotated_line = annotated_file.file
1016 .get_line(annotated_file.lines[line_idx].line_index)
1017 .unwrap_or_else(|| Cow::from(""));
1019 let last_buffer_line_num = buffer.num_lines();
1021 buffer.puts(last_buffer_line_num,
1023 &(annotated_file.lines[line_idx + 1].line_index - 1)
1026 draw_col_separator(&mut buffer, last_buffer_line_num, 1 + max_line_num_len);
1027 buffer.puts(last_buffer_line_num,
1032 for (depth, style) in &multilines {
1033 draw_multiline_line(&mut buffer,
1034 last_buffer_line_num,
1042 multilines.extend(&to_add);
1046 // final step: take our styled buffer, render it, then output it
1047 emit_to_destination(&buffer.render(), level, &mut self.dst)?;
1051 fn emit_suggestion_default(&mut self,
1052 suggestion: &CodeSuggestion,
1054 max_line_num_len: usize)
1056 use std::borrow::Borrow;
1058 let primary_span = suggestion.substitution_spans().next().unwrap();
1059 if let Some(ref cm) = self.cm {
1060 let mut buffer = StyledBuffer::new();
1062 let lines = cm.span_to_lines(primary_span).unwrap();
1064 assert!(!lines.lines.is_empty());
1066 buffer.append(0, &level.to_string(), Style::Level(level.clone()));
1067 buffer.append(0, ": ", Style::HeaderMsg);
1068 self.msg_to_buffer(&mut buffer,
1069 &[(suggestion.msg.to_owned(), Style::NoStyle)],
1072 Some(Style::HeaderMsg));
1074 let suggestions = suggestion.splice_lines(cm.borrow());
1075 let mut row_num = 1;
1076 for complete in suggestions.iter().take(MAX_SUGGESTIONS) {
1078 // print the suggestion without any line numbers, but leave
1079 // space for them. This helps with lining up with previous
1080 // snippets from the actual error being reported.
1081 let mut lines = complete.lines();
1082 for line in lines.by_ref().take(MAX_HIGHLIGHT_LINES) {
1083 draw_col_separator(&mut buffer, row_num, max_line_num_len + 1);
1084 buffer.append(row_num, line, Style::NoStyle);
1088 // if we elided some lines, add an ellipsis
1089 if let Some(_) = lines.next() {
1090 buffer.append(row_num, "...", Style::NoStyle);
1093 if suggestions.len() > MAX_SUGGESTIONS {
1094 let msg = format!("and {} other candidates", suggestions.len() - MAX_SUGGESTIONS);
1095 buffer.append(row_num, &msg, Style::NoStyle);
1097 emit_to_destination(&buffer.render(), level, &mut self.dst)?;
1101 fn emit_messages_default(&mut self,
1103 message: &Vec<(String, Style)>,
1104 code: &Option<String>,
1106 children: &Vec<SubDiagnostic>) {
1107 let max_line_num = self.get_max_line_num(span, children);
1108 let max_line_num_len = max_line_num.to_string().len();
1110 match self.emit_message_default(span, message, code, level, max_line_num_len, false) {
1112 if !children.is_empty() {
1113 let mut buffer = StyledBuffer::new();
1114 draw_col_separator_no_space(&mut buffer, 0, max_line_num_len + 1);
1115 match emit_to_destination(&buffer.render(), level, &mut self.dst) {
1117 Err(e) => panic!("failed to emit error: {}", e)
1120 for child in children {
1121 match child.render_span {
1122 Some(FullSpan(ref msp)) => {
1123 match self.emit_message_default(msp,
1124 &child.styled_message(),
1129 Err(e) => panic!("failed to emit error: {}", e),
1133 Some(Suggestion(ref cs)) => {
1134 match self.emit_suggestion_default(cs,
1137 Err(e) => panic!("failed to emit error: {}", e),
1142 match self.emit_message_default(&child.span,
1143 &child.styled_message(),
1148 Err(e) => panic!("failed to emit error: {}", e),
1155 Err(e) => panic!("failed to emit error: {}", e),
1157 match write!(&mut self.dst, "\n") {
1158 Err(e) => panic!("failed to emit error: {}", e),
1160 match self.dst.flush() {
1161 Err(e) => panic!("failed to emit error: {}", e),
1169 fn draw_col_separator(buffer: &mut StyledBuffer, line: usize, col: usize) {
1170 buffer.puts(line, col, "| ", Style::LineNumber);
1173 fn draw_col_separator_no_space(buffer: &mut StyledBuffer, line: usize, col: usize) {
1174 draw_col_separator_no_space_with_style(buffer, line, col, Style::LineNumber);
1177 fn draw_col_separator_no_space_with_style(buffer: &mut StyledBuffer,
1181 buffer.putc(line, col, '|', style);
1184 fn draw_range(buffer: &mut StyledBuffer, symbol: char, line: usize,
1185 col_from: usize, col_to: usize, style: Style) {
1186 for col in col_from..col_to {
1187 buffer.putc(line, col, symbol, style);
1191 fn draw_note_separator(buffer: &mut StyledBuffer, line: usize, col: usize) {
1192 buffer.puts(line, col, "= ", Style::LineNumber);
1195 fn draw_multiline_line(buffer: &mut StyledBuffer,
1201 buffer.putc(line, offset + depth - 1, '|', style);
1204 fn num_overlap(a_start: usize, a_end: usize, b_start: usize, b_end:usize, inclusive: bool) -> bool {
1205 let extra = if inclusive {
1210 (b_start..b_end + extra).contains(a_start) ||
1211 (a_start..a_end + extra).contains(b_start)
1213 fn overlaps(a1: &Annotation, a2: &Annotation, padding: usize) -> bool {
1214 num_overlap(a1.start_col, a1.end_col + padding, a2.start_col, a2.end_col, false)
1217 fn emit_to_destination(rendered_buffer: &Vec<Vec<StyledString>>,
1219 dst: &mut Destination)
1223 // In order to prevent error message interleaving, where multiple error lines get intermixed
1224 // when multiple compiler processes error simultaneously, we emit errors with additional
1227 // On Unix systems, we write into a buffered terminal rather than directly to a terminal. When
1228 // the .flush() is called we take the buffer created from the buffered writes and write it at
1229 // one shot. Because the Unix systems use ANSI for the colors, which is a text-based styling
1230 // scheme, this buffered approach works and maintains the styling.
1232 // On Windows, styling happens through calls to a terminal API. This prevents us from using the
1233 // same buffering approach. Instead, we use a global Windows mutex, which we acquire long
1234 // enough to output the full error message, then we release.
1235 let _buffer_lock = lock::acquire_global_lock("rustc_errors");
1236 for line in rendered_buffer {
1238 dst.apply_style(lvl.clone(), part.style)?;
1239 write!(dst, "{}", part.text)?;
1249 fn stderr_isatty() -> bool {
1251 unsafe { libc::isatty(libc::STDERR_FILENO) != 0 }
1254 fn stderr_isatty() -> bool {
1257 type HANDLE = *mut u8;
1258 const STD_ERROR_HANDLE: DWORD = -12i32 as DWORD;
1260 fn GetStdHandle(which: DWORD) -> HANDLE;
1261 fn GetConsoleMode(hConsoleHandle: HANDLE, lpMode: *mut DWORD) -> BOOL;
1264 let handle = GetStdHandle(STD_ERROR_HANDLE);
1266 GetConsoleMode(handle, &mut out) != 0
1270 pub type BufferedStderr = term::Terminal<Output = BufferedWriter> + Send;
1272 pub enum Destination {
1273 Terminal(Box<term::StderrTerminal>),
1274 BufferedTerminal(Box<BufferedStderr>),
1275 Raw(Box<Write + Send>),
1278 /// Buffered writer gives us a way on Unix to buffer up an entire error message before we output
1279 /// it. This helps to prevent interleaving of multiple error messages when multiple compiler
1280 /// processes error simultaneously
1281 pub struct BufferedWriter {
1285 impl BufferedWriter {
1286 // note: we use _new because the conditional compilation at its use site may make this
1287 // this function unused on some platforms
1288 fn _new() -> BufferedWriter {
1289 BufferedWriter { buffer: vec![] }
1293 impl Write for BufferedWriter {
1294 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
1296 self.buffer.push(*b);
1300 fn flush(&mut self) -> io::Result<()> {
1301 let mut stderr = io::stderr();
1302 let result = stderr.write_all(&self.buffer)
1303 .and_then(|_| stderr.flush());
1304 self.buffer.clear();
1310 #[cfg(not(windows))]
1311 /// When not on Windows, prefer the buffered terminal so that we can buffer an entire error
1312 /// to be emitted at one time.
1313 fn from_stderr() -> Destination {
1314 let stderr: Option<Box<BufferedStderr>> =
1315 term::TerminfoTerminal::new(BufferedWriter::_new())
1316 .map(|t| Box::new(t) as Box<BufferedStderr>);
1319 Some(t) => BufferedTerminal(t),
1320 None => Raw(Box::new(io::stderr())),
1325 /// Return a normal, unbuffered terminal when on Windows.
1326 fn from_stderr() -> Destination {
1327 let stderr: Option<Box<term::StderrTerminal>> = term::TerminfoTerminal::new(io::stderr())
1328 .map(|t| Box::new(t) as Box<term::StderrTerminal>)
1330 term::WinConsole::new(io::stderr())
1332 .map(|t| Box::new(t) as Box<term::StderrTerminal>)
1336 Some(t) => Terminal(t),
1337 None => Raw(Box::new(io::stderr())),
1341 fn apply_style(&mut self, lvl: Level, style: Style) -> io::Result<()> {
1343 Style::FileNameStyle | Style::LineAndColumn => {}
1344 Style::LineNumber => {
1345 self.start_attr(term::Attr::Bold)?;
1347 self.start_attr(term::Attr::ForegroundColor(term::color::BRIGHT_CYAN))?;
1349 self.start_attr(term::Attr::ForegroundColor(term::color::BRIGHT_BLUE))?;
1352 Style::ErrorCode => {
1353 self.start_attr(term::Attr::Bold)?;
1354 self.start_attr(term::Attr::ForegroundColor(term::color::BRIGHT_MAGENTA))?;
1356 Style::Quotation => {}
1357 Style::OldSchoolNote => {
1358 self.start_attr(term::Attr::Bold)?;
1359 self.start_attr(term::Attr::ForegroundColor(term::color::BRIGHT_GREEN))?;
1361 Style::OldSchoolNoteText | Style::HeaderMsg => {
1362 self.start_attr(term::Attr::Bold)?;
1364 self.start_attr(term::Attr::ForegroundColor(term::color::BRIGHT_WHITE))?;
1367 Style::UnderlinePrimary | Style::LabelPrimary => {
1368 self.start_attr(term::Attr::Bold)?;
1369 self.start_attr(term::Attr::ForegroundColor(lvl.color()))?;
1371 Style::UnderlineSecondary |
1372 Style::LabelSecondary => {
1373 self.start_attr(term::Attr::Bold)?;
1375 self.start_attr(term::Attr::ForegroundColor(term::color::BRIGHT_CYAN))?;
1377 self.start_attr(term::Attr::ForegroundColor(term::color::BRIGHT_BLUE))?;
1380 Style::NoStyle => {}
1381 Style::Level(l) => {
1382 self.start_attr(term::Attr::Bold)?;
1383 self.start_attr(term::Attr::ForegroundColor(l.color()))?;
1385 Style::Highlight => self.start_attr(term::Attr::Bold)?,
1390 fn start_attr(&mut self, attr: term::Attr) -> io::Result<()> {
1392 Terminal(ref mut t) => {
1395 BufferedTerminal(ref mut t) => {
1403 fn reset_attrs(&mut self) -> io::Result<()> {
1405 Terminal(ref mut t) => {
1408 BufferedTerminal(ref mut t) => {
1417 impl Write for Destination {
1418 fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
1420 Terminal(ref mut t) => t.write(bytes),
1421 BufferedTerminal(ref mut t) => t.write(bytes),
1422 Raw(ref mut w) => w.write(bytes),
1425 fn flush(&mut self) -> io::Result<()> {
1427 Terminal(ref mut t) => t.flush(),
1428 BufferedTerminal(ref mut t) => t.flush(),
1429 Raw(ref mut w) => w.flush(),