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