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