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