Skip to content

Commit 2ffed9b

Browse files
committed
Auto merge of rust-lang#136599 - yotamofek:pr/rustdoc-more-joined, r=<try>
librustdoc: more usages of `Joined::joined` Some missed opportunities from rust-lang#136244 r? `@GuillaumeGomez` since you reviewed the last one (feel free to re-assign, of course 😊) First two commits are just drive-by cleanups
2 parents d4bdd1e + 2341962 commit 2ffed9b

File tree

5 files changed

+100
-72
lines changed

5 files changed

+100
-72
lines changed

src/librustdoc/clean/mod.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -1143,9 +1143,9 @@ fn clean_args_from_types_and_body_id<'tcx>(
11431143
Arguments {
11441144
values: types
11451145
.iter()
1146-
.enumerate()
1147-
.map(|(i, ty)| Argument {
1148-
name: name_from_pat(body.params[i].pat),
1146+
.zip(body.params)
1147+
.map(|(ty, param)| Argument {
1148+
name: name_from_pat(param.pat),
11491149
type_: clean_ty(ty, cx),
11501150
is_const: false,
11511151
})

src/librustdoc/clean/utils.rs

+45-26
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(
@@ -299,35 +304,49 @@ pub(crate) fn name_from_pat(p: &hir::Pat<'_>) -> Symbol {
299304

300305
Symbol::intern(&match p.kind {
301306
// FIXME(never_patterns): does this make sense?
302-
PatKind::Wild | PatKind::Err(_) | PatKind::Never | PatKind::Struct(..) => {
307+
PatKind::Wild
308+
| PatKind::Err(_)
309+
| PatKind::Never
310+
| PatKind::Struct(..)
311+
| PatKind::Range(..) => {
303312
return kw::Underscore;
304313
}
305314
PatKind::Binding(_, _, ident, _) => return ident.name,
315+
PatKind::Box(p) | PatKind::Ref(p, _) | PatKind::Guard(p, _) => return name_from_pat(p),
306316
PatKind::TupleStruct(ref p, ..)
307317
| PatKind::Expr(PatExpr { kind: PatExprKind::Path(ref p), .. }) => qpath_to_string(p),
308318
PatKind::Or(pats) => {
309-
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)))
310323
}
311-
PatKind::Tuple(elts, _) => format!(
312-
"({})",
313-
elts.iter().map(|p| name_from_pat(p).to_string()).collect::<Vec<String>>().join(", ")
314-
),
315-
PatKind::Box(p) => return name_from_pat(p),
316324
PatKind::Deref(p) => format!("deref!({})", name_from_pat(p)),
317-
PatKind::Ref(p, _) => return name_from_pat(p),
318325
PatKind::Expr(..) => {
319326
warn!(
320327
"tried to get argument name from PatKind::Expr, which is silly in function arguments"
321328
);
322329
return Symbol::intern("()");
323330
}
324-
PatKind::Guard(p, _) => return name_from_pat(p),
325-
PatKind::Range(..) => return kw::Underscore,
326-
PatKind::Slice(begin, ref mid, end) => {
327-
let begin = begin.iter().map(|p| name_from_pat(p).to_string());
328-
let mid = mid.as_ref().map(|p| format!("..{}", name_from_pat(p))).into_iter();
329-
let end = end.iter().map(|p| name_from_pat(p).to_string());
330-
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+
)
331350
}
332351
})
333352
}

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

67
use rustc_ast as ast;
@@ -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

@@ -2073,11 +2074,12 @@ pub(crate) fn render_impl_summary(
20732074
) {
20742075
let inner_impl = i.inner_impl();
20752076
let id = cx.derive_id(get_id_for_impl(cx.tcx(), i.impl_item.item_id));
2076-
let aliases = if aliases.is_empty() {
2077-
String::new()
2078-
} else {
2079-
format!(" data-aliases=\"{}\"", aliases.join(","))
2080-
};
2077+
let aliases = fmt::from_fn(|f| {
2078+
if !aliases.is_empty() {
2079+
write!(f, " data-aliases=\"{}\"", fmt::from_fn(|f| aliases.joined(",", f)))?;
2080+
}
2081+
Ok(())
2082+
});
20812083
write!(w, "<section id=\"{id}\" class=\"impl\"{aliases}>");
20822084
render_rightside(w, cx, &i.impl_item, RenderMode::Normal);
20832085
write!(

src/librustdoc/html/render/print_item.rs

+35-32
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;
@@ -499,11 +498,7 @@ fn item_module(w: &mut Buffer, cx: &Context<'_>, item: &clean::Item, items: &[cl
499498
class = myitem.type_(),
500499
unsafety_flag = unsafety_flag,
501500
href = item_path(myitem.type_(), myitem.name.unwrap().as_str()),
502-
title = [myitem.type_().to_string(), full_path(cx, myitem)]
503-
.iter()
504-
.filter_map(|s| if !s.is_empty() { Some(s.as_str()) } else { None })
505-
.collect::<Vec<_>>()
506-
.join(" "),
501+
title = format_args!("{} {}", myitem.type_(), full_path(cx, myitem)),
507502
);
508503
}
509504
}
@@ -883,7 +878,7 @@ fn item_trait(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::Tra
883878
write!(
884879
w,
885880
"<div class=\"stab must_implement\">At least one of the `{}` methods is required.</div>",
886-
list.iter().join("`, `")
881+
fmt::from_fn(|f| list.iter().joined("`, `", f))
887882
);
888883
}
889884

@@ -1129,18 +1124,15 @@ fn item_trait(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::Tra
11291124
js_src_path.extend(cx.current.iter().copied());
11301125
js_src_path.push_fmt(format_args!("{}.{}.js", it.type_(), it.name.unwrap()));
11311126
}
1132-
let extern_crates = extern_crates
1133-
.into_iter()
1134-
.map(|cnum| tcx.crate_name(cnum).to_string())
1135-
.collect::<Vec<_>>()
1136-
.join(",");
1137-
let (extern_before, extern_after) =
1138-
if extern_crates.is_empty() { ("", "") } else { (" data-ignore-extern-crates=\"", "\"") };
1139-
write!(
1140-
w,
1141-
"<script src=\"{src}\"{extern_before}{extern_crates}{extern_after} async></script>",
1142-
src = js_src_path.finish(),
1143-
);
1127+
let extern_crates = fmt::from_fn(|f| {
1128+
if !extern_crates.is_empty() {
1129+
f.write_str(" data-ignore-extern-crates=\"")?;
1130+
extern_crates.iter().map(|&cnum| tcx.crate_name(cnum)).joined(",", f)?;
1131+
f.write_str("\"")?;
1132+
}
1133+
Ok(())
1134+
});
1135+
write!(w, "<script src=\"{src}\"{extern_crates} async></script>", src = js_src_path.finish(),);
11441136
}
11451137

11461138
fn item_trait_alias(
@@ -1351,7 +1343,7 @@ fn item_type_alias(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean
13511343
.collect();
13521344
js_src_path.extend(target_fqp[..target_fqp.len() - 1].iter().copied());
13531345
js_src_path.push_fmt(format_args!("{target_type}.{}.js", target_fqp.last().unwrap()));
1354-
let self_path = self_fqp.iter().map(Symbol::as_str).collect::<Vec<&str>>().join("::");
1346+
let self_path = fmt::from_fn(|f| self_fqp.iter().joined("::", f));
13551347
write!(
13561348
w,
13571349
"<script src=\"{src}\" data-self-path=\"{self_path}\" async></script>",
@@ -2290,18 +2282,29 @@ fn render_struct_fields(
22902282
{
22912283
write!(w, "<span class=\"comment\">/* private fields */</span>");
22922284
} else {
2293-
for (i, field) in fields.iter().enumerate() {
2294-
if i > 0 {
2295-
w.write_str(", ");
2296-
}
2297-
match field.kind {
2298-
clean::StrippedItem(box clean::StructFieldItem(..)) => write!(w, "_"),
2299-
clean::StructFieldItem(ref ty) => {
2300-
write!(w, "{}{}", visibility_print_with_space(field, cx), ty.print(cx),)
2301-
}
2302-
_ => unreachable!(),
2303-
}
2304-
}
2285+
write!(
2286+
w,
2287+
"{}",
2288+
fmt::from_fn(|f| fields
2289+
.iter()
2290+
.map(|field| {
2291+
fmt::from_fn(|f| match field.kind {
2292+
clean::StrippedItem(box clean::StructFieldItem(..)) => {
2293+
write!(f, "_")
2294+
}
2295+
clean::StructFieldItem(ref ty) => {
2296+
write!(
2297+
f,
2298+
"{}{}",
2299+
visibility_print_with_space(field, cx),
2300+
ty.print(cx)
2301+
)
2302+
}
2303+
_ => unreachable!(),
2304+
})
2305+
})
2306+
.joined(", ", f))
2307+
);
23052308
}
23062309
w.write_str(")");
23072310
if let Some(g) = g {

0 commit comments

Comments
 (0)