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