]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/clean/inline.rs
Rollup merge of #99036 - TaKO8Ki:fix-test-for-88138, r=compiler-errors
[rust.git] / src / librustdoc / clean / inline.rs
1 //! Support for inlining external documentation into the current AST.
2
3 use std::iter::once;
4 use std::sync::Arc;
5
6 use rustc_ast as ast;
7 use rustc_data_structures::fx::FxHashSet;
8 use rustc_data_structures::thin_vec::ThinVec;
9 use rustc_hir as hir;
10 use rustc_hir::def::{DefKind, Res};
11 use rustc_hir::def_id::DefId;
12 use rustc_hir::Mutability;
13 use rustc_metadata::creader::{CStore, LoadedMacro};
14 use rustc_middle::ty::{self, TyCtxt};
15 use rustc_span::hygiene::MacroKind;
16 use rustc_span::symbol::{kw, sym, Symbol};
17
18 use crate::clean::{
19     self, clean_fn_decl_from_did_and_sig, clean_ty_generics, utils, Attributes, AttributesExt,
20     Clean, ImplKind, ItemId, Type, Visibility,
21 };
22 use crate::core::DocContext;
23 use crate::formats::item_type::ItemType;
24
25 type Attrs<'hir> = &'hir [ast::Attribute];
26
27 /// Attempt to inline a definition into this AST.
28 ///
29 /// This function will fetch the definition specified, and if it is
30 /// from another crate it will attempt to inline the documentation
31 /// from the other crate into this crate.
32 ///
33 /// This is primarily used for `pub use` statements which are, in general,
34 /// implementation details. Inlining the documentation should help provide a
35 /// better experience when reading the documentation in this use case.
36 ///
37 /// The returned value is `None` if the definition could not be inlined,
38 /// and `Some` of a vector of items if it was successfully expanded.
39 ///
40 /// `parent_module` refers to the parent of the *re-export*, not the original item.
41 pub(crate) fn try_inline(
42     cx: &mut DocContext<'_>,
43     parent_module: DefId,
44     import_def_id: Option<DefId>,
45     res: Res,
46     name: Symbol,
47     attrs: Option<Attrs<'_>>,
48     visited: &mut FxHashSet<DefId>,
49 ) -> Option<Vec<clean::Item>> {
50     let did = res.opt_def_id()?;
51     if did.is_local() {
52         return None;
53     }
54     let mut ret = Vec::new();
55
56     debug!("attrs={:?}", attrs);
57     let attrs_clone = attrs;
58
59     let kind = match res {
60         Res::Def(DefKind::Trait, did) => {
61             record_extern_fqn(cx, did, ItemType::Trait);
62             build_impls(cx, Some(parent_module), did, attrs, &mut ret);
63             clean::TraitItem(build_external_trait(cx, did))
64         }
65         Res::Def(DefKind::Fn, did) => {
66             record_extern_fqn(cx, did, ItemType::Function);
67             clean::FunctionItem(build_external_function(cx, did))
68         }
69         Res::Def(DefKind::Struct, did) => {
70             record_extern_fqn(cx, did, ItemType::Struct);
71             build_impls(cx, Some(parent_module), did, attrs, &mut ret);
72             clean::StructItem(build_struct(cx, did))
73         }
74         Res::Def(DefKind::Union, did) => {
75             record_extern_fqn(cx, did, ItemType::Union);
76             build_impls(cx, Some(parent_module), did, attrs, &mut ret);
77             clean::UnionItem(build_union(cx, did))
78         }
79         Res::Def(DefKind::TyAlias, did) => {
80             record_extern_fqn(cx, did, ItemType::Typedef);
81             build_impls(cx, Some(parent_module), did, attrs, &mut ret);
82             clean::TypedefItem(build_type_alias(cx, did))
83         }
84         Res::Def(DefKind::Enum, did) => {
85             record_extern_fqn(cx, did, ItemType::Enum);
86             build_impls(cx, Some(parent_module), did, attrs, &mut ret);
87             clean::EnumItem(build_enum(cx, did))
88         }
89         Res::Def(DefKind::ForeignTy, did) => {
90             record_extern_fqn(cx, did, ItemType::ForeignType);
91             build_impls(cx, Some(parent_module), did, attrs, &mut ret);
92             clean::ForeignTypeItem
93         }
94         // Never inline enum variants but leave them shown as re-exports.
95         Res::Def(DefKind::Variant, _) => return None,
96         // Assume that enum variants and struct types are re-exported next to
97         // their constructors.
98         Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) => return Some(Vec::new()),
99         Res::Def(DefKind::Mod, did) => {
100             record_extern_fqn(cx, did, ItemType::Module);
101             clean::ModuleItem(build_module(cx, did, visited))
102         }
103         Res::Def(DefKind::Static(_), did) => {
104             record_extern_fqn(cx, did, ItemType::Static);
105             clean::StaticItem(build_static(cx, did, cx.tcx.is_mutable_static(did)))
106         }
107         Res::Def(DefKind::Const, did) => {
108             record_extern_fqn(cx, did, ItemType::Constant);
109             clean::ConstantItem(build_const(cx, did))
110         }
111         Res::Def(DefKind::Macro(kind), did) => {
112             let mac = build_macro(cx, did, name, import_def_id);
113
114             let type_kind = match kind {
115                 MacroKind::Bang => ItemType::Macro,
116                 MacroKind::Attr => ItemType::ProcAttribute,
117                 MacroKind::Derive => ItemType::ProcDerive,
118             };
119             record_extern_fqn(cx, did, type_kind);
120             mac
121         }
122         _ => return None,
123     };
124
125     let (attrs, cfg) = merge_attrs(cx, Some(parent_module), load_attrs(cx, did), attrs_clone);
126     cx.inlined.insert(did.into());
127     let mut item = clean::Item::from_def_id_and_attrs_and_parts(
128         did,
129         Some(name),
130         kind,
131         Box::new(attrs),
132         cx,
133         cfg,
134     );
135     if let Some(import_def_id) = import_def_id {
136         // The visibility needs to reflect the one from the reexport and not from the "source" DefId.
137         item.visibility = cx.tcx.visibility(import_def_id).clean(cx);
138     }
139     ret.push(item);
140     Some(ret)
141 }
142
143 pub(crate) fn try_inline_glob(
144     cx: &mut DocContext<'_>,
145     res: Res,
146     visited: &mut FxHashSet<DefId>,
147 ) -> Option<Vec<clean::Item>> {
148     let did = res.opt_def_id()?;
149     if did.is_local() {
150         return None;
151     }
152
153     match res {
154         Res::Def(DefKind::Mod, did) => {
155             let m = build_module(cx, did, visited);
156             Some(m.items)
157         }
158         // glob imports on things like enums aren't inlined even for local exports, so just bail
159         _ => None,
160     }
161 }
162
163 pub(crate) fn load_attrs<'hir>(cx: &DocContext<'hir>, did: DefId) -> Attrs<'hir> {
164     cx.tcx.get_attrs_unchecked(did)
165 }
166
167 /// Record an external fully qualified name in the external_paths cache.
168 ///
169 /// These names are used later on by HTML rendering to generate things like
170 /// source links back to the original item.
171 pub(crate) fn record_extern_fqn(cx: &mut DocContext<'_>, did: DefId, kind: ItemType) {
172     let crate_name = cx.tcx.crate_name(did.krate);
173
174     let relative =
175         cx.tcx.def_path(did).data.into_iter().filter_map(|elem| elem.data.get_opt_name());
176     let fqn = if let ItemType::Macro = kind {
177         // Check to see if it is a macro 2.0 or built-in macro
178         if matches!(
179             CStore::from_tcx(cx.tcx).load_macro_untracked(did, cx.sess()),
180             LoadedMacro::MacroDef(def, _)
181                 if matches!(&def.kind, ast::ItemKind::MacroDef(ast_def)
182                     if !ast_def.macro_rules)
183         ) {
184             once(crate_name).chain(relative).collect()
185         } else {
186             vec![crate_name, relative.last().expect("relative was empty")]
187         }
188     } else {
189         once(crate_name).chain(relative).collect()
190     };
191
192     if did.is_local() {
193         cx.cache.exact_paths.insert(did, fqn);
194     } else {
195         cx.cache.external_paths.insert(did, (fqn, kind));
196     }
197 }
198
199 pub(crate) fn build_external_trait(cx: &mut DocContext<'_>, did: DefId) -> clean::Trait {
200     let trait_items = cx
201         .tcx
202         .associated_items(did)
203         .in_definition_order()
204         .map(|item| {
205             // When building an external trait, the cleaned trait will have all items public,
206             // which causes methods to have a `pub` prefix, which is invalid since items in traits
207             // can not have a visibility prefix. Thus we override the visibility here manually.
208             // See https://github.com/rust-lang/rust/issues/81274
209             clean::Item { visibility: Visibility::Inherited, ..item.clean(cx) }
210         })
211         .collect();
212
213     let predicates = cx.tcx.predicates_of(did);
214     let generics = clean_ty_generics(cx, cx.tcx.generics_of(did), predicates);
215     let generics = filter_non_trait_generics(did, generics);
216     let (generics, supertrait_bounds) = separate_supertrait_bounds(generics);
217     let is_auto = cx.tcx.trait_is_auto(did);
218     clean::Trait {
219         unsafety: cx.tcx.trait_def(did).unsafety,
220         generics,
221         items: trait_items,
222         bounds: supertrait_bounds,
223         is_auto,
224     }
225 }
226
227 fn build_external_function<'tcx>(cx: &mut DocContext<'tcx>, did: DefId) -> clean::Function {
228     let sig = cx.tcx.fn_sig(did);
229
230     let predicates = cx.tcx.predicates_of(did);
231     let (generics, decl) = clean::enter_impl_trait(cx, |cx| {
232         // NOTE: generics need to be cleaned before the decl!
233         let generics = clean_ty_generics(cx, cx.tcx.generics_of(did), predicates);
234         let decl = clean_fn_decl_from_did_and_sig(cx, Some(did), sig);
235         (generics, decl)
236     });
237     clean::Function { decl, generics }
238 }
239
240 fn build_enum(cx: &mut DocContext<'_>, did: DefId) -> clean::Enum {
241     let predicates = cx.tcx.explicit_predicates_of(did);
242
243     clean::Enum {
244         generics: clean_ty_generics(cx, cx.tcx.generics_of(did), predicates),
245         variants: cx.tcx.adt_def(did).variants().iter().map(|v| v.clean(cx)).collect(),
246     }
247 }
248
249 fn build_struct(cx: &mut DocContext<'_>, did: DefId) -> clean::Struct {
250     let predicates = cx.tcx.explicit_predicates_of(did);
251     let variant = cx.tcx.adt_def(did).non_enum_variant();
252
253     clean::Struct {
254         struct_type: variant.ctor_kind,
255         generics: clean_ty_generics(cx, cx.tcx.generics_of(did), predicates),
256         fields: variant.fields.iter().map(|x| x.clean(cx)).collect(),
257     }
258 }
259
260 fn build_union(cx: &mut DocContext<'_>, did: DefId) -> clean::Union {
261     let predicates = cx.tcx.explicit_predicates_of(did);
262     let variant = cx.tcx.adt_def(did).non_enum_variant();
263
264     let generics = clean_ty_generics(cx, cx.tcx.generics_of(did), predicates);
265     let fields = variant.fields.iter().map(|x| x.clean(cx)).collect();
266     clean::Union { generics, fields }
267 }
268
269 fn build_type_alias(cx: &mut DocContext<'_>, did: DefId) -> clean::Typedef {
270     let predicates = cx.tcx.explicit_predicates_of(did);
271     let type_ = cx.tcx.type_of(did).clean(cx);
272
273     clean::Typedef {
274         type_,
275         generics: clean_ty_generics(cx, cx.tcx.generics_of(did), predicates),
276         item_type: None,
277     }
278 }
279
280 /// Builds all inherent implementations of an ADT (struct/union/enum) or Trait item/path/reexport.
281 pub(crate) fn build_impls(
282     cx: &mut DocContext<'_>,
283     parent_module: Option<DefId>,
284     did: DefId,
285     attrs: Option<Attrs<'_>>,
286     ret: &mut Vec<clean::Item>,
287 ) {
288     let _prof_timer = cx.tcx.sess.prof.generic_activity("build_inherent_impls");
289     let tcx = cx.tcx;
290
291     // for each implementation of an item represented by `did`, build the clean::Item for that impl
292     for &did in tcx.inherent_impls(did).iter() {
293         build_impl(cx, parent_module, did, attrs, ret);
294     }
295 }
296
297 /// `parent_module` refers to the parent of the re-export, not the original item
298 fn merge_attrs(
299     cx: &mut DocContext<'_>,
300     parent_module: Option<DefId>,
301     old_attrs: Attrs<'_>,
302     new_attrs: Option<Attrs<'_>>,
303 ) -> (clean::Attributes, Option<Arc<clean::cfg::Cfg>>) {
304     // NOTE: If we have additional attributes (from a re-export),
305     // always insert them first. This ensure that re-export
306     // doc comments show up before the original doc comments
307     // when we render them.
308     if let Some(inner) = new_attrs {
309         let mut both = inner.to_vec();
310         both.extend_from_slice(old_attrs);
311         (
312             if let Some(new_id) = parent_module {
313                 Attributes::from_ast(old_attrs, Some((inner, new_id)))
314             } else {
315                 Attributes::from_ast(&both, None)
316             },
317             both.cfg(cx.tcx, &cx.cache.hidden_cfg),
318         )
319     } else {
320         (old_attrs.clean(cx), old_attrs.cfg(cx.tcx, &cx.cache.hidden_cfg))
321     }
322 }
323
324 /// Inline an `impl`, inherent or of a trait. The `did` must be for an `impl`.
325 pub(crate) fn build_impl(
326     cx: &mut DocContext<'_>,
327     parent_module: Option<DefId>,
328     did: DefId,
329     attrs: Option<Attrs<'_>>,
330     ret: &mut Vec<clean::Item>,
331 ) {
332     if !cx.inlined.insert(did.into()) {
333         return;
334     }
335
336     let _prof_timer = cx.tcx.sess.prof.generic_activity("build_impl");
337
338     let tcx = cx.tcx;
339     let associated_trait = tcx.impl_trait_ref(did);
340
341     // Only inline impl if the implemented trait is
342     // reachable in rustdoc generated documentation
343     if !did.is_local() {
344         if let Some(traitref) = associated_trait {
345             let did = traitref.def_id;
346             if !cx.cache.access_levels.is_public(did) {
347                 return;
348             }
349
350             if let Some(stab) = tcx.lookup_stability(did) {
351                 if stab.is_unstable() && stab.feature == sym::rustc_private {
352                     return;
353                 }
354             }
355         }
356     }
357
358     let impl_item = match did.as_local() {
359         Some(did) => match &tcx.hir().expect_item(did).kind {
360             hir::ItemKind::Impl(impl_) => Some(impl_),
361             _ => panic!("`DefID` passed to `build_impl` is not an `impl"),
362         },
363         None => None,
364     };
365
366     let for_ = match &impl_item {
367         Some(impl_) => impl_.self_ty.clean(cx),
368         None => tcx.type_of(did).clean(cx),
369     };
370
371     // Only inline impl if the implementing type is
372     // reachable in rustdoc generated documentation
373     if !did.is_local() {
374         if let Some(did) = for_.def_id(&cx.cache) {
375             if !cx.cache.access_levels.is_public(did) {
376                 return;
377             }
378
379             if let Some(stab) = tcx.lookup_stability(did) {
380                 if stab.is_unstable() && stab.feature == sym::rustc_private {
381                     return;
382                 }
383             }
384         }
385     }
386
387     let document_hidden = cx.render_options.document_hidden;
388     let predicates = tcx.explicit_predicates_of(did);
389     let (trait_items, generics) = match impl_item {
390         Some(impl_) => (
391             impl_
392                 .items
393                 .iter()
394                 .map(|item| tcx.hir().impl_item(item.id))
395                 .filter(|item| {
396                     // Filter out impl items whose corresponding trait item has `doc(hidden)`
397                     // not to document such impl items.
398                     // For inherent impls, we don't do any filtering, because that's already done in strip_hidden.rs.
399
400                     // When `--document-hidden-items` is passed, we don't
401                     // do any filtering, too.
402                     if document_hidden {
403                         return true;
404                     }
405                     if let Some(associated_trait) = associated_trait {
406                         let assoc_kind = match item.kind {
407                             hir::ImplItemKind::Const(..) => ty::AssocKind::Const,
408                             hir::ImplItemKind::Fn(..) => ty::AssocKind::Fn,
409                             hir::ImplItemKind::TyAlias(..) => ty::AssocKind::Type,
410                         };
411                         let trait_item = tcx
412                             .associated_items(associated_trait.def_id)
413                             .find_by_name_and_kind(
414                                 tcx,
415                                 item.ident,
416                                 assoc_kind,
417                                 associated_trait.def_id,
418                             )
419                             .unwrap(); // SAFETY: For all impl items there exists trait item that has the same name.
420                         !tcx.is_doc_hidden(trait_item.def_id)
421                     } else {
422                         true
423                     }
424                 })
425                 .map(|item| item.clean(cx))
426                 .collect::<Vec<_>>(),
427             impl_.generics.clean(cx),
428         ),
429         None => (
430             tcx.associated_items(did)
431                 .in_definition_order()
432                 .filter(|item| {
433                     // If this is a trait impl, filter out associated items whose corresponding item
434                     // in the associated trait is marked `doc(hidden)`.
435                     // If this is an inherent impl, filter out private associated items.
436                     if let Some(associated_trait) = associated_trait {
437                         let trait_item = tcx
438                             .associated_items(associated_trait.def_id)
439                             .find_by_name_and_kind(
440                                 tcx,
441                                 item.ident(tcx),
442                                 item.kind,
443                                 associated_trait.def_id,
444                             )
445                             .unwrap(); // corresponding associated item has to exist
446                         !tcx.is_doc_hidden(trait_item.def_id)
447                     } else {
448                         item.vis.is_public()
449                     }
450                 })
451                 .map(|item| item.clean(cx))
452                 .collect::<Vec<_>>(),
453             clean::enter_impl_trait(cx, |cx| {
454                 clean_ty_generics(cx, tcx.generics_of(did), predicates)
455             }),
456         ),
457     };
458     let polarity = tcx.impl_polarity(did);
459     let trait_ = associated_trait.map(|t| t.clean(cx));
460     if trait_.as_ref().map(|t| t.def_id()) == tcx.lang_items().deref_trait() {
461         super::build_deref_target_impls(cx, &trait_items, ret);
462     }
463
464     // Return if the trait itself or any types of the generic parameters are doc(hidden).
465     let mut stack: Vec<&Type> = vec![&for_];
466
467     if let Some(did) = trait_.as_ref().map(|t| t.def_id()) {
468         if tcx.is_doc_hidden(did) {
469             return;
470         }
471     }
472     if let Some(generics) = trait_.as_ref().and_then(|t| t.generics()) {
473         stack.extend(generics);
474     }
475
476     while let Some(ty) = stack.pop() {
477         if let Some(did) = ty.def_id(&cx.cache) {
478             if tcx.is_doc_hidden(did) {
479                 return;
480             }
481         }
482         if let Some(generics) = ty.generics() {
483             stack.extend(generics);
484         }
485     }
486
487     if let Some(did) = trait_.as_ref().map(|t| t.def_id()) {
488         record_extern_trait(cx, did);
489     }
490
491     let (merged_attrs, cfg) = merge_attrs(cx, parent_module, load_attrs(cx, did), attrs);
492     trace!("merged_attrs={:?}", merged_attrs);
493
494     trace!(
495         "build_impl: impl {:?} for {:?}",
496         trait_.as_ref().map(|t| t.def_id()),
497         for_.def_id(&cx.cache)
498     );
499     ret.push(clean::Item::from_def_id_and_attrs_and_parts(
500         did,
501         None,
502         clean::ImplItem(clean::Impl {
503             unsafety: hir::Unsafety::Normal,
504             generics,
505             trait_,
506             for_,
507             items: trait_items,
508             polarity,
509             kind: if utils::has_doc_flag(tcx, did, sym::tuple_variadic) {
510                 ImplKind::TupleVaradic
511             } else {
512                 ImplKind::Normal
513             },
514         }),
515         Box::new(merged_attrs),
516         cx,
517         cfg,
518     ));
519 }
520
521 fn build_module(
522     cx: &mut DocContext<'_>,
523     did: DefId,
524     visited: &mut FxHashSet<DefId>,
525 ) -> clean::Module {
526     let mut items = Vec::new();
527
528     // If we're re-exporting a re-export it may actually re-export something in
529     // two namespaces, so the target may be listed twice. Make sure we only
530     // visit each node at most once.
531     for &item in cx.tcx.module_children(did).iter() {
532         if item.vis.is_public() {
533             let res = item.res.expect_non_local();
534             if let Some(def_id) = res.mod_def_id() {
535                 if did == def_id || !visited.insert(def_id) {
536                     continue;
537                 }
538             }
539             if let Res::PrimTy(p) = res {
540                 // Primitive types can't be inlined so generate an import instead.
541                 let prim_ty = clean::PrimitiveType::from(p);
542                 items.push(clean::Item {
543                     name: None,
544                     attrs: Box::new(clean::Attributes::default()),
545                     item_id: ItemId::Primitive(prim_ty, did.krate),
546                     visibility: clean::Public,
547                     kind: box clean::ImportItem(clean::Import::new_simple(
548                         item.ident.name,
549                         clean::ImportSource {
550                             path: clean::Path {
551                                 res,
552                                 segments: vec![clean::PathSegment {
553                                     name: prim_ty.as_sym(),
554                                     args: clean::GenericArgs::AngleBracketed {
555                                         args: Default::default(),
556                                         bindings: ThinVec::new(),
557                                     },
558                                 }],
559                             },
560                             did: None,
561                         },
562                         true,
563                     )),
564                     cfg: None,
565                 });
566             } else if let Some(i) = try_inline(cx, did, None, res, item.ident.name, None, visited) {
567                 items.extend(i)
568             }
569         }
570     }
571
572     let span = clean::Span::new(cx.tcx.def_span(did));
573     clean::Module { items, span }
574 }
575
576 pub(crate) fn print_inlined_const(tcx: TyCtxt<'_>, did: DefId) -> String {
577     if let Some(did) = did.as_local() {
578         let hir_id = tcx.hir().local_def_id_to_hir_id(did);
579         rustc_hir_pretty::id_to_string(&tcx.hir(), hir_id)
580     } else {
581         tcx.rendered_const(did).clone()
582     }
583 }
584
585 fn build_const(cx: &mut DocContext<'_>, def_id: DefId) -> clean::Constant {
586     clean::Constant {
587         type_: cx.tcx.type_of(def_id).clean(cx),
588         kind: clean::ConstantKind::Extern { def_id },
589     }
590 }
591
592 fn build_static(cx: &mut DocContext<'_>, did: DefId, mutable: bool) -> clean::Static {
593     clean::Static {
594         type_: cx.tcx.type_of(did).clean(cx),
595         mutability: if mutable { Mutability::Mut } else { Mutability::Not },
596         expr: None,
597     }
598 }
599
600 fn build_macro(
601     cx: &mut DocContext<'_>,
602     def_id: DefId,
603     name: Symbol,
604     import_def_id: Option<DefId>,
605 ) -> clean::ItemKind {
606     match CStore::from_tcx(cx.tcx).load_macro_untracked(def_id, cx.sess()) {
607         LoadedMacro::MacroDef(item_def, _) => {
608             if let ast::ItemKind::MacroDef(ref def) = item_def.kind {
609                 let vis = cx.tcx.visibility(import_def_id.unwrap_or(def_id)).clean(cx);
610                 clean::MacroItem(clean::Macro {
611                     source: utils::display_macro_source(cx, name, def, def_id, vis),
612                 })
613             } else {
614                 unreachable!()
615             }
616         }
617         LoadedMacro::ProcMacro(ext) => clean::ProcMacroItem(clean::ProcMacro {
618             kind: ext.macro_kind(),
619             helpers: ext.helper_attrs,
620         }),
621     }
622 }
623
624 /// A trait's generics clause actually contains all of the predicates for all of
625 /// its associated types as well. We specifically move these clauses to the
626 /// associated types instead when displaying, so when we're generating the
627 /// generics for the trait itself we need to be sure to remove them.
628 /// We also need to remove the implied "recursive" Self: Trait bound.
629 ///
630 /// The inverse of this filtering logic can be found in the `Clean`
631 /// implementation for `AssociatedType`
632 fn filter_non_trait_generics(trait_did: DefId, mut g: clean::Generics) -> clean::Generics {
633     for pred in &mut g.where_predicates {
634         match *pred {
635             clean::WherePredicate::BoundPredicate {
636                 ty: clean::Generic(ref s),
637                 ref mut bounds,
638                 ..
639             } if *s == kw::SelfUpper => {
640                 bounds.retain(|bound| match bound {
641                     clean::GenericBound::TraitBound(clean::PolyTrait { trait_, .. }, _) => {
642                         trait_.def_id() != trait_did
643                     }
644                     _ => true,
645                 });
646             }
647             _ => {}
648         }
649     }
650
651     g.where_predicates.retain(|pred| match pred {
652         clean::WherePredicate::BoundPredicate {
653             ty: clean::QPath { self_type: box clean::Generic(ref s), trait_, .. },
654             bounds,
655             ..
656         } => !(bounds.is_empty() || *s == kw::SelfUpper && trait_.def_id() == trait_did),
657         _ => true,
658     });
659     g
660 }
661
662 /// Supertrait bounds for a trait are also listed in the generics coming from
663 /// the metadata for a crate, so we want to separate those out and create a new
664 /// list of explicit supertrait bounds to render nicely.
665 fn separate_supertrait_bounds(
666     mut g: clean::Generics,
667 ) -> (clean::Generics, Vec<clean::GenericBound>) {
668     let mut ty_bounds = Vec::new();
669     g.where_predicates.retain(|pred| match *pred {
670         clean::WherePredicate::BoundPredicate { ty: clean::Generic(ref s), ref bounds, .. }
671             if *s == kw::SelfUpper =>
672         {
673             ty_bounds.extend(bounds.iter().cloned());
674             false
675         }
676         _ => true,
677     });
678     (g, ty_bounds)
679 }
680
681 pub(crate) fn record_extern_trait(cx: &mut DocContext<'_>, did: DefId) {
682     if did.is_local() {
683         return;
684     }
685
686     {
687         if cx.external_traits.borrow().contains_key(&did) || cx.active_extern_traits.contains(&did)
688         {
689             return;
690         }
691     }
692
693     {
694         cx.active_extern_traits.insert(did);
695     }
696
697     debug!("record_extern_trait: {:?}", did);
698     let trait_ = build_external_trait(cx, did);
699
700     let trait_ = clean::TraitWithExtraInfo {
701         trait_,
702         is_notable: clean::utils::has_doc_flag(cx.tcx, did, sym::notable_trait),
703     };
704     cx.external_traits.borrow_mut().insert(did, trait_);
705     cx.active_extern_traits.remove(&did);
706 }