]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/clean/inline.rs
Rollup merge of #85772 - luqmana:ignored-metadata, r=petrochenkov
[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_hir as hir;
9 use rustc_hir::def::{DefKind, Res};
10 use rustc_hir::def_id::DefId;
11 use rustc_hir::Mutability;
12 use rustc_metadata::creader::LoadedMacro;
13 use rustc_middle::ty::{self, TyCtxt};
14 use rustc_span::hygiene::MacroKind;
15 use rustc_span::symbol::{kw, sym, Symbol};
16 use rustc_span::Span;
17
18 use crate::clean::{self, Attributes, AttributesExt, FakeDefId, GetDefId, ToSource};
19 use crate::core::DocContext;
20 use crate::formats::item_type::ItemType;
21
22 use super::{Clean, Visibility};
23
24 type Attrs<'hir> = rustc_middle::ty::Attributes<'hir>;
25
26 /// Attempt to inline a definition into this AST.
27 ///
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.
31 ///
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.
35 ///
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.
38 ///
39 /// `parent_module` refers to the parent of the *re-export*, not the original item.
40 crate fn try_inline(
41     cx: &mut DocContext<'_>,
42     parent_module: DefId,
43     res: Res,
44     name: Symbol,
45     attrs: Option<Attrs<'_>>,
46     visited: &mut FxHashSet<DefId>,
47 ) -> Option<Vec<clean::Item>> {
48     let did = res.opt_def_id()?;
49     if did.is_local() {
50         return None;
51     }
52     let mut ret = Vec::new();
53
54     debug!("attrs={:?}", attrs);
55     let attrs_clone = attrs;
56
57     let kind = match res {
58         Res::Def(DefKind::Trait, did) => {
59             record_extern_fqn(cx, did, ItemType::Trait);
60             build_impls(cx, Some(parent_module), did, attrs, &mut ret);
61             clean::TraitItem(build_external_trait(cx, did))
62         }
63         Res::Def(DefKind::Fn, did) => {
64             record_extern_fqn(cx, did, ItemType::Function);
65             clean::FunctionItem(build_external_function(cx, did))
66         }
67         Res::Def(DefKind::Struct, did) => {
68             record_extern_fqn(cx, did, ItemType::Struct);
69             build_impls(cx, Some(parent_module), did, attrs, &mut ret);
70             clean::StructItem(build_struct(cx, did))
71         }
72         Res::Def(DefKind::Union, did) => {
73             record_extern_fqn(cx, did, ItemType::Union);
74             build_impls(cx, Some(parent_module), did, attrs, &mut ret);
75             clean::UnionItem(build_union(cx, did))
76         }
77         Res::Def(DefKind::TyAlias, did) => {
78             record_extern_fqn(cx, did, ItemType::Typedef);
79             build_impls(cx, Some(parent_module), did, attrs, &mut ret);
80             clean::TypedefItem(build_type_alias(cx, did), false)
81         }
82         Res::Def(DefKind::Enum, did) => {
83             record_extern_fqn(cx, did, ItemType::Enum);
84             build_impls(cx, Some(parent_module), did, attrs, &mut ret);
85             clean::EnumItem(build_enum(cx, did))
86         }
87         Res::Def(DefKind::ForeignTy, did) => {
88             record_extern_fqn(cx, did, ItemType::ForeignType);
89             build_impls(cx, Some(parent_module), did, attrs, &mut ret);
90             clean::ForeignTypeItem
91         }
92         // Never inline enum variants but leave them shown as re-exports.
93         Res::Def(DefKind::Variant, _) => return None,
94         // Assume that enum variants and struct types are re-exported next to
95         // their constructors.
96         Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) => return Some(Vec::new()),
97         Res::Def(DefKind::Mod, did) => {
98             record_extern_fqn(cx, did, ItemType::Module);
99             clean::ModuleItem(build_module(cx, did, visited))
100         }
101         Res::Def(DefKind::Static, did) => {
102             record_extern_fqn(cx, did, ItemType::Static);
103             clean::StaticItem(build_static(cx, did, cx.tcx.is_mutable_static(did)))
104         }
105         Res::Def(DefKind::Const, did) => {
106             record_extern_fqn(cx, did, ItemType::Constant);
107             clean::ConstantItem(build_const(cx, did))
108         }
109         Res::Def(DefKind::Macro(kind), did) => {
110             let mac = build_macro(cx, did, name);
111
112             let type_kind = match kind {
113                 MacroKind::Bang => ItemType::Macro,
114                 MacroKind::Attr => ItemType::ProcAttribute,
115                 MacroKind::Derive => ItemType::ProcDerive,
116             };
117             record_extern_fqn(cx, did, type_kind);
118             mac
119         }
120         _ => return None,
121     };
122
123     let (attrs, cfg) = merge_attrs(cx, Some(parent_module), load_attrs(cx, did), attrs_clone);
124     cx.inlined.insert(did.into());
125     ret.push(clean::Item::from_def_id_and_attrs_and_parts(
126         did,
127         Some(name),
128         kind,
129         box attrs,
130         cx,
131         cfg,
132     ));
133     Some(ret)
134 }
135
136 crate fn try_inline_glob(
137     cx: &mut DocContext<'_>,
138     res: Res,
139     visited: &mut FxHashSet<DefId>,
140 ) -> Option<Vec<clean::Item>> {
141     let did = res.opt_def_id()?;
142     if did.is_local() {
143         return None;
144     }
145
146     match res {
147         Res::Def(DefKind::Mod, did) => {
148             let m = build_module(cx, did, visited);
149             Some(m.items)
150         }
151         // glob imports on things like enums aren't inlined even for local exports, so just bail
152         _ => None,
153     }
154 }
155
156 crate fn load_attrs<'hir>(cx: &DocContext<'hir>, did: DefId) -> Attrs<'hir> {
157     cx.tcx.get_attrs(did)
158 }
159
160 /// Record an external fully qualified name in the external_paths cache.
161 ///
162 /// These names are used later on by HTML rendering to generate things like
163 /// source links back to the original item.
164 crate fn record_extern_fqn(cx: &mut DocContext<'_>, did: DefId, kind: ItemType) {
165     let crate_name = cx.tcx.crate_name(did.krate).to_string();
166
167     let relative = cx.tcx.def_path(did).data.into_iter().filter_map(|elem| {
168         // extern blocks have an empty name
169         let s = elem.data.to_string();
170         if !s.is_empty() { Some(s) } else { None }
171     });
172     let fqn = if let ItemType::Macro = kind {
173         // Check to see if it is a macro 2.0 or built-in macro
174         if matches!(
175             cx.enter_resolver(|r| r.cstore().load_macro_untracked(did, cx.sess())),
176             LoadedMacro::MacroDef(def, _)
177                 if matches!(&def.kind, ast::ItemKind::MacroDef(ast_def)
178                     if !ast_def.macro_rules)
179         ) {
180             once(crate_name).chain(relative).collect()
181         } else {
182             vec![crate_name, relative.last().expect("relative was empty")]
183         }
184     } else {
185         once(crate_name).chain(relative).collect()
186     };
187
188     if did.is_local() {
189         cx.cache.exact_paths.insert(did, fqn);
190     } else {
191         cx.cache.external_paths.insert(did, (fqn, kind));
192     }
193 }
194
195 crate fn build_external_trait(cx: &mut DocContext<'_>, did: DefId) -> clean::Trait {
196     let trait_items = cx
197         .tcx
198         .associated_items(did)
199         .in_definition_order()
200         .map(|item| {
201             // When building an external trait, the cleaned trait will have all items public,
202             // which causes methods to have a `pub` prefix, which is invalid since items in traits
203             // can not have a visibility prefix. Thus we override the visibility here manually.
204             // See https://github.com/rust-lang/rust/issues/81274
205             clean::Item { visibility: Visibility::Inherited, ..item.clean(cx) }
206         })
207         .collect();
208
209     let predicates = cx.tcx.predicates_of(did);
210     let generics = (cx.tcx.generics_of(did), predicates).clean(cx);
211     let generics = filter_non_trait_generics(did, generics);
212     let (generics, supertrait_bounds) = separate_supertrait_bounds(generics);
213     let is_auto = cx.tcx.trait_is_auto(did);
214     clean::Trait {
215         unsafety: cx.tcx.trait_def(did).unsafety,
216         generics,
217         items: trait_items,
218         bounds: supertrait_bounds,
219         is_auto,
220     }
221 }
222
223 fn build_external_function(cx: &mut DocContext<'_>, did: DefId) -> clean::Function {
224     let sig = cx.tcx.fn_sig(did);
225
226     let constness =
227         if cx.tcx.is_const_fn_raw(did) { hir::Constness::Const } else { hir::Constness::NotConst };
228     let asyncness = cx.tcx.asyncness(did);
229     let predicates = cx.tcx.predicates_of(did);
230     let (generics, decl) = clean::enter_impl_trait(cx, |cx| {
231         ((cx.tcx.generics_of(did), predicates).clean(cx), (did, sig).clean(cx))
232     });
233     clean::Function {
234         decl,
235         generics,
236         header: hir::FnHeader { unsafety: sig.unsafety(), abi: sig.abi(), constness, asyncness },
237     }
238 }
239
240 fn build_enum(cx: &mut DocContext<'_>, did: DefId) -> clean::Enum {
241     let predicates = cx.tcx.explicit_predicates_of(did);
242
243     clean::Enum {
244         generics: (cx.tcx.generics_of(did), predicates).clean(cx),
245         variants_stripped: false,
246         variants: cx.tcx.adt_def(did).variants.clean(cx),
247     }
248 }
249
250 fn build_struct(cx: &mut DocContext<'_>, did: DefId) -> clean::Struct {
251     let predicates = cx.tcx.explicit_predicates_of(did);
252     let variant = cx.tcx.adt_def(did).non_enum_variant();
253
254     clean::Struct {
255         struct_type: variant.ctor_kind,
256         generics: (cx.tcx.generics_of(did), predicates).clean(cx),
257         fields: variant.fields.clean(cx),
258         fields_stripped: false,
259     }
260 }
261
262 fn build_union(cx: &mut DocContext<'_>, did: DefId) -> clean::Union {
263     let predicates = cx.tcx.explicit_predicates_of(did);
264     let variant = cx.tcx.adt_def(did).non_enum_variant();
265
266     clean::Union {
267         generics: (cx.tcx.generics_of(did), predicates).clean(cx),
268         fields: variant.fields.clean(cx),
269         fields_stripped: false,
270     }
271 }
272
273 fn build_type_alias(cx: &mut DocContext<'_>, did: DefId) -> clean::Typedef {
274     let predicates = cx.tcx.explicit_predicates_of(did);
275     let type_ = cx.tcx.type_of(did).clean(cx);
276
277     clean::Typedef {
278         type_,
279         generics: (cx.tcx.generics_of(did), predicates).clean(cx),
280         item_type: None,
281     }
282 }
283
284 /// Builds all inherent implementations of an ADT (struct/union/enum) or Trait item/path/reexport.
285 crate fn build_impls(
286     cx: &mut DocContext<'_>,
287     parent_module: Option<DefId>,
288     did: DefId,
289     attrs: Option<Attrs<'_>>,
290     ret: &mut Vec<clean::Item>,
291 ) {
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 fn merge_attrs(
302     cx: &mut DocContext<'_>,
303     parent_module: Option<DefId>,
304     old_attrs: Attrs<'_>,
305     new_attrs: Option<Attrs<'_>>,
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(old_attrs, Some((inner, new_id)))
317             } else {
318                 Attributes::from_ast(&both, None)
319             },
320             both.cfg(cx.sess()),
321         )
322     } else {
323         (old_attrs.clean(cx), old_attrs.cfg(cx.sess()))
324     }
325 }
326
327 /// Builds a specific implementation of a type. The `did` could be a type method or trait method.
328 crate fn build_impl(
329     cx: &mut DocContext<'_>,
330     parent_module: impl Into<Option<DefId>>,
331     did: DefId,
332     attrs: Option<Attrs<'_>>,
333     ret: &mut Vec<clean::Item>,
334 ) {
335     if !cx.inlined.insert(did.into()) {
336         return;
337     }
338
339     let tcx = cx.tcx;
340     let associated_trait = tcx.impl_trait_ref(did);
341
342     // Only inline impl if the implemented trait is
343     // reachable in rustdoc generated documentation
344     if !did.is_local() {
345         if let Some(traitref) = associated_trait {
346             let did = traitref.def_id;
347             if !cx.cache.access_levels.is_public(did) {
348                 return;
349             }
350
351             if let Some(stab) = tcx.lookup_stability(did) {
352                 if stab.level.is_unstable() && stab.feature == sym::rustc_private {
353                     return;
354                 }
355             }
356         }
357     }
358
359     let impl_item = match did.as_local() {
360         Some(did) => {
361             let hir_id = tcx.hir().local_def_id_to_hir_id(did);
362             match &tcx.hir().expect_item(hir_id).kind {
363                 hir::ItemKind::Impl(impl_) => Some(impl_),
364                 _ => panic!("`DefID` passed to `build_impl` is not an `impl"),
365             }
366         }
367         None => None,
368     };
369
370     let for_ = match &impl_item {
371         Some(impl_) => impl_.self_ty.clean(cx),
372         None => tcx.type_of(did).clean(cx),
373     };
374
375     // Only inline impl if the implementing type is
376     // reachable in rustdoc generated documentation
377     if !did.is_local() {
378         if let Some(did) = for_.def_id() {
379             if !cx.cache.access_levels.is_public(did) {
380                 return;
381             }
382
383             if let Some(stab) = tcx.lookup_stability(did) {
384                 if stab.level.is_unstable() && stab.feature == sym::rustc_private {
385                     return;
386                 }
387             }
388         }
389     }
390
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).clean(cx))
398                 .collect::<Vec<_>>(),
399             impl_.generics.clean(cx),
400         ),
401         None => (
402             tcx.associated_items(did)
403                 .in_definition_order()
404                 .filter_map(|item| {
405                     if associated_trait.is_some() || item.vis == ty::Visibility::Public {
406                         Some(item.clean(cx))
407                     } else {
408                         None
409                     }
410                 })
411                 .collect::<Vec<_>>(),
412             clean::enter_impl_trait(cx, |cx| (tcx.generics_of(did), predicates).clean(cx)),
413         ),
414     };
415     let polarity = tcx.impl_polarity(did);
416     let trait_ = associated_trait.clean(cx).map(|bound| match bound {
417         clean::GenericBound::TraitBound(polyt, _) => polyt.trait_,
418         clean::GenericBound::Outlives(..) => unreachable!(),
419     });
420     if trait_.def_id() == tcx.lang_items().deref_trait() {
421         super::build_deref_target_impls(cx, &trait_items, ret);
422     }
423     if let Some(trait_did) = trait_.def_id() {
424         record_extern_trait(cx, trait_did);
425     }
426
427     let (merged_attrs, cfg) = merge_attrs(cx, parent_module.into(), load_attrs(cx, did), attrs);
428     debug!("merged_attrs={:?}", merged_attrs);
429
430     debug!("build_impl: impl {:?} for {:?}", trait_.def_id(), for_.def_id());
431     ret.push(clean::Item::from_def_id_and_attrs_and_parts(
432         did,
433         None,
434         clean::ImplItem(clean::Impl {
435             span: clean::types::rustc_span(did, cx.tcx),
436             unsafety: hir::Unsafety::Normal,
437             generics,
438             trait_,
439             for_,
440             items: trait_items,
441             negative_polarity: polarity.clean(cx),
442             synthetic: false,
443             blanket_impl: None,
444         }),
445         box merged_attrs,
446         cx,
447         cfg,
448     ));
449 }
450
451 fn build_module(
452     cx: &mut DocContext<'_>,
453     did: DefId,
454     visited: &mut FxHashSet<DefId>,
455 ) -> clean::Module {
456     let mut items = Vec::new();
457
458     // If we're re-exporting a re-export it may actually re-export something in
459     // two namespaces, so the target may be listed twice. Make sure we only
460     // visit each node at most once.
461     for &item in cx.tcx.item_children(did).iter() {
462         if item.vis == ty::Visibility::Public {
463             if let Some(def_id) = item.res.mod_def_id() {
464                 if did == def_id || !visited.insert(def_id) {
465                     continue;
466                 }
467             }
468             if let Res::PrimTy(p) = item.res {
469                 // Primitive types can't be inlined so generate an import instead.
470                 items.push(clean::Item {
471                     name: None,
472                     attrs: box clean::Attributes::default(),
473                     def_id: FakeDefId::new_fake(did.krate),
474                     visibility: clean::Public,
475                     kind: box clean::ImportItem(clean::Import::new_simple(
476                         item.ident.name,
477                         clean::ImportSource {
478                             path: clean::Path {
479                                 global: false,
480                                 res: item.res,
481                                 segments: vec![clean::PathSegment {
482                                     name: clean::PrimitiveType::from(p).as_sym(),
483                                     args: clean::GenericArgs::AngleBracketed {
484                                         args: Vec::new(),
485                                         bindings: Vec::new(),
486                                     },
487                                 }],
488                             },
489                             did: None,
490                         },
491                         true,
492                     )),
493                     cfg: None,
494                 });
495             } else if let Some(i) = try_inline(cx, did, item.res, item.ident.name, None, visited) {
496                 items.extend(i)
497             }
498         }
499     }
500
501     let span = clean::Span::from_rustc_span(cx.tcx.def_span(did));
502     clean::Module { items, span }
503 }
504
505 crate fn print_inlined_const(tcx: TyCtxt<'_>, did: DefId) -> String {
506     if let Some(did) = did.as_local() {
507         let hir_id = tcx.hir().local_def_id_to_hir_id(did);
508         rustc_hir_pretty::id_to_string(&tcx.hir(), hir_id)
509     } else {
510         tcx.rendered_const(did)
511     }
512 }
513
514 fn build_const(cx: &mut DocContext<'_>, def_id: DefId) -> clean::Constant {
515     clean::Constant {
516         type_: cx.tcx.type_of(def_id).clean(cx),
517         kind: clean::ConstantKind::Extern { def_id },
518     }
519 }
520
521 fn build_static(cx: &mut DocContext<'_>, did: DefId, mutable: bool) -> clean::Static {
522     clean::Static {
523         type_: cx.tcx.type_of(did).clean(cx),
524         mutability: if mutable { Mutability::Mut } else { Mutability::Not },
525         expr: None,
526     }
527 }
528
529 fn build_macro(cx: &mut DocContext<'_>, did: DefId, name: Symbol) -> clean::ItemKind {
530     let imported_from = cx.tcx.crate_name(did.krate);
531     match cx.enter_resolver(|r| r.cstore().load_macro_untracked(did, cx.sess())) {
532         LoadedMacro::MacroDef(def, _) => {
533             let matchers: Vec<Span> = if let ast::ItemKind::MacroDef(ref def) = def.kind {
534                 let tts: Vec<_> = def.body.inner_tokens().into_trees().collect();
535                 tts.chunks(4).map(|arm| arm[0].span()).collect()
536             } else {
537                 unreachable!()
538             };
539
540             let source = format!(
541                 "macro_rules! {} {{\n{}}}",
542                 name.clean(cx),
543                 matchers
544                     .iter()
545                     .map(|span| { format!("    {} => {{ ... }};\n", span.to_src(cx)) })
546                     .collect::<String>()
547             );
548
549             clean::MacroItem(clean::Macro { source, imported_from: Some(imported_from) })
550         }
551         LoadedMacro::ProcMacro(ext) => clean::ProcMacroItem(clean::ProcMacro {
552             kind: ext.macro_kind(),
553             helpers: ext.helper_attrs,
554         }),
555     }
556 }
557
558 /// A trait's generics clause actually contains all of the predicates for all of
559 /// its associated types as well. We specifically move these clauses to the
560 /// associated types instead when displaying, so when we're generating the
561 /// generics for the trait itself we need to be sure to remove them.
562 /// We also need to remove the implied "recursive" Self: Trait bound.
563 ///
564 /// The inverse of this filtering logic can be found in the `Clean`
565 /// implementation for `AssociatedType`
566 fn filter_non_trait_generics(trait_did: DefId, mut g: clean::Generics) -> clean::Generics {
567     for pred in &mut g.where_predicates {
568         match *pred {
569             clean::WherePredicate::BoundPredicate { ty: clean::Generic(ref s), ref mut bounds }
570                 if *s == kw::SelfUpper =>
571             {
572                 bounds.retain(|bound| match *bound {
573                     clean::GenericBound::TraitBound(
574                         clean::PolyTrait { trait_: clean::ResolvedPath { did, .. }, .. },
575                         _,
576                     ) => did != trait_did,
577                     _ => true,
578                 });
579             }
580             _ => {}
581         }
582     }
583
584     g.where_predicates.retain(|pred| match *pred {
585         clean::WherePredicate::BoundPredicate {
586             ty:
587                 clean::QPath {
588                     self_type: box clean::Generic(ref s),
589                     trait_: box clean::ResolvedPath { did, .. },
590                     name: ref _name,
591                     ..
592                 },
593             ref bounds,
594         } => !(bounds.is_empty() || *s == kw::SelfUpper && did == trait_did),
595         _ => true,
596     });
597     g
598 }
599
600 /// Supertrait bounds for a trait are also listed in the generics coming from
601 /// the metadata for a crate, so we want to separate those out and create a new
602 /// list of explicit supertrait bounds to render nicely.
603 fn separate_supertrait_bounds(
604     mut g: clean::Generics,
605 ) -> (clean::Generics, Vec<clean::GenericBound>) {
606     let mut ty_bounds = Vec::new();
607     g.where_predicates.retain(|pred| match *pred {
608         clean::WherePredicate::BoundPredicate { ty: clean::Generic(ref s), ref bounds }
609             if *s == kw::SelfUpper =>
610         {
611             ty_bounds.extend(bounds.iter().cloned());
612             false
613         }
614         _ => true,
615     });
616     (g, ty_bounds)
617 }
618
619 crate fn record_extern_trait(cx: &mut DocContext<'_>, did: DefId) {
620     if did.is_local() {
621         return;
622     }
623
624     {
625         if cx.external_traits.borrow().contains_key(&did) || cx.active_extern_traits.contains(&did)
626         {
627             return;
628         }
629     }
630
631     {
632         cx.active_extern_traits.insert(did);
633     }
634
635     debug!("record_extern_trait: {:?}", did);
636     let trait_ = build_external_trait(cx, did);
637
638     let trait_ = clean::TraitWithExtraInfo {
639         trait_,
640         is_notable: clean::utils::has_doc_flag(cx.tcx.get_attrs(did), sym::notable_trait),
641     };
642     cx.external_traits.borrow_mut().insert(did, trait_);
643     cx.active_extern_traits.remove(&did);
644 }