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();
37 self.fix_multispans_in_std_macros(&mut primary_span, &mut children);
38 self.emit_messages_default(&db.level,
46 /// maximum number of lines we will print for each error; arbitrary.
47 pub const MAX_HIGHLIGHT_LINES: usize = 6;
49 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
50 pub enum ColorConfig {
57 fn use_color(&self) -> bool {
59 ColorConfig::Always => true,
60 ColorConfig::Never => false,
61 ColorConfig::Auto => stderr_isatty(),
66 pub struct EmitterWriter {
68 cm: Option<Rc<CodeMapper>>,
71 struct FileWithAnnotatedLines {
74 multiline_depth: usize,
78 /// Do not use this for messages that end in `\n` – use `println_maybe_styled` instead. See
79 /// `EmitterWriter::print_maybe_styled` for details.
80 macro_rules! print_maybe_styled {
81 ($dst: expr, $style: expr, $($arg: tt)*) => {
82 $dst.print_maybe_styled(format_args!($($arg)*), $style, false)
86 macro_rules! println_maybe_styled {
87 ($dst: expr, $style: expr, $($arg: tt)*) => {
88 $dst.print_maybe_styled(format_args!($($arg)*), $style, true)
93 pub fn stderr(color_config: ColorConfig, code_map: Option<Rc<CodeMapper>>) -> EmitterWriter {
94 if color_config.use_color() {
95 let dst = Destination::from_stderr();
102 dst: Raw(Box::new(io::stderr())),
108 pub fn new(dst: Box<Write + Send>, code_map: Option<Rc<CodeMapper>>) -> EmitterWriter {
115 fn preprocess_annotations(&self, msp: &MultiSpan) -> Vec<FileWithAnnotatedLines> {
116 fn add_annotation_to_file(file_vec: &mut Vec<FileWithAnnotatedLines>,
121 for slot in file_vec.iter_mut() {
122 // Look through each of our files for the one we're adding to
123 if slot.file.name == file.name {
124 // See if we already have a line for it
125 for line_slot in &mut slot.lines {
126 if line_slot.line_index == line_index {
127 line_slot.annotations.push(ann);
131 // We don't have a line yet, create one
132 slot.lines.push(Line {
133 line_index: line_index,
134 annotations: vec![ann],
140 // This is the first time we're seeing the file
141 file_vec.push(FileWithAnnotatedLines {
144 line_index: line_index,
145 annotations: vec![ann],
151 let mut output = vec![];
152 let mut multiline_annotations = vec![];
154 if let Some(ref cm) = self.cm {
155 for span_label in msp.span_labels() {
156 if span_label.span == DUMMY_SP {
159 let lo = cm.lookup_char_pos(span_label.span.lo);
160 let mut hi = cm.lookup_char_pos(span_label.span.hi);
162 // Watch out for "empty spans". If we get a span like 6..6, we
163 // want to just display a `^` at 6, so convert that to
164 // 6..7. This is degenerate input, but it's best to degrade
165 // gracefully -- and the parser likes to supply a span like
166 // that for EOF, in particular.
167 if lo.col == hi.col && lo.line == hi.line {
168 hi.col = CharPos(lo.col.0 + 1);
171 let ann_type = if lo.line != hi.line {
172 let ml = MultilineAnnotation {
178 is_primary: span_label.is_primary,
179 label: span_label.label.clone(),
181 multiline_annotations.push((lo.file.clone(), ml.clone()));
182 AnnotationType::Multiline(ml)
184 AnnotationType::Singleline
186 let ann = Annotation {
189 is_primary: span_label.is_primary,
190 label: span_label.label.clone(),
191 annotation_type: ann_type,
194 if !ann.is_multiline() {
195 add_annotation_to_file(&mut output,
203 // Find overlapping multiline annotations, put them at different depths
204 multiline_annotations.sort_by(|a, b| {
205 (a.1.line_start, a.1.line_end).cmp(&(b.1.line_start, b.1.line_end))
207 for item in multiline_annotations.clone() {
209 for item in multiline_annotations.iter_mut() {
210 let ref mut a = item.1;
211 // Move all other multiline annotations overlapping with this one
212 // one level to the right.
214 num_overlap(ann.line_start, ann.line_end, a.line_start, a.line_end, true)
223 let mut max_depth = 0; // max overlapping multiline spans
224 for (file, ann) in multiline_annotations {
225 if ann.depth > max_depth {
226 max_depth = ann.depth;
228 add_annotation_to_file(&mut output, file.clone(), ann.line_start, ann.as_start());
229 let middle = min(ann.line_start + 4, ann.line_end);
230 for line in ann.line_start + 1..middle {
231 add_annotation_to_file(&mut output, file.clone(), line, ann.as_line());
233 if middle < ann.line_end - 1 {
234 for line in ann.line_end - 1..ann.line_end {
235 add_annotation_to_file(&mut output, file.clone(), line, ann.as_line());
238 add_annotation_to_file(&mut output, file, ann.line_end, ann.as_end());
240 for file_vec in output.iter_mut() {
241 file_vec.multiline_depth = max_depth;
246 fn render_source_line(&self,
247 buffer: &mut StyledBuffer,
251 code_offset: usize) -> Vec<(usize, Style)> {
252 let source_string = file.get_line(line.line_index - 1)
255 let line_offset = buffer.num_lines();
257 // First create the source line we will highlight.
258 buffer.puts(line_offset, code_offset, &source_string, Style::Quotation);
259 buffer.puts(line_offset,
261 &(line.line_index.to_string()),
264 draw_col_separator(buffer, line_offset, width_offset - 2);
266 // Special case when there's only one annotation involved, it is the start of a multiline
267 // span and there's no text at the beginning of the code line. Instead of doing the whole
276 // we simplify the output to:
282 if line.annotations.len() == 1 {
283 if let Some(ref ann) = line.annotations.get(0) {
284 if let AnnotationType::MultilineStart(depth) = ann.annotation_type {
285 if source_string[0..ann.start_col].trim() == "" {
286 let style = if ann.is_primary {
287 Style::UnderlinePrimary
289 Style::UnderlineSecondary
291 buffer.putc(line_offset,
292 width_offset + depth - 1,
295 return vec![(depth, style)];
301 // We want to display like this:
303 // vec.push(vec.pop().unwrap());
304 // --- ^^^ - previous borrow ends here
306 // | error occurs here
307 // previous borrow of `vec` occurs here
309 // But there are some weird edge cases to be aware of:
311 // vec.push(vec.pop().unwrap());
312 // -------- - previous borrow ends here
314 // |this makes no sense
315 // previous borrow of `vec` occurs here
317 // For this reason, we group the lines into "highlight lines"
318 // and "annotations lines", where the highlight lines have the `^`.
320 // Sort the annotations by (start, end col)
321 let mut annotations = line.annotations.clone();
323 annotations.reverse();
325 // First, figure out where each label will be positioned.
327 // In the case where you have the following annotations:
329 // vec.push(vec.pop().unwrap());
330 // -------- - previous borrow ends here [C]
332 // |this makes no sense [B]
333 // previous borrow of `vec` occurs here [A]
335 // `annotations_position` will hold [(2, A), (1, B), (0, C)].
337 // We try, when possible, to stick the rightmost annotation at the end
338 // of the highlight line:
340 // vec.push(vec.pop().unwrap());
341 // --- --- - previous borrow ends here
343 // But sometimes that's not possible because one of the other
344 // annotations overlaps it. For example, from the test
345 // `span_overlap_label`, we have the following annotations
346 // (written on distinct lines for clarity):
352 // In this case, we can't stick the rightmost-most label on
353 // the highlight line, or we would get:
360 // which is totally weird. Instead we want:
368 // which is...less weird, at least. In fact, in general, if
369 // the rightmost span overlaps with any other span, we should
370 // use the "hang below" version, so we can at least make it
371 // clear where the span *starts*. There's an exception for this
372 // logic, when the labels do not have a message:
387 let mut annotations_position = vec![];
388 let mut line_len = 0;
390 for (i, annotation) in annotations.iter().enumerate() {
391 for (j, next) in annotations.iter().enumerate() {
392 if overlaps(next, annotation, 0) // This label overlaps with another one and both
393 && annotation.has_label() // take space (they have text and are not
394 && j > i // multiline lines).
395 && p == 0 // We're currently on the first line, move the label one line down
397 // This annotation needs a new line in the output.
402 annotations_position.push((p, annotation));
403 for (j, next) in annotations.iter().enumerate() {
405 let l = if let Some(ref label) = next.label {
410 if (overlaps(next, annotation, l) // Do not allow two labels to be in the same
411 // line if they overlap including padding, to
412 // avoid situations like:
419 && annotation.has_label() // Both labels must have some text, otherwise
420 && next.has_label()) // they are not overlapping.
421 // Do not add a new line if this annotation
422 // or the next are vertical line placeholders.
423 || (annotation.takes_space() // If either this or the next annotation is
424 && next.has_label()) // multiline start/end, move it to a new line
425 || (annotation.has_label() // so as not to overlap the orizontal lines.
426 && next.takes_space())
427 || (annotation.takes_space()
428 && next.takes_space())
430 // This annotation needs a new line in the output.
445 // If there are no annotations or the only annotations on this line are
446 // MultilineLine, then there's only code being shown, stop processing.
447 if line.annotations.is_empty() || line.annotations.iter()
448 .filter(|a| !a.is_line()).collect::<Vec<_>>().len() == 0
453 // Write the colunmn separator.
455 // After this we will have:
464 for pos in 0..line_len + 1 {
465 draw_col_separator(buffer, line_offset + pos + 1, width_offset - 2);
466 buffer.putc(line_offset + pos + 1,
472 // Write the horizontal lines for multiline annotations
473 // (only the first and last lines need this).
475 // After this we will have:
484 for &(pos, annotation) in &annotations_position {
485 let style = if annotation.is_primary {
486 Style::UnderlinePrimary
488 Style::UnderlineSecondary
491 match annotation.annotation_type {
492 AnnotationType::MultilineStart(depth) |
493 AnnotationType::MultilineEnd(depth) => {
497 width_offset + depth,
498 code_offset + annotation.start_col,
505 // Write the vertical lines for labels that are on a different line as the underline.
507 // After this we will have:
516 for &(pos, annotation) in &annotations_position {
517 let style = if annotation.is_primary {
518 Style::UnderlinePrimary
520 Style::UnderlineSecondary
524 if pos > 1 && (annotation.has_label() || annotation.takes_space()) {
525 for p in line_offset + 1..line_offset + pos + 1 {
527 code_offset + annotation.start_col,
532 match annotation.annotation_type {
533 AnnotationType::MultilineStart(depth) => {
534 for p in line_offset + pos + 1..line_offset + line_len + 2 {
536 width_offset + depth - 1,
541 AnnotationType::MultilineEnd(depth) => {
542 for p in line_offset..line_offset + pos + 1 {
544 width_offset + depth - 1,
553 // Write the labels on the annotations that actually have a label.
555 // After this we will have:
560 // | something about `foo`
564 for &(pos, annotation) in &annotations_position {
565 let style = if annotation.is_primary {
568 Style::LabelSecondary
570 let (pos, col) = if pos == 0 {
571 (pos + 1, annotation.end_col + 1)
573 (pos + 2, annotation.start_col)
575 if let Some(ref label) = annotation.label {
576 buffer.puts(line_offset + pos,
583 // Sort from biggest span to smallest span so that smaller spans are
584 // represented in the output:
589 // | | something about `foo`
590 // | something about `fn foo()`
591 annotations_position.sort_by(|a, b| {
593 a.1.len().cmp(&b.1.len()).reverse()
596 // Write the underlines.
598 // After this we will have:
603 // | something about `foo`
607 for &(_, annotation) in &annotations_position {
608 let (underline, style) = if annotation.is_primary {
609 ('^', Style::UnderlinePrimary)
611 ('-', Style::UnderlineSecondary)
613 for p in annotation.start_col..annotation.end_col {
614 buffer.putc(line_offset + 1,
620 annotations_position.iter().filter_map(|&(_, annotation)| {
621 match annotation.annotation_type {
622 AnnotationType::MultilineStart(p) | AnnotationType::MultilineEnd(p) => {
623 let style = if annotation.is_primary {
626 Style::LabelSecondary
633 }).collect::<Vec<_>>()
636 fn get_multispan_max_line_num(&mut self, msp: &MultiSpan) -> usize {
638 if let Some(ref cm) = self.cm {
639 for primary_span in msp.primary_spans() {
640 if primary_span != &DUMMY_SP {
641 let hi = cm.lookup_char_pos(primary_span.hi);
647 for span_label in msp.span_labels() {
648 if span_label.span != DUMMY_SP {
649 let hi = cm.lookup_char_pos(span_label.span.hi);
659 fn get_max_line_num(&mut self, span: &MultiSpan, children: &Vec<SubDiagnostic>) -> usize {
662 let primary = self.get_multispan_max_line_num(span);
663 max = if primary > max { primary } else { max };
665 for sub in children {
666 let sub_result = self.get_multispan_max_line_num(&sub.span);
667 max = if sub_result > max { primary } else { max };
672 // This "fixes" MultiSpans that contain Spans that are pointing to locations inside of
673 // <*macros>. Since these locations are often difficult to read, we move these Spans from
674 // <*macros> to their corresponding use site.
675 fn fix_multispan_in_std_macros(&mut self, span: &mut MultiSpan) -> bool {
676 let mut spans_updated = false;
678 if let Some(ref cm) = self.cm {
679 let mut before_after: Vec<(Span, Span)> = vec![];
680 let mut new_labels: Vec<(Span, String)> = vec![];
682 // First, find all the spans in <*macros> and point instead at their use site
683 for sp in span.primary_spans() {
687 if cm.span_to_filename(sp.clone()).contains("macros>") {
688 let v = sp.macro_backtrace();
689 if let Some(use_site) = v.last() {
690 before_after.push((sp.clone(), use_site.call_site.clone()));
693 for trace in sp.macro_backtrace().iter().rev() {
694 // Only show macro locations that are local
695 // and display them like a span_note
696 if let Some(def_site) = trace.def_site_span {
697 if def_site == DUMMY_SP {
700 // Check to make sure we're not in any <*macros>
701 if !cm.span_to_filename(def_site).contains("macros>") &&
702 !trace.macro_decl_name.starts_with("#[") {
703 new_labels.push((trace.call_site,
704 "in this macro invocation".to_string()));
710 for (label_span, label_text) in new_labels {
711 span.push_span_label(label_span, label_text);
713 for sp_label in span.span_labels() {
714 if sp_label.span == DUMMY_SP {
717 if cm.span_to_filename(sp_label.span.clone()).contains("macros>") {
718 let v = sp_label.span.macro_backtrace();
719 if let Some(use_site) = v.last() {
720 before_after.push((sp_label.span.clone(), use_site.call_site.clone()));
724 // After we have them, make sure we replace these 'bad' def sites with their use sites
725 for (before, after) in before_after {
726 span.replace(before, after);
727 spans_updated = true;
734 // This does a small "fix" for multispans by looking to see if it can find any that
735 // point directly at <*macros>. Since these are often difficult to read, this
736 // will change the span to point at the use site.
737 fn fix_multispans_in_std_macros(&mut self,
738 span: &mut MultiSpan,
739 children: &mut Vec<SubDiagnostic>) {
740 let mut spans_updated = self.fix_multispan_in_std_macros(span);
741 for child in children.iter_mut() {
742 spans_updated |= self.fix_multispan_in_std_macros(&mut child.span);
745 children.push(SubDiagnostic {
747 message: vec![("this error originates in a macro outside of the current crate"
748 .to_string(), Style::NoStyle)],
749 span: MultiSpan::new(),
755 /// Add a left margin to every line but the first, given a padding length and the label being
756 /// displayed, keeping the provided highlighting.
757 fn msg_to_buffer(&self,
758 buffer: &mut StyledBuffer,
759 msg: &Vec<(String, Style)>,
762 override_style: Option<Style>) {
764 // The extra 5 ` ` is padding that's always needed to align to the `note: `:
777 // | | length of label
779 // `max_line_num_len`
780 let padding = (0..padding + label.len() + 5)
782 .collect::<String>();
784 /// Return wether `style`, or the override if present and the style is `NoStyle`.
785 fn style_or_override(style: Style, override_style: Option<Style>) -> Style {
786 if let Some(o) = override_style {
787 if style == Style::NoStyle {
794 let mut line_number = 0;
796 // Provided the following diagnostic message:
800 // ("highlighted multiline\nstring to\nsee how it ", Style::NoStyle),
801 // ("looks", Style::Highlight),
802 // ("with\nvery ", Style::NoStyle),
803 // ("weird", Style::Highlight),
804 // (" formats\n", Style::NoStyle),
805 // ("see?", Style::Highlight),
808 // the expected output on a note is (* surround the highlighted text)
810 // = note: highlighted multiline
812 // see how it *looks* with
813 // very *weird* formats
815 for &(ref text, ref style) in msg.iter() {
816 let lines = text.split('\n').collect::<Vec<_>>();
818 for (i, line) in lines.iter().enumerate() {
821 buffer.append(line_number, &padding, Style::NoStyle);
823 buffer.append(line_number, line, style_or_override(*style, override_style));
826 buffer.append(line_number, text, style_or_override(*style, override_style));
831 fn emit_message_default(&mut self,
833 msg: &Vec<(String, Style)>,
834 code: &Option<String>,
836 max_line_num_len: usize,
839 let mut buffer = StyledBuffer::new();
841 if msp.primary_spans().is_empty() && msp.span_labels().is_empty() && is_secondary {
842 // This is a secondary message with no span info
843 for _ in 0..max_line_num_len {
844 buffer.prepend(0, " ", Style::NoStyle);
846 draw_note_separator(&mut buffer, 0, max_line_num_len + 1);
847 buffer.append(0, &level.to_string(), Style::HeaderMsg);
848 buffer.append(0, ": ", Style::NoStyle);
849 self.msg_to_buffer(&mut buffer, msg, max_line_num_len, "note", None);
851 buffer.append(0, &level.to_string(), Style::Level(level.clone()));
854 buffer.append(0, "[", Style::Level(level.clone()));
855 buffer.append(0, &code, Style::Level(level.clone()));
856 buffer.append(0, "]", Style::Level(level.clone()));
860 buffer.append(0, ": ", Style::HeaderMsg);
861 for &(ref text, _) in msg.iter() {
862 buffer.append(0, text, Style::HeaderMsg);
866 // Preprocess all the annotations so that they are grouped by file and by line number
867 // This helps us quickly iterate over the whole message (including secondary file spans)
868 let mut annotated_files = self.preprocess_annotations(msp);
870 // Make sure our primary file comes first
871 let primary_lo = if let (Some(ref cm), Some(ref primary_span)) =
872 (self.cm.as_ref(), msp.primary_span().as_ref()) {
873 if primary_span != &&DUMMY_SP {
874 cm.lookup_char_pos(primary_span.lo)
876 emit_to_destination(&buffer.render(), level, &mut self.dst)?;
880 // If we don't have span information, emit and exit
881 emit_to_destination(&buffer.render(), level, &mut self.dst)?;
885 annotated_files.binary_search_by(|x| x.file.name.cmp(&primary_lo.file.name)) {
886 annotated_files.swap(0, pos);
889 // Print out the annotate source lines that correspond with the error
890 for annotated_file in annotated_files {
891 // print out the span location and spacer before we print the annotated source
892 // to do this, we need to know if this span will be primary
893 let is_primary = primary_lo.file.name == annotated_file.file.name;
895 // remember where we are in the output buffer for easy reference
896 let buffer_msg_line_offset = buffer.num_lines();
898 buffer.prepend(buffer_msg_line_offset, "--> ", Style::LineNumber);
899 let loc = primary_lo.clone();
900 buffer.append(buffer_msg_line_offset,
901 &format!("{}:{}:{}", loc.file.name, loc.line, loc.col.0 + 1),
902 Style::LineAndColumn);
903 for _ in 0..max_line_num_len {
904 buffer.prepend(buffer_msg_line_offset, " ", Style::NoStyle);
907 // remember where we are in the output buffer for easy reference
908 let buffer_msg_line_offset = buffer.num_lines();
911 draw_col_separator(&mut buffer, buffer_msg_line_offset, max_line_num_len + 1);
913 // Then, the secondary file indicator
914 buffer.prepend(buffer_msg_line_offset + 1, "::: ", Style::LineNumber);
915 buffer.append(buffer_msg_line_offset + 1,
916 &annotated_file.file.name,
917 Style::LineAndColumn);
918 for _ in 0..max_line_num_len {
919 buffer.prepend(buffer_msg_line_offset + 1, " ", Style::NoStyle);
923 // Put in the spacer between the location and annotated source
924 let buffer_msg_line_offset = buffer.num_lines();
925 draw_col_separator_no_space(&mut buffer, buffer_msg_line_offset, max_line_num_len + 1);
927 // Contains the vertical lines' positions for active multiline annotations
928 let mut multilines = HashMap::new();
930 // Next, output the annotate source for this file
931 for line_idx in 0..annotated_file.lines.len() {
932 let previous_buffer_line = buffer.num_lines();
934 let width_offset = 3 + max_line_num_len;
935 let code_offset = if annotated_file.multiline_depth == 0 {
938 width_offset + annotated_file.multiline_depth + 1
941 let depths = self.render_source_line(&mut buffer,
942 annotated_file.file.clone(),
943 &annotated_file.lines[line_idx],
947 let mut to_add = HashMap::new();
949 for (depth, style) in depths {
950 if multilines.get(&depth).is_some() {
951 multilines.remove(&depth);
953 to_add.insert(depth, style);
957 // Set the multiline annotation vertical lines to the left of
958 // the code in this line.
959 for (depth, style) in &multilines {
960 for line in previous_buffer_line..buffer.num_lines() {
961 draw_multiline_line(&mut buffer,
968 // check to see if we need to print out or elide lines that come between
969 // this annotated line and the next one.
970 if line_idx < (annotated_file.lines.len() - 1) {
971 let line_idx_delta = annotated_file.lines[line_idx + 1].line_index -
972 annotated_file.lines[line_idx].line_index;
973 if line_idx_delta > 2 {
974 let last_buffer_line_num = buffer.num_lines();
975 buffer.puts(last_buffer_line_num, 0, "...", Style::LineNumber);
977 // Set the multiline annotation vertical lines on `...` bridging line.
978 for (depth, style) in &multilines {
979 draw_multiline_line(&mut buffer,
980 last_buffer_line_num,
985 } else if line_idx_delta == 2 {
986 let unannotated_line = annotated_file.file
987 .get_line(annotated_file.lines[line_idx].line_index)
990 let last_buffer_line_num = buffer.num_lines();
992 buffer.puts(last_buffer_line_num,
994 &(annotated_file.lines[line_idx + 1].line_index - 1)
997 draw_col_separator(&mut buffer, last_buffer_line_num, 1 + max_line_num_len);
998 buffer.puts(last_buffer_line_num,
1003 for (depth, style) in &multilines {
1004 draw_multiline_line(&mut buffer,
1005 last_buffer_line_num,
1013 multilines.extend(&to_add);
1017 // final step: take our styled buffer, render it, then output it
1018 emit_to_destination(&buffer.render(), level, &mut self.dst)?;
1022 fn emit_suggestion_default(&mut self,
1023 suggestion: &CodeSuggestion,
1025 msg: &Vec<(String, Style)>,
1026 max_line_num_len: usize)
1028 use std::borrow::Borrow;
1030 let primary_span = suggestion.msp.primary_span().unwrap();
1031 if let Some(ref cm) = self.cm {
1032 let mut buffer = StyledBuffer::new();
1034 buffer.append(0, &level.to_string(), Style::Level(level.clone()));
1035 buffer.append(0, ": ", Style::HeaderMsg);
1036 self.msg_to_buffer(&mut buffer,
1040 Some(Style::HeaderMsg));
1042 let lines = cm.span_to_lines(primary_span).unwrap();
1044 assert!(!lines.lines.is_empty());
1046 let complete = suggestion.splice_lines(cm.borrow());
1048 // print the suggestion without any line numbers, but leave
1049 // space for them. This helps with lining up with previous
1050 // snippets from the actual error being reported.
1051 let mut lines = complete.lines();
1052 let mut row_num = 1;
1053 for line in lines.by_ref().take(MAX_HIGHLIGHT_LINES) {
1054 draw_col_separator(&mut buffer, row_num, max_line_num_len + 1);
1055 buffer.append(row_num, line, Style::NoStyle);
1059 // if we elided some lines, add an ellipsis
1060 if let Some(_) = lines.next() {
1061 buffer.append(row_num, "...", Style::NoStyle);
1063 emit_to_destination(&buffer.render(), level, &mut self.dst)?;
1067 fn emit_messages_default(&mut self,
1069 message: &Vec<(String, Style)>,
1070 code: &Option<String>,
1072 children: &Vec<SubDiagnostic>) {
1073 let max_line_num = self.get_max_line_num(span, children);
1074 let max_line_num_len = max_line_num.to_string().len();
1076 match self.emit_message_default(span, message, code, level, max_line_num_len, false) {
1078 if !children.is_empty() {
1079 let mut buffer = StyledBuffer::new();
1080 draw_col_separator_no_space(&mut buffer, 0, max_line_num_len + 1);
1081 match emit_to_destination(&buffer.render(), level, &mut self.dst) {
1083 Err(e) => panic!("failed to emit error: {}", e)
1086 for child in children {
1087 match child.render_span {
1088 Some(FullSpan(ref msp)) => {
1089 match self.emit_message_default(msp,
1090 &child.styled_message(),
1095 Err(e) => panic!("failed to emit error: {}", e),
1099 Some(Suggestion(ref cs)) => {
1100 match self.emit_suggestion_default(cs,
1102 &child.styled_message(),
1104 Err(e) => panic!("failed to emit error: {}", e),
1109 match self.emit_message_default(&child.span,
1110 &child.styled_message(),
1115 Err(e) => panic!("failed to emit error: {}", e),
1122 Err(e) => panic!("failed to emit error: {}", e),
1124 match write!(&mut self.dst, "\n") {
1125 Err(e) => panic!("failed to emit error: {}", e),
1127 match self.dst.flush() {
1128 Err(e) => panic!("failed to emit error: {}", e),
1136 fn draw_col_separator(buffer: &mut StyledBuffer, line: usize, col: usize) {
1137 buffer.puts(line, col, "| ", Style::LineNumber);
1140 fn draw_col_separator_no_space(buffer: &mut StyledBuffer, line: usize, col: usize) {
1141 draw_col_separator_no_space_with_style(buffer, line, col, Style::LineNumber);
1144 fn draw_col_separator_no_space_with_style(buffer: &mut StyledBuffer,
1148 buffer.putc(line, col, '|', style);
1151 fn draw_range(buffer: &mut StyledBuffer, symbol: char, line: usize,
1152 col_from: usize, col_to: usize, style: Style) {
1153 for col in col_from..col_to {
1154 buffer.putc(line, col, symbol, style);
1158 fn draw_note_separator(buffer: &mut StyledBuffer, line: usize, col: usize) {
1159 buffer.puts(line, col, "= ", Style::LineNumber);
1162 fn draw_multiline_line(buffer: &mut StyledBuffer,
1168 buffer.putc(line, offset + depth - 1, '|', style);
1171 fn num_overlap(a_start: usize, a_end: usize, b_start: usize, b_end:usize, inclusive: bool) -> bool {
1172 let extra = if inclusive {
1177 (b_start..b_end + extra).contains(a_start) ||
1178 (a_start..a_end + extra).contains(b_start)
1180 fn overlaps(a1: &Annotation, a2: &Annotation, padding: usize) -> bool {
1181 num_overlap(a1.start_col, a1.end_col + padding, a2.start_col, a2.end_col, false)
1184 fn emit_to_destination(rendered_buffer: &Vec<Vec<StyledString>>,
1186 dst: &mut Destination)
1190 // In order to prevent error message interleaving, where multiple error lines get intermixed
1191 // when multiple compiler processes error simultaneously, we emit errors with additional
1194 // On Unix systems, we write into a buffered terminal rather than directly to a terminal. When
1195 // the .flush() is called we take the buffer created from the buffered writes and write it at
1196 // one shot. Because the Unix systems use ANSI for the colors, which is a text-based styling
1197 // scheme, this buffered approach works and maintains the styling.
1199 // On Windows, styling happens through calls to a terminal API. This prevents us from using the
1200 // same buffering approach. Instead, we use a global Windows mutex, which we acquire long
1201 // enough to output the full error message, then we release.
1202 let _buffer_lock = lock::acquire_global_lock("rustc_errors");
1203 for line in rendered_buffer {
1205 dst.apply_style(lvl.clone(), part.style)?;
1206 write!(dst, "{}", part.text)?;
1216 fn stderr_isatty() -> bool {
1218 unsafe { libc::isatty(libc::STDERR_FILENO) != 0 }
1221 fn stderr_isatty() -> bool {
1224 type HANDLE = *mut u8;
1225 const STD_ERROR_HANDLE: DWORD = -12i32 as DWORD;
1227 fn GetStdHandle(which: DWORD) -> HANDLE;
1228 fn GetConsoleMode(hConsoleHandle: HANDLE, lpMode: *mut DWORD) -> BOOL;
1231 let handle = GetStdHandle(STD_ERROR_HANDLE);
1233 GetConsoleMode(handle, &mut out) != 0
1237 pub type BufferedStderr = term::Terminal<Output = BufferedWriter> + Send;
1239 pub enum Destination {
1240 Terminal(Box<term::StderrTerminal>),
1241 BufferedTerminal(Box<BufferedStderr>),
1242 Raw(Box<Write + Send>),
1245 /// Buffered writer gives us a way on Unix to buffer up an entire error message before we output
1246 /// it. This helps to prevent interleaving of multiple error messages when multiple compiler
1247 /// processes error simultaneously
1248 pub struct BufferedWriter {
1252 impl BufferedWriter {
1253 // note: we use _new because the conditional compilation at its use site may make this
1254 // this function unused on some platforms
1255 fn _new() -> BufferedWriter {
1256 BufferedWriter { buffer: vec![] }
1260 impl Write for BufferedWriter {
1261 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
1263 self.buffer.push(*b);
1267 fn flush(&mut self) -> io::Result<()> {
1268 let mut stderr = io::stderr();
1270 stderr.write_all(&self.buffer)?;
1273 self.buffer.clear();
1279 #[cfg(not(windows))]
1280 /// When not on Windows, prefer the buffered terminal so that we can buffer an entire error
1281 /// to be emitted at one time.
1282 fn from_stderr() -> Destination {
1283 let stderr: Option<Box<BufferedStderr>> =
1284 term::TerminfoTerminal::new(BufferedWriter::_new())
1285 .map(|t| Box::new(t) as Box<BufferedStderr>);
1288 Some(t) => BufferedTerminal(t),
1289 None => Raw(Box::new(io::stderr())),
1294 /// Return a normal, unbuffered terminal when on Windows.
1295 fn from_stderr() -> Destination {
1296 let stderr: Option<Box<term::StderrTerminal>> = term::TerminfoTerminal::new(io::stderr())
1297 .map(|t| Box::new(t) as Box<term::StderrTerminal>)
1299 term::WinConsole::new(io::stderr())
1301 .map(|t| Box::new(t) as Box<term::StderrTerminal>)
1305 Some(t) => Terminal(t),
1306 None => Raw(Box::new(io::stderr())),
1310 fn apply_style(&mut self, lvl: Level, style: Style) -> io::Result<()> {
1312 Style::FileNameStyle | Style::LineAndColumn => {}
1313 Style::LineNumber => {
1314 self.start_attr(term::Attr::Bold)?;
1316 self.start_attr(term::Attr::ForegroundColor(term::color::BRIGHT_CYAN))?;
1318 self.start_attr(term::Attr::ForegroundColor(term::color::BRIGHT_BLUE))?;
1321 Style::ErrorCode => {
1322 self.start_attr(term::Attr::Bold)?;
1323 self.start_attr(term::Attr::ForegroundColor(term::color::BRIGHT_MAGENTA))?;
1325 Style::Quotation => {}
1326 Style::OldSchoolNote => {
1327 self.start_attr(term::Attr::Bold)?;
1328 self.start_attr(term::Attr::ForegroundColor(term::color::BRIGHT_GREEN))?;
1330 Style::OldSchoolNoteText | Style::HeaderMsg => {
1331 self.start_attr(term::Attr::Bold)?;
1333 self.start_attr(term::Attr::ForegroundColor(term::color::BRIGHT_WHITE))?;
1336 Style::UnderlinePrimary | Style::LabelPrimary => {
1337 self.start_attr(term::Attr::Bold)?;
1338 self.start_attr(term::Attr::ForegroundColor(lvl.color()))?;
1340 Style::UnderlineSecondary |
1341 Style::LabelSecondary => {
1342 self.start_attr(term::Attr::Bold)?;
1344 self.start_attr(term::Attr::ForegroundColor(term::color::BRIGHT_CYAN))?;
1346 self.start_attr(term::Attr::ForegroundColor(term::color::BRIGHT_BLUE))?;
1349 Style::NoStyle => {}
1350 Style::Level(l) => {
1351 self.start_attr(term::Attr::Bold)?;
1352 self.start_attr(term::Attr::ForegroundColor(l.color()))?;
1354 Style::Highlight => self.start_attr(term::Attr::Bold)?,
1359 fn start_attr(&mut self, attr: term::Attr) -> io::Result<()> {
1361 Terminal(ref mut t) => {
1364 BufferedTerminal(ref mut t) => {
1372 fn reset_attrs(&mut self) -> io::Result<()> {
1374 Terminal(ref mut t) => {
1377 BufferedTerminal(ref mut t) => {
1386 impl Write for Destination {
1387 fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
1389 Terminal(ref mut t) => t.write(bytes),
1390 BufferedTerminal(ref mut t) => t.write(bytes),
1391 Raw(ref mut w) => w.write(bytes),
1394 fn flush(&mut self) -> io::Result<()> {
1396 Terminal(ref mut t) => t.flush(),
1397 BufferedTerminal(ref mut t) => t.flush(),
1398 Raw(ref mut w) => w.flush(),