1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use self::Destination::*;
13 use syntax_pos::{DUMMY_SP, FileMap, Span, MultiSpan, CharPos};
15 use {Level, CodeSuggestion, DiagnosticBuilder, SubDiagnostic, CodeMapper};
17 use snippet::{Annotation, AnnotationType, Line, MultilineAnnotation, StyledString, Style};
18 use styled_buffer::StyledBuffer;
21 use std::io::prelude::*;
25 use std::collections::HashMap;
28 /// Emitter trait for emitting errors.
30 /// Emit a structured diagnostic.
31 fn emit(&mut self, db: &DiagnosticBuilder);
34 impl Emitter for EmitterWriter {
35 fn emit(&mut self, db: &DiagnosticBuilder) {
36 let mut primary_span = db.span.clone();
37 let mut children = db.children.clone();
39 if let Some((sugg, rest)) = db.suggestions.split_first() {
41 // don't display multipart suggestions as labels
42 sugg.substitution_parts.len() == 1 &&
43 // don't display multi-suggestions as labels
44 sugg.substitutions() == 1 &&
45 // don't display long messages as labels
46 sugg.msg.split_whitespace().count() < 10 &&
47 // don't display multiline suggestions as labels
48 sugg.substitution_parts[0].substitutions[0].find('\n').is_none() {
49 let substitution = &sugg.substitution_parts[0].substitutions[0];
50 let msg = if substitution.len() == 0 {
51 // This substitution is only removal, don't show it
52 format!("help: {}", sugg.msg)
54 format!("help: {} `{}`", sugg.msg, substitution)
56 primary_span.push_span_label(sugg.substitution_spans().next().unwrap(), msg);
58 // if there are multiple suggestions, print them all in full
59 // to be consistent. We could try to figure out if we can
60 // make one (or the first one) inline, but that would give
61 // undue importance to a semi-random suggestion
62 for sugg in &db.suggestions {
63 children.push(SubDiagnostic {
66 span: MultiSpan::new(),
67 render_span: Some(Suggestion(sugg.clone())),
73 self.fix_multispans_in_std_macros(&mut primary_span, &mut children);
74 self.emit_messages_default(&db.level,
82 /// maximum number of lines we will print for each error; arbitrary.
83 pub const MAX_HIGHLIGHT_LINES: usize = 6;
84 /// maximum number of suggestions to be shown
86 /// Arbitrary, but taken from trait import suggestion limit
87 pub const MAX_SUGGESTIONS: usize = 4;
89 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
90 pub enum ColorConfig {
97 fn use_color(&self) -> bool {
99 ColorConfig::Always => true,
100 ColorConfig::Never => false,
101 ColorConfig::Auto => stderr_isatty(),
106 pub struct EmitterWriter {
108 cm: Option<Rc<CodeMapper>>,
111 struct FileWithAnnotatedLines {
114 multiline_depth: usize,
118 pub fn stderr(color_config: ColorConfig, code_map: Option<Rc<CodeMapper>>) -> EmitterWriter {
119 if color_config.use_color() {
120 let dst = Destination::from_stderr();
127 dst: Raw(Box::new(io::stderr())),
133 pub fn new(dst: Box<Write + Send>, code_map: Option<Rc<CodeMapper>>) -> EmitterWriter {
140 fn preprocess_annotations(&mut self, msp: &MultiSpan) -> Vec<FileWithAnnotatedLines> {
141 fn add_annotation_to_file(file_vec: &mut Vec<FileWithAnnotatedLines>,
146 for slot in file_vec.iter_mut() {
147 // Look through each of our files for the one we're adding to
148 if slot.file.name == file.name {
149 // See if we already have a line for it
150 for line_slot in &mut slot.lines {
151 if line_slot.line_index == line_index {
152 line_slot.annotations.push(ann);
156 // We don't have a line yet, create one
157 slot.lines.push(Line {
158 line_index: line_index,
159 annotations: vec![ann],
165 // This is the first time we're seeing the file
166 file_vec.push(FileWithAnnotatedLines {
169 line_index: line_index,
170 annotations: vec![ann],
176 let mut output = vec![];
177 let mut multiline_annotations = vec![];
179 if let Some(ref cm) = self.cm {
180 for span_label in msp.span_labels() {
181 if span_label.span == DUMMY_SP {
185 let lo = cm.lookup_char_pos(span_label.span.lo);
186 let mut hi = cm.lookup_char_pos(span_label.span.hi);
188 // Watch out for "empty spans". If we get a span like 6..6, we
189 // want to just display a `^` at 6, so convert that to
190 // 6..7. This is degenerate input, but it's best to degrade
191 // gracefully -- and the parser likes to supply a span like
192 // that for EOF, in particular.
193 if lo.col == hi.col && lo.line == hi.line {
194 hi.col = CharPos(lo.col.0 + 1);
197 let ann_type = if lo.line != hi.line {
198 let ml = MultilineAnnotation {
204 is_primary: span_label.is_primary,
205 label: span_label.label.clone(),
207 multiline_annotations.push((lo.file.clone(), ml.clone()));
208 AnnotationType::Multiline(ml)
210 AnnotationType::Singleline
212 let ann = Annotation {
215 is_primary: span_label.is_primary,
216 label: span_label.label.clone(),
217 annotation_type: ann_type,
220 if !ann.is_multiline() {
221 add_annotation_to_file(&mut output,
229 // Find overlapping multiline annotations, put them at different depths
230 multiline_annotations.sort_by(|a, b| {
231 (a.1.line_start, a.1.line_end).cmp(&(b.1.line_start, b.1.line_end))
233 for item in multiline_annotations.clone() {
235 for item in multiline_annotations.iter_mut() {
236 let ref mut a = item.1;
237 // Move all other multiline annotations overlapping with this one
238 // one level to the right.
240 num_overlap(ann.line_start, ann.line_end, a.line_start, a.line_end, true)
249 let mut max_depth = 0; // max overlapping multiline spans
250 for (file, ann) in multiline_annotations {
251 if ann.depth > max_depth {
252 max_depth = ann.depth;
254 add_annotation_to_file(&mut output, file.clone(), ann.line_start, ann.as_start());
255 let middle = min(ann.line_start + 4, ann.line_end);
256 for line in ann.line_start + 1..middle {
257 add_annotation_to_file(&mut output, file.clone(), line, ann.as_line());
259 if middle < ann.line_end - 1 {
260 for line in ann.line_end - 1..ann.line_end {
261 add_annotation_to_file(&mut output, file.clone(), line, ann.as_line());
264 add_annotation_to_file(&mut output, file, ann.line_end, ann.as_end());
266 for file_vec in output.iter_mut() {
267 file_vec.multiline_depth = max_depth;
272 fn render_source_line(&self,
273 buffer: &mut StyledBuffer,
277 code_offset: usize) -> Vec<(usize, Style)> {
278 let source_string = match file.get_line(line.line_index - 1) {
280 None => return Vec::new(),
283 let line_offset = buffer.num_lines();
285 // First create the source line we will highlight.
286 buffer.puts(line_offset, code_offset, &source_string, Style::Quotation);
287 buffer.puts(line_offset,
289 &(line.line_index.to_string()),
292 draw_col_separator(buffer, line_offset, width_offset - 2);
294 // Special case when there's only one annotation involved, it is the start of a multiline
295 // span and there's no text at the beginning of the code line. Instead of doing the whole
304 // we simplify the output to:
310 if line.annotations.len() == 1 {
311 if let Some(ref ann) = line.annotations.get(0) {
312 if let AnnotationType::MultilineStart(depth) = ann.annotation_type {
313 if source_string[0..ann.start_col].trim() == "" {
314 let style = if ann.is_primary {
315 Style::UnderlinePrimary
317 Style::UnderlineSecondary
319 buffer.putc(line_offset,
320 width_offset + depth - 1,
323 return vec![(depth, style)];
329 // We want to display like this:
331 // vec.push(vec.pop().unwrap());
332 // --- ^^^ - previous borrow ends here
334 // | error occurs here
335 // previous borrow of `vec` occurs here
337 // But there are some weird edge cases to be aware of:
339 // vec.push(vec.pop().unwrap());
340 // -------- - previous borrow ends here
342 // |this makes no sense
343 // previous borrow of `vec` occurs here
345 // For this reason, we group the lines into "highlight lines"
346 // and "annotations lines", where the highlight lines have the `^`.
348 // Sort the annotations by (start, end col)
349 let mut annotations = line.annotations.clone();
351 annotations.reverse();
353 // First, figure out where each label will be positioned.
355 // In the case where you have the following annotations:
357 // vec.push(vec.pop().unwrap());
358 // -------- - previous borrow ends here [C]
360 // |this makes no sense [B]
361 // previous borrow of `vec` occurs here [A]
363 // `annotations_position` will hold [(2, A), (1, B), (0, C)].
365 // We try, when possible, to stick the rightmost annotation at the end
366 // of the highlight line:
368 // vec.push(vec.pop().unwrap());
369 // --- --- - previous borrow ends here
371 // But sometimes that's not possible because one of the other
372 // annotations overlaps it. For example, from the test
373 // `span_overlap_label`, we have the following annotations
374 // (written on distinct lines for clarity):
380 // In this case, we can't stick the rightmost-most label on
381 // the highlight line, or we would get:
388 // which is totally weird. Instead we want:
396 // which is...less weird, at least. In fact, in general, if
397 // the rightmost span overlaps with any other span, we should
398 // use the "hang below" version, so we can at least make it
399 // clear where the span *starts*. There's an exception for this
400 // logic, when the labels do not have a message:
415 let mut annotations_position = vec![];
416 let mut line_len = 0;
418 for (i, annotation) in annotations.iter().enumerate() {
419 for (j, next) in annotations.iter().enumerate() {
420 if overlaps(next, annotation, 0) // This label overlaps with another one and both
421 && annotation.has_label() // take space (they have text and are not
422 && j > i // multiline lines).
423 && p == 0 // We're currently on the first line, move the label one line down
425 // This annotation needs a new line in the output.
430 annotations_position.push((p, annotation));
431 for (j, next) in annotations.iter().enumerate() {
433 let l = if let Some(ref label) = next.label {
438 if (overlaps(next, annotation, l) // Do not allow two labels to be in the same
439 // line if they overlap including padding, to
440 // avoid situations like:
447 && annotation.has_label() // Both labels must have some text, otherwise
448 && next.has_label()) // they are not overlapping.
449 // Do not add a new line if this annotation
450 // or the next are vertical line placeholders.
451 || (annotation.takes_space() // If either this or the next annotation is
452 && next.has_label()) // multiline start/end, move it to a new line
453 || (annotation.has_label() // so as not to overlap the orizontal lines.
454 && next.takes_space())
455 || (annotation.takes_space() && next.takes_space())
456 || (overlaps(next, annotation, l)
457 && next.end_col <= annotation.end_col
459 && p == 0) // Avoid #42595.
461 // This annotation needs a new line in the output.
476 // If there are no annotations or the only annotations on this line are
477 // MultilineLine, then there's only code being shown, stop processing.
478 if line.annotations.is_empty() || line.annotations.iter()
479 .filter(|a| !a.is_line()).collect::<Vec<_>>().len() == 0
484 // Write the colunmn separator.
486 // After this we will have:
495 for pos in 0..line_len + 1 {
496 draw_col_separator(buffer, line_offset + pos + 1, width_offset - 2);
497 buffer.putc(line_offset + pos + 1,
503 // Write the horizontal lines for multiline annotations
504 // (only the first and last lines need this).
506 // After this we will have:
515 for &(pos, annotation) in &annotations_position {
516 let style = if annotation.is_primary {
517 Style::UnderlinePrimary
519 Style::UnderlineSecondary
522 match annotation.annotation_type {
523 AnnotationType::MultilineStart(depth) |
524 AnnotationType::MultilineEnd(depth) => {
528 width_offset + depth,
529 code_offset + annotation.start_col,
536 // Write the vertical lines for labels that are on a different line as the underline.
538 // After this we will have:
547 for &(pos, annotation) in &annotations_position {
548 let style = if annotation.is_primary {
549 Style::UnderlinePrimary
551 Style::UnderlineSecondary
555 if pos > 1 && (annotation.has_label() || annotation.takes_space()) {
556 for p in line_offset + 1..line_offset + pos + 1 {
558 code_offset + annotation.start_col,
563 match annotation.annotation_type {
564 AnnotationType::MultilineStart(depth) => {
565 for p in line_offset + pos + 1..line_offset + line_len + 2 {
567 width_offset + depth - 1,
572 AnnotationType::MultilineEnd(depth) => {
573 for p in line_offset..line_offset + pos + 1 {
575 width_offset + depth - 1,
584 // Write the labels on the annotations that actually have a label.
586 // After this we will have:
591 // | something about `foo`
595 for &(pos, annotation) in &annotations_position {
596 let style = if annotation.is_primary {
599 Style::LabelSecondary
601 let (pos, col) = if pos == 0 {
602 (pos + 1, annotation.end_col + 1)
604 (pos + 2, annotation.start_col)
606 if let Some(ref label) = annotation.label {
607 buffer.puts(line_offset + pos,
614 // Sort from biggest span to smallest span so that smaller spans are
615 // represented in the output:
620 // | | something about `foo`
621 // | something about `fn foo()`
622 annotations_position.sort_by(|a, b| {
624 a.1.len().cmp(&b.1.len()).reverse()
627 // Write the underlines.
629 // After this we will have:
634 // | something about `foo`
638 for &(_, annotation) in &annotations_position {
639 let (underline, style) = if annotation.is_primary {
640 ('^', Style::UnderlinePrimary)
642 ('-', Style::UnderlineSecondary)
644 for p in annotation.start_col..annotation.end_col {
645 buffer.putc(line_offset + 1,
651 annotations_position.iter().filter_map(|&(_, annotation)| {
652 match annotation.annotation_type {
653 AnnotationType::MultilineStart(p) | AnnotationType::MultilineEnd(p) => {
654 let style = if annotation.is_primary {
657 Style::LabelSecondary
664 }).collect::<Vec<_>>()
667 fn get_multispan_max_line_num(&mut self, msp: &MultiSpan) -> usize {
669 if let Some(ref cm) = self.cm {
670 for primary_span in msp.primary_spans() {
671 if primary_span != &DUMMY_SP {
672 let hi = cm.lookup_char_pos(primary_span.hi);
678 for span_label in msp.span_labels() {
679 if span_label.span != DUMMY_SP {
680 let hi = cm.lookup_char_pos(span_label.span.hi);
690 fn get_max_line_num(&mut self, span: &MultiSpan, children: &Vec<SubDiagnostic>) -> usize {
693 let primary = self.get_multispan_max_line_num(span);
694 max = if primary > max { primary } else { max };
696 for sub in children {
697 let sub_result = self.get_multispan_max_line_num(&sub.span);
698 max = if sub_result > max { primary } else { max };
703 // This "fixes" MultiSpans that contain Spans that are pointing to locations inside of
704 // <*macros>. Since these locations are often difficult to read, we move these Spans from
705 // <*macros> to their corresponding use site.
706 fn fix_multispan_in_std_macros(&mut self, span: &mut MultiSpan) -> bool {
707 let mut spans_updated = false;
709 if let Some(ref cm) = self.cm {
710 let mut before_after: Vec<(Span, Span)> = vec![];
711 let mut new_labels: Vec<(Span, String)> = vec![];
713 // First, find all the spans in <*macros> and point instead at their use site
714 for sp in span.primary_spans() {
718 let call_sp = cm.call_span_if_macro(*sp);
720 before_after.push((sp.clone(), call_sp));
722 for trace in sp.macro_backtrace().iter().rev() {
723 // Only show macro locations that are local
724 // and display them like a span_note
725 if let Some(def_site) = trace.def_site_span {
726 if def_site == DUMMY_SP {
729 // Check to make sure we're not in any <*macros>
730 if !cm.span_to_filename(def_site).contains("macros>") &&
731 !trace.macro_decl_name.starts_with("#[") {
732 new_labels.push((trace.call_site,
733 "in this macro invocation".to_string()));
739 for (label_span, label_text) in new_labels {
740 span.push_span_label(label_span, label_text);
742 for sp_label in span.span_labels() {
743 if sp_label.span == DUMMY_SP {
746 if cm.span_to_filename(sp_label.span.clone()).contains("macros>") {
747 let v = sp_label.span.macro_backtrace();
748 if let Some(use_site) = v.last() {
749 before_after.push((sp_label.span.clone(), use_site.call_site.clone()));
753 // After we have them, make sure we replace these 'bad' def sites with their use sites
754 for (before, after) in before_after {
755 span.replace(before, after);
756 spans_updated = true;
763 // This does a small "fix" for multispans by looking to see if it can find any that
764 // point directly at <*macros>. Since these are often difficult to read, this
765 // will change the span to point at the use site.
766 fn fix_multispans_in_std_macros(&mut self,
767 span: &mut MultiSpan,
768 children: &mut Vec<SubDiagnostic>) {
769 let mut spans_updated = self.fix_multispan_in_std_macros(span);
770 for child in children.iter_mut() {
771 spans_updated |= self.fix_multispan_in_std_macros(&mut child.span);
774 children.push(SubDiagnostic {
776 message: vec![("this error originates in a macro outside of the current crate"
777 .to_string(), Style::NoStyle)],
778 span: MultiSpan::new(),
784 /// Add a left margin to every line but the first, given a padding length and the label being
785 /// displayed, keeping the provided highlighting.
786 fn msg_to_buffer(&self,
787 buffer: &mut StyledBuffer,
788 msg: &[(String, Style)],
791 override_style: Option<Style>) {
793 // The extra 5 ` ` is padding that's always needed to align to the `note: `:
806 // | | length of label
808 // `max_line_num_len`
809 let padding = (0..padding + label.len() + 5)
811 .collect::<String>();
813 /// Return wether `style`, or the override if present and the style is `NoStyle`.
814 fn style_or_override(style: Style, override_style: Option<Style>) -> Style {
815 if let Some(o) = override_style {
816 if style == Style::NoStyle {
823 let mut line_number = 0;
825 // Provided the following diagnostic message:
829 // ("highlighted multiline\nstring to\nsee how it ", Style::NoStyle),
830 // ("looks", Style::Highlight),
831 // ("with\nvery ", Style::NoStyle),
832 // ("weird", Style::Highlight),
833 // (" formats\n", Style::NoStyle),
834 // ("see?", Style::Highlight),
837 // the expected output on a note is (* surround the highlighted text)
839 // = note: highlighted multiline
841 // see how it *looks* with
842 // very *weird* formats
844 for &(ref text, ref style) in msg.iter() {
845 let lines = text.split('\n').collect::<Vec<_>>();
847 for (i, line) in lines.iter().enumerate() {
850 buffer.append(line_number, &padding, Style::NoStyle);
852 buffer.append(line_number, line, style_or_override(*style, override_style));
855 buffer.append(line_number, text, style_or_override(*style, override_style));
860 fn emit_message_default(&mut self,
862 msg: &Vec<(String, Style)>,
863 code: &Option<String>,
865 max_line_num_len: usize,
868 let mut buffer = StyledBuffer::new();
870 if msp.primary_spans().is_empty() && msp.span_labels().is_empty() && is_secondary {
871 // This is a secondary message with no span info
872 for _ in 0..max_line_num_len {
873 buffer.prepend(0, " ", Style::NoStyle);
875 draw_note_separator(&mut buffer, 0, max_line_num_len + 1);
876 buffer.append(0, &level.to_string(), Style::HeaderMsg);
877 buffer.append(0, ": ", Style::NoStyle);
878 self.msg_to_buffer(&mut buffer, msg, max_line_num_len, "note", None);
880 buffer.append(0, &level.to_string(), Style::Level(level.clone()));
883 buffer.append(0, "[", Style::Level(level.clone()));
884 buffer.append(0, &code, Style::Level(level.clone()));
885 buffer.append(0, "]", Style::Level(level.clone()));
889 buffer.append(0, ": ", Style::HeaderMsg);
890 for &(ref text, _) in msg.iter() {
891 buffer.append(0, text, Style::HeaderMsg);
895 // Preprocess all the annotations so that they are grouped by file and by line number
896 // This helps us quickly iterate over the whole message (including secondary file spans)
897 let mut annotated_files = self.preprocess_annotations(msp);
899 // Make sure our primary file comes first
900 let (primary_lo, cm) = if let (Some(cm), Some(ref primary_span)) =
901 (self.cm.as_ref(), msp.primary_span().as_ref()) {
902 if primary_span != &&DUMMY_SP {
903 (cm.lookup_char_pos(primary_span.lo), cm)
905 emit_to_destination(&buffer.render(), level, &mut self.dst)?;
909 // If we don't have span information, emit and exit
910 emit_to_destination(&buffer.render(), level, &mut self.dst)?;
914 annotated_files.binary_search_by(|x| x.file.name.cmp(&primary_lo.file.name)) {
915 annotated_files.swap(0, pos);
918 // Print out the annotate source lines that correspond with the error
919 for annotated_file in annotated_files {
920 // we can't annotate anything if the source is unavailable.
921 if !cm.ensure_filemap_source_present(annotated_file.file.clone()) {
925 // print out the span location and spacer before we print the annotated source
926 // to do this, we need to know if this span will be primary
927 let is_primary = primary_lo.file.name == annotated_file.file.name;
929 // remember where we are in the output buffer for easy reference
930 let buffer_msg_line_offset = buffer.num_lines();
932 buffer.prepend(buffer_msg_line_offset, "--> ", Style::LineNumber);
933 let loc = primary_lo.clone();
934 buffer.append(buffer_msg_line_offset,
935 &format!("{}:{}:{}", loc.file.name, loc.line, loc.col.0 + 1),
936 Style::LineAndColumn);
937 for _ in 0..max_line_num_len {
938 buffer.prepend(buffer_msg_line_offset, " ", Style::NoStyle);
941 // remember where we are in the output buffer for easy reference
942 let buffer_msg_line_offset = buffer.num_lines();
945 draw_col_separator(&mut buffer, buffer_msg_line_offset, max_line_num_len + 1);
947 // Then, the secondary file indicator
948 buffer.prepend(buffer_msg_line_offset + 1, "::: ", Style::LineNumber);
949 buffer.append(buffer_msg_line_offset + 1,
950 &annotated_file.file.name,
951 Style::LineAndColumn);
952 for _ in 0..max_line_num_len {
953 buffer.prepend(buffer_msg_line_offset + 1, " ", Style::NoStyle);
957 // Put in the spacer between the location and annotated source
958 let buffer_msg_line_offset = buffer.num_lines();
959 draw_col_separator_no_space(&mut buffer, buffer_msg_line_offset, max_line_num_len + 1);
961 // Contains the vertical lines' positions for active multiline annotations
962 let mut multilines = HashMap::new();
964 // Next, output the annotate source for this file
965 for line_idx in 0..annotated_file.lines.len() {
966 let previous_buffer_line = buffer.num_lines();
968 let width_offset = 3 + max_line_num_len;
969 let code_offset = if annotated_file.multiline_depth == 0 {
972 width_offset + annotated_file.multiline_depth + 1
975 let depths = self.render_source_line(&mut buffer,
976 annotated_file.file.clone(),
977 &annotated_file.lines[line_idx],
981 let mut to_add = HashMap::new();
983 for (depth, style) in depths {
984 if multilines.get(&depth).is_some() {
985 multilines.remove(&depth);
987 to_add.insert(depth, style);
991 // Set the multiline annotation vertical lines to the left of
992 // the code in this line.
993 for (depth, style) in &multilines {
994 for line in previous_buffer_line..buffer.num_lines() {
995 draw_multiline_line(&mut buffer,
1002 // check to see if we need to print out or elide lines that come between
1003 // this annotated line and the next one.
1004 if line_idx < (annotated_file.lines.len() - 1) {
1005 let line_idx_delta = annotated_file.lines[line_idx + 1].line_index -
1006 annotated_file.lines[line_idx].line_index;
1007 if line_idx_delta > 2 {
1008 let last_buffer_line_num = buffer.num_lines();
1009 buffer.puts(last_buffer_line_num, 0, "...", Style::LineNumber);
1011 // Set the multiline annotation vertical lines on `...` bridging line.
1012 for (depth, style) in &multilines {
1013 draw_multiline_line(&mut buffer,
1014 last_buffer_line_num,
1019 } else if line_idx_delta == 2 {
1020 let unannotated_line = annotated_file.file
1021 .get_line(annotated_file.lines[line_idx].line_index)
1022 .unwrap_or_else(|| Cow::from(""));
1024 let last_buffer_line_num = buffer.num_lines();
1026 buffer.puts(last_buffer_line_num,
1028 &(annotated_file.lines[line_idx + 1].line_index - 1)
1031 draw_col_separator(&mut buffer, last_buffer_line_num, 1 + max_line_num_len);
1032 buffer.puts(last_buffer_line_num,
1037 for (depth, style) in &multilines {
1038 draw_multiline_line(&mut buffer,
1039 last_buffer_line_num,
1047 multilines.extend(&to_add);
1051 // final step: take our styled buffer, render it, then output it
1052 emit_to_destination(&buffer.render(), level, &mut self.dst)?;
1056 fn emit_suggestion_default(&mut self,
1057 suggestion: &CodeSuggestion,
1059 max_line_num_len: usize)
1061 use std::borrow::Borrow;
1063 let primary_span = suggestion.substitution_spans().next().unwrap();
1064 if let Some(ref cm) = self.cm {
1065 let mut buffer = StyledBuffer::new();
1067 let lines = cm.span_to_lines(primary_span).unwrap();
1069 assert!(!lines.lines.is_empty());
1071 buffer.append(0, &level.to_string(), Style::Level(level.clone()));
1072 buffer.append(0, ": ", Style::HeaderMsg);
1073 self.msg_to_buffer(&mut buffer,
1074 &[(suggestion.msg.to_owned(), Style::NoStyle)],
1077 Some(Style::HeaderMsg));
1079 let suggestions = suggestion.splice_lines(cm.borrow());
1080 let mut row_num = 1;
1081 for complete in suggestions.iter().take(MAX_SUGGESTIONS) {
1083 // print the suggestion without any line numbers, but leave
1084 // space for them. This helps with lining up with previous
1085 // snippets from the actual error being reported.
1086 let mut lines = complete.lines();
1087 for line in lines.by_ref().take(MAX_HIGHLIGHT_LINES) {
1088 draw_col_separator(&mut buffer, row_num, max_line_num_len + 1);
1089 buffer.append(row_num, line, Style::NoStyle);
1093 // if we elided some lines, add an ellipsis
1094 if let Some(_) = lines.next() {
1095 buffer.append(row_num, "...", Style::NoStyle);
1098 if suggestions.len() > MAX_SUGGESTIONS {
1099 let msg = format!("and {} other candidates", suggestions.len() - MAX_SUGGESTIONS);
1100 buffer.append(row_num, &msg, Style::NoStyle);
1102 emit_to_destination(&buffer.render(), level, &mut self.dst)?;
1106 fn emit_messages_default(&mut self,
1108 message: &Vec<(String, Style)>,
1109 code: &Option<String>,
1111 children: &Vec<SubDiagnostic>) {
1112 let max_line_num = self.get_max_line_num(span, children);
1113 let max_line_num_len = max_line_num.to_string().len();
1115 match self.emit_message_default(span, message, code, level, max_line_num_len, false) {
1117 if !children.is_empty() {
1118 let mut buffer = StyledBuffer::new();
1119 draw_col_separator_no_space(&mut buffer, 0, max_line_num_len + 1);
1120 match emit_to_destination(&buffer.render(), level, &mut self.dst) {
1122 Err(e) => panic!("failed to emit error: {}", e)
1125 for child in children {
1126 match child.render_span {
1127 Some(FullSpan(ref msp)) => {
1128 match self.emit_message_default(msp,
1129 &child.styled_message(),
1134 Err(e) => panic!("failed to emit error: {}", e),
1138 Some(Suggestion(ref cs)) => {
1139 match self.emit_suggestion_default(cs,
1142 Err(e) => panic!("failed to emit error: {}", e),
1147 match self.emit_message_default(&child.span,
1148 &child.styled_message(),
1153 Err(e) => panic!("failed to emit error: {}", e),
1160 Err(e) => panic!("failed to emit error: {}", e),
1162 match write!(&mut self.dst, "\n") {
1163 Err(e) => panic!("failed to emit error: {}", e),
1165 match self.dst.flush() {
1166 Err(e) => panic!("failed to emit error: {}", e),
1174 fn draw_col_separator(buffer: &mut StyledBuffer, line: usize, col: usize) {
1175 buffer.puts(line, col, "| ", Style::LineNumber);
1178 fn draw_col_separator_no_space(buffer: &mut StyledBuffer, line: usize, col: usize) {
1179 draw_col_separator_no_space_with_style(buffer, line, col, Style::LineNumber);
1182 fn draw_col_separator_no_space_with_style(buffer: &mut StyledBuffer,
1186 buffer.putc(line, col, '|', style);
1189 fn draw_range(buffer: &mut StyledBuffer, symbol: char, line: usize,
1190 col_from: usize, col_to: usize, style: Style) {
1191 for col in col_from..col_to {
1192 buffer.putc(line, col, symbol, style);
1196 fn draw_note_separator(buffer: &mut StyledBuffer, line: usize, col: usize) {
1197 buffer.puts(line, col, "= ", Style::LineNumber);
1200 fn draw_multiline_line(buffer: &mut StyledBuffer,
1206 buffer.putc(line, offset + depth - 1, '|', style);
1209 fn num_overlap(a_start: usize, a_end: usize, b_start: usize, b_end:usize, inclusive: bool) -> bool {
1210 let extra = if inclusive {
1215 (b_start..b_end + extra).contains(a_start) ||
1216 (a_start..a_end + extra).contains(b_start)
1218 fn overlaps(a1: &Annotation, a2: &Annotation, padding: usize) -> bool {
1219 num_overlap(a1.start_col, a1.end_col + padding, a2.start_col, a2.end_col, false)
1222 fn emit_to_destination(rendered_buffer: &Vec<Vec<StyledString>>,
1224 dst: &mut Destination)
1228 // In order to prevent error message interleaving, where multiple error lines get intermixed
1229 // when multiple compiler processes error simultaneously, we emit errors with additional
1232 // On Unix systems, we write into a buffered terminal rather than directly to a terminal. When
1233 // the .flush() is called we take the buffer created from the buffered writes and write it at
1234 // one shot. Because the Unix systems use ANSI for the colors, which is a text-based styling
1235 // scheme, this buffered approach works and maintains the styling.
1237 // On Windows, styling happens through calls to a terminal API. This prevents us from using the
1238 // same buffering approach. Instead, we use a global Windows mutex, which we acquire long
1239 // enough to output the full error message, then we release.
1240 let _buffer_lock = lock::acquire_global_lock("rustc_errors");
1241 for line in rendered_buffer {
1243 dst.apply_style(lvl.clone(), part.style)?;
1244 write!(dst, "{}", part.text)?;
1254 fn stderr_isatty() -> bool {
1256 unsafe { libc::isatty(libc::STDERR_FILENO) != 0 }
1259 fn stderr_isatty() -> bool {
1262 type HANDLE = *mut u8;
1263 const STD_ERROR_HANDLE: DWORD = -12i32 as DWORD;
1265 fn GetStdHandle(which: DWORD) -> HANDLE;
1266 fn GetConsoleMode(hConsoleHandle: HANDLE, lpMode: *mut DWORD) -> BOOL;
1269 let handle = GetStdHandle(STD_ERROR_HANDLE);
1271 GetConsoleMode(handle, &mut out) != 0
1275 pub type BufferedStderr = term::Terminal<Output = BufferedWriter> + Send;
1277 pub enum Destination {
1278 Terminal(Box<term::StderrTerminal>),
1279 BufferedTerminal(Box<BufferedStderr>),
1280 Raw(Box<Write + Send>),
1283 /// Buffered writer gives us a way on Unix to buffer up an entire error message before we output
1284 /// it. This helps to prevent interleaving of multiple error messages when multiple compiler
1285 /// processes error simultaneously
1286 pub struct BufferedWriter {
1290 impl BufferedWriter {
1291 // note: we use _new because the conditional compilation at its use site may make this
1292 // this function unused on some platforms
1293 fn _new() -> BufferedWriter {
1294 BufferedWriter { buffer: vec![] }
1298 impl Write for BufferedWriter {
1299 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
1301 self.buffer.push(*b);
1305 fn flush(&mut self) -> io::Result<()> {
1306 let mut stderr = io::stderr();
1307 let result = stderr.write_all(&self.buffer)
1308 .and_then(|_| stderr.flush());
1309 self.buffer.clear();
1315 #[cfg(not(windows))]
1316 /// When not on Windows, prefer the buffered terminal so that we can buffer an entire error
1317 /// to be emitted at one time.
1318 fn from_stderr() -> Destination {
1319 let stderr: Option<Box<BufferedStderr>> =
1320 term::TerminfoTerminal::new(BufferedWriter::_new())
1321 .map(|t| Box::new(t) as Box<BufferedStderr>);
1324 Some(t) => BufferedTerminal(t),
1325 None => Raw(Box::new(io::stderr())),
1330 /// Return a normal, unbuffered terminal when on Windows.
1331 fn from_stderr() -> Destination {
1332 let stderr: Option<Box<term::StderrTerminal>> = term::TerminfoTerminal::new(io::stderr())
1333 .map(|t| Box::new(t) as Box<term::StderrTerminal>)
1335 term::WinConsole::new(io::stderr())
1337 .map(|t| Box::new(t) as Box<term::StderrTerminal>)
1341 Some(t) => Terminal(t),
1342 None => Raw(Box::new(io::stderr())),
1346 fn apply_style(&mut self, lvl: Level, style: Style) -> io::Result<()> {
1348 Style::FileNameStyle | Style::LineAndColumn => {}
1349 Style::LineNumber => {
1350 self.start_attr(term::Attr::Bold)?;
1352 self.start_attr(term::Attr::ForegroundColor(term::color::BRIGHT_CYAN))?;
1354 self.start_attr(term::Attr::ForegroundColor(term::color::BRIGHT_BLUE))?;
1357 Style::ErrorCode => {
1358 self.start_attr(term::Attr::Bold)?;
1359 self.start_attr(term::Attr::ForegroundColor(term::color::BRIGHT_MAGENTA))?;
1361 Style::Quotation => {}
1362 Style::OldSchoolNote => {
1363 self.start_attr(term::Attr::Bold)?;
1364 self.start_attr(term::Attr::ForegroundColor(term::color::BRIGHT_GREEN))?;
1366 Style::OldSchoolNoteText | Style::HeaderMsg => {
1367 self.start_attr(term::Attr::Bold)?;
1369 self.start_attr(term::Attr::ForegroundColor(term::color::BRIGHT_WHITE))?;
1372 Style::UnderlinePrimary | Style::LabelPrimary => {
1373 self.start_attr(term::Attr::Bold)?;
1374 self.start_attr(term::Attr::ForegroundColor(lvl.color()))?;
1376 Style::UnderlineSecondary |
1377 Style::LabelSecondary => {
1378 self.start_attr(term::Attr::Bold)?;
1380 self.start_attr(term::Attr::ForegroundColor(term::color::BRIGHT_CYAN))?;
1382 self.start_attr(term::Attr::ForegroundColor(term::color::BRIGHT_BLUE))?;
1385 Style::NoStyle => {}
1386 Style::Level(l) => {
1387 self.start_attr(term::Attr::Bold)?;
1388 self.start_attr(term::Attr::ForegroundColor(l.color()))?;
1390 Style::Highlight => self.start_attr(term::Attr::Bold)?,
1395 fn start_attr(&mut self, attr: term::Attr) -> io::Result<()> {
1397 Terminal(ref mut t) => {
1400 BufferedTerminal(ref mut t) => {
1408 fn reset_attrs(&mut self) -> io::Result<()> {
1410 Terminal(ref mut t) => {
1413 BufferedTerminal(ref mut t) => {
1422 impl Write for Destination {
1423 fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
1425 Terminal(ref mut t) => t.write(bytes),
1426 BufferedTerminal(ref mut t) => t.write(bytes),
1427 Raw(ref mut w) => w.write(bytes),
1430 fn flush(&mut self) -> io::Result<()> {
1432 Terminal(ref mut t) => t.flush(),
1433 BufferedTerminal(ref mut t) => t.flush(),
1434 Raw(ref mut w) => w.flush(),