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