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