]> git.proxmox.com Git - rustc.git/blob - src/librustc_errors/emitter.rs
New upstream version 1.37.0+dfsg1
[rustc.git] / src / librustc_errors / emitter.rs
1 //! The current rustc diagnostics emitter.
2 //!
3 //! An `Emitter` takes care of generating the output from a `DiagnosticBuilder` struct.
4 //!
5 //! There are various `Emitter` implementations that generate different output formats such as
6 //! JSON and human readable output.
7 //!
8 //! The output types are defined in `librustc::session::config::ErrorOutputType`.
9
10 use Destination::*;
11
12 use syntax_pos::{SourceFile, Span, MultiSpan};
13
14 use crate::{
15 Level, CodeSuggestion, DiagnosticBuilder, SubDiagnostic,
16 SuggestionStyle, SourceMapperDyn, DiagnosticId,
17 };
18 use crate::Level::Error;
19 use crate::snippet::{Annotation, AnnotationType, Line, MultilineAnnotation, StyledString, Style};
20 use crate::styled_buffer::StyledBuffer;
21
22 use rustc_data_structures::fx::FxHashMap;
23 use rustc_data_structures::sync::Lrc;
24 use std::borrow::Cow;
25 use std::io::prelude::*;
26 use std::io;
27 use std::cmp::{min, Reverse};
28 use std::path::Path;
29 use termcolor::{StandardStream, ColorChoice, ColorSpec, BufferWriter, Ansi};
30 use termcolor::{WriteColor, Color, Buffer};
31
32 /// Describes the way the content of the `rendered` field of the json output is generated
33 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
34 pub enum HumanReadableErrorType {
35 Default(ColorConfig),
36 AnnotateSnippet(ColorConfig),
37 Short(ColorConfig),
38 }
39
40 impl HumanReadableErrorType {
41 /// Returns a (`short`, `color`) tuple
42 pub fn unzip(self) -> (bool, ColorConfig) {
43 match self {
44 HumanReadableErrorType::Default(cc) => (false, cc),
45 HumanReadableErrorType::Short(cc) => (true, cc),
46 HumanReadableErrorType::AnnotateSnippet(cc) => (false, cc),
47 }
48 }
49 pub fn new_emitter(
50 self,
51 dst: Box<dyn Write + Send>,
52 source_map: Option<Lrc<SourceMapperDyn>>,
53 teach: bool,
54 ) -> EmitterWriter {
55 let (short, color_config) = self.unzip();
56 EmitterWriter::new(dst, source_map, short, teach, color_config.suggests_using_colors())
57 }
58 }
59
60 const ANONYMIZED_LINE_NUM: &str = "LL";
61
62 /// Emitter trait for emitting errors.
63 pub trait Emitter {
64 /// Emit a structured diagnostic.
65 fn emit_diagnostic(&mut self, db: &DiagnosticBuilder<'_>);
66
67 /// Emit a notification that an artifact has been output.
68 /// This is currently only supported for the JSON format,
69 /// other formats can, and will, simply ignore it.
70 fn emit_artifact_notification(&mut self, _path: &Path, _artifact_type: &str) {}
71
72 /// Checks if should show explanations about "rustc --explain"
73 fn should_show_explain(&self) -> bool {
74 true
75 }
76 }
77
78 impl Emitter for EmitterWriter {
79 fn emit_diagnostic(&mut self, db: &DiagnosticBuilder<'_>) {
80 let mut primary_span = db.span.clone();
81 let mut children = db.children.clone();
82 let mut suggestions: &[_] = &[];
83
84 if let Some((sugg, rest)) = db.suggestions.split_first() {
85 if rest.is_empty() &&
86 // don't display multi-suggestions as labels
87 sugg.substitutions.len() == 1 &&
88 // don't display multipart suggestions as labels
89 sugg.substitutions[0].parts.len() == 1 &&
90 // don't display long messages as labels
91 sugg.msg.split_whitespace().count() < 10 &&
92 // don't display multiline suggestions as labels
93 !sugg.substitutions[0].parts[0].snippet.contains('\n') &&
94 // when this style is set we want the suggestion to be a message, not inline
95 sugg.style != SuggestionStyle::HideCodeAlways &&
96 // trivial suggestion for tooling's sake, never shown
97 sugg.style != SuggestionStyle::CompletelyHidden
98 {
99 let substitution = &sugg.substitutions[0].parts[0].snippet.trim();
100 let msg = if substitution.len() == 0 || sugg.style.hide_inline() {
101 // This substitution is only removal or we explicitly don't want to show the
102 // code inline, don't show it
103 format!("help: {}", sugg.msg)
104 } else {
105 format!("help: {}: `{}`", sugg.msg, substitution)
106 };
107 primary_span.push_span_label(sugg.substitutions[0].parts[0].span, msg);
108 } else {
109 // if there are multiple suggestions, print them all in full
110 // to be consistent. We could try to figure out if we can
111 // make one (or the first one) inline, but that would give
112 // undue importance to a semi-random suggestion
113 suggestions = &db.suggestions;
114 }
115 }
116
117 self.fix_multispans_in_std_macros(&mut primary_span,
118 &mut children,
119 &db.level,
120 db.handler.flags.external_macro_backtrace);
121
122 self.emit_messages_default(&db.level,
123 &db.styled_message(),
124 &db.code,
125 &primary_span,
126 &children,
127 &suggestions);
128 }
129
130 fn should_show_explain(&self) -> bool {
131 !self.short_message
132 }
133 }
134
135 /// maximum number of lines we will print for each error; arbitrary.
136 pub const MAX_HIGHLIGHT_LINES: usize = 6;
137 /// maximum number of suggestions to be shown
138 ///
139 /// Arbitrary, but taken from trait import suggestion limit
140 pub const MAX_SUGGESTIONS: usize = 4;
141
142 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
143 pub enum ColorConfig {
144 Auto,
145 Always,
146 Never,
147 }
148
149 impl ColorConfig {
150 fn to_color_choice(self) -> ColorChoice {
151 match self {
152 ColorConfig::Always => {
153 if atty::is(atty::Stream::Stderr) {
154 ColorChoice::Always
155 } else {
156 ColorChoice::AlwaysAnsi
157 }
158 }
159 ColorConfig::Never => ColorChoice::Never,
160 ColorConfig::Auto if atty::is(atty::Stream::Stderr) => {
161 ColorChoice::Auto
162 }
163 ColorConfig::Auto => ColorChoice::Never,
164 }
165 }
166 fn suggests_using_colors(self) -> bool {
167 match self {
168 | ColorConfig::Always
169 | ColorConfig::Auto
170 => true,
171 ColorConfig::Never => false,
172 }
173 }
174 }
175
176 /// Handles the writing of `HumanReadableErrorType::Default` and `HumanReadableErrorType::Short`
177 pub struct EmitterWriter {
178 dst: Destination,
179 sm: Option<Lrc<SourceMapperDyn>>,
180 short_message: bool,
181 teach: bool,
182 ui_testing: bool,
183 }
184
185 #[derive(Debug)]
186 pub struct FileWithAnnotatedLines {
187 pub file: Lrc<SourceFile>,
188 pub lines: Vec<Line>,
189 multiline_depth: usize,
190 }
191
192 impl EmitterWriter {
193 pub fn stderr(color_config: ColorConfig,
194 source_map: Option<Lrc<SourceMapperDyn>>,
195 short_message: bool,
196 teach: bool)
197 -> EmitterWriter {
198 let dst = Destination::from_stderr(color_config);
199 EmitterWriter {
200 dst,
201 sm: source_map,
202 short_message,
203 teach,
204 ui_testing: false,
205 }
206 }
207
208 pub fn new(
209 dst: Box<dyn Write + Send>,
210 source_map: Option<Lrc<SourceMapperDyn>>,
211 short_message: bool,
212 teach: bool,
213 colored: bool,
214 ) -> EmitterWriter {
215 EmitterWriter {
216 dst: Raw(dst, colored),
217 sm: source_map,
218 short_message,
219 teach,
220 ui_testing: false,
221 }
222 }
223
224 pub fn ui_testing(mut self, ui_testing: bool) -> Self {
225 self.ui_testing = ui_testing;
226 self
227 }
228
229 fn maybe_anonymized(&self, line_num: usize) -> String {
230 if self.ui_testing {
231 ANONYMIZED_LINE_NUM.to_string()
232 } else {
233 line_num.to_string()
234 }
235 }
236
237 fn render_source_line(&self,
238 buffer: &mut StyledBuffer,
239 file: Lrc<SourceFile>,
240 line: &Line,
241 width_offset: usize,
242 code_offset: usize) -> Vec<(usize, Style)> {
243 if line.line_index == 0 {
244 return Vec::new();
245 }
246
247 let source_string = match file.get_line(line.line_index - 1) {
248 Some(s) => s,
249 None => return Vec::new(),
250 };
251
252 let line_offset = buffer.num_lines();
253
254 // First create the source line we will highlight.
255 buffer.puts(line_offset, code_offset, &source_string, Style::Quotation);
256 buffer.puts(line_offset,
257 0,
258 &self.maybe_anonymized(line.line_index),
259 Style::LineNumber);
260
261 draw_col_separator(buffer, line_offset, width_offset - 2);
262
263 // Special case when there's only one annotation involved, it is the start of a multiline
264 // span and there's no text at the beginning of the code line. Instead of doing the whole
265 // graph:
266 //
267 // 2 | fn foo() {
268 // | _^
269 // 3 | |
270 // 4 | | }
271 // | |_^ test
272 //
273 // we simplify the output to:
274 //
275 // 2 | / fn foo() {
276 // 3 | |
277 // 4 | | }
278 // | |_^ test
279 if line.annotations.len() == 1 {
280 if let Some(ref ann) = line.annotations.get(0) {
281 if let AnnotationType::MultilineStart(depth) = ann.annotation_type {
282 if source_string.chars()
283 .take(ann.start_col)
284 .all(|c| c.is_whitespace()) {
285 let style = if ann.is_primary {
286 Style::UnderlinePrimary
287 } else {
288 Style::UnderlineSecondary
289 };
290 buffer.putc(line_offset,
291 width_offset + depth - 1,
292 '/',
293 style);
294 return vec![(depth, style)];
295 }
296 }
297 }
298 }
299
300 // We want to display like this:
301 //
302 // vec.push(vec.pop().unwrap());
303 // --- ^^^ - previous borrow ends here
304 // | |
305 // | error occurs here
306 // previous borrow of `vec` occurs here
307 //
308 // But there are some weird edge cases to be aware of:
309 //
310 // vec.push(vec.pop().unwrap());
311 // -------- - previous borrow ends here
312 // ||
313 // |this makes no sense
314 // previous borrow of `vec` occurs here
315 //
316 // For this reason, we group the lines into "highlight lines"
317 // and "annotations lines", where the highlight lines have the `^`.
318
319 // Sort the annotations by (start, end col)
320 // The labels are reversed, sort and then reversed again.
321 // Consider a list of annotations (A1, A2, C1, C2, B1, B2) where
322 // the letter signifies the span. Here we are only sorting by the
323 // span and hence, the order of the elements with the same span will
324 // not change. On reversing the ordering (|a, b| but b.cmp(a)), you get
325 // (C1, C2, B1, B2, A1, A2). All the elements with the same span are
326 // still ordered first to last, but all the elements with different
327 // spans are ordered by their spans in last to first order. Last to
328 // first order is important, because the jiggly lines and | are on
329 // the left, so the rightmost span needs to be rendered first,
330 // otherwise the lines would end up needing to go over a message.
331
332 let mut annotations = line.annotations.clone();
333 annotations.sort_by_key(|a| Reverse(a.start_col));
334
335 // First, figure out where each label will be positioned.
336 //
337 // In the case where you have the following annotations:
338 //
339 // vec.push(vec.pop().unwrap());
340 // -------- - previous borrow ends here [C]
341 // ||
342 // |this makes no sense [B]
343 // previous borrow of `vec` occurs here [A]
344 //
345 // `annotations_position` will hold [(2, A), (1, B), (0, C)].
346 //
347 // We try, when possible, to stick the rightmost annotation at the end
348 // of the highlight line:
349 //
350 // vec.push(vec.pop().unwrap());
351 // --- --- - previous borrow ends here
352 //
353 // But sometimes that's not possible because one of the other
354 // annotations overlaps it. For example, from the test
355 // `span_overlap_label`, we have the following annotations
356 // (written on distinct lines for clarity):
357 //
358 // fn foo(x: u32) {
359 // --------------
360 // -
361 //
362 // In this case, we can't stick the rightmost-most label on
363 // the highlight line, or we would get:
364 //
365 // fn foo(x: u32) {
366 // -------- x_span
367 // |
368 // fn_span
369 //
370 // which is totally weird. Instead we want:
371 //
372 // fn foo(x: u32) {
373 // --------------
374 // | |
375 // | x_span
376 // fn_span
377 //
378 // which is...less weird, at least. In fact, in general, if
379 // the rightmost span overlaps with any other span, we should
380 // use the "hang below" version, so we can at least make it
381 // clear where the span *starts*. There's an exception for this
382 // logic, when the labels do not have a message:
383 //
384 // fn foo(x: u32) {
385 // --------------
386 // |
387 // x_span
388 //
389 // instead of:
390 //
391 // fn foo(x: u32) {
392 // --------------
393 // | |
394 // | x_span
395 // <EMPTY LINE>
396 //
397 let mut annotations_position = vec![];
398 let mut line_len = 0;
399 let mut p = 0;
400 for (i, annotation) in annotations.iter().enumerate() {
401 for (j, next) in annotations.iter().enumerate() {
402 if overlaps(next, annotation, 0) // This label overlaps with another one and both
403 && annotation.has_label() // take space (they have text and are not
404 && j > i // multiline lines).
405 && p == 0 // We're currently on the first line, move the label one line down
406 {
407 // If we're overlapping with an un-labelled annotation with the same span
408 // we can just merge them in the output
409 if next.start_col == annotation.start_col
410 && next.end_col == annotation.end_col
411 && !next.has_label()
412 {
413 continue;
414 }
415
416 // This annotation needs a new line in the output.
417 p += 1;
418 break;
419 }
420 }
421 annotations_position.push((p, annotation));
422 for (j, next) in annotations.iter().enumerate() {
423 if j > i {
424 let l = if let Some(ref label) = next.label {
425 label.len() + 2
426 } else {
427 0
428 };
429 if (overlaps(next, annotation, l) // Do not allow two labels to be in the same
430 // line if they overlap including padding, to
431 // avoid situations like:
432 //
433 // fn foo(x: u32) {
434 // -------^------
435 // | |
436 // fn_spanx_span
437 //
438 && annotation.has_label() // Both labels must have some text, otherwise
439 && next.has_label()) // they are not overlapping.
440 // Do not add a new line if this annotation
441 // or the next are vertical line placeholders.
442 || (annotation.takes_space() // If either this or the next annotation is
443 && next.has_label()) // multiline start/end, move it to a new line
444 || (annotation.has_label() // so as not to overlap the orizontal lines.
445 && next.takes_space())
446 || (annotation.takes_space() && next.takes_space())
447 || (overlaps(next, annotation, l)
448 && next.end_col <= annotation.end_col
449 && next.has_label()
450 && p == 0) // Avoid #42595.
451 {
452 // This annotation needs a new line in the output.
453 p += 1;
454 break;
455 }
456 }
457 }
458 if line_len < p {
459 line_len = p;
460 }
461 }
462
463 if line_len != 0 {
464 line_len += 1;
465 }
466
467 // If there are no annotations or the only annotations on this line are
468 // MultilineLine, then there's only code being shown, stop processing.
469 if line.annotations.iter().all(|a| a.is_line()) {
470 return vec![];
471 }
472
473 // Write the colunmn separator.
474 //
475 // After this we will have:
476 //
477 // 2 | fn foo() {
478 // |
479 // |
480 // |
481 // 3 |
482 // 4 | }
483 // |
484 for pos in 0..=line_len {
485 draw_col_separator(buffer, line_offset + pos + 1, width_offset - 2);
486 buffer.putc(line_offset + pos + 1,
487 width_offset - 2,
488 '|',
489 Style::LineNumber);
490 }
491
492 // Write the horizontal lines for multiline annotations
493 // (only the first and last lines need this).
494 //
495 // After this we will have:
496 //
497 // 2 | fn foo() {
498 // | __________
499 // |
500 // |
501 // 3 |
502 // 4 | }
503 // | _
504 for &(pos, annotation) in &annotations_position {
505 let style = if annotation.is_primary {
506 Style::UnderlinePrimary
507 } else {
508 Style::UnderlineSecondary
509 };
510 let pos = pos + 1;
511 match annotation.annotation_type {
512 AnnotationType::MultilineStart(depth) |
513 AnnotationType::MultilineEnd(depth) => {
514 draw_range(buffer,
515 '_',
516 line_offset + pos,
517 width_offset + depth,
518 code_offset + annotation.start_col,
519 style);
520 }
521 _ if self.teach => {
522 buffer.set_style_range(line_offset,
523 code_offset + annotation.start_col,
524 code_offset + annotation.end_col,
525 style,
526 annotation.is_primary);
527 }
528 _ => {}
529 }
530 }
531
532 // Write the vertical lines for labels that are on a different line as the underline.
533 //
534 // After this we will have:
535 //
536 // 2 | fn foo() {
537 // | __________
538 // | | |
539 // | |
540 // 3 |
541 // 4 | | }
542 // | |_
543 for &(pos, annotation) in &annotations_position {
544 let style = if annotation.is_primary {
545 Style::UnderlinePrimary
546 } else {
547 Style::UnderlineSecondary
548 };
549 let pos = pos + 1;
550
551 if pos > 1 && (annotation.has_label() || annotation.takes_space()) {
552 for p in line_offset + 1..=line_offset + pos {
553 buffer.putc(p,
554 code_offset + annotation.start_col,
555 '|',
556 style);
557 }
558 }
559 match annotation.annotation_type {
560 AnnotationType::MultilineStart(depth) => {
561 for p in line_offset + pos + 1..line_offset + line_len + 2 {
562 buffer.putc(p,
563 width_offset + depth - 1,
564 '|',
565 style);
566 }
567 }
568 AnnotationType::MultilineEnd(depth) => {
569 for p in line_offset..=line_offset + pos {
570 buffer.putc(p,
571 width_offset + depth - 1,
572 '|',
573 style);
574 }
575 }
576 _ => (),
577 }
578 }
579
580 // Write the labels on the annotations that actually have a label.
581 //
582 // After this we will have:
583 //
584 // 2 | fn foo() {
585 // | __________
586 // | |
587 // | something about `foo`
588 // 3 |
589 // 4 | }
590 // | _ test
591 for &(pos, annotation) in &annotations_position {
592 let style = if annotation.is_primary {
593 Style::LabelPrimary
594 } else {
595 Style::LabelSecondary
596 };
597 let (pos, col) = if pos == 0 {
598 (pos + 1, annotation.end_col + 1)
599 } else {
600 (pos + 2, annotation.start_col)
601 };
602 if let Some(ref label) = annotation.label {
603 buffer.puts(line_offset + pos,
604 code_offset + col,
605 &label,
606 style);
607 }
608 }
609
610 // Sort from biggest span to smallest span so that smaller spans are
611 // represented in the output:
612 //
613 // x | fn foo()
614 // | ^^^---^^
615 // | | |
616 // | | something about `foo`
617 // | something about `fn foo()`
618 annotations_position.sort_by(|a, b| {
619 // Decreasing order. When `a` and `b` are the same length, prefer `Primary`.
620 (a.1.len(), !a.1.is_primary).cmp(&(b.1.len(), !b.1.is_primary)).reverse()
621 });
622
623 // Write the underlines.
624 //
625 // After this we will have:
626 //
627 // 2 | fn foo() {
628 // | ____-_____^
629 // | |
630 // | something about `foo`
631 // 3 |
632 // 4 | }
633 // | _^ test
634 for &(_, annotation) in &annotations_position {
635 let (underline, style) = if annotation.is_primary {
636 ('^', Style::UnderlinePrimary)
637 } else {
638 ('-', Style::UnderlineSecondary)
639 };
640 for p in annotation.start_col..annotation.end_col {
641 buffer.putc(line_offset + 1,
642 code_offset + p,
643 underline,
644 style);
645 }
646 }
647 annotations_position.iter().filter_map(|&(_, annotation)| {
648 match annotation.annotation_type {
649 AnnotationType::MultilineStart(p) | AnnotationType::MultilineEnd(p) => {
650 let style = if annotation.is_primary {
651 Style::LabelPrimary
652 } else {
653 Style::LabelSecondary
654 };
655 Some((p, style))
656 }
657 _ => None
658 }
659
660 }).collect::<Vec<_>>()
661 }
662
663 fn get_multispan_max_line_num(&mut self, msp: &MultiSpan) -> usize {
664 let mut max = 0;
665 if let Some(ref sm) = self.sm {
666 for primary_span in msp.primary_spans() {
667 if !primary_span.is_dummy() {
668 let hi = sm.lookup_char_pos(primary_span.hi());
669 if hi.line > max {
670 max = hi.line;
671 }
672 }
673 }
674 if !self.short_message {
675 for span_label in msp.span_labels() {
676 if !span_label.span.is_dummy() {
677 let hi = sm.lookup_char_pos(span_label.span.hi());
678 if hi.line > max {
679 max = hi.line;
680 }
681 }
682 }
683 }
684 }
685 max
686 }
687
688 fn get_max_line_num(&mut self, span: &MultiSpan, children: &[SubDiagnostic]) -> usize {
689 let mut max = 0;
690
691 let primary = self.get_multispan_max_line_num(span);
692 max = if primary > max { primary } else { max };
693
694 for sub in children {
695 let sub_result = self.get_multispan_max_line_num(&sub.span);
696 max = if sub_result > max { primary } else { max };
697 }
698 max
699 }
700
701 // This "fixes" MultiSpans that contain Spans that are pointing to locations inside of
702 // <*macros>. Since these locations are often difficult to read, we move these Spans from
703 // <*macros> to their corresponding use site.
704 fn fix_multispan_in_std_macros(&mut self,
705 span: &mut MultiSpan,
706 always_backtrace: bool) -> bool {
707 let mut spans_updated = false;
708
709 if let Some(ref sm) = self.sm {
710 let mut before_after: Vec<(Span, Span)> = vec![];
711 let mut new_labels: Vec<(Span, String)> = vec![];
712
713 // First, find all the spans in <*macros> and point instead at their use site
714 for sp in span.primary_spans() {
715 if sp.is_dummy() {
716 continue;
717 }
718 let call_sp = sm.call_span_if_macro(*sp);
719 if call_sp != *sp && !always_backtrace {
720 before_after.push((*sp, call_sp));
721 }
722 let backtrace_len = sp.macro_backtrace().len();
723 for (i, trace) in sp.macro_backtrace().iter().rev().enumerate() {
724 // Only show macro locations that are local
725 // and display them like a span_note
726 if let Some(def_site) = trace.def_site_span {
727 if def_site.is_dummy() {
728 continue;
729 }
730 if always_backtrace {
731 new_labels.push((def_site,
732 format!("in this expansion of `{}`{}",
733 trace.macro_decl_name,
734 if backtrace_len > 2 {
735 // if backtrace_len == 1 it'll be pointed
736 // at by "in this macro invocation"
737 format!(" (#{})", i + 1)
738 } else {
739 String::new()
740 })));
741 }
742 // Check to make sure we're not in any <*macros>
743 if !sm.span_to_filename(def_site).is_macros() &&
744 !trace.macro_decl_name.starts_with("desugaring of ") &&
745 !trace.macro_decl_name.starts_with("#[") ||
746 always_backtrace {
747 new_labels.push((trace.call_site,
748 format!("in this macro invocation{}",
749 if backtrace_len > 2 && always_backtrace {
750 // only specify order when the macro
751 // backtrace is multiple levels deep
752 format!(" (#{})", i + 1)
753 } else {
754 String::new()
755 })));
756 if !always_backtrace {
757 break;
758 }
759 }
760 }
761 }
762 }
763 for (label_span, label_text) in new_labels {
764 span.push_span_label(label_span, label_text);
765 }
766 for sp_label in span.span_labels() {
767 if sp_label.span.is_dummy() {
768 continue;
769 }
770 if sm.span_to_filename(sp_label.span.clone()).is_macros() &&
771 !always_backtrace
772 {
773 let v = sp_label.span.macro_backtrace();
774 if let Some(use_site) = v.last() {
775 before_after.push((sp_label.span.clone(), use_site.call_site.clone()));
776 }
777 }
778 }
779 // After we have them, make sure we replace these 'bad' def sites with their use sites
780 for (before, after) in before_after {
781 span.replace(before, after);
782 spans_updated = true;
783 }
784 }
785
786 spans_updated
787 }
788
789 // This does a small "fix" for multispans by looking to see if it can find any that
790 // point directly at <*macros>. Since these are often difficult to read, this
791 // will change the span to point at the use site.
792 fn fix_multispans_in_std_macros(&mut self,
793 span: &mut MultiSpan,
794 children: &mut Vec<SubDiagnostic>,
795 level: &Level,
796 backtrace: bool) {
797 let mut spans_updated = self.fix_multispan_in_std_macros(span, backtrace);
798 for child in children.iter_mut() {
799 spans_updated |= self.fix_multispan_in_std_macros(&mut child.span, backtrace);
800 }
801 let msg = if level == &Error {
802 "this error originates in a macro outside of the current crate \
803 (in Nightly builds, run with -Z external-macro-backtrace \
804 for more info)".to_string()
805 } else {
806 "this warning originates in a macro outside of the current crate \
807 (in Nightly builds, run with -Z external-macro-backtrace \
808 for more info)".to_string()
809 };
810
811 if spans_updated {
812 children.push(SubDiagnostic {
813 level: Level::Note,
814 message: vec![
815 (msg,
816 Style::NoStyle),
817 ],
818 span: MultiSpan::new(),
819 render_span: None,
820 });
821 }
822 }
823
824 /// Adds a left margin to every line but the first, given a padding length and the label being
825 /// displayed, keeping the provided highlighting.
826 fn msg_to_buffer(&self,
827 buffer: &mut StyledBuffer,
828 msg: &[(String, Style)],
829 padding: usize,
830 label: &str,
831 override_style: Option<Style>) {
832
833 // The extra 5 ` ` is padding that's always needed to align to the `note: `:
834 //
835 // error: message
836 // --> file.rs:13:20
837 // |
838 // 13 | <CODE>
839 // | ^^^^
840 // |
841 // = note: multiline
842 // message
843 // ++^^^----xx
844 // | | | |
845 // | | | magic `2`
846 // | | length of label
847 // | magic `3`
848 // `max_line_num_len`
849 let padding = " ".repeat(padding + label.len() + 5);
850
851 /// Returns `true` if `style`, or the override if present and the style is `NoStyle`.
852 fn style_or_override(style: Style, override_style: Option<Style>) -> Style {
853 if let Some(o) = override_style {
854 if style == Style::NoStyle {
855 return o;
856 }
857 }
858 style
859 }
860
861 let mut line_number = 0;
862
863 // Provided the following diagnostic message:
864 //
865 // let msg = vec![
866 // ("
867 // ("highlighted multiline\nstring to\nsee how it ", Style::NoStyle),
868 // ("looks", Style::Highlight),
869 // ("with\nvery ", Style::NoStyle),
870 // ("weird", Style::Highlight),
871 // (" formats\n", Style::NoStyle),
872 // ("see?", Style::Highlight),
873 // ];
874 //
875 // the expected output on a note is (* surround the highlighted text)
876 //
877 // = note: highlighted multiline
878 // string to
879 // see how it *looks* with
880 // very *weird* formats
881 // see?
882 for &(ref text, ref style) in msg.iter() {
883 let lines = text.split('\n').collect::<Vec<_>>();
884 if lines.len() > 1 {
885 for (i, line) in lines.iter().enumerate() {
886 if i != 0 {
887 line_number += 1;
888 buffer.append(line_number, &padding, Style::NoStyle);
889 }
890 buffer.append(line_number, line, style_or_override(*style, override_style));
891 }
892 } else {
893 buffer.append(line_number, text, style_or_override(*style, override_style));
894 }
895 }
896 }
897
898 fn emit_message_default(
899 &mut self,
900 msp: &MultiSpan,
901 msg: &[(String, Style)],
902 code: &Option<DiagnosticId>,
903 level: &Level,
904 max_line_num_len: usize,
905 is_secondary: bool,
906 ) -> io::Result<()> {
907 let mut buffer = StyledBuffer::new();
908 let header_style = if is_secondary {
909 Style::HeaderMsg
910 } else {
911 Style::MainHeaderMsg
912 };
913
914 if !msp.has_primary_spans() && !msp.has_span_labels() && is_secondary
915 && !self.short_message {
916 // This is a secondary message with no span info
917 for _ in 0..max_line_num_len {
918 buffer.prepend(0, " ", Style::NoStyle);
919 }
920 draw_note_separator(&mut buffer, 0, max_line_num_len + 1);
921 let level_str = level.to_string();
922 if !level_str.is_empty() {
923 buffer.append(0, &level_str, Style::MainHeaderMsg);
924 buffer.append(0, ": ", Style::NoStyle);
925 }
926 self.msg_to_buffer(&mut buffer, msg, max_line_num_len, "note", None);
927 } else {
928 let level_str = level.to_string();
929 if !level_str.is_empty() {
930 buffer.append(0, &level_str, Style::Level(level.clone()));
931 }
932 // only render error codes, not lint codes
933 if let Some(DiagnosticId::Error(ref code)) = *code {
934 buffer.append(0, "[", Style::Level(level.clone()));
935 buffer.append(0, &code, Style::Level(level.clone()));
936 buffer.append(0, "]", Style::Level(level.clone()));
937 }
938 if !level_str.is_empty() {
939 buffer.append(0, ": ", header_style);
940 }
941 for &(ref text, _) in msg.iter() {
942 buffer.append(0, text, header_style);
943 }
944 }
945
946 let mut annotated_files = FileWithAnnotatedLines::collect_annotations(msp, &self.sm);
947
948 // Make sure our primary file comes first
949 let (primary_lo, sm) = if let (Some(sm), Some(ref primary_span)) =
950 (self.sm.as_ref(), msp.primary_span().as_ref()) {
951 if !primary_span.is_dummy() {
952 (sm.lookup_char_pos(primary_span.lo()), sm)
953 } else {
954 emit_to_destination(&buffer.render(), level, &mut self.dst, self.short_message)?;
955 return Ok(());
956 }
957 } else {
958 // If we don't have span information, emit and exit
959 emit_to_destination(&buffer.render(), level, &mut self.dst, self.short_message)?;
960 return Ok(());
961 };
962 if let Ok(pos) =
963 annotated_files.binary_search_by(|x| x.file.name.cmp(&primary_lo.file.name)) {
964 annotated_files.swap(0, pos);
965 }
966
967 // Print out the annotate source lines that correspond with the error
968 for annotated_file in annotated_files {
969 // we can't annotate anything if the source is unavailable.
970 if !sm.ensure_source_file_source_present(annotated_file.file.clone()) {
971 continue;
972 }
973
974 // print out the span location and spacer before we print the annotated source
975 // to do this, we need to know if this span will be primary
976 let is_primary = primary_lo.file.name == annotated_file.file.name;
977 if is_primary {
978 let loc = primary_lo.clone();
979 if !self.short_message {
980 // remember where we are in the output buffer for easy reference
981 let buffer_msg_line_offset = buffer.num_lines();
982
983 buffer.prepend(buffer_msg_line_offset, "--> ", Style::LineNumber);
984 buffer.append(buffer_msg_line_offset,
985 &format!("{}:{}:{}",
986 loc.file.name,
987 sm.doctest_offset_line(&loc.file.name, loc.line),
988 loc.col.0 + 1),
989 Style::LineAndColumn);
990 for _ in 0..max_line_num_len {
991 buffer.prepend(buffer_msg_line_offset, " ", Style::NoStyle);
992 }
993 } else {
994 buffer.prepend(0,
995 &format!("{}:{}:{}: ",
996 loc.file.name,
997 sm.doctest_offset_line(&loc.file.name, loc.line),
998 loc.col.0 + 1),
999 Style::LineAndColumn);
1000 }
1001 } else if !self.short_message {
1002 // remember where we are in the output buffer for easy reference
1003 let buffer_msg_line_offset = buffer.num_lines();
1004
1005 // Add spacing line
1006 draw_col_separator(&mut buffer, buffer_msg_line_offset, max_line_num_len + 1);
1007
1008 // Then, the secondary file indicator
1009 buffer.prepend(buffer_msg_line_offset + 1, "::: ", Style::LineNumber);
1010 let loc = if let Some(first_line) = annotated_file.lines.first() {
1011 let col = if let Some(first_annotation) = first_line.annotations.first() {
1012 format!(":{}", first_annotation.start_col + 1)
1013 } else {
1014 String::new()
1015 };
1016 format!("{}:{}{}",
1017 annotated_file.file.name,
1018 sm.doctest_offset_line(
1019 &annotated_file.file.name, first_line.line_index),
1020 col)
1021 } else {
1022 annotated_file.file.name.to_string()
1023 };
1024 buffer.append(buffer_msg_line_offset + 1,
1025 &loc,
1026 Style::LineAndColumn);
1027 for _ in 0..max_line_num_len {
1028 buffer.prepend(buffer_msg_line_offset + 1, " ", Style::NoStyle);
1029 }
1030 }
1031
1032 if !self.short_message {
1033 // Put in the spacer between the location and annotated source
1034 let buffer_msg_line_offset = buffer.num_lines();
1035 draw_col_separator_no_space(&mut buffer,
1036 buffer_msg_line_offset,
1037 max_line_num_len + 1);
1038
1039 // Contains the vertical lines' positions for active multiline annotations
1040 let mut multilines = FxHashMap::default();
1041
1042 // Next, output the annotate source for this file
1043 for line_idx in 0..annotated_file.lines.len() {
1044 let previous_buffer_line = buffer.num_lines();
1045
1046 let width_offset = 3 + max_line_num_len;
1047 let code_offset = if annotated_file.multiline_depth == 0 {
1048 width_offset
1049 } else {
1050 width_offset + annotated_file.multiline_depth + 1
1051 };
1052
1053 let depths = self.render_source_line(&mut buffer,
1054 annotated_file.file.clone(),
1055 &annotated_file.lines[line_idx],
1056 width_offset,
1057 code_offset);
1058
1059 let mut to_add = FxHashMap::default();
1060
1061 for (depth, style) in depths {
1062 if multilines.get(&depth).is_some() {
1063 multilines.remove(&depth);
1064 } else {
1065 to_add.insert(depth, style);
1066 }
1067 }
1068
1069 // Set the multiline annotation vertical lines to the left of
1070 // the code in this line.
1071 for (depth, style) in &multilines {
1072 for line in previous_buffer_line..buffer.num_lines() {
1073 draw_multiline_line(&mut buffer,
1074 line,
1075 width_offset,
1076 *depth,
1077 *style);
1078 }
1079 }
1080 // check to see if we need to print out or elide lines that come between
1081 // this annotated line and the next one.
1082 if line_idx < (annotated_file.lines.len() - 1) {
1083 let line_idx_delta = annotated_file.lines[line_idx + 1].line_index -
1084 annotated_file.lines[line_idx].line_index;
1085 if line_idx_delta > 2 {
1086 let last_buffer_line_num = buffer.num_lines();
1087 buffer.puts(last_buffer_line_num, 0, "...", Style::LineNumber);
1088
1089 // Set the multiline annotation vertical lines on `...` bridging line.
1090 for (depth, style) in &multilines {
1091 draw_multiline_line(&mut buffer,
1092 last_buffer_line_num,
1093 width_offset,
1094 *depth,
1095 *style);
1096 }
1097 } else if line_idx_delta == 2 {
1098 let unannotated_line = annotated_file.file
1099 .get_line(annotated_file.lines[line_idx].line_index)
1100 .unwrap_or_else(|| Cow::from(""));
1101
1102 let last_buffer_line_num = buffer.num_lines();
1103
1104 buffer.puts(last_buffer_line_num,
1105 0,
1106 &self.maybe_anonymized(annotated_file.lines[line_idx + 1]
1107 .line_index - 1),
1108 Style::LineNumber);
1109 draw_col_separator(&mut buffer,
1110 last_buffer_line_num,
1111 1 + max_line_num_len);
1112 buffer.puts(last_buffer_line_num,
1113 code_offset,
1114 &unannotated_line,
1115 Style::Quotation);
1116
1117 for (depth, style) in &multilines {
1118 draw_multiline_line(&mut buffer,
1119 last_buffer_line_num,
1120 width_offset,
1121 *depth,
1122 *style);
1123 }
1124 }
1125 }
1126
1127 multilines.extend(&to_add);
1128 }
1129 }
1130 }
1131
1132 // final step: take our styled buffer, render it, then output it
1133 emit_to_destination(&buffer.render(), level, &mut self.dst, self.short_message)?;
1134
1135 Ok(())
1136
1137 }
1138
1139 fn emit_suggestion_default(
1140 &mut self,
1141 suggestion: &CodeSuggestion,
1142 level: &Level,
1143 max_line_num_len: usize,
1144 ) -> io::Result<()> {
1145 if let Some(ref sm) = self.sm {
1146 let mut buffer = StyledBuffer::new();
1147
1148 // Render the suggestion message
1149 let level_str = level.to_string();
1150 if !level_str.is_empty() {
1151 buffer.append(0, &level_str, Style::Level(level.clone()));
1152 buffer.append(0, ": ", Style::HeaderMsg);
1153 }
1154 self.msg_to_buffer(
1155 &mut buffer,
1156 &[(suggestion.msg.to_owned(), Style::NoStyle)],
1157 max_line_num_len,
1158 "suggestion",
1159 Some(Style::HeaderMsg),
1160 );
1161
1162 // Render the replacements for each suggestion
1163 let suggestions = suggestion.splice_lines(&**sm);
1164
1165 let mut row_num = 2;
1166 for &(ref complete, ref parts) in suggestions.iter().take(MAX_SUGGESTIONS) {
1167 // Only show underline if the suggestion spans a single line and doesn't cover the
1168 // entirety of the code output. If you have multiple replacements in the same line
1169 // of code, show the underline.
1170 let show_underline = !(parts.len() == 1
1171 && parts[0].snippet.trim() == complete.trim())
1172 && complete.lines().count() == 1;
1173
1174 let lines = sm.span_to_lines(parts[0].span).unwrap();
1175
1176 assert!(!lines.lines.is_empty());
1177
1178 let line_start = sm.lookup_char_pos(parts[0].span.lo()).line;
1179 draw_col_separator_no_space(&mut buffer, 1, max_line_num_len + 1);
1180 let mut line_pos = 0;
1181 let mut lines = complete.lines();
1182 for line in lines.by_ref().take(MAX_HIGHLIGHT_LINES) {
1183 // Print the span column to avoid confusion
1184 buffer.puts(row_num,
1185 0,
1186 &self.maybe_anonymized(line_start + line_pos),
1187 Style::LineNumber);
1188 // print the suggestion
1189 draw_col_separator(&mut buffer, row_num, max_line_num_len + 1);
1190 buffer.append(row_num, line, Style::NoStyle);
1191 line_pos += 1;
1192 row_num += 1;
1193 }
1194
1195 // This offset and the ones below need to be signed to account for replacement code
1196 // that is shorter than the original code.
1197 let mut offset: isize = 0;
1198 // Only show an underline in the suggestions if the suggestion is not the
1199 // entirety of the code being shown and the displayed code is not multiline.
1200 if show_underline {
1201 draw_col_separator(&mut buffer, row_num, max_line_num_len + 1);
1202 for part in parts {
1203 let span_start_pos = sm.lookup_char_pos(part.span.lo()).col_display;
1204 let span_end_pos = sm.lookup_char_pos(part.span.hi()).col_display;
1205
1206 // Do not underline the leading...
1207 let start = part.snippet.len()
1208 .saturating_sub(part.snippet.trim_start().len());
1209 // ...or trailing spaces. Account for substitutions containing unicode
1210 // characters.
1211 let sub_len = part.snippet.trim().chars().fold(0, |acc, ch| {
1212 acc + unicode_width::UnicodeWidthChar::width(ch).unwrap_or(0)
1213 });
1214
1215 let underline_start = (span_start_pos + start) as isize + offset;
1216 let underline_end = (span_start_pos + start + sub_len) as isize + offset;
1217 for p in underline_start..underline_end {
1218 buffer.putc(row_num,
1219 max_line_num_len + 3 + p as usize,
1220 '^',
1221 Style::UnderlinePrimary);
1222 }
1223 // underline removals too
1224 if underline_start == underline_end {
1225 for p in underline_start-1..underline_start+1 {
1226 buffer.putc(row_num,
1227 max_line_num_len + 3 + p as usize,
1228 '-',
1229 Style::UnderlineSecondary);
1230 }
1231 }
1232
1233 // length of the code after substitution
1234 let full_sub_len = part.snippet.chars().fold(0, |acc, ch| {
1235 acc + unicode_width::UnicodeWidthChar::width(ch).unwrap_or(0) as isize
1236 });
1237
1238 // length of the code to be substituted
1239 let snippet_len = span_end_pos as isize - span_start_pos as isize;
1240 // For multiple substitutions, use the position *after* the previous
1241 // substitutions have happened.
1242 offset += full_sub_len - snippet_len;
1243 }
1244 row_num += 1;
1245 }
1246
1247 // if we elided some lines, add an ellipsis
1248 if lines.next().is_some() {
1249 buffer.puts(row_num, max_line_num_len - 1, "...", Style::LineNumber);
1250 } else if !show_underline {
1251 draw_col_separator_no_space(&mut buffer, row_num, max_line_num_len + 1);
1252 row_num += 1;
1253 }
1254 }
1255 if suggestions.len() > MAX_SUGGESTIONS {
1256 let msg = format!("and {} other candidates", suggestions.len() - MAX_SUGGESTIONS);
1257 buffer.puts(row_num, 0, &msg, Style::NoStyle);
1258 }
1259 emit_to_destination(&buffer.render(), level, &mut self.dst, self.short_message)?;
1260 }
1261 Ok(())
1262 }
1263
1264 fn emit_messages_default(&mut self,
1265 level: &Level,
1266 message: &[(String, Style)],
1267 code: &Option<DiagnosticId>,
1268 span: &MultiSpan,
1269 children: &[SubDiagnostic],
1270 suggestions: &[CodeSuggestion]) {
1271 let max_line_num_len = if self.ui_testing {
1272 ANONYMIZED_LINE_NUM.len()
1273 } else {
1274 self.get_max_line_num(span, children).to_string().len()
1275 };
1276
1277 match self.emit_message_default(span,
1278 message,
1279 code,
1280 level,
1281 max_line_num_len,
1282 false) {
1283 Ok(()) => {
1284 if !children.is_empty() {
1285 let mut buffer = StyledBuffer::new();
1286 if !self.short_message {
1287 draw_col_separator_no_space(&mut buffer, 0, max_line_num_len + 1);
1288 }
1289 match emit_to_destination(&buffer.render(), level, &mut self.dst,
1290 self.short_message) {
1291 Ok(()) => (),
1292 Err(e) => panic!("failed to emit error: {}", e)
1293 }
1294 }
1295 if !self.short_message {
1296 for child in children {
1297 let span = child.render_span.as_ref().unwrap_or(&child.span);
1298 match self.emit_message_default(
1299 &span,
1300 &child.styled_message(),
1301 &None,
1302 &child.level,
1303 max_line_num_len,
1304 true,
1305 ) {
1306 Err(e) => panic!("failed to emit error: {}", e),
1307 _ => ()
1308 }
1309 }
1310 for sugg in suggestions {
1311 if sugg.style == SuggestionStyle::CompletelyHidden {
1312 // do not display this suggestion, it is meant only for tools
1313 } else if sugg.style == SuggestionStyle::HideCodeAlways {
1314 match self.emit_message_default(
1315 &MultiSpan::new(),
1316 &[(sugg.msg.to_owned(), Style::HeaderMsg)],
1317 &None,
1318 &Level::Help,
1319 max_line_num_len,
1320 true,
1321 ) {
1322 Err(e) => panic!("failed to emit error: {}", e),
1323 _ => ()
1324 }
1325 } else {
1326 match self.emit_suggestion_default(
1327 sugg,
1328 &Level::Help,
1329 max_line_num_len,
1330 ) {
1331 Err(e) => panic!("failed to emit error: {}", e),
1332 _ => ()
1333 }
1334 }
1335 }
1336 }
1337 }
1338 Err(e) => panic!("failed to emit error: {}", e),
1339 }
1340
1341 let mut dst = self.dst.writable();
1342 match writeln!(dst) {
1343 Err(e) => panic!("failed to emit error: {}", e),
1344 _ => {
1345 match dst.flush() {
1346 Err(e) => panic!("failed to emit error: {}", e),
1347 _ => (),
1348 }
1349 }
1350 }
1351 }
1352 }
1353
1354 impl FileWithAnnotatedLines {
1355 /// Preprocess all the annotations so that they are grouped by file and by line number
1356 /// This helps us quickly iterate over the whole message (including secondary file spans)
1357 pub fn collect_annotations(
1358 msp: &MultiSpan,
1359 source_map: &Option<Lrc<SourceMapperDyn>>
1360 ) -> Vec<FileWithAnnotatedLines> {
1361 fn add_annotation_to_file(file_vec: &mut Vec<FileWithAnnotatedLines>,
1362 file: Lrc<SourceFile>,
1363 line_index: usize,
1364 ann: Annotation) {
1365
1366 for slot in file_vec.iter_mut() {
1367 // Look through each of our files for the one we're adding to
1368 if slot.file.name == file.name {
1369 // See if we already have a line for it
1370 for line_slot in &mut slot.lines {
1371 if line_slot.line_index == line_index {
1372 line_slot.annotations.push(ann);
1373 return;
1374 }
1375 }
1376 // We don't have a line yet, create one
1377 slot.lines.push(Line {
1378 line_index,
1379 annotations: vec![ann],
1380 });
1381 slot.lines.sort();
1382 return;
1383 }
1384 }
1385 // This is the first time we're seeing the file
1386 file_vec.push(FileWithAnnotatedLines {
1387 file,
1388 lines: vec![Line {
1389 line_index,
1390 annotations: vec![ann],
1391 }],
1392 multiline_depth: 0,
1393 });
1394 }
1395
1396 let mut output = vec![];
1397 let mut multiline_annotations = vec![];
1398
1399 if let Some(ref sm) = source_map {
1400 for span_label in msp.span_labels() {
1401 if span_label.span.is_dummy() {
1402 continue;
1403 }
1404
1405 let lo = sm.lookup_char_pos(span_label.span.lo());
1406 let mut hi = sm.lookup_char_pos(span_label.span.hi());
1407
1408 // Watch out for "empty spans". If we get a span like 6..6, we
1409 // want to just display a `^` at 6, so convert that to
1410 // 6..7. This is degenerate input, but it's best to degrade
1411 // gracefully -- and the parser likes to supply a span like
1412 // that for EOF, in particular.
1413
1414 if lo.col_display == hi.col_display && lo.line == hi.line {
1415 hi.col_display += 1;
1416 }
1417
1418 let ann_type = if lo.line != hi.line {
1419 let ml = MultilineAnnotation {
1420 depth: 1,
1421 line_start: lo.line,
1422 line_end: hi.line,
1423 start_col: lo.col_display,
1424 end_col: hi.col_display,
1425 is_primary: span_label.is_primary,
1426 label: span_label.label.clone(),
1427 overlaps_exactly: false,
1428 };
1429 multiline_annotations.push((lo.file.clone(), ml.clone()));
1430 AnnotationType::Multiline(ml)
1431 } else {
1432 AnnotationType::Singleline
1433 };
1434 let ann = Annotation {
1435 start_col: lo.col_display,
1436 end_col: hi.col_display,
1437 is_primary: span_label.is_primary,
1438 label: span_label.label.clone(),
1439 annotation_type: ann_type,
1440 };
1441
1442 if !ann.is_multiline() {
1443 add_annotation_to_file(&mut output, lo.file, lo.line, ann);
1444 }
1445 }
1446 }
1447
1448 // Find overlapping multiline annotations, put them at different depths
1449 multiline_annotations.sort_by_key(|&(_, ref ml)| (ml.line_start, ml.line_end));
1450 for item in multiline_annotations.clone() {
1451 let ann = item.1;
1452 for item in multiline_annotations.iter_mut() {
1453 let ref mut a = item.1;
1454 // Move all other multiline annotations overlapping with this one
1455 // one level to the right.
1456 if !(ann.same_span(a)) &&
1457 num_overlap(ann.line_start, ann.line_end, a.line_start, a.line_end, true)
1458 {
1459 a.increase_depth();
1460 } else if ann.same_span(a) && &ann != a {
1461 a.overlaps_exactly = true;
1462 } else {
1463 break;
1464 }
1465 }
1466 }
1467
1468 let mut max_depth = 0; // max overlapping multiline spans
1469 for (file, ann) in multiline_annotations {
1470 if ann.depth > max_depth {
1471 max_depth = ann.depth;
1472 }
1473 let mut end_ann = ann.as_end();
1474 if !ann.overlaps_exactly {
1475 // avoid output like
1476 //
1477 // | foo(
1478 // | _____^
1479 // | |_____|
1480 // | || bar,
1481 // | || );
1482 // | || ^
1483 // | ||______|
1484 // | |______foo
1485 // | baz
1486 //
1487 // and instead get
1488 //
1489 // | foo(
1490 // | _____^
1491 // | | bar,
1492 // | | );
1493 // | | ^
1494 // | | |
1495 // | |______foo
1496 // | baz
1497 add_annotation_to_file(&mut output, file.clone(), ann.line_start, ann.as_start());
1498 // 4 is the minimum vertical length of a multiline span when presented: two lines
1499 // of code and two lines of underline. This is not true for the special case where
1500 // the beginning doesn't have an underline, but the current logic seems to be
1501 // working correctly.
1502 let middle = min(ann.line_start + 4, ann.line_end);
1503 for line in ann.line_start + 1..middle {
1504 // Every `|` that joins the beginning of the span (`___^`) to the end (`|__^`).
1505 add_annotation_to_file(&mut output, file.clone(), line, ann.as_line());
1506 }
1507 if middle < ann.line_end - 1 {
1508 for line in ann.line_end - 1..ann.line_end {
1509 add_annotation_to_file(&mut output, file.clone(), line, ann.as_line());
1510 }
1511 }
1512 } else {
1513 end_ann.annotation_type = AnnotationType::Singleline;
1514 }
1515 add_annotation_to_file(&mut output, file, ann.line_end, end_ann);
1516 }
1517 for file_vec in output.iter_mut() {
1518 file_vec.multiline_depth = max_depth;
1519 }
1520 output
1521 }
1522 }
1523
1524 fn draw_col_separator(buffer: &mut StyledBuffer, line: usize, col: usize) {
1525 buffer.puts(line, col, "| ", Style::LineNumber);
1526 }
1527
1528 fn draw_col_separator_no_space(buffer: &mut StyledBuffer, line: usize, col: usize) {
1529 draw_col_separator_no_space_with_style(buffer, line, col, Style::LineNumber);
1530 }
1531
1532 fn draw_col_separator_no_space_with_style(buffer: &mut StyledBuffer,
1533 line: usize,
1534 col: usize,
1535 style: Style) {
1536 buffer.putc(line, col, '|', style);
1537 }
1538
1539 fn draw_range(buffer: &mut StyledBuffer, symbol: char, line: usize,
1540 col_from: usize, col_to: usize, style: Style) {
1541 for col in col_from..col_to {
1542 buffer.putc(line, col, symbol, style);
1543 }
1544 }
1545
1546 fn draw_note_separator(buffer: &mut StyledBuffer, line: usize, col: usize) {
1547 buffer.puts(line, col, "= ", Style::LineNumber);
1548 }
1549
1550 fn draw_multiline_line(buffer: &mut StyledBuffer,
1551 line: usize,
1552 offset: usize,
1553 depth: usize,
1554 style: Style)
1555 {
1556 buffer.putc(line, offset + depth - 1, '|', style);
1557 }
1558
1559 fn num_overlap(a_start: usize, a_end: usize, b_start: usize, b_end:usize, inclusive: bool) -> bool {
1560 let extra = if inclusive {
1561 1
1562 } else {
1563 0
1564 };
1565 (b_start..b_end + extra).contains(&a_start) ||
1566 (a_start..a_end + extra).contains(&b_start)
1567 }
1568 fn overlaps(a1: &Annotation, a2: &Annotation, padding: usize) -> bool {
1569 num_overlap(a1.start_col, a1.end_col + padding, a2.start_col, a2.end_col, false)
1570 }
1571
1572 fn emit_to_destination(rendered_buffer: &[Vec<StyledString>],
1573 lvl: &Level,
1574 dst: &mut Destination,
1575 short_message: bool)
1576 -> io::Result<()> {
1577 use crate::lock;
1578
1579 let mut dst = dst.writable();
1580
1581 // In order to prevent error message interleaving, where multiple error lines get intermixed
1582 // when multiple compiler processes error simultaneously, we emit errors with additional
1583 // steps.
1584 //
1585 // On Unix systems, we write into a buffered terminal rather than directly to a terminal. When
1586 // the .flush() is called we take the buffer created from the buffered writes and write it at
1587 // one shot. Because the Unix systems use ANSI for the colors, which is a text-based styling
1588 // scheme, this buffered approach works and maintains the styling.
1589 //
1590 // On Windows, styling happens through calls to a terminal API. This prevents us from using the
1591 // same buffering approach. Instead, we use a global Windows mutex, which we acquire long
1592 // enough to output the full error message, then we release.
1593 let _buffer_lock = lock::acquire_global_lock("rustc_errors");
1594 for (pos, line) in rendered_buffer.iter().enumerate() {
1595 for part in line {
1596 dst.apply_style(lvl.clone(), part.style)?;
1597 write!(dst, "{}", part.text)?;
1598 dst.reset()?;
1599 }
1600 if !short_message && (!lvl.is_failure_note() || pos != rendered_buffer.len() - 1) {
1601 writeln!(dst)?;
1602 }
1603 }
1604 dst.flush()?;
1605 Ok(())
1606 }
1607
1608 pub enum Destination {
1609 Terminal(StandardStream),
1610 Buffered(BufferWriter),
1611 // The bool denotes whether we should be emitting ansi color codes or not
1612 Raw(Box<(dyn Write + Send)>, bool),
1613 }
1614
1615 pub enum WritableDst<'a> {
1616 Terminal(&'a mut StandardStream),
1617 Buffered(&'a mut BufferWriter, Buffer),
1618 Raw(&'a mut (dyn Write + Send)),
1619 ColoredRaw(Ansi<&'a mut (dyn Write + Send)>),
1620 }
1621
1622 impl Destination {
1623 fn from_stderr(color: ColorConfig) -> Destination {
1624 let choice = color.to_color_choice();
1625 // On Windows we'll be performing global synchronization on the entire
1626 // system for emitting rustc errors, so there's no need to buffer
1627 // anything.
1628 //
1629 // On non-Windows we rely on the atomicity of `write` to ensure errors
1630 // don't get all jumbled up.
1631 if cfg!(windows) {
1632 Terminal(StandardStream::stderr(choice))
1633 } else {
1634 Buffered(BufferWriter::stderr(choice))
1635 }
1636 }
1637
1638 fn writable<'a>(&'a mut self) -> WritableDst<'a> {
1639 match *self {
1640 Destination::Terminal(ref mut t) => WritableDst::Terminal(t),
1641 Destination::Buffered(ref mut t) => {
1642 let buf = t.buffer();
1643 WritableDst::Buffered(t, buf)
1644 }
1645 Destination::Raw(ref mut t, false) => WritableDst::Raw(t),
1646 Destination::Raw(ref mut t, true) => WritableDst::ColoredRaw(Ansi::new(t)),
1647 }
1648 }
1649 }
1650
1651 impl<'a> WritableDst<'a> {
1652 fn apply_style(&mut self, lvl: Level, style: Style) -> io::Result<()> {
1653 let mut spec = ColorSpec::new();
1654 match style {
1655 Style::LineAndColumn => {}
1656 Style::LineNumber => {
1657 spec.set_bold(true);
1658 spec.set_intense(true);
1659 if cfg!(windows) {
1660 spec.set_fg(Some(Color::Cyan));
1661 } else {
1662 spec.set_fg(Some(Color::Blue));
1663 }
1664 }
1665 Style::Quotation => {}
1666 Style::MainHeaderMsg => {
1667 spec.set_bold(true);
1668 if cfg!(windows) {
1669 spec.set_intense(true)
1670 .set_fg(Some(Color::White));
1671 }
1672 }
1673 Style::UnderlinePrimary | Style::LabelPrimary => {
1674 spec = lvl.color();
1675 spec.set_bold(true);
1676 }
1677 Style::UnderlineSecondary |
1678 Style::LabelSecondary => {
1679 spec.set_bold(true)
1680 .set_intense(true);
1681 if cfg!(windows) {
1682 spec.set_fg(Some(Color::Cyan));
1683 } else {
1684 spec.set_fg(Some(Color::Blue));
1685 }
1686 }
1687 Style::HeaderMsg |
1688 Style::NoStyle => {}
1689 Style::Level(lvl) => {
1690 spec = lvl.color();
1691 spec.set_bold(true);
1692 }
1693 Style::Highlight => {
1694 spec.set_bold(true);
1695 }
1696 }
1697 self.set_color(&spec)
1698 }
1699
1700 fn set_color(&mut self, color: &ColorSpec) -> io::Result<()> {
1701 match *self {
1702 WritableDst::Terminal(ref mut t) => t.set_color(color),
1703 WritableDst::Buffered(_, ref mut t) => t.set_color(color),
1704 WritableDst::ColoredRaw(ref mut t) => t.set_color(color),
1705 WritableDst::Raw(_) => Ok(())
1706 }
1707 }
1708
1709 fn reset(&mut self) -> io::Result<()> {
1710 match *self {
1711 WritableDst::Terminal(ref mut t) => t.reset(),
1712 WritableDst::Buffered(_, ref mut t) => t.reset(),
1713 WritableDst::ColoredRaw(ref mut t) => t.reset(),
1714 WritableDst::Raw(_) => Ok(()),
1715 }
1716 }
1717 }
1718
1719 impl<'a> Write for WritableDst<'a> {
1720 fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
1721 match *self {
1722 WritableDst::Terminal(ref mut t) => t.write(bytes),
1723 WritableDst::Buffered(_, ref mut buf) => buf.write(bytes),
1724 WritableDst::Raw(ref mut w) => w.write(bytes),
1725 WritableDst::ColoredRaw(ref mut t) => t.write(bytes),
1726 }
1727 }
1728
1729 fn flush(&mut self) -> io::Result<()> {
1730 match *self {
1731 WritableDst::Terminal(ref mut t) => t.flush(),
1732 WritableDst::Buffered(_, ref mut buf) => buf.flush(),
1733 WritableDst::Raw(ref mut w) => w.flush(),
1734 WritableDst::ColoredRaw(ref mut w) => w.flush(),
1735 }
1736 }
1737 }
1738
1739 impl<'a> Drop for WritableDst<'a> {
1740 fn drop(&mut self) {
1741 match *self {
1742 WritableDst::Buffered(ref mut dst, ref mut buf) => {
1743 drop(dst.print(buf));
1744 }
1745 _ => {}
1746 }
1747 }
1748 }