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