]> git.proxmox.com Git - rustc.git/blame - src/librustc_errors/emitter.rs
New upstream version 1.44.1+dfsg1
[rustc.git] / src / librustc_errors / emitter.rs
CommitLineData
dc9dc135
XL
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//!
ba9703b0 8//! The output types are defined in `rustc_session::config::ErrorOutputType`.
dc9dc135 9
9fa01778 10use Destination::*;
1a4d82fc 11
dfeec247
XL
12use rustc_span::source_map::SourceMap;
13use rustc_span::{MultiSpan, SourceFile, Span};
223e47cc 14
60c5eb7d
XL
15use crate::snippet::{Annotation, AnnotationType, Line, MultilineAnnotation, Style, StyledString};
16use crate::styled_buffer::StyledBuffer;
9fa01778 17use crate::{
60c5eb7d 18 pluralize, CodeSuggestion, Diagnostic, DiagnosticId, Level, SubDiagnostic, SuggestionStyle,
9fa01778 19};
9cc50fc6 20
60c5eb7d 21use log::*;
b7449926 22use rustc_data_structures::fx::FxHashMap;
0531ce1d 23use rustc_data_structures::sync::Lrc;
dfeec247 24use rustc_span::hygiene::{ExpnKind, MacroKind};
041b39d2 25use std::borrow::Cow;
60c5eb7d 26use std::cmp::{max, min, Reverse};
c34b1796 27use std::io;
60c5eb7d 28use std::io::prelude::*;
74b04a01 29use std::iter;
48663c56 30use std::path::Path;
60c5eb7d
XL
31use termcolor::{Ansi, BufferWriter, ColorChoice, ColorSpec, StandardStream};
32use termcolor::{Buffer, Color, WriteColor};
1a4d82fc 33
48663c56
XL
34/// Describes the way the content of the `rendered` field of the json output is generated
35#[derive(Clone, Copy, Debug, PartialEq, Eq)]
36pub enum HumanReadableErrorType {
37 Default(ColorConfig),
dc9dc135 38 AnnotateSnippet(ColorConfig),
48663c56
XL
39 Short(ColorConfig),
40}
41
42impl HumanReadableErrorType {
43 /// Returns a (`short`, `color`) tuple
44 pub fn unzip(self) -> (bool, ColorConfig) {
45 match self {
46 HumanReadableErrorType::Default(cc) => (false, cc),
47 HumanReadableErrorType::Short(cc) => (true, cc),
dc9dc135 48 HumanReadableErrorType::AnnotateSnippet(cc) => (false, cc),
48663c56
XL
49 }
50 }
51 pub fn new_emitter(
52 self,
53 dst: Box<dyn Write + Send>,
60c5eb7d 54 source_map: Option<Lrc<SourceMap>>,
48663c56 55 teach: bool,
e1599b0c 56 terminal_width: Option<usize>,
74b04a01 57 macro_backtrace: bool,
48663c56
XL
58 ) -> EmitterWriter {
59 let (short, color_config) = self.unzip();
e1599b0c 60 let color = color_config.suggests_using_colors();
74b04a01 61 EmitterWriter::new(dst, source_map, short, teach, color, terminal_width, macro_backtrace)
e1599b0c
XL
62 }
63}
64
65#[derive(Clone, Copy, Debug)]
66struct Margin {
67 /// The available whitespace in the left that can be consumed when centering.
68 pub whitespace_left: usize,
69 /// The column of the beginning of left-most span.
70 pub span_left: usize,
71 /// The column of the end of right-most span.
72 pub span_right: usize,
73 /// The beginning of the line to be displayed.
74 pub computed_left: usize,
75 /// The end of the line to be displayed.
76 pub computed_right: usize,
77 /// The current width of the terminal. 140 by default and in tests.
78 pub column_width: usize,
79 /// The end column of a span label, including the span. Doesn't account for labels not in the
80 /// same line as the span.
81 pub label_right: usize,
82}
83
84impl Margin {
85 fn new(
86 whitespace_left: usize,
87 span_left: usize,
88 span_right: usize,
89 label_right: usize,
90 column_width: usize,
91 max_line_len: usize,
92 ) -> Self {
93 // The 6 is padding to give a bit of room for `...` when displaying:
94 // ```
95 // error: message
96 // --> file.rs:16:58
97 // |
98 // 16 | ... fn foo(self) -> Self::Bar {
99 // | ^^^^^^^^^
100 // ```
101
102 let mut m = Margin {
e74abb32
XL
103 whitespace_left: whitespace_left.saturating_sub(6),
104 span_left: span_left.saturating_sub(6),
e1599b0c
XL
105 span_right: span_right + 6,
106 computed_left: 0,
107 computed_right: 0,
108 column_width,
109 label_right: label_right + 6,
110 };
111 m.compute(max_line_len);
112 m
113 }
114
115 fn was_cut_left(&self) -> bool {
116 self.computed_left > 0
117 }
118
119 fn was_cut_right(&self, line_len: usize) -> bool {
60c5eb7d
XL
120 let right =
121 if self.computed_right == self.span_right || self.computed_right == self.label_right {
dfeec247
XL
122 // Account for the "..." padding given above. Otherwise we end up with code lines that
123 // do fit but end in "..." as if they were trimmed.
60c5eb7d
XL
124 self.computed_right - 6
125 } else {
126 self.computed_right
127 };
e74abb32 128 right < line_len && self.computed_left + self.column_width < line_len
e1599b0c
XL
129 }
130
131 fn compute(&mut self, max_line_len: usize) {
132 // When there's a lot of whitespace (>20), we want to trim it as it is useless.
133 self.computed_left = if self.whitespace_left > 20 {
134 self.whitespace_left - 16 // We want some padding.
135 } else {
136 0
137 };
138 // We want to show as much as possible, max_line_len is the right-most boundary for the
139 // relevant code.
140 self.computed_right = max(max_line_len, self.computed_left);
141
142 if self.computed_right - self.computed_left > self.column_width {
143 // Trimming only whitespace isn't enough, let's get craftier.
144 if self.label_right - self.whitespace_left <= self.column_width {
145 // Attempt to fit the code window only trimming whitespace.
146 self.computed_left = self.whitespace_left;
147 self.computed_right = self.computed_left + self.column_width;
148 } else if self.label_right - self.span_left <= self.column_width {
149 // Attempt to fit the code window considering only the spans and labels.
150 let padding_left = (self.column_width - (self.label_right - self.span_left)) / 2;
151 self.computed_left = self.span_left.saturating_sub(padding_left);
152 self.computed_right = self.computed_left + self.column_width;
153 } else if self.span_right - self.span_left <= self.column_width {
154 // Attempt to fit the code window considering the spans and labels plus padding.
155 let padding_left = (self.column_width - (self.span_right - self.span_left)) / 5 * 2;
156 self.computed_left = self.span_left.saturating_sub(padding_left);
157 self.computed_right = self.computed_left + self.column_width;
60c5eb7d
XL
158 } else {
159 // Mostly give up but still don't show the full line.
e1599b0c
XL
160 self.computed_left = self.span_left;
161 self.computed_right = self.span_right;
162 }
163 }
164 }
165
166 fn left(&self, line_len: usize) -> usize {
167 min(self.computed_left, line_len)
168 }
169
170 fn right(&self, line_len: usize) -> usize {
e74abb32 171 if line_len.saturating_sub(self.computed_left) <= self.column_width {
e1599b0c
XL
172 line_len
173 } else {
e74abb32 174 min(line_len, self.computed_right)
e1599b0c 175 }
48663c56
XL
176 }
177}
178
0531ce1d
XL
179const ANONYMIZED_LINE_NUM: &str = "LL";
180
5bcae85e 181/// Emitter trait for emitting errors.
9cc50fc6 182pub trait Emitter {
9cc50fc6 183 /// Emit a structured diagnostic.
e74abb32 184 fn emit_diagnostic(&mut self, diag: &Diagnostic);
48663c56
XL
185
186 /// Emit a notification that an artifact has been output.
187 /// This is currently only supported for the JSON format,
188 /// other formats can, and will, simply ignore it.
dc9dc135 189 fn emit_artifact_notification(&mut self, _path: &Path, _artifact_type: &str) {}
0531ce1d 190
9fa01778 191 /// Checks if should show explanations about "rustc --explain"
0531ce1d
XL
192 fn should_show_explain(&self) -> bool {
193 true
194 }
a7813a04 195
60c5eb7d 196 fn source_map(&self) -> Option<&Lrc<SourceMap>>;
e74abb32 197
e1599b0c
XL
198 /// Formats the substitutions of the primary_span
199 ///
200 /// The are a lot of conditions to this method, but in short:
201 ///
202 /// * If the current `Diagnostic` has only one visible `CodeSuggestion`,
203 /// we format the `help` suggestion depending on the content of the
204 /// substitutions. In that case, we return the modified span only.
205 ///
206 /// * If the current `Diagnostic` has multiple suggestions,
207 /// we return the original `primary_span` and the original suggestions.
208 fn primary_span_formatted<'a>(
209 &mut self,
e74abb32 210 diag: &'a Diagnostic,
e1599b0c 211 ) -> (MultiSpan, &'a [CodeSuggestion]) {
e74abb32
XL
212 let mut primary_span = diag.span.clone();
213 if let Some((sugg, rest)) = diag.suggestions.split_first() {
7cac9316 214 if rest.is_empty() &&
e1599b0c 215 // ^ if there is only one suggestion
7cac9316 216 // don't display multi-suggestions as labels
abe05a73
XL
217 sugg.substitutions.len() == 1 &&
218 // don't display multipart suggestions as labels
219 sugg.substitutions[0].parts.len() == 1 &&
7cac9316
XL
220 // don't display long messages as labels
221 sugg.msg.split_whitespace().count() < 10 &&
222 // don't display multiline suggestions as labels
9fa01778 223 !sugg.substitutions[0].parts[0].snippet.contains('\n') &&
e74abb32
XL
224 ![
225 // when this style is set we want the suggestion to be a message, not inline
226 SuggestionStyle::HideCodeAlways,
227 // trivial suggestion for tooling's sake, never shown
228 SuggestionStyle::CompletelyHidden,
229 // subtle suggestion, never shown inline
230 SuggestionStyle::ShowAlways,
231 ].contains(&sugg.style)
9fa01778 232 {
ff7c6d11 233 let substitution = &sugg.substitutions[0].parts[0].snippet.trim();
74b04a01 234 let msg = if substitution.is_empty() || sugg.style.hide_inline() {
e1599b0c
XL
235 // This substitution is only removal OR we explicitly don't want to show the
236 // code inline (`hide_inline`). Therefore, we don't show the substitution.
041b39d2
XL
237 format!("help: {}", sugg.msg)
238 } else {
e1599b0c 239 // Show the default suggestion text with the substitution
e74abb32
XL
240 format!(
241 "help: {}{}: `{}`",
242 sugg.msg,
60c5eb7d
XL
243 if self
244 .source_map()
245 .map(|sm| is_case_difference(
246 &**sm,
247 substitution,
248 sugg.substitutions[0].parts[0].span,
249 ))
250 .unwrap_or(false)
251 {
e74abb32
XL
252 " (notice the capitalization)"
253 } else {
254 ""
255 },
256 substitution,
257 )
041b39d2 258 };
abe05a73 259 primary_span.push_span_label(sugg.substitutions[0].parts[0].span, msg);
e1599b0c
XL
260
261 // We return only the modified primary_span
262 (primary_span, &[])
7cac9316
XL
263 } else {
264 // if there are multiple suggestions, print them all in full
265 // to be consistent. We could try to figure out if we can
266 // make one (or the first one) inline, but that would give
267 // undue importance to a semi-random suggestion
e74abb32 268 (primary_span, &diag.suggestions)
7cac9316 269 }
e1599b0c 270 } else {
e74abb32 271 (primary_span, &diag.suggestions)
e1599b0c
XL
272 }
273 }
274
74b04a01 275 fn fix_multispans_in_extern_macros_and_render_macro_backtrace(
60c5eb7d
XL
276 &self,
277 source_map: &Option<Lrc<SourceMap>>,
278 span: &mut MultiSpan,
279 children: &mut Vec<SubDiagnostic>,
280 level: &Level,
281 backtrace: bool,
282 ) {
74b04a01
XL
283 // Check for spans in macros, before `fix_multispans_in_extern_macros`
284 // has a chance to replace them.
285 let has_macro_spans = iter::once(&*span)
286 .chain(children.iter().map(|child| &child.span))
287 .flat_map(|span| span.primary_spans())
288 .copied()
289 .flat_map(|sp| {
290 sp.macro_backtrace().filter_map(|expn_data| {
291 match expn_data.kind {
292 ExpnKind::Root => None,
293
294 // Skip past non-macro entries, just in case there
295 // are some which do actually involve macros.
296 ExpnKind::Desugaring(..) | ExpnKind::AstPass(..) => None,
297
298 ExpnKind::Macro(macro_kind, _) => Some(macro_kind),
299 }
300 })
301 })
302 .next();
303
304 if !backtrace {
305 self.fix_multispans_in_extern_macros(source_map, span, children);
7cac9316
XL
306 }
307
74b04a01
XL
308 self.render_multispans_macro_backtrace(span, children, backtrace);
309
310 if !backtrace {
311 if let Some(macro_kind) = has_macro_spans {
312 let msg = format!(
313 "this {} originates in {} {} \
314 (in Nightly builds, run with -Z macro-backtrace for more info)",
315 level,
316 macro_kind.article(),
317 macro_kind.descr(),
318 );
319
320 children.push(SubDiagnostic {
321 level: Level::Note,
322 message: vec![(msg, Style::NoStyle)],
323 span: MultiSpan::new(),
324 render_span: None,
325 });
326 }
e1599b0c
XL
327 }
328 }
329
74b04a01 330 fn render_multispans_macro_backtrace(
60c5eb7d 331 &self,
60c5eb7d 332 span: &mut MultiSpan,
74b04a01
XL
333 children: &mut Vec<SubDiagnostic>,
334 backtrace: bool,
335 ) {
336 for span in iter::once(span).chain(children.iter_mut().map(|child| &mut child.span)) {
337 self.render_multispan_macro_backtrace(span, backtrace);
338 }
339 }
e1599b0c 340
74b04a01 341 fn render_multispan_macro_backtrace(&self, span: &mut MultiSpan, always_backtrace: bool) {
e74abb32 342 let mut new_labels: Vec<(Span, String)> = vec![];
e1599b0c 343
74b04a01 344 for &sp in span.primary_spans() {
e74abb32
XL
345 if sp.is_dummy() {
346 continue;
347 }
74b04a01
XL
348
349 // FIXME(eddyb) use `retain` on `macro_backtrace` to remove all the
350 // entries we don't want to print, to make sure the indices being
351 // printed are contiguous (or omitted if there's only one entry).
dfeec247 352 let macro_backtrace: Vec<_> = sp.macro_backtrace().collect();
dfeec247 353 for (i, trace) in macro_backtrace.iter().rev().enumerate() {
dfeec247 354 if trace.def_site.is_dummy() {
e1599b0c
XL
355 continue;
356 }
74b04a01 357
e74abb32 358 if always_backtrace {
60c5eb7d 359 new_labels.push((
dfeec247 360 trace.def_site,
60c5eb7d
XL
361 format!(
362 "in this expansion of `{}`{}",
dfeec247 363 trace.kind.descr(),
74b04a01
XL
364 if macro_backtrace.len() > 2 {
365 // if macro_backtrace.len() == 1 it'll be
366 // pointed at by "in this macro invocation"
60c5eb7d
XL
367 format!(" (#{})", i + 1)
368 } else {
369 String::new()
74b04a01 370 },
60c5eb7d
XL
371 ),
372 ));
e1599b0c 373 }
74b04a01
XL
374
375 // Don't add a label on the call site if the diagnostic itself
376 // already points to (a part of) that call site, as the label
377 // is meant for showing the relevant invocation when the actual
378 // diagnostic is pointing to some part of macro definition.
379 //
380 // This also handles the case where an external span got replaced
381 // with the call site span by `fix_multispans_in_extern_macros`.
382 //
383 // NB: `-Zmacro-backtrace` overrides this, for uniformity, as the
384 // "in this expansion of" label above is always added in that mode,
385 // and it needs an "in this macro invocation" label to match that.
386 let redundant_span = trace.call_site.contains(sp);
387
388 if !redundant_span && matches!(trace.kind, ExpnKind::Macro(MacroKind::Bang, _))
60c5eb7d
XL
389 || always_backtrace
390 {
391 new_labels.push((
392 trace.call_site,
393 format!(
394 "in this macro invocation{}",
74b04a01 395 if macro_backtrace.len() > 2 && always_backtrace {
60c5eb7d
XL
396 // only specify order when the macro
397 // backtrace is multiple levels deep
398 format!(" (#{})", i + 1)
399 } else {
400 String::new()
74b04a01 401 },
60c5eb7d
XL
402 ),
403 ));
74b04a01
XL
404 }
405 if !always_backtrace {
406 break;
e1599b0c
XL
407 }
408 }
e74abb32 409 }
74b04a01 410
e74abb32
XL
411 for (label_span, label_text) in new_labels {
412 span.push_span_label(label_span, label_text);
413 }
74b04a01
XL
414 }
415
416 // This does a small "fix" for multispans by looking to see if it can find any that
ba9703b0
XL
417 // point directly at external macros. Since these are often difficult to read,
418 // this will change the span to point at the use site.
74b04a01
XL
419 fn fix_multispans_in_extern_macros(
420 &self,
421 source_map: &Option<Lrc<SourceMap>>,
422 span: &mut MultiSpan,
423 children: &mut Vec<SubDiagnostic>,
424 ) {
ba9703b0
XL
425 debug!("fix_multispans_in_extern_macros: before: span={:?} children={:?}", span, children);
426 for span in iter::once(&mut *span).chain(children.iter_mut().map(|child| &mut child.span)) {
74b04a01 427 self.fix_multispan_in_extern_macros(source_map, span);
e74abb32 428 }
ba9703b0 429 debug!("fix_multispans_in_extern_macros: after: span={:?} children={:?}", span, children);
74b04a01
XL
430 }
431
ba9703b0
XL
432 // This "fixes" MultiSpans that contain `Span`s pointing to locations inside of external macros.
433 // Since these locations are often difficult to read,
434 // we move these spans from the external macros to their corresponding use site.
74b04a01
XL
435 fn fix_multispan_in_extern_macros(
436 &self,
437 source_map: &Option<Lrc<SourceMap>>,
438 span: &mut MultiSpan,
439 ) {
440 let sm = match source_map {
441 Some(ref sm) => sm,
442 None => return,
443 };
444
ba9703b0 445 // First, find all the spans in external macros and point instead at their use site.
74b04a01
XL
446 let replacements: Vec<(Span, Span)> = span
447 .primary_spans()
448 .iter()
449 .copied()
450 .chain(span.span_labels().iter().map(|sp_label| sp_label.span))
451 .filter_map(|sp| {
ba9703b0 452 if !sp.is_dummy() && sm.is_imported(sp) {
74b04a01
XL
453 let maybe_callsite = sp.source_callsite();
454 if sp != maybe_callsite {
455 return Some((sp, maybe_callsite));
456 }
457 }
458 None
459 })
460 .collect();
461
ba9703b0 462 // After we have them, make sure we replace these 'bad' def sites with their use sites.
74b04a01
XL
463 for (from, to) in replacements {
464 span.replace(from, to);
e1599b0c 465 }
e1599b0c
XL
466 }
467}
468
469impl Emitter for EmitterWriter {
60c5eb7d 470 fn source_map(&self) -> Option<&Lrc<SourceMap>> {
e74abb32
XL
471 self.sm.as_ref()
472 }
473
474 fn emit_diagnostic(&mut self, diag: &Diagnostic) {
475 let mut children = diag.children.clone();
476 let (mut primary_span, suggestions) = self.primary_span_formatted(&diag);
ba9703b0 477 debug!("emit_diagnostic: suggestions={:?}", suggestions);
e1599b0c 478
74b04a01 479 self.fix_multispans_in_extern_macros_and_render_macro_backtrace(
60c5eb7d
XL
480 &self.sm,
481 &mut primary_span,
482 &mut children,
483 &diag.level,
74b04a01 484 self.macro_backtrace,
60c5eb7d
XL
485 );
486
487 self.emit_messages_default(
488 &diag.level,
489 &diag.styled_message(),
490 &diag.code,
491 &primary_span,
492 &children,
493 &suggestions,
494 );
1a4d82fc 495 }
0531ce1d
XL
496
497 fn should_show_explain(&self) -> bool {
498 !self.short_message
499 }
223e47cc
LB
500}
501
60c5eb7d
XL
502/// An emitter that does nothing when emitting a diagnostic.
503pub struct SilentEmitter;
504
505impl Emitter for SilentEmitter {
506 fn source_map(&self) -> Option<&Lrc<SourceMap>> {
507 None
508 }
509 fn emit_diagnostic(&mut self, _: &Diagnostic) {}
510}
511
dfeec247 512/// Maximum number of lines we will print for each error; arbitrary.
7453a54e 513pub const MAX_HIGHLIGHT_LINES: usize = 6;
dfeec247
XL
514/// Maximum number of lines we will print for a multiline suggestion; arbitrary.
515///
516/// This should be replaced with a more involved mechanism to output multiline suggestions that
517/// more closely mimmics the regular diagnostic output, where irrelevant code lines are elided.
518pub const MAX_SUGGESTION_HIGHLIGHT_LINES: usize = 6;
519/// Maximum number of suggestions to be shown
7cac9316
XL
520///
521/// Arbitrary, but taken from trait import suggestion limit
522pub const MAX_SUGGESTIONS: usize = 4;
7453a54e 523
9cc50fc6 524#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1a4d82fc
JJ
525pub enum ColorConfig {
526 Auto,
527 Always,
9cc50fc6 528 Never,
223e47cc
LB
529}
530
9cc50fc6 531impl ColorConfig {
48663c56
XL
532 fn to_color_choice(self) -> ColorChoice {
533 match self {
a1dfa0c6
XL
534 ColorConfig::Always => {
535 if atty::is(atty::Stream::Stderr) {
536 ColorChoice::Always
537 } else {
538 ColorChoice::AlwaysAnsi
539 }
540 }
0531ce1d 541 ColorConfig::Never => ColorChoice::Never,
60c5eb7d 542 ColorConfig::Auto if atty::is(atty::Stream::Stderr) => ColorChoice::Auto,
0531ce1d 543 ColorConfig::Auto => ColorChoice::Never,
9cc50fc6 544 }
d9579d0f 545 }
48663c56
XL
546 fn suggests_using_colors(self) -> bool {
547 match self {
60c5eb7d 548 ColorConfig::Always | ColorConfig::Auto => true,
48663c56
XL
549 ColorConfig::Never => false,
550 }
551 }
d9579d0f
AL
552}
553
dc9dc135 554/// Handles the writing of `HumanReadableErrorType::Default` and `HumanReadableErrorType::Short`
9cc50fc6
SL
555pub struct EmitterWriter {
556 dst: Destination,
60c5eb7d 557 sm: Option<Lrc<SourceMap>>,
abe05a73 558 short_message: bool,
2c00a5a8 559 teach: bool,
0531ce1d 560 ui_testing: bool,
e1599b0c
XL
561 terminal_width: Option<usize>,
562
74b04a01 563 macro_backtrace: bool,
a7813a04 564}
223e47cc 565
dc9dc135
XL
566#[derive(Debug)]
567pub struct FileWithAnnotatedLines {
568 pub file: Lrc<SourceFile>,
569 pub lines: Vec<Line>,
476ff2be 570 multiline_depth: usize,
223e47cc
LB
571}
572
1a4d82fc 573impl EmitterWriter {
e1599b0c
XL
574 pub fn stderr(
575 color_config: ColorConfig,
60c5eb7d 576 source_map: Option<Lrc<SourceMap>>,
e1599b0c
XL
577 short_message: bool,
578 teach: bool,
579 terminal_width: Option<usize>,
74b04a01 580 macro_backtrace: bool,
e1599b0c 581 ) -> EmitterWriter {
0531ce1d
XL
582 let dst = Destination::from_stderr(color_config);
583 EmitterWriter {
584 dst,
a1dfa0c6 585 sm: source_map,
0531ce1d
XL
586 short_message,
587 teach,
588 ui_testing: false,
e1599b0c 589 terminal_width,
74b04a01 590 macro_backtrace,
1a4d82fc
JJ
591 }
592 }
593
48663c56
XL
594 pub fn new(
595 dst: Box<dyn Write + Send>,
60c5eb7d 596 source_map: Option<Lrc<SourceMap>>,
48663c56
XL
597 short_message: bool,
598 teach: bool,
599 colored: bool,
e1599b0c 600 terminal_width: Option<usize>,
74b04a01 601 macro_backtrace: bool,
48663c56 602 ) -> EmitterWriter {
c30ab7b3 603 EmitterWriter {
48663c56 604 dst: Raw(dst, colored),
a1dfa0c6 605 sm: source_map,
2c00a5a8
XL
606 short_message,
607 teach,
0531ce1d 608 ui_testing: false,
e1599b0c 609 terminal_width,
74b04a01 610 macro_backtrace,
0531ce1d
XL
611 }
612 }
613
614 pub fn ui_testing(mut self, ui_testing: bool) -> Self {
615 self.ui_testing = ui_testing;
616 self
617 }
618
619 fn maybe_anonymized(&self, line_num: usize) -> String {
60c5eb7d 620 if self.ui_testing { ANONYMIZED_LINE_NUM.to_string() } else { line_num.to_string() }
a7813a04
XL
621 }
622
e1599b0c
XL
623 fn draw_line(
624 &self,
625 buffer: &mut StyledBuffer,
626 source_string: &str,
627 line_index: usize,
628 line_offset: usize,
629 width_offset: usize,
630 code_offset: usize,
631 margin: Margin,
632 ) {
633 let line_len = source_string.len();
634 // Create the source line we will highlight.
635 let left = margin.left(line_len);
636 let right = margin.right(line_len);
637 // On long lines, we strip the source line, accounting for unicode.
638 let mut taken = 0;
60c5eb7d
XL
639 let code: String = source_string
640 .chars()
641 .skip(left)
642 .take_while(|ch| {
dfeec247
XL
643 // Make sure that the trimming on the right will fall within the terminal width.
644 // FIXME: `unicode_width` sometimes disagrees with terminals on how wide a `char` is.
645 // For now, just accept that sometimes the code line will be longer than desired.
60c5eb7d
XL
646 let next = unicode_width::UnicodeWidthChar::width(*ch).unwrap_or(1);
647 if taken + next > right - left {
648 return false;
649 }
650 taken += next;
651 true
652 })
653 .collect();
e1599b0c
XL
654 buffer.puts(line_offset, code_offset, &code, Style::Quotation);
655 if margin.was_cut_left() {
656 // We have stripped some code/whitespace from the beginning, make it clear.
657 buffer.puts(line_offset, code_offset, "...", Style::LineNumber);
658 }
659 if margin.was_cut_right(line_len) {
660 // We have stripped some code after the right-most span end, make it clear we did so.
661 buffer.puts(line_offset, code_offset + taken - 3, "...", Style::LineNumber);
662 }
663 buffer.puts(line_offset, 0, &self.maybe_anonymized(line_index), Style::LineNumber);
664
665 draw_col_separator(buffer, line_offset, width_offset - 2);
666 }
667
668 fn render_source_line(
669 &self,
670 buffer: &mut StyledBuffer,
671 file: Lrc<SourceFile>,
672 line: &Line,
673 width_offset: usize,
674 code_offset: usize,
675 margin: Margin,
676 ) -> Vec<(usize, Style)> {
677 // Draw:
678 //
679 // LL | ... code ...
680 // | ^^-^ span label
681 // | |
682 // | secondary span label
683 //
684 // ^^ ^ ^^^ ^^^^ ^^^ we don't care about code too far to the right of a span, we trim it
685 // | | | |
686 // | | | actual code found in your source code and the spans we use to mark it
687 // | | when there's too much wasted space to the left, trim it
688 // | vertical divider between the column number and the code
689 // column number
690
2c00a5a8
XL
691 if line.line_index == 0 {
692 return Vec::new();
693 }
694
7cac9316
XL
695 let source_string = match file.get_line(line.line_index - 1) {
696 Some(s) => s,
697 None => return Vec::new(),
698 };
5bcae85e
SL
699
700 let line_offset = buffer.num_lines();
c1a9b12d 701
e1599b0c
XL
702 let left = margin.left(source_string.len()); // Left trim
703 // Account for unicode characters of width !=0 that were removed.
60c5eb7d
XL
704 let left = source_string
705 .chars()
706 .take(left)
e74abb32
XL
707 .map(|ch| unicode_width::UnicodeWidthChar::width(ch).unwrap_or(1))
708 .sum();
5bcae85e 709
e1599b0c
XL
710 self.draw_line(
711 buffer,
712 &source_string,
713 line.line_index,
714 line_offset,
715 width_offset,
716 code_offset,
717 margin,
718 );
5bcae85e 719
cc61c64b
XL
720 // Special case when there's only one annotation involved, it is the start of a multiline
721 // span and there's no text at the beginning of the code line. Instead of doing the whole
722 // graph:
723 //
724 // 2 | fn foo() {
725 // | _^
726 // 3 | |
727 // 4 | | }
728 // | |_^ test
729 //
730 // we simplify the output to:
731 //
732 // 2 | / fn foo() {
733 // 3 | |
734 // 4 | | }
735 // | |_^ test
e74abb32
XL
736 if let [ann] = &line.annotations[..] {
737 if let AnnotationType::MultilineStart(depth) = ann.annotation_type {
738 if source_string.chars().take(ann.start_col).all(|c| c.is_whitespace()) {
739 let style = if ann.is_primary {
740 Style::UnderlinePrimary
741 } else {
742 Style::UnderlineSecondary
743 };
744 buffer.putc(line_offset, width_offset + depth - 1, '/', style);
745 return vec![(depth, style)];
cc61c64b
XL
746 }
747 }
748 }
749
5bcae85e
SL
750 // We want to display like this:
751 //
752 // vec.push(vec.pop().unwrap());
476ff2be 753 // --- ^^^ - previous borrow ends here
5bcae85e
SL
754 // | |
755 // | error occurs here
756 // previous borrow of `vec` occurs here
757 //
758 // But there are some weird edge cases to be aware of:
759 //
760 // vec.push(vec.pop().unwrap());
761 // -------- - previous borrow ends here
762 // ||
763 // |this makes no sense
764 // previous borrow of `vec` occurs here
765 //
766 // For this reason, we group the lines into "highlight lines"
cc61c64b 767 // and "annotations lines", where the highlight lines have the `^`.
5bcae85e
SL
768
769 // Sort the annotations by (start, end col)
3b2f2976
XL
770 // The labels are reversed, sort and then reversed again.
771 // Consider a list of annotations (A1, A2, C1, C2, B1, B2) where
772 // the letter signifies the span. Here we are only sorting by the
773 // span and hence, the order of the elements with the same span will
774 // not change. On reversing the ordering (|a, b| but b.cmp(a)), you get
775 // (C1, C2, B1, B2, A1, A2). All the elements with the same span are
776 // still ordered first to last, but all the elements with different
777 // spans are ordered by their spans in last to first order. Last to
778 // first order is important, because the jiggly lines and | are on
779 // the left, so the rightmost span needs to be rendered first,
780 // otherwise the lines would end up needing to go over a message.
781
5bcae85e 782 let mut annotations = line.annotations.clone();
8faf50e0 783 annotations.sort_by_key(|a| Reverse(a.start_col));
5bcae85e 784
476ff2be
SL
785 // First, figure out where each label will be positioned.
786 //
787 // In the case where you have the following annotations:
788 //
789 // vec.push(vec.pop().unwrap());
790 // -------- - previous borrow ends here [C]
791 // ||
792 // |this makes no sense [B]
793 // previous borrow of `vec` occurs here [A]
794 //
795 // `annotations_position` will hold [(2, A), (1, B), (0, C)].
796 //
797 // We try, when possible, to stick the rightmost annotation at the end
798 // of the highlight line:
5bcae85e
SL
799 //
800 // vec.push(vec.pop().unwrap());
801 // --- --- - previous borrow ends here
802 //
803 // But sometimes that's not possible because one of the other
804 // annotations overlaps it. For example, from the test
805 // `span_overlap_label`, we have the following annotations
806 // (written on distinct lines for clarity):
807 //
808 // fn foo(x: u32) {
809 // --------------
810 // -
811 //
812 // In this case, we can't stick the rightmost-most label on
813 // the highlight line, or we would get:
814 //
815 // fn foo(x: u32) {
816 // -------- x_span
817 // |
818 // fn_span
819 //
820 // which is totally weird. Instead we want:
821 //
822 // fn foo(x: u32) {
823 // --------------
824 // | |
825 // | x_span
826 // fn_span
827 //
828 // which is...less weird, at least. In fact, in general, if
829 // the rightmost span overlaps with any other span, we should
830 // use the "hang below" version, so we can at least make it
32a655c1
SL
831 // clear where the span *starts*. There's an exception for this
832 // logic, when the labels do not have a message:
833 //
834 // fn foo(x: u32) {
835 // --------------
836 // |
837 // x_span
838 //
839 // instead of:
840 //
841 // fn foo(x: u32) {
842 // --------------
843 // | |
844 // | x_span
845 // <EMPTY LINE>
846 //
476ff2be
SL
847 let mut annotations_position = vec![];
848 let mut line_len = 0;
849 let mut p = 0;
8bb4bdeb
XL
850 for (i, annotation) in annotations.iter().enumerate() {
851 for (j, next) in annotations.iter().enumerate() {
852 if overlaps(next, annotation, 0) // This label overlaps with another one and both
cc61c64b
XL
853 && annotation.has_label() // take space (they have text and are not
854 && j > i // multiline lines).
60c5eb7d
XL
855 && p == 0
856 // We're currently on the first line, move the label one line down
32a655c1 857 {
48663c56
XL
858 // If we're overlapping with an un-labelled annotation with the same span
859 // we can just merge them in the output
860 if next.start_col == annotation.start_col
60c5eb7d
XL
861 && next.end_col == annotation.end_col
862 && !next.has_label()
48663c56
XL
863 {
864 continue;
865 }
866
32a655c1 867 // This annotation needs a new line in the output.
476ff2be 868 p += 1;
8bb4bdeb 869 break;
a7813a04 870 }
c1a9b12d 871 }
476ff2be 872 annotations_position.push((p, annotation));
8bb4bdeb 873 for (j, next) in annotations.iter().enumerate() {
60c5eb7d 874 if j > i {
e74abb32 875 let l = next.label.as_ref().map_or(0, |label| label.len() + 2);
cc61c64b 876 if (overlaps(next, annotation, l) // Do not allow two labels to be in the same
8bb4bdeb
XL
877 // line if they overlap including padding, to
878 // avoid situations like:
879 //
880 // fn foo(x: u32) {
881 // -------^------
882 // | |
883 // fn_spanx_span
884 //
8bb4bdeb 885 && annotation.has_label() // Both labels must have some text, otherwise
cc61c64b
XL
886 && next.has_label()) // they are not overlapping.
887 // Do not add a new line if this annotation
888 // or the next are vertical line placeholders.
889 || (annotation.takes_space() // If either this or the next annotation is
890 && next.has_label()) // multiline start/end, move it to a new line
891 || (annotation.has_label() // so as not to overlap the orizontal lines.
892 && next.takes_space())
041b39d2
XL
893 || (annotation.takes_space() && next.takes_space())
894 || (overlaps(next, annotation, l)
895 && next.end_col <= annotation.end_col
896 && next.has_label()
60c5eb7d
XL
897 && p == 0)
898 // Avoid #42595.
8bb4bdeb 899 {
cc61c64b 900 // This annotation needs a new line in the output.
8bb4bdeb
XL
901 p += 1;
902 break;
903 }
476ff2be
SL
904 }
905 }
e74abb32 906 line_len = max(line_len, p);
476ff2be 907 }
cc61c64b 908
476ff2be
SL
909 if line_len != 0 {
910 line_len += 1;
5bcae85e
SL
911 }
912
476ff2be
SL
913 // If there are no annotations or the only annotations on this line are
914 // MultilineLine, then there's only code being shown, stop processing.
8faf50e0 915 if line.annotations.iter().all(|a| a.is_line()) {
cc61c64b 916 return vec![];
5bcae85e
SL
917 }
918
60c5eb7d 919 // Write the column separator.
32a655c1
SL
920 //
921 // After this we will have:
922 //
923 // 2 | fn foo() {
924 // |
925 // |
926 // |
927 // 3 |
928 // 4 | }
929 // |
0731742a 930 for pos in 0..=line_len {
476ff2be 931 draw_col_separator(buffer, line_offset + pos + 1, width_offset - 2);
60c5eb7d 932 buffer.putc(line_offset + pos + 1, width_offset - 2, '|', Style::LineNumber);
476ff2be
SL
933 }
934
935 // Write the horizontal lines for multiline annotations
936 // (only the first and last lines need this).
937 //
938 // After this we will have:
939 //
940 // 2 | fn foo() {
941 // | __________
942 // |
943 // |
944 // 3 |
945 // 4 | }
946 // | _
947 for &(pos, annotation) in &annotations_position {
948 let style = if annotation.is_primary {
949 Style::UnderlinePrimary
950 } else {
951 Style::UnderlineSecondary
952 };
953 let pos = pos + 1;
954 match annotation.annotation_type {
60c5eb7d 955 AnnotationType::MultilineStart(depth) | AnnotationType::MultilineEnd(depth) => {
e1599b0c
XL
956 draw_range(
957 buffer,
958 '_',
959 line_offset + pos,
960 width_offset + depth,
961 code_offset + annotation.start_col - left,
962 style,
963 );
476ff2be 964 }
2c00a5a8 965 _ if self.teach => {
e1599b0c
XL
966 buffer.set_style_range(
967 line_offset,
968 code_offset + annotation.start_col - left,
969 code_offset + annotation.end_col - left,
970 style,
971 annotation.is_primary,
972 );
2c00a5a8
XL
973 }
974 _ => {}
476ff2be
SL
975 }
976 }
977
cc61c64b 978 // Write the vertical lines for labels that are on a different line as the underline.
476ff2be
SL
979 //
980 // After this we will have:
981 //
982 // 2 | fn foo() {
983 // | __________
984 // | | |
985 // | |
60c5eb7d 986 // 3 | |
476ff2be
SL
987 // 4 | | }
988 // | |_
989 for &(pos, annotation) in &annotations_position {
990 let style = if annotation.is_primary {
991 Style::UnderlinePrimary
992 } else {
993 Style::UnderlineSecondary
994 };
995 let pos = pos + 1;
32a655c1 996
cc61c64b 997 if pos > 1 && (annotation.has_label() || annotation.takes_space()) {
0731742a 998 for p in line_offset + 1..=line_offset + pos {
60c5eb7d
XL
999 buffer.putc(
1000 p,
1001 (code_offset + annotation.start_col).saturating_sub(left),
1002 '|',
1003 style,
1004 );
476ff2be
SL
1005 }
1006 }
1007 match annotation.annotation_type {
1008 AnnotationType::MultilineStart(depth) => {
1009 for p in line_offset + pos + 1..line_offset + line_len + 2 {
60c5eb7d 1010 buffer.putc(p, width_offset + depth - 1, '|', style);
476ff2be
SL
1011 }
1012 }
1013 AnnotationType::MultilineEnd(depth) => {
0731742a 1014 for p in line_offset..=line_offset + pos {
60c5eb7d 1015 buffer.putc(p, width_offset + depth - 1, '|', style);
476ff2be
SL
1016 }
1017 }
476ff2be
SL
1018 _ => (),
1019 }
1020 }
1021
1022 // Write the labels on the annotations that actually have a label.
1023 //
1024 // After this we will have:
1025 //
1026 // 2 | fn foo() {
cc61c64b
XL
1027 // | __________
1028 // | |
1029 // | something about `foo`
1030 // 3 |
1031 // 4 | }
1032 // | _ test
476ff2be 1033 for &(pos, annotation) in &annotations_position {
60c5eb7d
XL
1034 let style =
1035 if annotation.is_primary { Style::LabelPrimary } else { Style::LabelSecondary };
476ff2be 1036 let (pos, col) = if pos == 0 {
e74abb32 1037 (pos + 1, (annotation.end_col + 1).saturating_sub(left))
476ff2be 1038 } else {
e74abb32 1039 (pos + 2, annotation.start_col.saturating_sub(left))
476ff2be
SL
1040 };
1041 if let Some(ref label) = annotation.label {
e1599b0c 1042 buffer.puts(line_offset + pos, code_offset + col, &label, style);
476ff2be
SL
1043 }
1044 }
1045
1046 // Sort from biggest span to smallest span so that smaller spans are
1047 // represented in the output:
1048 //
1049 // x | fn foo()
1050 // | ^^^---^^
1051 // | | |
1052 // | | something about `foo`
1053 // | something about `fn foo()`
e74abb32
XL
1054 annotations_position.sort_by_key(|(_, ann)| {
1055 // Decreasing order. When annotations share the same length, prefer `Primary`.
1056 (Reverse(ann.len()), ann.is_primary)
476ff2be 1057 });
5bcae85e 1058
476ff2be
SL
1059 // Write the underlines.
1060 //
1061 // After this we will have:
1062 //
1063 // 2 | fn foo() {
cc61c64b
XL
1064 // | ____-_____^
1065 // | |
1066 // | something about `foo`
1067 // 3 |
1068 // 4 | }
1069 // | _^ test
476ff2be
SL
1070 for &(_, annotation) in &annotations_position {
1071 let (underline, style) = if annotation.is_primary {
1072 ('^', Style::UnderlinePrimary)
5bcae85e 1073 } else {
476ff2be
SL
1074 ('-', Style::UnderlineSecondary)
1075 };
1076 for p in annotation.start_col..annotation.end_col {
e1599b0c
XL
1077 buffer.putc(
1078 line_offset + 1,
e74abb32 1079 (code_offset + p).saturating_sub(left),
e1599b0c
XL
1080 underline,
1081 style,
1082 );
c1a9b12d
SL
1083 }
1084 }
60c5eb7d
XL
1085 annotations_position
1086 .iter()
1087 .filter_map(|&(_, annotation)| match annotation.annotation_type {
cc61c64b
XL
1088 AnnotationType::MultilineStart(p) | AnnotationType::MultilineEnd(p) => {
1089 let style = if annotation.is_primary {
1090 Style::LabelPrimary
1091 } else {
1092 Style::LabelSecondary
1093 };
1094 Some((p, style))
abe05a73 1095 }
60c5eb7d
XL
1096 _ => None,
1097 })
1098 .collect::<Vec<_>>()
5bcae85e
SL
1099 }
1100
1101 fn get_multispan_max_line_num(&mut self, msp: &MultiSpan) -> usize {
e74abb32
XL
1102 let sm = match self.sm {
1103 Some(ref sm) => sm,
1104 None => return 0,
1105 };
1106
5bcae85e 1107 let mut max = 0;
e74abb32
XL
1108 for primary_span in msp.primary_spans() {
1109 if !primary_span.is_dummy() {
1110 let hi = sm.lookup_char_pos(primary_span.hi());
1111 max = (hi.line).max(max);
5bcae85e 1112 }
e74abb32
XL
1113 }
1114 if !self.short_message {
1115 for span_label in msp.span_labels() {
1116 if !span_label.span.is_dummy() {
1117 let hi = sm.lookup_char_pos(span_label.span.hi());
1118 max = (hi.line).max(max);
a7813a04 1119 }
7453a54e 1120 }
c1a9b12d 1121 }
e74abb32 1122
5bcae85e 1123 max
c1a9b12d
SL
1124 }
1125
8faf50e0 1126 fn get_max_line_num(&mut self, span: &MultiSpan, children: &[SubDiagnostic]) -> usize {
9e0c209e 1127 let primary = self.get_multispan_max_line_num(span);
60c5eb7d
XL
1128 children
1129 .iter()
e74abb32
XL
1130 .map(|sub| self.get_multispan_max_line_num(&sub.span))
1131 .max()
1132 .unwrap_or(0)
1133 .max(primary)
c1a9b12d
SL
1134 }
1135
9fa01778 1136 /// Adds a left margin to every line but the first, given a padding length and the label being
32a655c1 1137 /// displayed, keeping the provided highlighting.
60c5eb7d
XL
1138 fn msg_to_buffer(
1139 &self,
1140 buffer: &mut StyledBuffer,
1141 msg: &[(String, Style)],
1142 padding: usize,
1143 label: &str,
1144 override_style: Option<Style>,
1145 ) {
32a655c1
SL
1146 // The extra 5 ` ` is padding that's always needed to align to the `note: `:
1147 //
1148 // error: message
1149 // --> file.rs:13:20
1150 // |
1151 // 13 | <CODE>
1152 // | ^^^^
1153 // |
1154 // = note: multiline
1155 // message
1156 // ++^^^----xx
1157 // | | | |
1158 // | | | magic `2`
1159 // | | length of label
1160 // | magic `3`
1161 // `max_line_num_len`
8faf50e0 1162 let padding = " ".repeat(padding + label.len() + 5);
32a655c1 1163
e74abb32
XL
1164 /// Returns `override` if it is present and `style` is `NoStyle` or `style` otherwise
1165 fn style_or_override(style: Style, override_: Option<Style>) -> Style {
1166 match (style, override_) {
1167 (Style::NoStyle, Some(override_)) => override_,
1168 _ => style,
32a655c1 1169 }
32a655c1
SL
1170 }
1171
1172 let mut line_number = 0;
1173
1174 // Provided the following diagnostic message:
1175 //
1176 // let msg = vec![
1177 // ("
1178 // ("highlighted multiline\nstring to\nsee how it ", Style::NoStyle),
1179 // ("looks", Style::Highlight),
1180 // ("with\nvery ", Style::NoStyle),
1181 // ("weird", Style::Highlight),
1182 // (" formats\n", Style::NoStyle),
1183 // ("see?", Style::Highlight),
1184 // ];
1185 //
ff7c6d11 1186 // the expected output on a note is (* surround the highlighted text)
32a655c1
SL
1187 //
1188 // = note: highlighted multiline
1189 // string to
1190 // see how it *looks* with
1191 // very *weird* formats
1192 // see?
1193 for &(ref text, ref style) in msg.iter() {
1194 let lines = text.split('\n').collect::<Vec<_>>();
1195 if lines.len() > 1 {
1196 for (i, line) in lines.iter().enumerate() {
1197 if i != 0 {
1198 line_number += 1;
1199 buffer.append(line_number, &padding, Style::NoStyle);
1200 }
1201 buffer.append(line_number, line, style_or_override(*style, override_style));
1202 }
1203 } else {
1204 buffer.append(line_number, text, style_or_override(*style, override_style));
1205 }
1206 }
1207 }
1208
9fa01778
XL
1209 fn emit_message_default(
1210 &mut self,
1211 msp: &MultiSpan,
1212 msg: &[(String, Style)],
1213 code: &Option<DiagnosticId>,
1214 level: &Level,
1215 max_line_num_len: usize,
1216 is_secondary: bool,
1217 ) -> io::Result<()> {
5bcae85e 1218 let mut buffer = StyledBuffer::new();
60c5eb7d 1219 let header_style = if is_secondary { Style::HeaderMsg } else { Style::MainHeaderMsg };
5bcae85e 1220
60c5eb7d
XL
1221 if !msp.has_primary_spans() && !msp.has_span_labels() && is_secondary && !self.short_message
1222 {
5bcae85e
SL
1223 // This is a secondary message with no span info
1224 for _ in 0..max_line_num_len {
1225 buffer.prepend(0, " ", Style::NoStyle);
1226 }
1227 draw_note_separator(&mut buffer, 0, max_line_num_len + 1);
e1599b0c
XL
1228 if *level != Level::FailureNote {
1229 let level_str = level.to_string();
1230 if !level_str.is_empty() {
1231 buffer.append(0, &level_str, Style::MainHeaderMsg);
1232 buffer.append(0, ": ", Style::NoStyle);
1233 }
0531ce1d 1234 }
32a655c1 1235 self.msg_to_buffer(&mut buffer, msg, max_line_num_len, "note", None);
c30ab7b3 1236 } else {
0531ce1d 1237 let level_str = level.to_string();
e1599b0c
XL
1238 // The failure note level itself does not provide any useful diagnostic information
1239 if *level != Level::FailureNote && !level_str.is_empty() {
dfeec247 1240 buffer.append(0, &level_str, Style::Level(*level));
0531ce1d 1241 }
abe05a73
XL
1242 // only render error codes, not lint codes
1243 if let Some(DiagnosticId::Error(ref code)) = *code {
dfeec247
XL
1244 buffer.append(0, "[", Style::Level(*level));
1245 buffer.append(0, &code, Style::Level(*level));
1246 buffer.append(0, "]", Style::Level(*level));
5bcae85e 1247 }
e1599b0c 1248 if *level != Level::FailureNote && !level_str.is_empty() {
8faf50e0 1249 buffer.append(0, ": ", header_style);
0531ce1d 1250 }
32a655c1 1251 for &(ref text, _) in msg.iter() {
8faf50e0 1252 buffer.append(0, text, header_style);
32a655c1 1253 }
5bcae85e
SL
1254 }
1255
dc9dc135 1256 let mut annotated_files = FileWithAnnotatedLines::collect_annotations(msp, &self.sm);
a7813a04 1257
5bcae85e 1258 // Make sure our primary file comes first
a1dfa0c6 1259 let (primary_lo, sm) = if let (Some(sm), Some(ref primary_span)) =
60c5eb7d
XL
1260 (self.sm.as_ref(), msp.primary_span().as_ref())
1261 {
8faf50e0 1262 if !primary_span.is_dummy() {
a1dfa0c6 1263 (sm.lookup_char_pos(primary_span.lo()), sm)
5bcae85e 1264 } else {
abe05a73 1265 emit_to_destination(&buffer.render(), level, &mut self.dst, self.short_message)?;
5bcae85e 1266 return Ok(());
c30ab7b3
SL
1267 }
1268 } else {
1269 // If we don't have span information, emit and exit
abe05a73 1270 emit_to_destination(&buffer.render(), level, &mut self.dst, self.short_message)?;
c30ab7b3
SL
1271 return Ok(());
1272 };
5bcae85e 1273 if let Ok(pos) =
60c5eb7d
XL
1274 annotated_files.binary_search_by(|x| x.file.name.cmp(&primary_lo.file.name))
1275 {
5bcae85e
SL
1276 annotated_files.swap(0, pos);
1277 }
1278
1279 // Print out the annotate source lines that correspond with the error
1280 for annotated_file in annotated_files {
7cac9316 1281 // we can't annotate anything if the source is unavailable.
a1dfa0c6 1282 if !sm.ensure_source_file_source_present(annotated_file.file.clone()) {
7cac9316
XL
1283 continue;
1284 }
1285
5bcae85e
SL
1286 // print out the span location and spacer before we print the annotated source
1287 // to do this, we need to know if this span will be primary
1288 let is_primary = primary_lo.file.name == annotated_file.file.name;
1289 if is_primary {
5bcae85e 1290 let loc = primary_lo.clone();
abe05a73
XL
1291 if !self.short_message {
1292 // remember where we are in the output buffer for easy reference
1293 let buffer_msg_line_offset = buffer.num_lines();
1294
1295 buffer.prepend(buffer_msg_line_offset, "--> ", Style::LineNumber);
e1599b0c
XL
1296 buffer.append(
1297 buffer_msg_line_offset,
1298 &format!(
1299 "{}:{}:{}",
1300 loc.file.name,
1301 sm.doctest_offset_line(&loc.file.name, loc.line),
1302 loc.col.0 + 1,
1303 ),
1304 Style::LineAndColumn,
1305 );
abe05a73
XL
1306 for _ in 0..max_line_num_len {
1307 buffer.prepend(buffer_msg_line_offset, " ", Style::NoStyle);
1308 }
1309 } else {
e1599b0c
XL
1310 buffer.prepend(
1311 0,
1312 &format!(
1313 "{}:{}:{}: ",
1314 loc.file.name,
1315 sm.doctest_offset_line(&loc.file.name, loc.line),
1316 loc.col.0 + 1,
1317 ),
1318 Style::LineAndColumn,
1319 );
5bcae85e 1320 }
abe05a73 1321 } else if !self.short_message {
5bcae85e
SL
1322 // remember where we are in the output buffer for easy reference
1323 let buffer_msg_line_offset = buffer.num_lines();
1324
1325 // Add spacing line
1326 draw_col_separator(&mut buffer, buffer_msg_line_offset, max_line_num_len + 1);
1327
1328 // Then, the secondary file indicator
1329 buffer.prepend(buffer_msg_line_offset + 1, "::: ", Style::LineNumber);
2c00a5a8
XL
1330 let loc = if let Some(first_line) = annotated_file.lines.first() {
1331 let col = if let Some(first_annotation) = first_line.annotations.first() {
1332 format!(":{}", first_annotation.start_col + 1)
1333 } else {
b7449926 1334 String::new()
2c00a5a8 1335 };
60c5eb7d
XL
1336 format!(
1337 "{}:{}{}",
1338 annotated_file.file.name,
1339 sm.doctest_offset_line(&annotated_file.file.name, first_line.line_index),
1340 col
1341 )
2c00a5a8
XL
1342 } else {
1343 annotated_file.file.name.to_string()
1344 };
60c5eb7d 1345 buffer.append(buffer_msg_line_offset + 1, &loc, Style::LineAndColumn);
5bcae85e
SL
1346 for _ in 0..max_line_num_len {
1347 buffer.prepend(buffer_msg_line_offset + 1, " ", Style::NoStyle);
c1a9b12d 1348 }
a7813a04 1349 }
c1a9b12d 1350
abe05a73
XL
1351 if !self.short_message {
1352 // Put in the spacer between the location and annotated source
1353 let buffer_msg_line_offset = buffer.num_lines();
60c5eb7d
XL
1354 draw_col_separator_no_space(
1355 &mut buffer,
1356 buffer_msg_line_offset,
1357 max_line_num_len + 1,
1358 );
5bcae85e 1359
abe05a73 1360 // Contains the vertical lines' positions for active multiline annotations
b7449926 1361 let mut multilines = FxHashMap::default();
cc61c64b 1362
e1599b0c 1363 // Get the left-side margin to remove it
ba9703b0 1364 let mut whitespace_margin = usize::MAX;
e1599b0c
XL
1365 for line_idx in 0..annotated_file.lines.len() {
1366 let file = annotated_file.file.clone();
1367 let line = &annotated_file.lines[line_idx];
1368 if let Some(source_string) = file.get_line(line.line_index - 1) {
60c5eb7d
XL
1369 let leading_whitespace =
1370 source_string.chars().take_while(|c| c.is_whitespace()).count();
e1599b0c 1371 if source_string.chars().any(|c| !c.is_whitespace()) {
60c5eb7d 1372 whitespace_margin = min(whitespace_margin, leading_whitespace);
e1599b0c
XL
1373 }
1374 }
1375 }
ba9703b0 1376 if whitespace_margin == usize::MAX {
e1599b0c
XL
1377 whitespace_margin = 0;
1378 }
1379
1380 // Left-most column any visible span points at.
ba9703b0 1381 let mut span_left_margin = usize::MAX;
e1599b0c
XL
1382 for line in &annotated_file.lines {
1383 for ann in &line.annotations {
1384 span_left_margin = min(span_left_margin, ann.start_col);
1385 span_left_margin = min(span_left_margin, ann.end_col);
1386 }
1387 }
ba9703b0 1388 if span_left_margin == usize::MAX {
e1599b0c
XL
1389 span_left_margin = 0;
1390 }
1391
1392 // Right-most column any visible span points at.
1393 let mut span_right_margin = 0;
1394 let mut label_right_margin = 0;
1395 let mut max_line_len = 0;
1396 for line in &annotated_file.lines {
60c5eb7d
XL
1397 max_line_len = max(
1398 max_line_len,
1399 annotated_file.file.get_line(line.line_index - 1).map_or(0, |s| s.len()),
1400 );
e1599b0c
XL
1401 for ann in &line.annotations {
1402 span_right_margin = max(span_right_margin, ann.start_col);
1403 span_right_margin = max(span_right_margin, ann.end_col);
1404 // FIXME: account for labels not in the same line
e74abb32 1405 let label_right = ann.label.as_ref().map_or(0, |l| l.len() + 1);
e1599b0c
XL
1406 label_right_margin = max(label_right_margin, ann.end_col + label_right);
1407 }
1408 }
1409
1410 let width_offset = 3 + max_line_num_len;
1411 let code_offset = if annotated_file.multiline_depth == 0 {
1412 width_offset
1413 } else {
1414 width_offset + annotated_file.multiline_depth + 1
1415 };
1416
1417 let column_width = if let Some(width) = self.terminal_width {
1418 width.saturating_sub(code_offset)
1419 } else if self.ui_testing {
1420 140
1421 } else {
74b04a01 1422 termize::dimensions()
e1599b0c 1423 .map(|(w, _)| w.saturating_sub(code_offset))
ba9703b0 1424 .unwrap_or(usize::MAX)
e1599b0c
XL
1425 };
1426
1427 let margin = Margin::new(
1428 whitespace_margin,
1429 span_left_margin,
1430 span_right_margin,
1431 label_right_margin,
1432 column_width,
1433 max_line_len,
1434 );
1435
abe05a73
XL
1436 // Next, output the annotate source for this file
1437 for line_idx in 0..annotated_file.lines.len() {
1438 let previous_buffer_line = buffer.num_lines();
cc61c64b 1439
e1599b0c
XL
1440 let depths = self.render_source_line(
1441 &mut buffer,
1442 annotated_file.file.clone(),
1443 &annotated_file.lines[line_idx],
1444 width_offset,
1445 code_offset,
1446 margin,
1447 );
cc61c64b 1448
b7449926 1449 let mut to_add = FxHashMap::default();
5bcae85e 1450
abe05a73
XL
1451 for (depth, style) in depths {
1452 if multilines.get(&depth).is_some() {
1453 multilines.remove(&depth);
1454 } else {
1455 to_add.insert(depth, style);
1456 }
cc61c64b 1457 }
cc61c64b 1458
abe05a73
XL
1459 // Set the multiline annotation vertical lines to the left of
1460 // the code in this line.
1461 for (depth, style) in &multilines {
1462 for line in previous_buffer_line..buffer.num_lines() {
60c5eb7d 1463 draw_multiline_line(&mut buffer, line, width_offset, *depth, *style);
cc61c64b 1464 }
abe05a73
XL
1465 }
1466 // check to see if we need to print out or elide lines that come between
1467 // this annotated line and the next one.
1468 if line_idx < (annotated_file.lines.len() - 1) {
60c5eb7d
XL
1469 let line_idx_delta = annotated_file.lines[line_idx + 1].line_index
1470 - annotated_file.lines[line_idx].line_index;
abe05a73
XL
1471 if line_idx_delta > 2 {
1472 let last_buffer_line_num = buffer.num_lines();
1473 buffer.puts(last_buffer_line_num, 0, "...", Style::LineNumber);
1474
1475 // Set the multiline annotation vertical lines on `...` bridging line.
1476 for (depth, style) in &multilines {
60c5eb7d
XL
1477 draw_multiline_line(
1478 &mut buffer,
1479 last_buffer_line_num,
1480 width_offset,
1481 *depth,
1482 *style,
1483 );
abe05a73
XL
1484 }
1485 } else if line_idx_delta == 2 {
60c5eb7d
XL
1486 let unannotated_line = annotated_file
1487 .file
abe05a73
XL
1488 .get_line(annotated_file.lines[line_idx].line_index)
1489 .unwrap_or_else(|| Cow::from(""));
1490
1491 let last_buffer_line_num = buffer.num_lines();
1492
e1599b0c
XL
1493 self.draw_line(
1494 &mut buffer,
1495 &unannotated_line,
1496 annotated_file.lines[line_idx + 1].line_index - 1,
1497 last_buffer_line_num,
1498 width_offset,
1499 code_offset,
1500 margin,
1501 );
abe05a73
XL
1502
1503 for (depth, style) in &multilines {
e1599b0c
XL
1504 draw_multiline_line(
1505 &mut buffer,
1506 last_buffer_line_num,
1507 width_offset,
1508 *depth,
1509 *style,
1510 );
abe05a73 1511 }
cc61c64b 1512 }
c1a9b12d 1513 }
cc61c64b 1514
abe05a73
XL
1515 multilines.extend(&to_add);
1516 }
7453a54e
SL
1517 }
1518 }
5bcae85e 1519
5bcae85e 1520 // final step: take our styled buffer, render it, then output it
abe05a73 1521 emit_to_destination(&buffer.render(), level, &mut self.dst, self.short_message)?;
5bcae85e
SL
1522
1523 Ok(())
1524 }
ff7c6d11 1525
9fa01778
XL
1526 fn emit_suggestion_default(
1527 &mut self,
1528 suggestion: &CodeSuggestion,
1529 level: &Level,
1530 max_line_num_len: usize,
1531 ) -> io::Result<()> {
e74abb32
XL
1532 let sm = match self.sm {
1533 Some(ref sm) => sm,
60c5eb7d 1534 None => return Ok(()),
e74abb32 1535 };
5bcae85e 1536
60c5eb7d
XL
1537 // Render the replacements for each suggestion
1538 let suggestions = suggestion.splice_lines(&**sm);
ba9703b0 1539 debug!("emit_suggestion_default: suggestions={:?}", suggestions);
60c5eb7d
XL
1540
1541 if suggestions.is_empty() {
1542 // Suggestions coming from macros can have malformed spans. This is a heavy handed
1543 // approach to avoid ICEs by ignoring the suggestion outright.
1544 return Ok(());
1545 }
1546
e74abb32
XL
1547 let mut buffer = StyledBuffer::new();
1548
1549 // Render the suggestion message
1550 let level_str = level.to_string();
1551 if !level_str.is_empty() {
dfeec247 1552 buffer.append(0, &level_str, Style::Level(*level));
e74abb32
XL
1553 buffer.append(0, ": ", Style::HeaderMsg);
1554 }
1555 self.msg_to_buffer(
1556 &mut buffer,
1557 &[(suggestion.msg.to_owned(), Style::NoStyle)],
1558 max_line_num_len,
1559 "suggestion",
1560 Some(Style::HeaderMsg),
1561 );
1562
e74abb32
XL
1563 let mut row_num = 2;
1564 let mut notice_capitalization = false;
1565 for (complete, parts, only_capitalization) in suggestions.iter().take(MAX_SUGGESTIONS) {
1566 notice_capitalization |= only_capitalization;
1567 // Only show underline if the suggestion spans a single line and doesn't cover the
1568 // entirety of the code output. If you have multiple replacements in the same line
1569 // of code, show the underline.
60c5eb7d 1570 let show_underline = !(parts.len() == 1 && parts[0].snippet.trim() == complete.trim())
e74abb32
XL
1571 && complete.lines().count() == 1;
1572
60c5eb7d
XL
1573 let lines = sm
1574 .span_to_lines(parts[0].span)
1575 .expect("span_to_lines failed when emitting suggestion");
e74abb32 1576
ba9703b0 1577 assert!(!lines.lines.is_empty() || parts[0].span.is_dummy());
e74abb32
XL
1578
1579 let line_start = sm.lookup_char_pos(parts[0].span.lo()).line;
1580 draw_col_separator_no_space(&mut buffer, 1, max_line_num_len + 1);
e74abb32 1581 let mut lines = complete.lines();
74b04a01
XL
1582 for (line_pos, line) in lines.by_ref().take(MAX_SUGGESTION_HIGHLIGHT_LINES).enumerate()
1583 {
e74abb32 1584 // Print the span column to avoid confusion
60c5eb7d
XL
1585 buffer.puts(
1586 row_num,
1587 0,
1588 &self.maybe_anonymized(line_start + line_pos),
1589 Style::LineNumber,
1590 );
e74abb32
XL
1591 // print the suggestion
1592 draw_col_separator(&mut buffer, row_num, max_line_num_len + 1);
1593 buffer.append(row_num, line, Style::NoStyle);
e74abb32 1594 row_num += 1;
0531ce1d 1595 }
94b46f34 1596
e74abb32
XL
1597 // This offset and the ones below need to be signed to account for replacement code
1598 // that is shorter than the original code.
dfeec247 1599 let mut offsets: Vec<(usize, isize)> = Vec::new();
e74abb32
XL
1600 // Only show an underline in the suggestions if the suggestion is not the
1601 // entirety of the code being shown and the displayed code is not multiline.
1602 if show_underline {
1603 draw_col_separator(&mut buffer, row_num, max_line_num_len + 1);
1604 for part in parts {
1605 let span_start_pos = sm.lookup_char_pos(part.span.lo()).col_display;
1606 let span_end_pos = sm.lookup_char_pos(part.span.hi()).col_display;
1607
1608 // Do not underline the leading...
60c5eb7d 1609 let start = part.snippet.len().saturating_sub(part.snippet.trim_start().len());
e74abb32
XL
1610 // ...or trailing spaces. Account for substitutions containing unicode
1611 // characters.
60c5eb7d
XL
1612 let sub_len: usize = part
1613 .snippet
1614 .trim()
1615 .chars()
e74abb32
XL
1616 .map(|ch| unicode_width::UnicodeWidthChar::width(ch).unwrap_or(1))
1617 .sum();
1618
dfeec247
XL
1619 let offset: isize = offsets
1620 .iter()
1621 .filter_map(
1622 |(start, v)| if span_start_pos <= *start { None } else { Some(v) },
1623 )
1624 .sum();
e74abb32
XL
1625 let underline_start = (span_start_pos + start) as isize + offset;
1626 let underline_end = (span_start_pos + start + sub_len) as isize + offset;
dfeec247 1627 assert!(underline_start >= 0 && underline_end >= 0);
e74abb32 1628 for p in underline_start..underline_end {
60c5eb7d
XL
1629 buffer.putc(
1630 row_num,
dfeec247 1631 ((max_line_num_len + 3) as isize + p) as usize,
60c5eb7d
XL
1632 '^',
1633 Style::UnderlinePrimary,
1634 );
e74abb32
XL
1635 }
1636 // underline removals too
1637 if underline_start == underline_end {
60c5eb7d
XL
1638 for p in underline_start - 1..underline_start + 1 {
1639 buffer.putc(
1640 row_num,
dfeec247 1641 ((max_line_num_len + 3) as isize + p) as usize,
60c5eb7d
XL
1642 '-',
1643 Style::UnderlineSecondary,
1644 );
94b46f34 1645 }
041b39d2 1646 }
5bcae85e 1647
e74abb32 1648 // length of the code after substitution
60c5eb7d
XL
1649 let full_sub_len = part
1650 .snippet
1651 .chars()
e74abb32
XL
1652 .map(|ch| unicode_width::UnicodeWidthChar::width(ch).unwrap_or(1))
1653 .sum::<usize>() as isize;
1654
1655 // length of the code to be substituted
1656 let snippet_len = span_end_pos as isize - span_start_pos as isize;
1657 // For multiple substitutions, use the position *after* the previous
dfeec247
XL
1658 // substitutions have happened, only when further substitutions are
1659 // located strictly after.
1660 offsets.push((span_end_pos, full_sub_len - snippet_len));
7cac9316 1661 }
e74abb32 1662 row_num += 1;
7cac9316 1663 }
e74abb32
XL
1664
1665 // if we elided some lines, add an ellipsis
1666 if lines.next().is_some() {
1667 buffer.puts(row_num, max_line_num_len - 1, "...", Style::LineNumber);
1668 } else if !show_underline {
1669 draw_col_separator_no_space(&mut buffer, row_num, max_line_num_len + 1);
1670 row_num += 1;
7453a54e 1671 }
c1a9b12d 1672 }
e74abb32
XL
1673 if suggestions.len() > MAX_SUGGESTIONS {
1674 let others = suggestions.len() - MAX_SUGGESTIONS;
60c5eb7d 1675 let msg = format!("and {} other candidate{}", others, pluralize!(others));
e74abb32
XL
1676 buffer.puts(row_num, max_line_num_len + 3, &msg, Style::NoStyle);
1677 } else if notice_capitalization {
1678 let msg = "notice the capitalization difference";
1679 buffer.puts(row_num, max_line_num_len + 3, &msg, Style::NoStyle);
1680 }
1681 emit_to_destination(&buffer.render(), level, &mut self.dst, self.short_message)?;
7453a54e 1682 Ok(())
c1a9b12d 1683 }
ff7c6d11 1684
e74abb32
XL
1685 fn emit_messages_default(
1686 &mut self,
1687 level: &Level,
1688 message: &[(String, Style)],
1689 code: &Option<DiagnosticId>,
1690 span: &MultiSpan,
1691 children: &[SubDiagnostic],
1692 suggestions: &[CodeSuggestion],
1693 ) {
0531ce1d
XL
1694 let max_line_num_len = if self.ui_testing {
1695 ANONYMIZED_LINE_NUM.len()
1696 } else {
1697 self.get_max_line_num(span, children).to_string().len()
1698 };
5bcae85e 1699
e74abb32 1700 match self.emit_message_default(span, message, code, level, max_line_num_len, false) {
5bcae85e 1701 Ok(()) => {
60c5eb7d
XL
1702 if !children.is_empty()
1703 || suggestions.iter().any(|s| s.style != SuggestionStyle::CompletelyHidden)
1704 {
5bcae85e 1705 let mut buffer = StyledBuffer::new();
abe05a73
XL
1706 if !self.short_message {
1707 draw_col_separator_no_space(&mut buffer, 0, max_line_num_len + 1);
1708 }
60c5eb7d
XL
1709 match emit_to_destination(
1710 &buffer.render(),
1711 level,
1712 &mut self.dst,
1713 self.short_message,
1714 ) {
5bcae85e 1715 Ok(()) => (),
60c5eb7d 1716 Err(e) => panic!("failed to emit error: {}", e),
5bcae85e
SL
1717 }
1718 }
abe05a73
XL
1719 if !self.short_message {
1720 for child in children {
1721 let span = child.render_span.as_ref().unwrap_or(&child.span);
ba9703b0 1722 if let Err(err) = self.emit_message_default(
9fa01778
XL
1723 &span,
1724 &child.styled_message(),
1725 &None,
1726 &child.level,
1727 max_line_num_len,
1728 true,
1729 ) {
ba9703b0 1730 panic!("failed to emit error: {}", err);
abe05a73
XL
1731 }
1732 }
1733 for sugg in suggestions {
9fa01778
XL
1734 if sugg.style == SuggestionStyle::CompletelyHidden {
1735 // do not display this suggestion, it is meant only for tools
1736 } else if sugg.style == SuggestionStyle::HideCodeAlways {
ba9703b0 1737 if let Err(e) = self.emit_message_default(
9fa01778
XL
1738 &MultiSpan::new(),
1739 &[(sugg.msg.to_owned(), Style::HeaderMsg)],
1740 &None,
1741 &Level::Help,
1742 max_line_num_len,
1743 true,
1744 ) {
ba9703b0 1745 panic!("failed to emit error: {}", e);
9fa01778 1746 }
ba9703b0
XL
1747 } else if let Err(e) =
1748 self.emit_suggestion_default(sugg, &Level::Help, max_line_num_len)
1749 {
1750 panic!("failed to emit error: {}", e);
1751 };
5bcae85e
SL
1752 }
1753 }
1754 }
c30ab7b3 1755 Err(e) => panic!("failed to emit error: {}", e),
5bcae85e 1756 }
0531ce1d
XL
1757
1758 let mut dst = self.dst.writable();
dc9dc135 1759 match writeln!(dst) {
5bcae85e 1760 Err(e) => panic!("failed to emit error: {}", e),
ba9703b0
XL
1761 _ => {
1762 if let Err(e) = dst.flush() {
1763 panic!("failed to emit error: {}", e)
1764 }
1765 }
c1a9b12d 1766 }
c1a9b12d 1767 }
1a4d82fc 1768}
970d7e83 1769
dc9dc135
XL
1770impl FileWithAnnotatedLines {
1771 /// Preprocess all the annotations so that they are grouped by file and by line number
1772 /// This helps us quickly iterate over the whole message (including secondary file spans)
1773 pub fn collect_annotations(
1774 msp: &MultiSpan,
60c5eb7d 1775 source_map: &Option<Lrc<SourceMap>>,
dc9dc135 1776 ) -> Vec<FileWithAnnotatedLines> {
60c5eb7d
XL
1777 fn add_annotation_to_file(
1778 file_vec: &mut Vec<FileWithAnnotatedLines>,
1779 file: Lrc<SourceFile>,
1780 line_index: usize,
1781 ann: Annotation,
1782 ) {
dc9dc135
XL
1783 for slot in file_vec.iter_mut() {
1784 // Look through each of our files for the one we're adding to
1785 if slot.file.name == file.name {
1786 // See if we already have a line for it
1787 for line_slot in &mut slot.lines {
1788 if line_slot.line_index == line_index {
1789 line_slot.annotations.push(ann);
1790 return;
1791 }
1792 }
1793 // We don't have a line yet, create one
60c5eb7d 1794 slot.lines.push(Line { line_index, annotations: vec![ann] });
dc9dc135
XL
1795 slot.lines.sort();
1796 return;
1797 }
1798 }
1799 // This is the first time we're seeing the file
1800 file_vec.push(FileWithAnnotatedLines {
1801 file,
60c5eb7d 1802 lines: vec![Line { line_index, annotations: vec![ann] }],
dc9dc135
XL
1803 multiline_depth: 0,
1804 });
1805 }
1806
1807 let mut output = vec![];
1808 let mut multiline_annotations = vec![];
1809
1810 if let Some(ref sm) = source_map {
1811 for span_label in msp.span_labels() {
1812 if span_label.span.is_dummy() {
1813 continue;
1814 }
1815
1816 let lo = sm.lookup_char_pos(span_label.span.lo());
1817 let mut hi = sm.lookup_char_pos(span_label.span.hi());
1818
1819 // Watch out for "empty spans". If we get a span like 6..6, we
1820 // want to just display a `^` at 6, so convert that to
1821 // 6..7. This is degenerate input, but it's best to degrade
1822 // gracefully -- and the parser likes to supply a span like
1823 // that for EOF, in particular.
1824
1825 if lo.col_display == hi.col_display && lo.line == hi.line {
1826 hi.col_display += 1;
1827 }
1828
e74abb32 1829 if lo.line != hi.line {
dc9dc135
XL
1830 let ml = MultilineAnnotation {
1831 depth: 1,
1832 line_start: lo.line,
1833 line_end: hi.line,
1834 start_col: lo.col_display,
1835 end_col: hi.col_display,
1836 is_primary: span_label.is_primary,
e74abb32 1837 label: span_label.label,
dc9dc135
XL
1838 overlaps_exactly: false,
1839 };
e74abb32 1840 multiline_annotations.push((lo.file, ml));
dc9dc135 1841 } else {
e74abb32
XL
1842 let ann = Annotation {
1843 start_col: lo.col_display,
1844 end_col: hi.col_display,
1845 is_primary: span_label.is_primary,
1846 label: span_label.label,
1847 annotation_type: AnnotationType::Singleline,
1848 };
dc9dc135 1849 add_annotation_to_file(&mut output, lo.file, lo.line, ann);
e74abb32 1850 };
dc9dc135
XL
1851 }
1852 }
1853
1854 // Find overlapping multiline annotations, put them at different depths
1855 multiline_annotations.sort_by_key(|&(_, ref ml)| (ml.line_start, ml.line_end));
e74abb32
XL
1856 for (_, ann) in multiline_annotations.clone() {
1857 for (_, a) in multiline_annotations.iter_mut() {
dc9dc135
XL
1858 // Move all other multiline annotations overlapping with this one
1859 // one level to the right.
60c5eb7d
XL
1860 if !(ann.same_span(a))
1861 && num_overlap(ann.line_start, ann.line_end, a.line_start, a.line_end, true)
dc9dc135
XL
1862 {
1863 a.increase_depth();
1864 } else if ann.same_span(a) && &ann != a {
1865 a.overlaps_exactly = true;
1866 } else {
1867 break;
1868 }
1869 }
1870 }
1871
60c5eb7d 1872 let mut max_depth = 0; // max overlapping multiline spans
dc9dc135 1873 for (file, ann) in multiline_annotations {
e74abb32 1874 max_depth = max(max_depth, ann.depth);
dc9dc135
XL
1875 let mut end_ann = ann.as_end();
1876 if !ann.overlaps_exactly {
1877 // avoid output like
1878 //
1879 // | foo(
1880 // | _____^
1881 // | |_____|
1882 // | || bar,
1883 // | || );
1884 // | || ^
1885 // | ||______|
1886 // | |______foo
1887 // | baz
1888 //
1889 // and instead get
1890 //
1891 // | foo(
1892 // | _____^
1893 // | | bar,
1894 // | | );
1895 // | | ^
1896 // | | |
1897 // | |______foo
1898 // | baz
1899 add_annotation_to_file(&mut output, file.clone(), ann.line_start, ann.as_start());
1900 // 4 is the minimum vertical length of a multiline span when presented: two lines
1901 // of code and two lines of underline. This is not true for the special case where
1902 // the beginning doesn't have an underline, but the current logic seems to be
1903 // working correctly.
1904 let middle = min(ann.line_start + 4, ann.line_end);
1905 for line in ann.line_start + 1..middle {
1906 // Every `|` that joins the beginning of the span (`___^`) to the end (`|__^`).
1907 add_annotation_to_file(&mut output, file.clone(), line, ann.as_line());
1908 }
e74abb32
XL
1909 let line_end = ann.line_end - 1;
1910 if middle < line_end {
1911 add_annotation_to_file(&mut output, file.clone(), line_end, ann.as_line());
dc9dc135
XL
1912 }
1913 } else {
1914 end_ann.annotation_type = AnnotationType::Singleline;
1915 }
1916 add_annotation_to_file(&mut output, file, ann.line_end, end_ann);
1917 }
1918 for file_vec in output.iter_mut() {
1919 file_vec.multiline_depth = max_depth;
1920 }
1921 output
1922 }
1923}
1924
5bcae85e
SL
1925fn draw_col_separator(buffer: &mut StyledBuffer, line: usize, col: usize) {
1926 buffer.puts(line, col, "| ", Style::LineNumber);
7453a54e
SL
1927}
1928
5bcae85e 1929fn draw_col_separator_no_space(buffer: &mut StyledBuffer, line: usize, col: usize) {
476ff2be
SL
1930 draw_col_separator_no_space_with_style(buffer, line, col, Style::LineNumber);
1931}
1932
60c5eb7d
XL
1933fn draw_col_separator_no_space_with_style(
1934 buffer: &mut StyledBuffer,
1935 line: usize,
1936 col: usize,
1937 style: Style,
1938) {
476ff2be
SL
1939 buffer.putc(line, col, '|', style);
1940}
1941
60c5eb7d
XL
1942fn draw_range(
1943 buffer: &mut StyledBuffer,
1944 symbol: char,
1945 line: usize,
1946 col_from: usize,
1947 col_to: usize,
1948 style: Style,
1949) {
476ff2be
SL
1950 for col in col_from..col_to {
1951 buffer.putc(line, col, symbol, style);
1952 }
5bcae85e
SL
1953}
1954
1955fn draw_note_separator(buffer: &mut StyledBuffer, line: usize, col: usize) {
1956 buffer.puts(line, col, "= ", Style::LineNumber);
1957}
1958
60c5eb7d
XL
1959fn draw_multiline_line(
1960 buffer: &mut StyledBuffer,
1961 line: usize,
1962 offset: usize,
1963 depth: usize,
1964 style: Style,
1965) {
cc61c64b
XL
1966 buffer.putc(line, offset + depth - 1, '|', style);
1967}
1968
60c5eb7d
XL
1969fn num_overlap(
1970 a_start: usize,
1971 a_end: usize,
1972 b_start: usize,
1973 b_end: usize,
1974 inclusive: bool,
1975) -> bool {
1976 let extra = if inclusive { 1 } else { 0 };
1977 (b_start..b_end + extra).contains(&a_start) || (a_start..a_end + extra).contains(&b_start)
476ff2be 1978}
8bb4bdeb
XL
1979fn overlaps(a1: &Annotation, a2: &Annotation, padding: usize) -> bool {
1980 num_overlap(a1.start_col, a1.end_col + padding, a2.start_col, a2.end_col, false)
5bcae85e
SL
1981}
1982
60c5eb7d
XL
1983fn emit_to_destination(
1984 rendered_buffer: &[Vec<StyledString>],
1985 lvl: &Level,
1986 dst: &mut Destination,
1987 short_message: bool,
1988) -> io::Result<()> {
9fa01778 1989 use crate::lock;
9e0c209e 1990
0531ce1d
XL
1991 let mut dst = dst.writable();
1992
9e0c209e
SL
1993 // In order to prevent error message interleaving, where multiple error lines get intermixed
1994 // when multiple compiler processes error simultaneously, we emit errors with additional
1995 // steps.
1996 //
1997 // On Unix systems, we write into a buffered terminal rather than directly to a terminal. When
1998 // the .flush() is called we take the buffer created from the buffered writes and write it at
1999 // one shot. Because the Unix systems use ANSI for the colors, which is a text-based styling
2000 // scheme, this buffered approach works and maintains the styling.
2001 //
2002 // On Windows, styling happens through calls to a terminal API. This prevents us from using the
2003 // same buffering approach. Instead, we use a global Windows mutex, which we acquire long
2004 // enough to output the full error message, then we release.
2005 let _buffer_lock = lock::acquire_global_lock("rustc_errors");
0531ce1d 2006 for (pos, line) in rendered_buffer.iter().enumerate() {
5bcae85e 2007 for part in line {
ba9703b0 2008 dst.apply_style(*lvl, part.style)?;
5bcae85e 2009 write!(dst, "{}", part.text)?;
0531ce1d 2010 dst.reset()?;
a7813a04 2011 }
0531ce1d 2012 if !short_message && (!lvl.is_failure_note() || pos != rendered_buffer.len() - 1) {
dc9dc135 2013 writeln!(dst)?;
abe05a73 2014 }
9cc50fc6 2015 }
9e0c209e 2016 dst.flush()?;
9cc50fc6
SL
2017 Ok(())
2018}
2019
5bcae85e 2020pub enum Destination {
0531ce1d
XL
2021 Terminal(StandardStream),
2022 Buffered(BufferWriter),
48663c56
XL
2023 // The bool denotes whether we should be emitting ansi color codes or not
2024 Raw(Box<(dyn Write + Send)>, bool),
9cc50fc6
SL
2025}
2026
0531ce1d
XL
2027pub enum WritableDst<'a> {
2028 Terminal(&'a mut StandardStream),
2029 Buffered(&'a mut BufferWriter, Buffer),
48663c56
XL
2030 Raw(&'a mut (dyn Write + Send)),
2031 ColoredRaw(Ansi<&'a mut (dyn Write + Send)>),
9e0c209e
SL
2032}
2033
9cc50fc6 2034impl Destination {
0531ce1d
XL
2035 fn from_stderr(color: ColorConfig) -> Destination {
2036 let choice = color.to_color_choice();
2037 // On Windows we'll be performing global synchronization on the entire
2038 // system for emitting rustc errors, so there's no need to buffer
2039 // anything.
2040 //
2041 // On non-Windows we rely on the atomicity of `write` to ensure errors
2042 // don't get all jumbled up.
2043 if cfg!(windows) {
2044 Terminal(StandardStream::stderr(choice))
2045 } else {
2046 Buffered(BufferWriter::stderr(choice))
9e0c209e
SL
2047 }
2048 }
2049
416331ca 2050 fn writable(&mut self) -> WritableDst<'_> {
0531ce1d
XL
2051 match *self {
2052 Destination::Terminal(ref mut t) => WritableDst::Terminal(t),
2053 Destination::Buffered(ref mut t) => {
2054 let buf = t.buffer();
2055 WritableDst::Buffered(t, buf)
2056 }
48663c56
XL
2057 Destination::Raw(ref mut t, false) => WritableDst::Raw(t),
2058 Destination::Raw(ref mut t, true) => WritableDst::ColoredRaw(Ansi::new(t)),
9cc50fc6
SL
2059 }
2060 }
0531ce1d 2061}
9cc50fc6 2062
0531ce1d 2063impl<'a> WritableDst<'a> {
c30ab7b3 2064 fn apply_style(&mut self, lvl: Level, style: Style) -> io::Result<()> {
0531ce1d 2065 let mut spec = ColorSpec::new();
a7813a04 2066 match style {
041b39d2 2067 Style::LineAndColumn => {}
a7813a04 2068 Style::LineNumber => {
0531ce1d
XL
2069 spec.set_bold(true);
2070 spec.set_intense(true);
9e0c209e 2071 if cfg!(windows) {
0531ce1d 2072 spec.set_fg(Some(Color::Cyan));
9e0c209e 2073 } else {
0531ce1d 2074 spec.set_fg(Some(Color::Blue));
9e0c209e 2075 }
a7813a04 2076 }
5bcae85e 2077 Style::Quotation => {}
dc9dc135 2078 Style::MainHeaderMsg => {
0531ce1d 2079 spec.set_bold(true);
9e0c209e 2080 if cfg!(windows) {
60c5eb7d 2081 spec.set_intense(true).set_fg(Some(Color::White));
9e0c209e 2082 }
a7813a04
XL
2083 }
2084 Style::UnderlinePrimary | Style::LabelPrimary => {
0531ce1d
XL
2085 spec = lvl.color();
2086 spec.set_bold(true);
a7813a04 2087 }
60c5eb7d
XL
2088 Style::UnderlineSecondary | Style::LabelSecondary => {
2089 spec.set_bold(true).set_intense(true);
9e0c209e 2090 if cfg!(windows) {
0531ce1d 2091 spec.set_fg(Some(Color::Cyan));
9e0c209e 2092 } else {
0531ce1d 2093 spec.set_fg(Some(Color::Blue));
9e0c209e 2094 }
a7813a04 2095 }
60c5eb7d 2096 Style::HeaderMsg | Style::NoStyle => {}
0531ce1d
XL
2097 Style::Level(lvl) => {
2098 spec = lvl.color();
2099 spec.set_bold(true);
2100 }
2101 Style::Highlight => {
2102 spec.set_bold(true);
a7813a04
XL
2103 }
2104 }
0531ce1d 2105 self.set_color(&spec)
a7813a04
XL
2106 }
2107
0531ce1d 2108 fn set_color(&mut self, color: &ColorSpec) -> io::Result<()> {
a7813a04 2109 match *self {
0531ce1d
XL
2110 WritableDst::Terminal(ref mut t) => t.set_color(color),
2111 WritableDst::Buffered(_, ref mut t) => t.set_color(color),
48663c56 2112 WritableDst::ColoredRaw(ref mut t) => t.set_color(color),
60c5eb7d 2113 WritableDst::Raw(_) => Ok(()),
a7813a04 2114 }
a7813a04
XL
2115 }
2116
0531ce1d 2117 fn reset(&mut self) -> io::Result<()> {
a7813a04 2118 match *self {
0531ce1d
XL
2119 WritableDst::Terminal(ref mut t) => t.reset(),
2120 WritableDst::Buffered(_, ref mut t) => t.reset(),
48663c56 2121 WritableDst::ColoredRaw(ref mut t) => t.reset(),
0531ce1d 2122 WritableDst::Raw(_) => Ok(()),
a7813a04 2123 }
a7813a04 2124 }
9cc50fc6
SL
2125}
2126
0531ce1d 2127impl<'a> Write for WritableDst<'a> {
c34b1796
AL
2128 fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
2129 match *self {
0531ce1d
XL
2130 WritableDst::Terminal(ref mut t) => t.write(bytes),
2131 WritableDst::Buffered(_, ref mut buf) => buf.write(bytes),
2132 WritableDst::Raw(ref mut w) => w.write(bytes),
48663c56 2133 WritableDst::ColoredRaw(ref mut t) => t.write(bytes),
c34b1796
AL
2134 }
2135 }
0531ce1d 2136
c34b1796 2137 fn flush(&mut self) -> io::Result<()> {
1a4d82fc 2138 match *self {
0531ce1d
XL
2139 WritableDst::Terminal(ref mut t) => t.flush(),
2140 WritableDst::Buffered(_, ref mut buf) => buf.flush(),
2141 WritableDst::Raw(ref mut w) => w.flush(),
48663c56 2142 WritableDst::ColoredRaw(ref mut w) => w.flush(),
0531ce1d
XL
2143 }
2144 }
2145}
2146
2147impl<'a> Drop for WritableDst<'a> {
2148 fn drop(&mut self) {
ba9703b0
XL
2149 if let WritableDst::Buffered(ref mut dst, ref mut buf) = self {
2150 drop(dst.print(buf));
1a4d82fc
JJ
2151 }
2152 }
9e0c209e 2153}
e74abb32
XL
2154
2155/// Whether the original and suggested code are visually similar enough to warrant extra wording.
60c5eb7d 2156pub fn is_case_difference(sm: &SourceMap, suggested: &str, sp: Span) -> bool {
e74abb32 2157 // FIXME: this should probably be extended to also account for `FO0` → `FOO` and unicode.
60c5eb7d
XL
2158 let found = match sm.span_to_snippet(sp) {
2159 Ok(snippet) => snippet,
2160 Err(e) => {
2161 warn!("Invalid span {:?}. Err={:?}", sp, e);
2162 return false;
2163 }
2164 };
e74abb32
XL
2165 let ascii_confusables = &['c', 'f', 'i', 'k', 'o', 's', 'u', 'v', 'w', 'x', 'y', 'z'];
2166 // All the chars that differ in capitalization are confusable (above):
60c5eb7d
XL
2167 let confusable = found
2168 .chars()
2169 .zip(suggested.chars())
2170 .filter(|(f, s)| f != s)
2171 .all(|(f, s)| (ascii_confusables.contains(&f) || ascii_confusables.contains(&s)));
e74abb32
XL
2172 confusable && found.to_lowercase() == suggested.to_lowercase()
2173 // FIXME: We sometimes suggest the same thing we already have, which is a
2174 // bug, but be defensive against that here.
2175 && found != suggested
2176}