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