rustc_errors/emitter.rs
1//! The current rustc diagnostics emitter.
2//!
3//! An `Emitter` takes care of generating the output from a `Diag` 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 `rustc_session::config::ErrorOutputType`.
9
10use std::borrow::Cow;
11use std::cmp::{Reverse, max, min};
12use std::error::Report;
13use std::io::prelude::*;
14use std::io::{self, IsTerminal};
15use std::iter;
16use std::path::Path;
17use std::sync::Arc;
18
19use derive_setters::Setters;
20use rustc_data_structures::fx::{FxHashMap, FxIndexMap, FxIndexSet};
21use rustc_data_structures::sync::{DynSend, IntoDynSyncSend};
22use rustc_error_messages::{FluentArgs, SpanLabel};
23use rustc_lexer;
24use rustc_lint_defs::pluralize;
25use rustc_span::hygiene::{ExpnKind, MacroKind};
26use rustc_span::source_map::SourceMap;
27use rustc_span::{FileLines, FileName, SourceFile, Span, char_width, str_width};
28use termcolor::{Buffer, BufferWriter, Color, ColorChoice, ColorSpec, StandardStream, WriteColor};
29use tracing::{debug, instrument, trace, warn};
30
31use crate::diagnostic::DiagLocation;
32use crate::registry::Registry;
33use crate::snippet::{
34 Annotation, AnnotationColumn, AnnotationType, Line, MultilineAnnotation, Style, StyledString,
35};
36use crate::styled_buffer::StyledBuffer;
37use crate::timings::TimingRecord;
38use crate::translation::{Translator, to_fluent_args};
39use crate::{
40 CodeSuggestion, DiagInner, DiagMessage, ErrCode, Level, MultiSpan, Subdiag,
41 SubstitutionHighlight, SuggestionStyle, TerminalUrl,
42};
43
44/// Default column width, used in tests and when terminal dimensions cannot be determined.
45const DEFAULT_COLUMN_WIDTH: usize = 140;
46
47/// Describes the way the content of the `rendered` field of the json output is generated
48#[derive(Clone, Copy, Debug, PartialEq, Eq)]
49pub enum HumanReadableErrorType {
50 Default,
51 Unicode,
52 AnnotateSnippet,
53 Short,
54}
55
56impl HumanReadableErrorType {
57 pub fn short(&self) -> bool {
58 *self == HumanReadableErrorType::Short
59 }
60}
61
62#[derive(Clone, Copy, Debug)]
63struct Margin {
64 /// The available whitespace in the left that can be consumed when centering.
65 pub whitespace_left: usize,
66 /// The column of the beginning of leftmost span.
67 pub span_left: usize,
68 /// The column of the end of rightmost span.
69 pub span_right: usize,
70 /// The beginning of the line to be displayed.
71 pub computed_left: usize,
72 /// The end of the line to be displayed.
73 pub computed_right: usize,
74 /// The current width of the terminal. Uses value of `DEFAULT_COLUMN_WIDTH` constant by default
75 /// and in tests.
76 pub column_width: usize,
77 /// The end column of a span label, including the span. Doesn't account for labels not in the
78 /// same line as the span.
79 pub label_right: usize,
80}
81
82impl Margin {
83 fn new(
84 whitespace_left: usize,
85 span_left: usize,
86 span_right: usize,
87 label_right: usize,
88 column_width: usize,
89 max_line_len: usize,
90 ) -> Self {
91 // The 6 is padding to give a bit of room for `...` when displaying:
92 // ```
93 // error: message
94 // --> file.rs:16:58
95 // |
96 // 16 | ... fn foo(self) -> Self::Bar {
97 // | ^^^^^^^^^
98 // ```
99
100 let mut m = Margin {
101 whitespace_left: whitespace_left.saturating_sub(6),
102 span_left: span_left.saturating_sub(6),
103 span_right: span_right + 6,
104 computed_left: 0,
105 computed_right: 0,
106 column_width,
107 label_right: label_right + 6,
108 };
109 m.compute(max_line_len);
110 m
111 }
112
113 fn was_cut_left(&self) -> bool {
114 self.computed_left > 0
115 }
116
117 fn compute(&mut self, max_line_len: usize) {
118 // When there's a lot of whitespace (>20), we want to trim it as it is useless.
119 // FIXME: this doesn't account for '\t', but to do so correctly we need to perform that
120 // calculation later, right before printing in order to be accurate with both unicode
121 // handling and trimming of long lines.
122 self.computed_left = if self.whitespace_left > 20 {
123 self.whitespace_left - 16 // We want some padding.
124 } else {
125 0
126 };
127 // We want to show as much as possible, max_line_len is the rightmost boundary for the
128 // relevant code.
129 self.computed_right = max(max_line_len, self.computed_left);
130
131 if self.computed_right - self.computed_left > self.column_width {
132 // Trimming only whitespace isn't enough, let's get craftier.
133 if self.label_right - self.whitespace_left <= self.column_width {
134 // Attempt to fit the code window only trimming whitespace.
135 self.computed_left = self.whitespace_left;
136 self.computed_right = self.computed_left + self.column_width;
137 } else if self.label_right - self.span_left <= self.column_width {
138 // Attempt to fit the code window considering only the spans and labels.
139 let padding_left = (self.column_width - (self.label_right - self.span_left)) / 2;
140 self.computed_left = self.span_left.saturating_sub(padding_left);
141 self.computed_right = self.computed_left + self.column_width;
142 } else if self.span_right - self.span_left <= self.column_width {
143 // Attempt to fit the code window considering the spans and labels plus padding.
144 let padding_left = (self.column_width - (self.span_right - self.span_left)) / 5 * 2;
145 self.computed_left = self.span_left.saturating_sub(padding_left);
146 self.computed_right = self.computed_left + self.column_width;
147 } else {
148 // Mostly give up but still don't show the full line.
149 self.computed_left = self.span_left;
150 self.computed_right = self.span_right;
151 }
152 }
153 }
154
155 fn left(&self, line_len: usize) -> usize {
156 min(self.computed_left, line_len)
157 }
158
159 fn right(&self, line_len: usize) -> usize {
160 if line_len.saturating_sub(self.computed_left) <= self.column_width {
161 line_len
162 } else {
163 min(line_len, self.computed_right)
164 }
165 }
166}
167
168pub enum TimingEvent {
169 Start,
170 End,
171}
172
173const ANONYMIZED_LINE_NUM: &str = "LL";
174
175pub type DynEmitter = dyn Emitter + DynSend;
176
177/// Emitter trait for emitting errors and other structured information.
178pub trait Emitter {
179 /// Emit a structured diagnostic.
180 fn emit_diagnostic(&mut self, diag: DiagInner, registry: &Registry);
181
182 /// Emit a notification that an artifact has been output.
183 /// Currently only supported for the JSON format.
184 fn emit_artifact_notification(&mut self, _path: &Path, _artifact_type: &str) {}
185
186 /// Emit a timestamp with start/end of a timing section.
187 /// Currently only supported for the JSON format.
188 fn emit_timing_section(&mut self, _record: TimingRecord, _event: TimingEvent) {}
189
190 /// Emit a report about future breakage.
191 /// Currently only supported for the JSON format.
192 fn emit_future_breakage_report(&mut self, _diags: Vec<DiagInner>, _registry: &Registry) {}
193
194 /// Emit list of unused externs.
195 /// Currently only supported for the JSON format.
196 fn emit_unused_externs(
197 &mut self,
198 _lint_level: rustc_lint_defs::Level,
199 _unused_externs: &[&str],
200 ) {
201 }
202
203 /// Checks if should show explanations about "rustc --explain"
204 fn should_show_explain(&self) -> bool {
205 true
206 }
207
208 /// Checks if we can use colors in the current output stream.
209 fn supports_color(&self) -> bool {
210 false
211 }
212
213 fn source_map(&self) -> Option<&SourceMap>;
214
215 fn translator(&self) -> &Translator;
216
217 /// Formats the substitutions of the primary_span
218 ///
219 /// There are a lot of conditions to this method, but in short:
220 ///
221 /// * If the current `DiagInner` has only one visible `CodeSuggestion`,
222 /// we format the `help` suggestion depending on the content of the
223 /// substitutions. In that case, we modify the span and clear the
224 /// suggestions.
225 ///
226 /// * If the current `DiagInner` has multiple suggestions,
227 /// we leave `primary_span` and the suggestions untouched.
228 fn primary_span_formatted(
229 &self,
230 primary_span: &mut MultiSpan,
231 suggestions: &mut Vec<CodeSuggestion>,
232 fluent_args: &FluentArgs<'_>,
233 ) {
234 if let Some((sugg, rest)) = suggestions.split_first() {
235 let msg = self
236 .translator()
237 .translate_message(&sugg.msg, fluent_args)
238 .map_err(Report::new)
239 .unwrap();
240 if rest.is_empty()
241 // ^ if there is only one suggestion
242 // don't display multi-suggestions as labels
243 && let [substitution] = sugg.substitutions.as_slice()
244 // don't display multipart suggestions as labels
245 && let [part] = substitution.parts.as_slice()
246 // don't display long messages as labels
247 && msg.split_whitespace().count() < 10
248 // don't display multiline suggestions as labels
249 && !part.snippet.contains('\n')
250 && ![
251 // when this style is set we want the suggestion to be a message, not inline
252 SuggestionStyle::HideCodeAlways,
253 // trivial suggestion for tooling's sake, never shown
254 SuggestionStyle::CompletelyHidden,
255 // subtle suggestion, never shown inline
256 SuggestionStyle::ShowAlways,
257 ].contains(&sugg.style)
258 {
259 let snippet = part.snippet.trim();
260 let msg = if snippet.is_empty() || sugg.style.hide_inline() {
261 // This substitution is only removal OR we explicitly don't want to show the
262 // code inline (`hide_inline`). Therefore, we don't show the substitution.
263 format!("help: {msg}")
264 } else {
265 // Show the default suggestion text with the substitution
266 format!(
267 "help: {}{}: `{}`",
268 msg,
269 if self
270 .source_map()
271 .is_some_and(|sm| is_case_difference(sm, snippet, part.span,))
272 {
273 " (notice the capitalization)"
274 } else {
275 ""
276 },
277 snippet,
278 )
279 };
280 primary_span.push_span_label(part.span, msg);
281
282 // We return only the modified primary_span
283 suggestions.clear();
284 } else {
285 // if there are multiple suggestions, print them all in full
286 // to be consistent. We could try to figure out if we can
287 // make one (or the first one) inline, but that would give
288 // undue importance to a semi-random suggestion
289 }
290 } else {
291 // do nothing
292 }
293 }
294
295 fn fix_multispans_in_extern_macros_and_render_macro_backtrace(
296 &self,
297 span: &mut MultiSpan,
298 children: &mut Vec<Subdiag>,
299 level: &Level,
300 backtrace: bool,
301 ) {
302 // Check for spans in macros, before `fix_multispans_in_extern_macros`
303 // has a chance to replace them.
304 let has_macro_spans: Vec<_> = iter::once(&*span)
305 .chain(children.iter().map(|child| &child.span))
306 .flat_map(|span| span.primary_spans())
307 .flat_map(|sp| sp.macro_backtrace())
308 .filter_map(|expn_data| {
309 match expn_data.kind {
310 ExpnKind::Root => None,
311
312 // Skip past non-macro entries, just in case there
313 // are some which do actually involve macros.
314 ExpnKind::Desugaring(..) | ExpnKind::AstPass(..) => None,
315
316 ExpnKind::Macro(macro_kind, name) => {
317 Some((macro_kind, name, expn_data.hide_backtrace))
318 }
319 }
320 })
321 .collect();
322
323 if !backtrace {
324 self.fix_multispans_in_extern_macros(span, children);
325 }
326
327 self.render_multispans_macro_backtrace(span, children, backtrace);
328
329 if !backtrace {
330 // Skip builtin macros, as their expansion isn't relevant to the end user. This includes
331 // actual intrinsics, like `asm!`.
332 if let Some((macro_kind, name, _)) = has_macro_spans.first()
333 && let Some((_, _, false)) = has_macro_spans.last()
334 {
335 // Mark the actual macro this originates from
336 let and_then = if let Some((macro_kind, last_name, _)) = has_macro_spans.last()
337 && last_name != name
338 {
339 let descr = macro_kind.descr();
340 format!(" which comes from the expansion of the {descr} `{last_name}`")
341 } else {
342 "".to_string()
343 };
344
345 let descr = macro_kind.descr();
346 let msg = format!(
347 "this {level} originates in the {descr} `{name}`{and_then} \
348 (in Nightly builds, run with -Z macro-backtrace for more info)",
349 );
350
351 children.push(Subdiag {
352 level: Level::Note,
353 messages: vec![(DiagMessage::from(msg), Style::NoStyle)],
354 span: MultiSpan::new(),
355 });
356 }
357 }
358 }
359
360 fn render_multispans_macro_backtrace(
361 &self,
362 span: &mut MultiSpan,
363 children: &mut Vec<Subdiag>,
364 backtrace: bool,
365 ) {
366 for span in iter::once(span).chain(children.iter_mut().map(|child| &mut child.span)) {
367 self.render_multispan_macro_backtrace(span, backtrace);
368 }
369 }
370
371 fn render_multispan_macro_backtrace(&self, span: &mut MultiSpan, always_backtrace: bool) {
372 let mut new_labels = FxIndexSet::default();
373
374 for &sp in span.primary_spans() {
375 if sp.is_dummy() {
376 continue;
377 }
378
379 // FIXME(eddyb) use `retain` on `macro_backtrace` to remove all the
380 // entries we don't want to print, to make sure the indices being
381 // printed are contiguous (or omitted if there's only one entry).
382 let macro_backtrace: Vec<_> = sp.macro_backtrace().collect();
383 for (i, trace) in macro_backtrace.iter().rev().enumerate() {
384 if trace.def_site.is_dummy() {
385 continue;
386 }
387
388 if always_backtrace {
389 new_labels.insert((
390 trace.def_site,
391 format!(
392 "in this expansion of `{}`{}",
393 trace.kind.descr(),
394 if macro_backtrace.len() > 1 {
395 // if macro_backtrace.len() == 1 it'll be
396 // pointed at by "in this macro invocation"
397 format!(" (#{})", i + 1)
398 } else {
399 String::new()
400 },
401 ),
402 ));
403 }
404
405 // Don't add a label on the call site if the diagnostic itself
406 // already points to (a part of) that call site, as the label
407 // is meant for showing the relevant invocation when the actual
408 // diagnostic is pointing to some part of macro definition.
409 //
410 // This also handles the case where an external span got replaced
411 // with the call site span by `fix_multispans_in_extern_macros`.
412 //
413 // NB: `-Zmacro-backtrace` overrides this, for uniformity, as the
414 // "in this expansion of" label above is always added in that mode,
415 // and it needs an "in this macro invocation" label to match that.
416 let redundant_span = trace.call_site.contains(sp);
417
418 if !redundant_span || always_backtrace {
419 let msg: Cow<'static, _> = match trace.kind {
420 ExpnKind::Macro(MacroKind::Attr, _) => {
421 "this procedural macro expansion".into()
422 }
423 ExpnKind::Macro(MacroKind::Derive, _) => {
424 "this derive macro expansion".into()
425 }
426 ExpnKind::Macro(MacroKind::Bang, _) => "this macro invocation".into(),
427 ExpnKind::Root => "the crate root".into(),
428 ExpnKind::AstPass(kind) => kind.descr().into(),
429 ExpnKind::Desugaring(kind) => {
430 format!("this {} desugaring", kind.descr()).into()
431 }
432 };
433 new_labels.insert((
434 trace.call_site,
435 format!(
436 "in {}{}",
437 msg,
438 if macro_backtrace.len() > 1 && always_backtrace {
439 // only specify order when the macro
440 // backtrace is multiple levels deep
441 format!(" (#{})", i + 1)
442 } else {
443 String::new()
444 },
445 ),
446 ));
447 }
448 if !always_backtrace {
449 break;
450 }
451 }
452 }
453
454 for (label_span, label_text) in new_labels {
455 span.push_span_label(label_span, label_text);
456 }
457 }
458
459 // This does a small "fix" for multispans by looking to see if it can find any that
460 // point directly at external macros. Since these are often difficult to read,
461 // this will change the span to point at the use site.
462 fn fix_multispans_in_extern_macros(&self, span: &mut MultiSpan, children: &mut Vec<Subdiag>) {
463 debug!("fix_multispans_in_extern_macros: before: span={:?} children={:?}", span, children);
464 self.fix_multispan_in_extern_macros(span);
465 for child in children.iter_mut() {
466 self.fix_multispan_in_extern_macros(&mut child.span);
467 }
468 debug!("fix_multispans_in_extern_macros: after: span={:?} children={:?}", span, children);
469 }
470
471 // This "fixes" MultiSpans that contain `Span`s pointing to locations inside of external macros.
472 // Since these locations are often difficult to read,
473 // we move these spans from the external macros to their corresponding use site.
474 fn fix_multispan_in_extern_macros(&self, span: &mut MultiSpan) {
475 let Some(source_map) = self.source_map() else { return };
476 // First, find all the spans in external macros and point instead at their use site.
477 let replacements: Vec<(Span, Span)> = span
478 .primary_spans()
479 .iter()
480 .copied()
481 .chain(span.span_labels().iter().map(|sp_label| sp_label.span))
482 .filter_map(|sp| {
483 if !sp.is_dummy() && source_map.is_imported(sp) {
484 let maybe_callsite = sp.source_callsite();
485 if sp != maybe_callsite {
486 return Some((sp, maybe_callsite));
487 }
488 }
489 None
490 })
491 .collect();
492
493 // After we have them, make sure we replace these 'bad' def sites with their use sites.
494 for (from, to) in replacements {
495 span.replace(from, to);
496 }
497 }
498}
499
500impl Emitter for HumanEmitter {
501 fn source_map(&self) -> Option<&SourceMap> {
502 self.sm.as_deref()
503 }
504
505 fn emit_diagnostic(&mut self, mut diag: DiagInner, _registry: &Registry) {
506 let fluent_args = to_fluent_args(diag.args.iter());
507
508 let mut suggestions = diag.suggestions.unwrap_tag();
509 self.primary_span_formatted(&mut diag.span, &mut suggestions, &fluent_args);
510
511 self.fix_multispans_in_extern_macros_and_render_macro_backtrace(
512 &mut diag.span,
513 &mut diag.children,
514 &diag.level,
515 self.macro_backtrace,
516 );
517
518 self.emit_messages_default(
519 &diag.level,
520 &diag.messages,
521 &fluent_args,
522 &diag.code,
523 &diag.span,
524 &diag.children,
525 &suggestions,
526 self.track_diagnostics.then_some(&diag.emitted_at),
527 );
528 }
529
530 fn should_show_explain(&self) -> bool {
531 !self.short_message
532 }
533
534 fn supports_color(&self) -> bool {
535 self.dst.supports_color()
536 }
537
538 fn translator(&self) -> &Translator {
539 &self.translator
540 }
541}
542
543/// An emitter that does nothing when emitting a non-fatal diagnostic.
544/// Fatal diagnostics are forwarded to `fatal_emitter` to avoid silent
545/// failures of rustc, as witnessed e.g. in issue #89358.
546pub struct FatalOnlyEmitter {
547 pub fatal_emitter: Box<dyn Emitter + DynSend>,
548 pub fatal_note: Option<String>,
549}
550
551impl Emitter for FatalOnlyEmitter {
552 fn source_map(&self) -> Option<&SourceMap> {
553 None
554 }
555
556 fn emit_diagnostic(&mut self, mut diag: DiagInner, registry: &Registry) {
557 if diag.level == Level::Fatal {
558 if let Some(fatal_note) = &self.fatal_note {
559 diag.sub(Level::Note, fatal_note.clone(), MultiSpan::new());
560 }
561 self.fatal_emitter.emit_diagnostic(diag, registry);
562 }
563 }
564
565 fn translator(&self) -> &Translator {
566 self.fatal_emitter.translator()
567 }
568}
569
570pub struct SilentEmitter {
571 pub translator: Translator,
572}
573
574impl Emitter for SilentEmitter {
575 fn source_map(&self) -> Option<&SourceMap> {
576 None
577 }
578
579 fn emit_diagnostic(&mut self, _diag: DiagInner, _registry: &Registry) {}
580
581 fn translator(&self) -> &Translator {
582 &self.translator
583 }
584}
585
586/// Maximum number of suggestions to be shown
587///
588/// Arbitrary, but taken from trait import suggestion limit
589pub const MAX_SUGGESTIONS: usize = 4;
590
591#[derive(Clone, Copy, Debug, PartialEq, Eq)]
592pub enum ColorConfig {
593 Auto,
594 Always,
595 Never,
596}
597
598impl ColorConfig {
599 pub fn to_color_choice(self) -> ColorChoice {
600 match self {
601 ColorConfig::Always => {
602 if io::stderr().is_terminal() {
603 ColorChoice::Always
604 } else {
605 ColorChoice::AlwaysAnsi
606 }
607 }
608 ColorConfig::Never => ColorChoice::Never,
609 ColorConfig::Auto if io::stderr().is_terminal() => ColorChoice::Auto,
610 ColorConfig::Auto => ColorChoice::Never,
611 }
612 }
613}
614
615#[derive(Debug, Clone, Copy, PartialEq, Eq)]
616pub enum OutputTheme {
617 Ascii,
618 Unicode,
619}
620
621/// Handles the writing of `HumanReadableErrorType::Default` and `HumanReadableErrorType::Short`
622#[derive(Setters)]
623pub struct HumanEmitter {
624 #[setters(skip)]
625 dst: IntoDynSyncSend<Destination>,
626 sm: Option<Arc<SourceMap>>,
627 #[setters(skip)]
628 translator: Translator,
629 short_message: bool,
630 ui_testing: bool,
631 ignored_directories_in_source_blocks: Vec<String>,
632 diagnostic_width: Option<usize>,
633
634 macro_backtrace: bool,
635 track_diagnostics: bool,
636 terminal_url: TerminalUrl,
637 theme: OutputTheme,
638}
639
640#[derive(Debug)]
641pub(crate) struct FileWithAnnotatedLines {
642 pub(crate) file: Arc<SourceFile>,
643 pub(crate) lines: Vec<Line>,
644 multiline_depth: usize,
645}
646
647impl HumanEmitter {
648 pub fn new(dst: Destination, translator: Translator) -> HumanEmitter {
649 HumanEmitter {
650 dst: IntoDynSyncSend(dst),
651 sm: None,
652 translator,
653 short_message: false,
654 ui_testing: false,
655 ignored_directories_in_source_blocks: Vec::new(),
656 diagnostic_width: None,
657 macro_backtrace: false,
658 track_diagnostics: false,
659 terminal_url: TerminalUrl::No,
660 theme: OutputTheme::Ascii,
661 }
662 }
663
664 fn maybe_anonymized(&self, line_num: usize) -> Cow<'static, str> {
665 if self.ui_testing {
666 Cow::Borrowed(ANONYMIZED_LINE_NUM)
667 } else {
668 Cow::Owned(line_num.to_string())
669 }
670 }
671
672 fn draw_line(
673 &self,
674 buffer: &mut StyledBuffer,
675 source_string: &str,
676 line_index: usize,
677 line_offset: usize,
678 width_offset: usize,
679 code_offset: usize,
680 margin: Margin,
681 ) -> usize {
682 let line_len = source_string.len();
683 // Create the source line we will highlight.
684 let left = margin.left(line_len);
685 let right = margin.right(line_len);
686 // FIXME: The following code looks fishy. See #132860.
687 // On long lines, we strip the source line, accounting for unicode.
688 let code: String = source_string
689 .chars()
690 .enumerate()
691 .skip_while(|(i, _)| *i < left)
692 .take_while(|(i, _)| *i < right)
693 .map(|(_, c)| c)
694 .collect();
695 let code = normalize_whitespace(&code);
696 let was_cut_right =
697 source_string.chars().enumerate().skip_while(|(i, _)| *i < right).next().is_some();
698 buffer.puts(line_offset, code_offset, &code, Style::Quotation);
699 let placeholder = self.margin();
700 if margin.was_cut_left() {
701 // We have stripped some code/whitespace from the beginning, make it clear.
702 buffer.puts(line_offset, code_offset, placeholder, Style::LineNumber);
703 }
704 if was_cut_right {
705 let padding = str_width(placeholder);
706 // We have stripped some code after the rightmost span end, make it clear we did so.
707 buffer.puts(
708 line_offset,
709 code_offset + str_width(&code) - padding,
710 placeholder,
711 Style::LineNumber,
712 );
713 }
714 buffer.puts(line_offset, 0, &self.maybe_anonymized(line_index), Style::LineNumber);
715
716 self.draw_col_separator_no_space(buffer, line_offset, width_offset - 2);
717 left
718 }
719
720 #[instrument(level = "trace", skip(self), ret)]
721 fn render_source_line(
722 &self,
723 buffer: &mut StyledBuffer,
724 file: Arc<SourceFile>,
725 line: &Line,
726 width_offset: usize,
727 code_offset: usize,
728 margin: Margin,
729 close_window: bool,
730 ) -> Vec<(usize, Style)> {
731 // Draw:
732 //
733 // LL | ... code ...
734 // | ^^-^ span label
735 // | |
736 // | secondary span label
737 //
738 // ^^ ^ ^^^ ^^^^ ^^^ we don't care about code too far to the right of a span, we trim it
739 // | | | |
740 // | | | actual code found in your source code and the spans we use to mark it
741 // | | when there's too much wasted space to the left, trim it
742 // | vertical divider between the column number and the code
743 // column number
744
745 if line.line_index == 0 {
746 return Vec::new();
747 }
748
749 let Some(source_string) = file.get_line(line.line_index - 1) else {
750 return Vec::new();
751 };
752 trace!(?source_string);
753
754 let line_offset = buffer.num_lines();
755
756 // Left trim.
757 // FIXME: This looks fishy. See #132860.
758 let left = self.draw_line(
759 buffer,
760 &source_string,
761 line.line_index,
762 line_offset,
763 width_offset,
764 code_offset,
765 margin,
766 );
767
768 // Special case when there's only one annotation involved, it is the start of a multiline
769 // span and there's no text at the beginning of the code line. Instead of doing the whole
770 // graph:
771 //
772 // 2 | fn foo() {
773 // | _^
774 // 3 | |
775 // 4 | | }
776 // | |_^ test
777 //
778 // we simplify the output to:
779 //
780 // 2 | / fn foo() {
781 // 3 | |
782 // 4 | | }
783 // | |_^ test
784 let mut buffer_ops = vec![];
785 let mut annotations = vec![];
786 let mut short_start = true;
787 for ann in &line.annotations {
788 if let AnnotationType::MultilineStart(depth) = ann.annotation_type {
789 if source_string.chars().take(ann.start_col.file).all(|c| c.is_whitespace()) {
790 let uline = self.underline(ann.is_primary);
791 let chr = uline.multiline_whole_line;
792 annotations.push((depth, uline.style));
793 buffer_ops.push((line_offset, width_offset + depth - 1, chr, uline.style));
794 } else {
795 short_start = false;
796 break;
797 }
798 } else if let AnnotationType::MultilineLine(_) = ann.annotation_type {
799 } else {
800 short_start = false;
801 break;
802 }
803 }
804 if short_start {
805 for (y, x, c, s) in buffer_ops {
806 buffer.putc(y, x, c, s);
807 }
808 return annotations;
809 }
810
811 // We want to display like this:
812 //
813 // vec.push(vec.pop().unwrap());
814 // --- ^^^ - previous borrow ends here
815 // | |
816 // | error occurs here
817 // previous borrow of `vec` occurs here
818 //
819 // But there are some weird edge cases to be aware of:
820 //
821 // vec.push(vec.pop().unwrap());
822 // -------- - previous borrow ends here
823 // ||
824 // |this makes no sense
825 // previous borrow of `vec` occurs here
826 //
827 // For this reason, we group the lines into "highlight lines"
828 // and "annotations lines", where the highlight lines have the `^`.
829
830 // Sort the annotations by (start, end col)
831 // The labels are reversed, sort and then reversed again.
832 // Consider a list of annotations (A1, A2, C1, C2, B1, B2) where
833 // the letter signifies the span. Here we are only sorting by the
834 // span and hence, the order of the elements with the same span will
835 // not change. On reversing the ordering (|a, b| but b.cmp(a)), you get
836 // (C1, C2, B1, B2, A1, A2). All the elements with the same span are
837 // still ordered first to last, but all the elements with different
838 // spans are ordered by their spans in last to first order. Last to
839 // first order is important, because the jiggly lines and | are on
840 // the left, so the rightmost span needs to be rendered first,
841 // otherwise the lines would end up needing to go over a message.
842
843 let mut annotations = line.annotations.clone();
844 annotations.sort_by_key(|a| Reverse(a.start_col));
845
846 // First, figure out where each label will be positioned.
847 //
848 // In the case where you have the following annotations:
849 //
850 // vec.push(vec.pop().unwrap());
851 // -------- - previous borrow ends here [C]
852 // ||
853 // |this makes no sense [B]
854 // previous borrow of `vec` occurs here [A]
855 //
856 // `annotations_position` will hold [(2, A), (1, B), (0, C)].
857 //
858 // We try, when possible, to stick the rightmost annotation at the end
859 // of the highlight line:
860 //
861 // vec.push(vec.pop().unwrap());
862 // --- --- - previous borrow ends here
863 //
864 // But sometimes that's not possible because one of the other
865 // annotations overlaps it. For example, from the test
866 // `span_overlap_label`, we have the following annotations
867 // (written on distinct lines for clarity):
868 //
869 // fn foo(x: u32) {
870 // --------------
871 // -
872 //
873 // In this case, we can't stick the rightmost-most label on
874 // the highlight line, or we would get:
875 //
876 // fn foo(x: u32) {
877 // -------- x_span
878 // |
879 // fn_span
880 //
881 // which is totally weird. Instead we want:
882 //
883 // fn foo(x: u32) {
884 // --------------
885 // | |
886 // | x_span
887 // fn_span
888 //
889 // which is...less weird, at least. In fact, in general, if
890 // the rightmost span overlaps with any other span, we should
891 // use the "hang below" version, so we can at least make it
892 // clear where the span *starts*. There's an exception for this
893 // logic, when the labels do not have a message:
894 //
895 // fn foo(x: u32) {
896 // --------------
897 // |
898 // x_span
899 //
900 // instead of:
901 //
902 // fn foo(x: u32) {
903 // --------------
904 // | |
905 // | x_span
906 // <EMPTY LINE>
907 //
908 let mut overlap = vec![false; annotations.len()];
909 let mut annotations_position = vec![];
910 let mut line_len: usize = 0;
911 let mut p = 0;
912 for (i, annotation) in annotations.iter().enumerate() {
913 for (j, next) in annotations.iter().enumerate() {
914 if overlaps(next, annotation, 0) && j > i {
915 overlap[i] = true;
916 overlap[j] = true;
917 }
918 if overlaps(next, annotation, 0) // This label overlaps with another one and both
919 && annotation.has_label() // take space (they have text and are not
920 && j > i // multiline lines).
921 && p == 0
922 // We're currently on the first line, move the label one line down
923 {
924 // If we're overlapping with an un-labelled annotation with the same span
925 // we can just merge them in the output
926 if next.start_col == annotation.start_col
927 && next.end_col == annotation.end_col
928 && !next.has_label()
929 {
930 continue;
931 }
932
933 // This annotation needs a new line in the output.
934 p += 1;
935 break;
936 }
937 }
938 annotations_position.push((p, annotation));
939 for (j, next) in annotations.iter().enumerate() {
940 if j > i {
941 let l = next.label.as_ref().map_or(0, |label| label.len() + 2);
942 if (overlaps(next, annotation, l) // Do not allow two labels to be in the same
943 // line if they overlap including padding, to
944 // avoid situations like:
945 //
946 // fn foo(x: u32) {
947 // -------^------
948 // | |
949 // fn_spanx_span
950 //
951 && annotation.has_label() // Both labels must have some text, otherwise
952 && next.has_label()) // they are not overlapping.
953 // Do not add a new line if this annotation
954 // or the next are vertical line placeholders.
955 || (annotation.takes_space() // If either this or the next annotation is
956 && next.has_label()) // multiline start/end, move it to a new line
957 || (annotation.has_label() // so as not to overlap the horizontal lines.
958 && next.takes_space())
959 || (annotation.takes_space() && next.takes_space())
960 || (overlaps(next, annotation, l)
961 && next.end_col <= annotation.end_col
962 && next.has_label()
963 && p == 0)
964 // Avoid #42595.
965 {
966 // This annotation needs a new line in the output.
967 p += 1;
968 break;
969 }
970 }
971 }
972 line_len = max(line_len, p);
973 }
974
975 if line_len != 0 {
976 line_len += 1;
977 }
978
979 // If there are no annotations or the only annotations on this line are
980 // MultilineLine, then there's only code being shown, stop processing.
981 if line.annotations.iter().all(|a| a.is_line()) {
982 return vec![];
983 }
984
985 if annotations_position
986 .iter()
987 .all(|(_, ann)| matches!(ann.annotation_type, AnnotationType::MultilineStart(_)))
988 && let Some(max_pos) = annotations_position.iter().map(|(pos, _)| *pos).max()
989 {
990 // Special case the following, so that we minimize overlapping multiline spans.
991 //
992 // 3 │ X0 Y0 Z0
993 // │ ┏━━━━━┛ │ │ < We are writing these lines
994 // │ ┃┌───────┘ │ < by reverting the "depth" of
995 // │ ┃│┌─────────┘ < their multiline spans.
996 // 4 │ ┃││ X1 Y1 Z1
997 // 5 │ ┃││ X2 Y2 Z2
998 // │ ┃│└────╿──│──┘ `Z` label
999 // │ ┃└─────│──┤
1000 // │ ┗━━━━━━┥ `Y` is a good letter too
1001 // ╰╴ `X` is a good letter
1002 for (pos, _) in &mut annotations_position {
1003 *pos = max_pos - *pos;
1004 }
1005 // We know then that we don't need an additional line for the span label, saving us
1006 // one line of vertical space.
1007 line_len = line_len.saturating_sub(1);
1008 }
1009
1010 // Write the column separator.
1011 //
1012 // After this we will have:
1013 //
1014 // 2 | fn foo() {
1015 // |
1016 // |
1017 // |
1018 // 3 |
1019 // 4 | }
1020 // |
1021 for pos in 0..=line_len {
1022 self.draw_col_separator_no_space(buffer, line_offset + pos + 1, width_offset - 2);
1023 }
1024 if close_window {
1025 self.draw_col_separator_end(buffer, line_offset + line_len + 1, width_offset - 2);
1026 }
1027
1028 // Write the horizontal lines for multiline annotations
1029 // (only the first and last lines need this).
1030 //
1031 // After this we will have:
1032 //
1033 // 2 | fn foo() {
1034 // | __________
1035 // |
1036 // |
1037 // 3 |
1038 // 4 | }
1039 // | _
1040 for &(pos, annotation) in &annotations_position {
1041 let underline = self.underline(annotation.is_primary);
1042 let pos = pos + 1;
1043 match annotation.annotation_type {
1044 AnnotationType::MultilineStart(depth) | AnnotationType::MultilineEnd(depth) => {
1045 let pre: usize = source_string
1046 .chars()
1047 .take(annotation.start_col.file)
1048 .skip(left)
1049 .map(|c| char_width(c))
1050 .sum();
1051 self.draw_range(
1052 buffer,
1053 underline.multiline_horizontal,
1054 line_offset + pos,
1055 width_offset + depth,
1056 code_offset + pre,
1057 underline.style,
1058 );
1059 }
1060 _ => {}
1061 }
1062 }
1063
1064 // Write the vertical lines for labels that are on a different line as the underline.
1065 //
1066 // After this we will have:
1067 //
1068 // 2 | fn foo() {
1069 // | __________
1070 // | | |
1071 // | |
1072 // 3 | |
1073 // 4 | | }
1074 // | |_
1075 for &(pos, annotation) in &annotations_position {
1076 let underline = self.underline(annotation.is_primary);
1077 let pos = pos + 1;
1078
1079 let code_offset = code_offset
1080 + source_string
1081 .chars()
1082 .take(annotation.start_col.file)
1083 .skip(left)
1084 .map(|c| char_width(c))
1085 .sum::<usize>();
1086 if pos > 1 && (annotation.has_label() || annotation.takes_space()) {
1087 for p in line_offset + 1..=line_offset + pos {
1088 buffer.putc(
1089 p,
1090 code_offset,
1091 match annotation.annotation_type {
1092 AnnotationType::MultilineLine(_) => underline.multiline_vertical,
1093 _ => underline.vertical_text_line,
1094 },
1095 underline.style,
1096 );
1097 }
1098 if let AnnotationType::MultilineStart(_) = annotation.annotation_type {
1099 buffer.putc(
1100 line_offset + pos,
1101 code_offset,
1102 underline.bottom_right,
1103 underline.style,
1104 );
1105 }
1106 if let AnnotationType::MultilineEnd(_) = annotation.annotation_type
1107 && annotation.has_label()
1108 {
1109 buffer.putc(
1110 line_offset + pos,
1111 code_offset,
1112 underline.multiline_bottom_right_with_text,
1113 underline.style,
1114 );
1115 }
1116 }
1117 match annotation.annotation_type {
1118 AnnotationType::MultilineStart(depth) => {
1119 buffer.putc(
1120 line_offset + pos,
1121 width_offset + depth - 1,
1122 underline.top_left,
1123 underline.style,
1124 );
1125 for p in line_offset + pos + 1..line_offset + line_len + 2 {
1126 buffer.putc(
1127 p,
1128 width_offset + depth - 1,
1129 underline.multiline_vertical,
1130 underline.style,
1131 );
1132 }
1133 }
1134 AnnotationType::MultilineEnd(depth) => {
1135 for p in line_offset..line_offset + pos {
1136 buffer.putc(
1137 p,
1138 width_offset + depth - 1,
1139 underline.multiline_vertical,
1140 underline.style,
1141 );
1142 }
1143 buffer.putc(
1144 line_offset + pos,
1145 width_offset + depth - 1,
1146 underline.bottom_left,
1147 underline.style,
1148 );
1149 }
1150 _ => (),
1151 }
1152 }
1153
1154 // Write the labels on the annotations that actually have a label.
1155 //
1156 // After this we will have:
1157 //
1158 // 2 | fn foo() {
1159 // | __________
1160 // | |
1161 // | something about `foo`
1162 // 3 |
1163 // 4 | }
1164 // | _ test
1165 for &(pos, annotation) in &annotations_position {
1166 let style =
1167 if annotation.is_primary { Style::LabelPrimary } else { Style::LabelSecondary };
1168 let (pos, col) = if pos == 0 {
1169 let pre: usize = source_string
1170 .chars()
1171 .take(annotation.end_col.file)
1172 .skip(left)
1173 .map(|c| char_width(c))
1174 .sum();
1175 if annotation.end_col.file == 0 {
1176 (pos + 1, (pre + 2))
1177 } else {
1178 let pad = if annotation.end_col.file - annotation.start_col.file == 0 {
1179 2
1180 } else {
1181 1
1182 };
1183 (pos + 1, (pre + pad))
1184 }
1185 } else {
1186 let pre: usize = source_string
1187 .chars()
1188 .take(annotation.start_col.file)
1189 .skip(left)
1190 .map(|c| char_width(c))
1191 .sum();
1192 (pos + 2, pre)
1193 };
1194 if let Some(ref label) = annotation.label {
1195 buffer.puts(line_offset + pos, code_offset + col, label, style);
1196 }
1197 }
1198
1199 // Sort from biggest span to smallest span so that smaller spans are
1200 // represented in the output:
1201 //
1202 // x | fn foo()
1203 // | ^^^---^^
1204 // | | |
1205 // | | something about `foo`
1206 // | something about `fn foo()`
1207 annotations_position.sort_by_key(|(_, ann)| {
1208 // Decreasing order. When annotations share the same length, prefer `Primary`.
1209 (Reverse(ann.len()), ann.is_primary)
1210 });
1211
1212 // Write the underlines.
1213 //
1214 // After this we will have:
1215 //
1216 // 2 | fn foo() {
1217 // | ____-_____^
1218 // | |
1219 // | something about `foo`
1220 // 3 |
1221 // 4 | }
1222 // | _^ test
1223 for &(pos, annotation) in &annotations_position {
1224 let uline = self.underline(annotation.is_primary);
1225 let width = annotation.end_col.file - annotation.start_col.file;
1226 let previous: String =
1227 source_string.chars().take(annotation.start_col.file).skip(left).collect();
1228 let underlined: String =
1229 source_string.chars().skip(annotation.start_col.file).take(width).collect();
1230 debug!(?previous, ?underlined);
1231 let code_offset = code_offset
1232 + source_string
1233 .chars()
1234 .take(annotation.start_col.file)
1235 .skip(left)
1236 .map(|c| char_width(c))
1237 .sum::<usize>();
1238 let ann_width: usize = source_string
1239 .chars()
1240 .skip(annotation.start_col.file)
1241 .take(width)
1242 .map(|c| char_width(c))
1243 .sum();
1244 let ann_width = if ann_width == 0
1245 && matches!(annotation.annotation_type, AnnotationType::Singleline)
1246 {
1247 1
1248 } else {
1249 ann_width
1250 };
1251 for p in 0..ann_width {
1252 // The default span label underline.
1253 buffer.putc(line_offset + 1, code_offset + p, uline.underline, uline.style);
1254 }
1255
1256 if pos == 0
1257 && matches!(
1258 annotation.annotation_type,
1259 AnnotationType::MultilineStart(_) | AnnotationType::MultilineEnd(_)
1260 )
1261 {
1262 // The beginning of a multiline span with its leftward moving line on the same line.
1263 buffer.putc(
1264 line_offset + 1,
1265 code_offset,
1266 match annotation.annotation_type {
1267 AnnotationType::MultilineStart(_) => uline.top_right_flat,
1268 AnnotationType::MultilineEnd(_) => uline.multiline_end_same_line,
1269 _ => panic!("unexpected annotation type: {annotation:?}"),
1270 },
1271 uline.style,
1272 );
1273 } else if pos != 0
1274 && matches!(
1275 annotation.annotation_type,
1276 AnnotationType::MultilineStart(_) | AnnotationType::MultilineEnd(_)
1277 )
1278 {
1279 // The beginning of a multiline span with its leftward moving line on another line,
1280 // so we start going down first.
1281 buffer.putc(
1282 line_offset + 1,
1283 code_offset,
1284 match annotation.annotation_type {
1285 AnnotationType::MultilineStart(_) => uline.multiline_start_down,
1286 AnnotationType::MultilineEnd(_) => uline.multiline_end_up,
1287 _ => panic!("unexpected annotation type: {annotation:?}"),
1288 },
1289 uline.style,
1290 );
1291 } else if pos != 0 && annotation.has_label() {
1292 // The beginning of a span label with an actual label, we'll point down.
1293 buffer.putc(line_offset + 1, code_offset, uline.label_start, uline.style);
1294 }
1295 }
1296
1297 // We look for individual *long* spans, and we trim the *middle*, so that we render
1298 // LL | ...= [0, 0, 0, ..., 0, 0];
1299 // | ^^^^^^^^^^...^^^^^^^ expected `&[u8]`, found `[{integer}; 1680]`
1300 for (i, (_pos, annotation)) in annotations_position.iter().enumerate() {
1301 // Skip cases where multiple spans overlap each other.
1302 if overlap[i] {
1303 continue;
1304 };
1305 let AnnotationType::Singleline = annotation.annotation_type else { continue };
1306 let width = annotation.end_col.display - annotation.start_col.display;
1307 if width > margin.column_width * 2 && width > 10 {
1308 // If the terminal is *too* small, we keep at least a tiny bit of the span for
1309 // display.
1310 let pad = max(margin.column_width / 3, 5);
1311 // Code line
1312 buffer.replace(
1313 line_offset,
1314 annotation.start_col.file + pad,
1315 annotation.end_col.file - pad,
1316 self.margin(),
1317 );
1318 // Underline line
1319 buffer.replace(
1320 line_offset + 1,
1321 annotation.start_col.file + pad,
1322 annotation.end_col.file - pad,
1323 self.margin(),
1324 );
1325 }
1326 }
1327 annotations_position
1328 .iter()
1329 .filter_map(|&(_, annotation)| match annotation.annotation_type {
1330 AnnotationType::MultilineStart(p) | AnnotationType::MultilineEnd(p) => {
1331 let style = if annotation.is_primary {
1332 Style::LabelPrimary
1333 } else {
1334 Style::LabelSecondary
1335 };
1336 Some((p, style))
1337 }
1338 _ => None,
1339 })
1340 .collect::<Vec<_>>()
1341 }
1342
1343 fn get_multispan_max_line_num(&mut self, msp: &MultiSpan) -> usize {
1344 let Some(ref sm) = self.sm else {
1345 return 0;
1346 };
1347
1348 let will_be_emitted = |span: Span| {
1349 !span.is_dummy() && {
1350 let file = sm.lookup_source_file(span.hi());
1351 should_show_source_code(&self.ignored_directories_in_source_blocks, sm, &file)
1352 }
1353 };
1354
1355 let mut max = 0;
1356 for primary_span in msp.primary_spans() {
1357 if will_be_emitted(*primary_span) {
1358 let hi = sm.lookup_char_pos(primary_span.hi());
1359 max = (hi.line).max(max);
1360 }
1361 }
1362 if !self.short_message {
1363 for span_label in msp.span_labels() {
1364 if will_be_emitted(span_label.span) {
1365 let hi = sm.lookup_char_pos(span_label.span.hi());
1366 max = (hi.line).max(max);
1367 }
1368 }
1369 }
1370
1371 max
1372 }
1373
1374 fn get_max_line_num(&mut self, span: &MultiSpan, children: &[Subdiag]) -> usize {
1375 let primary = self.get_multispan_max_line_num(span);
1376 children
1377 .iter()
1378 .map(|sub| self.get_multispan_max_line_num(&sub.span))
1379 .max()
1380 .unwrap_or(0)
1381 .max(primary)
1382 }
1383
1384 /// Adds a left margin to every line but the first, given a padding length and the label being
1385 /// displayed, keeping the provided highlighting.
1386 fn msgs_to_buffer(
1387 &self,
1388 buffer: &mut StyledBuffer,
1389 msgs: &[(DiagMessage, Style)],
1390 args: &FluentArgs<'_>,
1391 padding: usize,
1392 label: &str,
1393 override_style: Option<Style>,
1394 ) -> usize {
1395 // The extra 5 ` ` is padding that's always needed to align to the `note: `:
1396 //
1397 // error: message
1398 // --> file.rs:13:20
1399 // |
1400 // 13 | <CODE>
1401 // | ^^^^
1402 // |
1403 // = note: multiline
1404 // message
1405 // ++^^^----xx
1406 // | | | |
1407 // | | | magic `2`
1408 // | | length of label
1409 // | magic `3`
1410 // `max_line_num_len`
1411 let padding = " ".repeat(padding + label.len() + 5);
1412
1413 /// Returns `override` if it is present and `style` is `NoStyle` or `style` otherwise
1414 fn style_or_override(style: Style, override_: Option<Style>) -> Style {
1415 match (style, override_) {
1416 (Style::NoStyle, Some(override_)) => override_,
1417 _ => style,
1418 }
1419 }
1420
1421 let mut line_number = 0;
1422
1423 // Provided the following diagnostic message:
1424 //
1425 // let msgs = vec![
1426 // ("
1427 // ("highlighted multiline\nstring to\nsee how it ", Style::NoStyle),
1428 // ("looks", Style::Highlight),
1429 // ("with\nvery ", Style::NoStyle),
1430 // ("weird", Style::Highlight),
1431 // (" formats\n", Style::NoStyle),
1432 // ("see?", Style::Highlight),
1433 // ];
1434 //
1435 // the expected output on a note is (* surround the highlighted text)
1436 //
1437 // = note: highlighted multiline
1438 // string to
1439 // see how it *looks* with
1440 // very *weird* formats
1441 // see?
1442 for (text, style) in msgs.iter() {
1443 let text = self.translator.translate_message(text, args).map_err(Report::new).unwrap();
1444 let text = &normalize_whitespace(&text);
1445 let lines = text.split('\n').collect::<Vec<_>>();
1446 if lines.len() > 1 {
1447 for (i, line) in lines.iter().enumerate() {
1448 if i != 0 {
1449 line_number += 1;
1450 buffer.append(line_number, &padding, Style::NoStyle);
1451 }
1452 buffer.append(line_number, line, style_or_override(*style, override_style));
1453 }
1454 } else {
1455 buffer.append(line_number, text, style_or_override(*style, override_style));
1456 }
1457 }
1458 line_number
1459 }
1460
1461 #[instrument(level = "trace", skip(self, args), ret)]
1462 fn emit_messages_default_inner(
1463 &mut self,
1464 msp: &MultiSpan,
1465 msgs: &[(DiagMessage, Style)],
1466 args: &FluentArgs<'_>,
1467 code: &Option<ErrCode>,
1468 level: &Level,
1469 max_line_num_len: usize,
1470 is_secondary: bool,
1471 emitted_at: Option<&DiagLocation>,
1472 is_cont: bool,
1473 ) -> io::Result<()> {
1474 let mut buffer = StyledBuffer::new();
1475
1476 if !msp.has_primary_spans() && !msp.has_span_labels() && is_secondary && !self.short_message
1477 {
1478 // This is a secondary message with no span info
1479 for _ in 0..max_line_num_len {
1480 buffer.prepend(0, " ", Style::NoStyle);
1481 }
1482 self.draw_note_separator(&mut buffer, 0, max_line_num_len + 1, is_cont);
1483 if *level != Level::FailureNote {
1484 buffer.append(0, level.to_str(), Style::MainHeaderMsg);
1485 buffer.append(0, ": ", Style::NoStyle);
1486 }
1487 let printed_lines =
1488 self.msgs_to_buffer(&mut buffer, msgs, args, max_line_num_len, "note", None);
1489 if is_cont && matches!(self.theme, OutputTheme::Unicode) {
1490 // There's another note after this one, associated to the subwindow above.
1491 // We write additional vertical lines to join them:
1492 // ╭▸ test.rs:3:3
1493 // │
1494 // 3 │ code
1495 // │ ━━━━
1496 // │
1497 // ├ note: foo
1498 // │ bar
1499 // ╰ note: foo
1500 // bar
1501 for i in 1..=printed_lines {
1502 self.draw_col_separator_no_space(&mut buffer, i, max_line_num_len + 1);
1503 }
1504 }
1505 } else {
1506 let mut label_width = 0;
1507 // The failure note level itself does not provide any useful diagnostic information
1508 if *level != Level::FailureNote {
1509 buffer.append(0, level.to_str(), Style::Level(*level));
1510 label_width += level.to_str().len();
1511 }
1512 if let Some(code) = code {
1513 buffer.append(0, "[", Style::Level(*level));
1514 let code = if let TerminalUrl::Yes = self.terminal_url {
1515 let path = "https://doc.rust-lang.org/error_codes";
1516 format!("\x1b]8;;{path}/{code}.html\x07{code}\x1b]8;;\x07")
1517 } else {
1518 code.to_string()
1519 };
1520 buffer.append(0, &code, Style::Level(*level));
1521 buffer.append(0, "]", Style::Level(*level));
1522 label_width += 2 + code.len();
1523 }
1524 let header_style = if is_secondary {
1525 Style::HeaderMsg
1526 } else if self.short_message {
1527 // For short messages avoid bolding the message, as it doesn't look great (#63835).
1528 Style::NoStyle
1529 } else {
1530 Style::MainHeaderMsg
1531 };
1532 if *level != Level::FailureNote {
1533 buffer.append(0, ": ", header_style);
1534 label_width += 2;
1535 }
1536 let mut line = 0;
1537 for (text, style) in msgs.iter() {
1538 let text =
1539 self.translator.translate_message(text, args).map_err(Report::new).unwrap();
1540 // Account for newlines to align output to its label.
1541 for text in normalize_whitespace(&text).lines() {
1542 buffer.append(
1543 line,
1544 &format!(
1545 "{}{}",
1546 if line == 0 { String::new() } else { " ".repeat(label_width) },
1547 text
1548 ),
1549 match style {
1550 Style::Highlight => *style,
1551 _ => header_style,
1552 },
1553 );
1554 line += 1;
1555 }
1556 // We add lines above, but if the last line has no explicit newline (which would
1557 // yield an empty line), then we revert one line up to continue with the next
1558 // styled text chunk on the same line as the last one from the prior one. Otherwise
1559 // every `text` would appear on their own line (because even though they didn't end
1560 // in '\n', they advanced `line` by one).
1561 if line > 0 {
1562 line -= 1;
1563 }
1564 }
1565 if self.short_message {
1566 let labels = msp
1567 .span_labels()
1568 .into_iter()
1569 .filter_map(|label| match label.label {
1570 Some(msg) if label.is_primary => {
1571 let text = self.translator.translate_message(&msg, args).ok()?;
1572 if !text.trim().is_empty() { Some(text.to_string()) } else { None }
1573 }
1574 _ => None,
1575 })
1576 .collect::<Vec<_>>()
1577 .join(", ");
1578 if !labels.is_empty() {
1579 buffer.append(line, ": ", Style::NoStyle);
1580 buffer.append(line, &labels, Style::NoStyle);
1581 }
1582 }
1583 }
1584 let mut annotated_files = FileWithAnnotatedLines::collect_annotations(self, args, msp);
1585 trace!("{annotated_files:#?}");
1586
1587 // Make sure our primary file comes first
1588 let primary_span = msp.primary_span().unwrap_or_default();
1589 let (Some(sm), false) = (self.sm.as_ref(), primary_span.is_dummy()) else {
1590 // If we don't have span information, emit and exit
1591 return emit_to_destination(&buffer.render(), level, &mut self.dst, self.short_message);
1592 };
1593 let primary_lo = sm.lookup_char_pos(primary_span.lo());
1594 if let Ok(pos) =
1595 annotated_files.binary_search_by(|x| x.file.name.cmp(&primary_lo.file.name))
1596 {
1597 annotated_files.swap(0, pos);
1598 }
1599
1600 // Print out the annotate source lines that correspond with the error
1601 for annotated_file in annotated_files {
1602 // we can't annotate anything if the source is unavailable.
1603 if !should_show_source_code(
1604 &self.ignored_directories_in_source_blocks,
1605 sm,
1606 &annotated_file.file,
1607 ) {
1608 if !self.short_message {
1609 // We'll just print an unannotated message.
1610 for (annotation_id, line) in annotated_file.lines.iter().enumerate() {
1611 let mut annotations = line.annotations.clone();
1612 annotations.sort_by_key(|a| Reverse(a.start_col));
1613 let mut line_idx = buffer.num_lines();
1614
1615 let labels: Vec<_> = annotations
1616 .iter()
1617 .filter_map(|a| Some((a.label.as_ref()?, a.is_primary)))
1618 .filter(|(l, _)| !l.is_empty())
1619 .collect();
1620
1621 if annotation_id == 0 || !labels.is_empty() {
1622 buffer.append(
1623 line_idx,
1624 &format!(
1625 "{}:{}:{}",
1626 sm.filename_for_diagnostics(&annotated_file.file.name),
1627 sm.doctest_offset_line(
1628 &annotated_file.file.name,
1629 line.line_index
1630 ),
1631 annotations[0].start_col.file + 1,
1632 ),
1633 Style::LineAndColumn,
1634 );
1635 if annotation_id == 0 {
1636 buffer.prepend(line_idx, self.file_start(), Style::LineNumber);
1637 } else {
1638 buffer.prepend(
1639 line_idx,
1640 self.secondary_file_start(),
1641 Style::LineNumber,
1642 );
1643 }
1644 for _ in 0..max_line_num_len {
1645 buffer.prepend(line_idx, " ", Style::NoStyle);
1646 }
1647 line_idx += 1;
1648 }
1649 for (label, is_primary) in labels.into_iter() {
1650 let style = if is_primary {
1651 Style::LabelPrimary
1652 } else {
1653 Style::LabelSecondary
1654 };
1655 let pipe = self.col_separator();
1656 buffer.prepend(line_idx, &format!(" {pipe}"), Style::LineNumber);
1657 for _ in 0..max_line_num_len {
1658 buffer.prepend(line_idx, " ", Style::NoStyle);
1659 }
1660 line_idx += 1;
1661 let chr = self.note_separator();
1662 buffer.append(line_idx, &format!(" {chr} note: "), style);
1663 for _ in 0..max_line_num_len {
1664 buffer.prepend(line_idx, " ", Style::NoStyle);
1665 }
1666 buffer.append(line_idx, label, style);
1667 line_idx += 1;
1668 }
1669 }
1670 }
1671 continue;
1672 }
1673
1674 // print out the span location and spacer before we print the annotated source
1675 // to do this, we need to know if this span will be primary
1676 let is_primary = primary_lo.file.name == annotated_file.file.name;
1677 if is_primary {
1678 let loc = primary_lo.clone();
1679 if !self.short_message {
1680 // remember where we are in the output buffer for easy reference
1681 let buffer_msg_line_offset = buffer.num_lines();
1682
1683 buffer.prepend(buffer_msg_line_offset, self.file_start(), Style::LineNumber);
1684 buffer.append(
1685 buffer_msg_line_offset,
1686 &format!(
1687 "{}:{}:{}",
1688 sm.filename_for_diagnostics(&loc.file.name),
1689 sm.doctest_offset_line(&loc.file.name, loc.line),
1690 loc.col.0 + 1,
1691 ),
1692 Style::LineAndColumn,
1693 );
1694 for _ in 0..max_line_num_len {
1695 buffer.prepend(buffer_msg_line_offset, " ", Style::NoStyle);
1696 }
1697 } else {
1698 buffer.prepend(
1699 0,
1700 &format!(
1701 "{}:{}:{}: ",
1702 sm.filename_for_diagnostics(&loc.file.name),
1703 sm.doctest_offset_line(&loc.file.name, loc.line),
1704 loc.col.0 + 1,
1705 ),
1706 Style::LineAndColumn,
1707 );
1708 }
1709 } else if !self.short_message {
1710 // remember where we are in the output buffer for easy reference
1711 let buffer_msg_line_offset = buffer.num_lines();
1712
1713 // Add spacing line, as shown:
1714 // --> $DIR/file:54:15
1715 // |
1716 // LL | code
1717 // | ^^^^
1718 // | (<- It prints *this* line)
1719 // ::: $DIR/other_file.rs:15:5
1720 // |
1721 // LL | code
1722 // | ----
1723 self.draw_col_separator_no_space(
1724 &mut buffer,
1725 buffer_msg_line_offset,
1726 max_line_num_len + 1,
1727 );
1728
1729 // Then, the secondary file indicator
1730 buffer.prepend(
1731 buffer_msg_line_offset + 1,
1732 self.secondary_file_start(),
1733 Style::LineNumber,
1734 );
1735 let loc = if let Some(first_line) = annotated_file.lines.first() {
1736 let col = if let Some(first_annotation) = first_line.annotations.first() {
1737 format!(":{}", first_annotation.start_col.file + 1)
1738 } else {
1739 String::new()
1740 };
1741 format!(
1742 "{}:{}{}",
1743 sm.filename_for_diagnostics(&annotated_file.file.name),
1744 sm.doctest_offset_line(&annotated_file.file.name, first_line.line_index),
1745 col
1746 )
1747 } else {
1748 format!("{}", sm.filename_for_diagnostics(&annotated_file.file.name))
1749 };
1750 buffer.append(buffer_msg_line_offset + 1, &loc, Style::LineAndColumn);
1751 for _ in 0..max_line_num_len {
1752 buffer.prepend(buffer_msg_line_offset + 1, " ", Style::NoStyle);
1753 }
1754 }
1755
1756 if !self.short_message {
1757 // Put in the spacer between the location and annotated source
1758 let buffer_msg_line_offset = buffer.num_lines();
1759 self.draw_col_separator_no_space(
1760 &mut buffer,
1761 buffer_msg_line_offset,
1762 max_line_num_len + 1,
1763 );
1764
1765 // Contains the vertical lines' positions for active multiline annotations
1766 let mut multilines = FxIndexMap::default();
1767
1768 // Get the left-side margin to remove it
1769 let mut whitespace_margin = usize::MAX;
1770 for line_idx in 0..annotated_file.lines.len() {
1771 let file = Arc::clone(&annotated_file.file);
1772 let line = &annotated_file.lines[line_idx];
1773 if let Some(source_string) =
1774 line.line_index.checked_sub(1).and_then(|l| file.get_line(l))
1775 {
1776 // Whitespace can only be removed (aka considered leading)
1777 // if the lexer considers it whitespace.
1778 // non-rustc_lexer::is_whitespace() chars are reported as an
1779 // error (ex. no-break-spaces \u{a0}), and thus can't be considered
1780 // for removal during error reporting.
1781 // FIXME: doesn't account for '\t' properly.
1782 let leading_whitespace = source_string
1783 .chars()
1784 .take_while(|c| rustc_lexer::is_whitespace(*c))
1785 .count();
1786 if source_string.chars().any(|c| !rustc_lexer::is_whitespace(c)) {
1787 whitespace_margin = min(whitespace_margin, leading_whitespace);
1788 }
1789 }
1790 }
1791 if whitespace_margin == usize::MAX {
1792 whitespace_margin = 0;
1793 }
1794
1795 // Left-most column any visible span points at.
1796 let mut span_left_margin = usize::MAX;
1797 for line in &annotated_file.lines {
1798 for ann in &line.annotations {
1799 span_left_margin = min(span_left_margin, ann.start_col.file);
1800 span_left_margin = min(span_left_margin, ann.end_col.file);
1801 }
1802 }
1803 if span_left_margin == usize::MAX {
1804 span_left_margin = 0;
1805 }
1806
1807 // Right-most column any visible span points at.
1808 let mut span_right_margin = 0;
1809 let mut label_right_margin = 0;
1810 let mut max_line_len = 0;
1811 for line in &annotated_file.lines {
1812 max_line_len = max(
1813 max_line_len,
1814 line.line_index
1815 .checked_sub(1)
1816 .and_then(|l| annotated_file.file.get_line(l))
1817 .map_or(0, |s| s.len()),
1818 );
1819 for ann in &line.annotations {
1820 span_right_margin = max(span_right_margin, ann.start_col.file);
1821 span_right_margin = max(span_right_margin, ann.end_col.file);
1822 // FIXME: account for labels not in the same line
1823 let label_right = ann.label.as_ref().map_or(0, |l| l.len() + 1);
1824 label_right_margin =
1825 max(label_right_margin, ann.end_col.file + label_right);
1826 }
1827 }
1828
1829 let width_offset = 3 + max_line_num_len;
1830 let code_offset = if annotated_file.multiline_depth == 0 {
1831 width_offset
1832 } else {
1833 width_offset + annotated_file.multiline_depth + 1
1834 };
1835
1836 let column_width = self.column_width(code_offset);
1837
1838 let margin = Margin::new(
1839 whitespace_margin,
1840 span_left_margin,
1841 span_right_margin,
1842 label_right_margin,
1843 column_width,
1844 max_line_len,
1845 );
1846
1847 // Next, output the annotate source for this file
1848 for line_idx in 0..annotated_file.lines.len() {
1849 let previous_buffer_line = buffer.num_lines();
1850
1851 let depths = self.render_source_line(
1852 &mut buffer,
1853 Arc::clone(&annotated_file.file),
1854 &annotated_file.lines[line_idx],
1855 width_offset,
1856 code_offset,
1857 margin,
1858 !is_cont && line_idx + 1 == annotated_file.lines.len(),
1859 );
1860
1861 let mut to_add = FxHashMap::default();
1862
1863 for (depth, style) in depths {
1864 // FIXME(#120456) - is `swap_remove` correct?
1865 if multilines.swap_remove(&depth).is_none() {
1866 to_add.insert(depth, style);
1867 }
1868 }
1869
1870 // Set the multiline annotation vertical lines to the left of
1871 // the code in this line.
1872 for (depth, style) in &multilines {
1873 for line in previous_buffer_line..buffer.num_lines() {
1874 self.draw_multiline_line(
1875 &mut buffer,
1876 line,
1877 width_offset,
1878 *depth,
1879 *style,
1880 );
1881 }
1882 }
1883 // check to see if we need to print out or elide lines that come between
1884 // this annotated line and the next one.
1885 if line_idx < (annotated_file.lines.len() - 1) {
1886 let line_idx_delta = annotated_file.lines[line_idx + 1].line_index
1887 - annotated_file.lines[line_idx].line_index;
1888 if line_idx_delta > 2 {
1889 let last_buffer_line_num = buffer.num_lines();
1890 self.draw_line_separator(
1891 &mut buffer,
1892 last_buffer_line_num,
1893 width_offset,
1894 );
1895
1896 // Set the multiline annotation vertical lines on `...` bridging line.
1897 for (depth, style) in &multilines {
1898 self.draw_multiline_line(
1899 &mut buffer,
1900 last_buffer_line_num,
1901 width_offset,
1902 *depth,
1903 *style,
1904 );
1905 }
1906 if let Some(line) = annotated_file.lines.get(line_idx) {
1907 for ann in &line.annotations {
1908 if let AnnotationType::MultilineStart(pos) = ann.annotation_type
1909 {
1910 // In the case where we have elided the entire start of the
1911 // multispan because those lines were empty, we still need
1912 // to draw the `|`s across the `...`.
1913 self.draw_multiline_line(
1914 &mut buffer,
1915 last_buffer_line_num,
1916 width_offset,
1917 pos,
1918 if ann.is_primary {
1919 Style::UnderlinePrimary
1920 } else {
1921 Style::UnderlineSecondary
1922 },
1923 );
1924 }
1925 }
1926 }
1927 } else if line_idx_delta == 2 {
1928 let unannotated_line = annotated_file
1929 .file
1930 .get_line(annotated_file.lines[line_idx].line_index)
1931 .unwrap_or_else(|| Cow::from(""));
1932
1933 let last_buffer_line_num = buffer.num_lines();
1934
1935 self.draw_line(
1936 &mut buffer,
1937 &normalize_whitespace(&unannotated_line),
1938 annotated_file.lines[line_idx + 1].line_index - 1,
1939 last_buffer_line_num,
1940 width_offset,
1941 code_offset,
1942 margin,
1943 );
1944
1945 for (depth, style) in &multilines {
1946 self.draw_multiline_line(
1947 &mut buffer,
1948 last_buffer_line_num,
1949 width_offset,
1950 *depth,
1951 *style,
1952 );
1953 }
1954 if let Some(line) = annotated_file.lines.get(line_idx) {
1955 for ann in &line.annotations {
1956 if let AnnotationType::MultilineStart(pos) = ann.annotation_type
1957 {
1958 self.draw_multiline_line(
1959 &mut buffer,
1960 last_buffer_line_num,
1961 width_offset,
1962 pos,
1963 if ann.is_primary {
1964 Style::UnderlinePrimary
1965 } else {
1966 Style::UnderlineSecondary
1967 },
1968 );
1969 }
1970 }
1971 }
1972 }
1973 }
1974
1975 multilines.extend(&to_add);
1976 }
1977 }
1978 trace!("buffer: {:#?}", buffer.render());
1979 }
1980
1981 if let Some(tracked) = emitted_at {
1982 let track = format!("-Ztrack-diagnostics: created at {tracked}");
1983 let len = buffer.num_lines();
1984 buffer.append(len, &track, Style::NoStyle);
1985 }
1986
1987 // final step: take our styled buffer, render it, then output it
1988 emit_to_destination(&buffer.render(), level, &mut self.dst, self.short_message)?;
1989
1990 Ok(())
1991 }
1992
1993 fn column_width(&self, code_offset: usize) -> usize {
1994 if let Some(width) = self.diagnostic_width {
1995 width.saturating_sub(code_offset)
1996 } else if self.ui_testing || cfg!(miri) {
1997 DEFAULT_COLUMN_WIDTH
1998 } else {
1999 termize::dimensions()
2000 .map(|(w, _)| w.saturating_sub(code_offset))
2001 .unwrap_or(DEFAULT_COLUMN_WIDTH)
2002 }
2003 }
2004
2005 fn emit_suggestion_default(
2006 &mut self,
2007 span: &MultiSpan,
2008 suggestion: &CodeSuggestion,
2009 args: &FluentArgs<'_>,
2010 level: &Level,
2011 max_line_num_len: usize,
2012 ) -> io::Result<()> {
2013 let Some(ref sm) = self.sm else {
2014 return Ok(());
2015 };
2016
2017 // Render the replacements for each suggestion
2018 let suggestions = suggestion.splice_lines(sm);
2019 debug!(?suggestions);
2020
2021 if suggestions.is_empty() {
2022 // Here we check if there are suggestions that have actual code changes. We sometimes
2023 // suggest the same code that is already there, instead of changing how we produce the
2024 // suggestions and filtering there, we just don't emit the suggestion.
2025 // Suggestions coming from macros can also have malformed spans. This is a heavy handed
2026 // approach to avoid ICEs by ignoring the suggestion outright.
2027 return Ok(());
2028 }
2029
2030 let mut buffer = StyledBuffer::new();
2031
2032 // Render the suggestion message
2033 buffer.append(0, level.to_str(), Style::Level(*level));
2034 buffer.append(0, ": ", Style::HeaderMsg);
2035
2036 let mut msg = vec![(suggestion.msg.to_owned(), Style::NoStyle)];
2037 if suggestions
2038 .iter()
2039 .take(MAX_SUGGESTIONS)
2040 .any(|(_, _, _, only_capitalization)| *only_capitalization)
2041 {
2042 msg.push((" (notice the capitalization difference)".into(), Style::NoStyle));
2043 }
2044 self.msgs_to_buffer(
2045 &mut buffer,
2046 &msg,
2047 args,
2048 max_line_num_len,
2049 "suggestion",
2050 Some(Style::HeaderMsg),
2051 );
2052
2053 let other_suggestions = suggestions.len().saturating_sub(MAX_SUGGESTIONS);
2054
2055 let mut row_num = 2;
2056 for (i, (complete, parts, highlights, _)) in
2057 suggestions.into_iter().enumerate().take(MAX_SUGGESTIONS)
2058 {
2059 debug!(?complete, ?parts, ?highlights);
2060
2061 let has_deletion =
2062 parts.iter().any(|p| p.is_deletion(sm) || p.is_destructive_replacement(sm));
2063 let is_multiline = complete.lines().count() > 1;
2064
2065 if i == 0 {
2066 self.draw_col_separator_start(&mut buffer, row_num - 1, max_line_num_len + 1);
2067 } else {
2068 buffer.puts(
2069 row_num - 1,
2070 max_line_num_len + 1,
2071 self.multi_suggestion_separator(),
2072 Style::LineNumber,
2073 );
2074 }
2075 if let Some(span) = span.primary_span() {
2076 // Compare the primary span of the diagnostic with the span of the suggestion
2077 // being emitted. If they belong to the same file, we don't *need* to show the
2078 // file name, saving in verbosity, but if it *isn't* we do need it, otherwise we're
2079 // telling users to make a change but not clarifying *where*.
2080 let loc = sm.lookup_char_pos(parts[0].span.lo());
2081 if loc.file.name != sm.span_to_filename(span) && loc.file.name.is_real() {
2082 // --> file.rs:line:col
2083 // |
2084 let arrow = self.file_start();
2085 buffer.puts(row_num - 1, 0, arrow, Style::LineNumber);
2086 let filename = sm.filename_for_diagnostics(&loc.file.name);
2087 let offset = sm.doctest_offset_line(&loc.file.name, loc.line);
2088 let message = format!("{}:{}:{}", filename, offset, loc.col.0 + 1);
2089 if row_num == 2 {
2090 let col = usize::max(max_line_num_len + 1, arrow.len());
2091 buffer.puts(1, col, &message, Style::LineAndColumn);
2092 } else {
2093 buffer.append(row_num - 1, &message, Style::LineAndColumn);
2094 }
2095 for _ in 0..max_line_num_len {
2096 buffer.prepend(row_num - 1, " ", Style::NoStyle);
2097 }
2098 self.draw_col_separator_no_space(&mut buffer, row_num, max_line_num_len + 1);
2099 row_num += 1;
2100 }
2101 }
2102 let show_code_change = if has_deletion && !is_multiline {
2103 DisplaySuggestion::Diff
2104 } else if let [part] = &parts[..]
2105 && part.snippet.ends_with('\n')
2106 && part.snippet.trim() == complete.trim()
2107 {
2108 // We are adding a line(s) of code before code that was already there.
2109 DisplaySuggestion::Add
2110 } else if (parts.len() != 1 || parts[0].snippet.trim() != complete.trim())
2111 && !is_multiline
2112 {
2113 DisplaySuggestion::Underline
2114 } else {
2115 DisplaySuggestion::None
2116 };
2117
2118 if let DisplaySuggestion::Diff = show_code_change {
2119 row_num += 1;
2120 }
2121
2122 let file_lines = sm
2123 .span_to_lines(parts[0].span)
2124 .expect("span_to_lines failed when emitting suggestion");
2125
2126 assert!(!file_lines.lines.is_empty() || parts[0].span.is_dummy());
2127
2128 let line_start = sm.lookup_char_pos(parts[0].span.lo()).line;
2129 let mut lines = complete.lines();
2130 if lines.clone().next().is_none() {
2131 // Account for a suggestion to completely remove a line(s) with whitespace (#94192).
2132 let line_end = sm.lookup_char_pos(parts[0].span.hi()).line;
2133 for line in line_start..=line_end {
2134 buffer.puts(
2135 row_num - 1 + line - line_start,
2136 0,
2137 &self.maybe_anonymized(line),
2138 Style::LineNumber,
2139 );
2140 buffer.puts(
2141 row_num - 1 + line - line_start,
2142 max_line_num_len + 1,
2143 "- ",
2144 Style::Removal,
2145 );
2146 buffer.puts(
2147 row_num - 1 + line - line_start,
2148 max_line_num_len + 3,
2149 &normalize_whitespace(&file_lines.file.get_line(line - 1).unwrap()),
2150 Style::Removal,
2151 );
2152 }
2153 row_num += line_end - line_start;
2154 }
2155 let mut unhighlighted_lines = Vec::new();
2156 let mut last_pos = 0;
2157 let mut is_item_attribute = false;
2158 for (line_pos, (line, highlight_parts)) in lines.by_ref().zip(highlights).enumerate() {
2159 last_pos = line_pos;
2160 debug!(%line_pos, %line, ?highlight_parts);
2161
2162 // Remember lines that are not highlighted to hide them if needed
2163 if highlight_parts.is_empty() {
2164 unhighlighted_lines.push((line_pos, line));
2165 continue;
2166 }
2167 if highlight_parts.len() == 1
2168 && line.trim().starts_with("#[")
2169 && line.trim().ends_with(']')
2170 {
2171 is_item_attribute = true;
2172 }
2173
2174 match unhighlighted_lines.len() {
2175 0 => (),
2176 // Since we show first line, "..." line and last line,
2177 // There is no reason to hide if there are 3 or less lines
2178 // (because then we just replace a line with ... which is
2179 // not helpful)
2180 n if n <= 3 => unhighlighted_lines.drain(..).for_each(|(p, l)| {
2181 self.draw_code_line(
2182 &mut buffer,
2183 &mut row_num,
2184 &[],
2185 p + line_start,
2186 l,
2187 show_code_change,
2188 max_line_num_len,
2189 &file_lines,
2190 is_multiline,
2191 )
2192 }),
2193 // Print first unhighlighted line, "..." and last unhighlighted line, like so:
2194 //
2195 // LL | this line was highlighted
2196 // LL | this line is just for context
2197 // ...
2198 // LL | this line is just for context
2199 // LL | this line was highlighted
2200 _ => {
2201 let last_line = unhighlighted_lines.pop();
2202 let first_line = unhighlighted_lines.drain(..).next();
2203
2204 if let Some((p, l)) = first_line {
2205 self.draw_code_line(
2206 &mut buffer,
2207 &mut row_num,
2208 &[],
2209 p + line_start,
2210 l,
2211 show_code_change,
2212 max_line_num_len,
2213 &file_lines,
2214 is_multiline,
2215 )
2216 }
2217
2218 let placeholder = self.margin();
2219 let padding = str_width(placeholder);
2220 buffer.puts(
2221 row_num,
2222 max_line_num_len.saturating_sub(padding),
2223 placeholder,
2224 Style::LineNumber,
2225 );
2226 row_num += 1;
2227
2228 if let Some((p, l)) = last_line {
2229 self.draw_code_line(
2230 &mut buffer,
2231 &mut row_num,
2232 &[],
2233 p + line_start,
2234 l,
2235 show_code_change,
2236 max_line_num_len,
2237 &file_lines,
2238 is_multiline,
2239 )
2240 }
2241 }
2242 }
2243
2244 self.draw_code_line(
2245 &mut buffer,
2246 &mut row_num,
2247 &highlight_parts,
2248 line_pos + line_start,
2249 line,
2250 show_code_change,
2251 max_line_num_len,
2252 &file_lines,
2253 is_multiline,
2254 )
2255 }
2256 if let DisplaySuggestion::Add = show_code_change
2257 && is_item_attribute
2258 {
2259 // The suggestion adds an entire line of code, ending on a newline, so we'll also
2260 // print the *following* line, to provide context of what we're advising people to
2261 // do. Otherwise you would only see contextless code that can be confused for
2262 // already existing code, despite the colors and UI elements.
2263 // We special case `#[derive(_)]\n` and other attribute suggestions, because those
2264 // are the ones where context is most useful.
2265 let file_lines = sm
2266 .span_to_lines(parts[0].span.shrink_to_hi())
2267 .expect("span_to_lines failed when emitting suggestion");
2268 let line_num = sm.lookup_char_pos(parts[0].span.lo()).line;
2269 if let Some(line) = file_lines.file.get_line(line_num - 1) {
2270 let line = normalize_whitespace(&line);
2271 self.draw_code_line(
2272 &mut buffer,
2273 &mut row_num,
2274 &[],
2275 line_num + last_pos + 1,
2276 &line,
2277 DisplaySuggestion::None,
2278 max_line_num_len,
2279 &file_lines,
2280 is_multiline,
2281 )
2282 }
2283 }
2284
2285 // This offset and the ones below need to be signed to account for replacement code
2286 // that is shorter than the original code.
2287 let mut offsets: Vec<(usize, isize)> = Vec::new();
2288 // Only show an underline in the suggestions if the suggestion is not the
2289 // entirety of the code being shown and the displayed code is not multiline.
2290 if let DisplaySuggestion::Diff | DisplaySuggestion::Underline | DisplaySuggestion::Add =
2291 show_code_change
2292 {
2293 for part in parts {
2294 let snippet = if let Ok(snippet) = sm.span_to_snippet(part.span) {
2295 snippet
2296 } else {
2297 String::new()
2298 };
2299 let span_start_pos = sm.lookup_char_pos(part.span.lo()).col_display;
2300 let span_end_pos = sm.lookup_char_pos(part.span.hi()).col_display;
2301
2302 // If this addition is _only_ whitespace, then don't trim it,
2303 // or else we're just not rendering anything.
2304 let is_whitespace_addition = part.snippet.trim().is_empty();
2305
2306 // Do not underline the leading...
2307 let start = if is_whitespace_addition {
2308 0
2309 } else {
2310 part.snippet.len().saturating_sub(part.snippet.trim_start().len())
2311 };
2312 // ...or trailing spaces. Account for substitutions containing unicode
2313 // characters.
2314 let sub_len: usize = str_width(if is_whitespace_addition {
2315 &part.snippet
2316 } else {
2317 part.snippet.trim()
2318 });
2319
2320 let offset: isize = offsets
2321 .iter()
2322 .filter_map(
2323 |(start, v)| if span_start_pos < *start { None } else { Some(v) },
2324 )
2325 .sum();
2326 let underline_start = (span_start_pos + start) as isize + offset;
2327 let underline_end = (span_start_pos + start + sub_len) as isize + offset;
2328 assert!(underline_start >= 0 && underline_end >= 0);
2329 let padding: usize = max_line_num_len + 3;
2330 for p in underline_start..underline_end {
2331 if let DisplaySuggestion::Underline = show_code_change
2332 && is_different(sm, &part.snippet, part.span)
2333 {
2334 // If this is a replacement, underline with `~`, if this is an addition
2335 // underline with `+`.
2336 buffer.putc(
2337 row_num,
2338 (padding as isize + p) as usize,
2339 if part.is_addition(sm) { '+' } else { self.diff() },
2340 Style::Addition,
2341 );
2342 }
2343 }
2344 if let DisplaySuggestion::Diff = show_code_change {
2345 // Colorize removal with red in diff format.
2346
2347 // Below, there's some tricky buffer indexing going on. `row_num` at this
2348 // point corresponds to:
2349 //
2350 // |
2351 // LL | CODE
2352 // | ++++ <- `row_num`
2353 //
2354 // in the buffer. When we have a diff format output, we end up with
2355 //
2356 // |
2357 // LL - OLDER <- row_num - 2
2358 // LL + NEWER
2359 // | <- row_num
2360 //
2361 // The `row_num - 2` is to select the buffer line that has the "old version
2362 // of the diff" at that point. When the removal is a single line, `i` is
2363 // `0`, `newlines` is `1` so `(newlines - i - 1)` ends up being `0`, so row
2364 // points at `LL - OLDER`. When the removal corresponds to multiple lines,
2365 // we end up with `newlines > 1` and `i` being `0..newlines - 1`.
2366 //
2367 // |
2368 // LL - OLDER <- row_num - 2 - (newlines - last_i - 1)
2369 // LL - CODE
2370 // LL - BEING
2371 // LL - REMOVED <- row_num - 2 - (newlines - first_i - 1)
2372 // LL + NEWER
2373 // | <- row_num
2374
2375 let newlines = snippet.lines().count();
2376 if newlines > 0 && row_num > newlines {
2377 // Account for removals where the part being removed spans multiple
2378 // lines.
2379 // FIXME: We check the number of rows because in some cases, like in
2380 // `tests/ui/lint/invalid-nan-comparison-suggestion.rs`, the rendered
2381 // suggestion will only show the first line of code being replaced. The
2382 // proper way of doing this would be to change the suggestion rendering
2383 // logic to show the whole prior snippet, but the current output is not
2384 // too bad to begin with, so we side-step that issue here.
2385 for (i, line) in snippet.lines().enumerate() {
2386 let line = normalize_whitespace(line);
2387 let row = row_num - 2 - (newlines - i - 1);
2388 // On the first line, we highlight between the start of the part
2389 // span, and the end of that line.
2390 // On the last line, we highlight between the start of the line, and
2391 // the column of the part span end.
2392 // On all others, we highlight the whole line.
2393 let start = if i == 0 {
2394 (padding as isize + span_start_pos as isize) as usize
2395 } else {
2396 padding
2397 };
2398 let end = if i == 0 {
2399 (padding as isize
2400 + span_start_pos as isize
2401 + line.len() as isize)
2402 as usize
2403 } else if i == newlines - 1 {
2404 (padding as isize + span_end_pos as isize) as usize
2405 } else {
2406 (padding as isize + line.len() as isize) as usize
2407 };
2408 buffer.set_style_range(row, start, end, Style::Removal, true);
2409 }
2410 } else {
2411 // The removed code fits all in one line.
2412 buffer.set_style_range(
2413 row_num - 2,
2414 (padding as isize + span_start_pos as isize) as usize,
2415 (padding as isize + span_end_pos as isize) as usize,
2416 Style::Removal,
2417 true,
2418 );
2419 }
2420 }
2421
2422 // length of the code after substitution
2423 let full_sub_len = str_width(&part.snippet) as isize;
2424
2425 // length of the code to be substituted
2426 let snippet_len = span_end_pos as isize - span_start_pos as isize;
2427 // For multiple substitutions, use the position *after* the previous
2428 // substitutions have happened, only when further substitutions are
2429 // located strictly after.
2430 offsets.push((span_end_pos, full_sub_len - snippet_len));
2431 }
2432 row_num += 1;
2433 }
2434
2435 // if we elided some lines, add an ellipsis
2436 if lines.next().is_some() {
2437 let placeholder = self.margin();
2438 let padding = str_width(placeholder);
2439 buffer.puts(
2440 row_num,
2441 max_line_num_len.saturating_sub(padding),
2442 placeholder,
2443 Style::LineNumber,
2444 );
2445 } else {
2446 let row = match show_code_change {
2447 DisplaySuggestion::Diff
2448 | DisplaySuggestion::Add
2449 | DisplaySuggestion::Underline => row_num - 1,
2450 DisplaySuggestion::None => row_num,
2451 };
2452 self.draw_col_separator_end(&mut buffer, row, max_line_num_len + 1);
2453 row_num = row + 1;
2454 }
2455 }
2456 if other_suggestions > 0 {
2457 let msg = format!(
2458 "and {} other candidate{}",
2459 other_suggestions,
2460 pluralize!(other_suggestions)
2461 );
2462 buffer.puts(row_num, max_line_num_len + 3, &msg, Style::NoStyle);
2463 }
2464
2465 emit_to_destination(&buffer.render(), level, &mut self.dst, self.short_message)?;
2466 Ok(())
2467 }
2468
2469 #[instrument(level = "trace", skip(self, args, code, children, suggestions))]
2470 fn emit_messages_default(
2471 &mut self,
2472 level: &Level,
2473 messages: &[(DiagMessage, Style)],
2474 args: &FluentArgs<'_>,
2475 code: &Option<ErrCode>,
2476 span: &MultiSpan,
2477 children: &[Subdiag],
2478 suggestions: &[CodeSuggestion],
2479 emitted_at: Option<&DiagLocation>,
2480 ) {
2481 let max_line_num_len = if self.ui_testing {
2482 ANONYMIZED_LINE_NUM.len()
2483 } else {
2484 let n = self.get_max_line_num(span, children);
2485 num_decimal_digits(n)
2486 };
2487
2488 match self.emit_messages_default_inner(
2489 span,
2490 messages,
2491 args,
2492 code,
2493 level,
2494 max_line_num_len,
2495 false,
2496 emitted_at,
2497 !children.is_empty()
2498 || suggestions.iter().any(|s| s.style != SuggestionStyle::CompletelyHidden),
2499 ) {
2500 Ok(()) => {
2501 if !children.is_empty()
2502 || suggestions.iter().any(|s| s.style != SuggestionStyle::CompletelyHidden)
2503 {
2504 let mut buffer = StyledBuffer::new();
2505 if !self.short_message {
2506 if let Some(child) = children.iter().next()
2507 && child.span.primary_spans().is_empty()
2508 {
2509 // We'll continue the vertical bar to point into the next note.
2510 self.draw_col_separator_no_space(&mut buffer, 0, max_line_num_len + 1);
2511 } else {
2512 // We'll close the vertical bar to visually end the code window.
2513 self.draw_col_separator_end(&mut buffer, 0, max_line_num_len + 1);
2514 }
2515 }
2516 if let Err(e) = emit_to_destination(
2517 &buffer.render(),
2518 level,
2519 &mut self.dst,
2520 self.short_message,
2521 ) {
2522 panic!("failed to emit error: {e}")
2523 }
2524 }
2525 if !self.short_message {
2526 for (i, child) in children.iter().enumerate() {
2527 assert!(child.level.can_be_subdiag());
2528 let span = &child.span;
2529 // FIXME: audit that this behaves correctly with suggestions.
2530 let should_close = match children.get(i + 1) {
2531 Some(c) => !c.span.primary_spans().is_empty(),
2532 None => i + 1 == children.len(),
2533 };
2534 if let Err(err) = self.emit_messages_default_inner(
2535 span,
2536 &child.messages,
2537 args,
2538 &None,
2539 &child.level,
2540 max_line_num_len,
2541 true,
2542 None,
2543 !should_close,
2544 ) {
2545 panic!("failed to emit error: {err}");
2546 }
2547 }
2548 for (i, sugg) in suggestions.iter().enumerate() {
2549 match sugg.style {
2550 SuggestionStyle::CompletelyHidden => {
2551 // do not display this suggestion, it is meant only for tools
2552 }
2553 SuggestionStyle::HideCodeAlways => {
2554 if let Err(e) = self.emit_messages_default_inner(
2555 &MultiSpan::new(),
2556 &[(sugg.msg.to_owned(), Style::HeaderMsg)],
2557 args,
2558 &None,
2559 &Level::Help,
2560 max_line_num_len,
2561 true,
2562 None,
2563 // FIXME: this needs to account for the suggestion type,
2564 // some don't take any space.
2565 i + 1 != suggestions.len(),
2566 ) {
2567 panic!("failed to emit error: {e}");
2568 }
2569 }
2570 SuggestionStyle::HideCodeInline
2571 | SuggestionStyle::ShowCode
2572 | SuggestionStyle::ShowAlways => {
2573 if let Err(e) = self.emit_suggestion_default(
2574 span,
2575 sugg,
2576 args,
2577 &Level::Help,
2578 max_line_num_len,
2579 ) {
2580 panic!("failed to emit error: {e}");
2581 }
2582 }
2583 }
2584 }
2585 }
2586 }
2587 Err(e) => panic!("failed to emit error: {e}"),
2588 }
2589
2590 match writeln!(self.dst) {
2591 Err(e) => panic!("failed to emit error: {e}"),
2592 _ => {
2593 if let Err(e) = self.dst.flush() {
2594 panic!("failed to emit error: {e}")
2595 }
2596 }
2597 }
2598 }
2599
2600 fn draw_code_line(
2601 &self,
2602 buffer: &mut StyledBuffer,
2603 row_num: &mut usize,
2604 highlight_parts: &[SubstitutionHighlight],
2605 line_num: usize,
2606 line_to_add: &str,
2607 show_code_change: DisplaySuggestion,
2608 max_line_num_len: usize,
2609 file_lines: &FileLines,
2610 is_multiline: bool,
2611 ) {
2612 if let DisplaySuggestion::Diff = show_code_change {
2613 // We need to print more than one line if the span we need to remove is multiline.
2614 // For more info: https://github.com/rust-lang/rust/issues/92741
2615 let lines_to_remove = file_lines.lines.iter().take(file_lines.lines.len() - 1);
2616 for (index, line_to_remove) in lines_to_remove.enumerate() {
2617 buffer.puts(
2618 *row_num - 1,
2619 0,
2620 &self.maybe_anonymized(line_num + index),
2621 Style::LineNumber,
2622 );
2623 buffer.puts(*row_num - 1, max_line_num_len + 1, "- ", Style::Removal);
2624 let line = normalize_whitespace(
2625 &file_lines.file.get_line(line_to_remove.line_index).unwrap(),
2626 );
2627 buffer.puts(*row_num - 1, max_line_num_len + 3, &line, Style::NoStyle);
2628 *row_num += 1;
2629 }
2630 // If the last line is exactly equal to the line we need to add, we can skip both of
2631 // them. This allows us to avoid output like the following:
2632 // 2 - &
2633 // 2 + if true { true } else { false }
2634 // 3 - if true { true } else { false }
2635 // If those lines aren't equal, we print their diff
2636 let last_line_index = file_lines.lines[file_lines.lines.len() - 1].line_index;
2637 let last_line = &file_lines.file.get_line(last_line_index).unwrap();
2638 if last_line != line_to_add {
2639 buffer.puts(
2640 *row_num - 1,
2641 0,
2642 &self.maybe_anonymized(line_num + file_lines.lines.len() - 1),
2643 Style::LineNumber,
2644 );
2645 buffer.puts(*row_num - 1, max_line_num_len + 1, "- ", Style::Removal);
2646 buffer.puts(
2647 *row_num - 1,
2648 max_line_num_len + 3,
2649 &normalize_whitespace(last_line),
2650 Style::NoStyle,
2651 );
2652 if !line_to_add.trim().is_empty() {
2653 // Check if after the removal, the line is left with only whitespace. If so, we
2654 // will not show an "addition" line, as removing the whole line is what the user
2655 // would really want.
2656 // For example, for the following:
2657 // |
2658 // 2 - .await
2659 // 2 + (note the left over whitespace)
2660 // |
2661 // We really want
2662 // |
2663 // 2 - .await
2664 // |
2665 // *row_num -= 1;
2666 buffer.puts(*row_num, 0, &self.maybe_anonymized(line_num), Style::LineNumber);
2667 buffer.puts(*row_num, max_line_num_len + 1, "+ ", Style::Addition);
2668 buffer.append(*row_num, &normalize_whitespace(line_to_add), Style::NoStyle);
2669 } else {
2670 *row_num -= 1;
2671 }
2672 } else {
2673 *row_num -= 2;
2674 }
2675 } else if is_multiline {
2676 buffer.puts(*row_num, 0, &self.maybe_anonymized(line_num), Style::LineNumber);
2677 match &highlight_parts {
2678 [SubstitutionHighlight { start: 0, end }] if *end == line_to_add.len() => {
2679 buffer.puts(*row_num, max_line_num_len + 1, "+ ", Style::Addition);
2680 }
2681 [] => {
2682 // FIXME: needed? Doesn't get exercised in any test.
2683 self.draw_col_separator_no_space(buffer, *row_num, max_line_num_len + 1);
2684 }
2685 _ => {
2686 let diff = self.diff();
2687 buffer.puts(
2688 *row_num,
2689 max_line_num_len + 1,
2690 &format!("{diff} "),
2691 Style::Addition,
2692 );
2693 }
2694 }
2695 // LL | line_to_add
2696 // ++^^^
2697 // | |
2698 // | magic `3`
2699 // `max_line_num_len`
2700 buffer.puts(
2701 *row_num,
2702 max_line_num_len + 3,
2703 &normalize_whitespace(line_to_add),
2704 Style::NoStyle,
2705 );
2706 } else if let DisplaySuggestion::Add = show_code_change {
2707 buffer.puts(*row_num, 0, &self.maybe_anonymized(line_num), Style::LineNumber);
2708 buffer.puts(*row_num, max_line_num_len + 1, "+ ", Style::Addition);
2709 buffer.append(*row_num, &normalize_whitespace(line_to_add), Style::NoStyle);
2710 } else {
2711 buffer.puts(*row_num, 0, &self.maybe_anonymized(line_num), Style::LineNumber);
2712 self.draw_col_separator(buffer, *row_num, max_line_num_len + 1);
2713 buffer.append(*row_num, &normalize_whitespace(line_to_add), Style::NoStyle);
2714 }
2715
2716 // Colorize addition/replacements with green.
2717 for &SubstitutionHighlight { start, end } in highlight_parts {
2718 // This is a no-op for empty ranges
2719 if start != end {
2720 // Account for tabs when highlighting (#87972).
2721 let tabs: usize = line_to_add
2722 .chars()
2723 .take(start)
2724 .map(|ch| match ch {
2725 '\t' => 3,
2726 _ => 0,
2727 })
2728 .sum();
2729 buffer.set_style_range(
2730 *row_num,
2731 max_line_num_len + 3 + start + tabs,
2732 max_line_num_len + 3 + end + tabs,
2733 Style::Addition,
2734 true,
2735 );
2736 }
2737 }
2738 *row_num += 1;
2739 }
2740
2741 fn underline(&self, is_primary: bool) -> UnderlineParts {
2742 // X0 Y0
2743 // label_start > ┯━━━━ < underline
2744 // │ < vertical_text_line
2745 // text
2746
2747 // multiline_start_down ⤷ X0 Y0
2748 // top_left > ┌───╿──┘ < top_right_flat
2749 // top_left > ┏│━━━┙ < top_right
2750 // multiline_vertical > ┃│
2751 // ┃│ X1 Y1
2752 // ┃│ X2 Y2
2753 // ┃└────╿──┘ < multiline_end_same_line
2754 // bottom_left > ┗━━━━━┥ < bottom_right_with_text
2755 // multiline_horizontal ^ `X` is a good letter
2756
2757 // multiline_whole_line > ┏ X0 Y0
2758 // ┃ X1 Y1
2759 // ┗━━━━┛ < multiline_end_same_line
2760
2761 // multiline_whole_line > ┏ X0 Y0
2762 // ┃ X1 Y1
2763 // ┃ ╿ < multiline_end_up
2764 // ┗━━┛ < bottom_right
2765
2766 match (self.theme, is_primary) {
2767 (OutputTheme::Ascii, true) => UnderlineParts {
2768 style: Style::UnderlinePrimary,
2769 underline: '^',
2770 label_start: '^',
2771 vertical_text_line: '|',
2772 multiline_vertical: '|',
2773 multiline_horizontal: '_',
2774 multiline_whole_line: '/',
2775 multiline_start_down: '^',
2776 bottom_right: '|',
2777 top_left: ' ',
2778 top_right_flat: '^',
2779 bottom_left: '|',
2780 multiline_end_up: '^',
2781 multiline_end_same_line: '^',
2782 multiline_bottom_right_with_text: '|',
2783 },
2784 (OutputTheme::Ascii, false) => UnderlineParts {
2785 style: Style::UnderlineSecondary,
2786 underline: '-',
2787 label_start: '-',
2788 vertical_text_line: '|',
2789 multiline_vertical: '|',
2790 multiline_horizontal: '_',
2791 multiline_whole_line: '/',
2792 multiline_start_down: '-',
2793 bottom_right: '|',
2794 top_left: ' ',
2795 top_right_flat: '-',
2796 bottom_left: '|',
2797 multiline_end_up: '-',
2798 multiline_end_same_line: '-',
2799 multiline_bottom_right_with_text: '|',
2800 },
2801 (OutputTheme::Unicode, true) => UnderlineParts {
2802 style: Style::UnderlinePrimary,
2803 underline: '━',
2804 label_start: '┯',
2805 vertical_text_line: '│',
2806 multiline_vertical: '┃',
2807 multiline_horizontal: '━',
2808 multiline_whole_line: '┏',
2809 multiline_start_down: '╿',
2810 bottom_right: '┙',
2811 top_left: '┏',
2812 top_right_flat: '┛',
2813 bottom_left: '┗',
2814 multiline_end_up: '╿',
2815 multiline_end_same_line: '┛',
2816 multiline_bottom_right_with_text: '┥',
2817 },
2818 (OutputTheme::Unicode, false) => UnderlineParts {
2819 style: Style::UnderlineSecondary,
2820 underline: '─',
2821 label_start: '┬',
2822 vertical_text_line: '│',
2823 multiline_vertical: '│',
2824 multiline_horizontal: '─',
2825 multiline_whole_line: '┌',
2826 multiline_start_down: '│',
2827 bottom_right: '┘',
2828 top_left: '┌',
2829 top_right_flat: '┘',
2830 bottom_left: '└',
2831 multiline_end_up: '│',
2832 multiline_end_same_line: '┘',
2833 multiline_bottom_right_with_text: '┤',
2834 },
2835 }
2836 }
2837
2838 fn col_separator(&self) -> char {
2839 match self.theme {
2840 OutputTheme::Ascii => '|',
2841 OutputTheme::Unicode => '│',
2842 }
2843 }
2844
2845 fn note_separator(&self) -> char {
2846 match self.theme {
2847 OutputTheme::Ascii => '=',
2848 OutputTheme::Unicode => '╰',
2849 }
2850 }
2851
2852 fn multi_suggestion_separator(&self) -> &'static str {
2853 match self.theme {
2854 OutputTheme::Ascii => "|",
2855 OutputTheme::Unicode => "├╴",
2856 }
2857 }
2858
2859 fn draw_col_separator(&self, buffer: &mut StyledBuffer, line: usize, col: usize) {
2860 let chr = self.col_separator();
2861 buffer.puts(line, col, &format!("{chr} "), Style::LineNumber);
2862 }
2863
2864 fn draw_col_separator_no_space(&self, buffer: &mut StyledBuffer, line: usize, col: usize) {
2865 let chr = self.col_separator();
2866 self.draw_col_separator_no_space_with_style(buffer, chr, line, col, Style::LineNumber);
2867 }
2868
2869 fn draw_col_separator_start(&self, buffer: &mut StyledBuffer, line: usize, col: usize) {
2870 match self.theme {
2871 OutputTheme::Ascii => {
2872 self.draw_col_separator_no_space_with_style(
2873 buffer,
2874 '|',
2875 line,
2876 col,
2877 Style::LineNumber,
2878 );
2879 }
2880 OutputTheme::Unicode => {
2881 self.draw_col_separator_no_space_with_style(
2882 buffer,
2883 '╭',
2884 line,
2885 col,
2886 Style::LineNumber,
2887 );
2888 self.draw_col_separator_no_space_with_style(
2889 buffer,
2890 '╴',
2891 line,
2892 col + 1,
2893 Style::LineNumber,
2894 );
2895 }
2896 }
2897 }
2898
2899 fn draw_col_separator_end(&self, buffer: &mut StyledBuffer, line: usize, col: usize) {
2900 match self.theme {
2901 OutputTheme::Ascii => {
2902 self.draw_col_separator_no_space_with_style(
2903 buffer,
2904 '|',
2905 line,
2906 col,
2907 Style::LineNumber,
2908 );
2909 }
2910 OutputTheme::Unicode => {
2911 self.draw_col_separator_no_space_with_style(
2912 buffer,
2913 '╰',
2914 line,
2915 col,
2916 Style::LineNumber,
2917 );
2918 self.draw_col_separator_no_space_with_style(
2919 buffer,
2920 '╴',
2921 line,
2922 col + 1,
2923 Style::LineNumber,
2924 );
2925 }
2926 }
2927 }
2928
2929 fn draw_col_separator_no_space_with_style(
2930 &self,
2931 buffer: &mut StyledBuffer,
2932 chr: char,
2933 line: usize,
2934 col: usize,
2935 style: Style,
2936 ) {
2937 buffer.putc(line, col, chr, style);
2938 }
2939
2940 fn draw_range(
2941 &self,
2942 buffer: &mut StyledBuffer,
2943 symbol: char,
2944 line: usize,
2945 col_from: usize,
2946 col_to: usize,
2947 style: Style,
2948 ) {
2949 for col in col_from..col_to {
2950 buffer.putc(line, col, symbol, style);
2951 }
2952 }
2953
2954 fn draw_note_separator(
2955 &self,
2956 buffer: &mut StyledBuffer,
2957 line: usize,
2958 col: usize,
2959 is_cont: bool,
2960 ) {
2961 let chr = match self.theme {
2962 OutputTheme::Ascii => "= ",
2963 OutputTheme::Unicode if is_cont => "├ ",
2964 OutputTheme::Unicode => "╰ ",
2965 };
2966 buffer.puts(line, col, chr, Style::LineNumber);
2967 }
2968
2969 fn draw_multiline_line(
2970 &self,
2971 buffer: &mut StyledBuffer,
2972 line: usize,
2973 offset: usize,
2974 depth: usize,
2975 style: Style,
2976 ) {
2977 let chr = match (style, self.theme) {
2978 (Style::UnderlinePrimary | Style::LabelPrimary, OutputTheme::Ascii) => '|',
2979 (_, OutputTheme::Ascii) => '|',
2980 (Style::UnderlinePrimary | Style::LabelPrimary, OutputTheme::Unicode) => '┃',
2981 (_, OutputTheme::Unicode) => '│',
2982 };
2983 buffer.putc(line, offset + depth - 1, chr, style);
2984 }
2985
2986 fn file_start(&self) -> &'static str {
2987 match self.theme {
2988 OutputTheme::Ascii => "--> ",
2989 OutputTheme::Unicode => " ╭▸ ",
2990 }
2991 }
2992
2993 fn secondary_file_start(&self) -> &'static str {
2994 match self.theme {
2995 OutputTheme::Ascii => "::: ",
2996 OutputTheme::Unicode => " ⸬ ",
2997 }
2998 }
2999
3000 fn diff(&self) -> char {
3001 match self.theme {
3002 OutputTheme::Ascii => '~',
3003 OutputTheme::Unicode => '±',
3004 }
3005 }
3006
3007 fn draw_line_separator(&self, buffer: &mut StyledBuffer, line: usize, col: usize) {
3008 let (column, dots) = match self.theme {
3009 OutputTheme::Ascii => (0, "..."),
3010 OutputTheme::Unicode => (col - 2, "‡"),
3011 };
3012 buffer.puts(line, column, dots, Style::LineNumber);
3013 }
3014
3015 fn margin(&self) -> &'static str {
3016 match self.theme {
3017 OutputTheme::Ascii => "...",
3018 OutputTheme::Unicode => "…",
3019 }
3020 }
3021}
3022
3023#[derive(Debug, Clone, Copy)]
3024struct UnderlineParts {
3025 style: Style,
3026 underline: char,
3027 label_start: char,
3028 vertical_text_line: char,
3029 multiline_vertical: char,
3030 multiline_horizontal: char,
3031 multiline_whole_line: char,
3032 multiline_start_down: char,
3033 bottom_right: char,
3034 top_left: char,
3035 top_right_flat: char,
3036 bottom_left: char,
3037 multiline_end_up: char,
3038 multiline_end_same_line: char,
3039 multiline_bottom_right_with_text: char,
3040}
3041
3042#[derive(Clone, Copy, Debug)]
3043enum DisplaySuggestion {
3044 Underline,
3045 Diff,
3046 None,
3047 Add,
3048}
3049
3050impl FileWithAnnotatedLines {
3051 /// Preprocess all the annotations so that they are grouped by file and by line number
3052 /// This helps us quickly iterate over the whole message (including secondary file spans)
3053 pub(crate) fn collect_annotations(
3054 emitter: &dyn Emitter,
3055 args: &FluentArgs<'_>,
3056 msp: &MultiSpan,
3057 ) -> Vec<FileWithAnnotatedLines> {
3058 fn add_annotation_to_file(
3059 file_vec: &mut Vec<FileWithAnnotatedLines>,
3060 file: Arc<SourceFile>,
3061 line_index: usize,
3062 ann: Annotation,
3063 ) {
3064 for slot in file_vec.iter_mut() {
3065 // Look through each of our files for the one we're adding to
3066 if slot.file.name == file.name {
3067 // See if we already have a line for it
3068 for line_slot in &mut slot.lines {
3069 if line_slot.line_index == line_index {
3070 line_slot.annotations.push(ann);
3071 return;
3072 }
3073 }
3074 // We don't have a line yet, create one
3075 slot.lines.push(Line { line_index, annotations: vec![ann] });
3076 slot.lines.sort();
3077 return;
3078 }
3079 }
3080 // This is the first time we're seeing the file
3081 file_vec.push(FileWithAnnotatedLines {
3082 file,
3083 lines: vec![Line { line_index, annotations: vec![ann] }],
3084 multiline_depth: 0,
3085 });
3086 }
3087
3088 let mut output = vec![];
3089 let mut multiline_annotations = vec![];
3090
3091 if let Some(sm) = emitter.source_map() {
3092 for SpanLabel { span, is_primary, label } in msp.span_labels() {
3093 // If we don't have a useful span, pick the primary span if that exists.
3094 // Worst case we'll just print an error at the top of the main file.
3095 let span = match (span.is_dummy(), msp.primary_span()) {
3096 (_, None) | (false, _) => span,
3097 (true, Some(span)) => span,
3098 };
3099
3100 let lo = sm.lookup_char_pos(span.lo());
3101 let mut hi = sm.lookup_char_pos(span.hi());
3102
3103 // Watch out for "empty spans". If we get a span like 6..6, we
3104 // want to just display a `^` at 6, so convert that to
3105 // 6..7. This is degenerate input, but it's best to degrade
3106 // gracefully -- and the parser likes to supply a span like
3107 // that for EOF, in particular.
3108
3109 if lo.col_display == hi.col_display && lo.line == hi.line {
3110 hi.col_display += 1;
3111 }
3112
3113 let label = label.as_ref().map(|m| {
3114 normalize_whitespace(
3115 &emitter
3116 .translator()
3117 .translate_message(m, args)
3118 .map_err(Report::new)
3119 .unwrap(),
3120 )
3121 });
3122
3123 if lo.line != hi.line {
3124 let ml = MultilineAnnotation {
3125 depth: 1,
3126 line_start: lo.line,
3127 line_end: hi.line,
3128 start_col: AnnotationColumn::from_loc(&lo),
3129 end_col: AnnotationColumn::from_loc(&hi),
3130 is_primary,
3131 label,
3132 overlaps_exactly: false,
3133 };
3134 multiline_annotations.push((lo.file, ml));
3135 } else {
3136 let ann = Annotation {
3137 start_col: AnnotationColumn::from_loc(&lo),
3138 end_col: AnnotationColumn::from_loc(&hi),
3139 is_primary,
3140 label,
3141 annotation_type: AnnotationType::Singleline,
3142 };
3143 add_annotation_to_file(&mut output, lo.file, lo.line, ann);
3144 };
3145 }
3146 }
3147
3148 // Find overlapping multiline annotations, put them at different depths
3149 multiline_annotations.sort_by_key(|(_, ml)| (ml.line_start, usize::MAX - ml.line_end));
3150 for (_, ann) in multiline_annotations.clone() {
3151 for (_, a) in multiline_annotations.iter_mut() {
3152 // Move all other multiline annotations overlapping with this one
3153 // one level to the right.
3154 if !(ann.same_span(a))
3155 && num_overlap(ann.line_start, ann.line_end, a.line_start, a.line_end, true)
3156 {
3157 a.increase_depth();
3158 } else if ann.same_span(a) && &ann != a {
3159 a.overlaps_exactly = true;
3160 } else {
3161 break;
3162 }
3163 }
3164 }
3165
3166 let mut max_depth = 0; // max overlapping multiline spans
3167 for (_, ann) in &multiline_annotations {
3168 max_depth = max(max_depth, ann.depth);
3169 }
3170 // Change order of multispan depth to minimize the number of overlaps in the ASCII art.
3171 for (_, a) in multiline_annotations.iter_mut() {
3172 a.depth = max_depth - a.depth + 1;
3173 }
3174 for (file, ann) in multiline_annotations {
3175 let mut end_ann = ann.as_end();
3176 if !ann.overlaps_exactly {
3177 // avoid output like
3178 //
3179 // | foo(
3180 // | _____^
3181 // | |_____|
3182 // | || bar,
3183 // | || );
3184 // | || ^
3185 // | ||______|
3186 // | |______foo
3187 // | baz
3188 //
3189 // and instead get
3190 //
3191 // | foo(
3192 // | _____^
3193 // | | bar,
3194 // | | );
3195 // | | ^
3196 // | | |
3197 // | |______foo
3198 // | baz
3199 add_annotation_to_file(
3200 &mut output,
3201 Arc::clone(&file),
3202 ann.line_start,
3203 ann.as_start(),
3204 );
3205 // 4 is the minimum vertical length of a multiline span when presented: two lines
3206 // of code and two lines of underline. This is not true for the special case where
3207 // the beginning doesn't have an underline, but the current logic seems to be
3208 // working correctly.
3209 let middle = min(ann.line_start + 4, ann.line_end);
3210 // We'll show up to 4 lines past the beginning of the multispan start.
3211 // We will *not* include the tail of lines that are only whitespace, a comment or
3212 // a bare delimiter.
3213 let filter = |s: &str| {
3214 let s = s.trim();
3215 // Consider comments as empty, but don't consider docstrings to be empty.
3216 !(s.starts_with("//") && !(s.starts_with("///") || s.starts_with("//!")))
3217 // Consider lines with nothing but whitespace, a single delimiter as empty.
3218 && !["", "{", "}", "(", ")", "[", "]"].contains(&s)
3219 };
3220 let until = (ann.line_start..middle)
3221 .rev()
3222 .filter_map(|line| file.get_line(line - 1).map(|s| (line + 1, s)))
3223 .find(|(_, s)| filter(s))
3224 .map(|(line, _)| line)
3225 .unwrap_or(ann.line_start);
3226 for line in ann.line_start + 1..until {
3227 // Every `|` that joins the beginning of the span (`___^`) to the end (`|__^`).
3228 add_annotation_to_file(&mut output, Arc::clone(&file), line, ann.as_line());
3229 }
3230 let line_end = ann.line_end - 1;
3231 let end_is_empty = file.get_line(line_end - 1).is_some_and(|s| !filter(&s));
3232 if middle < line_end && !end_is_empty {
3233 add_annotation_to_file(&mut output, Arc::clone(&file), line_end, ann.as_line());
3234 }
3235 } else {
3236 end_ann.annotation_type = AnnotationType::Singleline;
3237 }
3238 add_annotation_to_file(&mut output, file, ann.line_end, end_ann);
3239 }
3240 for file_vec in output.iter_mut() {
3241 file_vec.multiline_depth = max_depth;
3242 }
3243 output
3244 }
3245}
3246
3247// instead of taking the String length or dividing by 10 while > 0, we multiply a limit by 10 until
3248// we're higher. If the loop isn't exited by the `return`, the last multiplication will wrap, which
3249// is OK, because while we cannot fit a higher power of 10 in a usize, the loop will end anyway.
3250// This is also why we need the max number of decimal digits within a `usize`.
3251fn num_decimal_digits(num: usize) -> usize {
3252 #[cfg(target_pointer_width = "64")]
3253 const MAX_DIGITS: usize = 20;
3254
3255 #[cfg(target_pointer_width = "32")]
3256 const MAX_DIGITS: usize = 10;
3257
3258 #[cfg(target_pointer_width = "16")]
3259 const MAX_DIGITS: usize = 5;
3260
3261 let mut lim = 10;
3262 for num_digits in 1..MAX_DIGITS {
3263 if num < lim {
3264 return num_digits;
3265 }
3266 lim = lim.wrapping_mul(10);
3267 }
3268 MAX_DIGITS
3269}
3270
3271// We replace some characters so the CLI output is always consistent and underlines aligned.
3272// Keep the following list in sync with `rustc_span::char_width`.
3273const OUTPUT_REPLACEMENTS: &[(char, &str)] = &[
3274 // In terminals without Unicode support the following will be garbled, but in *all* terminals
3275 // the underlying codepoint will be as well. We could gate this replacement behind a "unicode
3276 // support" gate.
3277 ('\0', "␀"),
3278 ('\u{0001}', "␁"),
3279 ('\u{0002}', "␂"),
3280 ('\u{0003}', "␃"),
3281 ('\u{0004}', "␄"),
3282 ('\u{0005}', "␅"),
3283 ('\u{0006}', "␆"),
3284 ('\u{0007}', "␇"),
3285 ('\u{0008}', "␈"),
3286 ('\t', " "), // We do our own tab replacement
3287 ('\u{000b}', "␋"),
3288 ('\u{000c}', "␌"),
3289 ('\u{000d}', "␍"),
3290 ('\u{000e}', "␎"),
3291 ('\u{000f}', "␏"),
3292 ('\u{0010}', "␐"),
3293 ('\u{0011}', "␑"),
3294 ('\u{0012}', "␒"),
3295 ('\u{0013}', "␓"),
3296 ('\u{0014}', "␔"),
3297 ('\u{0015}', "␕"),
3298 ('\u{0016}', "␖"),
3299 ('\u{0017}', "␗"),
3300 ('\u{0018}', "␘"),
3301 ('\u{0019}', "␙"),
3302 ('\u{001a}', "␚"),
3303 ('\u{001b}', "␛"),
3304 ('\u{001c}', "␜"),
3305 ('\u{001d}', "␝"),
3306 ('\u{001e}', "␞"),
3307 ('\u{001f}', "␟"),
3308 ('\u{007f}', "␡"),
3309 ('\u{200d}', ""), // Replace ZWJ for consistent terminal output of grapheme clusters.
3310 ('\u{202a}', "�"), // The following unicode text flow control characters are inconsistently
3311 ('\u{202b}', "�"), // supported across CLIs and can cause confusion due to the bytes on disk
3312 ('\u{202c}', "�"), // not corresponding to the visible source code, so we replace them always.
3313 ('\u{202d}', "�"),
3314 ('\u{202e}', "�"),
3315 ('\u{2066}', "�"),
3316 ('\u{2067}', "�"),
3317 ('\u{2068}', "�"),
3318 ('\u{2069}', "�"),
3319];
3320
3321fn normalize_whitespace(s: &str) -> String {
3322 const {
3323 let mut i = 1;
3324 while i < OUTPUT_REPLACEMENTS.len() {
3325 assert!(
3326 OUTPUT_REPLACEMENTS[i - 1].0 < OUTPUT_REPLACEMENTS[i].0,
3327 "The OUTPUT_REPLACEMENTS array must be sorted (for binary search to work) \
3328 and must contain no duplicate entries"
3329 );
3330 i += 1;
3331 }
3332 }
3333 // Scan the input string for a character in the ordered table above.
3334 // If it's present, replace it with its alternative string (it can be more than 1 char!).
3335 // Otherwise, retain the input char.
3336 s.chars().fold(String::with_capacity(s.len()), |mut s, c| {
3337 match OUTPUT_REPLACEMENTS.binary_search_by_key(&c, |(k, _)| *k) {
3338 Ok(i) => s.push_str(OUTPUT_REPLACEMENTS[i].1),
3339 _ => s.push(c),
3340 }
3341 s
3342 })
3343}
3344
3345fn num_overlap(
3346 a_start: usize,
3347 a_end: usize,
3348 b_start: usize,
3349 b_end: usize,
3350 inclusive: bool,
3351) -> bool {
3352 let extra = if inclusive { 1 } else { 0 };
3353 (b_start..b_end + extra).contains(&a_start) || (a_start..a_end + extra).contains(&b_start)
3354}
3355
3356fn overlaps(a1: &Annotation, a2: &Annotation, padding: usize) -> bool {
3357 num_overlap(
3358 a1.start_col.display,
3359 a1.end_col.display + padding,
3360 a2.start_col.display,
3361 a2.end_col.display,
3362 false,
3363 )
3364}
3365
3366fn emit_to_destination(
3367 rendered_buffer: &[Vec<StyledString>],
3368 lvl: &Level,
3369 dst: &mut Destination,
3370 short_message: bool,
3371) -> io::Result<()> {
3372 use crate::lock;
3373
3374 // In order to prevent error message interleaving, where multiple error lines get intermixed
3375 // when multiple compiler processes error simultaneously, we emit errors with additional
3376 // steps.
3377 //
3378 // On Unix systems, we write into a buffered terminal rather than directly to a terminal. When
3379 // the .flush() is called we take the buffer created from the buffered writes and write it at
3380 // one shot. Because the Unix systems use ANSI for the colors, which is a text-based styling
3381 // scheme, this buffered approach works and maintains the styling.
3382 //
3383 // On Windows, styling happens through calls to a terminal API. This prevents us from using the
3384 // same buffering approach. Instead, we use a global Windows mutex, which we acquire long
3385 // enough to output the full error message, then we release.
3386 let _buffer_lock = lock::acquire_global_lock("rustc_errors");
3387 for (pos, line) in rendered_buffer.iter().enumerate() {
3388 for part in line {
3389 let style = part.style.color_spec(*lvl);
3390 dst.set_color(&style)?;
3391 write!(dst, "{}", part.text)?;
3392 dst.reset()?;
3393 }
3394 if !short_message && (!lvl.is_failure_note() || pos != rendered_buffer.len() - 1) {
3395 writeln!(dst)?;
3396 }
3397 }
3398 dst.flush()?;
3399 Ok(())
3400}
3401
3402pub type Destination = Box<dyn WriteColor + Send>;
3403
3404struct Buffy {
3405 buffer_writer: BufferWriter,
3406 buffer: Buffer,
3407}
3408
3409impl Write for Buffy {
3410 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
3411 self.buffer.write(buf)
3412 }
3413
3414 fn flush(&mut self) -> io::Result<()> {
3415 self.buffer_writer.print(&self.buffer)?;
3416 self.buffer.clear();
3417 Ok(())
3418 }
3419}
3420
3421impl Drop for Buffy {
3422 fn drop(&mut self) {
3423 if !self.buffer.is_empty() {
3424 self.flush().unwrap();
3425 panic!("buffers need to be flushed in order to print their contents");
3426 }
3427 }
3428}
3429
3430impl WriteColor for Buffy {
3431 fn supports_color(&self) -> bool {
3432 self.buffer.supports_color()
3433 }
3434
3435 fn set_color(&mut self, spec: &ColorSpec) -> io::Result<()> {
3436 self.buffer.set_color(spec)
3437 }
3438
3439 fn reset(&mut self) -> io::Result<()> {
3440 self.buffer.reset()
3441 }
3442}
3443
3444pub fn stderr_destination(color: ColorConfig) -> Destination {
3445 let choice = color.to_color_choice();
3446 // On Windows we'll be performing global synchronization on the entire
3447 // system for emitting rustc errors, so there's no need to buffer
3448 // anything.
3449 //
3450 // On non-Windows we rely on the atomicity of `write` to ensure errors
3451 // don't get all jumbled up.
3452 if cfg!(windows) {
3453 Box::new(StandardStream::stderr(choice))
3454 } else {
3455 let buffer_writer = BufferWriter::stderr(choice);
3456 let buffer = buffer_writer.buffer();
3457 Box::new(Buffy { buffer_writer, buffer })
3458 }
3459}
3460
3461/// On Windows, BRIGHT_BLUE is hard to read on black. Use cyan instead.
3462///
3463/// See #36178.
3464const BRIGHT_BLUE: Color = if cfg!(windows) { Color::Cyan } else { Color::Blue };
3465
3466impl Style {
3467 fn color_spec(&self, lvl: Level) -> ColorSpec {
3468 let mut spec = ColorSpec::new();
3469 match self {
3470 Style::Addition => {
3471 spec.set_fg(Some(Color::Green)).set_intense(true);
3472 }
3473 Style::Removal => {
3474 spec.set_fg(Some(Color::Red)).set_intense(true);
3475 }
3476 Style::LineAndColumn => {}
3477 Style::LineNumber => {
3478 spec.set_bold(true);
3479 spec.set_intense(true);
3480 spec.set_fg(Some(BRIGHT_BLUE));
3481 }
3482 Style::Quotation => {}
3483 Style::MainHeaderMsg => {
3484 spec.set_bold(true);
3485 if cfg!(windows) {
3486 spec.set_intense(true).set_fg(Some(Color::White));
3487 }
3488 }
3489 Style::UnderlinePrimary | Style::LabelPrimary => {
3490 spec = lvl.color();
3491 spec.set_bold(true);
3492 }
3493 Style::UnderlineSecondary | Style::LabelSecondary => {
3494 spec.set_bold(true).set_intense(true);
3495 spec.set_fg(Some(BRIGHT_BLUE));
3496 }
3497 Style::HeaderMsg | Style::NoStyle => {}
3498 Style::Level(lvl) => {
3499 spec = lvl.color();
3500 spec.set_bold(true);
3501 }
3502 Style::Highlight => {
3503 spec.set_bold(true).set_fg(Some(Color::Magenta));
3504 }
3505 }
3506 spec
3507 }
3508}
3509
3510/// Whether the original and suggested code are the same.
3511pub fn is_different(sm: &SourceMap, suggested: &str, sp: Span) -> bool {
3512 let found = match sm.span_to_snippet(sp) {
3513 Ok(snippet) => snippet,
3514 Err(e) => {
3515 warn!(error = ?e, "Invalid span {:?}", sp);
3516 return true;
3517 }
3518 };
3519 found != suggested
3520}
3521
3522/// Whether the original and suggested code are visually similar enough to warrant extra wording.
3523pub fn is_case_difference(sm: &SourceMap, suggested: &str, sp: Span) -> bool {
3524 // FIXME: this should probably be extended to also account for `FO0` → `FOO` and unicode.
3525 let found = match sm.span_to_snippet(sp) {
3526 Ok(snippet) => snippet,
3527 Err(e) => {
3528 warn!(error = ?e, "Invalid span {:?}", sp);
3529 return false;
3530 }
3531 };
3532 let ascii_confusables = &['c', 'f', 'i', 'k', 'o', 's', 'u', 'v', 'w', 'x', 'y', 'z'];
3533 // All the chars that differ in capitalization are confusable (above):
3534 let confusable = iter::zip(found.chars(), suggested.chars())
3535 .filter(|(f, s)| f != s)
3536 .all(|(f, s)| (ascii_confusables.contains(&f) || ascii_confusables.contains(&s)));
3537 confusable && found.to_lowercase() == suggested.to_lowercase()
3538 // FIXME: We sometimes suggest the same thing we already have, which is a
3539 // bug, but be defensive against that here.
3540 && found != suggested
3541}
3542
3543pub(crate) fn should_show_source_code(
3544 ignored_directories: &[String],
3545 sm: &SourceMap,
3546 file: &SourceFile,
3547) -> bool {
3548 if !sm.ensure_source_file_source_present(file) {
3549 return false;
3550 }
3551
3552 let FileName::Real(name) = &file.name else { return true };
3553 name.local_path()
3554 .map(|path| ignored_directories.iter().all(|dir| !path.starts_with(dir)))
3555 .unwrap_or(true)
3556}