codemap2_diagnostic/emitter.rs
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.
4//
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.
10
11use std::io::prelude::*;
12use std::io;
13use std::cmp::min;
14use std::sync::Arc;
15use std::collections::HashMap;
16use atty;
17use termcolor::{StandardStream, ColorChoice, ColorSpec, BufferWriter};
18use termcolor::{WriteColor, Color, Buffer};
19
20use { Level, Diagnostic, SpanLabel, SpanStyle };
21use codemap2::{CodeMap, File, FileData};
22use snippet::{Annotation, AnnotationType, Line, MultilineAnnotation, StyledString, Style};
23use styled_buffer::StyledBuffer;
24
25/// Settings for terminal styling.
26#[derive(Clone, Copy, Debug, PartialEq, Eq)]
27pub enum ColorConfig {
28 /// Use colored output if stdout is a terminal.
29 Auto,
30
31 /// Always use colored output.
32 Always,
33
34 /// Never use colored output.
35 Never,
36}
37
38impl ColorConfig {
39 fn to_color_choice(&self) -> ColorChoice {
40 match *self {
41 ColorConfig::Always => ColorChoice::Always,
42 ColorConfig::Never => ColorChoice::Never,
43 ColorConfig::Auto if atty::is(atty::Stream::Stderr) => {
44 ColorChoice::Auto
45 }
46 ColorConfig::Auto => ColorChoice::Never,
47 }
48 }
49}
50
51/// Formats and prints diagnostic messages.
52pub struct Emitter<'a, T: FileData> {
53 dst: Destination<'a>,
54 cm: Option<&'a CodeMap<T>>,
55}
56
57struct FileWithAnnotatedLines<T: FileData> {
58 file: Arc<File<T>>,
59 lines: Vec<Line>,
60 multiline_depth: usize,
61}
62
63impl<'a, T: FileData> Emitter<'a, T> {
64 /// Creates an emitter wrapping stderr.
65 pub fn stderr(color_config: ColorConfig, code_map: Option<&'a CodeMap<T>>) -> Self {
66 let dst = Destination::from_stderr(color_config);
67 Self {
68 dst,
69 cm: code_map,
70 }
71 }
72
73 /// Creates an emitter wrapping a vector.
74 pub fn vec(vec: &'a mut Vec<u8>, code_map: Option<&'a CodeMap<T>>) -> Self {
75 Self {
76 dst: Raw(Box::new(vec)),
77 cm: code_map,
78 }
79 }
80
81 /// Creates an emitter wrapping a boxed `Write` trait object.
82 pub fn new(dst: Box<dyn Write + Send + 'a>, code_map: Option<&'a CodeMap<T>>) -> Self {
83 Emitter {
84 dst: Raw(dst),
85 cm: code_map,
86 }
87 }
88
89 fn preprocess_annotations(cm: Option<&'a CodeMap<T>>, spans: &[SpanLabel]) -> Vec<FileWithAnnotatedLines<T>> {
90 fn add_annotation_to_file<'a, T: FileData>(file_vec: &mut Vec<FileWithAnnotatedLines<T>>,
91 file: Arc<File<T>>,
92 line_index: usize,
93 ann: Annotation) {
94
95 for slot in file_vec.iter_mut() {
96 // Look through each of our files for the one we're adding to
97 if slot.file.name() == file.name() {
98 // See if we already have a line for it
99 for line_slot in &mut slot.lines {
100 if line_slot.line_index == line_index {
101 line_slot.annotations.push(ann);
102 return;
103 }
104 }
105 // We don't have a line yet, create one
106 slot.lines.push(Line {
107 line_index,
108 annotations: vec![ann],
109 });
110 slot.lines.sort();
111 return;
112 }
113 }
114 // This is the first time we're seeing the file
115 file_vec.push(FileWithAnnotatedLines {
116 file,
117 lines: vec![Line {
118 line_index: line_index,
119 annotations: vec![ann],
120 }],
121 multiline_depth: 0,
122 });
123 }
124
125 let mut output = vec![];
126 let mut multiline_annotations = vec![];
127
128 if let Some(ref cm) = cm {
129 for span_label in spans {
130 let mut loc = cm.look_up_span(span_label.span);
131
132 // Watch out for "empty spans". If we get a span like 6..6, we
133 // want to just display a `^` at 6, so convert that to
134 // 6..7. This is degenerate input, but it's best to degrade
135 // gracefully -- and the parser likes to supply a span like
136 // that for EOF, in particular.
137 if loc.begin == loc.end {
138 loc.end.column = loc.begin.column + 1;
139 }
140
141 let ann_type = if loc.begin.line != loc.end.line {
142 let ml = MultilineAnnotation {
143 depth: 1,
144 line_start: loc.begin.line,
145 line_end: loc.end.line,
146 start_col: loc.begin.column,
147 end_col: loc.end.column,
148 is_primary: span_label.style == SpanStyle::Primary,
149 label: span_label.label.clone(),
150 };
151 multiline_annotations.push((loc.file.clone(), ml.clone()));
152 AnnotationType::Multiline(ml)
153 } else {
154 AnnotationType::Singleline
155 };
156 let ann = Annotation {
157 start_col: loc.begin.column,
158 end_col: loc.end.column,
159 is_primary: span_label.style == SpanStyle::Primary,
160 label: span_label.label.clone(),
161 annotation_type: ann_type,
162 };
163
164 if !ann.is_multiline() {
165 add_annotation_to_file(&mut output,
166 loc.file,
167 loc.begin.line,
168 ann);
169 }
170 }
171 }
172
173 // Find overlapping multiline annotations, put them at different depths
174 multiline_annotations.sort_by(|a, b| {
175 (a.1.line_start, a.1.line_end).cmp(&(b.1.line_start, b.1.line_end))
176 });
177 for item in multiline_annotations.clone() {
178 let ann = item.1;
179 for item in multiline_annotations.iter_mut() {
180 let ref mut a = item.1;
181 // Move all other multiline annotations overlapping with this one
182 // one level to the right.
183 if &ann != a &&
184 num_overlap(ann.line_start, ann.line_end, a.line_start, a.line_end, true)
185 {
186 a.increase_depth();
187 } else {
188 break;
189 }
190 }
191 }
192
193 let mut max_depth = 0; // max overlapping multiline spans
194 for (file, ann) in multiline_annotations {
195 if ann.depth > max_depth {
196 max_depth = ann.depth;
197 }
198 add_annotation_to_file(&mut output, file.clone(), ann.line_start, ann.as_start());
199 let middle = min(ann.line_start + 4, ann.line_end);
200 for line in ann.line_start + 1..middle {
201 add_annotation_to_file(&mut output, file.clone(), line, ann.as_line());
202 }
203 if middle < ann.line_end - 1 {
204 for line in ann.line_end - 1..ann.line_end {
205 add_annotation_to_file(&mut output, file.clone(), line, ann.as_line());
206 }
207 }
208 add_annotation_to_file(&mut output, file, ann.line_end, ann.as_end());
209 }
210 for file_vec in output.iter_mut() {
211 file_vec.multiline_depth = max_depth;
212 }
213 output
214 }
215
216 fn render_source_line(&self,
217 buffer: &mut StyledBuffer,
218 file: &File<T>,
219 line: &Line,
220 width_offset: usize,
221 code_offset: usize) -> Vec<(usize, Style)> {
222
223 let source_string = file.source_line(line.line_index);
224
225 let line_offset = buffer.num_lines();
226
227 // First create the source line we will highlight.
228 buffer.puts(line_offset, code_offset, &source_string, Style::Quotation);
229 buffer.puts(line_offset,
230 0,
231 &((line.line_index + 1).to_string()),
232 Style::LineNumber);
233
234 draw_col_separator(buffer, line_offset, width_offset - 2);
235
236 // Special case when there's only one annotation involved, it is the start of a multiline
237 // span and there's no text at the beginning of the code line. Instead of doing the whole
238 // graph:
239 //
240 // 2 | fn foo() {
241 // | _^
242 // 3 | |
243 // 4 | | }
244 // | |_^ test
245 //
246 // we simplify the output to:
247 //
248 // 2 | / fn foo() {
249 // 3 | |
250 // 4 | | }
251 // | |_^ test
252 if line.annotations.len() == 1 {
253 if let Some(ref ann) = line.annotations.get(0) {
254 if let AnnotationType::MultilineStart(depth) = ann.annotation_type {
255 if source_string.chars()
256 .take(ann.start_col)
257 .all(|c| c.is_whitespace()) {
258 let style = if ann.is_primary {
259 Style::UnderlinePrimary
260 } else {
261 Style::UnderlineSecondary
262 };
263 buffer.putc(line_offset,
264 width_offset + depth - 1,
265 '/',
266 style);
267 return vec![(depth, style)];
268 }
269 }
270 }
271 }
272
273 // We want to display like this:
274 //
275 // vec.push(vec.pop().unwrap());
276 // --- ^^^ - previous borrow ends here
277 // | |
278 // | error occurs here
279 // previous borrow of `vec` occurs here
280 //
281 // But there are some weird edge cases to be aware of:
282 //
283 // vec.push(vec.pop().unwrap());
284 // -------- - previous borrow ends here
285 // ||
286 // |this makes no sense
287 // previous borrow of `vec` occurs here
288 //
289 // For this reason, we group the lines into "highlight lines"
290 // and "annotations lines", where the highlight lines have the `^`.
291
292 // Sort the annotations by (start, end col)
293 // The labels are reversed, sort and then reversed again.
294 // Consider a list of annotations (A1, A2, C1, C2, B1, B2) where
295 // the letter signifies the span. Here we are only sorting by the
296 // span and hence, the order of the elements with the same span will
297 // not change. On reversing the ordering (|a, b| but b.cmp(a)), you get
298 // (C1, C2, B1, B2, A1, A2). All the elements with the same span are
299 // still ordered first to last, but all the elements with different
300 // spans are ordered by their spans in last to first order. Last to
301 // first order is important, because the jiggly lines and | are on
302 // the left, so the rightmost span needs to be rendered first,
303 // otherwise the lines would end up needing to go over a message.
304 let mut annotations = line.annotations.clone();
305 annotations.sort_by(|a,b| b.start_col.cmp(&a.start_col));
306
307 // First, figure out where each label will be positioned.
308 //
309 // In the case where you have the following annotations:
310 //
311 // vec.push(vec.pop().unwrap());
312 // -------- - previous borrow ends here [C]
313 // ||
314 // |this makes no sense [B]
315 // previous borrow of `vec` occurs here [A]
316 //
317 // `annotations_position` will hold [(2, A), (1, B), (0, C)].
318 //
319 // We try, when possible, to stick the rightmost annotation at the end
320 // of the highlight line:
321 //
322 // vec.push(vec.pop().unwrap());
323 // --- --- - previous borrow ends here
324 //
325 // But sometimes that's not possible because one of the other
326 // annotations overlaps it. For example, from the test
327 // `span_overlap_label`, we have the following annotations
328 // (written on distinct lines for clarity):
329 //
330 // fn foo(x: u32) {
331 // --------------
332 // -
333 //
334 // In this case, we can't stick the rightmost-most label on
335 // the highlight line, or we would get:
336 //
337 // fn foo(x: u32) {
338 // -------- x_span
339 // |
340 // fn_span
341 //
342 // which is totally weird. Instead we want:
343 //
344 // fn foo(x: u32) {
345 // --------------
346 // | |
347 // | x_span
348 // fn_span
349 //
350 // which is...less weird, at least. In fact, in general, if
351 // the rightmost span overlaps with any other span, we should
352 // use the "hang below" version, so we can at least make it
353 // clear where the span *starts*. There's an exception for this
354 // logic, when the labels do not have a message:
355 //
356 // fn foo(x: u32) {
357 // --------------
358 // |
359 // x_span
360 //
361 // instead of:
362 //
363 // fn foo(x: u32) {
364 // --------------
365 // | |
366 // | x_span
367 // <EMPTY LINE>
368 //
369 let mut annotations_position = vec![];
370 let mut line_len = 0;
371 let mut p = 0;
372 for (i, annotation) in annotations.iter().enumerate() {
373 for (j, next) in annotations.iter().enumerate() {
374 if overlaps(next, annotation, 0) // This label overlaps with another one and both
375 && annotation.has_label() // take space (they have text and are not
376 && j > i // multiline lines).
377 && p == 0 // We're currently on the first line, move the label one line down
378 {
379 // This annotation needs a new line in the output.
380 p += 1;
381 break;
382 }
383 }
384 annotations_position.push((p, annotation));
385 for (j, next) in annotations.iter().enumerate() {
386 if j > i {
387 let l = if let Some(ref label) = next.label {
388 label.len() + 2
389 } else {
390 0
391 };
392 if (overlaps(next, annotation, l) // Do not allow two labels to be in the same
393 // line if they overlap including padding, to
394 // avoid situations like:
395 //
396 // fn foo(x: u32) {
397 // -------^------
398 // | |
399 // fn_spanx_span
400 //
401 && annotation.has_label() // Both labels must have some text, otherwise
402 && next.has_label()) // they are not overlapping.
403 // Do not add a new line if this annotation
404 // or the next are vertical line placeholders.
405 || (annotation.takes_space() // If either this or the next annotation is
406 && next.has_label()) // multiline start/end, move it to a new line
407 || (annotation.has_label() // so as not to overlap the orizontal lines.
408 && next.takes_space())
409 || (annotation.takes_space() && next.takes_space())
410 || (overlaps(next, annotation, l)
411 && next.end_col <= annotation.end_col
412 && next.has_label()
413 && p == 0) // Avoid #42595.
414 {
415 // This annotation needs a new line in the output.
416 p += 1;
417 break;
418 }
419 }
420 }
421 if line_len < p {
422 line_len = p;
423 }
424 }
425
426 if line_len != 0 {
427 line_len += 1;
428 }
429
430 // If there are no annotations or the only annotations on this line are
431 // MultilineLine, then there's only code being shown, stop processing.
432 if line.annotations.is_empty() || line.annotations.iter()
433 .filter(|a| !a.is_line()).collect::<Vec<_>>().len() == 0
434 {
435 return vec![];
436 }
437
438 // Write the colunmn separator.
439 //
440 // After this we will have:
441 //
442 // 2 | fn foo() {
443 // |
444 // |
445 // |
446 // 3 |
447 // 4 | }
448 // |
449 for pos in 0..line_len + 1 {
450 draw_col_separator(buffer, line_offset + pos + 1, width_offset - 2);
451 buffer.putc(line_offset + pos + 1,
452 width_offset - 2,
453 '|',
454 Style::LineNumber);
455 }
456
457 // Write the horizontal lines for multiline annotations
458 // (only the first and last lines need this).
459 //
460 // After this we will have:
461 //
462 // 2 | fn foo() {
463 // | __________
464 // |
465 // |
466 // 3 |
467 // 4 | }
468 // | _
469 for &(pos, annotation) in &annotations_position {
470 let style = if annotation.is_primary {
471 Style::UnderlinePrimary
472 } else {
473 Style::UnderlineSecondary
474 };
475 let pos = pos + 1;
476 match annotation.annotation_type {
477 AnnotationType::MultilineStart(depth) |
478 AnnotationType::MultilineEnd(depth) => {
479 draw_range(buffer,
480 '_',
481 line_offset + pos,
482 width_offset + depth,
483 code_offset + annotation.start_col,
484 style);
485 }
486 _ => (),
487 }
488 }
489
490 // Write the vertical lines for labels that are on a different line as the underline.
491 //
492 // After this we will have:
493 //
494 // 2 | fn foo() {
495 // | __________
496 // | | |
497 // | |
498 // 3 |
499 // 4 | | }
500 // | |_
501 for &(pos, annotation) in &annotations_position {
502 let style = if annotation.is_primary {
503 Style::UnderlinePrimary
504 } else {
505 Style::UnderlineSecondary
506 };
507 let pos = pos + 1;
508
509 if pos > 1 && (annotation.has_label() || annotation.takes_space()) {
510 for p in line_offset + 1..line_offset + pos + 1 {
511 buffer.putc(p,
512 code_offset + annotation.start_col,
513 '|',
514 style);
515 }
516 }
517 match annotation.annotation_type {
518 AnnotationType::MultilineStart(depth) => {
519 for p in line_offset + pos + 1..line_offset + line_len + 2 {
520 buffer.putc(p,
521 width_offset + depth - 1,
522 '|',
523 style);
524 }
525 }
526 AnnotationType::MultilineEnd(depth) => {
527 for p in line_offset..line_offset + pos + 1 {
528 buffer.putc(p,
529 width_offset + depth - 1,
530 '|',
531 style);
532 }
533 }
534 _ => (),
535 }
536 }
537
538 // Write the labels on the annotations that actually have a label.
539 //
540 // After this we will have:
541 //
542 // 2 | fn foo() {
543 // | __________
544 // | |
545 // | something about `foo`
546 // 3 |
547 // 4 | }
548 // | _ test
549 for &(pos, annotation) in &annotations_position {
550 let style = if annotation.is_primary {
551 Style::LabelPrimary
552 } else {
553 Style::LabelSecondary
554 };
555 let (pos, col) = if pos == 0 {
556 (pos + 1, annotation.end_col + 1)
557 } else {
558 (pos + 2, annotation.start_col)
559 };
560 if let Some(ref label) = annotation.label {
561 buffer.puts(line_offset + pos,
562 code_offset + col,
563 &label,
564 style);
565 }
566 }
567
568 // Sort from biggest span to smallest span so that smaller spans are
569 // represented in the output:
570 //
571 // x | fn foo()
572 // | ^^^---^^
573 // | | |
574 // | | something about `foo`
575 // | something about `fn foo()`
576 annotations_position.sort_by(|a, b| {
577 // Decreasing order
578 a.1.len().cmp(&b.1.len()).reverse()
579 });
580
581 // Write the underlines.
582 //
583 // After this we will have:
584 //
585 // 2 | fn foo() {
586 // | ____-_____^
587 // | |
588 // | something about `foo`
589 // 3 |
590 // 4 | }
591 // | _^ test
592 for &(_, annotation) in &annotations_position {
593 let (underline, style) = if annotation.is_primary {
594 ('^', Style::UnderlinePrimary)
595 } else {
596 ('-', Style::UnderlineSecondary)
597 };
598 for p in annotation.start_col..annotation.end_col {
599 buffer.putc(line_offset + 1,
600 code_offset + p,
601 underline,
602 style);
603 }
604 }
605 annotations_position.iter().filter_map(|&(_, annotation)| {
606 match annotation.annotation_type {
607 AnnotationType::MultilineStart(p) | AnnotationType::MultilineEnd(p) => {
608 let style = if annotation.is_primary {
609 Style::LabelPrimary
610 } else {
611 Style::LabelSecondary
612 };
613 Some((p, style))
614 },
615 _ => None
616 }
617
618 }).collect::<Vec<_>>()
619 }
620
621 fn get_max_line_num(&mut self, diagnostics: &[Diagnostic]) -> usize {
622 if let Some(ref cm) = self.cm {
623 diagnostics.iter().map(|d| {
624 d.spans.iter().map(|span_label| {
625 cm.look_up_pos(span_label.span.high()).position.line
626 }).max().unwrap_or(0)
627 }).max().unwrap_or(0)
628 } else { 0 }
629 }
630
631 /// Add a left margin to every line but the first, given a padding length and the label being
632 /// displayed, keeping the provided highlighting.
633 fn msg_to_buffer(&self,
634 buffer: &mut StyledBuffer,
635 msg: &Vec<(String, Style)>,
636 padding: usize,
637 label: &str,
638 override_style: Option<Style>) {
639
640 // The extra 5 ` ` is padding that's always needed to align to the `note: `:
641 //
642 // error: message
643 // --> file.rs:13:20
644 // |
645 // 13 | <CODE>
646 // | ^^^^
647 // |
648 // = note: multiline
649 // message
650 // ++^^^----xx
651 // | | | |
652 // | | | magic `2`
653 // | | length of label
654 // | magic `3`
655 // `max_line_num_len`
656 let padding = (0..padding + label.len() + 5)
657 .map(|_| " ")
658 .collect::<String>();
659
660 /// Return wether `style`, or the override if present and the style is `NoStyle`.
661 fn style_or_override(style: Style, override_style: Option<Style>) -> Style {
662 if let Some(o) = override_style {
663 if style == Style::NoStyle {
664 return o;
665 }
666 }
667 style
668 }
669
670 let mut line_number = 0;
671
672 // Provided the following diagnostic message:
673 //
674 // let msg = vec![
675 // ("
676 // ("highlighted multiline\nstring to\nsee how it ", Style::NoStyle),
677 // ("looks", Style::Highlight),
678 // ("with\nvery ", Style::NoStyle),
679 // ("weird", Style::Highlight),
680 // (" formats\n", Style::NoStyle),
681 // ("see?", Style::Highlight),
682 // ];
683 //
684 // the expected output on a note is (* surround the highlighted text)
685 //
686 // = note: highlighted multiline
687 // string to
688 // see how it *looks* with
689 // very *weird* formats
690 // see?
691 for &(ref text, ref style) in msg.iter() {
692 let lines = text.split('\n').collect::<Vec<_>>();
693 if lines.len() > 1 {
694 for (i, line) in lines.iter().enumerate() {
695 if i != 0 {
696 line_number += 1;
697 buffer.append(line_number, &padding, Style::NoStyle);
698 }
699 buffer.append(line_number, line, style_or_override(*style, override_style));
700 }
701 } else {
702 buffer.append(line_number, text, style_or_override(*style, override_style));
703 }
704 }
705 }
706
707 fn emit_message_default(&mut self,
708 spans: &[SpanLabel],
709 msg: &Vec<(String, Style)>,
710 code: &Option<String>,
711 level: &Level,
712 max_line_num_len: usize,
713 is_secondary: bool)
714 -> io::Result<()> {
715 let mut buffer = StyledBuffer::new();
716
717 if is_secondary && spans.len() == 0 {
718 // This is a secondary message with no span info
719 for _ in 0..max_line_num_len {
720 buffer.prepend(0, " ", Style::NoStyle);
721 }
722 draw_note_separator(&mut buffer, 0, max_line_num_len + 1);
723 buffer.append(0, &level.to_string(), Style::HeaderMsg);
724 buffer.append(0, ": ", Style::NoStyle);
725 self.msg_to_buffer(&mut buffer, msg, max_line_num_len, "note", None);
726 } else {
727 buffer.append(0, &level.to_string(), Style::Level(level.clone()));
728 if let Some(code) = code.as_ref() {
729 buffer.append(0, "[", Style::Level(level.clone()));
730 buffer.append(0, &code, Style::Level(level.clone()));
731 buffer.append(0, "]", Style::Level(level.clone()));
732 }
733 buffer.append(0, ": ", Style::HeaderMsg);
734 for &(ref text, _) in msg.iter() {
735 buffer.append(0, text, Style::HeaderMsg);
736 }
737 }
738
739 // Preprocess all the annotations so that they are grouped by file and by line number
740 // This helps us quickly iterate over the whole message (including secondary file spans)
741 let mut annotated_files = Emitter::preprocess_annotations(self.cm, spans);
742
743 // Make sure our primary file comes first
744 let primary_lo = if let (Some(ref cm), Some(ref primary_span)) =
745 (self.cm.as_ref(), spans.iter().find(|x| x.style == SpanStyle::Primary)) {
746 cm.look_up_pos(primary_span.span.low())
747 } else {
748 // If we don't have span information, emit and exit
749 emit_to_destination(&buffer.render(), level, &mut self.dst)?;
750 return Ok(());
751 };
752 // get the index for
753 // let's see if not binary searching and instead searching for equality breaks things
754 if let Some(pos) = annotated_files.iter().position(|x| x.file.name() == primary_lo.file.name()) {
755 annotated_files.swap(0, pos);
756 }
757 // if let Ok(pos) =
758 // annotated_files.binary_search_by(|x| x.file.name().cmp(&primary_lo.file.name())) {
759 // annotated_files.swap(0, pos);
760 // }
761
762 // Print out the annotate source lines that correspond with the error
763 for annotated_file in annotated_files {
764 // print out the span location and spacer before we print the annotated source
765 // to do this, we need to know if this span will be primary
766 let is_primary = primary_lo.file.name() == annotated_file.file.name();
767 if is_primary {
768 // remember where we are in the output buffer for easy reference
769 let buffer_msg_line_offset = buffer.num_lines();
770
771 buffer.prepend(buffer_msg_line_offset, "--> ", Style::LineNumber);
772 let loc = primary_lo.clone();
773 buffer.append(buffer_msg_line_offset,
774 &format!("{}:{}:{}", loc.file.name(), loc.position.line + 1, loc.position.column + 1),
775 Style::LineAndColumn);
776 for _ in 0..max_line_num_len {
777 buffer.prepend(buffer_msg_line_offset, " ", Style::NoStyle);
778 }
779 } else {
780 // remember where we are in the output buffer for easy reference
781 let buffer_msg_line_offset = buffer.num_lines();
782
783 // Add spacing line
784 draw_col_separator(&mut buffer, buffer_msg_line_offset, max_line_num_len + 1);
785
786 // Then, the secondary file indicator
787 buffer.prepend(buffer_msg_line_offset + 1, "::: ", Style::LineNumber);
788 buffer.append(buffer_msg_line_offset + 1,
789 // TODO: maybe make it so it doesn't have to convert to string
790 &annotated_file.file.name().to_string(),
791 Style::LineAndColumn);
792 for _ in 0..max_line_num_len {
793 buffer.prepend(buffer_msg_line_offset + 1, " ", Style::NoStyle);
794 }
795 }
796
797 // Put in the spacer between the location and annotated source
798 let buffer_msg_line_offset = buffer.num_lines();
799 draw_col_separator_no_space(&mut buffer, buffer_msg_line_offset, max_line_num_len + 1);
800
801 // Contains the vertical lines' positions for active multiline annotations
802 let mut multilines = HashMap::new();
803
804 // Next, output the annotate source for this file
805 for line_idx in 0..annotated_file.lines.len() {
806 let previous_buffer_line = buffer.num_lines();
807
808 let width_offset = 3 + max_line_num_len;
809 let code_offset = if annotated_file.multiline_depth == 0 {
810 width_offset
811 } else {
812 width_offset + annotated_file.multiline_depth + 1
813 };
814
815 let depths = self.render_source_line(&mut buffer,
816 &annotated_file.file,
817 &annotated_file.lines[line_idx],
818 width_offset,
819 code_offset);
820
821 let mut to_add = HashMap::new();
822
823 for (depth, style) in depths {
824 if multilines.get(&depth).is_some() {
825 multilines.remove(&depth);
826 } else {
827 to_add.insert(depth, style);
828 }
829 }
830
831 // Set the multiline annotation vertical lines to the left of
832 // the code in this line.
833 for (depth, style) in &multilines {
834 for line in previous_buffer_line..buffer.num_lines() {
835 draw_multiline_line(&mut buffer,
836 line,
837 width_offset,
838 *depth,
839 *style);
840 }
841 }
842 // check to see if we need to print out or elide lines that come between
843 // this annotated line and the next one.
844 if line_idx < (annotated_file.lines.len() - 1) {
845 let line_idx_delta = annotated_file.lines[line_idx + 1].line_index -
846 annotated_file.lines[line_idx].line_index;
847 if line_idx_delta > 2 {
848 let last_buffer_line_num = buffer.num_lines();
849 buffer.puts(last_buffer_line_num, 0, "...", Style::LineNumber);
850
851 // Set the multiline annotation vertical lines on `...` bridging line.
852 for (depth, style) in &multilines {
853 draw_multiline_line(&mut buffer,
854 last_buffer_line_num,
855 width_offset,
856 *depth,
857 *style);
858 }
859 } else if line_idx_delta == 2 {
860 let unannotated_line = annotated_file.file
861 .source_line(annotated_file.lines[line_idx].line_index);
862
863 let last_buffer_line_num = buffer.num_lines();
864
865 buffer.puts(last_buffer_line_num,
866 0,
867 &(annotated_file.lines[line_idx + 1].line_index - 1)
868 .to_string(),
869 Style::LineNumber);
870 draw_col_separator(&mut buffer, last_buffer_line_num, 1 + max_line_num_len);
871 buffer.puts(last_buffer_line_num,
872 code_offset,
873 &unannotated_line,
874 Style::Quotation);
875
876 for (depth, style) in &multilines {
877 draw_multiline_line(&mut buffer,
878 last_buffer_line_num,
879 width_offset,
880 *depth,
881 *style);
882 }
883 }
884 }
885
886 multilines.extend(&to_add);
887 }
888 }
889
890 // final step: take our styled buffer, render it, then output it
891 emit_to_destination(&buffer.render(), level, &mut self.dst)?;
892
893 Ok(())
894 }
895
896 /// Print a group of diagnostic messages.
897 ///
898 /// The messages within a group are printed atomically without spacing between them, and share
899 /// consistent formatting elements, such as aligned line number width.
900 pub fn emit(&mut self, msgs: &[Diagnostic]) {
901 let max_line_num = self.get_max_line_num(msgs) + 1;
902 let max_line_num_len = max_line_num.to_string().len();
903
904 for msg in msgs {
905 match self.emit_message_default(&msg.spans[..], &vec![(msg.message.clone(), Style::NoStyle)], &msg.code, &msg.level, max_line_num_len, false) {
906 Ok(()) => (),
907 Err(e) => panic!("failed to emit error: {}", e)
908 }
909 }
910
911 let mut dst = self.dst.writable();
912 match write!(dst, "\n") {
913 Err(e) => panic!("failed to emit error: {}", e),
914 _ => {
915 match dst.flush() {
916 Err(e) => panic!("failed to emit error: {}", e),
917 _ => (),
918 }
919 }
920 }
921 }
922}
923
924
925fn draw_col_separator(buffer: &mut StyledBuffer, line: usize, col: usize) {
926 buffer.puts(line, col, "| ", Style::LineNumber);
927}
928
929fn draw_col_separator_no_space(buffer: &mut StyledBuffer, line: usize, col: usize) {
930 draw_col_separator_no_space_with_style(buffer, line, col, Style::LineNumber);
931}
932
933fn draw_col_separator_no_space_with_style(buffer: &mut StyledBuffer,
934 line: usize,
935 col: usize,
936 style: Style) {
937 buffer.putc(line, col, '|', style);
938}
939
940fn draw_range(buffer: &mut StyledBuffer, symbol: char, line: usize,
941 col_from: usize, col_to: usize, style: Style) {
942 for col in col_from..col_to {
943 buffer.putc(line, col, symbol, style);
944 }
945}
946
947fn draw_note_separator(buffer: &mut StyledBuffer, line: usize, col: usize) {
948 buffer.puts(line, col, "= ", Style::LineNumber);
949}
950
951fn draw_multiline_line(buffer: &mut StyledBuffer,
952 line: usize,
953 offset: usize,
954 depth: usize,
955 style: Style)
956{
957 buffer.putc(line, offset + depth - 1, '|', style);
958}
959
960fn num_overlap(a_start: usize, a_end: usize, b_start: usize, b_end:usize, inclusive: bool) -> bool {
961 let extra = if inclusive {
962 1
963 } else {
964 0
965 };
966
967 (a_start >= b_start && a_start < b_end + extra)
968 || (b_start >= a_start && b_start < a_end + extra)
969}
970fn overlaps(a1: &Annotation, a2: &Annotation, padding: usize) -> bool {
971 num_overlap(a1.start_col, a1.end_col + padding, a2.start_col, a2.end_col, false)
972}
973
974fn emit_to_destination(rendered_buffer: &Vec<Vec<StyledString>>,
975 lvl: &Level,
976 dst: &mut Destination)
977 -> io::Result<()> {
978 use lock;
979
980 let mut dst = dst.writable();
981
982 // In order to prevent error message interleaving, where multiple error lines get intermixed
983 // when multiple compiler processes error simultaneously, we emit errors with additional
984 // steps.
985 //
986 // On Unix systems, we write into a buffered terminal rather than directly to a terminal. When
987 // the .flush() is called we take the buffer created from the buffered writes and write it at
988 // one shot. Because the Unix systems use ANSI for the colors, which is a text-based styling
989 // scheme, this buffered approach works and maintains the styling.
990 //
991 // On Windows, styling happens through calls to a terminal API. This prevents us from using the
992 // same buffering approach. Instead, we use a global Windows mutex, which we acquire long
993 // enough to output the full error message, then we release.
994 let _buffer_lock = lock::acquire_global_lock("rustc_errors");
995 for line in rendered_buffer {
996 for part in line {
997 dst.apply_style(lvl.clone(), part.style)?;
998 write!(dst, "{}", part.text)?;
999 dst.reset()?;
1000 }
1001 write!(dst, "\n")?;
1002 }
1003 dst.flush()?;
1004 Ok(())
1005}
1006
1007#[allow(dead_code)]
1008enum Destination<'a> {
1009 Terminal(StandardStream),
1010 Buffered(BufferWriter),
1011 Raw(Box<dyn Write + Send + 'a>),
1012}
1013
1014use self::Destination::*;
1015
1016enum WritableDst<'a, 'b> {
1017 Terminal(&'b mut StandardStream),
1018 Buffered(&'b mut BufferWriter, Buffer),
1019 Raw(&'b mut Box<dyn Write + Send + 'a>),
1020}
1021
1022impl<'a> Destination<'a> {
1023 fn from_stderr(color: ColorConfig) -> Destination<'a> {
1024 let choice = color.to_color_choice();
1025 // On Windows we'll be performing global synchronization on the entire
1026 // system for emitting rustc errors, so there's no need to buffer
1027 // anything.
1028 //
1029 // On non-Windows we rely on the atomicity of `write` to ensure errors
1030 // don't get all jumbled up.
1031 if cfg!(windows) {
1032 Destination::Terminal(StandardStream::stderr(choice))
1033 } else {
1034 Destination::Buffered(BufferWriter::stderr(choice))
1035 }
1036 }
1037
1038 fn writable<'b>(&'b mut self) -> WritableDst<'a, 'b> {
1039 match *self {
1040 Destination::Terminal(ref mut t) => WritableDst::Terminal(t),
1041 Destination::Buffered(ref mut t) => {
1042 let buf = t.buffer();
1043 WritableDst::Buffered(t, buf)
1044 }
1045 Destination::Raw(ref mut t) => WritableDst::Raw(t),
1046 }
1047 }
1048}
1049
1050impl<'a, 'b> WritableDst<'a, 'b> {
1051 fn apply_style(&mut self, lvl: Level, style: Style) -> io::Result<()> {
1052 let mut spec = ColorSpec::new();
1053 match style {
1054 Style::LineAndColumn => {}
1055 Style::LineNumber => {
1056 spec.set_bold(true);
1057 spec.set_intense(true);
1058 if cfg!(windows) {
1059 spec.set_fg(Some(Color::Cyan));
1060 } else {
1061 spec.set_fg(Some(Color::Blue));
1062 }
1063 }
1064 Style::Quotation => {}
1065 Style::HeaderMsg => {
1066 spec.set_bold(true);
1067 if cfg!(windows) {
1068 spec.set_intense(true)
1069 .set_fg(Some(Color::White));
1070 }
1071 }
1072 Style::UnderlinePrimary | Style::LabelPrimary => {
1073 spec = lvl.color();
1074 spec.set_bold(true);
1075 }
1076 Style::UnderlineSecondary |
1077 Style::LabelSecondary => {
1078 spec.set_bold(true)
1079 .set_intense(true);
1080 if cfg!(windows) {
1081 spec.set_fg(Some(Color::Cyan));
1082 } else {
1083 spec.set_fg(Some(Color::Blue));
1084 }
1085 }
1086 Style::NoStyle => {}
1087 Style::Level(lvl) => {
1088 spec = lvl.color();
1089 spec.set_bold(true);
1090 }
1091 Style::Highlight => {
1092 spec.set_bold(true);
1093 }
1094 }
1095 self.set_color(&spec)
1096 }
1097
1098 fn set_color(&mut self, color: &ColorSpec) -> io::Result<()> {
1099 match *self {
1100 WritableDst::Terminal(ref mut t) => t.set_color(color),
1101 WritableDst::Buffered(_, ref mut t) => t.set_color(color),
1102 WritableDst::Raw(_) => Ok(())
1103 }
1104 }
1105
1106 fn reset(&mut self) -> io::Result<()> {
1107 match *self {
1108 WritableDst::Terminal(ref mut t) => t.reset(),
1109 WritableDst::Buffered(_, ref mut t) => t.reset(),
1110 WritableDst::Raw(_) => Ok(()),
1111 }
1112 }
1113}
1114
1115impl<'a, 'b> Write for WritableDst<'a, 'b> {
1116 fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
1117 match *self {
1118 WritableDst::Terminal(ref mut t) => t.write(bytes),
1119 WritableDst::Buffered(_, ref mut buf) => buf.write(bytes),
1120 WritableDst::Raw(ref mut w) => w.write(bytes),
1121 }
1122 }
1123
1124 fn flush(&mut self) -> io::Result<()> {
1125 match *self {
1126 WritableDst::Terminal(ref mut t) => t.flush(),
1127 WritableDst::Buffered(_, ref mut buf) => buf.flush(),
1128 WritableDst::Raw(ref mut w) => w.flush(),
1129 }
1130 }
1131}
1132
1133impl<'a, 'b> Drop for WritableDst<'a, 'b> {
1134 fn drop(&mut self) {
1135 match *self {
1136 WritableDst::Buffered(ref mut dst, ref mut buf) => {
1137 drop(dst.print(buf));
1138 }
1139 _ => {}
1140 }
1141 }
1142}