Skip to content

Commit a68aff6

Browse files
authored
Rollup merge of #149208 - GuillaumeGomez:less-unwraps, r=yotamofek,lolbinarycat
[rustdoc] Make more functions return `fmt::Result` and reduce number of `.unwrap()` calls Following our discussion in #149028 (comment), this PR makes more function return `fmt::Result`, allowing to use `?` a lot more, and also reducing number of `.unwrap()` calls. r? `@lolbinarycat`
2 parents ade1581 + c524ed7 commit a68aff6

File tree

4 files changed

+78
-79
lines changed

4 files changed

+78
-79
lines changed

src/librustdoc/html/format.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1252,9 +1252,9 @@ struct Indent(usize);
12521252

12531253
impl Display for Indent {
12541254
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1255-
(0..self.0).for_each(|_| {
1256-
f.write_char(' ').unwrap();
1257-
});
1255+
for _ in 0..self.0 {
1256+
f.write_char(' ')?;
1257+
}
12581258
Ok(())
12591259
}
12601260
}

src/librustdoc/html/length_limit.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ impl HtmlWithLimit {
8787
pub(super) fn close_tag(&mut self) {
8888
if let Some(tag_name) = self.unclosed_tags.pop() {
8989
// Close the most recently opened tag.
90-
write!(self.buf, "</{tag_name}>").unwrap()
90+
write!(self.buf, "</{tag_name}>").expect("infallible string operation");
9191
}
9292
// There are valid cases where `close_tag()` is called without
9393
// there being any tags to close. For example, this occurs when
@@ -99,7 +99,7 @@ impl HtmlWithLimit {
9999
/// Write all queued tags and add them to the `unclosed_tags` list.
100100
fn flush_queue(&mut self) {
101101
for tag_name in self.queued_tags.drain(..) {
102-
write!(self.buf, "<{tag_name}>").unwrap();
102+
write!(self.buf, "<{tag_name}>").expect("infallible string operation");
103103

104104
self.unclosed_tags.push(tag_name);
105105
}

src/librustdoc/html/render/mod.rs

Lines changed: 43 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -916,7 +916,7 @@ fn render_impls(
916916
impls: &[&Impl],
917917
containing_item: &clean::Item,
918918
toggle_open_by_default: bool,
919-
) {
919+
) -> fmt::Result {
920920
let mut rendered_impls = impls
921921
.iter()
922922
.map(|i| {
@@ -942,7 +942,7 @@ fn render_impls(
942942
})
943943
.collect::<Vec<_>>();
944944
rendered_impls.sort();
945-
w.write_str(&rendered_impls.join("")).unwrap();
945+
w.write_str(&rendered_impls.join(""))
946946
}
947947

948948
/// Build a (possibly empty) `href` attribute (a key-value pair) for the given associated item.
@@ -1037,7 +1037,7 @@ fn assoc_const(
10371037
) -> impl fmt::Display {
10381038
let tcx = cx.tcx();
10391039
fmt::from_fn(move |w| {
1040-
render_attributes_in_code(w, it, &" ".repeat(indent), cx);
1040+
render_attributes_in_code(w, it, &" ".repeat(indent), cx)?;
10411041
write!(
10421042
w,
10431043
"{indent}{vis}const <a{href} class=\"constant\">{name}</a>{generics}: {ty}",
@@ -1145,10 +1145,10 @@ fn assoc_method(
11451145
let (indent, indent_str, end_newline) = if parent == ItemType::Trait {
11461146
header_len += 4;
11471147
let indent_str = " ";
1148-
render_attributes_in_code(w, meth, indent_str, cx);
1148+
render_attributes_in_code(w, meth, indent_str, cx)?;
11491149
(4, indent_str, Ending::NoNewline)
11501150
} else {
1151-
render_attributes_in_code(w, meth, "", cx);
1151+
render_attributes_in_code(w, meth, "", cx)?;
11521152
(0, "", Ending::Newline)
11531153
};
11541154
write!(
@@ -1365,42 +1365,40 @@ fn render_all_impls(
13651365
concrete: &[&Impl],
13661366
synthetic: &[&Impl],
13671367
blanket_impl: &[&Impl],
1368-
) {
1368+
) -> fmt::Result {
13691369
let impls = {
13701370
let mut buf = String::new();
1371-
render_impls(cx, &mut buf, concrete, containing_item, true);
1371+
render_impls(cx, &mut buf, concrete, containing_item, true)?;
13721372
buf
13731373
};
13741374
if !impls.is_empty() {
13751375
write!(
13761376
w,
13771377
"{}<div id=\"trait-implementations-list\">{impls}</div>",
13781378
write_impl_section_heading("Trait Implementations", "trait-implementations")
1379-
)
1380-
.unwrap();
1379+
)?;
13811380
}
13821381

13831382
if !synthetic.is_empty() {
13841383
write!(
13851384
w,
13861385
"{}<div id=\"synthetic-implementations-list\">",
13871386
write_impl_section_heading("Auto Trait Implementations", "synthetic-implementations",)
1388-
)
1389-
.unwrap();
1390-
render_impls(cx, &mut w, synthetic, containing_item, false);
1391-
w.write_str("</div>").unwrap();
1387+
)?;
1388+
render_impls(cx, &mut w, synthetic, containing_item, false)?;
1389+
w.write_str("</div>")?;
13921390
}
13931391

13941392
if !blanket_impl.is_empty() {
13951393
write!(
13961394
w,
13971395
"{}<div id=\"blanket-implementations-list\">",
13981396
write_impl_section_heading("Blanket Implementations", "blanket-implementations")
1399-
)
1400-
.unwrap();
1401-
render_impls(cx, &mut w, blanket_impl, containing_item, false);
1402-
w.write_str("</div>").unwrap();
1397+
)?;
1398+
render_impls(cx, &mut w, blanket_impl, containing_item, false)?;
1399+
w.write_str("</div>")?;
14031400
}
1401+
Ok(())
14041402
}
14051403

14061404
fn render_assoc_items(
@@ -1412,8 +1410,7 @@ fn render_assoc_items(
14121410
fmt::from_fn(move |f| {
14131411
let mut derefs = DefIdSet::default();
14141412
derefs.insert(it);
1415-
render_assoc_items_inner(f, cx, containing_item, it, what, &mut derefs);
1416-
Ok(())
1413+
render_assoc_items_inner(f, cx, containing_item, it, what, &mut derefs)
14171414
})
14181415
}
14191416

@@ -1424,10 +1421,10 @@ fn render_assoc_items_inner(
14241421
it: DefId,
14251422
what: AssocItemRender<'_>,
14261423
derefs: &mut DefIdSet,
1427-
) {
1424+
) -> fmt::Result {
14281425
info!("Documenting associated items of {:?}", containing_item.name);
14291426
let cache = &cx.shared.cache;
1430-
let Some(v) = cache.impls.get(&it) else { return };
1427+
let Some(v) = cache.impls.get(&it) else { return Ok(()) };
14311428
let (mut non_trait, traits): (Vec<_>, _) =
14321429
v.iter().partition(|i| i.inner_impl().trait_.is_none());
14331430
if !non_trait.is_empty() {
@@ -1511,8 +1508,7 @@ fn render_assoc_items_inner(
15111508
matches!(what, AssocItemRender::DerefFor { .. })
15121509
.then_some("</details>")
15131510
.maybe_display(),
1514-
)
1515-
.unwrap();
1511+
)?;
15161512
}
15171513
}
15181514

@@ -1522,22 +1518,23 @@ fn render_assoc_items_inner(
15221518
if let Some(impl_) = deref_impl {
15231519
let has_deref_mut =
15241520
traits.iter().any(|t| t.trait_did() == cx.tcx().lang_items().deref_mut_trait());
1525-
render_deref_methods(&mut w, cx, impl_, containing_item, has_deref_mut, derefs);
1521+
render_deref_methods(&mut w, cx, impl_, containing_item, has_deref_mut, derefs)?;
15261522
}
15271523

15281524
// If we were already one level into rendering deref methods, we don't want to render
15291525
// anything after recursing into any further deref methods above.
15301526
if let AssocItemRender::DerefFor { .. } = what {
1531-
return;
1527+
return Ok(());
15321528
}
15331529

15341530
let (synthetic, concrete): (Vec<&Impl>, Vec<&Impl>) =
15351531
traits.into_iter().partition(|t| t.inner_impl().kind.is_auto());
15361532
let (blanket_impl, concrete): (Vec<&Impl>, _) =
15371533
concrete.into_iter().partition(|t| t.inner_impl().kind.is_blanket());
15381534

1539-
render_all_impls(w, cx, containing_item, &concrete, &synthetic, &blanket_impl);
1535+
render_all_impls(w, cx, containing_item, &concrete, &synthetic, &blanket_impl)?;
15401536
}
1537+
Ok(())
15411538
}
15421539

15431540
/// `derefs` is the set of all deref targets that have already been handled.
@@ -1548,7 +1545,7 @@ fn render_deref_methods(
15481545
container_item: &clean::Item,
15491546
deref_mut: bool,
15501547
derefs: &mut DefIdSet,
1551-
) {
1548+
) -> fmt::Result {
15521549
let cache = cx.cache();
15531550
let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
15541551
let (target, real_target) = impl_
@@ -1574,15 +1571,16 @@ fn render_deref_methods(
15741571
// `impl Deref<Target = S> for S`
15751572
if did == type_did || !derefs.insert(did) {
15761573
// Avoid infinite cycles
1577-
return;
1574+
return Ok(());
15781575
}
15791576
}
1580-
render_assoc_items_inner(&mut w, cx, container_item, did, what, derefs);
1577+
render_assoc_items_inner(&mut w, cx, container_item, did, what, derefs)?;
15811578
} else if let Some(prim) = target.primitive_type()
15821579
&& let Some(&did) = cache.primitive_locations.get(&prim)
15831580
{
1584-
render_assoc_items_inner(&mut w, cx, container_item, did, what, derefs);
1581+
render_assoc_items_inner(&mut w, cx, container_item, did, what, derefs)?;
15851582
}
1583+
Ok(())
15861584
}
15871585

15881586
fn should_render_item(item: &clean::Item, deref_mut_: bool, tcx: TyCtxt<'_>) -> bool {
@@ -1805,8 +1803,7 @@ fn render_impl(
18051803
// because impls can't have a stability.
18061804
if !item.doc_value().is_empty() {
18071805
document_item_info(cx, it, Some(parent))
1808-
.render_into(&mut info_buffer)
1809-
.unwrap();
1806+
.render_into(&mut info_buffer)?;
18101807
doc_buffer = document_full(item, cx, HeadingOffset::H5).to_string();
18111808
short_documented = false;
18121809
} else {
@@ -1823,9 +1820,7 @@ fn render_impl(
18231820
}
18241821
}
18251822
} else {
1826-
document_item_info(cx, item, Some(parent))
1827-
.render_into(&mut info_buffer)
1828-
.unwrap();
1823+
document_item_info(cx, item, Some(parent)).render_into(&mut info_buffer)?;
18291824
if rendering_params.show_def_docs {
18301825
doc_buffer = document_full(item, cx, HeadingOffset::H5).to_string();
18311826
short_documented = false;
@@ -2920,7 +2915,7 @@ fn render_attributes_in_code(
29202915
item: &clean::Item,
29212916
prefix: &str,
29222917
cx: &Context<'_>,
2923-
) {
2918+
) -> fmt::Result {
29242919
for attr in &item.attrs.other_attrs {
29252920
let hir::Attribute::Parsed(kind) = attr else { continue };
29262921
let attr = match kind {
@@ -2934,24 +2929,30 @@ fn render_attributes_in_code(
29342929
AttributeKind::NonExhaustive(..) => Cow::Borrowed("#[non_exhaustive]"),
29352930
_ => continue,
29362931
};
2937-
render_code_attribute(prefix, attr.as_ref(), w);
2932+
render_code_attribute(prefix, attr.as_ref(), w)?;
29382933
}
29392934

29402935
if let Some(def_id) = item.def_id()
29412936
&& let Some(repr) = repr_attribute(cx.tcx(), cx.cache(), def_id)
29422937
{
2943-
render_code_attribute(prefix, &repr, w);
2938+
render_code_attribute(prefix, &repr, w)?;
29442939
}
2940+
Ok(())
29452941
}
29462942

2947-
fn render_repr_attribute_in_code(w: &mut impl fmt::Write, cx: &Context<'_>, def_id: DefId) {
2943+
fn render_repr_attribute_in_code(
2944+
w: &mut impl fmt::Write,
2945+
cx: &Context<'_>,
2946+
def_id: DefId,
2947+
) -> fmt::Result {
29482948
if let Some(repr) = repr_attribute(cx.tcx(), cx.cache(), def_id) {
2949-
render_code_attribute("", &repr, w);
2949+
render_code_attribute("", &repr, w)?;
29502950
}
2951+
Ok(())
29512952
}
29522953

2953-
fn render_code_attribute(prefix: &str, attr: &str, w: &mut impl fmt::Write) {
2954-
write!(w, "<div class=\"code-attribute\">{prefix}{attr}</div>").unwrap();
2954+
fn render_code_attribute(prefix: &str, attr: &str, w: &mut impl fmt::Write) -> fmt::Result {
2955+
write!(w, "<div class=\"code-attribute\">{prefix}{attr}</div>")
29552956
}
29562957

29572958
/// Compute the *public* `#[repr]` of the item given by `DefId`.

0 commit comments

Comments
 (0)