Skip to content

Commit 9656ba7

Browse files
committed
Auto merge of #141573 - nnethercote:rustdoc-alloc-cleanups, r=<try>
rustdoc: cleanups relating to allocations These commits generally clean up the code a bit and also reduce allocation rates a bit. r? `@camelid`
2 parents 95a2212 + c51f167 commit 9656ba7

File tree

10 files changed

+103
-106
lines changed

10 files changed

+103
-106
lines changed

src/librustdoc/clean/types.rs

Lines changed: 8 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ impl From<DefId> for ItemId {
106106
}
107107

108108
/// The crate currently being documented.
109-
#[derive(Clone, Debug)]
109+
#[derive(Debug)]
110110
pub(crate) struct Crate {
111111
pub(crate) module: Item,
112112
/// Only here so that they can be filtered through the rustdoc passes.
@@ -1622,9 +1622,7 @@ impl Type {
16221622
a.def_id() == b.def_id()
16231623
&& a.generics()
16241624
.zip(b.generics())
1625-
.map(|(ag, bg)| {
1626-
ag.iter().zip(bg.iter()).all(|(at, bt)| at.is_doc_subtype_of(bt, cache))
1627-
})
1625+
.map(|(ag, bg)| ag.zip(bg).all(|(at, bt)| at.is_doc_subtype_of(bt, cache)))
16281626
.unwrap_or(true)
16291627
}
16301628
// Other cases, such as primitives, just use recursion.
@@ -1697,7 +1695,7 @@ impl Type {
16971695
}
16981696
}
16991697

1700-
pub(crate) fn generics(&self) -> Option<Vec<&Type>> {
1698+
pub(crate) fn generics<'a>(&'a self) -> Option<impl Iterator<Item = &'a Type>> {
17011699
match self {
17021700
Type::Path { path, .. } => path.generics(),
17031701
_ => None,
@@ -2255,17 +2253,13 @@ impl Path {
22552253
self.segments.last().map(|seg| &seg.args)
22562254
}
22572255

2258-
pub(crate) fn generics(&self) -> Option<Vec<&Type>> {
2256+
pub(crate) fn generics<'a>(&'a self) -> Option<impl Iterator<Item = &'a Type>> {
22592257
self.segments.last().and_then(|seg| {
22602258
if let GenericArgs::AngleBracketed { ref args, .. } = seg.args {
2261-
Some(
2262-
args.iter()
2263-
.filter_map(|arg| match arg {
2264-
GenericArg::Type(ty) => Some(ty),
2265-
_ => None,
2266-
})
2267-
.collect(),
2268-
)
2259+
Some(args.iter().filter_map(|arg| match arg {
2260+
GenericArg::Type(ty) => Some(ty),
2261+
_ => None,
2262+
}))
22692263
} else {
22702264
None
22712265
}

src/librustdoc/html/format.rs

Lines changed: 31 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -483,12 +483,12 @@ fn generate_item_def_id_path(
483483
let mut is_remote = false;
484484

485485
let url_parts = url_parts(cx.cache(), def_id, module_fqp, &cx.current, &mut is_remote)?;
486-
let (url_parts, shortty, fqp) = make_href(root_path, shortty, url_parts, &fqp, is_remote)?;
487-
if def_id == original_def_id {
488-
return Ok((url_parts, shortty, fqp));
489-
}
490-
let kind = ItemType::from_def_kind(original_def_kind, Some(def_kind));
491-
Ok((format!("{url_parts}#{kind}.{}", tcx.item_name(original_def_id)), shortty, fqp))
486+
let mut url_parts = make_href(root_path, shortty, url_parts, &fqp, is_remote);
487+
if def_id != original_def_id {
488+
let kind = ItemType::from_def_kind(original_def_kind, Some(def_kind));
489+
url_parts = format!("{url_parts}#{kind}.{}", tcx.item_name(original_def_id))
490+
};
491+
Ok((url_parts, shortty, fqp))
492492
}
493493

494494
fn to_module_fqp(shortty: ItemType, fqp: &[Symbol]) -> &[Symbol] {
@@ -510,7 +510,7 @@ fn url_parts(
510510
builder.extend(module_fqp.iter().copied());
511511
Ok(builder)
512512
}
513-
ExternalLocation::Local => Ok(href_relative_parts(module_fqp, relative_to).collect()),
513+
ExternalLocation::Local => Ok(href_relative_parts(module_fqp, relative_to)),
514514
ExternalLocation::Unknown => Err(HrefError::DocumentationNotBuilt),
515515
}
516516
}
@@ -521,7 +521,7 @@ fn make_href(
521521
mut url_parts: UrlPartsBuilder,
522522
fqp: &[Symbol],
523523
is_remote: bool,
524-
) -> Result<(String, ItemType, Vec<Symbol>), HrefError> {
524+
) -> String {
525525
if !is_remote && let Some(root_path) = root_path {
526526
let root = root_path.trim_end_matches('/');
527527
url_parts.push_front(root);
@@ -536,7 +536,7 @@ fn make_href(
536536
url_parts.push_fmt(format_args!("{shortty}.{last}.html"));
537537
}
538538
}
539-
Ok((url_parts.finish(), shortty, fqp.to_vec()))
539+
url_parts.finish()
540540
}
541541

542542
pub(crate) fn href_with_root_path(
@@ -587,7 +587,7 @@ pub(crate) fn href_with_root_path(
587587
Some(&(ref fqp, shortty)) => (fqp, shortty, {
588588
let module_fqp = to_module_fqp(shortty, fqp.as_slice());
589589
debug!(?fqp, ?shortty, ?module_fqp);
590-
href_relative_parts(module_fqp, relative_to).collect()
590+
href_relative_parts(module_fqp, relative_to)
591591
}),
592592
None => {
593593
// Associated items are handled differently with "jump to def". The anchor is generated
@@ -606,7 +606,8 @@ pub(crate) fn href_with_root_path(
606606
}
607607
}
608608
};
609-
make_href(root_path, shortty, url_parts, fqp, is_remote)
609+
let url_parts = make_href(root_path, shortty, url_parts, &fqp, is_remote);
610+
Ok((url_parts, shortty, fqp.clone()))
610611
}
611612

612613
pub(crate) fn href(
@@ -619,34 +620,30 @@ pub(crate) fn href(
619620
/// Both paths should only be modules.
620621
/// This is because modules get their own directories; that is, `std::vec` and `std::vec::Vec` will
621622
/// both need `../iter/trait.Iterator.html` to get at the iterator trait.
622-
pub(crate) fn href_relative_parts<'fqp>(
623-
fqp: &'fqp [Symbol],
624-
relative_to_fqp: &[Symbol],
625-
) -> Box<dyn Iterator<Item = Symbol> + 'fqp> {
623+
pub(crate) fn href_relative_parts(fqp: &[Symbol], relative_to_fqp: &[Symbol]) -> UrlPartsBuilder {
626624
for (i, (f, r)) in fqp.iter().zip(relative_to_fqp.iter()).enumerate() {
627625
// e.g. linking to std::iter from std::vec (`dissimilar_part_count` will be 1)
628626
if f != r {
629627
let dissimilar_part_count = relative_to_fqp.len() - i;
630628
let fqp_module = &fqp[i..];
631-
return Box::new(
632-
iter::repeat_n(sym::dotdot, dissimilar_part_count)
633-
.chain(fqp_module.iter().copied()),
634-
);
629+
return iter::repeat_n(sym::dotdot, dissimilar_part_count)
630+
.chain(fqp_module.iter().copied())
631+
.collect();
635632
}
636633
}
637634
match relative_to_fqp.len().cmp(&fqp.len()) {
638635
Ordering::Less => {
639636
// e.g. linking to std::sync::atomic from std::sync
640-
Box::new(fqp[relative_to_fqp.len()..fqp.len()].iter().copied())
637+
fqp[relative_to_fqp.len()..fqp.len()].iter().copied().collect()
641638
}
642639
Ordering::Greater => {
643640
// e.g. linking to std::sync from std::sync::atomic
644641
let dissimilar_part_count = relative_to_fqp.len() - fqp.len();
645-
Box::new(iter::repeat_n(sym::dotdot, dissimilar_part_count))
642+
iter::repeat_n(sym::dotdot, dissimilar_part_count).collect()
646643
}
647644
Ordering::Equal => {
648645
// linking to the same module
649-
Box::new(iter::empty())
646+
UrlPartsBuilder::new()
650647
}
651648
}
652649
}
@@ -708,13 +705,13 @@ fn resolved_path(
708705
f,
709706
"{path}::{anchor}",
710707
path = join_with_double_colon(&fqp[..fqp.len() - 1]),
711-
anchor = anchor(did, *fqp.last().unwrap(), cx)
708+
anchor = print_anchor(did, *fqp.last().unwrap(), cx)
712709
)
713710
} else {
714711
write!(f, "{}", last.name)
715712
}
716713
} else {
717-
write!(f, "{}", anchor(did, last.name, cx))
714+
write!(f, "{}", print_anchor(did, last.name, cx))
718715
}
719716
});
720717
write!(w, "{path}{args}", args = last.args.print(cx))?;
@@ -800,7 +797,7 @@ fn primitive_link_fragment(
800797
Ok(())
801798
}
802799

803-
fn tybounds(
800+
fn print_tybounds(
804801
bounds: &[clean::PolyTrait],
805802
lt: &Option<clean::Lifetime>,
806803
cx: &Context<'_>,
@@ -832,7 +829,7 @@ fn print_higher_ranked_params_with_space(
832829
})
833830
}
834831

835-
pub(crate) fn anchor(did: DefId, text: Symbol, cx: &Context<'_>) -> impl Display {
832+
pub(crate) fn print_anchor(did: DefId, text: Symbol, cx: &Context<'_>) -> impl Display {
836833
fmt::from_fn(move |f| {
837834
let parts = href(did, cx);
838835
if let Ok((url, short_ty, fqp)) = parts {
@@ -866,7 +863,7 @@ fn fmt_type(
866863
}
867864
clean::DynTrait(bounds, lt) => {
868865
f.write_str("dyn ")?;
869-
tybounds(bounds, lt, cx).fmt(f)
866+
print_tybounds(bounds, lt, cx).fmt(f)
870867
}
871868
clean::Infer => write!(f, "_"),
872869
clean::Primitive(clean::PrimitiveType::Never) => {
@@ -1122,16 +1119,16 @@ impl clean::Impl {
11221119
write!(f, "!")?;
11231120
}
11241121
if self.kind.is_fake_variadic()
1125-
&& let generics = ty.generics()
1126-
&& let &[inner_type] = generics.as_ref().map_or(&[][..], |v| &v[..])
1122+
&& let Some(mut generics) = ty.generics()
1123+
&& let (Some(inner_type), None) = (generics.next(), generics.next())
11271124
{
11281125
let last = ty.last();
11291126
if f.alternate() {
11301127
write!(f, "{}<", last)?;
11311128
self.print_type(inner_type, f, use_absolute, cx)?;
11321129
write!(f, ">")?;
11331130
} else {
1134-
write!(f, "{}&lt;", anchor(ty.def_id(), last, cx))?;
1131+
write!(f, "{}&lt;", print_anchor(ty.def_id(), last, cx))?;
11351132
self.print_type(inner_type, f, use_absolute, cx)?;
11361133
write!(f, "&gt;")?;
11371134
}
@@ -1201,12 +1198,11 @@ impl clean::Impl {
12011198
fmt_type(&bare_fn.decl.output, f, use_absolute, cx)?;
12021199
}
12031200
} else if let clean::Type::Path { path } = type_
1204-
&& let Some(generics) = path.generics()
1205-
&& generics.len() == 1
1201+
&& let Some(mut generics) = path.generics()
1202+
&& let (Some(ty), None) = (generics.next(), generics.next())
12061203
&& self.kind.is_fake_variadic()
12071204
{
1208-
let ty = generics[0];
1209-
let wrapper = anchor(path.def_id(), path.last(), cx);
1205+
let wrapper = print_anchor(path.def_id(), path.last(), cx);
12101206
if f.alternate() {
12111207
write!(f, "{wrapper:#}&lt;")?;
12121208
} else {
@@ -1419,7 +1415,7 @@ pub(crate) fn visibility_print_with_space(item: &clean::Item, cx: &Context<'_>)
14191415
debug!("path={path:?}");
14201416
// modified from `resolved_path()` to work with `DefPathData`
14211417
let last_name = path.data.last().unwrap().data.get_opt_name().unwrap();
1422-
let anchor = anchor(vis_did, last_name, cx);
1418+
let anchor = print_anchor(vis_did, last_name, cx);
14231419

14241420
let mut s = "pub(in ".to_owned();
14251421
for seg in &path.data[..path.data.len() - 1] {

src/librustdoc/html/layout.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ use super::static_files::{STATIC_FILES, StaticFiles};
88
use crate::externalfiles::ExternalHtml;
99
use crate::html::render::{StylePath, ensure_trailing_slash};
1010

11-
#[derive(Clone)]
1211
pub(crate) struct Layout {
1312
pub(crate) logo: String,
1413
pub(crate) favicon: String,

src/librustdoc/html/markdown.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -195,7 +195,7 @@ fn slugify(c: char) -> Option<char> {
195195
}
196196
}
197197

198-
#[derive(Clone, Debug)]
198+
#[derive(Debug)]
199199
pub struct Playground {
200200
pub crate_name: Option<Symbol>,
201201
pub url: String,

src/librustdoc/html/render/context.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ use rustc_span::edition::Edition;
1414
use rustc_span::{FileName, Symbol, sym};
1515
use tracing::info;
1616

17-
use super::print_item::{full_path, item_path, print_item};
17+
use super::print_item::{full_path, print_item, print_item_path};
1818
use super::sidebar::{ModuleLike, Sidebar, print_sidebar, sidebar_module_like};
1919
use super::{AllTypes, LinkFromSrc, StylePath, collect_spans_and_sources, scrape_examples_help};
2020
use crate::clean::types::ExternalLocation;
@@ -266,7 +266,7 @@ impl<'tcx> Context<'tcx> {
266266
for name in &names[..names.len() - 1] {
267267
write!(f, "{name}/")?;
268268
}
269-
write!(f, "{}", item_path(ty, names.last().unwrap().as_str()))
269+
write!(f, "{}", print_item_path(ty, names.last().unwrap().as_str()))
270270
});
271271
match self.shared.redirections {
272272
Some(ref redirections) => {
@@ -278,7 +278,7 @@ impl<'tcx> Context<'tcx> {
278278
let _ = write!(
279279
current_path,
280280
"{}",
281-
item_path(ty, names.last().unwrap().as_str())
281+
print_item_path(ty, names.last().unwrap().as_str())
282282
);
283283
redirections.borrow_mut().insert(current_path, path.to_string());
284284
}
@@ -847,7 +847,7 @@ impl<'tcx> FormatRenderer<'tcx> for Context<'tcx> {
847847
if !buf.is_empty() {
848848
let name = item.name.as_ref().unwrap();
849849
let item_type = item.type_();
850-
let file_name = item_path(item_type, name.as_str()).to_string();
850+
let file_name = print_item_path(item_type, name.as_str()).to_string();
851851
self.shared.ensure_dir(&self.dst)?;
852852
let joint_dst = self.dst.join(&file_name);
853853
self.shared.fs.write(joint_dst, buf)?;

src/librustdoc/html/render/mod.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2548,7 +2548,7 @@ fn item_ty_to_section(ty: ItemType) -> ItemSection {
25482548
/// types are re-exported, we don't use the corresponding
25492549
/// entry from the js file, as inlining will have already
25502550
/// picked up the impl
2551-
fn collect_paths_for_type(first_ty: clean::Type, cache: &Cache) -> Vec<String> {
2551+
fn collect_paths_for_type(first_ty: &clean::Type, cache: &Cache) -> Vec<String> {
25522552
let mut out = Vec::new();
25532553
let mut visited = FxHashSet::default();
25542554
let mut work = VecDeque::new();
@@ -2565,7 +2565,7 @@ fn collect_paths_for_type(first_ty: clean::Type, cache: &Cache) -> Vec<String> {
25652565
work.push_back(first_ty);
25662566

25672567
while let Some(ty) = work.pop_front() {
2568-
if !visited.insert(ty.clone()) {
2568+
if !visited.insert(ty) {
25692569
continue;
25702570
}
25712571

@@ -2575,16 +2575,16 @@ fn collect_paths_for_type(first_ty: clean::Type, cache: &Cache) -> Vec<String> {
25752575
work.extend(tys.into_iter());
25762576
}
25772577
clean::Type::Slice(ty) => {
2578-
work.push_back(*ty);
2578+
work.push_back(ty);
25792579
}
25802580
clean::Type::Array(ty, _) => {
2581-
work.push_back(*ty);
2581+
work.push_back(ty);
25822582
}
25832583
clean::Type::RawPointer(_, ty) => {
2584-
work.push_back(*ty);
2584+
work.push_back(ty);
25852585
}
25862586
clean::Type::BorrowedRef { type_, .. } => {
2587-
work.push_back(*type_);
2587+
work.push_back(type_);
25882588
}
25892589
clean::Type::QPath(box clean::QPathData { self_type, trait_, .. }) => {
25902590
work.push_back(self_type);

0 commit comments

Comments
 (0)