Skip to content

Commit 613ef74

Browse files
committed
Auto merge of rust-lang#80987 - GuillaumeGomez:remove-cache-key, r=jyn514
Remove CACHE_KEY global We realized in rust-lang#80914 that the cache handling (through a global) needed to be updated to make it much easier to handle. r? `@jyn514`
2 parents 742c972 + d78e1ed commit 613ef74

File tree

14 files changed

+791
-622
lines changed

14 files changed

+791
-622
lines changed

src/librustdoc/clean/mod.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -2329,14 +2329,14 @@ impl Clean<Item> for (&hir::MacroDef<'_>, Option<Symbol>) {
23292329
if matchers.len() <= 1 {
23302330
format!(
23312331
"{}macro {}{} {{\n ...\n}}",
2332-
vis.print_with_space(cx.tcx, def_id),
2332+
vis.print_with_space(cx.tcx, def_id, &cx.cache),
23332333
name,
23342334
matchers.iter().map(|span| span.to_src(cx)).collect::<String>(),
23352335
)
23362336
} else {
23372337
format!(
23382338
"{}macro {} {{\n{}}}",
2339-
vis.print_with_space(cx.tcx, def_id),
2339+
vis.print_with_space(cx.tcx, def_id, &cx.cache),
23402340
name,
23412341
matchers
23422342
.iter()

src/librustdoc/clean/types.rs

+63-25
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ use crate::clean::inline;
3737
use crate::clean::types::Type::{QPath, ResolvedPath};
3838
use crate::clean::Clean;
3939
use crate::core::DocContext;
40-
use crate::formats::cache::cache;
40+
use crate::formats::cache::Cache;
4141
use crate::formats::item_type::ItemType;
4242
use crate::html::render::cache::ExternalLocation;
4343

@@ -169,8 +169,8 @@ impl Item {
169169
self.attrs.collapsed_doc_value()
170170
}
171171

172-
crate fn links(&self) -> Vec<RenderedLink> {
173-
self.attrs.links(&self.def_id.krate)
172+
crate fn links(&self, cache: &Cache) -> Vec<RenderedLink> {
173+
self.attrs.links(&self.def_id.krate, cache)
174174
}
175175

176176
crate fn is_crate(&self) -> bool {
@@ -826,7 +826,7 @@ impl Attributes {
826826
/// Gets links as a vector
827827
///
828828
/// Cache must be populated before call
829-
crate fn links(&self, krate: &CrateNum) -> Vec<RenderedLink> {
829+
crate fn links(&self, krate: &CrateNum, cache: &Cache) -> Vec<RenderedLink> {
830830
use crate::html::format::href;
831831
use crate::html::render::CURRENT_DEPTH;
832832

@@ -835,7 +835,7 @@ impl Attributes {
835835
.filter_map(|ItemLink { link: s, link_text, did, fragment }| {
836836
match *did {
837837
Some(did) => {
838-
if let Some((mut href, ..)) = href(did) {
838+
if let Some((mut href, ..)) = href(did, cache) {
839839
if let Some(ref fragment) = *fragment {
840840
href.push('#');
841841
href.push_str(fragment);
@@ -851,7 +851,6 @@ impl Attributes {
851851
}
852852
None => {
853853
if let Some(ref fragment) = *fragment {
854-
let cache = cache();
855854
let url = match cache.extern_locations.get(krate) {
856855
Some(&(_, _, ExternalLocation::Local)) => {
857856
let depth = CURRENT_DEPTH.with(|l| l.get());
@@ -1177,6 +1176,13 @@ impl GetDefId for FnRetTy {
11771176
DefaultReturn => None,
11781177
}
11791178
}
1179+
1180+
fn def_id_full(&self, cache: &Cache) -> Option<DefId> {
1181+
match *self {
1182+
Return(ref ty) => ty.def_id_full(cache),
1183+
DefaultReturn => None,
1184+
}
1185+
}
11801186
}
11811187

11821188
#[derive(Clone, Debug)]
@@ -1299,13 +1305,31 @@ crate enum TypeKind {
12991305
}
13001306

13011307
crate trait GetDefId {
1308+
/// Use this method to get the [`DefId`] of a [`clean`] AST node.
1309+
/// This will return [`None`] when called on a primitive [`clean::Type`].
1310+
/// Use [`Self::def_id_full`] if you want to include primitives.
1311+
///
1312+
/// [`clean`]: crate::clean
1313+
/// [`clean::Type`]: crate::clean::Type
1314+
// FIXME: get rid of this function and always use `def_id_full`
13021315
fn def_id(&self) -> Option<DefId>;
1316+
1317+
/// Use this method to get the [DefId] of a [clean] AST node, including [PrimitiveType]s.
1318+
///
1319+
/// See [`Self::def_id`] for more.
1320+
///
1321+
/// [clean]: crate::clean
1322+
fn def_id_full(&self, cache: &Cache) -> Option<DefId>;
13031323
}
13041324

13051325
impl<T: GetDefId> GetDefId for Option<T> {
13061326
fn def_id(&self) -> Option<DefId> {
13071327
self.as_ref().and_then(|d| d.def_id())
13081328
}
1329+
1330+
fn def_id_full(&self, cache: &Cache) -> Option<DefId> {
1331+
self.as_ref().and_then(|d| d.def_id_full(cache))
1332+
}
13091333
}
13101334

13111335
impl Type {
@@ -1393,30 +1417,40 @@ impl Type {
13931417
}
13941418
}
13951419

1396-
impl GetDefId for Type {
1397-
fn def_id(&self) -> Option<DefId> {
1398-
match *self {
1399-
ResolvedPath { did, .. } => Some(did),
1400-
Primitive(p) => cache().primitive_locations.get(&p).cloned(),
1401-
BorrowedRef { type_: box Generic(..), .. } => {
1402-
Primitive(PrimitiveType::Reference).def_id()
1403-
}
1404-
BorrowedRef { ref type_, .. } => type_.def_id(),
1420+
impl Type {
1421+
fn inner_def_id(&self, cache: Option<&Cache>) -> Option<DefId> {
1422+
let t: PrimitiveType = match *self {
1423+
ResolvedPath { did, .. } => return Some(did),
1424+
Primitive(p) => return cache.and_then(|c| c.primitive_locations.get(&p).cloned()),
1425+
BorrowedRef { type_: box Generic(..), .. } => PrimitiveType::Reference,
1426+
BorrowedRef { ref type_, .. } => return type_.inner_def_id(cache),
14051427
Tuple(ref tys) => {
14061428
if tys.is_empty() {
1407-
Primitive(PrimitiveType::Unit).def_id()
1429+
PrimitiveType::Unit
14081430
} else {
1409-
Primitive(PrimitiveType::Tuple).def_id()
1431+
PrimitiveType::Tuple
14101432
}
14111433
}
1412-
BareFunction(..) => Primitive(PrimitiveType::Fn).def_id(),
1413-
Never => Primitive(PrimitiveType::Never).def_id(),
1414-
Slice(..) => Primitive(PrimitiveType::Slice).def_id(),
1415-
Array(..) => Primitive(PrimitiveType::Array).def_id(),
1416-
RawPointer(..) => Primitive(PrimitiveType::RawPointer).def_id(),
1417-
QPath { ref self_type, .. } => self_type.def_id(),
1418-
_ => None,
1419-
}
1434+
BareFunction(..) => PrimitiveType::Fn,
1435+
Never => PrimitiveType::Never,
1436+
Slice(..) => PrimitiveType::Slice,
1437+
Array(..) => PrimitiveType::Array,
1438+
RawPointer(..) => PrimitiveType::RawPointer,
1439+
QPath { ref self_type, .. } => return self_type.inner_def_id(cache),
1440+
// FIXME: remove this wildcard
1441+
_ => return None,
1442+
};
1443+
cache.and_then(|c| Primitive(t).def_id_full(c))
1444+
}
1445+
}
1446+
1447+
impl GetDefId for Type {
1448+
fn def_id(&self) -> Option<DefId> {
1449+
self.inner_def_id(None)
1450+
}
1451+
1452+
fn def_id_full(&self, cache: &Cache) -> Option<DefId> {
1453+
self.inner_def_id(Some(cache))
14201454
}
14211455
}
14221456

@@ -1817,6 +1851,10 @@ impl GetDefId for Typedef {
18171851
fn def_id(&self) -> Option<DefId> {
18181852
self.type_.def_id()
18191853
}
1854+
1855+
fn def_id_full(&self, cache: &Cache) -> Option<DefId> {
1856+
self.type_.def_id_full(cache)
1857+
}
18201858
}
18211859

18221860
#[derive(Clone, Debug)]

src/librustdoc/clean/utils.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -177,7 +177,7 @@ crate fn get_real_types(
177177
return res;
178178
}
179179
if arg.is_full_generic() {
180-
let arg_s = Symbol::intern(&arg.print().to_string());
180+
let arg_s = Symbol::intern(&arg.print(&cx.cache).to_string());
181181
if let Some(where_pred) = generics.where_predicates.iter().find(|g| match g {
182182
WherePredicate::BoundPredicate { ty, .. } => ty.def_id() == arg.def_id(),
183183
_ => false,
@@ -473,7 +473,7 @@ crate fn resolve_type(cx: &DocContext<'_>, path: Path, id: hir::HirId) -> Type {
473473
return Generic(kw::SelfUpper);
474474
}
475475
Res::Def(DefKind::TyParam, _) if path.segments.len() == 1 => {
476-
return Generic(Symbol::intern(&format!("{:#}", path.print())));
476+
return Generic(Symbol::intern(&format!("{:#}", path.print(&cx.cache))));
477477
}
478478
Res::SelfTy(..) | Res::Def(DefKind::TyParam | DefKind::AssocTy, _) => true,
479479
_ => false,

src/librustdoc/config.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -261,7 +261,7 @@ crate struct RenderOptions {
261261
}
262262

263263
/// Temporary storage for data obtained during `RustdocVisitor::clean()`.
264-
/// Later on moved into `CACHE_KEY`.
264+
/// Later on moved into `cache`.
265265
#[derive(Default, Clone)]
266266
crate struct RenderInfo {
267267
crate inlined: FxHashSet<DefId>,

src/librustdoc/core.rs

+6-2
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ use crate::clean;
3232
use crate::clean::{AttributesExt, MAX_DEF_ID};
3333
use crate::config::{Options as RustdocOptions, RenderOptions};
3434
use crate::config::{OutputFormat, RenderInfo};
35+
use crate::formats::cache::Cache;
3536
use crate::passes::{self, Condition::*, ConditionalPass};
3637

3738
crate use rustc_session::config::{DebuggingOptions, Input, Options};
@@ -45,9 +46,9 @@ crate struct DocContext<'tcx> {
4546
///
4647
/// Most of this logic is copied from rustc_lint::late.
4748
crate param_env: Cell<ParamEnv<'tcx>>,
48-
/// Later on moved into `CACHE_KEY`
49+
/// Later on moved into `cache`
4950
crate renderinfo: RefCell<RenderInfo>,
50-
/// Later on moved through `clean::Crate` into `CACHE_KEY`
51+
/// Later on moved through `clean::Crate` into `cache`
5152
crate external_traits: Rc<RefCell<FxHashMap<DefId, clean::Trait>>>,
5253
/// Used while populating `external_traits` to ensure we don't process the same trait twice at
5354
/// the same time.
@@ -75,6 +76,8 @@ crate struct DocContext<'tcx> {
7576
/// See `collect_intra_doc_links::traits_implemented_by` for more details.
7677
/// `map<module, set<trait>>`
7778
crate module_trait_cache: RefCell<FxHashMap<DefId, FxHashSet<DefId>>>,
79+
/// Fake empty cache used when cache is required as parameter.
80+
crate cache: Cache,
7881
}
7982

8083
impl<'tcx> DocContext<'tcx> {
@@ -524,6 +527,7 @@ crate fn run_global_ctxt(
524527
.collect(),
525528
render_options,
526529
module_trait_cache: RefCell::new(FxHashMap::default()),
530+
cache: Cache::default(),
527531
};
528532
debug!("crate: {:?}", tcx.hir().krate());
529533

src/librustdoc/formats/cache.rs

+2-9
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
1-
use std::cell::RefCell;
21
use std::collections::BTreeMap;
32
use std::mem;
43
use std::path::{Path, PathBuf};
5-
use std::sync::Arc;
64

75
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
86
use rustc_hir::def_id::{CrateNum, DefId, CRATE_DEF_INDEX};
@@ -19,8 +17,6 @@ use crate::html::markdown::short_markdown_summary;
1917
use crate::html::render::cache::{extern_location, get_index_search_type, ExternalLocation};
2018
use crate::html::render::IndexItem;
2119

22-
thread_local!(crate static CACHE_KEY: RefCell<Arc<Cache>> = Default::default());
23-
2420
/// This cache is used to store information about the [`clean::Crate`] being
2521
/// rendered in order to provide more useful documentation. This contains
2622
/// information like all implementors of a trait, all traits a type implements,
@@ -197,6 +193,7 @@ impl Cache {
197193
}
198194

199195
cache.stack.push(krate.name.to_string());
196+
200197
krate = cache.fold_crate(krate);
201198

202199
for (trait_did, dids, impl_) in cache.orphan_trait_impls.drain(..) {
@@ -319,7 +316,7 @@ impl DocFolder for Cache {
319316
.map_or_else(String::new, |x| short_markdown_summary(&x.as_str())),
320317
parent,
321318
parent_idx: None,
322-
search_type: get_index_search_type(&item),
319+
search_type: get_index_search_type(&item, None),
323320
});
324321

325322
for alias in item.attrs.get_doc_aliases() {
@@ -477,7 +474,3 @@ impl DocFolder for Cache {
477474
ret
478475
}
479476
}
480-
481-
crate fn cache() -> Arc<Cache> {
482-
CACHE_KEY.with(|c| c.borrow().clone())
483-
}

src/librustdoc/formats/mod.rs

+5
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ use rustc_span::def_id::DefId;
88

99
use crate::clean;
1010
use crate::clean::types::GetDefId;
11+
use crate::formats::cache::Cache;
1112

1213
/// Specifies whether rendering directly implemented trait items or ones from a certain Deref
1314
/// impl.
@@ -41,4 +42,8 @@ impl Impl {
4142
crate fn trait_did(&self) -> Option<DefId> {
4243
self.inner_impl().trait_.def_id()
4344
}
45+
46+
crate fn trait_did_full(&self, cache: &Cache) -> Option<DefId> {
47+
self.inner_impl().trait_.def_id_full(cache)
48+
}
4449
}

src/librustdoc/formats/renderer.rs

+11-22
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,10 @@
1-
use std::sync::Arc;
2-
31
use rustc_middle::ty::TyCtxt;
42
use rustc_span::edition::Edition;
53

64
use crate::clean;
75
use crate::config::{RenderInfo, RenderOptions};
86
use crate::error::Error;
9-
use crate::formats::cache::{Cache, CACHE_KEY};
7+
use crate::formats::cache::Cache;
108

119
/// Allows for different backends to rustdoc to be used with the `run_format()` function. Each
1210
/// backend renderer has hooks for initialization, documenting an item, entering and exiting a
@@ -22,20 +20,15 @@ crate trait FormatRenderer<'tcx>: Clone {
2220
options: RenderOptions,
2321
render_info: RenderInfo,
2422
edition: Edition,
25-
cache: &mut Cache,
23+
cache: Cache,
2624
tcx: TyCtxt<'tcx>,
2725
) -> Result<(Self, clean::Crate), Error>;
2826

2927
/// Renders a single non-module item. This means no recursive sub-item rendering is required.
30-
fn item(&mut self, item: clean::Item, cache: &Cache) -> Result<(), Error>;
28+
fn item(&mut self, item: clean::Item) -> Result<(), Error>;
3129

3230
/// Renders a module (should not handle recursing into children).
33-
fn mod_item_in(
34-
&mut self,
35-
item: &clean::Item,
36-
item_name: &str,
37-
cache: &Cache,
38-
) -> Result<(), Error>;
31+
fn mod_item_in(&mut self, item: &clean::Item, item_name: &str) -> Result<(), Error>;
3932

4033
/// Runs after recursively rendering all sub-items of a module.
4134
fn mod_item_out(&mut self, item_name: &str) -> Result<(), Error>;
@@ -46,9 +39,10 @@ crate trait FormatRenderer<'tcx>: Clone {
4639
fn after_krate(
4740
&mut self,
4841
krate: &clean::Crate,
49-
cache: &Cache,
5042
diag: &rustc_errors::Handler,
5143
) -> Result<(), Error>;
44+
45+
fn cache(&self) -> &Cache;
5246
}
5347

5448
/// Main method for rendering a crate.
@@ -60,7 +54,7 @@ crate fn run_format<'tcx, T: FormatRenderer<'tcx>>(
6054
edition: Edition,
6155
tcx: TyCtxt<'tcx>,
6256
) -> Result<(), Error> {
63-
let (krate, mut cache) = tcx.sess.time("create_format_cache", || {
57+
let (krate, cache) = tcx.sess.time("create_format_cache", || {
6458
Cache::from_krate(
6559
render_info.clone(),
6660
options.document_private,
@@ -73,12 +67,7 @@ crate fn run_format<'tcx, T: FormatRenderer<'tcx>>(
7367

7468
let (mut format_renderer, mut krate) = prof
7569
.extra_verbose_generic_activity("create_renderer", T::descr())
76-
.run(|| T::init(krate, options, render_info, edition, &mut cache, tcx))?;
77-
78-
let cache = Arc::new(cache);
79-
// Freeze the cache now that the index has been built. Put an Arc into TLS for future
80-
// parallelization opportunities
81-
CACHE_KEY.with(|v| *v.borrow_mut() = cache.clone());
70+
.run(|| T::init(krate, options, render_info, edition, cache, tcx))?;
8271

8372
let mut item = match krate.module.take() {
8473
Some(i) => i,
@@ -101,7 +90,7 @@ crate fn run_format<'tcx, T: FormatRenderer<'tcx>>(
10190
}
10291
let _timer = prof.generic_activity_with_arg("render_mod_item", name.as_str());
10392

104-
cx.mod_item_in(&item, &name, &cache)?;
93+
cx.mod_item_in(&item, &name)?;
10594
let module = match *item.kind {
10695
clean::StrippedItem(box clean::ModuleItem(m)) | clean::ModuleItem(m) => m,
10796
_ => unreachable!(),
@@ -114,9 +103,9 @@ crate fn run_format<'tcx, T: FormatRenderer<'tcx>>(
114103
cx.mod_item_out(&name)?;
115104
} else if item.name.is_some() {
116105
prof.generic_activity_with_arg("render_item", &*item.name.unwrap_or(unknown).as_str())
117-
.run(|| cx.item(item, &cache))?;
106+
.run(|| cx.item(item))?;
118107
}
119108
}
120109
prof.extra_verbose_generic_activity("renderer_after_krate", T::descr())
121-
.run(|| format_renderer.after_krate(&krate, &cache, diag))
110+
.run(|| format_renderer.after_krate(&krate, diag))
122111
}

0 commit comments

Comments
 (0)