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