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