Skip to content

Get rid of unnecessary BufDisplay abstraction #141288

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
May 21, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 1 addition & 18 deletions src/librustdoc/html/layout.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::fmt::{self, Display};
use std::fmt::Display;
use std::path::PathBuf;

use askama::Template;
Expand Down Expand Up @@ -71,23 +71,6 @@ struct PageLayout<'a> {

pub(crate) use crate::html::render::sidebar::filters;

/// Implements [`Display`] for a function that accepts a mutable reference to a [`String`], and (optionally) writes to it.
///
/// The wrapped function will receive an empty string, and can modify it,
/// and the `Display` implementation will write the contents of the string after the function has finished.
pub(crate) struct BufDisplay<F>(pub F);

impl<F> Display for BufDisplay<F>
where
F: Fn(&mut String),
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut buf = String::new();
self.0(&mut buf);
f.write_str(&buf)
}
}

pub(crate) fn render<T: Display, S: Display>(
layout: &Layout,
page: &Page<'_>,
Expand Down
7 changes: 2 additions & 5 deletions src/librustdoc/html/render/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,10 @@ use crate::formats::cache::Cache;
use crate::formats::item_type::ItemType;
use crate::html::escape::Escape;
use crate::html::format::join_with_double_colon;
use crate::html::layout::{self, BufDisplay};
use crate::html::markdown::{self, ErrorCodes, IdMap, plain_text_summary};
use crate::html::render::write_shared::write_shared;
use crate::html::url_parts_builder::UrlPartsBuilder;
use crate::html::{sources, static_files};
use crate::html::{layout, sources, static_files};
use crate::scrape_examples::AllCallLocations;
use crate::{DOC_RUST_LANG_ORG_VERSION, try_err};

Expand Down Expand Up @@ -250,9 +249,7 @@ impl<'tcx> Context<'tcx> {
layout::render(
&self.shared.layout,
&page,
BufDisplay(|buf: &mut String| {
print_sidebar(self, it, buf);
}),
fmt::from_fn(|f| print_sidebar(self, it, f)),
content,
&self.shared.style_files,
)
Expand Down
37 changes: 19 additions & 18 deletions src/librustdoc/html/render/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -538,7 +538,7 @@ fn document(
}

fmt::from_fn(move |f| {
document_item_info(cx, item, parent).render_into(f).unwrap();
document_item_info(cx, item, parent).render_into(f)?;
if parent.is_none() {
write!(f, "{}", document_full_collapsible(item, cx, heading_offset))
} else {
Expand Down Expand Up @@ -582,7 +582,7 @@ fn document_short(
show_def_docs: bool,
) -> impl fmt::Display {
fmt::from_fn(move |f| {
document_item_info(cx, item, Some(parent)).render_into(f).unwrap();
document_item_info(cx, item, Some(parent)).render_into(f)?;
if !show_def_docs {
return Ok(());
}
Expand Down Expand Up @@ -661,7 +661,7 @@ fn document_full_inner(
};

if let clean::ItemKind::FunctionItem(..) | clean::ItemKind::MethodItem(..) = kind {
render_call_locations(f, cx, item);
render_call_locations(f, cx, item)?;
}
Ok(())
})
Expand Down Expand Up @@ -2584,11 +2584,15 @@ const MAX_FULL_EXAMPLES: usize = 5;
const NUM_VISIBLE_LINES: usize = 10;

/// Generates the HTML for example call locations generated via the --scrape-examples flag.
fn render_call_locations<W: fmt::Write>(mut w: W, cx: &Context<'_>, item: &clean::Item) {
fn render_call_locations<W: fmt::Write>(
mut w: W,
cx: &Context<'_>,
item: &clean::Item,
) -> fmt::Result {
let tcx = cx.tcx();
let def_id = item.item_id.expect_def_id();
let key = tcx.def_path_hash(def_id);
let Some(call_locations) = cx.shared.call_locations.get(&key) else { return };
let Some(call_locations) = cx.shared.call_locations.get(&key) else { return Ok(()) };

// Generate a unique ID so users can link to this section for a given method
let id = cx.derive_id("scraped-examples");
Expand All @@ -2602,8 +2606,7 @@ fn render_call_locations<W: fmt::Write>(mut w: W, cx: &Context<'_>, item: &clean
</h5>",
root_path = cx.root_path(),
id = id
)
.unwrap();
)?;

// Create a URL to a particular location in a reverse-dependency's source file
let link_to_loc = |call_data: &CallData, loc: &CallLocation| -> (String, String) {
Expand Down Expand Up @@ -2705,7 +2708,8 @@ fn render_call_locations<W: fmt::Write>(mut w: W, cx: &Context<'_>, item: &clean
title: init_title,
locations: locations_encoded,
}),
);
)
.unwrap();

true
};
Expand Down Expand Up @@ -2761,8 +2765,7 @@ fn render_call_locations<W: fmt::Write>(mut w: W, cx: &Context<'_>, item: &clean
<div class=\"hide-more\">Hide additional examples</div>\
<div class=\"more-scraped-examples\">\
<div class=\"toggle-line\"><div class=\"toggle-line-inner\"></div></div>"
)
.unwrap();
)?;

// Only generate inline code for MAX_FULL_EXAMPLES number of examples. Otherwise we could
// make the page arbitrarily huge!
Expand All @@ -2774,23 +2777,21 @@ fn render_call_locations<W: fmt::Write>(mut w: W, cx: &Context<'_>, item: &clean
if it.peek().is_some() {
w.write_str(
r#"<div class="example-links">Additional examples can be found in:<br><ul>"#,
)
.unwrap();
it.for_each(|(_, call_data)| {
)?;
it.try_for_each(|(_, call_data)| {
let (url, _) = link_to_loc(call_data, &call_data.locations[0]);
write!(
w,
r#"<li><a href="{url}">{name}</a></li>"#,
url = url,
name = call_data.display_name
)
.unwrap();
});
w.write_str("</ul></div>").unwrap();
})?;
w.write_str("</ul></div>")?;
}

w.write_str("</div></details>").unwrap();
w.write_str("</div></details>")?;
}

w.write_str("</div>").unwrap();
w.write_str("</div>")
}
10 changes: 8 additions & 2 deletions src/librustdoc/html/render/sidebar.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use std::borrow::Cow;
use std::cmp::Ordering;
use std::fmt;

use askama::Template;
use rustc_data_structures::fx::FxHashSet;
Expand Down Expand Up @@ -135,7 +136,11 @@ pub(crate) mod filters {
}
}

pub(super) fn print_sidebar(cx: &Context<'_>, it: &clean::Item, buffer: &mut String) {
pub(super) fn print_sidebar(
cx: &Context<'_>,
it: &clean::Item,
mut buffer: impl fmt::Write,
) -> fmt::Result {
let mut ids = IdMap::new();
let mut blocks: Vec<LinkBlock<'_>> = docblock_toc(cx, it, &mut ids).into_iter().collect();
let deref_id_map = cx.deref_id_map.borrow();
Expand Down Expand Up @@ -195,7 +200,8 @@ pub(super) fn print_sidebar(cx: &Context<'_>, it: &clean::Item, buffer: &mut Str
blocks,
path,
};
sidebar.render_into(buffer).unwrap();
sidebar.render_into(&mut buffer)?;
Ok(())
}

fn get_struct_fields_name<'a>(fields: &'a [clean::Item]) -> Vec<Link<'a>> {
Expand Down
21 changes: 9 additions & 12 deletions src/librustdoc/html/sources.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,8 @@ use rustc_session::Session;
use rustc_span::{FileName, FileNameDisplayPreference, RealFileName, sym};
use tracing::info;

use super::highlight;
use super::layout::{self, BufDisplay};
use super::render::Context;
use super::{highlight, layout};
use crate::clean;
use crate::clean::utils::has_doc_flag;
use crate::docfs::PathError;
Expand Down Expand Up @@ -243,16 +242,16 @@ impl SourceCollector<'_, '_> {
&shared.layout,
&page,
"",
BufDisplay(|buf: &mut String| {
fmt::from_fn(|f| {
print_src(
buf,
f,
contents,
file_span,
self.cx,
&root_path,
&highlight::DecorationInfo::default(),
&source_context,
);
)
}),
&shared.style_files,
);
Expand Down Expand Up @@ -331,7 +330,7 @@ pub(crate) fn print_src(
root_path: &str,
decoration_info: &highlight::DecorationInfo,
source_context: &SourceContext<'_>,
) {
) -> fmt::Result {
let mut lines = s.lines().count();
let line_info = if let SourceContext::Embedded(info) = source_context {
highlight::LineInfo::new_scraped(lines as u32, info.offset as u32)
Expand Down Expand Up @@ -367,12 +366,10 @@ pub(crate) fn print_src(
},
max_nb_digits,
}
.render_into(&mut writer)
.unwrap(),
.render_into(&mut writer),
SourceContext::Embedded(info) => {
ScrapedSource { info, code_html: code, max_nb_digits }
.render_into(&mut writer)
.unwrap();
ScrapedSource { info, code_html: code, max_nb_digits }.render_into(&mut writer)
}
};
}?;
Ok(())
}
Loading