]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/passes/collect_trait_impls.rs
Rollup merge of #82305 - camelid:no-more-refcell, r=jyn514
[rust.git] / src / librustdoc / passes / collect_trait_impls.rs
1 use super::Pass;
2 use crate::clean::*;
3 use crate::core::DocContext;
4 use crate::fold::DocFolder;
5
6 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
7 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
8 use rustc_middle::ty::DefIdTree;
9 use rustc_span::symbol::sym;
10
11 crate const COLLECT_TRAIT_IMPLS: Pass = Pass {
12     name: "collect-trait-impls",
13     run: collect_trait_impls,
14     description: "retrieves trait impls for items in the crate",
15 };
16
17 crate fn collect_trait_impls(krate: Crate, cx: &mut DocContext<'_>) -> Crate {
18     let (mut krate, synth_impls) = cx.sess().time("collect_synthetic_impls", || {
19         let mut synth = SyntheticImplCollector { cx, impls: Vec::new() };
20         (synth.fold_crate(krate), synth.impls)
21     });
22
23     let prims: FxHashSet<PrimitiveType> = krate.primitives.iter().map(|p| p.1).collect();
24
25     let crate_items = {
26         let mut coll = ItemCollector::new();
27         krate = cx.sess().time("collect_items_for_trait_impls", || coll.fold_crate(krate));
28         coll.items
29     };
30
31     let mut new_items = Vec::new();
32
33     for &cnum in cx.tcx.crates().iter() {
34         for &(did, _) in cx.tcx.all_trait_implementations(cnum).iter() {
35             cx.tcx.sess.prof.generic_activity("build_extern_trait_impl").run(|| {
36                 inline::build_impl(cx, None, did, None, &mut new_items);
37             });
38         }
39     }
40
41     // Also try to inline primitive impls from other crates.
42     for &def_id in PrimitiveType::all_impls(cx.tcx).values().flatten() {
43         if !def_id.is_local() {
44             cx.tcx.sess.prof.generic_activity("build_primitive_trait_impls").run(|| {
45                 inline::build_impl(cx, None, def_id, None, &mut new_items);
46
47                 // FIXME(eddyb) is this `doc(hidden)` check needed?
48                 if !cx.tcx.get_attrs(def_id).lists(sym::doc).has_word(sym::hidden) {
49                     let self_ty = cx.tcx.type_of(def_id);
50                     let impls = get_auto_trait_and_blanket_impls(cx, self_ty, def_id);
51
52                     new_items.extend(impls.filter(|i| cx.renderinfo.inlined.insert(i.def_id)));
53                 }
54             });
55         }
56     }
57
58     // `tcx.crates()` doesn't include the local crate, and `tcx.all_trait_implementations`
59     // doesn't work with it anyway, so pull them from the HIR map instead
60     let mut extra_attrs = Vec::new();
61     for &trait_did in cx.tcx.all_traits(LOCAL_CRATE).iter() {
62         for &impl_did in cx.tcx.hir().trait_impls(trait_did) {
63             let impl_did = impl_did.to_def_id();
64             cx.tcx.sess.prof.generic_activity("build_local_trait_impl").run(|| {
65                 let mut parent = cx.tcx.parent(impl_did);
66                 while let Some(did) = parent {
67                     extra_attrs.extend(
68                         cx.tcx
69                             .get_attrs(did)
70                             .iter()
71                             .filter(|attr| attr.has_name(sym::doc))
72                             .filter(|attr| {
73                                 if let Some([attr]) = attr.meta_item_list().as_deref() {
74                                     attr.has_name(sym::cfg)
75                                 } else {
76                                     false
77                                 }
78                             })
79                             .cloned(),
80                     );
81                     parent = cx.tcx.parent(did);
82                 }
83                 inline::build_impl(cx, None, impl_did, Some(&extra_attrs), &mut new_items);
84                 extra_attrs.clear();
85             });
86         }
87     }
88
89     let mut cleaner = BadImplStripper { prims, items: crate_items };
90
91     let mut type_did_to_deref_target: FxHashMap<DefId, &Type> = FxHashMap::default();
92     // Gather all type to `Deref` target edges.
93     for it in &new_items {
94         if let ImplItem(Impl { ref for_, ref trait_, ref items, .. }) = *it.kind {
95             if trait_.def_id() == cx.tcx.lang_items().deref_trait() {
96                 let target = items.iter().find_map(|item| match *item.kind {
97                     TypedefItem(ref t, true) => Some(&t.type_),
98                     _ => None,
99                 });
100                 if let (Some(for_did), Some(target)) = (for_.def_id(), target) {
101                     type_did_to_deref_target.insert(for_did, target);
102                 }
103             }
104         }
105     }
106     // Follow all `Deref` targets of included items and recursively add them as valid
107     fn add_deref_target(
108         map: &FxHashMap<DefId, &Type>,
109         cleaner: &mut BadImplStripper,
110         type_did: &DefId,
111     ) {
112         if let Some(target) = map.get(type_did) {
113             debug!("add_deref_target: type {:?}, target {:?}", type_did, target);
114             if let Some(target_prim) = target.primitive_type() {
115                 cleaner.prims.insert(target_prim);
116             } else if let Some(target_did) = target.def_id() {
117                 // `impl Deref<Target = S> for S`
118                 if target_did == *type_did {
119                     // Avoid infinite cycles
120                     return;
121                 }
122                 cleaner.items.insert(target_did);
123                 add_deref_target(map, cleaner, &target_did);
124             }
125         }
126     }
127     for type_did in type_did_to_deref_target.keys() {
128         // Since only the `DefId` portion of the `Type` instances is known to be same for both the
129         // `Deref` target type and the impl for type positions, this map of types is keyed by
130         // `DefId` and for convenience uses a special cleaner that accepts `DefId`s directly.
131         if cleaner.keep_impl_with_def_id(type_did) {
132             add_deref_target(&type_did_to_deref_target, &mut cleaner, type_did);
133         }
134     }
135
136     let items = if let Some(ref mut it) = krate.module {
137         if let ModuleItem(Module { ref mut items, .. }) = *it.kind {
138             items
139         } else {
140             panic!("collect-trait-impls can't run");
141         }
142     } else {
143         panic!("collect-trait-impls can't run");
144     };
145
146     items.extend(synth_impls);
147     for it in new_items.drain(..) {
148         if let ImplItem(Impl { ref for_, ref trait_, ref blanket_impl, .. }) = *it.kind {
149             if !(cleaner.keep_impl(for_)
150                 || trait_.as_ref().map_or(false, |t| cleaner.keep_impl(t))
151                 || blanket_impl.is_some())
152             {
153                 continue;
154             }
155         }
156
157         items.push(it);
158     }
159
160     krate
161 }
162
163 struct SyntheticImplCollector<'a, 'tcx> {
164     cx: &'a mut DocContext<'tcx>,
165     impls: Vec<Item>,
166 }
167
168 impl<'a, 'tcx> DocFolder for SyntheticImplCollector<'a, 'tcx> {
169     fn fold_item(&mut self, i: Item) -> Option<Item> {
170         if i.is_struct() || i.is_enum() || i.is_union() {
171             // FIXME(eddyb) is this `doc(hidden)` check needed?
172             if !self.cx.tcx.get_attrs(i.def_id).lists(sym::doc).has_word(sym::hidden) {
173                 self.impls.extend(get_auto_trait_and_blanket_impls(
174                     self.cx,
175                     self.cx.tcx.type_of(i.def_id),
176                     i.def_id,
177                 ));
178             }
179         }
180
181         Some(self.fold_item_recur(i))
182     }
183 }
184
185 #[derive(Default)]
186 struct ItemCollector {
187     items: FxHashSet<DefId>,
188 }
189
190 impl ItemCollector {
191     fn new() -> Self {
192         Self::default()
193     }
194 }
195
196 impl DocFolder for ItemCollector {
197     fn fold_item(&mut self, i: Item) -> Option<Item> {
198         self.items.insert(i.def_id);
199
200         Some(self.fold_item_recur(i))
201     }
202 }
203
204 struct BadImplStripper {
205     prims: FxHashSet<PrimitiveType>,
206     items: FxHashSet<DefId>,
207 }
208
209 impl BadImplStripper {
210     fn keep_impl(&self, ty: &Type) -> bool {
211         if let Generic(_) = ty {
212             // keep impls made on generics
213             true
214         } else if let Some(prim) = ty.primitive_type() {
215             self.prims.contains(&prim)
216         } else if let Some(did) = ty.def_id() {
217             self.keep_impl_with_def_id(&did)
218         } else {
219             false
220         }
221     }
222
223     fn keep_impl_with_def_id(&self, did: &DefId) -> bool {
224         self.items.contains(did)
225     }
226 }