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