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