]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/passes/collect_trait_impls.rs
Rollup merge of #96614 - JohnTitor:test-92305, r=oli-obk
[rust.git] / src / librustdoc / passes / collect_trait_impls.rs
1 //! Collects trait impls for each item in the crate. For example, if a crate
2 //! defines a struct that implements a trait, this pass will note that the
3 //! struct implements that trait.
4 use super::Pass;
5 use crate::clean::*;
6 use crate::core::DocContext;
7 use crate::formats::cache::Cache;
8 use crate::visit::DocVisitor;
9
10 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
11 use rustc_hir::def_id::DefId;
12 use rustc_middle::ty::DefIdTree;
13 use rustc_span::symbol::sym;
14
15 crate const COLLECT_TRAIT_IMPLS: Pass = Pass {
16     name: "collect-trait-impls",
17     run: collect_trait_impls,
18     description: "retrieves trait impls for items in the crate",
19 };
20
21 crate fn collect_trait_impls(mut krate: Crate, cx: &mut DocContext<'_>) -> Crate {
22     let synth_impls = cx.sess().time("collect_synthetic_impls", || {
23         let mut synth = SyntheticImplCollector { cx, impls: Vec::new() };
24         synth.visit_crate(&krate);
25         synth.impls
26     });
27
28     let prims: FxHashSet<PrimitiveType> = krate.primitives.iter().map(|p| p.1).collect();
29
30     let crate_items = {
31         let mut coll = ItemCollector::new();
32         cx.sess().time("collect_items_for_trait_impls", || coll.visit_crate(&krate));
33         coll.items
34     };
35
36     let mut new_items_external = Vec::new();
37     let mut new_items_local = Vec::new();
38
39     // External trait impls.
40     cx.with_all_trait_impls(|cx, all_trait_impls| {
41         let _prof_timer = cx.tcx.sess.prof.generic_activity("build_extern_trait_impls");
42         for &impl_def_id in all_trait_impls.iter().skip_while(|def_id| def_id.is_local()) {
43             inline::build_impl(cx, None, impl_def_id, None, &mut new_items_external);
44         }
45     });
46
47     // Local trait impls.
48     cx.with_all_trait_impls(|cx, all_trait_impls| {
49         let _prof_timer = cx.tcx.sess.prof.generic_activity("build_local_trait_impls");
50         let mut attr_buf = Vec::new();
51         for &impl_def_id in all_trait_impls.iter().take_while(|def_id| def_id.is_local()) {
52             let mut parent = Some(cx.tcx.parent(impl_def_id));
53             while let Some(did) = parent {
54                 attr_buf.extend(
55                     cx.tcx
56                         .get_attrs(did)
57                         .iter()
58                         .filter(|attr| attr.has_name(sym::doc))
59                         .filter(|attr| {
60                             if let Some([attr]) = attr.meta_item_list().as_deref() {
61                                 attr.has_name(sym::cfg)
62                             } else {
63                                 false
64                             }
65                         })
66                         .cloned(),
67                 );
68                 parent = cx.tcx.opt_parent(did);
69             }
70             inline::build_impl(cx, None, impl_def_id, Some(&attr_buf), &mut new_items_local);
71             attr_buf.clear();
72         }
73     });
74
75     cx.tcx.sess.prof.generic_activity("build_primitive_trait_impls").run(|| {
76         for def_id in PrimitiveType::all_impls(cx.tcx) {
77             // Try to inline primitive impls from other crates.
78             if !def_id.is_local() {
79                 inline::build_impl(cx, None, def_id, None, &mut new_items_external);
80             }
81         }
82         for (prim, did) in PrimitiveType::primitive_locations(cx.tcx) {
83             // Do not calculate blanket impl list for docs that are not going to be rendered.
84             // While the `impl` blocks themselves are only in `libcore`, the module with `doc`
85             // attached is directly included in `libstd` as well.
86             if did.is_local() {
87                 for def_id in prim.impls(cx.tcx) {
88                     let impls = get_auto_trait_and_blanket_impls(cx, def_id);
89                     new_items_external.extend(impls.filter(|i| cx.inlined.insert(i.item_id)));
90                 }
91             }
92         }
93     });
94
95     let mut cleaner = BadImplStripper { prims, items: crate_items, cache: &cx.cache };
96     let mut type_did_to_deref_target: FxHashMap<DefId, &Type> = FxHashMap::default();
97
98     // Follow all `Deref` targets of included items and recursively add them as valid
99     fn add_deref_target(
100         cx: &DocContext<'_>,
101         map: &FxHashMap<DefId, &Type>,
102         cleaner: &mut BadImplStripper<'_>,
103         targets: &mut FxHashSet<DefId>,
104         type_did: DefId,
105     ) {
106         if let Some(target) = map.get(&type_did) {
107             debug!("add_deref_target: type {:?}, target {:?}", type_did, target);
108             if let Some(target_prim) = target.primitive_type() {
109                 cleaner.prims.insert(target_prim);
110             } else if let Some(target_did) = target.def_id(&cx.cache) {
111                 // `impl Deref<Target = S> for S`
112                 if !targets.insert(target_did) {
113                     // Avoid infinite cycles
114                     return;
115                 }
116                 cleaner.items.insert(target_did.into());
117                 add_deref_target(cx, map, cleaner, targets, target_did);
118             }
119         }
120     }
121
122     // scan through included items ahead of time to splice in Deref targets to the "valid" sets
123     for it in new_items_external.iter().chain(new_items_local.iter()) {
124         if let ImplItem(Impl { ref for_, ref trait_, ref items, .. }) = *it.kind {
125             if trait_.as_ref().map(|t| t.def_id()) == cx.tcx.lang_items().deref_trait()
126                 && cleaner.keep_impl(for_, true)
127             {
128                 let target = items
129                     .iter()
130                     .find_map(|item| match *item.kind {
131                         AssocTypeItem(ref t, _) => Some(&t.type_),
132                         _ => None,
133                     })
134                     .expect("Deref impl without Target type");
135
136                 if let Some(prim) = target.primitive_type() {
137                     cleaner.prims.insert(prim);
138                 } else if let Some(did) = target.def_id(&cx.cache) {
139                     cleaner.items.insert(did.into());
140                 }
141                 if let Some(for_did) = for_.def_id(&cx.cache) {
142                     if type_did_to_deref_target.insert(for_did, target).is_none() {
143                         // Since only the `DefId` portion of the `Type` instances is known to be same for both the
144                         // `Deref` target type and the impl for type positions, this map of types is keyed by
145                         // `DefId` and for convenience uses a special cleaner that accepts `DefId`s directly.
146                         if cleaner.keep_impl_with_def_id(for_did.into()) {
147                             let mut targets = FxHashSet::default();
148                             targets.insert(for_did);
149                             add_deref_target(
150                                 cx,
151                                 &type_did_to_deref_target,
152                                 &mut cleaner,
153                                 &mut targets,
154                                 for_did,
155                             );
156                         }
157                     }
158                 }
159             }
160         }
161     }
162
163     // Filter out external items that are not needed
164     new_items_external.retain(|it| {
165         if let ImplItem(Impl { ref for_, ref trait_, ref kind, .. }) = *it.kind {
166             cleaner.keep_impl(
167                 for_,
168                 trait_.as_ref().map(|t| t.def_id()) == cx.tcx.lang_items().deref_trait(),
169             ) || trait_.as_ref().map_or(false, |t| cleaner.keep_impl_with_def_id(t.def_id().into()))
170                 || kind.is_blanket()
171         } else {
172             true
173         }
174     });
175
176     if let ModuleItem(Module { items, .. }) = &mut *krate.module.kind {
177         items.extend(synth_impls);
178         items.extend(new_items_external);
179         items.extend(new_items_local);
180     } else {
181         panic!("collect-trait-impls can't run");
182     };
183
184     krate
185 }
186
187 struct SyntheticImplCollector<'a, 'tcx> {
188     cx: &'a mut DocContext<'tcx>,
189     impls: Vec<Item>,
190 }
191
192 impl<'a, 'tcx> DocVisitor for SyntheticImplCollector<'a, 'tcx> {
193     fn visit_item(&mut self, i: &Item) {
194         if i.is_struct() || i.is_enum() || i.is_union() {
195             // FIXME(eddyb) is this `doc(hidden)` check needed?
196             if !self.cx.tcx.is_doc_hidden(i.item_id.expect_def_id()) {
197                 self.impls
198                     .extend(get_auto_trait_and_blanket_impls(self.cx, i.item_id.expect_def_id()));
199             }
200         }
201
202         self.visit_item_recur(i)
203     }
204 }
205
206 #[derive(Default)]
207 struct ItemCollector {
208     items: FxHashSet<ItemId>,
209 }
210
211 impl ItemCollector {
212     fn new() -> Self {
213         Self::default()
214     }
215 }
216
217 impl DocVisitor for ItemCollector {
218     fn visit_item(&mut self, i: &Item) {
219         self.items.insert(i.item_id);
220
221         self.visit_item_recur(i)
222     }
223 }
224
225 struct BadImplStripper<'a> {
226     prims: FxHashSet<PrimitiveType>,
227     items: FxHashSet<ItemId>,
228     cache: &'a Cache,
229 }
230
231 impl<'a> BadImplStripper<'a> {
232     fn keep_impl(&self, ty: &Type, is_deref: bool) -> bool {
233         if let Generic(_) = ty {
234             // keep impls made on generics
235             true
236         } else if let Some(prim) = ty.primitive_type() {
237             self.prims.contains(&prim)
238         } else if let Some(did) = ty.def_id(self.cache) {
239             is_deref || self.keep_impl_with_def_id(did.into())
240         } else {
241             false
242         }
243     }
244
245     fn keep_impl_with_def_id(&self, item_id: ItemId) -> bool {
246         self.items.contains(&item_id)
247     }
248 }