Skip to content
This repository was archived by the owner on May 28, 2025. It is now read-only.

Commit 9763eb8

Browse files
committed
rustdoc: Move most shared fields to SharedContext
...and remove `Rc`s for the moved fields. The only shared one that I didn't move was `cache`; see the doc-comment I added to `cache` for details.
1 parent 8fd946c commit 9763eb8

File tree

2 files changed

+48
-37
lines changed

2 files changed

+48
-37
lines changed

src/librustdoc/html/render/context.rs

Lines changed: 26 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,11 @@ use std::collections::BTreeMap;
33
use std::io;
44
use std::path::PathBuf;
55
use std::rc::Rc;
6-
use std::sync::mpsc::{channel, Receiver};
6+
use std::sync::mpsc::channel;
77
use std::sync::Arc;
88

99
use rustc_data_structures::fx::FxHashMap;
10-
use rustc_hir::def_id::{DefId, LOCAL_CRATE};
10+
use rustc_hir::def_id::LOCAL_CRATE;
1111
use rustc_middle::ty::TyCtxt;
1212
use rustc_session::Session;
1313
use rustc_span::edition::Edition;
@@ -31,7 +31,7 @@ use crate::formats::item_type::ItemType;
3131
use crate::formats::FormatRenderer;
3232
use crate::html::escape::Escape;
3333
use crate::html::format::Buffer;
34-
use crate::html::markdown::{self, plain_text_summary, ErrorCodes, IdMap};
34+
use crate::html::markdown::{self, plain_text_summary, ErrorCodes};
3535
use crate::html::{layout, sources};
3636

3737
/// Major driving force in all rustdoc rendering. This contains information
@@ -53,20 +53,16 @@ crate struct Context<'tcx> {
5353
/// real location of an item. This is used to allow external links to
5454
/// publicly reused items to redirect to the right location.
5555
crate render_redirect_pages: bool,
56-
/// `None` by default, depends on the `generate-redirect-map` option flag. If this field is set
57-
/// to `Some(...)`, it'll store redirections and then generate a JSON file at the top level of
58-
/// the crate.
59-
crate redirections: Option<Rc<RefCell<FxHashMap<String, String>>>>,
60-
/// The map used to ensure all generated 'id=' attributes are unique.
61-
pub(super) id_map: Rc<RefCell<IdMap>>,
62-
/// Tracks section IDs for `Deref` targets so they match in both the main
63-
/// body and the sidebar.
64-
pub(super) deref_id_map: Rc<RefCell<FxHashMap<DefId, String>>>,
6556
crate shared: Arc<SharedContext<'tcx>>,
66-
all: Rc<RefCell<AllTypes>>,
67-
/// Storage for the errors produced while generating documentation so they
68-
/// can be printed together at the end.
69-
crate errors: Rc<Receiver<String>>,
57+
/// The [`Cache`] used during rendering.
58+
///
59+
/// Ideally the cache would be in [`SharedContext`], but it's mutated
60+
/// between when the `SharedContext` is created and when `Context`
61+
/// is created, so more refactoring would be needed.
62+
///
63+
/// It's immutable once in `Context`, so it's not as bad that it's not in
64+
/// `SharedContext`.
65+
// FIXME: move `cache` to `SharedContext`
7066
crate cache: Rc<Cache>,
7167
}
7268

@@ -91,7 +87,7 @@ impl<'tcx> Context<'tcx> {
9187
}
9288

9389
pub(super) fn derive_id(&self, id: String) -> String {
94-
let mut map = self.id_map.borrow_mut();
90+
let mut map = self.shared.id_map.borrow_mut();
9591
map.derive(id)
9692
}
9793

@@ -149,8 +145,8 @@ impl<'tcx> Context<'tcx> {
149145
};
150146

151147
{
152-
self.id_map.borrow_mut().reset();
153-
self.id_map.borrow_mut().populate(&INITIAL_IDS);
148+
self.shared.id_map.borrow_mut().reset();
149+
self.shared.id_map.borrow_mut().populate(&INITIAL_IDS);
154150
}
155151

156152
if !self.render_redirect_pages {
@@ -169,7 +165,7 @@ impl<'tcx> Context<'tcx> {
169165
path.push('/');
170166
}
171167
path.push_str(&item_path(ty, names.last().unwrap()));
172-
match self.redirections {
168+
match self.shared.redirections {
173169
Some(ref redirections) => {
174170
let mut current_path = String::new();
175171
for name in &self.current {
@@ -383,6 +379,11 @@ impl<'tcx> FormatRenderer<'tcx> for Context<'tcx> {
383379
edition,
384380
codes: ErrorCodes::from(unstable_features.is_nightly_build()),
385381
playground,
382+
id_map: RefCell::new(id_map),
383+
deref_id_map: RefCell::new(FxHashMap::default()),
384+
all: RefCell::new(AllTypes::new()),
385+
errors: receiver,
386+
redirections: if generate_redirect_map { Some(Default::default()) } else { None },
386387
};
387388

388389
// Add the default themes to the `Vec` of stylepaths
@@ -409,13 +410,8 @@ impl<'tcx> FormatRenderer<'tcx> for Context<'tcx> {
409410
current: Vec::new(),
410411
dst,
411412
render_redirect_pages: false,
412-
id_map: Rc::new(RefCell::new(id_map)),
413-
deref_id_map: Rc::new(RefCell::new(FxHashMap::default())),
414413
shared: Arc::new(scx),
415-
all: Rc::new(RefCell::new(AllTypes::new())),
416-
errors: Rc::new(receiver),
417414
cache: Rc::new(cache),
418-
redirections: if generate_redirect_map { Some(Default::default()) } else { None },
419415
};
420416

421417
CURRENT_DEPTH.with(|s| s.set(0));
@@ -464,7 +460,7 @@ impl<'tcx> FormatRenderer<'tcx> for Context<'tcx> {
464460
} else {
465461
String::new()
466462
};
467-
let all = self.all.replace(AllTypes::new());
463+
let all = self.shared.all.replace(AllTypes::new());
468464
let v = layout::render(
469465
&self.shared.layout,
470466
&page,
@@ -494,7 +490,7 @@ impl<'tcx> FormatRenderer<'tcx> for Context<'tcx> {
494490
&style_files,
495491
);
496492
self.shared.fs.write(&settings_file, v.as_bytes())?;
497-
if let Some(redirections) = self.redirections.take() {
493+
if let Some(ref redirections) = self.shared.redirections {
498494
if !redirections.borrow().is_empty() {
499495
let redirect_map_path =
500496
self.dst.join(&*krate.name.as_str()).join("redirect-map.json");
@@ -506,7 +502,7 @@ impl<'tcx> FormatRenderer<'tcx> for Context<'tcx> {
506502

507503
// Flush pending errors.
508504
Arc::get_mut(&mut self.shared).unwrap().fs.close();
509-
let nb_errors = self.errors.iter().map(|err| diag.struct_err(&err).emit()).count();
505+
let nb_errors = self.shared.errors.iter().map(|err| diag.struct_err(&err).emit()).count();
510506
if nb_errors > 0 {
511507
Err(Error::new(io::Error::new(io::ErrorKind::Other, "I/O error"), ""))
512508
} else {
@@ -585,13 +581,13 @@ impl<'tcx> FormatRenderer<'tcx> for Context<'tcx> {
585581
self.shared.fs.write(&joint_dst, buf.as_bytes())?;
586582

587583
if !self.render_redirect_pages {
588-
self.all.borrow_mut().append(full_path(self, &item), &item_type);
584+
self.shared.all.borrow_mut().append(full_path(self, &item), &item_type);
589585
}
590586
// If the item is a macro, redirect from the old macro URL (with !)
591587
// to the new one (without).
592588
if item_type == ItemType::Macro {
593589
let redir_name = format!("{}.{}!.html", item_type, name);
594-
if let Some(ref redirections) = self.redirections {
590+
if let Some(ref redirections) = self.shared.redirections {
595591
let crate_name = &self.shared.layout.krate;
596592
redirections.borrow_mut().insert(
597593
format!("{}/{}", crate_name, redir_name),

src/librustdoc/html/render/mod.rs

Lines changed: 22 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ use std::fmt;
4141
use std::path::{Path, PathBuf};
4242
use std::str;
4343
use std::string::ToString;
44+
use std::sync::mpsc::Receiver;
4445

4546
use itertools::Itertools;
4647
use rustc_ast_pretty::pprust;
@@ -69,7 +70,7 @@ use crate::html::format::{
6970
PrintWithSpace, WhereClause,
7071
};
7172
use crate::html::layout;
72-
use crate::html::markdown::{self, ErrorCodes, Markdown, MarkdownHtml, MarkdownSummaryLine};
73+
use crate::html::markdown::{self, ErrorCodes, IdMap, Markdown, MarkdownHtml, MarkdownSummaryLine};
7374

7475
/// A pair of name and its optional document.
7576
crate type NameDoc = (String, Option<String>);
@@ -119,6 +120,19 @@ crate struct SharedContext<'tcx> {
119120
crate edition: Edition,
120121
crate codes: ErrorCodes,
121122
playground: Option<markdown::Playground>,
123+
/// The map used to ensure all generated 'id=' attributes are unique.
124+
id_map: RefCell<IdMap>,
125+
/// Tracks section IDs for `Deref` targets so they match in both the main
126+
/// body and the sidebar.
127+
deref_id_map: RefCell<FxHashMap<DefId, String>>,
128+
all: RefCell<AllTypes>,
129+
/// Storage for the errors produced while generating documentation so they
130+
/// can be printed together at the end.
131+
crate errors: Receiver<String>,
132+
/// `None` by default, depends on the `generate-redirect-map` option flag. If this field is set
133+
/// to `Some(...)`, it'll store redirections and then generate a JSON file at the top level of
134+
/// the crate.
135+
crate redirections: Option<RefCell<FxHashMap<String, String>>>,
122136
}
123137

124138
impl SharedContext<'_> {
@@ -635,7 +649,7 @@ fn render_markdown(
635649
prefix: &str,
636650
is_hidden: bool,
637651
) {
638-
let mut ids = cx.id_map.borrow_mut();
652+
let mut ids = cx.shared.id_map.borrow_mut();
639653
write!(
640654
w,
641655
"<div class=\"docblock{}\">{}{}</div>",
@@ -795,7 +809,7 @@ fn short_item_info(
795809

796810
if let Some(note) = note {
797811
let note = note.as_str();
798-
let mut ids = cx.id_map.borrow_mut();
812+
let mut ids = cx.shared.id_map.borrow_mut();
799813
let html = MarkdownHtml(
800814
&note,
801815
&mut ids,
@@ -834,7 +848,7 @@ fn short_item_info(
834848
message.push_str(&format!(" ({})", feature));
835849

836850
if let Some(unstable_reason) = reason {
837-
let mut ids = cx.id_map.borrow_mut();
851+
let mut ids = cx.shared.id_map.borrow_mut();
838852
message = format!(
839853
"<details><summary>{}</summary>{}</details>",
840854
message,
@@ -1174,7 +1188,8 @@ fn render_assoc_items(
11741188
type_.print(cx.cache())
11751189
)));
11761190
debug!("Adding {} to deref id map", type_.print(cx.cache()));
1177-
cx.deref_id_map
1191+
cx.shared
1192+
.deref_id_map
11781193
.borrow_mut()
11791194
.insert(type_.def_id_full(cx.cache()).unwrap(), id.clone());
11801195
write!(
@@ -1481,7 +1496,7 @@ fn render_impl(
14811496
}
14821497

14831498
if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
1484-
let mut ids = cx.id_map.borrow_mut();
1499+
let mut ids = cx.shared.id_map.borrow_mut();
14851500
write!(
14861501
w,
14871502
"<div class=\"docblock\">{}</div>",
@@ -2030,7 +2045,7 @@ fn sidebar_deref_methods(cx: &Context<'_>, out: &mut Buffer, impl_: &Impl, v: &V
20302045
.flat_map(|i| get_methods(i.inner_impl(), true, &mut used_links, deref_mut, c))
20312046
.collect::<Vec<_>>();
20322047
if !ret.is_empty() {
2033-
let deref_id_map = cx.deref_id_map.borrow();
2048+
let deref_id_map = cx.shared.deref_id_map.borrow();
20342049
let id = deref_id_map
20352050
.get(&real_target.def_id_full(cx.cache()).unwrap())
20362051
.expect("Deref section without derived id");

0 commit comments

Comments
 (0)