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 || !sugg.show_code_when_inline {
51 // This substitution is only removal or we explicitely don't want to show the
52 // code inline, don't show it
53 format!("help: {}", sugg.msg)
55 format!("help: {}: `{}`", sugg.msg, substitution)
57 primary_span.push_span_label(sugg.substitution_spans().next().unwrap(), msg);
59 // if there are multiple suggestions, print them all in full
60 // to be consistent. We could try to figure out if we can
61 // make one (or the first one) inline, but that would give
62 // undue importance to a semi-random suggestion
63 for sugg in &db.suggestions {
64 children.push(SubDiagnostic {
67 span: MultiSpan::new(),
68 render_span: Some(Suggestion(sugg.clone())),
74 self.fix_multispans_in_std_macros(&mut primary_span, &mut children);
75 self.emit_messages_default(&db.level,
83 /// maximum number of lines we will print for each error; arbitrary.
84 pub const MAX_HIGHLIGHT_LINES: usize = 6;
85 /// maximum number of suggestions to be shown
87 /// Arbitrary, but taken from trait import suggestion limit
88 pub const MAX_SUGGESTIONS: usize = 4;
90 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
91 pub enum ColorConfig {
98 fn use_color(&self) -> bool {
100 ColorConfig::Always => true,
101 ColorConfig::Never => false,
102 ColorConfig::Auto => stderr_isatty(),
107 pub struct EmitterWriter {
109 cm: Option<Rc<CodeMapper>>,
112 struct FileWithAnnotatedLines {
115 multiline_depth: usize,
119 pub fn stderr(color_config: ColorConfig, code_map: Option<Rc<CodeMapper>>) -> EmitterWriter {
120 if color_config.use_color() {
121 let dst = Destination::from_stderr();
128 dst: Raw(Box::new(io::stderr())),
134 pub fn new(dst: Box<Write + Send>, code_map: Option<Rc<CodeMapper>>) -> EmitterWriter {
141 fn preprocess_annotations(&mut self, msp: &MultiSpan) -> Vec<FileWithAnnotatedLines> {
142 fn add_annotation_to_file(file_vec: &mut Vec<FileWithAnnotatedLines>,
147 for slot in file_vec.iter_mut() {
148 // Look through each of our files for the one we're adding to
149 if slot.file.name == file.name {
150 // See if we already have a line for it
151 for line_slot in &mut slot.lines {
152 if line_slot.line_index == line_index {
153 line_slot.annotations.push(ann);
157 // We don't have a line yet, create one
158 slot.lines.push(Line {
160 annotations: vec![ann],
166 // This is the first time we're seeing the file
167 file_vec.push(FileWithAnnotatedLines {
171 annotations: vec![ann],
177 let mut output = vec![];
178 let mut multiline_annotations = vec![];
180 if let Some(ref cm) = self.cm {
181 for span_label in msp.span_labels() {
182 if span_label.span == DUMMY_SP {
186 let lo = cm.lookup_char_pos(span_label.span.lo());
187 let mut hi = cm.lookup_char_pos(span_label.span.hi());
189 // Watch out for "empty spans". If we get a span like 6..6, we
190 // want to just display a `^` at 6, so convert that to
191 // 6..7. This is degenerate input, but it's best to degrade
192 // gracefully -- and the parser likes to supply a span like
193 // that for EOF, in particular.
194 if lo.col == hi.col && lo.line == hi.line {
195 hi.col = CharPos(lo.col.0 + 1);
198 let ann_type = if lo.line != hi.line {
199 let ml = MultilineAnnotation {
205 is_primary: span_label.is_primary,
206 label: span_label.label.clone(),
208 multiline_annotations.push((lo.file.clone(), ml.clone()));
209 AnnotationType::Multiline(ml)
211 AnnotationType::Singleline
213 let ann = Annotation {
216 is_primary: span_label.is_primary,
217 label: span_label.label.clone(),
218 annotation_type: ann_type,
221 if !ann.is_multiline() {
222 add_annotation_to_file(&mut output,
230 // Find overlapping multiline annotations, put them at different depths
231 multiline_annotations.sort_by(|a, b| {
232 (a.1.line_start, a.1.line_end).cmp(&(b.1.line_start, b.1.line_end))
234 for item in multiline_annotations.clone() {
236 for item in multiline_annotations.iter_mut() {
237 let ref mut a = item.1;
238 // Move all other multiline annotations overlapping with this one
239 // one level to the right.
241 num_overlap(ann.line_start, ann.line_end, a.line_start, a.line_end, true)
250 let mut max_depth = 0; // max overlapping multiline spans
251 for (file, ann) in multiline_annotations {
252 if ann.depth > max_depth {
253 max_depth = ann.depth;
255 add_annotation_to_file(&mut output, file.clone(), ann.line_start, ann.as_start());
256 let middle = min(ann.line_start + 4, ann.line_end);
257 for line in ann.line_start + 1..middle {
258 add_annotation_to_file(&mut output, file.clone(), line, ann.as_line());
260 if middle < ann.line_end - 1 {
261 for line in ann.line_end - 1..ann.line_end {
262 add_annotation_to_file(&mut output, file.clone(), line, ann.as_line());
265 add_annotation_to_file(&mut output, file, ann.line_end, ann.as_end());
267 for file_vec in output.iter_mut() {
268 file_vec.multiline_depth = max_depth;
273 fn render_source_line(&self,
274 buffer: &mut StyledBuffer,
278 code_offset: usize) -> Vec<(usize, Style)> {
279 let source_string = match file.get_line(line.line_index - 1) {
281 None => return Vec::new(),
284 let line_offset = buffer.num_lines();
286 // First create the source line we will highlight.
287 buffer.puts(line_offset, code_offset, &source_string, Style::Quotation);
288 buffer.puts(line_offset,
290 &(line.line_index.to_string()),
293 draw_col_separator(buffer, line_offset, width_offset - 2);
295 // Special case when there's only one annotation involved, it is the start of a multiline
296 // span and there's no text at the beginning of the code line. Instead of doing the whole
305 // we simplify the output to:
311 if line.annotations.len() == 1 {
312 if let Some(ref ann) = line.annotations.get(0) {
313 if let AnnotationType::MultilineStart(depth) = ann.annotation_type {
314 if source_string.chars()
316 .all(|c| c.is_whitespace()) {
317 let style = if ann.is_primary {
318 Style::UnderlinePrimary
320 Style::UnderlineSecondary
322 buffer.putc(line_offset,
323 width_offset + depth - 1,
326 return vec![(depth, style)];
332 // We want to display like this:
334 // vec.push(vec.pop().unwrap());
335 // --- ^^^ - previous borrow ends here
337 // | error occurs here
338 // previous borrow of `vec` occurs here
340 // But there are some weird edge cases to be aware of:
342 // vec.push(vec.pop().unwrap());
343 // -------- - previous borrow ends here
345 // |this makes no sense
346 // previous borrow of `vec` occurs here
348 // For this reason, we group the lines into "highlight lines"
349 // and "annotations lines", where the highlight lines have the `^`.
351 // Sort the annotations by (start, end col)
352 // The labels are reversed, sort and then reversed again.
353 // Consider a list of annotations (A1, A2, C1, C2, B1, B2) where
354 // the letter signifies the span. Here we are only sorting by the
355 // span and hence, the order of the elements with the same span will
356 // not change. On reversing the ordering (|a, b| but b.cmp(a)), you get
357 // (C1, C2, B1, B2, A1, A2). All the elements with the same span are
358 // still ordered first to last, but all the elements with different
359 // spans are ordered by their spans in last to first order. Last to
360 // first order is important, because the jiggly lines and | are on
361 // the left, so the rightmost span needs to be rendered first,
362 // otherwise the lines would end up needing to go over a message.
364 let mut annotations = line.annotations.clone();
365 annotations.sort_by(|a,b| b.start_col.cmp(&a.start_col));
367 // First, figure out where each label will be positioned.
369 // In the case where you have the following annotations:
371 // vec.push(vec.pop().unwrap());
372 // -------- - previous borrow ends here [C]
374 // |this makes no sense [B]
375 // previous borrow of `vec` occurs here [A]
377 // `annotations_position` will hold [(2, A), (1, B), (0, C)].
379 // We try, when possible, to stick the rightmost annotation at the end
380 // of the highlight line:
382 // vec.push(vec.pop().unwrap());
383 // --- --- - previous borrow ends here
385 // But sometimes that's not possible because one of the other
386 // annotations overlaps it. For example, from the test
387 // `span_overlap_label`, we have the following annotations
388 // (written on distinct lines for clarity):
394 // In this case, we can't stick the rightmost-most label on
395 // the highlight line, or we would get:
402 // which is totally weird. Instead we want:
410 // which is...less weird, at least. In fact, in general, if
411 // the rightmost span overlaps with any other span, we should
412 // use the "hang below" version, so we can at least make it
413 // clear where the span *starts*. There's an exception for this
414 // logic, when the labels do not have a message:
429 let mut annotations_position = vec![];
430 let mut line_len = 0;
432 for (i, annotation) in annotations.iter().enumerate() {
433 for (j, next) in annotations.iter().enumerate() {
434 if overlaps(next, annotation, 0) // This label overlaps with another one and both
435 && annotation.has_label() // take space (they have text and are not
436 && j > i // multiline lines).
437 && p == 0 // We're currently on the first line, move the label one line down
439 // This annotation needs a new line in the output.
444 annotations_position.push((p, annotation));
445 for (j, next) in annotations.iter().enumerate() {
447 let l = if let Some(ref label) = next.label {
452 if (overlaps(next, annotation, l) // Do not allow two labels to be in the same
453 // line if they overlap including padding, to
454 // avoid situations like:
461 && annotation.has_label() // Both labels must have some text, otherwise
462 && next.has_label()) // they are not overlapping.
463 // Do not add a new line if this annotation
464 // or the next are vertical line placeholders.
465 || (annotation.takes_space() // If either this or the next annotation is
466 && next.has_label()) // multiline start/end, move it to a new line
467 || (annotation.has_label() // so as not to overlap the orizontal lines.
468 && next.takes_space())
469 || (annotation.takes_space() && next.takes_space())
470 || (overlaps(next, annotation, l)
471 && next.end_col <= annotation.end_col
473 && p == 0) // Avoid #42595.
475 // This annotation needs a new line in the output.
490 // If there are no annotations or the only annotations on this line are
491 // MultilineLine, then there's only code being shown, stop processing.
492 if line.annotations.is_empty() || line.annotations.iter()
493 .filter(|a| !a.is_line()).collect::<Vec<_>>().len() == 0
498 // Write the colunmn separator.
500 // After this we will have:
509 for pos in 0..line_len + 1 {
510 draw_col_separator(buffer, line_offset + pos + 1, width_offset - 2);
511 buffer.putc(line_offset + pos + 1,
517 // Write the horizontal lines for multiline annotations
518 // (only the first and last lines need this).
520 // After this we will have:
529 for &(pos, annotation) in &annotations_position {
530 let style = if annotation.is_primary {
531 Style::UnderlinePrimary
533 Style::UnderlineSecondary
536 match annotation.annotation_type {
537 AnnotationType::MultilineStart(depth) |
538 AnnotationType::MultilineEnd(depth) => {
542 width_offset + depth,
543 code_offset + annotation.start_col,
550 // Write the vertical lines for labels that are on a different line as the underline.
552 // After this we will have:
561 for &(pos, annotation) in &annotations_position {
562 let style = if annotation.is_primary {
563 Style::UnderlinePrimary
565 Style::UnderlineSecondary
569 if pos > 1 && (annotation.has_label() || annotation.takes_space()) {
570 for p in line_offset + 1..line_offset + pos + 1 {
572 code_offset + annotation.start_col,
577 match annotation.annotation_type {
578 AnnotationType::MultilineStart(depth) => {
579 for p in line_offset + pos + 1..line_offset + line_len + 2 {
581 width_offset + depth - 1,
586 AnnotationType::MultilineEnd(depth) => {
587 for p in line_offset..line_offset + pos + 1 {
589 width_offset + depth - 1,
598 // Write the labels on the annotations that actually have a label.
600 // After this we will have:
605 // | something about `foo`
609 for &(pos, annotation) in &annotations_position {
610 let style = if annotation.is_primary {
613 Style::LabelSecondary
615 let (pos, col) = if pos == 0 {
616 (pos + 1, annotation.end_col + 1)
618 (pos + 2, annotation.start_col)
620 if let Some(ref label) = annotation.label {
621 buffer.puts(line_offset + pos,
628 // Sort from biggest span to smallest span so that smaller spans are
629 // represented in the output:
634 // | | something about `foo`
635 // | something about `fn foo()`
636 annotations_position.sort_by(|a, b| {
638 a.1.len().cmp(&b.1.len()).reverse()
641 // Write the underlines.
643 // After this we will have:
648 // | something about `foo`
652 for &(_, annotation) in &annotations_position {
653 let (underline, style) = if annotation.is_primary {
654 ('^', Style::UnderlinePrimary)
656 ('-', Style::UnderlineSecondary)
658 for p in annotation.start_col..annotation.end_col {
659 buffer.putc(line_offset + 1,
665 annotations_position.iter().filter_map(|&(_, annotation)| {
666 match annotation.annotation_type {
667 AnnotationType::MultilineStart(p) | AnnotationType::MultilineEnd(p) => {
668 let style = if annotation.is_primary {
671 Style::LabelSecondary
678 }).collect::<Vec<_>>()
681 fn get_multispan_max_line_num(&mut self, msp: &MultiSpan) -> usize {
683 if let Some(ref cm) = self.cm {
684 for primary_span in msp.primary_spans() {
685 if primary_span != &DUMMY_SP {
686 let hi = cm.lookup_char_pos(primary_span.hi());
692 for span_label in msp.span_labels() {
693 if span_label.span != DUMMY_SP {
694 let hi = cm.lookup_char_pos(span_label.span.hi());
704 fn get_max_line_num(&mut self, span: &MultiSpan, children: &Vec<SubDiagnostic>) -> usize {
707 let primary = self.get_multispan_max_line_num(span);
708 max = if primary > max { primary } else { max };
710 for sub in children {
711 let sub_result = self.get_multispan_max_line_num(&sub.span);
712 max = if sub_result > max { primary } else { max };
717 // This "fixes" MultiSpans that contain Spans that are pointing to locations inside of
718 // <*macros>. Since these locations are often difficult to read, we move these Spans from
719 // <*macros> to their corresponding use site.
720 fn fix_multispan_in_std_macros(&mut self, span: &mut MultiSpan) -> bool {
721 let mut spans_updated = false;
723 if let Some(ref cm) = self.cm {
724 let mut before_after: Vec<(Span, Span)> = vec![];
725 let mut new_labels: Vec<(Span, String)> = vec![];
727 // First, find all the spans in <*macros> and point instead at their use site
728 for sp in span.primary_spans() {
732 let call_sp = cm.call_span_if_macro(*sp);
734 before_after.push((sp.clone(), call_sp));
736 for trace in sp.macro_backtrace().iter().rev() {
737 // Only show macro locations that are local
738 // and display them like a span_note
739 if let Some(def_site) = trace.def_site_span {
740 if def_site == DUMMY_SP {
743 // Check to make sure we're not in any <*macros>
744 if !cm.span_to_filename(def_site).contains("macros>") &&
745 !trace.macro_decl_name.starts_with("#[") {
746 new_labels.push((trace.call_site,
747 "in this macro invocation".to_string()));
753 for (label_span, label_text) in new_labels {
754 span.push_span_label(label_span, label_text);
756 for sp_label in span.span_labels() {
757 if sp_label.span == DUMMY_SP {
760 if cm.span_to_filename(sp_label.span.clone()).contains("macros>") {
761 let v = sp_label.span.macro_backtrace();
762 if let Some(use_site) = v.last() {
763 before_after.push((sp_label.span.clone(), use_site.call_site.clone()));
767 // After we have them, make sure we replace these 'bad' def sites with their use sites
768 for (before, after) in before_after {
769 span.replace(before, after);
770 spans_updated = true;
777 // This does a small "fix" for multispans by looking to see if it can find any that
778 // point directly at <*macros>. Since these are often difficult to read, this
779 // will change the span to point at the use site.
780 fn fix_multispans_in_std_macros(&mut self,
781 span: &mut MultiSpan,
782 children: &mut Vec<SubDiagnostic>) {
783 let mut spans_updated = self.fix_multispan_in_std_macros(span);
784 for child in children.iter_mut() {
785 spans_updated |= self.fix_multispan_in_std_macros(&mut child.span);
788 children.push(SubDiagnostic {
790 message: vec![("this error originates in a macro outside of the current crate"
791 .to_string(), Style::NoStyle)],
792 span: MultiSpan::new(),
798 /// Add a left margin to every line but the first, given a padding length and the label being
799 /// displayed, keeping the provided highlighting.
800 fn msg_to_buffer(&self,
801 buffer: &mut StyledBuffer,
802 msg: &[(String, Style)],
805 override_style: Option<Style>) {
807 // The extra 5 ` ` is padding that's always needed to align to the `note: `:
820 // | | length of label
822 // `max_line_num_len`
823 let padding = (0..padding + label.len() + 5)
825 .collect::<String>();
827 /// Return whether `style`, or the override if present and the style is `NoStyle`.
828 fn style_or_override(style: Style, override_style: Option<Style>) -> Style {
829 if let Some(o) = override_style {
830 if style == Style::NoStyle {
837 let mut line_number = 0;
839 // Provided the following diagnostic message:
843 // ("highlighted multiline\nstring to\nsee how it ", Style::NoStyle),
844 // ("looks", Style::Highlight),
845 // ("with\nvery ", Style::NoStyle),
846 // ("weird", Style::Highlight),
847 // (" formats\n", Style::NoStyle),
848 // ("see?", Style::Highlight),
851 // the expected output on a note is (* surround the highlighted text)
853 // = note: highlighted multiline
855 // see how it *looks* with
856 // very *weird* formats
858 for &(ref text, ref style) in msg.iter() {
859 let lines = text.split('\n').collect::<Vec<_>>();
861 for (i, line) in lines.iter().enumerate() {
864 buffer.append(line_number, &padding, Style::NoStyle);
866 buffer.append(line_number, line, style_or_override(*style, override_style));
869 buffer.append(line_number, text, style_or_override(*style, override_style));
874 fn emit_message_default(&mut self,
876 msg: &Vec<(String, Style)>,
877 code: &Option<String>,
879 max_line_num_len: usize,
882 let mut buffer = StyledBuffer::new();
884 if msp.primary_spans().is_empty() && msp.span_labels().is_empty() && is_secondary {
885 // This is a secondary message with no span info
886 for _ in 0..max_line_num_len {
887 buffer.prepend(0, " ", Style::NoStyle);
889 draw_note_separator(&mut buffer, 0, max_line_num_len + 1);
890 buffer.append(0, &level.to_string(), Style::HeaderMsg);
891 buffer.append(0, ": ", Style::NoStyle);
892 self.msg_to_buffer(&mut buffer, msg, max_line_num_len, "note", None);
894 buffer.append(0, &level.to_string(), Style::Level(level.clone()));
897 buffer.append(0, "[", Style::Level(level.clone()));
898 buffer.append(0, &code, Style::Level(level.clone()));
899 buffer.append(0, "]", Style::Level(level.clone()));
903 buffer.append(0, ": ", Style::HeaderMsg);
904 for &(ref text, _) in msg.iter() {
905 buffer.append(0, text, Style::HeaderMsg);
909 // Preprocess all the annotations so that they are grouped by file and by line number
910 // This helps us quickly iterate over the whole message (including secondary file spans)
911 let mut annotated_files = self.preprocess_annotations(msp);
913 // Make sure our primary file comes first
914 let (primary_lo, cm) = if let (Some(cm), Some(ref primary_span)) =
915 (self.cm.as_ref(), msp.primary_span().as_ref()) {
916 if primary_span != &&DUMMY_SP {
917 (cm.lookup_char_pos(primary_span.lo()), cm)
919 emit_to_destination(&buffer.render(), level, &mut self.dst)?;
923 // If we don't have span information, emit and exit
924 emit_to_destination(&buffer.render(), level, &mut self.dst)?;
928 annotated_files.binary_search_by(|x| x.file.name.cmp(&primary_lo.file.name)) {
929 annotated_files.swap(0, pos);
932 // Print out the annotate source lines that correspond with the error
933 for annotated_file in annotated_files {
934 // we can't annotate anything if the source is unavailable.
935 if !cm.ensure_filemap_source_present(annotated_file.file.clone()) {
939 // print out the span location and spacer before we print the annotated source
940 // to do this, we need to know if this span will be primary
941 let is_primary = primary_lo.file.name == annotated_file.file.name;
943 // remember where we are in the output buffer for easy reference
944 let buffer_msg_line_offset = buffer.num_lines();
946 buffer.prepend(buffer_msg_line_offset, "--> ", Style::LineNumber);
947 let loc = primary_lo.clone();
948 buffer.append(buffer_msg_line_offset,
949 &format!("{}:{}:{}", loc.file.name, loc.line, loc.col.0 + 1),
950 Style::LineAndColumn);
951 for _ in 0..max_line_num_len {
952 buffer.prepend(buffer_msg_line_offset, " ", Style::NoStyle);
955 // remember where we are in the output buffer for easy reference
956 let buffer_msg_line_offset = buffer.num_lines();
959 draw_col_separator(&mut buffer, buffer_msg_line_offset, max_line_num_len + 1);
961 // Then, the secondary file indicator
962 buffer.prepend(buffer_msg_line_offset + 1, "::: ", Style::LineNumber);
963 buffer.append(buffer_msg_line_offset + 1,
964 &annotated_file.file.name,
965 Style::LineAndColumn);
966 for _ in 0..max_line_num_len {
967 buffer.prepend(buffer_msg_line_offset + 1, " ", Style::NoStyle);
971 // Put in the spacer between the location and annotated source
972 let buffer_msg_line_offset = buffer.num_lines();
973 draw_col_separator_no_space(&mut buffer, buffer_msg_line_offset, max_line_num_len + 1);
975 // Contains the vertical lines' positions for active multiline annotations
976 let mut multilines = HashMap::new();
978 // Next, output the annotate source for this file
979 for line_idx in 0..annotated_file.lines.len() {
980 let previous_buffer_line = buffer.num_lines();
982 let width_offset = 3 + max_line_num_len;
983 let code_offset = if annotated_file.multiline_depth == 0 {
986 width_offset + annotated_file.multiline_depth + 1
989 let depths = self.render_source_line(&mut buffer,
990 annotated_file.file.clone(),
991 &annotated_file.lines[line_idx],
995 let mut to_add = HashMap::new();
997 for (depth, style) in depths {
998 if multilines.get(&depth).is_some() {
999 multilines.remove(&depth);
1001 to_add.insert(depth, style);
1005 // Set the multiline annotation vertical lines to the left of
1006 // the code in this line.
1007 for (depth, style) in &multilines {
1008 for line in previous_buffer_line..buffer.num_lines() {
1009 draw_multiline_line(&mut buffer,
1016 // check to see if we need to print out or elide lines that come between
1017 // this annotated line and the next one.
1018 if line_idx < (annotated_file.lines.len() - 1) {
1019 let line_idx_delta = annotated_file.lines[line_idx + 1].line_index -
1020 annotated_file.lines[line_idx].line_index;
1021 if line_idx_delta > 2 {
1022 let last_buffer_line_num = buffer.num_lines();
1023 buffer.puts(last_buffer_line_num, 0, "...", Style::LineNumber);
1025 // Set the multiline annotation vertical lines on `...` bridging line.
1026 for (depth, style) in &multilines {
1027 draw_multiline_line(&mut buffer,
1028 last_buffer_line_num,
1033 } else if line_idx_delta == 2 {
1034 let unannotated_line = annotated_file.file
1035 .get_line(annotated_file.lines[line_idx].line_index)
1036 .unwrap_or_else(|| Cow::from(""));
1038 let last_buffer_line_num = buffer.num_lines();
1040 buffer.puts(last_buffer_line_num,
1042 &(annotated_file.lines[line_idx + 1].line_index - 1)
1045 draw_col_separator(&mut buffer, last_buffer_line_num, 1 + max_line_num_len);
1046 buffer.puts(last_buffer_line_num,
1051 for (depth, style) in &multilines {
1052 draw_multiline_line(&mut buffer,
1053 last_buffer_line_num,
1061 multilines.extend(&to_add);
1065 // final step: take our styled buffer, render it, then output it
1066 emit_to_destination(&buffer.render(), level, &mut self.dst)?;
1070 fn emit_suggestion_default(&mut self,
1071 suggestion: &CodeSuggestion,
1073 max_line_num_len: usize)
1075 use std::borrow::Borrow;
1077 let primary_sub = &suggestion.substitution_parts[0];
1078 if let Some(ref cm) = self.cm {
1079 let mut buffer = StyledBuffer::new();
1081 let lines = cm.span_to_lines(primary_sub.span).unwrap();
1083 assert!(!lines.lines.is_empty());
1085 buffer.append(0, &level.to_string(), Style::Level(level.clone()));
1086 buffer.append(0, ": ", Style::HeaderMsg);
1087 self.msg_to_buffer(&mut buffer,
1088 &[(suggestion.msg.to_owned(), Style::NoStyle)],
1091 Some(Style::HeaderMsg));
1093 let suggestions = suggestion.splice_lines(cm.borrow());
1094 let span_start_pos = cm.lookup_char_pos(primary_sub.span.lo());
1095 let line_start = span_start_pos.line;
1096 draw_col_separator_no_space(&mut buffer, 1, max_line_num_len + 1);
1097 let mut row_num = 2;
1098 for (&(ref complete, show_underline), ref sub) in suggestions
1099 .iter().zip(primary_sub.substitutions.iter()).take(MAX_SUGGESTIONS)
1101 let mut line_pos = 0;
1102 // Only show underline if there's a single suggestion and it is a single line
1103 let mut lines = complete.lines();
1104 for line in lines.by_ref().take(MAX_HIGHLIGHT_LINES) {
1105 // Print the span column to avoid confusion
1106 buffer.puts(row_num,
1108 &((line_start + line_pos).to_string()),
1110 // print the suggestion
1111 draw_col_separator(&mut buffer, row_num, max_line_num_len + 1);
1112 buffer.append(row_num, line, Style::NoStyle);
1115 // Only show an underline in the suggestions if the suggestion is not the
1116 // entirety of the code being shown and the displayed code is not multiline.
1118 draw_col_separator(&mut buffer, row_num, max_line_num_len + 1);
1119 let sub_len = sub.trim_right().len();
1120 let underline_start = span_start_pos.col.0;
1121 let underline_end = span_start_pos.col.0 + sub_len;
1122 for p in underline_start..underline_end {
1123 buffer.putc(row_num,
1124 max_line_num_len + 3 + p,
1126 Style::UnderlinePrimary);
1132 // if we elided some lines, add an ellipsis
1133 if let Some(_) = lines.next() {
1134 buffer.puts(row_num, max_line_num_len - 1, "...", Style::LineNumber);
1135 } else if !show_underline {
1136 draw_col_separator_no_space(&mut buffer, row_num, max_line_num_len + 1);
1140 if suggestions.len() > MAX_SUGGESTIONS {
1141 let msg = format!("and {} other candidates", suggestions.len() - MAX_SUGGESTIONS);
1142 buffer.puts(row_num, 0, &msg, Style::NoStyle);
1144 emit_to_destination(&buffer.render(), level, &mut self.dst)?;
1148 fn emit_messages_default(&mut self,
1150 message: &Vec<(String, Style)>,
1151 code: &Option<String>,
1153 children: &Vec<SubDiagnostic>) {
1154 let max_line_num = self.get_max_line_num(span, children);
1155 let max_line_num_len = max_line_num.to_string().len();
1157 match self.emit_message_default(span, message, code, level, max_line_num_len, false) {
1159 if !children.is_empty() {
1160 let mut buffer = StyledBuffer::new();
1161 draw_col_separator_no_space(&mut buffer, 0, max_line_num_len + 1);
1162 match emit_to_destination(&buffer.render(), level, &mut self.dst) {
1164 Err(e) => panic!("failed to emit error: {}", e)
1167 for child in children {
1168 match child.render_span {
1169 Some(FullSpan(ref msp)) => {
1170 match self.emit_message_default(msp,
1171 &child.styled_message(),
1176 Err(e) => panic!("failed to emit error: {}", e),
1180 Some(Suggestion(ref cs)) => {
1181 match self.emit_suggestion_default(cs,
1184 Err(e) => panic!("failed to emit error: {}", e),
1189 match self.emit_message_default(&child.span,
1190 &child.styled_message(),
1195 Err(e) => panic!("failed to emit error: {}", e),
1202 Err(e) => panic!("failed to emit error: {}", e),
1204 match write!(&mut self.dst, "\n") {
1205 Err(e) => panic!("failed to emit error: {}", e),
1207 match self.dst.flush() {
1208 Err(e) => panic!("failed to emit error: {}", e),
1216 fn draw_col_separator(buffer: &mut StyledBuffer, line: usize, col: usize) {
1217 buffer.puts(line, col, "| ", Style::LineNumber);
1220 fn draw_col_separator_no_space(buffer: &mut StyledBuffer, line: usize, col: usize) {
1221 draw_col_separator_no_space_with_style(buffer, line, col, Style::LineNumber);
1224 fn draw_col_separator_no_space_with_style(buffer: &mut StyledBuffer,
1228 buffer.putc(line, col, '|', style);
1231 fn draw_range(buffer: &mut StyledBuffer, symbol: char, line: usize,
1232 col_from: usize, col_to: usize, style: Style) {
1233 for col in col_from..col_to {
1234 buffer.putc(line, col, symbol, style);
1238 fn draw_note_separator(buffer: &mut StyledBuffer, line: usize, col: usize) {
1239 buffer.puts(line, col, "= ", Style::LineNumber);
1242 fn draw_multiline_line(buffer: &mut StyledBuffer,
1248 buffer.putc(line, offset + depth - 1, '|', style);
1251 fn num_overlap(a_start: usize, a_end: usize, b_start: usize, b_end:usize, inclusive: bool) -> bool {
1252 let extra = if inclusive {
1257 (b_start..b_end + extra).contains(a_start) ||
1258 (a_start..a_end + extra).contains(b_start)
1260 fn overlaps(a1: &Annotation, a2: &Annotation, padding: usize) -> bool {
1261 num_overlap(a1.start_col, a1.end_col + padding, a2.start_col, a2.end_col, false)
1264 fn emit_to_destination(rendered_buffer: &Vec<Vec<StyledString>>,
1266 dst: &mut Destination)
1270 // In order to prevent error message interleaving, where multiple error lines get intermixed
1271 // when multiple compiler processes error simultaneously, we emit errors with additional
1274 // On Unix systems, we write into a buffered terminal rather than directly to a terminal. When
1275 // the .flush() is called we take the buffer created from the buffered writes and write it at
1276 // one shot. Because the Unix systems use ANSI for the colors, which is a text-based styling
1277 // scheme, this buffered approach works and maintains the styling.
1279 // On Windows, styling happens through calls to a terminal API. This prevents us from using the
1280 // same buffering approach. Instead, we use a global Windows mutex, which we acquire long
1281 // enough to output the full error message, then we release.
1282 let _buffer_lock = lock::acquire_global_lock("rustc_errors");
1283 for line in rendered_buffer {
1285 dst.apply_style(lvl.clone(), part.style)?;
1286 write!(dst, "{}", part.text)?;
1296 fn stderr_isatty() -> bool {
1298 unsafe { libc::isatty(libc::STDERR_FILENO) != 0 }
1301 fn stderr_isatty() -> bool {
1304 type HANDLE = *mut u8;
1305 const STD_ERROR_HANDLE: DWORD = -12i32 as DWORD;
1307 fn GetStdHandle(which: DWORD) -> HANDLE;
1308 fn GetConsoleMode(hConsoleHandle: HANDLE, lpMode: *mut DWORD) -> BOOL;
1311 let handle = GetStdHandle(STD_ERROR_HANDLE);
1313 GetConsoleMode(handle, &mut out) != 0
1317 pub type BufferedStderr = term::Terminal<Output = BufferedWriter> + Send;
1319 pub enum Destination {
1320 Terminal(Box<term::StderrTerminal>),
1321 BufferedTerminal(Box<BufferedStderr>),
1322 Raw(Box<Write + Send>),
1325 /// Buffered writer gives us a way on Unix to buffer up an entire error message before we output
1326 /// it. This helps to prevent interleaving of multiple error messages when multiple compiler
1327 /// processes error simultaneously
1328 pub struct BufferedWriter {
1332 impl BufferedWriter {
1333 // note: we use _new because the conditional compilation at its use site may make this
1334 // this function unused on some platforms
1335 fn _new() -> BufferedWriter {
1336 BufferedWriter { buffer: vec![] }
1340 impl Write for BufferedWriter {
1341 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
1343 self.buffer.push(*b);
1347 fn flush(&mut self) -> io::Result<()> {
1348 let mut stderr = io::stderr();
1349 let result = stderr.write_all(&self.buffer)
1350 .and_then(|_| stderr.flush());
1351 self.buffer.clear();
1357 #[cfg(not(windows))]
1358 /// When not on Windows, prefer the buffered terminal so that we can buffer an entire error
1359 /// to be emitted at one time.
1360 fn from_stderr() -> Destination {
1361 let stderr: Option<Box<BufferedStderr>> =
1362 term::TerminfoTerminal::new(BufferedWriter::_new())
1363 .map(|t| Box::new(t) as Box<BufferedStderr>);
1366 Some(t) => BufferedTerminal(t),
1367 None => Raw(Box::new(io::stderr())),
1372 /// Return a normal, unbuffered terminal when on Windows.
1373 fn from_stderr() -> Destination {
1374 let stderr: Option<Box<term::StderrTerminal>> = term::TerminfoTerminal::new(io::stderr())
1375 .map(|t| Box::new(t) as Box<term::StderrTerminal>)
1377 term::WinConsole::new(io::stderr())
1379 .map(|t| Box::new(t) as Box<term::StderrTerminal>)
1383 Some(t) => Terminal(t),
1384 None => Raw(Box::new(io::stderr())),
1388 fn apply_style(&mut self, lvl: Level, style: Style) -> io::Result<()> {
1390 Style::LineAndColumn => {}
1391 Style::LineNumber => {
1392 self.start_attr(term::Attr::Bold)?;
1394 self.start_attr(term::Attr::ForegroundColor(term::color::BRIGHT_CYAN))?;
1396 self.start_attr(term::Attr::ForegroundColor(term::color::BRIGHT_BLUE))?;
1399 Style::Quotation => {}
1400 Style::HeaderMsg => {
1401 self.start_attr(term::Attr::Bold)?;
1403 self.start_attr(term::Attr::ForegroundColor(term::color::BRIGHT_WHITE))?;
1406 Style::UnderlinePrimary | Style::LabelPrimary => {
1407 self.start_attr(term::Attr::Bold)?;
1408 self.start_attr(term::Attr::ForegroundColor(lvl.color()))?;
1410 Style::UnderlineSecondary |
1411 Style::LabelSecondary => {
1412 self.start_attr(term::Attr::Bold)?;
1414 self.start_attr(term::Attr::ForegroundColor(term::color::BRIGHT_CYAN))?;
1416 self.start_attr(term::Attr::ForegroundColor(term::color::BRIGHT_BLUE))?;
1419 Style::NoStyle => {}
1420 Style::Level(l) => {
1421 self.start_attr(term::Attr::Bold)?;
1422 self.start_attr(term::Attr::ForegroundColor(l.color()))?;
1424 Style::Highlight => self.start_attr(term::Attr::Bold)?,
1429 fn start_attr(&mut self, attr: term::Attr) -> io::Result<()> {
1431 Terminal(ref mut t) => {
1434 BufferedTerminal(ref mut t) => {
1442 fn reset_attrs(&mut self) -> io::Result<()> {
1444 Terminal(ref mut t) => {
1447 BufferedTerminal(ref mut t) => {
1456 impl Write for Destination {
1457 fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
1459 Terminal(ref mut t) => t.write(bytes),
1460 BufferedTerminal(ref mut t) => t.write(bytes),
1461 Raw(ref mut w) => w.write(bytes),
1464 fn flush(&mut self) -> io::Result<()> {
1466 Terminal(ref mut t) => t.flush(),
1467 BufferedTerminal(ref mut t) => t.flush(),
1468 Raw(ref mut w) => w.flush(),