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