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