1 //! Support for inlining external documentation into the current AST.
6 use rustc_data_structures::fx::FxHashSet;
8 use rustc_hir::def::{CtorKind, DefKind, Res};
9 use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX};
10 use rustc_hir::Mutability;
11 use rustc_metadata::creader::LoadedMacro;
13 use rustc_mir::const_eval::is_min_const_fn;
14 use rustc_span::hygiene::MacroKind;
15 use rustc_span::symbol::{sym, Symbol};
18 use crate::clean::{self, GetDefId, ToSource, TypeKind};
19 use crate::core::DocContext;
24 type Attrs<'hir> = rustc_middle::ty::Attributes<'hir>;
26 /// Attempt to inline a definition into this AST.
28 /// This function will fetch the definition specified, and if it is
29 /// from another crate it will attempt to inline the documentation
30 /// from the other crate into this crate.
32 /// This is primarily used for `pub use` statements which are, in general,
33 /// implementation details. Inlining the documentation should help provide a
34 /// better experience when reading the documentation in this use case.
36 /// The returned value is `None` if the definition could not be inlined,
37 /// and `Some` of a vector of items if it was successfully expanded.
42 attrs: Option<Attrs<'_>>,
43 visited: &mut FxHashSet<DefId>,
44 ) -> Option<Vec<clean::Item>> {
45 let did = res.opt_def_id()?;
49 let mut ret = Vec::new();
51 let attrs_clone = attrs;
53 let inner = match res {
54 Res::Def(DefKind::Trait, did) => {
55 record_extern_fqn(cx, did, clean::TypeKind::Trait);
56 ret.extend(build_impls(cx, did, attrs));
57 clean::TraitItem(build_external_trait(cx, did))
59 Res::Def(DefKind::Fn, did) => {
60 record_extern_fqn(cx, did, clean::TypeKind::Function);
61 clean::FunctionItem(build_external_function(cx, did))
63 Res::Def(DefKind::Struct, did) => {
64 record_extern_fqn(cx, did, clean::TypeKind::Struct);
65 ret.extend(build_impls(cx, did, attrs));
66 clean::StructItem(build_struct(cx, did))
68 Res::Def(DefKind::Union, did) => {
69 record_extern_fqn(cx, did, clean::TypeKind::Union);
70 ret.extend(build_impls(cx, did, attrs));
71 clean::UnionItem(build_union(cx, did))
73 Res::Def(DefKind::TyAlias, did) => {
74 record_extern_fqn(cx, did, clean::TypeKind::Typedef);
75 ret.extend(build_impls(cx, did, attrs));
76 clean::TypedefItem(build_type_alias(cx, did), false)
78 Res::Def(DefKind::Enum, did) => {
79 record_extern_fqn(cx, did, clean::TypeKind::Enum);
80 ret.extend(build_impls(cx, did, attrs));
81 clean::EnumItem(build_enum(cx, did))
83 Res::Def(DefKind::ForeignTy, did) => {
84 record_extern_fqn(cx, did, clean::TypeKind::Foreign);
85 ret.extend(build_impls(cx, did, attrs));
86 clean::ForeignTypeItem
88 // Never inline enum variants but leave them shown as re-exports.
89 Res::Def(DefKind::Variant, _) => return None,
90 // Assume that enum variants and struct types are re-exported next to
91 // their constructors.
92 Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) => return Some(Vec::new()),
93 Res::Def(DefKind::Mod, did) => {
94 record_extern_fqn(cx, did, clean::TypeKind::Module);
95 clean::ModuleItem(build_module(cx, did, visited))
97 Res::Def(DefKind::Static, did) => {
98 record_extern_fqn(cx, did, clean::TypeKind::Static);
99 clean::StaticItem(build_static(cx, did, cx.tcx.is_mutable_static(did)))
101 Res::Def(DefKind::Const, did) => {
102 record_extern_fqn(cx, did, clean::TypeKind::Const);
103 clean::ConstantItem(build_const(cx, did))
105 Res::Def(DefKind::Macro(kind), did) => {
106 let mac = build_macro(cx, did, name);
108 let type_kind = match kind {
109 MacroKind::Bang => TypeKind::Macro,
110 MacroKind::Attr => TypeKind::Attr,
111 MacroKind::Derive => TypeKind::Derive,
113 record_extern_fqn(cx, did, type_kind);
119 let target_attrs = load_attrs(cx, did);
120 let attrs = merge_attrs(cx, target_attrs, attrs_clone);
122 cx.renderinfo.borrow_mut().inlined.insert(did);
123 ret.push(clean::Item {
124 source: cx.tcx.def_span(did).clean(cx),
125 name: Some(name.clean(cx)),
128 visibility: clean::Public,
129 stability: cx.tcx.lookup_stability(did).clean(cx),
130 deprecation: cx.tcx.lookup_deprecation(did).clean(cx),
136 pub fn try_inline_glob(
139 visited: &mut FxHashSet<DefId>,
140 ) -> Option<Vec<clean::Item>> {
144 let did = res.def_id();
150 Res::Def(DefKind::Mod, did) => {
151 let m = build_module(cx, did, visited);
154 // glob imports on things like enums aren't inlined even for local exports, so just bail
159 pub fn load_attrs<'hir>(cx: &DocContext<'hir>, did: DefId) -> Attrs<'hir> {
160 cx.tcx.get_attrs(did)
163 /// Record an external fully qualified name in the external_paths cache.
165 /// These names are used later on by HTML rendering to generate things like
166 /// source links back to the original item.
167 pub fn record_extern_fqn(cx: &DocContext<'_>, did: DefId, kind: clean::TypeKind) {
168 let crate_name = cx.tcx.crate_name(did.krate).to_string();
170 let relative = cx.tcx.def_path(did).data.into_iter().filter_map(|elem| {
171 // extern blocks have an empty name
172 let s = elem.data.to_string();
173 if !s.is_empty() { Some(s) } else { None }
175 let fqn = if let clean::TypeKind::Macro = kind {
176 vec![crate_name, relative.last().expect("relative was empty")]
178 once(crate_name).chain(relative).collect()
182 cx.renderinfo.borrow_mut().exact_paths.insert(did, fqn);
184 cx.renderinfo.borrow_mut().external_paths.insert(did, (fqn, kind));
188 pub fn build_external_trait(cx: &DocContext<'_>, did: DefId) -> clean::Trait {
190 cx.tcx.associated_items(did).in_definition_order().map(|item| item.clean(cx)).collect();
192 let auto_trait = cx.tcx.trait_def(did).has_auto_impl;
193 let predicates = cx.tcx.predicates_of(did);
194 let generics = (cx.tcx.generics_of(did), predicates).clean(cx);
195 let generics = filter_non_trait_generics(did, generics);
196 let (generics, supertrait_bounds) = separate_supertrait_bounds(generics);
197 let is_spotlight = load_attrs(cx, did).clean(cx).has_doc_flag(sym::spotlight);
198 let is_auto = cx.tcx.trait_is_auto(did);
201 unsafety: cx.tcx.trait_def(did).unsafety,
204 bounds: supertrait_bounds,
210 fn build_external_function(cx: &DocContext<'_>, did: DefId) -> clean::Function {
211 let sig = cx.tcx.fn_sig(did);
214 if is_min_const_fn(cx.tcx, did) { hir::Constness::Const } else { hir::Constness::NotConst };
215 let asyncness = cx.tcx.asyncness(did);
216 let predicates = cx.tcx.predicates_of(did);
217 let (generics, decl) = clean::enter_impl_trait(cx, || {
218 ((cx.tcx.generics_of(did), predicates).clean(cx), (did, sig).clean(cx))
220 let (all_types, ret_types) = clean::get_all_types(&generics, &decl, cx);
224 header: hir::FnHeader { unsafety: sig.unsafety(), abi: sig.abi(), constness, asyncness },
230 fn build_enum(cx: &DocContext<'_>, did: DefId) -> clean::Enum {
231 let predicates = cx.tcx.explicit_predicates_of(did);
234 generics: (cx.tcx.generics_of(did), predicates).clean(cx),
235 variants_stripped: false,
236 variants: cx.tcx.adt_def(did).variants.clean(cx),
240 fn build_struct(cx: &DocContext<'_>, did: DefId) -> clean::Struct {
241 let predicates = cx.tcx.explicit_predicates_of(did);
242 let variant = cx.tcx.adt_def(did).non_enum_variant();
245 struct_type: match variant.ctor_kind {
246 CtorKind::Fictive => doctree::Plain,
247 CtorKind::Fn => doctree::Tuple,
248 CtorKind::Const => doctree::Unit,
250 generics: (cx.tcx.generics_of(did), predicates).clean(cx),
251 fields: variant.fields.clean(cx),
252 fields_stripped: false,
256 fn build_union(cx: &DocContext<'_>, did: DefId) -> clean::Union {
257 let predicates = cx.tcx.explicit_predicates_of(did);
258 let variant = cx.tcx.adt_def(did).non_enum_variant();
261 struct_type: doctree::Plain,
262 generics: (cx.tcx.generics_of(did), predicates).clean(cx),
263 fields: variant.fields.clean(cx),
264 fields_stripped: false,
268 fn build_type_alias(cx: &DocContext<'_>, did: DefId) -> clean::Typedef {
269 let predicates = cx.tcx.explicit_predicates_of(did);
272 type_: cx.tcx.type_of(did).clean(cx),
273 generics: (cx.tcx.generics_of(did), predicates).clean(cx),
274 item_type: build_type_alias_type(cx, did),
278 fn build_type_alias_type(cx: &DocContext<'_>, did: DefId) -> Option<clean::Type> {
279 let type_ = cx.tcx.type_of(did).clean(cx);
280 type_.def_id().and_then(|did| build_ty(cx, did))
283 pub fn build_ty(cx: &DocContext<'_>, did: DefId) -> Option<clean::Type> {
284 match cx.tcx.def_kind(did) {
285 DefKind::Struct | DefKind::Union | DefKind::Enum | DefKind::Const | DefKind::Static => {
286 Some(cx.tcx.type_of(did).clean(cx))
288 DefKind::TyAlias => build_type_alias_type(cx, did),
293 pub fn build_impls(cx: &DocContext<'_>, did: DefId, attrs: Option<Attrs<'_>>) -> Vec<clean::Item> {
295 let mut impls = Vec::new();
297 for &did in tcx.inherent_impls(did).iter() {
298 build_impl(cx, did, attrs, &mut impls);
307 other_attrs: Option<Attrs<'_>>,
308 ) -> clean::Attributes {
309 let mut merged_attrs: Vec<ast::Attribute> = Vec::with_capacity(attrs.len());
310 // 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(a) = other_attrs {
315 merged_attrs.extend(a.iter().cloned());
317 merged_attrs.extend(attrs.to_vec());
318 merged_attrs.clean(cx)
324 attrs: Option<Attrs<'_>>,
325 ret: &mut Vec<clean::Item>,
327 if !cx.renderinfo.borrow_mut().inlined.insert(did) {
331 let attrs = merge_attrs(cx, load_attrs(cx, did), attrs);
334 let associated_trait = tcx.impl_trait_ref(did);
336 // Only inline impl if the implemented trait is
337 // reachable in rustdoc generated documentation
339 if let Some(traitref) = associated_trait {
340 if !cx.renderinfo.borrow().access_levels.is_public(traitref.def_id) {
345 // Skip foreign unstable traits from lists of trait implementations and
346 // such. This helps prevent dependencies of the standard library, for
347 // example, from getting documented as "traits `u32` implements" which
348 // isn't really too helpful.
349 if let Some(stab) = cx.tcx.lookup_stability(did) {
350 if stab.level.is_unstable() {
356 let for_ = if let Some(did) = did.as_local() {
357 let hir_id = tcx.hir().as_local_hir_id(did);
358 match tcx.hir().expect_item(hir_id).kind {
359 hir::ItemKind::Impl { self_ty, .. } => self_ty.clean(cx),
360 _ => panic!("did given to build_impl was not an impl"),
363 tcx.type_of(did).clean(cx)
366 // Only inline impl if the implementing type is
367 // reachable in rustdoc generated documentation
369 if let Some(did) = for_.def_id() {
370 if !cx.renderinfo.borrow().access_levels.is_public(did) {
376 let predicates = tcx.explicit_predicates_of(did);
377 let (trait_items, generics) = if let Some(did) = did.as_local() {
378 let hir_id = tcx.hir().as_local_hir_id(did);
379 match tcx.hir().expect_item(hir_id).kind {
380 hir::ItemKind::Impl { ref generics, ref items, .. } => (
381 items.iter().map(|item| tcx.hir().impl_item(item.id).clean(cx)).collect::<Vec<_>>(),
384 _ => panic!("did given to build_impl was not an impl"),
388 tcx.associated_items(did)
389 .in_definition_order()
391 if associated_trait.is_some() || item.vis == ty::Visibility::Public {
397 .collect::<Vec<_>>(),
398 clean::enter_impl_trait(cx, || (tcx.generics_of(did), predicates).clean(cx)),
401 let polarity = tcx.impl_polarity(did);
402 let trait_ = associated_trait.clean(cx).map(|bound| match bound {
403 clean::GenericBound::TraitBound(polyt, _) => polyt.trait_,
404 clean::GenericBound::Outlives(..) => unreachable!(),
406 if trait_.def_id() == tcx.lang_items().deref_trait() {
407 super::build_deref_target_impls(cx, &trait_items, ret);
409 if let Some(trait_did) = trait_.def_id() {
410 record_extern_trait(cx, trait_did);
413 let provided = trait_
415 .map(|did| tcx.provided_trait_methods(did).map(|meth| meth.ident.to_string()).collect())
416 .unwrap_or_default();
418 debug!("build_impl: impl {:?} for {:?}", trait_.def_id(), for_.def_id());
420 ret.push(clean::Item {
421 inner: clean::ImplItem(clean::Impl {
422 unsafety: hir::Unsafety::Normal,
424 provided_trait_methods: provided,
428 polarity: Some(polarity.clean(cx)),
432 source: tcx.def_span(did).clean(cx),
435 visibility: clean::Inherited,
436 stability: tcx.lookup_stability(did).clean(cx),
437 deprecation: tcx.lookup_deprecation(did).clean(cx),
442 fn build_module(cx: &DocContext<'_>, did: DefId, visited: &mut FxHashSet<DefId>) -> clean::Module {
443 let mut items = Vec::new();
444 fill_in(cx, did, &mut items, visited);
445 return clean::Module { items, is_crate: false };
450 items: &mut Vec<clean::Item>,
451 visited: &mut FxHashSet<DefId>,
453 // If we're re-exporting a re-export it may actually re-export something in
454 // two namespaces, so the target may be listed twice. Make sure we only
455 // visit each node at most once.
456 for &item in cx.tcx.item_children(did).iter() {
457 if item.vis == ty::Visibility::Public {
458 if let Some(def_id) = item.res.mod_def_id() {
459 if did == def_id || !visited.insert(def_id) {
463 if let Res::PrimTy(p) = item.res {
464 // Primitive types can't be inlined so generate an import instead.
465 items.push(clean::Item {
467 attrs: clean::Attributes::default(),
468 source: clean::Span::empty(),
469 def_id: DefId::local(CRATE_DEF_INDEX),
470 visibility: clean::Public,
473 inner: clean::ImportItem(clean::Import::Simple(
474 item.ident.to_string(),
475 clean::ImportSource {
479 segments: vec![clean::PathSegment {
480 name: clean::PrimitiveType::from(p).as_str().to_string(),
481 args: clean::GenericArgs::AngleBracketed {
483 bindings: Vec::new(),
491 } else if let Some(i) = try_inline(cx, item.res, item.ident.name, None, visited) {
499 pub fn print_inlined_const(cx: &DocContext<'_>, did: DefId) -> String {
500 if let Some(did) = did.as_local() {
501 let hir_id = cx.tcx.hir().as_local_hir_id(did);
502 rustc_hir_pretty::id_to_string(&cx.tcx.hir(), hir_id)
504 cx.tcx.rendered_const(did)
508 fn build_const(cx: &DocContext<'_>, did: DefId) -> clean::Constant {
510 type_: cx.tcx.type_of(did).clean(cx),
511 expr: print_inlined_const(cx, did),
512 value: clean::utils::print_evaluated_const(cx, did),
513 is_literal: did.as_local().map_or(false, |did| {
514 clean::utils::is_literal_expr(cx, cx.tcx.hir().as_local_hir_id(did))
519 fn build_static(cx: &DocContext<'_>, did: DefId, mutable: bool) -> clean::Static {
521 type_: cx.tcx.type_of(did).clean(cx),
522 mutability: if mutable { Mutability::Mut } else { Mutability::Not },
523 expr: "\n\n\n".to_string(), // trigger the "[definition]" links
527 fn build_macro(cx: &DocContext<'_>, did: DefId, name: Symbol) -> clean::ItemEnum {
528 let imported_from = cx.tcx.original_crate_name(did.krate);
529 match cx.enter_resolver(|r| r.cstore().load_macro_untracked(did, cx.sess())) {
530 LoadedMacro::MacroDef(def, _) => {
531 let matchers: Vec<Span> = if let ast::ItemKind::MacroDef(ref def) = def.kind {
532 let tts: Vec<_> = def.body.inner_tokens().into_trees().collect();
533 tts.chunks(4).map(|arm| arm[0].span()).collect()
538 let source = format!(
539 "macro_rules! {} {{\n{}}}",
543 .map(|span| { format!(" {} => {{ ... }};\n", span.to_src(cx)) })
547 clean::MacroItem(clean::Macro { source, imported_from: Some(imported_from).clean(cx) })
549 LoadedMacro::ProcMacro(ext) => clean::ProcMacroItem(clean::ProcMacro {
550 kind: ext.macro_kind(),
551 helpers: ext.helper_attrs.clean(cx),
556 /// A trait's generics clause actually contains all of the predicates for all of
557 /// its associated types as well. We specifically move these clauses to the
558 /// associated types instead when displaying, so when we're generating the
559 /// generics for the trait itself we need to be sure to remove them.
560 /// We also need to remove the implied "recursive" Self: Trait bound.
562 /// The inverse of this filtering logic can be found in the `Clean`
563 /// implementation for `AssociatedType`
564 fn filter_non_trait_generics(trait_did: DefId, mut g: clean::Generics) -> clean::Generics {
565 for pred in &mut g.where_predicates {
567 clean::WherePredicate::BoundPredicate { ty: clean::Generic(ref s), ref mut bounds }
570 bounds.retain(|bound| match *bound {
571 clean::GenericBound::TraitBound(
572 clean::PolyTrait { trait_: clean::ResolvedPath { did, .. }, .. },
574 ) => did != trait_did,
582 g.where_predicates.retain(|pred| match *pred {
583 clean::WherePredicate::BoundPredicate {
586 self_type: box clean::Generic(ref s),
587 trait_: box clean::ResolvedPath { did, .. },
591 } => !(bounds.is_empty() || *s == "Self" && did == trait_did),
597 /// Supertrait bounds for a trait are also listed in the generics coming from
598 /// the metadata for a crate, so we want to separate those out and create a new
599 /// list of explicit supertrait bounds to render nicely.
600 fn separate_supertrait_bounds(
601 mut g: clean::Generics,
602 ) -> (clean::Generics, Vec<clean::GenericBound>) {
603 let mut ty_bounds = Vec::new();
604 g.where_predicates.retain(|pred| match *pred {
605 clean::WherePredicate::BoundPredicate { ty: clean::Generic(ref s), ref bounds }
608 ty_bounds.extend(bounds.iter().cloned());
616 pub fn record_extern_trait(cx: &DocContext<'_>, did: DefId) {
622 if cx.external_traits.borrow().contains_key(&did)
623 || cx.active_extern_traits.borrow().contains(&did)
629 cx.active_extern_traits.borrow_mut().insert(did);
631 debug!("record_extern_trait: {:?}", did);
632 let trait_ = build_external_trait(cx, did);
634 cx.external_traits.borrow_mut().insert(did, trait_);
635 cx.active_extern_traits.borrow_mut().remove(&did);