Skip to content

Commit

Permalink
Auto merge of rust-lang#136599 - yotamofek:pr/rustdoc-more-joined, r=…
Browse files Browse the repository at this point in the history
…<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
  • Loading branch information
bors committed Feb 5, 2025
2 parents d4bdd1e + 2341962 commit 2ffed9b
Show file tree
Hide file tree
Showing 5 changed files with 100 additions and 72 deletions.
6 changes: 3 additions & 3 deletions src/librustdoc/clean/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1143,9 +1143,9 @@ fn clean_args_from_types_and_body_id<'tcx>(
Arguments {
values: types
.iter()
.enumerate()
.map(|(i, ty)| Argument {
name: name_from_pat(body.params[i].pat),
.zip(body.params)
.map(|(ty, param)| Argument {
name: name_from_pat(param.pat),
type_: clean_ty(ty, cx),
is_const: false,
})
Expand Down
71 changes: 45 additions & 26 deletions src/librustdoc/clean/utils.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use std::assert_matches::debug_assert_matches;
use std::fmt::Write as _;
use std::fmt::{self, Display, Write as _};
use std::mem;
use std::sync::LazyLock as Lazy;

Expand All @@ -24,6 +24,7 @@ use crate::clean::{
clean_middle_ty, inline,
};
use crate::core::DocContext;
use crate::joined::Joined as _;

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

let mut s = String::new();
for (i, seg) in segments.iter().enumerate() {
if i > 0 {
s.push_str("::");
}
if seg.ident.name != kw::PathRoot {
s.push_str(seg.ident.as_str());
}
}
s
fmt::from_fn(|f| {
segments
.iter()
.map(|seg| {
fmt::from_fn(|f| {
if seg.ident.name != kw::PathRoot {
write!(f, "{}", seg.ident)?;
}
Ok(())
})
})
.joined("::", f)
})
.to_string()
}

pub(crate) fn build_deref_target_impls(
Expand Down Expand Up @@ -299,35 +304,49 @@ pub(crate) fn name_from_pat(p: &hir::Pat<'_>) -> Symbol {

Symbol::intern(&match p.kind {
// FIXME(never_patterns): does this make sense?
PatKind::Wild | PatKind::Err(_) | PatKind::Never | PatKind::Struct(..) => {
PatKind::Wild
| PatKind::Err(_)
| PatKind::Never
| PatKind::Struct(..)
| PatKind::Range(..) => {
return kw::Underscore;
}
PatKind::Binding(_, _, ident, _) => return ident.name,
PatKind::Box(p) | PatKind::Ref(p, _) | PatKind::Guard(p, _) => return name_from_pat(p),
PatKind::TupleStruct(ref p, ..)
| PatKind::Expr(PatExpr { kind: PatExprKind::Path(ref p), .. }) => qpath_to_string(p),
PatKind::Or(pats) => {
pats.iter().map(|p| name_from_pat(p).to_string()).collect::<Vec<String>>().join(" | ")
fmt::from_fn(|f| pats.iter().map(|p| name_from_pat(p)).joined(" | ", f)).to_string()
}
PatKind::Tuple(elts, _) => {
format!("({})", fmt::from_fn(|f| elts.iter().map(|p| name_from_pat(p)).joined(", ", f)))
}
PatKind::Tuple(elts, _) => format!(
"({})",
elts.iter().map(|p| name_from_pat(p).to_string()).collect::<Vec<String>>().join(", ")
),
PatKind::Box(p) => return name_from_pat(p),
PatKind::Deref(p) => format!("deref!({})", name_from_pat(p)),
PatKind::Ref(p, _) => return name_from_pat(p),
PatKind::Expr(..) => {
warn!(
"tried to get argument name from PatKind::Expr, which is silly in function arguments"
);
return Symbol::intern("()");
}
PatKind::Guard(p, _) => return name_from_pat(p),
PatKind::Range(..) => return kw::Underscore,
PatKind::Slice(begin, ref mid, end) => {
let begin = begin.iter().map(|p| name_from_pat(p).to_string());
let mid = mid.as_ref().map(|p| format!("..{}", name_from_pat(p))).into_iter();
let end = end.iter().map(|p| name_from_pat(p).to_string());
format!("[{}]", begin.chain(mid).chain(end).collect::<Vec<_>>().join(", "))
PatKind::Slice(begin, mid, end) => {
fn print_pat<'a>(pat: &'a Pat<'a>, wild: bool) -> impl Display + 'a {
fmt::from_fn(move |f| {
if wild {
f.write_str("..")?;
}
name_from_pat(pat).fmt(f)
})
}

format!(
"[{}]",
fmt::from_fn(|f| {
let begin = begin.iter().map(|p| print_pat(p, false));
let mid = mid.map(|p| print_pat(p, true));
let end = end.iter().map(|p| print_pat(p, false));
begin.chain(mid).chain(end).joined(", ", f)
})
)
}
})
}
Expand Down
16 changes: 10 additions & 6 deletions src/librustdoc/doctest/make.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! Logic for transforming the raw code given by the user into something actually
//! runnable, e.g. by adding a `main` function if it doesn't already exist.
use std::fmt::{self, Write as _};
use std::io;

use rustc_ast as ast;
Expand All @@ -18,6 +19,7 @@ use tracing::debug;

use super::GlobalTestOptions;
use crate::html::markdown::LangString;
use crate::joined::Joined as _;

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

// add extra 4 spaces for each line to offset the code block
if opts.insert_indent_space {
prog.push_str(
&everything_else
write!(
prog,
"{}",
fmt::from_fn(|f| everything_else
.lines()
.map(|line| format!(" {}", line))
.collect::<Vec<String>>()
.join("\n"),
);
.map(|line| fmt::from_fn(move |f| write!(f, " {line}")))
.joined("\n", f))
)
.unwrap();
} else {
prog.push_str(everything_else);
};
Expand Down
12 changes: 7 additions & 5 deletions src/librustdoc/html/render/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ use crate::html::markdown::{
};
use crate::html::static_files::SCRAPE_EXAMPLES_HELP_MD;
use crate::html::{highlight, sources};
use crate::joined::Joined as _;
use crate::scrape_examples::{CallData, CallLocation};
use crate::{DOC_RUST_LANG_ORG_VERSION, try_none};

Expand Down Expand Up @@ -2073,11 +2074,12 @@ pub(crate) fn render_impl_summary(
) {
let inner_impl = i.inner_impl();
let id = cx.derive_id(get_id_for_impl(cx.tcx(), i.impl_item.item_id));
let aliases = if aliases.is_empty() {
String::new()
} else {
format!(" data-aliases=\"{}\"", aliases.join(","))
};
let aliases = fmt::from_fn(|f| {
if !aliases.is_empty() {
write!(f, " data-aliases=\"{}\"", fmt::from_fn(|f| aliases.joined(",", f)))?;
}
Ok(())
});
write!(w, "<section id=\"{id}\" class=\"impl\"{aliases}>");
render_rightside(w, cx, &i.impl_item, RenderMode::Normal);
write!(
Expand Down
67 changes: 35 additions & 32 deletions src/librustdoc/html/render/print_item.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ use std::cmp::Ordering;
use std::fmt;
use std::fmt::{Display, Write};

use itertools::Itertools;
use rinja::Template;
use rustc_abi::VariantIdx;
use rustc_data_structures::captures::Captures;
Expand Down Expand Up @@ -499,11 +498,7 @@ fn item_module(w: &mut Buffer, cx: &Context<'_>, item: &clean::Item, items: &[cl
class = myitem.type_(),
unsafety_flag = unsafety_flag,
href = item_path(myitem.type_(), myitem.name.unwrap().as_str()),
title = [myitem.type_().to_string(), full_path(cx, myitem)]
.iter()
.filter_map(|s| if !s.is_empty() { Some(s.as_str()) } else { None })
.collect::<Vec<_>>()
.join(" "),
title = format_args!("{} {}", myitem.type_(), full_path(cx, myitem)),
);
}
}
Expand Down Expand Up @@ -883,7 +878,7 @@ fn item_trait(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::Tra
write!(
w,
"<div class=\"stab must_implement\">At least one of the `{}` methods is required.</div>",
list.iter().join("`, `")
fmt::from_fn(|f| list.iter().joined("`, `", f))
);
}

Expand Down Expand Up @@ -1129,18 +1124,15 @@ fn item_trait(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::Tra
js_src_path.extend(cx.current.iter().copied());
js_src_path.push_fmt(format_args!("{}.{}.js", it.type_(), it.name.unwrap()));
}
let extern_crates = extern_crates
.into_iter()
.map(|cnum| tcx.crate_name(cnum).to_string())
.collect::<Vec<_>>()
.join(",");
let (extern_before, extern_after) =
if extern_crates.is_empty() { ("", "") } else { (" data-ignore-extern-crates=\"", "\"") };
write!(
w,
"<script src=\"{src}\"{extern_before}{extern_crates}{extern_after} async></script>",
src = js_src_path.finish(),
);
let extern_crates = fmt::from_fn(|f| {
if !extern_crates.is_empty() {
f.write_str(" data-ignore-extern-crates=\"")?;
extern_crates.iter().map(|&cnum| tcx.crate_name(cnum)).joined(",", f)?;
f.write_str("\"")?;
}
Ok(())
});
write!(w, "<script src=\"{src}\"{extern_crates} async></script>", src = js_src_path.finish(),);
}

fn item_trait_alias(
Expand Down Expand Up @@ -1351,7 +1343,7 @@ fn item_type_alias(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean
.collect();
js_src_path.extend(target_fqp[..target_fqp.len() - 1].iter().copied());
js_src_path.push_fmt(format_args!("{target_type}.{}.js", target_fqp.last().unwrap()));
let self_path = self_fqp.iter().map(Symbol::as_str).collect::<Vec<&str>>().join("::");
let self_path = fmt::from_fn(|f| self_fqp.iter().joined("::", f));
write!(
w,
"<script src=\"{src}\" data-self-path=\"{self_path}\" async></script>",
Expand Down Expand Up @@ -2290,18 +2282,29 @@ fn render_struct_fields(
{
write!(w, "<span class=\"comment\">/* private fields */</span>");
} else {
for (i, field) in fields.iter().enumerate() {
if i > 0 {
w.write_str(", ");
}
match field.kind {
clean::StrippedItem(box clean::StructFieldItem(..)) => write!(w, "_"),
clean::StructFieldItem(ref ty) => {
write!(w, "{}{}", visibility_print_with_space(field, cx), ty.print(cx),)
}
_ => unreachable!(),
}
}
write!(
w,
"{}",
fmt::from_fn(|f| fields
.iter()
.map(|field| {
fmt::from_fn(|f| match field.kind {
clean::StrippedItem(box clean::StructFieldItem(..)) => {
write!(f, "_")
}
clean::StructFieldItem(ref ty) => {
write!(
f,
"{}{}",
visibility_print_with_space(field, cx),
ty.print(cx)
)
}
_ => unreachable!(),
})
})
.joined(", ", f))
);
}
w.write_str(")");
if let Some(g) = g {
Expand Down

0 comments on commit 2ffed9b

Please sign in to comment.