Skip to content

Commit c83181b

Browse files
committed
WIP: Join trait
1 parent 6b5c926 commit c83181b

File tree

5 files changed

+76
-45
lines changed

5 files changed

+76
-45
lines changed

src/librustdoc/clean/cfg.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
use std::fmt::{self, Write};
77
use std::{mem, ops};
88

9-
use itertools::Itertools;
109
use rustc_ast::{LitKind, MetaItem, MetaItemInner, MetaItemKind, MetaItemLit};
1110
use rustc_data_structures::fx::FxHashSet;
1211
use rustc_feature::Features;
@@ -15,6 +14,7 @@ use rustc_span::Span;
1514
use rustc_span::symbol::{Symbol, sym};
1615

1716
use crate::html::escape::Escape;
17+
use crate::join::Join as _;
1818

1919
#[cfg(test)]
2020
mod tests;
@@ -441,9 +441,8 @@ impl fmt::Display for Display<'_> {
441441
let separator =
442442
if sub_cfgs.iter().all(Cfg::is_simple) { " nor " } else { ", nor " };
443443
fmt.write_str("neither ")?;
444-
sub_cfgs
445-
.iter()
446-
.map(|sub_cfg| {
444+
(|| {
445+
sub_cfgs.iter().map(|sub_cfg| {
447446
fmt::from_fn(|fmt| {
448447
write_with_opt_paren(
449448
fmt,
@@ -452,8 +451,9 @@ impl fmt::Display for Display<'_> {
452451
)
453452
})
454453
})
455-
.format(separator)
456-
.fmt(fmt)
454+
})
455+
.join(separator)
456+
.fmt(fmt)
457457
}
458458
ref simple @ Cfg::Cfg(..) => write!(fmt, "non-{}", Display(simple, self.1)),
459459
ref c => write!(fmt, "not ({})", Display(c, self.1)),

src/librustdoc/html/format.rs

Lines changed: 32 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@ use std::cmp::Ordering;
1212
use std::fmt::{self, Display, Write};
1313
use std::iter::{self, once};
1414

15-
use itertools::Itertools;
1615
use rustc_abi::ExternAbi;
1716
use rustc_attr_parsing::{ConstStability, StabilityLevel, StableSince};
1817
use rustc_data_structures::captures::Captures;
@@ -34,6 +33,7 @@ use crate::formats::cache::Cache;
3433
use crate::formats::item_type::ItemType;
3534
use crate::html::escape::{Escape, EscapeBodyText};
3635
use crate::html::render::Context;
36+
use crate::join::Join as _;
3737
use crate::passes::collect_intra_doc_links::UrlFragment;
3838

3939
pub(crate) trait Print {
@@ -150,14 +150,13 @@ pub(crate) fn print_generic_bounds<'a, 'tcx: 'a>(
150150
cx: &'a Context<'tcx>,
151151
) -> impl Display + 'a + Captures<'tcx> {
152152
fmt::from_fn(move |f| {
153-
let mut bounds_dup = FxHashSet::default();
153+
(|| {
154+
let mut bounds_dup = FxHashSet::default();
154155

155-
bounds
156-
.iter()
157-
.filter(|b| bounds_dup.insert(*b))
158-
.map(|bound| bound.print(cx))
159-
.format(" + ")
160-
.fmt(f)
156+
bounds.iter().filter(move |b| bounds_dup.insert(*b)).map(|bound| bound.print(cx))
157+
})
158+
.join(" + ")
159+
.fmt(f)
161160
})
162161
}
163162

@@ -172,7 +171,7 @@ impl clean::GenericParamDef {
172171

173172
if !outlives.is_empty() {
174173
f.write_str(": ")?;
175-
write!(f, "{}", outlives.iter().map(|lt| lt.print()).format(" + "))?;
174+
write!(f, "{}", (|| outlives.iter().map(|lt| lt.print())).join(" + "))?;
176175
}
177176

178177
Ok(())
@@ -222,10 +221,11 @@ impl clean::Generics {
222221
return Ok(());
223222
}
224223

224+
let real_params = (|| real_params.clone().map(|g| g.print(cx))).join(", ");
225225
if f.alternate() {
226-
write!(f, "<{:#}>", real_params.map(|g| g.print(cx)).format(", "))
226+
write!(f, "<{:#}>", real_params)
227227
} else {
228-
write!(f, "&lt;{}&gt;", real_params.map(|g| g.print(cx)).format(", "))
228+
write!(f, "&lt;{}&gt;", real_params)
229229
}
230230
})
231231
}
@@ -247,10 +247,12 @@ pub(crate) fn print_where_clause<'a, 'tcx: 'a>(
247247
ending: Ending,
248248
) -> impl Display + 'a + Captures<'tcx> {
249249
fmt::from_fn(move |f| {
250-
let mut where_predicates = gens
251-
.where_predicates
252-
.iter()
253-
.map(|pred| {
250+
if gens.where_predicates.is_empty() {
251+
return Ok(());
252+
}
253+
254+
let where_predicates = || {
255+
gens.where_predicates.iter().map(|pred| {
254256
fmt::from_fn(move |f| {
255257
if f.alternate() {
256258
f.write_str(" ")?;
@@ -289,13 +291,9 @@ pub(crate) fn print_where_clause<'a, 'tcx: 'a>(
289291
}
290292
})
291293
})
292-
.peekable();
293-
294-
if where_predicates.peek().is_none() {
295-
return Ok(());
296-
}
294+
};
297295

298-
let where_preds = where_predicates.format(",");
296+
let where_preds = where_predicates.join(",");
299297
let clause = if f.alternate() {
300298
if ending == Ending::Newline {
301299
format!(" where{where_preds},")
@@ -392,7 +390,7 @@ impl clean::GenericBound {
392390
} else {
393391
f.write_str("use&lt;")?;
394392
}
395-
args.iter().format(", ").fmt(f)?;
393+
(|| args.iter()).join(", ").fmt(f)?;
396394
if f.alternate() { f.write_str(">") } else { f.write_str("&gt;") }
397395
}
398396
})
@@ -496,7 +494,7 @@ pub(crate) enum HrefError {
496494
// Panics if `syms` is empty.
497495
pub(crate) fn join_with_double_colon(syms: &[Symbol]) -> String {
498496
let mut s = String::with_capacity(estimate_item_path_byte_length(syms.len()));
499-
write!(s, "{}", syms.iter().format("::")).unwrap();
497+
write!(s, "{}", (|| syms.iter()).join("::")).unwrap();
500498
s
501499
}
502500

@@ -546,14 +544,14 @@ fn generate_macro_def_id_path(
546544
let url = match cache.extern_locations[&def_id.krate] {
547545
ExternalLocation::Remote(ref s) => {
548546
// `ExternalLocation::Remote` always end with a `/`.
549-
format!("{s}{path}", path = path.iter().format("/"))
547+
format!("{s}{path}", path = (|| path.iter()).join("/"))
550548
}
551549
ExternalLocation::Local => {
552550
// `root_path` always end with a `/`.
553551
format!(
554552
"{root_path}{path}",
555553
root_path = root_path.unwrap_or(""),
556-
path = path.iter().format("/")
554+
path = (|| path.iter()).join("/")
557555
)
558556
}
559557
ExternalLocation::Unknown => {
@@ -917,7 +915,7 @@ fn tybounds<'a, 'tcx: 'a>(
917915
cx: &'a Context<'tcx>,
918916
) -> impl Display + 'a + Captures<'tcx> {
919917
fmt::from_fn(move |f| {
920-
bounds.iter().map(|bound| bound.print(cx)).format(" + ").fmt(f)?;
918+
(|| bounds.iter().map(|bound| bound.print(cx))).join(" + ").fmt(f)?;
921919
if let Some(lt) = lt {
922920
// We don't need to check `alternate` since we can be certain that
923921
// the lifetime doesn't contain any characters which need escaping.
@@ -936,7 +934,7 @@ fn print_higher_ranked_params_with_space<'a, 'tcx: 'a>(
936934
if !params.is_empty() {
937935
f.write_str(keyword)?;
938936
f.write_str(if f.alternate() { "<" } else { "&lt;" })?;
939-
params.iter().map(|lt| lt.print(cx)).format(", ").fmt(f)?;
937+
(|| params.iter().map(|lt| lt.print(cx))).join(", ").fmt(f)?;
940938
f.write_str(if f.alternate() { "> " } else { "&gt; " })?;
941939
}
942940
Ok(())
@@ -1027,12 +1025,12 @@ fn fmt_type(
10271025
primitive_link(
10281026
f,
10291027
PrimitiveType::Tuple,
1030-
format_args!("({})", generic_names.iter().format(", ")),
1028+
format_args!("({})", (|| generic_names.iter()).join(", ")),
10311029
cx,
10321030
)
10331031
} else {
10341032
f.write_str("(")?;
1035-
many.iter().map(|item| item.print(cx)).format(", ").fmt(f)?;
1033+
(|| many.iter().map(|item| item.print(cx))).join(", ").fmt(f)?;
10361034
f.write_str(")")
10371035
}
10381036
}
@@ -1362,16 +1360,16 @@ impl clean::Arguments {
13621360
cx: &'a Context<'tcx>,
13631361
) -> impl Display + 'a + Captures<'tcx> {
13641362
fmt::from_fn(move |f| {
1365-
self.values
1366-
.iter()
1367-
.map(|input| {
1363+
(|| {
1364+
self.values.iter().map(|input| {
13681365
fmt::from_fn(|f| {
13691366
write!(f, "{}: ", input.name)?;
13701367
input.type_.print(cx).fmt(f)
13711368
})
13721369
})
1373-
.format(", ")
1374-
.fmt(f)
1370+
})
1371+
.join(", ")
1372+
.fmt(f)
13751373
})
13761374
}
13771375
}

src/librustdoc/html/render/print_item.rs

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ use crate::html::format::{
3737
use crate::html::markdown::{HeadingOffset, MarkdownSummaryLine};
3838
use crate::html::render::{document_full, document_item_info};
3939
use crate::html::url_parts_builder::UrlPartsBuilder;
40+
use crate::join::Join as _;
4041

4142
/// Generates a Rinja template struct for rendering items with common methods.
4243
///
@@ -1432,16 +1433,17 @@ fn print_tuple_struct_fields<'a, 'cx: 'a>(
14321433
return f.write_str("<span class=\"comment\">/* private fields */</span>");
14331434
}
14341435

1435-
s.iter()
1436-
.map(|ty| {
1436+
(|| {
1437+
s.iter().map(|ty| {
14371438
fmt::from_fn(|f| match ty.kind {
14381439
clean::StrippedItem(box clean::StructFieldItem(_)) => f.write_str("_"),
14391440
clean::StructFieldItem(ref ty) => write!(f, "{}", ty.print(cx)),
14401441
_ => unreachable!(),
14411442
})
14421443
})
1443-
.format(", ")
1444-
.fmt(f)
1444+
})
1445+
.join(", ")
1446+
.fmt(f)
14451447
})
14461448
}
14471449

@@ -2064,7 +2066,7 @@ fn bounds(t_bounds: &[clean::GenericBound], trait_alias: bool, cx: &Context<'_>)
20642066
bounds.push_str(": ");
20652067
}
20662068
}
2067-
write!(bounds, "{}", t_bounds.iter().map(|p| p.print(cx)).format(inter_str)).unwrap();
2069+
write!(bounds, "{}", (|| t_bounds.iter().map(|p| p.print(cx))).join(inter_str)).unwrap();
20682070
bounds
20692071
}
20702072

src/librustdoc/join.rs

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
use std::fmt::{self, Display};
2+
3+
pub(crate) trait Join {
4+
fn join<'f, 'sep: 'f>(self, sep: &'sep str) -> impl Display + 'f
5+
where
6+
Self: 'f;
7+
}
8+
9+
impl<F, I, T> Join for F
10+
where
11+
F: Fn() -> I,
12+
I: Iterator<Item = T>,
13+
T: Display,
14+
{
15+
fn join<'f, 'sep: 'f>(self, sep: &'sep str) -> impl Display + 'f
16+
where
17+
Self: 'f,
18+
{
19+
fmt::from_fn(move |f| {
20+
let mut iter = self();
21+
let Some(first) = iter.next() else { return Ok(()) };
22+
first.fmt(f)?;
23+
while let Some(item) = iter.next() {
24+
f.write_str(sep)?;
25+
item.fmt(f)?;
26+
}
27+
Ok(())
28+
})
29+
}
30+
}

src/librustdoc/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,7 @@ mod fold;
113113
mod formats;
114114
// used by the error-index generator, so it needs to be public
115115
pub mod html;
116+
mod join;
116117
mod json;
117118
pub(crate) mod lint;
118119
mod markdown;

0 commit comments

Comments
 (0)