Skip to content

Commit a8b49ff

Browse files
committedMay 8, 2021
Minimize amount of fake DefIds used in rustdoc
1 parent e5f83d2 commit a8b49ff

File tree

12 files changed

+55
-90
lines changed

12 files changed

+55
-90
lines changed
 

‎src/librustdoc/clean/mod.rs

+4-12
Original file line numberDiff line numberDiff line change
@@ -533,8 +533,7 @@ impl Clean<Generics> for hir::Generics<'_> {
533533
match param.kind {
534534
GenericParamDefKind::Lifetime => unreachable!(),
535535
GenericParamDefKind::Type { did, ref bounds, .. } => {
536-
cx.impl_trait_bounds
537-
.insert(FakeDefId::new_real(did).into(), bounds.clone());
536+
cx.impl_trait_bounds.insert(did.into(), bounds.clone());
538537
}
539538
GenericParamDefKind::Const { .. } => unreachable!(),
540539
}
@@ -615,7 +614,7 @@ impl<'a, 'tcx> Clean<Generics> for (&'a ty::Generics, ty::GenericPredicates<'tcx
615614
.collect::<Vec<GenericParamDef>>();
616615

617616
// param index -> [(DefId of trait, associated type name, type)]
618-
let mut impl_trait_proj = FxHashMap::<u32, Vec<(FakeDefId, Symbol, Ty<'tcx>)>>::default();
617+
let mut impl_trait_proj = FxHashMap::<u32, Vec<(DefId, Symbol, Ty<'tcx>)>>::default();
619618

620619
let where_predicates = preds
621620
.predicates
@@ -687,13 +686,7 @@ impl<'a, 'tcx> Clean<Generics> for (&'a ty::Generics, ty::GenericPredicates<'tcx
687686
if let Some(proj) = impl_trait_proj.remove(&idx) {
688687
for (trait_did, name, rhs) in proj {
689688
let rhs = rhs.clean(cx);
690-
simplify::merge_bounds(
691-
cx,
692-
&mut bounds,
693-
trait_did.expect_real(),
694-
name,
695-
&rhs,
696-
);
689+
simplify::merge_bounds(cx, &mut bounds, trait_did, name, &rhs);
697690
}
698691
}
699692
} else {
@@ -1183,8 +1176,7 @@ fn clean_qpath(hir_ty: &hir::Ty<'_>, cx: &mut DocContext<'_>) -> Type {
11831176
if let Some(new_ty) = cx.ty_substs.get(&did).cloned() {
11841177
return new_ty;
11851178
}
1186-
if let Some(bounds) = cx.impl_trait_bounds.remove(&FakeDefId::new_real(did).into())
1187-
{
1179+
if let Some(bounds) = cx.impl_trait_bounds.remove(&did.into()) {
11881180
return ImplTrait(bounds);
11891181
}
11901182
}

‎src/librustdoc/clean/types.rs

+2-6
Original file line numberDiff line numberDiff line change
@@ -73,10 +73,6 @@ impl FakeDefId {
7373
Self::Fake(DefIndex::from(id), krate)
7474
}
7575

76-
crate fn new_real(id: DefId) -> Self {
77-
Self::Real(id)
78-
}
79-
8076
#[inline]
8177
crate fn is_local(self) -> bool {
8278
match self {
@@ -485,7 +481,7 @@ impl Item {
485481
.filter_map(|ItemLink { link: s, link_text, did, ref fragment }| {
486482
match did {
487483
Some(did) => {
488-
if let Some((mut href, ..)) = href(did.expect_real(), cx) {
484+
if let Some((mut href, ..)) = href(did.clone(), cx) {
489485
if let Some(ref fragment) = *fragment {
490486
href.push('#');
491487
href.push_str(fragment);
@@ -976,7 +972,7 @@ crate struct ItemLink {
976972
/// This may not be the same as `link` if there was a disambiguator
977973
/// in an intra-doc link (e.g. \[`fn@f`\])
978974
pub(crate) link_text: String,
979-
pub(crate) did: Option<FakeDefId>,
975+
pub(crate) did: Option<DefId>,
980976
/// The url fragment to append to the link
981977
pub(crate) fragment: Option<String>,
982978
}

‎src/librustdoc/core.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -583,12 +583,12 @@ impl<'tcx> Visitor<'tcx> for EmitIgnoredResolutionErrors<'tcx> {
583583
/// for `impl Trait` in argument position.
584584
#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
585585
crate enum ImplTraitParam {
586-
DefId(FakeDefId),
586+
DefId(DefId),
587587
ParamIndex(u32),
588588
}
589589

590-
impl From<FakeDefId> for ImplTraitParam {
591-
fn from(did: FakeDefId) -> Self {
590+
impl From<DefId> for ImplTraitParam {
591+
fn from(did: DefId) -> Self {
592592
ImplTraitParam::DefId(did)
593593
}
594594
}

‎src/librustdoc/formats/cache.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ crate struct Cache {
6767
/// When rendering traits, it's often useful to be able to list all
6868
/// implementors of the trait, and this mapping is exactly, that: a mapping
6969
/// of trait ids to the list of known implementors of the trait
70-
crate implementors: FxHashMap<FakeDefId, Vec<Impl>>,
70+
crate implementors: FxHashMap<DefId, Vec<Impl>>,
7171

7272
/// Cache of where external crate documentation can be found.
7373
crate extern_locations: FxHashMap<CrateNum, ExternalLocation>,
@@ -299,7 +299,7 @@ impl<'a, 'tcx> DocFolder for CacheBuilder<'a, 'tcx> {
299299
desc: item
300300
.doc_value()
301301
.map_or_else(String::new, |x| short_markdown_summary(&x.as_str())),
302-
parent: parent.map(FakeDefId::new_real),
302+
parent,
303303
parent_idx: None,
304304
search_type: get_index_search_type(&item, &self.empty_cache, self.tcx),
305305
aliases: item.attrs.get_doc_aliases(),

‎src/librustdoc/html/render/cache.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use serde::ser::{Serialize, SerializeStruct, Serializer};
77

88
use crate::clean;
99
use crate::clean::types::{
10-
FakeDefId, FnDecl, FnRetTy, GenericBound, Generics, GetDefId, Type, WherePredicate,
10+
FnDecl, FnRetTy, GenericBound, Generics, GetDefId, Type, WherePredicate,
1111
};
1212
use crate::formats::cache::Cache;
1313
use crate::formats::item_type::ItemType;
@@ -82,7 +82,7 @@ crate fn build_index<'tcx>(krate: &clean::Crate, cache: &mut Cache, tcx: TyCtxt<
8282
defid_to_pathid.insert(defid, pathid);
8383
lastpathid += 1;
8484

85-
if let Some(&(ref fqp, short)) = paths.get(&defid.expect_real()) {
85+
if let Some(&(ref fqp, short)) = paths.get(&defid) {
8686
crate_paths.push((short, fqp.last().unwrap().clone()));
8787
Some(pathid)
8888
} else {
@@ -214,7 +214,7 @@ crate fn get_index_search_type<'tcx>(
214214

215215
fn get_index_type(clean_type: &clean::Type, cache: &Cache) -> RenderType {
216216
RenderType {
217-
ty: clean_type.def_id_full(cache).map(FakeDefId::new_real),
217+
ty: clean_type.def_id_full(cache),
218218
idx: None,
219219
name: get_index_type_name(clean_type, true).map(|s| s.as_str().to_ascii_lowercase()),
220220
generics: get_generics(clean_type, cache),
@@ -256,7 +256,7 @@ fn get_generics(clean_type: &clean::Type, cache: &Cache) -> Option<Vec<Generic>>
256256
.filter_map(|t| {
257257
get_index_type_name(t, false).map(|name| Generic {
258258
name: name.as_str().to_ascii_lowercase(),
259-
defid: t.def_id_full(cache).map(FakeDefId::new_real),
259+
defid: t.def_id_full(cache),
260260
idx: None,
261261
})
262262
})

‎src/librustdoc/html/render/mod.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ crate struct IndexItem {
8787
crate name: String,
8888
crate path: String,
8989
crate desc: String,
90-
crate parent: Option<FakeDefId>,
90+
crate parent: Option<DefId>,
9191
crate parent_idx: Option<usize>,
9292
crate search_type: Option<IndexItemFunctionType>,
9393
crate aliases: Box<[String]>,
@@ -96,7 +96,7 @@ crate struct IndexItem {
9696
/// A type used for the search index.
9797
#[derive(Debug)]
9898
crate struct RenderType {
99-
ty: Option<FakeDefId>,
99+
ty: Option<DefId>,
100100
idx: Option<usize>,
101101
name: Option<String>,
102102
generics: Option<Vec<Generic>>,
@@ -128,7 +128,7 @@ impl Serialize for RenderType {
128128
#[derive(Debug)]
129129
crate struct Generic {
130130
name: String,
131-
defid: Option<FakeDefId>,
131+
defid: Option<DefId>,
132132
idx: Option<usize>,
133133
}
134134

@@ -2118,7 +2118,7 @@ fn sidebar_trait(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, t: &clean
21182118
"</div>",
21192119
);
21202120

2121-
if let Some(implementors) = cx.cache.implementors.get(&it.def_id) {
2121+
if let Some(implementors) = cx.cache.implementors.get(&it.def_id.expect_real()) {
21222122
let cache = cx.cache();
21232123
let mut res = implementors
21242124
.iter()

‎src/librustdoc/html/render/print_item.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -635,7 +635,7 @@ fn item_trait(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::Tra
635635
// If there are methods directly on this trait object, render them here.
636636
render_assoc_items(w, cx, it, it.def_id.expect_real(), AssocItemRender::All);
637637

638-
if let Some(implementors) = cx.cache.implementors.get(&it.def_id) {
638+
if let Some(implementors) = cx.cache.implementors.get(&it.def_id.expect_real()) {
639639
// The DefId is for the first Type found with that name. The bool is
640640
// if any Types with the same name but different DefId have been found.
641641
let mut implementor_dups: FxHashMap<Symbol, (DefId, bool)> = FxHashMap::default();

‎src/librustdoc/html/render/write_shared.rs

-2
Original file line numberDiff line numberDiff line change
@@ -464,8 +464,6 @@ pub(super) fn write_shared(
464464
// Update the list of all implementors for traits
465465
let dst = cx.dst.join("implementors");
466466
for (&did, imps) in &cx.cache.implementors {
467-
let did = did.expect_real();
468-
469467
// Private modules can leak through to this phase of rustdoc, which
470468
// could contain implementations for otherwise private types. In some
471469
// rare cases we could find an implementation for an item which wasn't

‎src/librustdoc/json/conversions.rs

+2-3
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,8 @@ use rustc_span::Pos;
1414

1515
use rustdoc_json_types::*;
1616

17-
use crate::clean;
1817
use crate::clean::utils::print_const_expr;
19-
use crate::clean::FakeDefId;
18+
use crate::clean::{self, FakeDefId};
2019
use crate::formats::item_type::ItemType;
2120
use crate::json::JsonRenderer;
2221
use std::collections::HashSet;
@@ -31,7 +30,7 @@ impl JsonRenderer<'_> {
3130
.into_iter()
3231
.flatten()
3332
.filter_map(|clean::ItemLink { link, did, .. }| {
34-
did.map(|did| (link.clone(), from_def_id(did)))
33+
did.map(|did| (link.clone(), from_def_id(did.into())))
3534
})
3635
.collect();
3736
let docs = item.attrs.collapsed_doc_value();

‎src/librustdoc/json/mod.rs

+8-7
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,14 @@ use std::path::PathBuf;
1212
use std::rc::Rc;
1313

1414
use rustc_data_structures::fx::FxHashMap;
15+
use rustc_hir::def_id::DefId;
1516
use rustc_middle::ty::TyCtxt;
1617
use rustc_session::Session;
1718

1819
use rustdoc_json_types as types;
1920

2021
use crate::clean;
21-
use crate::clean::{ExternalCrate, FakeDefId};
22+
use crate::clean::ExternalCrate;
2223
use crate::config::RenderOptions;
2324
use crate::error::Error;
2425
use crate::formats::cache::Cache;
@@ -42,7 +43,7 @@ impl JsonRenderer<'tcx> {
4243
self.tcx.sess
4344
}
4445

45-
fn get_trait_implementors(&mut self, id: FakeDefId) -> Vec<types::Id> {
46+
fn get_trait_implementors(&mut self, id: DefId) -> Vec<types::Id> {
4647
Rc::clone(&self.cache)
4748
.implementors
4849
.get(&id)
@@ -59,10 +60,10 @@ impl JsonRenderer<'tcx> {
5960
.unwrap_or_default()
6061
}
6162

62-
fn get_impls(&mut self, id: FakeDefId) -> Vec<types::Id> {
63+
fn get_impls(&mut self, id: DefId) -> Vec<types::Id> {
6364
Rc::clone(&self.cache)
6465
.impls
65-
.get(&id.expect_real())
66+
.get(&id)
6667
.map(|impls| {
6768
impls
6869
.iter()
@@ -163,11 +164,11 @@ impl<'tcx> FormatRenderer<'tcx> for JsonRenderer<'tcx> {
163164
let id = item.def_id;
164165
if let Some(mut new_item) = self.convert_item(item) {
165166
if let types::ItemEnum::Trait(ref mut t) = new_item.inner {
166-
t.implementors = self.get_trait_implementors(id)
167+
t.implementors = self.get_trait_implementors(id.expect_real())
167168
} else if let types::ItemEnum::Struct(ref mut s) = new_item.inner {
168-
s.impls = self.get_impls(id)
169+
s.impls = self.get_impls(id.expect_real())
169170
} else if let types::ItemEnum::Enum(ref mut e) = new_item.inner {
170-
e.impls = self.get_impls(id)
171+
e.impls = self.get_impls(id.expect_real())
171172
}
172173
let removed = self.index.borrow_mut().insert(from_def_id(id), new_item.clone());
173174

‎src/librustdoc/passes/collect_intra_doc_links.rs

+21-42
Original file line numberDiff line numberDiff line change
@@ -30,9 +30,7 @@ use std::convert::{TryFrom, TryInto};
3030
use std::mem;
3131
use std::ops::Range;
3232

33-
use crate::clean::{
34-
self, utils::find_nearest_parent_module, Crate, FakeDefId, Item, ItemLink, PrimitiveType,
35-
};
33+
use crate::clean::{self, utils::find_nearest_parent_module, Crate, Item, ItemLink, PrimitiveType};
3634
use crate::core::DocContext;
3735
use crate::fold::DocFolder;
3836
use crate::html::markdown::{markdown_links, MarkdownLink};
@@ -248,7 +246,7 @@ enum AnchorFailure {
248246

249247
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
250248
struct ResolutionInfo {
251-
module_id: FakeDefId,
249+
module_id: DefId,
252250
dis: Option<Disambiguator>,
253251
path_str: String,
254252
extra_fragment: Option<String>,
@@ -274,7 +272,7 @@ struct LinkCollector<'a, 'tcx> {
274272
///
275273
/// The last module will be used if the parent scope of the current item is
276274
/// unknown.
277-
mod_ids: Vec<FakeDefId>,
275+
mod_ids: Vec<DefId>,
278276
/// This is used to store the kind of associated items,
279277
/// because `clean` and the disambiguator code expect them to be different.
280278
/// See the code for associated items on inherent impls for details.
@@ -861,7 +859,7 @@ impl<'a, 'tcx> DocFolder for LinkCollector<'a, 'tcx> {
861859
let inner_docs = item.inner_docs(self.cx.tcx);
862860

863861
if item.is_mod() && inner_docs {
864-
self.mod_ids.push(item.def_id);
862+
self.mod_ids.push(item.def_id.expect_real());
865863
}
866864

867865
// We want to resolve in the lexical scope of the documentation.
@@ -888,7 +886,7 @@ impl<'a, 'tcx> DocFolder for LinkCollector<'a, 'tcx> {
888886

889887
Some(if item.is_mod() {
890888
if !inner_docs {
891-
self.mod_ids.push(item.def_id);
889+
self.mod_ids.push(item.def_id.expect_real());
892890
}
893891

894892
let ret = self.fold_item_recur(item);
@@ -1070,11 +1068,8 @@ impl LinkCollector<'_, '_> {
10701068
// we've already pushed this node onto the resolution stack but
10711069
// for outer comments we explicitly try and resolve against the
10721070
// parent_node first.
1073-
let base_node = if item.is_mod() && inner_docs {
1074-
self.mod_ids.last().copied()
1075-
} else {
1076-
parent_node.map(|id| FakeDefId::new_real(id))
1077-
};
1071+
let base_node =
1072+
if item.is_mod() && inner_docs { self.mod_ids.last().copied() } else { parent_node };
10781073

10791074
let mut module_id = if let Some(id) = base_node {
10801075
id
@@ -1119,7 +1114,7 @@ impl LinkCollector<'_, '_> {
11191114
resolved_self = format!("self::{}", &path_str["crate::".len()..]);
11201115
path_str = &resolved_self;
11211116
}
1122-
module_id = FakeDefId::new_real(DefId { krate, index: CRATE_DEF_INDEX });
1117+
module_id = DefId { krate, index: CRATE_DEF_INDEX };
11231118
}
11241119

11251120
let (mut res, mut fragment) = self.resolve_with_disambiguator_cached(
@@ -1180,8 +1175,8 @@ impl LinkCollector<'_, '_> {
11801175
report_diagnostic(self.cx.tcx, BROKEN_INTRA_DOC_LINKS, &msg, &diag_info, callback);
11811176
};
11821177

1183-
let verify = |kind: DefKind, id: FakeDefId| {
1184-
let (kind, id) = self.kind_side_channel.take().unwrap_or((kind, id.expect_real()));
1178+
let verify = |kind: DefKind, id: DefId| {
1179+
let (kind, id) = self.kind_side_channel.take().unwrap_or((kind, id));
11851180
debug!("intra-doc link to {} resolved to {:?} (id: {:?})", path_str, res, id);
11861181

11871182
// Disallow e.g. linking to enums with `struct@`
@@ -1341,7 +1336,7 @@ impl LinkCollector<'_, '_> {
13411336

13421337
match disambiguator.map(Disambiguator::ns) {
13431338
Some(expected_ns @ (ValueNS | TypeNS)) => {
1344-
match self.resolve(path_str, expected_ns, base_node.expect_real(), extra_fragment) {
1339+
match self.resolve(path_str, expected_ns, base_node, extra_fragment) {
13451340
Ok(res) => Some(res),
13461341
Err(ErrorKind::Resolve(box mut kind)) => {
13471342
// We only looked in one namespace. Try to give a better error if possible.
@@ -1350,12 +1345,9 @@ impl LinkCollector<'_, '_> {
13501345
// FIXME: really it should be `resolution_failure` that does this, not `resolve_with_disambiguator`
13511346
// See https://github.com/rust-lang/rust/pull/76955#discussion_r493953382 for a good approach
13521347
for &new_ns in &[other_ns, MacroNS] {
1353-
if let Some(res) = self.check_full_res(
1354-
new_ns,
1355-
path_str,
1356-
base_node.expect_real(),
1357-
extra_fragment,
1358-
) {
1348+
if let Some(res) =
1349+
self.check_full_res(new_ns, path_str, base_node, extra_fragment)
1350+
{
13591351
kind = ResolutionFailure::WrongNamespace { res, expected_ns };
13601352
break;
13611353
}
@@ -1377,14 +1369,9 @@ impl LinkCollector<'_, '_> {
13771369
// Try everything!
13781370
let mut candidates = PerNS {
13791371
macro_ns: self
1380-
.resolve_macro(path_str, base_node.expect_real())
1372+
.resolve_macro(path_str, base_node)
13811373
.map(|res| (res, extra_fragment.clone())),
1382-
type_ns: match self.resolve(
1383-
path_str,
1384-
TypeNS,
1385-
base_node.expect_real(),
1386-
extra_fragment,
1387-
) {
1374+
type_ns: match self.resolve(path_str, TypeNS, base_node, extra_fragment) {
13881375
Ok(res) => {
13891376
debug!("got res in TypeNS: {:?}", res);
13901377
Ok(res)
@@ -1395,12 +1382,7 @@ impl LinkCollector<'_, '_> {
13951382
}
13961383
Err(ErrorKind::Resolve(box kind)) => Err(kind),
13971384
},
1398-
value_ns: match self.resolve(
1399-
path_str,
1400-
ValueNS,
1401-
base_node.expect_real(),
1402-
extra_fragment,
1403-
) {
1385+
value_ns: match self.resolve(path_str, ValueNS, base_node, extra_fragment) {
14041386
Ok(res) => Ok(res),
14051387
Err(ErrorKind::AnchorFailure(msg)) => {
14061388
anchor_failure(self.cx, diag, msg);
@@ -1456,17 +1438,14 @@ impl LinkCollector<'_, '_> {
14561438
}
14571439
}
14581440
Some(MacroNS) => {
1459-
match self.resolve_macro(path_str, base_node.expect_real()) {
1441+
match self.resolve_macro(path_str, base_node) {
14601442
Ok(res) => Some((res, extra_fragment.clone())),
14611443
Err(mut kind) => {
14621444
// `resolve_macro` only looks in the macro namespace. Try to give a better error if possible.
14631445
for &ns in &[TypeNS, ValueNS] {
1464-
if let Some(res) = self.check_full_res(
1465-
ns,
1466-
path_str,
1467-
base_node.expect_real(),
1468-
extra_fragment,
1469-
) {
1446+
if let Some(res) =
1447+
self.check_full_res(ns, path_str, base_node, extra_fragment)
1448+
{
14701449
kind =
14711450
ResolutionFailure::WrongNamespace { res, expected_ns: MacroNS };
14721451
break;

‎src/librustdoc/passes/collect_trait_impls.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -126,7 +126,7 @@ crate fn collect_trait_impls(krate: Crate, cx: &mut DocContext<'_>) -> Crate {
126126
// Since only the `DefId` portion of the `Type` instances is known to be same for both the
127127
// `Deref` target type and the impl for type positions, this map of types is keyed by
128128
// `DefId` and for convenience uses a special cleaner that accepts `DefId`s directly.
129-
if cleaner.keep_impl_with_def_id(&FakeDefId::new_real(*type_did)) {
129+
if cleaner.keep_impl_with_def_id(FakeDefId::Real(*type_did)) {
130130
add_deref_target(&type_did_to_deref_target, &mut cleaner, type_did);
131131
}
132132
}
@@ -206,13 +206,13 @@ impl BadImplStripper {
206206
} else if let Some(prim) = ty.primitive_type() {
207207
self.prims.contains(&prim)
208208
} else if let Some(did) = ty.def_id() {
209-
self.keep_impl_with_def_id(&did.into())
209+
self.keep_impl_with_def_id(did.into())
210210
} else {
211211
false
212212
}
213213
}
214214

215-
fn keep_impl_with_def_id(&self, did: &FakeDefId) -> bool {
216-
self.items.contains(did)
215+
fn keep_impl_with_def_id(&self, did: FakeDefId) -> bool {
216+
self.items.contains(&did)
217217
}
218218
}

0 commit comments

Comments
 (0)
Please sign in to comment.