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 // We want to display like this:
268 // vec.push(vec.pop().unwrap());
269 // --- ^^^ - previous borrow ends here
271 // | error occurs here
272 // previous borrow of `vec` occurs here
274 // But there are some weird edge cases to be aware of:
276 // vec.push(vec.pop().unwrap());
277 // -------- - previous borrow ends here
279 // |this makes no sense
280 // previous borrow of `vec` occurs here
282 // For this reason, we group the lines into "highlight lines"
283 // and "annotations lines", where the highlight lines have the `^`.
285 // Sort the annotations by (start, end col)
286 let mut annotations = line.annotations.clone();
288 annotations.reverse();
290 // First, figure out where each label will be positioned.
292 // In the case where you have the following annotations:
294 // vec.push(vec.pop().unwrap());
295 // -------- - previous borrow ends here [C]
297 // |this makes no sense [B]
298 // previous borrow of `vec` occurs here [A]
300 // `annotations_position` will hold [(2, A), (1, B), (0, C)].
302 // We try, when possible, to stick the rightmost annotation at the end
303 // of the highlight line:
305 // vec.push(vec.pop().unwrap());
306 // --- --- - previous borrow ends here
308 // But sometimes that's not possible because one of the other
309 // annotations overlaps it. For example, from the test
310 // `span_overlap_label`, we have the following annotations
311 // (written on distinct lines for clarity):
317 // In this case, we can't stick the rightmost-most label on
318 // the highlight line, or we would get:
325 // which is totally weird. Instead we want:
333 // which is...less weird, at least. In fact, in general, if
334 // the rightmost span overlaps with any other span, we should
335 // use the "hang below" version, so we can at least make it
336 // clear where the span *starts*. There's an exception for this
337 // logic, when the labels do not have a message:
352 let mut annotations_position = vec![];
353 let mut line_len = 0;
355 for (i, annotation) in annotations.iter().enumerate() {
356 for (j, next) in annotations.iter().enumerate() {
357 if overlaps(next, annotation, 0) // This label overlaps with another one and both
358 && !annotation.is_line() // take space (they have text and are not
359 && !next.is_line() // multiline lines).
360 && annotation.has_label()
362 && p == 0 // We're currently on the first line, move the label one line down
364 // This annotation needs a new line in the output.
369 annotations_position.push((p, annotation));
370 for (j, next) in annotations.iter().enumerate() {
372 let l = if let Some(ref label) = next.label {
377 if overlaps(next, annotation, l) // Do not allow two labels to be in the same
378 // line if they overlap including padding, to
379 // avoid situations like:
386 && !annotation.is_line() // Do not add a new line if this annotation
387 && !next.is_line() // or the next are vertical line placeholders.
388 && annotation.has_label() // Both labels must have some text, otherwise
389 && next.has_label() // they are not overlapping.
404 // If there are no annotations or the only annotations on this line are
405 // MultilineLine, then there's only code being shown, stop processing.
406 if line.annotations.is_empty() || line.annotations.iter()
407 .filter(|a| !a.is_line()).collect::<Vec<_>>().len() == 0
412 // Write the colunmn separator.
414 // After this we will have:
423 for pos in 0..line_len + 1 {
424 draw_col_separator(buffer, line_offset + pos + 1, width_offset - 2);
425 buffer.putc(line_offset + pos + 1,
431 // Write the horizontal lines for multiline annotations
432 // (only the first and last lines need this).
434 // After this we will have:
443 for &(pos, annotation) in &annotations_position {
444 let style = if annotation.is_primary {
445 Style::UnderlinePrimary
447 Style::UnderlineSecondary
450 match annotation.annotation_type {
451 AnnotationType::MultilineStart(depth) |
452 AnnotationType::MultilineEnd(depth) => {
456 width_offset + depth,
457 code_offset + annotation.start_col,
464 // Write the vertical lines for labels that are on a different line as the underline.
466 // After this we will have:
475 for &(pos, annotation) in &annotations_position {
476 let style = if annotation.is_primary {
477 Style::UnderlinePrimary
479 Style::UnderlineSecondary
483 if pos > 1 && annotation.has_label() {
484 for p in line_offset + 1..line_offset + pos + 1 {
486 code_offset + annotation.start_col,
491 match annotation.annotation_type {
492 AnnotationType::MultilineStart(depth) => {
493 for p in line_offset + pos + 1..line_offset + line_len + 2 {
495 width_offset + depth - 1,
500 AnnotationType::MultilineEnd(depth) => {
501 for p in line_offset..line_offset + pos + 1 {
503 width_offset + depth - 1,
512 // Write the labels on the annotations that actually have a label.
514 // After this we will have:
517 // | __________ starting here...
519 // | something about `foo`
522 // | _ ...ending here: test
523 for &(pos, annotation) in &annotations_position {
524 let style = if annotation.is_primary {
527 Style::LabelSecondary
529 let (pos, col) = if pos == 0 {
530 (pos + 1, annotation.end_col + 1)
532 (pos + 2, annotation.start_col)
534 if let Some(ref label) = annotation.label {
535 buffer.puts(line_offset + pos,
542 // Sort from biggest span to smallest span so that smaller spans are
543 // represented in the output:
548 // | | something about `foo`
549 // | something about `fn foo()`
550 annotations_position.sort_by(|a, b| {
552 a.1.len().cmp(&b.1.len()).reverse()
555 // Write the underlines.
557 // After this we will have:
560 // | ____-_____^ starting here...
562 // | something about `foo`
565 // | _^ ...ending here: test
566 for &(_, annotation) in &annotations_position {
567 let (underline, style) = if annotation.is_primary {
568 ('^', Style::UnderlinePrimary)
570 ('-', Style::UnderlineSecondary)
572 for p in annotation.start_col..annotation.end_col {
573 buffer.putc(line_offset + 1,
579 annotations_position.iter().filter_map(|&(_, annotation)| {
580 match annotation.annotation_type {
581 AnnotationType::MultilineStart(p) | AnnotationType::MultilineEnd(p) => {
582 let style = if annotation.is_primary {
585 Style::LabelSecondary
592 }).collect::<Vec<_>>()
595 fn get_multispan_max_line_num(&mut self, msp: &MultiSpan) -> usize {
597 if let Some(ref cm) = self.cm {
598 for primary_span in msp.primary_spans() {
599 if primary_span != &DUMMY_SP {
600 let hi = cm.lookup_char_pos(primary_span.hi);
606 for span_label in msp.span_labels() {
607 if span_label.span != DUMMY_SP {
608 let hi = cm.lookup_char_pos(span_label.span.hi);
618 fn get_max_line_num(&mut self, span: &MultiSpan, children: &Vec<SubDiagnostic>) -> usize {
621 let primary = self.get_multispan_max_line_num(span);
622 max = if primary > max { primary } else { max };
624 for sub in children {
625 let sub_result = self.get_multispan_max_line_num(&sub.span);
626 max = if sub_result > max { primary } else { max };
631 // This "fixes" MultiSpans that contain Spans that are pointing to locations inside of
632 // <*macros>. Since these locations are often difficult to read, we move these Spans from
633 // <*macros> to their corresponding use site.
634 fn fix_multispan_in_std_macros(&mut self, span: &mut MultiSpan) -> bool {
635 let mut spans_updated = false;
637 if let Some(ref cm) = self.cm {
638 let mut before_after: Vec<(Span, Span)> = vec![];
639 let mut new_labels: Vec<(Span, String)> = vec![];
641 // First, find all the spans in <*macros> and point instead at their use site
642 for sp in span.primary_spans() {
646 if cm.span_to_filename(sp.clone()).contains("macros>") {
647 let v = sp.macro_backtrace();
648 if let Some(use_site) = v.last() {
649 before_after.push((sp.clone(), use_site.call_site.clone()));
652 for trace in sp.macro_backtrace().iter().rev() {
653 // Only show macro locations that are local
654 // and display them like a span_note
655 if let Some(def_site) = trace.def_site_span {
656 if def_site == DUMMY_SP {
659 // Check to make sure we're not in any <*macros>
660 if !cm.span_to_filename(def_site).contains("macros>") &&
661 !trace.macro_decl_name.starts_with("#[") {
662 new_labels.push((trace.call_site,
663 "in this macro invocation".to_string()));
669 for (label_span, label_text) in new_labels {
670 span.push_span_label(label_span, label_text);
672 for sp_label in span.span_labels() {
673 if sp_label.span == DUMMY_SP {
676 if cm.span_to_filename(sp_label.span.clone()).contains("macros>") {
677 let v = sp_label.span.macro_backtrace();
678 if let Some(use_site) = v.last() {
679 before_after.push((sp_label.span.clone(), use_site.call_site.clone()));
683 // After we have them, make sure we replace these 'bad' def sites with their use sites
684 for (before, after) in before_after {
685 span.replace(before, after);
686 spans_updated = true;
693 // This does a small "fix" for multispans by looking to see if it can find any that
694 // point directly at <*macros>. Since these are often difficult to read, this
695 // will change the span to point at the use site.
696 fn fix_multispans_in_std_macros(&mut self,
697 span: &mut MultiSpan,
698 children: &mut Vec<SubDiagnostic>) {
699 let mut spans_updated = self.fix_multispan_in_std_macros(span);
700 for child in children.iter_mut() {
701 spans_updated |= self.fix_multispan_in_std_macros(&mut child.span);
704 children.push(SubDiagnostic {
706 message: vec![("this error originates in a macro outside of the current crate"
707 .to_string(), Style::NoStyle)],
708 span: MultiSpan::new(),
714 /// Add a left margin to every line but the first, given a padding length and the label being
715 /// displayed, keeping the provided highlighting.
716 fn msg_to_buffer(&self,
717 buffer: &mut StyledBuffer,
718 msg: &Vec<(String, Style)>,
721 override_style: Option<Style>) {
723 // The extra 5 ` ` is padding that's always needed to align to the `note: `:
736 // | | length of label
738 // `max_line_num_len`
739 let padding = (0..padding + label.len() + 5)
741 .collect::<String>();
743 /// Return wether `style`, or the override if present and the style is `NoStyle`.
744 fn style_or_override(style: Style, override_style: Option<Style>) -> Style {
745 if let Some(o) = override_style {
746 if style == Style::NoStyle {
753 let mut line_number = 0;
755 // Provided the following diagnostic message:
759 // ("highlighted multiline\nstring to\nsee how it ", Style::NoStyle),
760 // ("looks", Style::Highlight),
761 // ("with\nvery ", Style::NoStyle),
762 // ("weird", Style::Highlight),
763 // (" formats\n", Style::NoStyle),
764 // ("see?", Style::Highlight),
767 // the expected output on a note is (* surround the highlighted text)
769 // = note: highlighted multiline
771 // see how it *looks* with
772 // very *weird* formats
774 for &(ref text, ref style) in msg.iter() {
775 let lines = text.split('\n').collect::<Vec<_>>();
777 for (i, line) in lines.iter().enumerate() {
780 buffer.append(line_number, &padding, Style::NoStyle);
782 buffer.append(line_number, line, style_or_override(*style, override_style));
785 buffer.append(line_number, text, style_or_override(*style, override_style));
790 fn emit_message_default(&mut self,
792 msg: &Vec<(String, Style)>,
793 code: &Option<String>,
795 max_line_num_len: usize,
798 let mut buffer = StyledBuffer::new();
800 if msp.primary_spans().is_empty() && msp.span_labels().is_empty() && is_secondary {
801 // This is a secondary message with no span info
802 for _ in 0..max_line_num_len {
803 buffer.prepend(0, " ", Style::NoStyle);
805 draw_note_separator(&mut buffer, 0, max_line_num_len + 1);
806 buffer.append(0, &level.to_string(), Style::HeaderMsg);
807 buffer.append(0, ": ", Style::NoStyle);
808 self.msg_to_buffer(&mut buffer, msg, max_line_num_len, "note", None);
810 buffer.append(0, &level.to_string(), Style::Level(level.clone()));
813 buffer.append(0, "[", Style::Level(level.clone()));
814 buffer.append(0, &code, Style::Level(level.clone()));
815 buffer.append(0, "]", Style::Level(level.clone()));
819 buffer.append(0, ": ", Style::HeaderMsg);
820 for &(ref text, _) in msg.iter() {
821 buffer.append(0, text, Style::HeaderMsg);
825 // Preprocess all the annotations so that they are grouped by file and by line number
826 // This helps us quickly iterate over the whole message (including secondary file spans)
827 let mut annotated_files = self.preprocess_annotations(msp);
829 // Make sure our primary file comes first
830 let primary_lo = if let (Some(ref cm), Some(ref primary_span)) =
831 (self.cm.as_ref(), msp.primary_span().as_ref()) {
832 if primary_span != &&DUMMY_SP {
833 cm.lookup_char_pos(primary_span.lo)
835 emit_to_destination(&buffer.render(), level, &mut self.dst)?;
839 // If we don't have span information, emit and exit
840 emit_to_destination(&buffer.render(), level, &mut self.dst)?;
844 annotated_files.binary_search_by(|x| x.file.name.cmp(&primary_lo.file.name)) {
845 annotated_files.swap(0, pos);
848 // Print out the annotate source lines that correspond with the error
849 for annotated_file in annotated_files {
850 // print out the span location and spacer before we print the annotated source
851 // to do this, we need to know if this span will be primary
852 let is_primary = primary_lo.file.name == annotated_file.file.name;
854 // remember where we are in the output buffer for easy reference
855 let buffer_msg_line_offset = buffer.num_lines();
857 buffer.prepend(buffer_msg_line_offset, "--> ", Style::LineNumber);
858 let loc = primary_lo.clone();
859 buffer.append(buffer_msg_line_offset,
860 &format!("{}:{}:{}", loc.file.name, loc.line, loc.col.0 + 1),
861 Style::LineAndColumn);
862 for _ in 0..max_line_num_len {
863 buffer.prepend(buffer_msg_line_offset, " ", Style::NoStyle);
866 // remember where we are in the output buffer for easy reference
867 let buffer_msg_line_offset = buffer.num_lines();
870 draw_col_separator(&mut buffer, buffer_msg_line_offset, max_line_num_len + 1);
872 // Then, the secondary file indicator
873 buffer.prepend(buffer_msg_line_offset + 1, "::: ", Style::LineNumber);
874 buffer.append(buffer_msg_line_offset + 1,
875 &annotated_file.file.name,
876 Style::LineAndColumn);
877 for _ in 0..max_line_num_len {
878 buffer.prepend(buffer_msg_line_offset + 1, " ", Style::NoStyle);
882 // Put in the spacer between the location and annotated source
883 let buffer_msg_line_offset = buffer.num_lines();
884 draw_col_separator_no_space(&mut buffer, buffer_msg_line_offset, max_line_num_len + 1);
886 // Contains the vertical lines' positions for active multiline annotations
887 let mut multilines = HashMap::new();
889 // Next, output the annotate source for this file
890 for line_idx in 0..annotated_file.lines.len() {
891 let previous_buffer_line = buffer.num_lines();
893 let width_offset = 3 + max_line_num_len;
894 let code_offset = if annotated_file.multiline_depth == 0 {
897 width_offset + annotated_file.multiline_depth + 1
900 let depths = self.render_source_line(&mut buffer,
901 annotated_file.file.clone(),
902 &annotated_file.lines[line_idx],
906 let mut to_add = HashMap::new();
908 for (depth, style) in depths {
909 if multilines.get(&depth).is_some() {
910 multilines.remove(&depth);
912 to_add.insert(depth, style);
916 // Set the multiline annotation vertical lines to the left of
917 // the code in this line.
918 for (depth, style) in &multilines {
919 for line in previous_buffer_line..buffer.num_lines() {
920 draw_multiline_line(&mut buffer,
927 // check to see if we need to print out or elide lines that come between
928 // this annotated line and the next one.
929 if line_idx < (annotated_file.lines.len() - 1) {
930 let line_idx_delta = annotated_file.lines[line_idx + 1].line_index -
931 annotated_file.lines[line_idx].line_index;
932 if line_idx_delta > 2 {
933 let last_buffer_line_num = buffer.num_lines();
934 buffer.puts(last_buffer_line_num, 0, "...", Style::LineNumber);
936 // Set the multiline annotation vertical lines on `...` bridging line.
937 for (depth, style) in &multilines {
938 draw_multiline_line(&mut buffer,
939 last_buffer_line_num,
944 } else if line_idx_delta == 2 {
945 let unannotated_line = annotated_file.file
946 .get_line(annotated_file.lines[line_idx].line_index)
949 let last_buffer_line_num = buffer.num_lines();
951 buffer.puts(last_buffer_line_num,
953 &(annotated_file.lines[line_idx + 1].line_index - 1)
956 draw_col_separator(&mut buffer, last_buffer_line_num, 1 + max_line_num_len);
957 buffer.puts(last_buffer_line_num,
962 for (depth, style) in &multilines {
963 draw_multiline_line(&mut buffer,
964 last_buffer_line_num,
972 multilines.extend(&to_add);
976 // final step: take our styled buffer, render it, then output it
977 emit_to_destination(&buffer.render(), level, &mut self.dst)?;
981 fn emit_suggestion_default(&mut self,
982 suggestion: &CodeSuggestion,
984 msg: &Vec<(String, Style)>,
985 max_line_num_len: usize)
987 use std::borrow::Borrow;
989 let primary_span = suggestion.msp.primary_span().unwrap();
990 if let Some(ref cm) = self.cm {
991 let mut buffer = StyledBuffer::new();
993 buffer.append(0, &level.to_string(), Style::Level(level.clone()));
994 buffer.append(0, ": ", Style::HeaderMsg);
995 self.msg_to_buffer(&mut buffer,
999 Some(Style::HeaderMsg));
1001 let lines = cm.span_to_lines(primary_span).unwrap();
1003 assert!(!lines.lines.is_empty());
1005 let complete = suggestion.splice_lines(cm.borrow());
1007 // print the suggestion without any line numbers, but leave
1008 // space for them. This helps with lining up with previous
1009 // snippets from the actual error being reported.
1010 let mut lines = complete.lines();
1011 let mut row_num = 1;
1012 for line in lines.by_ref().take(MAX_HIGHLIGHT_LINES) {
1013 draw_col_separator(&mut buffer, row_num, max_line_num_len + 1);
1014 buffer.append(row_num, line, Style::NoStyle);
1018 // if we elided some lines, add an ellipsis
1019 if let Some(_) = lines.next() {
1020 buffer.append(row_num, "...", Style::NoStyle);
1022 emit_to_destination(&buffer.render(), level, &mut self.dst)?;
1026 fn emit_messages_default(&mut self,
1028 message: &Vec<(String, Style)>,
1029 code: &Option<String>,
1031 children: &Vec<SubDiagnostic>) {
1032 let max_line_num = self.get_max_line_num(span, children);
1033 let max_line_num_len = max_line_num.to_string().len();
1035 match self.emit_message_default(span, message, code, level, max_line_num_len, false) {
1037 if !children.is_empty() {
1038 let mut buffer = StyledBuffer::new();
1039 draw_col_separator_no_space(&mut buffer, 0, max_line_num_len + 1);
1040 match emit_to_destination(&buffer.render(), level, &mut self.dst) {
1042 Err(e) => panic!("failed to emit error: {}", e)
1045 for child in children {
1046 match child.render_span {
1047 Some(FullSpan(ref msp)) => {
1048 match self.emit_message_default(msp,
1049 &child.styled_message(),
1054 Err(e) => panic!("failed to emit error: {}", e),
1058 Some(Suggestion(ref cs)) => {
1059 match self.emit_suggestion_default(cs,
1061 &child.styled_message(),
1063 Err(e) => panic!("failed to emit error: {}", e),
1068 match self.emit_message_default(&child.span,
1069 &child.styled_message(),
1074 Err(e) => panic!("failed to emit error: {}", e),
1081 Err(e) => panic!("failed to emit error: {}", e),
1083 match write!(&mut self.dst, "\n") {
1084 Err(e) => panic!("failed to emit error: {}", e),
1086 match self.dst.flush() {
1087 Err(e) => panic!("failed to emit error: {}", e),
1095 fn draw_col_separator(buffer: &mut StyledBuffer, line: usize, col: usize) {
1096 buffer.puts(line, col, "| ", Style::LineNumber);
1099 fn draw_col_separator_no_space(buffer: &mut StyledBuffer, line: usize, col: usize) {
1100 draw_col_separator_no_space_with_style(buffer, line, col, Style::LineNumber);
1103 fn draw_col_separator_no_space_with_style(buffer: &mut StyledBuffer,
1107 buffer.putc(line, col, '|', style);
1110 fn draw_range(buffer: &mut StyledBuffer, symbol: char, line: usize,
1111 col_from: usize, col_to: usize, style: Style) {
1112 for col in col_from..col_to {
1113 buffer.putc(line, col, symbol, style);
1117 fn draw_note_separator(buffer: &mut StyledBuffer, line: usize, col: usize) {
1118 buffer.puts(line, col, "= ", Style::LineNumber);
1121 fn draw_multiline_line(buffer: &mut StyledBuffer,
1127 buffer.putc(line, offset + depth - 1, '|', style);
1130 fn num_overlap(a_start: usize, a_end: usize, b_start: usize, b_end:usize, inclusive: bool) -> bool {
1131 let extra = if inclusive {
1136 (b_start..b_end + extra).contains(a_start) ||
1137 (a_start..a_end + extra).contains(b_start)
1139 fn overlaps(a1: &Annotation, a2: &Annotation, padding: usize) -> bool {
1140 num_overlap(a1.start_col, a1.end_col + padding, a2.start_col, a2.end_col, false)
1143 fn emit_to_destination(rendered_buffer: &Vec<Vec<StyledString>>,
1145 dst: &mut Destination)
1149 // In order to prevent error message interleaving, where multiple error lines get intermixed
1150 // when multiple compiler processes error simultaneously, we emit errors with additional
1153 // On Unix systems, we write into a buffered terminal rather than directly to a terminal. When
1154 // the .flush() is called we take the buffer created from the buffered writes and write it at
1155 // one shot. Because the Unix systems use ANSI for the colors, which is a text-based styling
1156 // scheme, this buffered approach works and maintains the styling.
1158 // On Windows, styling happens through calls to a terminal API. This prevents us from using the
1159 // same buffering approach. Instead, we use a global Windows mutex, which we acquire long
1160 // enough to output the full error message, then we release.
1161 let _buffer_lock = lock::acquire_global_lock("rustc_errors");
1162 for line in rendered_buffer {
1164 dst.apply_style(lvl.clone(), part.style)?;
1165 write!(dst, "{}", part.text)?;
1175 fn stderr_isatty() -> bool {
1177 unsafe { libc::isatty(libc::STDERR_FILENO) != 0 }
1180 fn stderr_isatty() -> bool {
1183 type HANDLE = *mut u8;
1184 const STD_ERROR_HANDLE: DWORD = -12i32 as DWORD;
1186 fn GetStdHandle(which: DWORD) -> HANDLE;
1187 fn GetConsoleMode(hConsoleHandle: HANDLE, lpMode: *mut DWORD) -> BOOL;
1190 let handle = GetStdHandle(STD_ERROR_HANDLE);
1192 GetConsoleMode(handle, &mut out) != 0
1196 pub type BufferedStderr = term::Terminal<Output = BufferedWriter> + Send;
1198 pub enum Destination {
1199 Terminal(Box<term::StderrTerminal>),
1200 BufferedTerminal(Box<BufferedStderr>),
1201 Raw(Box<Write + Send>),
1204 /// Buffered writer gives us a way on Unix to buffer up an entire error message before we output
1205 /// it. This helps to prevent interleaving of multiple error messages when multiple compiler
1206 /// processes error simultaneously
1207 pub struct BufferedWriter {
1211 impl BufferedWriter {
1212 // note: we use _new because the conditional compilation at its use site may make this
1213 // this function unused on some platforms
1214 fn _new() -> BufferedWriter {
1215 BufferedWriter { buffer: vec![] }
1219 impl Write for BufferedWriter {
1220 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
1222 self.buffer.push(*b);
1226 fn flush(&mut self) -> io::Result<()> {
1227 let mut stderr = io::stderr();
1229 stderr.write_all(&self.buffer)?;
1232 self.buffer.clear();
1238 #[cfg(not(windows))]
1239 /// When not on Windows, prefer the buffered terminal so that we can buffer an entire error
1240 /// to be emitted at one time.
1241 fn from_stderr() -> Destination {
1242 let stderr: Option<Box<BufferedStderr>> =
1243 term::TerminfoTerminal::new(BufferedWriter::_new())
1244 .map(|t| Box::new(t) as Box<BufferedStderr>);
1247 Some(t) => BufferedTerminal(t),
1248 None => Raw(Box::new(io::stderr())),
1253 /// Return a normal, unbuffered terminal when on Windows.
1254 fn from_stderr() -> Destination {
1255 let stderr: Option<Box<term::StderrTerminal>> = term::TerminfoTerminal::new(io::stderr())
1256 .map(|t| Box::new(t) as Box<term::StderrTerminal>)
1258 term::WinConsole::new(io::stderr())
1260 .map(|t| Box::new(t) as Box<term::StderrTerminal>)
1264 Some(t) => Terminal(t),
1265 None => Raw(Box::new(io::stderr())),
1269 fn apply_style(&mut self, lvl: Level, style: Style) -> io::Result<()> {
1271 Style::FileNameStyle | Style::LineAndColumn => {}
1272 Style::LineNumber => {
1273 self.start_attr(term::Attr::Bold)?;
1275 self.start_attr(term::Attr::ForegroundColor(term::color::BRIGHT_CYAN))?;
1277 self.start_attr(term::Attr::ForegroundColor(term::color::BRIGHT_BLUE))?;
1280 Style::ErrorCode => {
1281 self.start_attr(term::Attr::Bold)?;
1282 self.start_attr(term::Attr::ForegroundColor(term::color::BRIGHT_MAGENTA))?;
1284 Style::Quotation => {}
1285 Style::OldSchoolNote => {
1286 self.start_attr(term::Attr::Bold)?;
1287 self.start_attr(term::Attr::ForegroundColor(term::color::BRIGHT_GREEN))?;
1289 Style::OldSchoolNoteText | Style::HeaderMsg => {
1290 self.start_attr(term::Attr::Bold)?;
1292 self.start_attr(term::Attr::ForegroundColor(term::color::BRIGHT_WHITE))?;
1295 Style::UnderlinePrimary | Style::LabelPrimary => {
1296 self.start_attr(term::Attr::Bold)?;
1297 self.start_attr(term::Attr::ForegroundColor(lvl.color()))?;
1299 Style::UnderlineSecondary |
1300 Style::LabelSecondary => {
1301 self.start_attr(term::Attr::Bold)?;
1303 self.start_attr(term::Attr::ForegroundColor(term::color::BRIGHT_CYAN))?;
1305 self.start_attr(term::Attr::ForegroundColor(term::color::BRIGHT_BLUE))?;
1308 Style::NoStyle => {}
1309 Style::Level(l) => {
1310 self.start_attr(term::Attr::Bold)?;
1311 self.start_attr(term::Attr::ForegroundColor(l.color()))?;
1313 Style::Highlight => self.start_attr(term::Attr::Bold)?,
1318 fn start_attr(&mut self, attr: term::Attr) -> io::Result<()> {
1320 Terminal(ref mut t) => {
1323 BufferedTerminal(ref mut t) => {
1331 fn reset_attrs(&mut self) -> io::Result<()> {
1333 Terminal(ref mut t) => {
1336 BufferedTerminal(ref mut t) => {
1345 impl Write for Destination {
1346 fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
1348 Terminal(ref mut t) => t.write(bytes),
1349 BufferedTerminal(ref mut t) => t.write(bytes),
1350 Raw(ref mut w) => w.write(bytes),
1353 fn flush(&mut self) -> io::Result<()> {
1355 Terminal(ref mut t) => t.flush(),
1356 BufferedTerminal(ref mut t) => t.flush(),
1357 Raw(ref mut w) => w.flush(),