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;
20 use std::io::prelude::*;
24 use std::collections::HashMap;
27 /// Emitter trait for emitting errors.
29 /// Emit a structured diagnostic.
30 fn emit(&mut self, db: &DiagnosticBuilder);
33 impl Emitter for EmitterWriter {
34 fn emit(&mut self, db: &DiagnosticBuilder) {
35 let mut primary_span = db.span.clone();
36 let mut children = db.children.clone();
38 if let Some((sugg, rest)) = db.suggestions.split_first() {
40 // don't display multipart suggestions as labels
41 sugg.substitution_parts.len() == 1 &&
42 // don't display multi-suggestions as labels
43 sugg.substitutions() == 1 &&
44 // don't display long messages as labels
45 sugg.msg.split_whitespace().count() < 10 &&
46 // don't display multiline suggestions as labels
47 sugg.substitution_parts[0].substitutions[0].find('\n').is_none() {
48 let substitution = &sugg.substitution_parts[0].substitutions[0];
49 let msg = format!("help: {} `{}`", sugg.msg, substitution);
50 primary_span.push_span_label(sugg.substitution_spans().next().unwrap(), msg);
52 // if there are multiple suggestions, print them all in full
53 // to be consistent. We could try to figure out if we can
54 // make one (or the first one) inline, but that would give
55 // undue importance to a semi-random suggestion
56 for sugg in &db.suggestions {
57 children.push(SubDiagnostic {
60 span: MultiSpan::new(),
61 render_span: Some(Suggestion(sugg.clone())),
67 self.fix_multispans_in_std_macros(&mut primary_span, &mut children);
68 self.emit_messages_default(&db.level,
76 /// maximum number of lines we will print for each error; arbitrary.
77 pub const MAX_HIGHLIGHT_LINES: usize = 6;
78 /// maximum number of suggestions to be shown
80 /// Arbitrary, but taken from trait import suggestion limit
81 pub const MAX_SUGGESTIONS: usize = 4;
83 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
84 pub enum ColorConfig {
91 fn use_color(&self) -> bool {
93 ColorConfig::Always => true,
94 ColorConfig::Never => false,
95 ColorConfig::Auto => stderr_isatty(),
100 pub struct EmitterWriter {
102 cm: Option<Rc<CodeMapper>>,
105 struct FileWithAnnotatedLines {
108 multiline_depth: usize,
112 pub fn stderr(color_config: ColorConfig, code_map: Option<Rc<CodeMapper>>) -> EmitterWriter {
113 if color_config.use_color() {
114 let dst = Destination::from_stderr();
121 dst: Raw(Box::new(io::stderr())),
127 pub fn new(dst: Box<Write + Send>, code_map: Option<Rc<CodeMapper>>) -> EmitterWriter {
134 fn preprocess_annotations(&self, msp: &MultiSpan) -> Vec<FileWithAnnotatedLines> {
135 fn add_annotation_to_file(file_vec: &mut Vec<FileWithAnnotatedLines>,
140 for slot in file_vec.iter_mut() {
141 // Look through each of our files for the one we're adding to
142 if slot.file.name == file.name {
143 // See if we already have a line for it
144 for line_slot in &mut slot.lines {
145 if line_slot.line_index == line_index {
146 line_slot.annotations.push(ann);
150 // We don't have a line yet, create one
151 slot.lines.push(Line {
152 line_index: line_index,
153 annotations: vec![ann],
159 // This is the first time we're seeing the file
160 file_vec.push(FileWithAnnotatedLines {
163 line_index: line_index,
164 annotations: vec![ann],
170 let mut output = vec![];
171 let mut multiline_annotations = vec![];
173 if let Some(ref cm) = self.cm {
174 for span_label in msp.span_labels() {
175 if span_label.span == DUMMY_SP {
178 let lo = cm.lookup_char_pos(span_label.span.lo);
179 let mut hi = cm.lookup_char_pos(span_label.span.hi);
181 // Watch out for "empty spans". If we get a span like 6..6, we
182 // want to just display a `^` at 6, so convert that to
183 // 6..7. This is degenerate input, but it's best to degrade
184 // gracefully -- and the parser likes to supply a span like
185 // that for EOF, in particular.
186 if lo.col == hi.col && lo.line == hi.line {
187 hi.col = CharPos(lo.col.0 + 1);
190 let ann_type = if lo.line != hi.line {
191 let ml = MultilineAnnotation {
197 is_primary: span_label.is_primary,
198 label: span_label.label.clone(),
200 multiline_annotations.push((lo.file.clone(), ml.clone()));
201 AnnotationType::Multiline(ml)
203 AnnotationType::Singleline
205 let ann = Annotation {
208 is_primary: span_label.is_primary,
209 label: span_label.label.clone(),
210 annotation_type: ann_type,
213 if !ann.is_multiline() {
214 add_annotation_to_file(&mut output,
222 // Find overlapping multiline annotations, put them at different depths
223 multiline_annotations.sort_by(|a, b| {
224 (a.1.line_start, a.1.line_end).cmp(&(b.1.line_start, b.1.line_end))
226 for item in multiline_annotations.clone() {
228 for item in multiline_annotations.iter_mut() {
229 let ref mut a = item.1;
230 // Move all other multiline annotations overlapping with this one
231 // one level to the right.
233 num_overlap(ann.line_start, ann.line_end, a.line_start, a.line_end, true)
242 let mut max_depth = 0; // max overlapping multiline spans
243 for (file, ann) in multiline_annotations {
244 if ann.depth > max_depth {
245 max_depth = ann.depth;
247 add_annotation_to_file(&mut output, file.clone(), ann.line_start, ann.as_start());
248 let middle = min(ann.line_start + 4, ann.line_end);
249 for line in ann.line_start + 1..middle {
250 add_annotation_to_file(&mut output, file.clone(), line, ann.as_line());
252 if middle < ann.line_end - 1 {
253 for line in ann.line_end - 1..ann.line_end {
254 add_annotation_to_file(&mut output, file.clone(), line, ann.as_line());
257 add_annotation_to_file(&mut output, file, ann.line_end, ann.as_end());
259 for file_vec in output.iter_mut() {
260 file_vec.multiline_depth = max_depth;
265 fn render_source_line(&self,
266 buffer: &mut StyledBuffer,
270 code_offset: usize) -> Vec<(usize, Style)> {
271 let source_string = match file.get_line(line.line_index - 1) {
273 None => return Vec::new(),
276 let line_offset = buffer.num_lines();
278 // First create the source line we will highlight.
279 buffer.puts(line_offset, code_offset, &source_string, Style::Quotation);
280 buffer.puts(line_offset,
282 &(line.line_index.to_string()),
285 draw_col_separator(buffer, line_offset, width_offset - 2);
287 // Special case when there's only one annotation involved, it is the start of a multiline
288 // span and there's no text at the beginning of the code line. Instead of doing the whole
297 // we simplify the output to:
303 if line.annotations.len() == 1 {
304 if let Some(ref ann) = line.annotations.get(0) {
305 if let AnnotationType::MultilineStart(depth) = ann.annotation_type {
306 if source_string[0..ann.start_col].trim() == "" {
307 let style = if ann.is_primary {
308 Style::UnderlinePrimary
310 Style::UnderlineSecondary
312 buffer.putc(line_offset,
313 width_offset + depth - 1,
316 return vec![(depth, style)];
322 // We want to display like this:
324 // vec.push(vec.pop().unwrap());
325 // --- ^^^ - previous borrow ends here
327 // | error occurs here
328 // previous borrow of `vec` occurs here
330 // But there are some weird edge cases to be aware of:
332 // vec.push(vec.pop().unwrap());
333 // -------- - previous borrow ends here
335 // |this makes no sense
336 // previous borrow of `vec` occurs here
338 // For this reason, we group the lines into "highlight lines"
339 // and "annotations lines", where the highlight lines have the `^`.
341 // Sort the annotations by (start, end col)
342 let mut annotations = line.annotations.clone();
344 annotations.reverse();
346 // First, figure out where each label will be positioned.
348 // In the case where you have the following annotations:
350 // vec.push(vec.pop().unwrap());
351 // -------- - previous borrow ends here [C]
353 // |this makes no sense [B]
354 // previous borrow of `vec` occurs here [A]
356 // `annotations_position` will hold [(2, A), (1, B), (0, C)].
358 // We try, when possible, to stick the rightmost annotation at the end
359 // of the highlight line:
361 // vec.push(vec.pop().unwrap());
362 // --- --- - previous borrow ends here
364 // But sometimes that's not possible because one of the other
365 // annotations overlaps it. For example, from the test
366 // `span_overlap_label`, we have the following annotations
367 // (written on distinct lines for clarity):
373 // In this case, we can't stick the rightmost-most label on
374 // the highlight line, or we would get:
381 // which is totally weird. Instead we want:
389 // which is...less weird, at least. In fact, in general, if
390 // the rightmost span overlaps with any other span, we should
391 // use the "hang below" version, so we can at least make it
392 // clear where the span *starts*. There's an exception for this
393 // logic, when the labels do not have a message:
408 let mut annotations_position = vec![];
409 let mut line_len = 0;
411 for (i, annotation) in annotations.iter().enumerate() {
412 for (j, next) in annotations.iter().enumerate() {
413 if overlaps(next, annotation, 0) // This label overlaps with another one and both
414 && annotation.has_label() // take space (they have text and are not
415 && j > i // multiline lines).
416 && p == 0 // We're currently on the first line, move the label one line down
418 // This annotation needs a new line in the output.
423 annotations_position.push((p, annotation));
424 for (j, next) in annotations.iter().enumerate() {
426 let l = if let Some(ref label) = next.label {
431 if (overlaps(next, annotation, l) // Do not allow two labels to be in the same
432 // line if they overlap including padding, to
433 // avoid situations like:
440 && annotation.has_label() // Both labels must have some text, otherwise
441 && next.has_label()) // they are not overlapping.
442 // Do not add a new line if this annotation
443 // or the next are vertical line placeholders.
444 || (annotation.takes_space() // If either this or the next annotation is
445 && next.has_label()) // multiline start/end, move it to a new line
446 || (annotation.has_label() // so as not to overlap the orizontal lines.
447 && next.takes_space())
448 || (annotation.takes_space()
449 && next.takes_space())
451 // This annotation needs a new line in the output.
466 // If there are no annotations or the only annotations on this line are
467 // MultilineLine, then there's only code being shown, stop processing.
468 if line.annotations.is_empty() || line.annotations.iter()
469 .filter(|a| !a.is_line()).collect::<Vec<_>>().len() == 0
474 // Write the colunmn separator.
476 // After this we will have:
485 for pos in 0..line_len + 1 {
486 draw_col_separator(buffer, line_offset + pos + 1, width_offset - 2);
487 buffer.putc(line_offset + pos + 1,
493 // Write the horizontal lines for multiline annotations
494 // (only the first and last lines need this).
496 // After this we will have:
505 for &(pos, annotation) in &annotations_position {
506 let style = if annotation.is_primary {
507 Style::UnderlinePrimary
509 Style::UnderlineSecondary
512 match annotation.annotation_type {
513 AnnotationType::MultilineStart(depth) |
514 AnnotationType::MultilineEnd(depth) => {
518 width_offset + depth,
519 code_offset + annotation.start_col,
526 // Write the vertical lines for labels that are on a different line as the underline.
528 // After this we will have:
537 for &(pos, annotation) in &annotations_position {
538 let style = if annotation.is_primary {
539 Style::UnderlinePrimary
541 Style::UnderlineSecondary
545 if pos > 1 && (annotation.has_label() || annotation.takes_space()) {
546 for p in line_offset + 1..line_offset + pos + 1 {
548 code_offset + annotation.start_col,
553 match annotation.annotation_type {
554 AnnotationType::MultilineStart(depth) => {
555 for p in line_offset + pos + 1..line_offset + line_len + 2 {
557 width_offset + depth - 1,
562 AnnotationType::MultilineEnd(depth) => {
563 for p in line_offset..line_offset + pos + 1 {
565 width_offset + depth - 1,
574 // Write the labels on the annotations that actually have a label.
576 // After this we will have:
581 // | something about `foo`
585 for &(pos, annotation) in &annotations_position {
586 let style = if annotation.is_primary {
589 Style::LabelSecondary
591 let (pos, col) = if pos == 0 {
592 (pos + 1, annotation.end_col + 1)
594 (pos + 2, annotation.start_col)
596 if let Some(ref label) = annotation.label {
597 buffer.puts(line_offset + pos,
604 // Sort from biggest span to smallest span so that smaller spans are
605 // represented in the output:
610 // | | something about `foo`
611 // | something about `fn foo()`
612 annotations_position.sort_by(|a, b| {
614 a.1.len().cmp(&b.1.len()).reverse()
617 // Write the underlines.
619 // After this we will have:
624 // | something about `foo`
628 for &(_, annotation) in &annotations_position {
629 let (underline, style) = if annotation.is_primary {
630 ('^', Style::UnderlinePrimary)
632 ('-', Style::UnderlineSecondary)
634 for p in annotation.start_col..annotation.end_col {
635 buffer.putc(line_offset + 1,
641 annotations_position.iter().filter_map(|&(_, annotation)| {
642 match annotation.annotation_type {
643 AnnotationType::MultilineStart(p) | AnnotationType::MultilineEnd(p) => {
644 let style = if annotation.is_primary {
647 Style::LabelSecondary
654 }).collect::<Vec<_>>()
657 fn get_multispan_max_line_num(&mut self, msp: &MultiSpan) -> usize {
659 if let Some(ref cm) = self.cm {
660 for primary_span in msp.primary_spans() {
661 if primary_span != &DUMMY_SP {
662 let hi = cm.lookup_char_pos(primary_span.hi);
668 for span_label in msp.span_labels() {
669 if span_label.span != DUMMY_SP {
670 let hi = cm.lookup_char_pos(span_label.span.hi);
680 fn get_max_line_num(&mut self, span: &MultiSpan, children: &Vec<SubDiagnostic>) -> usize {
683 let primary = self.get_multispan_max_line_num(span);
684 max = if primary > max { primary } else { max };
686 for sub in children {
687 let sub_result = self.get_multispan_max_line_num(&sub.span);
688 max = if sub_result > max { primary } else { max };
693 // This "fixes" MultiSpans that contain Spans that are pointing to locations inside of
694 // <*macros>. Since these locations are often difficult to read, we move these Spans from
695 // <*macros> to their corresponding use site.
696 fn fix_multispan_in_std_macros(&mut self, span: &mut MultiSpan) -> bool {
697 let mut spans_updated = false;
699 if let Some(ref cm) = self.cm {
700 let mut before_after: Vec<(Span, Span)> = vec![];
701 let mut new_labels: Vec<(Span, String)> = vec![];
703 // First, find all the spans in <*macros> and point instead at their use site
704 for sp in span.primary_spans() {
708 let call_sp = cm.call_span_if_macro(*sp);
710 before_after.push((sp.clone(), call_sp));
712 for trace in sp.macro_backtrace().iter().rev() {
713 // Only show macro locations that are local
714 // and display them like a span_note
715 if let Some(def_site) = trace.def_site_span {
716 if def_site == DUMMY_SP {
719 // Check to make sure we're not in any <*macros>
720 if !cm.span_to_filename(def_site).contains("macros>") &&
721 !trace.macro_decl_name.starts_with("#[") {
722 new_labels.push((trace.call_site,
723 "in this macro invocation".to_string()));
729 for (label_span, label_text) in new_labels {
730 span.push_span_label(label_span, label_text);
732 for sp_label in span.span_labels() {
733 if sp_label.span == DUMMY_SP {
736 if cm.span_to_filename(sp_label.span.clone()).contains("macros>") {
737 let v = sp_label.span.macro_backtrace();
738 if let Some(use_site) = v.last() {
739 before_after.push((sp_label.span.clone(), use_site.call_site.clone()));
743 // After we have them, make sure we replace these 'bad' def sites with their use sites
744 for (before, after) in before_after {
745 span.replace(before, after);
746 spans_updated = true;
753 // This does a small "fix" for multispans by looking to see if it can find any that
754 // point directly at <*macros>. Since these are often difficult to read, this
755 // will change the span to point at the use site.
756 fn fix_multispans_in_std_macros(&mut self,
757 span: &mut MultiSpan,
758 children: &mut Vec<SubDiagnostic>) {
759 let mut spans_updated = self.fix_multispan_in_std_macros(span);
760 for child in children.iter_mut() {
761 spans_updated |= self.fix_multispan_in_std_macros(&mut child.span);
764 children.push(SubDiagnostic {
766 message: vec![("this error originates in a macro outside of the current crate"
767 .to_string(), Style::NoStyle)],
768 span: MultiSpan::new(),
774 /// Add a left margin to every line but the first, given a padding length and the label being
775 /// displayed, keeping the provided highlighting.
776 fn msg_to_buffer(&self,
777 buffer: &mut StyledBuffer,
778 msg: &[(String, Style)],
781 override_style: Option<Style>) {
783 // The extra 5 ` ` is padding that's always needed to align to the `note: `:
796 // | | length of label
798 // `max_line_num_len`
799 let padding = (0..padding + label.len() + 5)
801 .collect::<String>();
803 /// Return wether `style`, or the override if present and the style is `NoStyle`.
804 fn style_or_override(style: Style, override_style: Option<Style>) -> Style {
805 if let Some(o) = override_style {
806 if style == Style::NoStyle {
813 let mut line_number = 0;
815 // Provided the following diagnostic message:
819 // ("highlighted multiline\nstring to\nsee how it ", Style::NoStyle),
820 // ("looks", Style::Highlight),
821 // ("with\nvery ", Style::NoStyle),
822 // ("weird", Style::Highlight),
823 // (" formats\n", Style::NoStyle),
824 // ("see?", Style::Highlight),
827 // the expected output on a note is (* surround the highlighted text)
829 // = note: highlighted multiline
831 // see how it *looks* with
832 // very *weird* formats
834 for &(ref text, ref style) in msg.iter() {
835 let lines = text.split('\n').collect::<Vec<_>>();
837 for (i, line) in lines.iter().enumerate() {
840 buffer.append(line_number, &padding, Style::NoStyle);
842 buffer.append(line_number, line, style_or_override(*style, override_style));
845 buffer.append(line_number, text, style_or_override(*style, override_style));
850 fn emit_message_default(&mut self,
852 msg: &Vec<(String, Style)>,
853 code: &Option<String>,
855 max_line_num_len: usize,
858 let mut buffer = StyledBuffer::new();
860 if msp.primary_spans().is_empty() && msp.span_labels().is_empty() && is_secondary {
861 // This is a secondary message with no span info
862 for _ in 0..max_line_num_len {
863 buffer.prepend(0, " ", Style::NoStyle);
865 draw_note_separator(&mut buffer, 0, max_line_num_len + 1);
866 buffer.append(0, &level.to_string(), Style::HeaderMsg);
867 buffer.append(0, ": ", Style::NoStyle);
868 self.msg_to_buffer(&mut buffer, msg, max_line_num_len, "note", None);
870 buffer.append(0, &level.to_string(), Style::Level(level.clone()));
873 buffer.append(0, "[", Style::Level(level.clone()));
874 buffer.append(0, &code, Style::Level(level.clone()));
875 buffer.append(0, "]", Style::Level(level.clone()));
879 buffer.append(0, ": ", Style::HeaderMsg);
880 for &(ref text, _) in msg.iter() {
881 buffer.append(0, text, Style::HeaderMsg);
885 // Preprocess all the annotations so that they are grouped by file and by line number
886 // This helps us quickly iterate over the whole message (including secondary file spans)
887 let mut annotated_files = self.preprocess_annotations(msp);
889 // Make sure our primary file comes first
890 let primary_lo = if let (Some(ref cm), Some(ref primary_span)) =
891 (self.cm.as_ref(), msp.primary_span().as_ref()) {
892 if primary_span != &&DUMMY_SP {
893 cm.lookup_char_pos(primary_span.lo)
895 emit_to_destination(&buffer.render(), level, &mut self.dst)?;
899 // If we don't have span information, emit and exit
900 emit_to_destination(&buffer.render(), level, &mut self.dst)?;
904 annotated_files.binary_search_by(|x| x.file.name.cmp(&primary_lo.file.name)) {
905 annotated_files.swap(0, pos);
908 // Print out the annotate source lines that correspond with the error
909 for annotated_file in annotated_files {
910 // we can't annotate anything if the source is unavailable.
911 if annotated_file.file.src.is_none() {
915 // print out the span location and spacer before we print the annotated source
916 // to do this, we need to know if this span will be primary
917 let is_primary = primary_lo.file.name == annotated_file.file.name;
919 // remember where we are in the output buffer for easy reference
920 let buffer_msg_line_offset = buffer.num_lines();
922 buffer.prepend(buffer_msg_line_offset, "--> ", Style::LineNumber);
923 let loc = primary_lo.clone();
924 buffer.append(buffer_msg_line_offset,
925 &format!("{}:{}:{}", loc.file.name, loc.line, loc.col.0 + 1),
926 Style::LineAndColumn);
927 for _ in 0..max_line_num_len {
928 buffer.prepend(buffer_msg_line_offset, " ", Style::NoStyle);
931 // remember where we are in the output buffer for easy reference
932 let buffer_msg_line_offset = buffer.num_lines();
935 draw_col_separator(&mut buffer, buffer_msg_line_offset, max_line_num_len + 1);
937 // Then, the secondary file indicator
938 buffer.prepend(buffer_msg_line_offset + 1, "::: ", Style::LineNumber);
939 buffer.append(buffer_msg_line_offset + 1,
940 &annotated_file.file.name,
941 Style::LineAndColumn);
942 for _ in 0..max_line_num_len {
943 buffer.prepend(buffer_msg_line_offset + 1, " ", Style::NoStyle);
947 // Put in the spacer between the location and annotated source
948 let buffer_msg_line_offset = buffer.num_lines();
949 draw_col_separator_no_space(&mut buffer, buffer_msg_line_offset, max_line_num_len + 1);
951 // Contains the vertical lines' positions for active multiline annotations
952 let mut multilines = HashMap::new();
954 // Next, output the annotate source for this file
955 for line_idx in 0..annotated_file.lines.len() {
956 let previous_buffer_line = buffer.num_lines();
958 let width_offset = 3 + max_line_num_len;
959 let code_offset = if annotated_file.multiline_depth == 0 {
962 width_offset + annotated_file.multiline_depth + 1
965 let depths = self.render_source_line(&mut buffer,
966 annotated_file.file.clone(),
967 &annotated_file.lines[line_idx],
971 let mut to_add = HashMap::new();
973 for (depth, style) in depths {
974 if multilines.get(&depth).is_some() {
975 multilines.remove(&depth);
977 to_add.insert(depth, style);
981 // Set the multiline annotation vertical lines to the left of
982 // the code in this line.
983 for (depth, style) in &multilines {
984 for line in previous_buffer_line..buffer.num_lines() {
985 draw_multiline_line(&mut buffer,
992 // check to see if we need to print out or elide lines that come between
993 // this annotated line and the next one.
994 if line_idx < (annotated_file.lines.len() - 1) {
995 let line_idx_delta = annotated_file.lines[line_idx + 1].line_index -
996 annotated_file.lines[line_idx].line_index;
997 if line_idx_delta > 2 {
998 let last_buffer_line_num = buffer.num_lines();
999 buffer.puts(last_buffer_line_num, 0, "...", Style::LineNumber);
1001 // Set the multiline annotation vertical lines on `...` bridging line.
1002 for (depth, style) in &multilines {
1003 draw_multiline_line(&mut buffer,
1004 last_buffer_line_num,
1009 } else if line_idx_delta == 2 {
1010 let unannotated_line = annotated_file.file
1011 .get_line(annotated_file.lines[line_idx].line_index)
1014 let last_buffer_line_num = buffer.num_lines();
1016 buffer.puts(last_buffer_line_num,
1018 &(annotated_file.lines[line_idx + 1].line_index - 1)
1021 draw_col_separator(&mut buffer, last_buffer_line_num, 1 + max_line_num_len);
1022 buffer.puts(last_buffer_line_num,
1027 for (depth, style) in &multilines {
1028 draw_multiline_line(&mut buffer,
1029 last_buffer_line_num,
1037 multilines.extend(&to_add);
1041 // final step: take our styled buffer, render it, then output it
1042 emit_to_destination(&buffer.render(), level, &mut self.dst)?;
1046 fn emit_suggestion_default(&mut self,
1047 suggestion: &CodeSuggestion,
1049 max_line_num_len: usize)
1051 use std::borrow::Borrow;
1053 let primary_span = suggestion.substitution_spans().next().unwrap();
1054 if let Some(ref cm) = self.cm {
1055 let mut buffer = StyledBuffer::new();
1057 let lines = cm.span_to_lines(primary_span).unwrap();
1059 assert!(!lines.lines.is_empty());
1061 buffer.append(0, &level.to_string(), Style::Level(level.clone()));
1062 buffer.append(0, ": ", Style::HeaderMsg);
1063 self.msg_to_buffer(&mut buffer,
1064 &[(suggestion.msg.to_owned(), Style::NoStyle)],
1067 Some(Style::HeaderMsg));
1069 let suggestions = suggestion.splice_lines(cm.borrow());
1070 let mut row_num = 1;
1071 for complete in suggestions.iter().take(MAX_SUGGESTIONS) {
1073 // print the suggestion without any line numbers, but leave
1074 // space for them. This helps with lining up with previous
1075 // snippets from the actual error being reported.
1076 let mut lines = complete.lines();
1077 for line in lines.by_ref().take(MAX_HIGHLIGHT_LINES) {
1078 draw_col_separator(&mut buffer, row_num, max_line_num_len + 1);
1079 buffer.append(row_num, line, Style::NoStyle);
1083 // if we elided some lines, add an ellipsis
1084 if let Some(_) = lines.next() {
1085 buffer.append(row_num, "...", Style::NoStyle);
1088 if suggestions.len() > MAX_SUGGESTIONS {
1089 let msg = format!("and {} other candidates", suggestions.len() - MAX_SUGGESTIONS);
1090 buffer.append(row_num, &msg, Style::NoStyle);
1092 emit_to_destination(&buffer.render(), level, &mut self.dst)?;
1096 fn emit_messages_default(&mut self,
1098 message: &Vec<(String, Style)>,
1099 code: &Option<String>,
1101 children: &Vec<SubDiagnostic>) {
1102 let max_line_num = self.get_max_line_num(span, children);
1103 let max_line_num_len = max_line_num.to_string().len();
1105 match self.emit_message_default(span, message, code, level, max_line_num_len, false) {
1107 if !children.is_empty() {
1108 let mut buffer = StyledBuffer::new();
1109 draw_col_separator_no_space(&mut buffer, 0, max_line_num_len + 1);
1110 match emit_to_destination(&buffer.render(), level, &mut self.dst) {
1112 Err(e) => panic!("failed to emit error: {}", e)
1115 for child in children {
1116 match child.render_span {
1117 Some(FullSpan(ref msp)) => {
1118 match self.emit_message_default(msp,
1119 &child.styled_message(),
1124 Err(e) => panic!("failed to emit error: {}", e),
1128 Some(Suggestion(ref cs)) => {
1129 match self.emit_suggestion_default(cs,
1132 Err(e) => panic!("failed to emit error: {}", e),
1137 match self.emit_message_default(&child.span,
1138 &child.styled_message(),
1143 Err(e) => panic!("failed to emit error: {}", e),
1150 Err(e) => panic!("failed to emit error: {}", e),
1152 match write!(&mut self.dst, "\n") {
1153 Err(e) => panic!("failed to emit error: {}", e),
1155 match self.dst.flush() {
1156 Err(e) => panic!("failed to emit error: {}", e),
1164 fn draw_col_separator(buffer: &mut StyledBuffer, line: usize, col: usize) {
1165 buffer.puts(line, col, "| ", Style::LineNumber);
1168 fn draw_col_separator_no_space(buffer: &mut StyledBuffer, line: usize, col: usize) {
1169 draw_col_separator_no_space_with_style(buffer, line, col, Style::LineNumber);
1172 fn draw_col_separator_no_space_with_style(buffer: &mut StyledBuffer,
1176 buffer.putc(line, col, '|', style);
1179 fn draw_range(buffer: &mut StyledBuffer, symbol: char, line: usize,
1180 col_from: usize, col_to: usize, style: Style) {
1181 for col in col_from..col_to {
1182 buffer.putc(line, col, symbol, style);
1186 fn draw_note_separator(buffer: &mut StyledBuffer, line: usize, col: usize) {
1187 buffer.puts(line, col, "= ", Style::LineNumber);
1190 fn draw_multiline_line(buffer: &mut StyledBuffer,
1196 buffer.putc(line, offset + depth - 1, '|', style);
1199 fn num_overlap(a_start: usize, a_end: usize, b_start: usize, b_end:usize, inclusive: bool) -> bool {
1200 let extra = if inclusive {
1205 (b_start..b_end + extra).contains(a_start) ||
1206 (a_start..a_end + extra).contains(b_start)
1208 fn overlaps(a1: &Annotation, a2: &Annotation, padding: usize) -> bool {
1209 num_overlap(a1.start_col, a1.end_col + padding, a2.start_col, a2.end_col, false)
1212 fn emit_to_destination(rendered_buffer: &Vec<Vec<StyledString>>,
1214 dst: &mut Destination)
1218 // In order to prevent error message interleaving, where multiple error lines get intermixed
1219 // when multiple compiler processes error simultaneously, we emit errors with additional
1222 // On Unix systems, we write into a buffered terminal rather than directly to a terminal. When
1223 // the .flush() is called we take the buffer created from the buffered writes and write it at
1224 // one shot. Because the Unix systems use ANSI for the colors, which is a text-based styling
1225 // scheme, this buffered approach works and maintains the styling.
1227 // On Windows, styling happens through calls to a terminal API. This prevents us from using the
1228 // same buffering approach. Instead, we use a global Windows mutex, which we acquire long
1229 // enough to output the full error message, then we release.
1230 let _buffer_lock = lock::acquire_global_lock("rustc_errors");
1231 for line in rendered_buffer {
1233 dst.apply_style(lvl.clone(), part.style)?;
1234 write!(dst, "{}", part.text)?;
1244 fn stderr_isatty() -> bool {
1246 unsafe { libc::isatty(libc::STDERR_FILENO) != 0 }
1249 fn stderr_isatty() -> bool {
1252 type HANDLE = *mut u8;
1253 const STD_ERROR_HANDLE: DWORD = -12i32 as DWORD;
1255 fn GetStdHandle(which: DWORD) -> HANDLE;
1256 fn GetConsoleMode(hConsoleHandle: HANDLE, lpMode: *mut DWORD) -> BOOL;
1259 let handle = GetStdHandle(STD_ERROR_HANDLE);
1261 GetConsoleMode(handle, &mut out) != 0
1265 pub type BufferedStderr = term::Terminal<Output = BufferedWriter> + Send;
1267 pub enum Destination {
1268 Terminal(Box<term::StderrTerminal>),
1269 BufferedTerminal(Box<BufferedStderr>),
1270 Raw(Box<Write + Send>),
1273 /// Buffered writer gives us a way on Unix to buffer up an entire error message before we output
1274 /// it. This helps to prevent interleaving of multiple error messages when multiple compiler
1275 /// processes error simultaneously
1276 pub struct BufferedWriter {
1280 impl BufferedWriter {
1281 // note: we use _new because the conditional compilation at its use site may make this
1282 // this function unused on some platforms
1283 fn _new() -> BufferedWriter {
1284 BufferedWriter { buffer: vec![] }
1288 impl Write for BufferedWriter {
1289 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
1291 self.buffer.push(*b);
1295 fn flush(&mut self) -> io::Result<()> {
1296 let mut stderr = io::stderr();
1297 let result = stderr.write_all(&self.buffer)
1298 .and_then(|_| stderr.flush());
1299 self.buffer.clear();
1305 #[cfg(not(windows))]
1306 /// When not on Windows, prefer the buffered terminal so that we can buffer an entire error
1307 /// to be emitted at one time.
1308 fn from_stderr() -> Destination {
1309 let stderr: Option<Box<BufferedStderr>> =
1310 term::TerminfoTerminal::new(BufferedWriter::_new())
1311 .map(|t| Box::new(t) as Box<BufferedStderr>);
1314 Some(t) => BufferedTerminal(t),
1315 None => Raw(Box::new(io::stderr())),
1320 /// Return a normal, unbuffered terminal when on Windows.
1321 fn from_stderr() -> Destination {
1322 let stderr: Option<Box<term::StderrTerminal>> = term::TerminfoTerminal::new(io::stderr())
1323 .map(|t| Box::new(t) as Box<term::StderrTerminal>)
1325 term::WinConsole::new(io::stderr())
1327 .map(|t| Box::new(t) as Box<term::StderrTerminal>)
1331 Some(t) => Terminal(t),
1332 None => Raw(Box::new(io::stderr())),
1336 fn apply_style(&mut self, lvl: Level, style: Style) -> io::Result<()> {
1338 Style::FileNameStyle | Style::LineAndColumn => {}
1339 Style::LineNumber => {
1340 self.start_attr(term::Attr::Bold)?;
1342 self.start_attr(term::Attr::ForegroundColor(term::color::BRIGHT_CYAN))?;
1344 self.start_attr(term::Attr::ForegroundColor(term::color::BRIGHT_BLUE))?;
1347 Style::ErrorCode => {
1348 self.start_attr(term::Attr::Bold)?;
1349 self.start_attr(term::Attr::ForegroundColor(term::color::BRIGHT_MAGENTA))?;
1351 Style::Quotation => {}
1352 Style::OldSchoolNote => {
1353 self.start_attr(term::Attr::Bold)?;
1354 self.start_attr(term::Attr::ForegroundColor(term::color::BRIGHT_GREEN))?;
1356 Style::OldSchoolNoteText | Style::HeaderMsg => {
1357 self.start_attr(term::Attr::Bold)?;
1359 self.start_attr(term::Attr::ForegroundColor(term::color::BRIGHT_WHITE))?;
1362 Style::UnderlinePrimary | Style::LabelPrimary => {
1363 self.start_attr(term::Attr::Bold)?;
1364 self.start_attr(term::Attr::ForegroundColor(lvl.color()))?;
1366 Style::UnderlineSecondary |
1367 Style::LabelSecondary => {
1368 self.start_attr(term::Attr::Bold)?;
1370 self.start_attr(term::Attr::ForegroundColor(term::color::BRIGHT_CYAN))?;
1372 self.start_attr(term::Attr::ForegroundColor(term::color::BRIGHT_BLUE))?;
1375 Style::NoStyle => {}
1376 Style::Level(l) => {
1377 self.start_attr(term::Attr::Bold)?;
1378 self.start_attr(term::Attr::ForegroundColor(l.color()))?;
1380 Style::Highlight => self.start_attr(term::Attr::Bold)?,
1385 fn start_attr(&mut self, attr: term::Attr) -> io::Result<()> {
1387 Terminal(ref mut t) => {
1390 BufferedTerminal(ref mut t) => {
1398 fn reset_attrs(&mut self) -> io::Result<()> {
1400 Terminal(ref mut t) => {
1403 BufferedTerminal(ref mut t) => {
1412 impl Write for Destination {
1413 fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
1415 Terminal(ref mut t) => t.write(bytes),
1416 BufferedTerminal(ref mut t) => t.write(bytes),
1417 Raw(ref mut w) => w.write(bytes),
1420 fn flush(&mut self) -> io::Result<()> {
1422 Terminal(ref mut t) => t.flush(),
1423 BufferedTerminal(ref mut t) => t.flush(),
1424 Raw(ref mut w) => w.flush(),