perf(diagnostics): reduce graphical formatting overhead (#25714)

Keep diagnostic titles inline and bypass color formatting when the
active style is plain, reducing focused graphical-rendering time by
5–9%.

AI assistance: Codex was used. The contributor remains responsible for
this change.

<sub>Stack created with <a
href="https://github.com/github/gh-stack">GitHub Stacks CLI</a></sub>
This commit is contained in:
Boshen authored and GitHub committed 2026-08-16 19:06:17 +08:00
1 parent 10fc4b7d33
commit 71528342ee
3 files changed
+122 -46

No files matched your search

@@ -7,10 +7,7 @@
//! text hanging off each one. For multi-line spans the closing label is drawn
//! by [`render_multi_line_end`](GraphicalReportHandler::render_multi_line_end).
use std::{
cmp::max,
fmt::{self, Write},
};
use std::{cmp::max, fmt};
use owo_colors::{OwoColorize, Style};
use smallvec::SmallVec;
@@ -30,6 +27,27 @@ struct Underline {
line: char,
}
impl Underline {
fn write(&self, f: &mut impl fmt::Write) -> fmt::Result {
// Use pre-encoded chunks for built-in theme characters.
let Some((underline_chunk, char_len)) = (match self.line {
'─' => Some((UNICODE_BARS, '─'.len_utf8())),
'^' => Some((ASCII_CARETS, 1)),
_ => None,
}) else {
write_repeated_char(f, ' ', self.padding)?;
write_repeated_char(f, self.line, self.left)?;
f.write_char(self.marker)?;
return write_repeated_char(f, self.line, self.right);
};
write_repeated_chunk(f, SPACES, 1, self.padding)?;
write_repeated_chunk(f, underline_chunk, char_len, self.left)?;
f.write_char(self.marker)?;
write_repeated_chunk(f, underline_chunk, char_len, self.right)
}
}
const CHUNK_CHARS: usize = 64;
const MIN_CHUNKED_CHARS: usize = 8;
const SPACES: &str =
@@ -70,23 +88,7 @@ fn write_padding(f: &mut impl fmt::Write, count: usize) -> fmt::Result {
impl fmt::Display for Underline {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// Built-in themes repeat these characters frequently, so emit them in chunks.
// Preserve the original character loop for custom themes.
let Some((underline_chunk, char_len)) = (match self.line {
'─' => Some((UNICODE_BARS, '─'.len_utf8())),
'^' => Some((ASCII_CARETS, 1)),
_ => None,
}) else {
write_repeated_char(f, ' ', self.padding)?;
write_repeated_char(f, self.line, self.left)?;
f.write_char(self.marker)?;
return write_repeated_char(f, self.line, self.right);
};
write_repeated_chunk(f, SPACES, 1, self.padding)?;
write_repeated_chunk(f, underline_chunk, char_len, self.left)?;
f.write_char(self.marker)?;
write_repeated_chunk(f, underline_chunk, char_len, self.right)
self.write(f)
}
}
@@ -105,6 +107,22 @@ struct LabelContext<'a, 'source, 'label> {
vertical_bars: &'a [(&'a FancySpan<'label>, usize)],
}
impl LabelText<'_> {
fn write_unstyled(&self, f: &mut impl fmt::Write) -> fmt::Result {
let chars = self.chars;
let label = self.label;
match self.render_mode {
LabelRenderMode::SingleLine => {
write!(f, "{}{}{} {label}", chars.lbot, chars.hbar, chars.hbar)
}
LabelRenderMode::BlockFirst => {
write!(f, "{}{}{} {label}", chars.lbot, chars.hbar, chars.rcross)
}
LabelRenderMode::BlockRest => write!(f, " {} {label}", chars.vbar),
}
}
}
impl fmt::Display for LabelText<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let chars = self.chars;
@@ -157,18 +175,18 @@ impl GraphicalReportHandler {
} else {
chars.underline
};
write!(
f,
"{}",
Underline {
padding: width,
left: num_left,
marker,
right: num_right,
line: chars.underline,
}
.style(hl.style)
)?;
let underline = Underline {
padding: width,
left: num_left,
marker,
right: num_right,
line: chars.underline,
};
if hl.style.is_plain() {
underline.write(f)?;
} else {
write!(f, "{}", underline.style(hl.style))?;
}
highest = max(highest, end);
vbar_offsets.push((hl, vbar_offset));
}
@@ -227,7 +245,12 @@ impl GraphicalReportHandler {
style: hl.style,
render_mode,
};
writeln!(f, "{}", line.style(hl.style))?;
if hl.style.is_plain() {
line.write_unstyled(f)?;
} else {
write!(f, "{}", line.style(hl.style))?;
}
f.write_char('\n')?;
break;
}
write!(f, "{}", self.theme.characters.vbar.style(offset_hl.style))?;
@@ -314,6 +337,29 @@ impl GraphicalReportHandler {
mod tests {
use super::*;
#[test]
fn plain_fast_paths_match_display_output() {
let underline = Underline { padding: 3, left: 2, marker: '|', right: 4, line: '^' };
let mut output = String::new();
underline.write(&mut output).unwrap();
assert_eq!(output, underline.to_string());
let theme = crate::GraphicalTheme::none();
for render_mode in
[LabelRenderMode::SingleLine, LabelRenderMode::BlockFirst, LabelRenderMode::BlockRest]
{
let label = LabelText {
chars: &theme.characters,
label: "plain label",
style: Style::new(),
render_mode,
};
output.clear();
label.write_unstyled(&mut output).unwrap();
assert_eq!(output, label.to_string());
}
}
#[test]
fn repeated_chars_match_standard_output() {
for c in [' ', '─', '^', 'x', '🐂'] {
@@ -7,13 +7,34 @@
//! using the shared [`wrap_options`](GraphicalReportHandler::wrap_options)
//! helper.
use std::fmt;
use std::fmt::{self, Write as _};
use owo_colors::OwoColorize;
use smallvec::SmallVec;
use super::handler::{GraphicalReportHandler, LinkStyle};
use crate::{Diagnostic, Severity, source_impls::SpanScanner};
struct TitleBuffer(SmallVec<[u8; 128]>);
impl TitleBuffer {
fn new() -> Self {
Self(SmallVec::new())
}
fn as_str(&self) -> &str {
// SAFETY: writes only append valid UTF-8.
unsafe { std::str::from_utf8_unchecked(&self.0) }
}
}
impl fmt::Write for TitleBuffer {
fn write_str(&mut self, text: &str) -> fmt::Result {
self.0.extend_from_slice(text.as_bytes());
Ok(())
}
}
impl GraphicalReportHandler {
/// Render a [`Diagnostic`].
///
@@ -114,22 +135,26 @@ impl GraphicalReportHandler {
let width = self.termwidth.saturating_sub(2);
let title = match (self.links, diagnostic.url(), diagnostic.code()) {
let mut title = TitleBuffer::new();
match (self.links, diagnostic.url(), diagnostic.code()) {
(LinkStyle::Link, Some(url), Some(code)) => {
// magic unicode escape sequences to make the terminal print a hyperlink
const CTL: &str = "\u{1b}]8;;";
const END: &str = "\u{1b}]8;;\u{1b}\\";
let code = code.style(severity_style);
let title = diagnostic.style(severity_style);
format!("{CTL}{url}\u{1b}\\{code}{END}: {title}")
let diagnostic = diagnostic.style(severity_style);
write!(title, "{CTL}{url}\u{1b}\\{code}{END}: {diagnostic}")?;
}
(_, _, Some(code)) if severity_style.is_plain() => {
write!(title, "{code}: {diagnostic}")?;
}
(_, _, Some(code)) if severity_style.is_plain() => format!("{code}: {diagnostic}"),
(_, _, Some(code)) => {
format!("{}", format_args!("{code}: {diagnostic}").style(severity_style))
write!(title, "{}", format_args!("{code}: {diagnostic}").style(severity_style))?;
}
_ if severity_style.is_plain() => diagnostic.to_string(),
_ => format!("{}", diagnostic.style(severity_style)),
};
_ if severity_style.is_plain() => write!(title, "{diagnostic}")?,
_ => write!(title, "{}", diagnostic.style(severity_style))?,
}
let title = title.as_str();
if !title.contains('\n')
&& severity_icon.len().saturating_add(title.len()).saturating_add(3) <= width
{
@@ -152,7 +177,7 @@ impl GraphicalReportHandler {
)
};
let opts = Self::wrap_options(width, &initial_indent, &rest_indent);
Self::write_fill(f, &title, opts)?;
Self::write_fill(f, title, opts)?;
}
f.write_char('\n')?;
@@ -149,8 +149,13 @@ impl GraphicalReportHandler {
match source_name {
Some(source_name) => {
let source_name = source_name.style(self.theme.styles.link);
writeln!(f, "[{}:{}:{}]", source_name, primary_line + 1, primary_column + 1)?;
let style = self.theme.styles.link;
if style.is_plain() {
writeln!(f, "[{source_name}:{}:{}]", primary_line + 1, primary_column + 1)?;
} else {
let source_name = source_name.style(style);
writeln!(f, "[{}:{}:{}]", source_name, primary_line + 1, primary_column + 1)?;
}
}
_ => {
if lines.len() <= 1 {