Skip to content

Commit 4457ce5

Browse files
committed
librustdoc: more usages of Joined::joined
1 parent 301af42 commit 4457ce5

File tree

4 files changed

+93
-69
lines changed

4 files changed

+93
-69
lines changed

src/librustdoc/clean/utils.rs

+39-21
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use std::assert_matches::debug_assert_matches;
2-
use std::fmt::Write as _;
2+
use std::fmt::{self, Display, Write as _};
33
use std::mem;
44
use std::sync::LazyLock as Lazy;
55

@@ -24,6 +24,7 @@ use crate::clean::{
2424
clean_middle_ty, inline,
2525
};
2626
use crate::core::DocContext;
27+
use crate::joined::Joined as _;
2728

2829
#[cfg(test)]
2930
mod tests;
@@ -250,16 +251,20 @@ pub(crate) fn qpath_to_string(p: &hir::QPath<'_>) -> String {
250251
hir::QPath::LangItem(lang_item, ..) => return lang_item.name().to_string(),
251252
};
252253

253-
let mut s = String::new();
254-
for (i, seg) in segments.iter().enumerate() {
255-
if i > 0 {
256-
s.push_str("::");
257-
}
258-
if seg.ident.name != kw::PathRoot {
259-
s.push_str(seg.ident.as_str());
260-
}
261-
}
262-
s
254+
fmt::from_fn(|f| {
255+
segments
256+
.iter()
257+
.map(|seg| {
258+
fmt::from_fn(|f| {
259+
if seg.ident.name != kw::PathRoot {
260+
write!(f, "{}", seg.ident)?;
261+
}
262+
Ok(())
263+
})
264+
})
265+
.joined("::", f)
266+
})
267+
.to_string()
263268
}
264269

265270
pub(crate) fn build_deref_target_impls(
@@ -311,24 +316,37 @@ pub(crate) fn name_from_pat(p: &hir::Pat<'_>) -> Symbol {
311316
PatKind::TupleStruct(ref p, ..)
312317
| PatKind::Expr(PatExpr { kind: PatExprKind::Path(ref p), .. }) => qpath_to_string(p),
313318
PatKind::Or(pats) => {
314-
pats.iter().map(|p| name_from_pat(p).to_string()).collect::<Vec<String>>().join(" | ")
319+
fmt::from_fn(|f| pats.iter().map(|p| name_from_pat(p)).joined(" | ", f)).to_string()
320+
}
321+
PatKind::Tuple(elts, _) => {
322+
format!("({})", fmt::from_fn(|f| elts.iter().map(|p| name_from_pat(p)).joined(", ", f)))
315323
}
316-
PatKind::Tuple(elts, _) => format!(
317-
"({})",
318-
elts.iter().map(|p| name_from_pat(p).to_string()).collect::<Vec<String>>().join(", ")
319-
),
320324
PatKind::Deref(p) => format!("deref!({})", name_from_pat(p)),
321325
PatKind::Expr(..) => {
322326
warn!(
323327
"tried to get argument name from PatKind::Expr, which is silly in function arguments"
324328
);
325329
return Symbol::intern("()");
326330
}
327-
PatKind::Slice(begin, ref mid, end) => {
328-
let begin = begin.iter().map(|p| name_from_pat(p).to_string());
329-
let mid = mid.as_ref().map(|p| format!("..{}", name_from_pat(p))).into_iter();
330-
let end = end.iter().map(|p| name_from_pat(p).to_string());
331-
format!("[{}]", begin.chain(mid).chain(end).collect::<Vec<_>>().join(", "))
331+
PatKind::Slice(begin, mid, end) => {
332+
fn print_pat<'a>(pat: &'a Pat<'a>, wild: bool) -> impl Display + 'a {
333+
fmt::from_fn(move |f| {
334+
if wild {
335+
f.write_str("..")?;
336+
}
337+
name_from_pat(pat).fmt(f)
338+
})
339+
}
340+
341+
format!(
342+
"[{}]",
343+
fmt::from_fn(|f| {
344+
let begin = begin.iter().map(|p| print_pat(p, false));
345+
let mid = mid.map(|p| print_pat(p, true));
346+
let end = end.iter().map(|p| print_pat(p, false));
347+
begin.chain(mid).chain(end).joined(", ", f)
348+
})
349+
)
332350
}
333351
})
334352
}

src/librustdoc/doctest/make.rs

+10-6
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
//! Logic for transforming the raw code given by the user into something actually
22
//! runnable, e.g. by adding a `main` function if it doesn't already exist.
33
4+
use std::fmt::{self, Write as _};
45
use std::io;
56
use std::sync::Arc;
67

@@ -18,6 +19,7 @@ use tracing::debug;
1819

1920
use super::GlobalTestOptions;
2021
use crate::html::markdown::LangString;
22+
use crate::joined::Joined as _;
2123

2224
/// This struct contains information about the doctest itself which is then used to generate
2325
/// doctest source code appropriately.
@@ -232,13 +234,15 @@ impl DocTestBuilder {
232234

233235
// add extra 4 spaces for each line to offset the code block
234236
if opts.insert_indent_space {
235-
prog.push_str(
236-
&everything_else
237+
write!(
238+
prog,
239+
"{}",
240+
fmt::from_fn(|f| everything_else
237241
.lines()
238-
.map(|line| format!(" {}", line))
239-
.collect::<Vec<String>>()
240-
.join("\n"),
241-
);
242+
.map(|line| fmt::from_fn(move |f| write!(f, " {line}")))
243+
.joined("\n", f))
244+
)
245+
.unwrap();
242246
} else {
243247
prog.push_str(everything_else);
244248
};

src/librustdoc/html/render/mod.rs

+7-5
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,7 @@ use crate::html::markdown::{
7878
};
7979
use crate::html::static_files::SCRAPE_EXAMPLES_HELP_MD;
8080
use crate::html::{highlight, sources};
81+
use crate::joined::Joined as _;
8182
use crate::scrape_examples::{CallData, CallLocation};
8283
use crate::{DOC_RUST_LANG_ORG_VERSION, try_none};
8384

@@ -2117,11 +2118,12 @@ pub(crate) fn render_impl_summary(
21172118
) {
21182119
let inner_impl = i.inner_impl();
21192120
let id = cx.derive_id(get_id_for_impl(cx.tcx(), i.impl_item.item_id));
2120-
let aliases = if aliases.is_empty() {
2121-
String::new()
2122-
} else {
2123-
format!(" data-aliases=\"{}\"", aliases.join(","))
2124-
};
2121+
let aliases = fmt::from_fn(|f| {
2122+
if !aliases.is_empty() {
2123+
write!(f, " data-aliases=\"{}\"", fmt::from_fn(|f| aliases.joined(",", f)))?;
2124+
}
2125+
Ok(())
2126+
});
21252127
write_str(w, format_args!("<section id=\"{id}\" class=\"impl\"{aliases}>"));
21262128
render_rightside(w, cx, &i.impl_item, RenderMode::Normal);
21272129
write_str(

src/librustdoc/html/render/print_item.rs

+37-37
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ use std::cmp::Ordering;
22
use std::fmt;
33
use std::fmt::{Display, Write};
44

5-
use itertools::Itertools;
65
use rinja::Template;
76
use rustc_abi::VariantIdx;
87
use rustc_data_structures::captures::Captures;
@@ -514,11 +513,7 @@ fn item_module(w: &mut String, cx: &Context<'_>, item: &clean::Item, items: &[cl
514513
class = myitem.type_(),
515514
unsafety_flag = unsafety_flag,
516515
href = item_path(myitem.type_(), myitem.name.unwrap().as_str()),
517-
title = [myitem.type_().to_string(), full_path(cx, myitem)]
518-
.iter()
519-
.filter_map(|s| if !s.is_empty() { Some(s.as_str()) } else { None })
520-
.collect::<Vec<_>>()
521-
.join(" "),
516+
title = format_args!("{} {}", myitem.type_(), full_path(cx, myitem)),
522517
),
523518
);
524519
}
@@ -916,7 +911,7 @@ fn item_trait(w: &mut String, cx: &Context<'_>, it: &clean::Item, t: &clean::Tra
916911
w,
917912
format_args!(
918913
"<div class=\"stab must_implement\">At least one of the `{}` methods is required.</div>",
919-
list.iter().join("`, `")
914+
fmt::from_fn(|f| list.iter().joined("`, `", f))
920915
),
921916
);
922917
}
@@ -1169,17 +1164,18 @@ fn item_trait(w: &mut String, cx: &Context<'_>, it: &clean::Item, t: &clean::Tra
11691164
js_src_path.extend(cx.current.iter().copied());
11701165
js_src_path.push_fmt(format_args!("{}.{}.js", it.type_(), it.name.unwrap()));
11711166
}
1172-
let extern_crates = extern_crates
1173-
.into_iter()
1174-
.map(|cnum| tcx.crate_name(cnum).to_string())
1175-
.collect::<Vec<_>>()
1176-
.join(",");
1177-
let (extern_before, extern_after) =
1178-
if extern_crates.is_empty() { ("", "") } else { (" data-ignore-extern-crates=\"", "\"") };
1167+
let extern_crates = fmt::from_fn(|f| {
1168+
if !extern_crates.is_empty() {
1169+
f.write_str(" data-ignore-extern-crates=\"")?;
1170+
extern_crates.iter().map(|&cnum| tcx.crate_name(cnum)).joined(",", f)?;
1171+
f.write_str("\"")?;
1172+
}
1173+
Ok(())
1174+
});
11791175
write_str(
11801176
w,
11811177
format_args!(
1182-
"<script src=\"{src}\"{extern_before}{extern_crates}{extern_after} async></script>",
1178+
"<script src=\"{src}\"{extern_crates} async></script>",
11831179
src = js_src_path.finish()
11841180
),
11851181
);
@@ -1401,7 +1397,7 @@ fn item_type_alias(w: &mut String, cx: &Context<'_>, it: &clean::Item, t: &clean
14011397
.collect();
14021398
js_src_path.extend(target_fqp[..target_fqp.len() - 1].iter().copied());
14031399
js_src_path.push_fmt(format_args!("{target_type}.{}.js", target_fqp.last().unwrap()));
1404-
let self_path = self_fqp.iter().map(Symbol::as_str).collect::<Vec<&str>>().join("::");
1400+
let self_path = fmt::from_fn(|f| self_fqp.iter().joined("::", f));
14051401
write_str(
14061402
w,
14071403
format_args!(
@@ -2371,27 +2367,31 @@ fn render_struct_fields(
23712367
{
23722368
write_str(w, format_args!("<span class=\"comment\">/* private fields */</span>"));
23732369
} else {
2374-
for (i, field) in fields.iter().enumerate() {
2375-
if i > 0 {
2376-
w.push_str(", ");
2377-
}
2378-
match field.kind {
2379-
clean::StrippedItem(box clean::StructFieldItem(..)) => {
2380-
write_str(w, format_args!("_"));
2381-
}
2382-
clean::StructFieldItem(ref ty) => {
2383-
write_str(
2384-
w,
2385-
format_args!(
2386-
"{}{}",
2387-
visibility_print_with_space(field, cx),
2388-
ty.print(cx)
2389-
),
2390-
);
2391-
}
2392-
_ => unreachable!(),
2393-
}
2394-
}
2370+
write_str(
2371+
w,
2372+
format_args!(
2373+
"{}",
2374+
fmt::from_fn(|f| fields
2375+
.iter()
2376+
.map(|field| {
2377+
fmt::from_fn(|f| match field.kind {
2378+
clean::StrippedItem(box clean::StructFieldItem(..)) => {
2379+
write!(f, "_")
2380+
}
2381+
clean::StructFieldItem(ref ty) => {
2382+
write!(
2383+
f,
2384+
"{}{}",
2385+
visibility_print_with_space(field, cx),
2386+
ty.print(cx)
2387+
)
2388+
}
2389+
_ => unreachable!(),
2390+
})
2391+
})
2392+
.joined(", ", f))
2393+
),
2394+
);
23952395
}
23962396
w.push_str(")");
23972397
if let Some(g) = g {

0 commit comments

Comments
 (0)