]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/passes/collect_trait_impls.rs
Auto merge of #104999 - saethlin:immediate-abort-inlining, r=thomcc
[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, LOCAL_CRATE};
12 use rustc_middle::ty::{self, DefIdTree};
13 use rustc_span::symbol::sym;
14
15 pub(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 pub(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 local_crate = ExternalCrate { crate_num: LOCAL_CRATE };
29     let prims: FxHashSet<PrimitiveType> =
30         local_crate.primitives(cx.tcx).iter().map(|p| p.1).collect();
31
32     let crate_items = {
33         let mut coll = ItemCollector::new();
34         cx.sess().time("collect_items_for_trait_impls", || coll.visit_crate(&krate));
35         coll.items
36     };
37
38     let mut new_items_external = Vec::new();
39     let mut new_items_local = Vec::new();
40
41     // External trait impls.
42     cx.with_all_trait_impls(|cx, all_trait_impls| {
43         let _prof_timer = cx.tcx.sess.prof.generic_activity("build_extern_trait_impls");
44         for &impl_def_id in all_trait_impls.iter().skip_while(|def_id| def_id.is_local()) {
45             inline::build_impl(cx, None, impl_def_id, None, &mut new_items_external);
46         }
47     });
48
49     // Local trait impls.
50     cx.with_all_trait_impls(|cx, all_trait_impls| {
51         let _prof_timer = cx.tcx.sess.prof.generic_activity("build_local_trait_impls");
52         let mut attr_buf = Vec::new();
53         for &impl_def_id in all_trait_impls.iter().take_while(|def_id| def_id.is_local()) {
54             let mut parent = Some(cx.tcx.parent(impl_def_id));
55             while let Some(did) = parent {
56                 attr_buf.extend(
57                     cx.tcx
58                         .get_attrs(did, sym::doc)
59                         .filter(|attr| {
60                             if let Some([attr]) = attr.meta_item_list().as_deref() {
61                                 attr.has_name(sym::cfg)
62                             } else {
63                                 false
64                             }
65                         })
66                         .cloned(),
67                 );
68                 parent = cx.tcx.opt_parent(did);
69             }
70             inline::build_impl(cx, None, impl_def_id, Some(&attr_buf), &mut new_items_local);
71             attr_buf.clear();
72         }
73     });
74
75     cx.tcx.sess.prof.generic_activity("build_primitive_trait_impls").run(|| {
76         for def_id in PrimitiveType::all_impls(cx.tcx) {
77             // Try to inline primitive impls from other crates.
78             if !def_id.is_local() {
79                 inline::build_impl(cx, None, def_id, None, &mut new_items_external);
80             }
81         }
82         for (prim, did) in PrimitiveType::primitive_locations(cx.tcx) {
83             // Do not calculate blanket impl list for docs that are not going to be rendered.
84             // While the `impl` blocks themselves are only in `libcore`, the module with `doc`
85             // attached is directly included in `libstd` as well.
86             let tcx = cx.tcx;
87             if did.is_local() {
88                 for def_id in prim.impls(tcx).filter(|def_id| {
89                     // Avoid including impl blocks with filled-in generics.
90                     // https://github.com/rust-lang/rust/issues/94937
91                     //
92                     // FIXME(notriddle): https://github.com/rust-lang/rust/issues/97129
93                     //
94                     // This tactic of using inherent impl blocks for getting
95                     // auto traits and blanket impls is a hack. What we really
96                     // want is to check if `[T]` impls `Send`, which has
97                     // nothing to do with the inherent impl.
98                     //
99                     // Rustdoc currently uses these `impl` block as a source of
100                     // the `Ty`, as well as the `ParamEnv`, `SubstsRef`, and
101                     // `Generics`. To avoid relying on the `impl` block, these
102                     // things would need to be created from wholecloth, in a
103                     // form that is valid for use in type inference.
104                     let ty = tcx.type_of(def_id);
105                     match ty.kind() {
106                         ty::Slice(ty)
107                         | ty::Ref(_, ty, _)
108                         | ty::RawPtr(ty::TypeAndMut { ty, .. }) => {
109                             matches!(ty.kind(), ty::Param(..))
110                         }
111                         ty::Tuple(tys) => tys.iter().all(|ty| matches!(ty.kind(), ty::Param(..))),
112                         _ => true,
113                     }
114                 }) {
115                     let impls = get_auto_trait_and_blanket_impls(cx, def_id);
116                     new_items_external.extend(impls.filter(|i| cx.inlined.insert(i.item_id)));
117                 }
118             }
119         }
120     });
121
122     let mut cleaner = BadImplStripper { prims, items: crate_items, cache: &cx.cache };
123     let mut type_did_to_deref_target: FxHashMap<DefId, &Type> = FxHashMap::default();
124
125     // Follow all `Deref` targets of included items and recursively add them as valid
126     fn add_deref_target(
127         cx: &DocContext<'_>,
128         map: &FxHashMap<DefId, &Type>,
129         cleaner: &mut BadImplStripper<'_>,
130         targets: &mut FxHashSet<DefId>,
131         type_did: DefId,
132     ) {
133         if let Some(target) = map.get(&type_did) {
134             debug!("add_deref_target: type {:?}, target {:?}", type_did, target);
135             if let Some(target_prim) = target.primitive_type() {
136                 cleaner.prims.insert(target_prim);
137             } else if let Some(target_did) = target.def_id(&cx.cache) {
138                 // `impl Deref<Target = S> for S`
139                 if !targets.insert(target_did) {
140                     // Avoid infinite cycles
141                     return;
142                 }
143                 cleaner.items.insert(target_did.into());
144                 add_deref_target(cx, map, cleaner, targets, target_did);
145             }
146         }
147     }
148
149     // scan through included items ahead of time to splice in Deref targets to the "valid" sets
150     for it in new_items_external.iter().chain(new_items_local.iter()) {
151         if let ImplItem(box Impl { ref for_, ref trait_, ref items, .. }) = *it.kind {
152             if trait_.as_ref().map(|t| t.def_id()) == cx.tcx.lang_items().deref_trait()
153                 && cleaner.keep_impl(for_, true)
154             {
155                 let target = items
156                     .iter()
157                     .find_map(|item| match *item.kind {
158                         AssocTypeItem(ref t, _) => Some(&t.type_),
159                         _ => None,
160                     })
161                     .expect("Deref impl without Target type");
162
163                 if let Some(prim) = target.primitive_type() {
164                     cleaner.prims.insert(prim);
165                 } else if let Some(did) = target.def_id(&cx.cache) {
166                     cleaner.items.insert(did.into());
167                 }
168                 if let Some(for_did) = for_.def_id(&cx.cache) {
169                     if type_did_to_deref_target.insert(for_did, target).is_none() {
170                         // Since only the `DefId` portion of the `Type` instances is known to be same for both the
171                         // `Deref` target type and the impl for type positions, this map of types is keyed by
172                         // `DefId` and for convenience uses a special cleaner that accepts `DefId`s directly.
173                         if cleaner.keep_impl_with_def_id(for_did.into()) {
174                             let mut targets = FxHashSet::default();
175                             targets.insert(for_did);
176                             add_deref_target(
177                                 cx,
178                                 &type_did_to_deref_target,
179                                 &mut cleaner,
180                                 &mut targets,
181                                 for_did,
182                             );
183                         }
184                     }
185                 }
186             }
187         }
188     }
189
190     // Filter out external items that are not needed
191     new_items_external.retain(|it| {
192         if let ImplItem(box Impl { ref for_, ref trait_, ref kind, .. }) = *it.kind {
193             cleaner.keep_impl(
194                 for_,
195                 trait_.as_ref().map(|t| t.def_id()) == cx.tcx.lang_items().deref_trait(),
196             ) || trait_.as_ref().map_or(false, |t| cleaner.keep_impl_with_def_id(t.def_id().into()))
197                 || kind.is_blanket()
198         } else {
199             true
200         }
201     });
202
203     if let ModuleItem(Module { items, .. }) = &mut *krate.module.kind {
204         items.extend(synth_impls);
205         items.extend(new_items_external);
206         items.extend(new_items_local);
207     } else {
208         panic!("collect-trait-impls can't run");
209     };
210
211     krate
212 }
213
214 struct SyntheticImplCollector<'a, 'tcx> {
215     cx: &'a mut DocContext<'tcx>,
216     impls: Vec<Item>,
217 }
218
219 impl<'a, 'tcx> DocVisitor for SyntheticImplCollector<'a, 'tcx> {
220     fn visit_item(&mut self, i: &Item) {
221         if i.is_struct() || i.is_enum() || i.is_union() {
222             // FIXME(eddyb) is this `doc(hidden)` check needed?
223             if !self.cx.tcx.is_doc_hidden(i.item_id.expect_def_id()) {
224                 self.impls
225                     .extend(get_auto_trait_and_blanket_impls(self.cx, i.item_id.expect_def_id()));
226             }
227         }
228
229         self.visit_item_recur(i)
230     }
231 }
232
233 #[derive(Default)]
234 struct ItemCollector {
235     items: FxHashSet<ItemId>,
236 }
237
238 impl ItemCollector {
239     fn new() -> Self {
240         Self::default()
241     }
242 }
243
244 impl DocVisitor for ItemCollector {
245     fn visit_item(&mut self, i: &Item) {
246         self.items.insert(i.item_id);
247
248         self.visit_item_recur(i)
249     }
250 }
251
252 struct BadImplStripper<'a> {
253     prims: FxHashSet<PrimitiveType>,
254     items: FxHashSet<ItemId>,
255     cache: &'a Cache,
256 }
257
258 impl<'a> BadImplStripper<'a> {
259     fn keep_impl(&self, ty: &Type, is_deref: bool) -> bool {
260         if let Generic(_) = ty {
261             // keep impls made on generics
262             true
263         } else if let Some(prim) = ty.primitive_type() {
264             self.prims.contains(&prim)
265         } else if let Some(did) = ty.def_id(self.cache) {
266             is_deref || self.keep_impl_with_def_id(did.into())
267         } else {
268             false
269         }
270     }
271
272     fn keep_impl_with_def_id(&self, item_id: ItemId) -> bool {
273         self.items.contains(&item_id)
274     }
275 }