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