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